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/DiagnosticPrinter.h"
19 #include "llvm/IR/InlineAsm.h"
20 #include "llvm/IR/IntrinsicInst.h"
21 #include "llvm/IR/LLVMContext.h"
22 #include "llvm/IR/Module.h"
23 #include "llvm/IR/OperandTraits.h"
24 #include "llvm/IR/Operator.h"
25 #include "llvm/Support/DataStream.h"
26 #include "llvm/Support/ManagedStatic.h"
27 #include "llvm/Support/MathExtras.h"
28 #include "llvm/Support/MemoryBuffer.h"
29 #include "llvm/Support/raw_ostream.h"
34 SWITCH_INST_MAGIC = 0x4B5 // May 2012 => 1205 => Hex
37 BitcodeDiagnosticInfo::BitcodeDiagnosticInfo(std::error_code EC,
38 DiagnosticSeverity Severity,
40 : DiagnosticInfo(DK_Bitcode, Severity), Msg(Msg), EC(EC) {}
42 void BitcodeDiagnosticInfo::print(DiagnosticPrinter &DP) const { DP << Msg; }
44 static std::error_code Error(DiagnosticHandlerFunction DiagnosticHandler,
45 std::error_code EC, const Twine &Message) {
46 BitcodeDiagnosticInfo DI(EC, DS_Error, Message);
47 DiagnosticHandler(DI);
51 static std::error_code Error(DiagnosticHandlerFunction DiagnosticHandler,
53 return Error(DiagnosticHandler, EC, EC.message());
56 std::error_code BitcodeReader::Error(BitcodeError E, const Twine &Message) {
57 return ::Error(DiagnosticHandler, make_error_code(E), Message);
60 std::error_code BitcodeReader::Error(const Twine &Message) {
61 return ::Error(DiagnosticHandler,
62 make_error_code(BitcodeError::CorruptedBitcode), Message);
65 std::error_code BitcodeReader::Error(BitcodeError E) {
66 return ::Error(DiagnosticHandler, make_error_code(E));
69 static DiagnosticHandlerFunction getDiagHandler(DiagnosticHandlerFunction F,
73 return [&C](const DiagnosticInfo &DI) { C.diagnose(DI); };
76 BitcodeReader::BitcodeReader(MemoryBuffer *buffer, LLVMContext &C,
77 DiagnosticHandlerFunction DiagnosticHandler)
78 : Context(C), DiagnosticHandler(getDiagHandler(DiagnosticHandler, C)),
79 TheModule(nullptr), Buffer(buffer), LazyStreamer(nullptr),
80 NextUnreadBit(0), SeenValueSymbolTable(false), ValueList(C),
81 MDValueList(C), SeenFirstFunctionBody(false), UseRelativeIDs(false),
82 WillMaterializeAllForwardRefs(false) {}
84 BitcodeReader::BitcodeReader(DataStreamer *streamer, LLVMContext &C,
85 DiagnosticHandlerFunction DiagnosticHandler)
86 : Context(C), DiagnosticHandler(getDiagHandler(DiagnosticHandler, C)),
87 TheModule(nullptr), Buffer(nullptr), LazyStreamer(streamer),
88 NextUnreadBit(0), SeenValueSymbolTable(false), ValueList(C),
89 MDValueList(C), SeenFirstFunctionBody(false), UseRelativeIDs(false),
90 WillMaterializeAllForwardRefs(false) {}
92 std::error_code BitcodeReader::materializeForwardReferencedFunctions() {
93 if (WillMaterializeAllForwardRefs)
94 return std::error_code();
97 WillMaterializeAllForwardRefs = true;
99 while (!BasicBlockFwdRefQueue.empty()) {
100 Function *F = BasicBlockFwdRefQueue.front();
101 BasicBlockFwdRefQueue.pop_front();
102 assert(F && "Expected valid function");
103 if (!BasicBlockFwdRefs.count(F))
104 // Already materialized.
107 // Check for a function that isn't materializable to prevent an infinite
108 // loop. When parsing a blockaddress stored in a global variable, there
109 // isn't a trivial way to check if a function will have a body without a
110 // linear search through FunctionsWithBodies, so just check it here.
111 if (!F->isMaterializable())
112 return Error("Never resolved function from blockaddress");
114 // Try to materialize F.
115 if (std::error_code EC = materialize(F))
118 assert(BasicBlockFwdRefs.empty() && "Function missing from queue");
121 WillMaterializeAllForwardRefs = false;
122 return std::error_code();
125 void BitcodeReader::FreeState() {
127 std::vector<Type*>().swap(TypeList);
130 std::vector<Comdat *>().swap(ComdatList);
132 std::vector<AttributeSet>().swap(MAttributes);
133 std::vector<BasicBlock*>().swap(FunctionBBs);
134 std::vector<Function*>().swap(FunctionsWithBodies);
135 DeferredFunctionInfo.clear();
138 assert(BasicBlockFwdRefs.empty() && "Unresolved blockaddress fwd references");
139 BasicBlockFwdRefQueue.clear();
142 //===----------------------------------------------------------------------===//
143 // Helper functions to implement forward reference resolution, etc.
144 //===----------------------------------------------------------------------===//
146 /// ConvertToString - Convert a string from a record into an std::string, return
148 template<typename StrTy>
149 static bool ConvertToString(ArrayRef<uint64_t> Record, unsigned Idx,
151 if (Idx > Record.size())
154 for (unsigned i = Idx, e = Record.size(); i != e; ++i)
155 Result += (char)Record[i];
159 static bool hasImplicitComdat(size_t Val) {
163 case 1: // Old WeakAnyLinkage
164 case 4: // Old LinkOnceAnyLinkage
165 case 10: // Old WeakODRLinkage
166 case 11: // Old LinkOnceODRLinkage
171 static GlobalValue::LinkageTypes getDecodedLinkage(unsigned Val) {
173 default: // Map unknown/new linkages to external
175 return GlobalValue::ExternalLinkage;
177 return GlobalValue::AppendingLinkage;
179 return GlobalValue::InternalLinkage;
181 return GlobalValue::ExternalLinkage; // Obsolete DLLImportLinkage
183 return GlobalValue::ExternalLinkage; // Obsolete DLLExportLinkage
185 return GlobalValue::ExternalWeakLinkage;
187 return GlobalValue::CommonLinkage;
189 return GlobalValue::PrivateLinkage;
191 return GlobalValue::AvailableExternallyLinkage;
193 return GlobalValue::PrivateLinkage; // Obsolete LinkerPrivateLinkage
195 return GlobalValue::PrivateLinkage; // Obsolete LinkerPrivateWeakLinkage
197 return GlobalValue::ExternalLinkage; // Obsolete LinkOnceODRAutoHideLinkage
198 case 1: // Old value with implicit comdat.
200 return GlobalValue::WeakAnyLinkage;
201 case 10: // Old value with implicit comdat.
203 return GlobalValue::WeakODRLinkage;
204 case 4: // Old value with implicit comdat.
206 return GlobalValue::LinkOnceAnyLinkage;
207 case 11: // Old value with implicit comdat.
209 return GlobalValue::LinkOnceODRLinkage;
213 static GlobalValue::VisibilityTypes GetDecodedVisibility(unsigned Val) {
215 default: // Map unknown visibilities to default.
216 case 0: return GlobalValue::DefaultVisibility;
217 case 1: return GlobalValue::HiddenVisibility;
218 case 2: return GlobalValue::ProtectedVisibility;
222 static GlobalValue::DLLStorageClassTypes
223 GetDecodedDLLStorageClass(unsigned Val) {
225 default: // Map unknown values to default.
226 case 0: return GlobalValue::DefaultStorageClass;
227 case 1: return GlobalValue::DLLImportStorageClass;
228 case 2: return GlobalValue::DLLExportStorageClass;
232 static GlobalVariable::ThreadLocalMode GetDecodedThreadLocalMode(unsigned Val) {
234 case 0: return GlobalVariable::NotThreadLocal;
235 default: // Map unknown non-zero value to general dynamic.
236 case 1: return GlobalVariable::GeneralDynamicTLSModel;
237 case 2: return GlobalVariable::LocalDynamicTLSModel;
238 case 3: return GlobalVariable::InitialExecTLSModel;
239 case 4: return GlobalVariable::LocalExecTLSModel;
243 static int GetDecodedCastOpcode(unsigned Val) {
246 case bitc::CAST_TRUNC : return Instruction::Trunc;
247 case bitc::CAST_ZEXT : return Instruction::ZExt;
248 case bitc::CAST_SEXT : return Instruction::SExt;
249 case bitc::CAST_FPTOUI : return Instruction::FPToUI;
250 case bitc::CAST_FPTOSI : return Instruction::FPToSI;
251 case bitc::CAST_UITOFP : return Instruction::UIToFP;
252 case bitc::CAST_SITOFP : return Instruction::SIToFP;
253 case bitc::CAST_FPTRUNC : return Instruction::FPTrunc;
254 case bitc::CAST_FPEXT : return Instruction::FPExt;
255 case bitc::CAST_PTRTOINT: return Instruction::PtrToInt;
256 case bitc::CAST_INTTOPTR: return Instruction::IntToPtr;
257 case bitc::CAST_BITCAST : return Instruction::BitCast;
258 case bitc::CAST_ADDRSPACECAST: return Instruction::AddrSpaceCast;
261 static int GetDecodedBinaryOpcode(unsigned Val, Type *Ty) {
264 case bitc::BINOP_ADD:
265 return Ty->isFPOrFPVectorTy() ? Instruction::FAdd : Instruction::Add;
266 case bitc::BINOP_SUB:
267 return Ty->isFPOrFPVectorTy() ? Instruction::FSub : Instruction::Sub;
268 case bitc::BINOP_MUL:
269 return Ty->isFPOrFPVectorTy() ? Instruction::FMul : Instruction::Mul;
270 case bitc::BINOP_UDIV: return Instruction::UDiv;
271 case bitc::BINOP_SDIV:
272 return Ty->isFPOrFPVectorTy() ? Instruction::FDiv : Instruction::SDiv;
273 case bitc::BINOP_UREM: return Instruction::URem;
274 case bitc::BINOP_SREM:
275 return Ty->isFPOrFPVectorTy() ? Instruction::FRem : Instruction::SRem;
276 case bitc::BINOP_SHL: return Instruction::Shl;
277 case bitc::BINOP_LSHR: return Instruction::LShr;
278 case bitc::BINOP_ASHR: return Instruction::AShr;
279 case bitc::BINOP_AND: return Instruction::And;
280 case bitc::BINOP_OR: return Instruction::Or;
281 case bitc::BINOP_XOR: return Instruction::Xor;
285 static AtomicRMWInst::BinOp GetDecodedRMWOperation(unsigned Val) {
287 default: return AtomicRMWInst::BAD_BINOP;
288 case bitc::RMW_XCHG: return AtomicRMWInst::Xchg;
289 case bitc::RMW_ADD: return AtomicRMWInst::Add;
290 case bitc::RMW_SUB: return AtomicRMWInst::Sub;
291 case bitc::RMW_AND: return AtomicRMWInst::And;
292 case bitc::RMW_NAND: return AtomicRMWInst::Nand;
293 case bitc::RMW_OR: return AtomicRMWInst::Or;
294 case bitc::RMW_XOR: return AtomicRMWInst::Xor;
295 case bitc::RMW_MAX: return AtomicRMWInst::Max;
296 case bitc::RMW_MIN: return AtomicRMWInst::Min;
297 case bitc::RMW_UMAX: return AtomicRMWInst::UMax;
298 case bitc::RMW_UMIN: return AtomicRMWInst::UMin;
302 static AtomicOrdering GetDecodedOrdering(unsigned Val) {
304 case bitc::ORDERING_NOTATOMIC: return NotAtomic;
305 case bitc::ORDERING_UNORDERED: return Unordered;
306 case bitc::ORDERING_MONOTONIC: return Monotonic;
307 case bitc::ORDERING_ACQUIRE: return Acquire;
308 case bitc::ORDERING_RELEASE: return Release;
309 case bitc::ORDERING_ACQREL: return AcquireRelease;
310 default: // Map unknown orderings to sequentially-consistent.
311 case bitc::ORDERING_SEQCST: return SequentiallyConsistent;
315 static SynchronizationScope GetDecodedSynchScope(unsigned Val) {
317 case bitc::SYNCHSCOPE_SINGLETHREAD: return SingleThread;
318 default: // Map unknown scopes to cross-thread.
319 case bitc::SYNCHSCOPE_CROSSTHREAD: return CrossThread;
323 static Comdat::SelectionKind getDecodedComdatSelectionKind(unsigned Val) {
325 default: // Map unknown selection kinds to any.
326 case bitc::COMDAT_SELECTION_KIND_ANY:
328 case bitc::COMDAT_SELECTION_KIND_EXACT_MATCH:
329 return Comdat::ExactMatch;
330 case bitc::COMDAT_SELECTION_KIND_LARGEST:
331 return Comdat::Largest;
332 case bitc::COMDAT_SELECTION_KIND_NO_DUPLICATES:
333 return Comdat::NoDuplicates;
334 case bitc::COMDAT_SELECTION_KIND_SAME_SIZE:
335 return Comdat::SameSize;
339 static void UpgradeDLLImportExportLinkage(llvm::GlobalValue *GV, unsigned Val) {
341 case 5: GV->setDLLStorageClass(GlobalValue::DLLImportStorageClass); break;
342 case 6: GV->setDLLStorageClass(GlobalValue::DLLExportStorageClass); break;
348 /// @brief A class for maintaining the slot number definition
349 /// as a placeholder for the actual definition for forward constants defs.
350 class ConstantPlaceHolder : public ConstantExpr {
351 void operator=(const ConstantPlaceHolder &) LLVM_DELETED_FUNCTION;
353 // allocate space for exactly one operand
354 void *operator new(size_t s) {
355 return User::operator new(s, 1);
357 explicit ConstantPlaceHolder(Type *Ty, LLVMContext& Context)
358 : ConstantExpr(Ty, Instruction::UserOp1, &Op<0>(), 1) {
359 Op<0>() = UndefValue::get(Type::getInt32Ty(Context));
362 /// @brief Methods to support type inquiry through isa, cast, and dyn_cast.
363 static bool classof(const Value *V) {
364 return isa<ConstantExpr>(V) &&
365 cast<ConstantExpr>(V)->getOpcode() == Instruction::UserOp1;
369 /// Provide fast operand accessors
370 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
374 // FIXME: can we inherit this from ConstantExpr?
376 struct OperandTraits<ConstantPlaceHolder> :
377 public FixedNumOperandTraits<ConstantPlaceHolder, 1> {
379 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ConstantPlaceHolder, Value)
383 void BitcodeReaderValueList::AssignValue(Value *V, unsigned Idx) {
392 WeakVH &OldV = ValuePtrs[Idx];
398 // Handle constants and non-constants (e.g. instrs) differently for
400 if (Constant *PHC = dyn_cast<Constant>(&*OldV)) {
401 ResolveConstants.push_back(std::make_pair(PHC, Idx));
404 // If there was a forward reference to this value, replace it.
405 Value *PrevVal = OldV;
406 OldV->replaceAllUsesWith(V);
412 Constant *BitcodeReaderValueList::getConstantFwdRef(unsigned Idx,
417 if (Value *V = ValuePtrs[Idx]) {
418 assert(Ty == V->getType() && "Type mismatch in constant table!");
419 return cast<Constant>(V);
422 // Create and return a placeholder, which will later be RAUW'd.
423 Constant *C = new ConstantPlaceHolder(Ty, Context);
428 Value *BitcodeReaderValueList::getValueFwdRef(unsigned Idx, Type *Ty) {
432 if (Value *V = ValuePtrs[Idx]) {
433 assert((!Ty || Ty == V->getType()) && "Type mismatch in value table!");
437 // No type specified, must be invalid reference.
438 if (!Ty) return nullptr;
440 // Create and return a placeholder, which will later be RAUW'd.
441 Value *V = new Argument(Ty);
446 /// ResolveConstantForwardRefs - Once all constants are read, this method bulk
447 /// resolves any forward references. The idea behind this is that we sometimes
448 /// get constants (such as large arrays) which reference *many* forward ref
449 /// constants. Replacing each of these causes a lot of thrashing when
450 /// building/reuniquing the constant. Instead of doing this, we look at all the
451 /// uses and rewrite all the place holders at once for any constant that uses
453 void BitcodeReaderValueList::ResolveConstantForwardRefs() {
454 // Sort the values by-pointer so that they are efficient to look up with a
456 std::sort(ResolveConstants.begin(), ResolveConstants.end());
458 SmallVector<Constant*, 64> NewOps;
460 while (!ResolveConstants.empty()) {
461 Value *RealVal = operator[](ResolveConstants.back().second);
462 Constant *Placeholder = ResolveConstants.back().first;
463 ResolveConstants.pop_back();
465 // Loop over all users of the placeholder, updating them to reference the
466 // new value. If they reference more than one placeholder, update them all
468 while (!Placeholder->use_empty()) {
469 auto UI = Placeholder->user_begin();
472 // If the using object isn't uniqued, just update the operands. This
473 // handles instructions and initializers for global variables.
474 if (!isa<Constant>(U) || isa<GlobalValue>(U)) {
475 UI.getUse().set(RealVal);
479 // Otherwise, we have a constant that uses the placeholder. Replace that
480 // constant with a new constant that has *all* placeholder uses updated.
481 Constant *UserC = cast<Constant>(U);
482 for (User::op_iterator I = UserC->op_begin(), E = UserC->op_end();
485 if (!isa<ConstantPlaceHolder>(*I)) {
486 // Not a placeholder reference.
488 } else if (*I == Placeholder) {
489 // Common case is that it just references this one placeholder.
492 // Otherwise, look up the placeholder in ResolveConstants.
493 ResolveConstantsTy::iterator It =
494 std::lower_bound(ResolveConstants.begin(), ResolveConstants.end(),
495 std::pair<Constant*, unsigned>(cast<Constant>(*I),
497 assert(It != ResolveConstants.end() && It->first == *I);
498 NewOp = operator[](It->second);
501 NewOps.push_back(cast<Constant>(NewOp));
504 // Make the new constant.
506 if (ConstantArray *UserCA = dyn_cast<ConstantArray>(UserC)) {
507 NewC = ConstantArray::get(UserCA->getType(), NewOps);
508 } else if (ConstantStruct *UserCS = dyn_cast<ConstantStruct>(UserC)) {
509 NewC = ConstantStruct::get(UserCS->getType(), NewOps);
510 } else if (isa<ConstantVector>(UserC)) {
511 NewC = ConstantVector::get(NewOps);
513 assert(isa<ConstantExpr>(UserC) && "Must be a ConstantExpr.");
514 NewC = cast<ConstantExpr>(UserC)->getWithOperands(NewOps);
517 UserC->replaceAllUsesWith(NewC);
518 UserC->destroyConstant();
522 // Update all ValueHandles, they should be the only users at this point.
523 Placeholder->replaceAllUsesWith(RealVal);
528 void BitcodeReaderMDValueList::AssignValue(Metadata *MD, unsigned Idx) {
537 TrackingMDRef &OldMD = MDValuePtrs[Idx];
543 // If there was a forward reference to this value, replace it.
544 MDNodeFwdDecl *PrevMD = cast<MDNodeFwdDecl>(OldMD.get());
545 PrevMD->replaceAllUsesWith(MD);
546 MDNode::deleteTemporary(PrevMD);
550 Metadata *BitcodeReaderMDValueList::getValueFwdRef(unsigned Idx) {
554 if (Metadata *MD = MDValuePtrs[Idx])
557 // Create and return a placeholder, which will later be RAUW'd.
560 Metadata *MD = MDNode::getTemporary(Context, None);
561 MDValuePtrs[Idx].reset(MD);
565 void BitcodeReaderMDValueList::tryToResolveCycles() {
571 // Still forward references... can't resolve cycles.
574 // Resolve any cycles.
575 for (auto &MD : MDValuePtrs) {
576 assert(!(MD && isa<MDNodeFwdDecl>(MD)) && "Unexpected forward reference");
577 if (auto *N = dyn_cast_or_null<UniquableMDNode>(MD))
582 Type *BitcodeReader::getTypeByID(unsigned ID) {
583 // The type table size is always specified correctly.
584 if (ID >= TypeList.size())
587 if (Type *Ty = TypeList[ID])
590 // If we have a forward reference, the only possible case is when it is to a
591 // named struct. Just create a placeholder for now.
592 return TypeList[ID] = createIdentifiedStructType(Context);
595 StructType *BitcodeReader::createIdentifiedStructType(LLVMContext &Context,
597 auto *Ret = StructType::create(Context, Name);
598 IdentifiedStructTypes.push_back(Ret);
602 StructType *BitcodeReader::createIdentifiedStructType(LLVMContext &Context) {
603 auto *Ret = StructType::create(Context);
604 IdentifiedStructTypes.push_back(Ret);
609 //===----------------------------------------------------------------------===//
610 // Functions for parsing blocks from the bitcode file
611 //===----------------------------------------------------------------------===//
614 /// \brief This fills an AttrBuilder object with the LLVM attributes that have
615 /// been decoded from the given integer. This function must stay in sync with
616 /// 'encodeLLVMAttributesForBitcode'.
617 static void decodeLLVMAttributesForBitcode(AttrBuilder &B,
618 uint64_t EncodedAttrs) {
619 // FIXME: Remove in 4.0.
621 // The alignment is stored as a 16-bit raw value from bits 31--16. We shift
622 // the bits above 31 down by 11 bits.
623 unsigned Alignment = (EncodedAttrs & (0xffffULL << 16)) >> 16;
624 assert((!Alignment || isPowerOf2_32(Alignment)) &&
625 "Alignment must be a power of two.");
628 B.addAlignmentAttr(Alignment);
629 B.addRawValue(((EncodedAttrs & (0xfffffULL << 32)) >> 11) |
630 (EncodedAttrs & 0xffff));
633 std::error_code BitcodeReader::ParseAttributeBlock() {
634 if (Stream.EnterSubBlock(bitc::PARAMATTR_BLOCK_ID))
635 return Error("Invalid record");
637 if (!MAttributes.empty())
638 return Error("Invalid multiple blocks");
640 SmallVector<uint64_t, 64> Record;
642 SmallVector<AttributeSet, 8> Attrs;
644 // Read all the records.
646 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
648 switch (Entry.Kind) {
649 case BitstreamEntry::SubBlock: // Handled for us already.
650 case BitstreamEntry::Error:
651 return Error("Malformed block");
652 case BitstreamEntry::EndBlock:
653 return std::error_code();
654 case BitstreamEntry::Record:
655 // The interesting case.
661 switch (Stream.readRecord(Entry.ID, Record)) {
662 default: // Default behavior: ignore.
664 case bitc::PARAMATTR_CODE_ENTRY_OLD: { // ENTRY: [paramidx0, attr0, ...]
665 // FIXME: Remove in 4.0.
666 if (Record.size() & 1)
667 return Error("Invalid record");
669 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
671 decodeLLVMAttributesForBitcode(B, Record[i+1]);
672 Attrs.push_back(AttributeSet::get(Context, Record[i], B));
675 MAttributes.push_back(AttributeSet::get(Context, Attrs));
679 case bitc::PARAMATTR_CODE_ENTRY: { // ENTRY: [attrgrp0, attrgrp1, ...]
680 for (unsigned i = 0, e = Record.size(); i != e; ++i)
681 Attrs.push_back(MAttributeGroups[Record[i]]);
683 MAttributes.push_back(AttributeSet::get(Context, Attrs));
691 // Returns Attribute::None on unrecognized codes.
692 static Attribute::AttrKind GetAttrFromCode(uint64_t Code) {
695 return Attribute::None;
696 case bitc::ATTR_KIND_ALIGNMENT:
697 return Attribute::Alignment;
698 case bitc::ATTR_KIND_ALWAYS_INLINE:
699 return Attribute::AlwaysInline;
700 case bitc::ATTR_KIND_BUILTIN:
701 return Attribute::Builtin;
702 case bitc::ATTR_KIND_BY_VAL:
703 return Attribute::ByVal;
704 case bitc::ATTR_KIND_IN_ALLOCA:
705 return Attribute::InAlloca;
706 case bitc::ATTR_KIND_COLD:
707 return Attribute::Cold;
708 case bitc::ATTR_KIND_INLINE_HINT:
709 return Attribute::InlineHint;
710 case bitc::ATTR_KIND_IN_REG:
711 return Attribute::InReg;
712 case bitc::ATTR_KIND_JUMP_TABLE:
713 return Attribute::JumpTable;
714 case bitc::ATTR_KIND_MIN_SIZE:
715 return Attribute::MinSize;
716 case bitc::ATTR_KIND_NAKED:
717 return Attribute::Naked;
718 case bitc::ATTR_KIND_NEST:
719 return Attribute::Nest;
720 case bitc::ATTR_KIND_NO_ALIAS:
721 return Attribute::NoAlias;
722 case bitc::ATTR_KIND_NO_BUILTIN:
723 return Attribute::NoBuiltin;
724 case bitc::ATTR_KIND_NO_CAPTURE:
725 return Attribute::NoCapture;
726 case bitc::ATTR_KIND_NO_DUPLICATE:
727 return Attribute::NoDuplicate;
728 case bitc::ATTR_KIND_NO_IMPLICIT_FLOAT:
729 return Attribute::NoImplicitFloat;
730 case bitc::ATTR_KIND_NO_INLINE:
731 return Attribute::NoInline;
732 case bitc::ATTR_KIND_NON_LAZY_BIND:
733 return Attribute::NonLazyBind;
734 case bitc::ATTR_KIND_NON_NULL:
735 return Attribute::NonNull;
736 case bitc::ATTR_KIND_DEREFERENCEABLE:
737 return Attribute::Dereferenceable;
738 case bitc::ATTR_KIND_NO_RED_ZONE:
739 return Attribute::NoRedZone;
740 case bitc::ATTR_KIND_NO_RETURN:
741 return Attribute::NoReturn;
742 case bitc::ATTR_KIND_NO_UNWIND:
743 return Attribute::NoUnwind;
744 case bitc::ATTR_KIND_OPTIMIZE_FOR_SIZE:
745 return Attribute::OptimizeForSize;
746 case bitc::ATTR_KIND_OPTIMIZE_NONE:
747 return Attribute::OptimizeNone;
748 case bitc::ATTR_KIND_READ_NONE:
749 return Attribute::ReadNone;
750 case bitc::ATTR_KIND_READ_ONLY:
751 return Attribute::ReadOnly;
752 case bitc::ATTR_KIND_RETURNED:
753 return Attribute::Returned;
754 case bitc::ATTR_KIND_RETURNS_TWICE:
755 return Attribute::ReturnsTwice;
756 case bitc::ATTR_KIND_S_EXT:
757 return Attribute::SExt;
758 case bitc::ATTR_KIND_STACK_ALIGNMENT:
759 return Attribute::StackAlignment;
760 case bitc::ATTR_KIND_STACK_PROTECT:
761 return Attribute::StackProtect;
762 case bitc::ATTR_KIND_STACK_PROTECT_REQ:
763 return Attribute::StackProtectReq;
764 case bitc::ATTR_KIND_STACK_PROTECT_STRONG:
765 return Attribute::StackProtectStrong;
766 case bitc::ATTR_KIND_STRUCT_RET:
767 return Attribute::StructRet;
768 case bitc::ATTR_KIND_SANITIZE_ADDRESS:
769 return Attribute::SanitizeAddress;
770 case bitc::ATTR_KIND_SANITIZE_THREAD:
771 return Attribute::SanitizeThread;
772 case bitc::ATTR_KIND_SANITIZE_MEMORY:
773 return Attribute::SanitizeMemory;
774 case bitc::ATTR_KIND_UW_TABLE:
775 return Attribute::UWTable;
776 case bitc::ATTR_KIND_Z_EXT:
777 return Attribute::ZExt;
781 std::error_code BitcodeReader::ParseAttrKind(uint64_t Code,
782 Attribute::AttrKind *Kind) {
783 *Kind = GetAttrFromCode(Code);
784 if (*Kind == Attribute::None)
785 return Error(BitcodeError::CorruptedBitcode,
786 "Unknown attribute kind (" + Twine(Code) + ")");
787 return std::error_code();
790 std::error_code BitcodeReader::ParseAttributeGroupBlock() {
791 if (Stream.EnterSubBlock(bitc::PARAMATTR_GROUP_BLOCK_ID))
792 return Error("Invalid record");
794 if (!MAttributeGroups.empty())
795 return Error("Invalid multiple blocks");
797 SmallVector<uint64_t, 64> Record;
799 // Read all the records.
801 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
803 switch (Entry.Kind) {
804 case BitstreamEntry::SubBlock: // Handled for us already.
805 case BitstreamEntry::Error:
806 return Error("Malformed block");
807 case BitstreamEntry::EndBlock:
808 return std::error_code();
809 case BitstreamEntry::Record:
810 // The interesting case.
816 switch (Stream.readRecord(Entry.ID, Record)) {
817 default: // Default behavior: ignore.
819 case bitc::PARAMATTR_GRP_CODE_ENTRY: { // ENTRY: [grpid, idx, a0, a1, ...]
820 if (Record.size() < 3)
821 return Error("Invalid record");
823 uint64_t GrpID = Record[0];
824 uint64_t Idx = Record[1]; // Index of the object this attribute refers to.
827 for (unsigned i = 2, e = Record.size(); i != e; ++i) {
828 if (Record[i] == 0) { // Enum attribute
829 Attribute::AttrKind Kind;
830 if (std::error_code EC = ParseAttrKind(Record[++i], &Kind))
833 B.addAttribute(Kind);
834 } else if (Record[i] == 1) { // Integer attribute
835 Attribute::AttrKind Kind;
836 if (std::error_code EC = ParseAttrKind(Record[++i], &Kind))
838 if (Kind == Attribute::Alignment)
839 B.addAlignmentAttr(Record[++i]);
840 else if (Kind == Attribute::StackAlignment)
841 B.addStackAlignmentAttr(Record[++i]);
842 else if (Kind == Attribute::Dereferenceable)
843 B.addDereferenceableAttr(Record[++i]);
844 } else { // String attribute
845 assert((Record[i] == 3 || Record[i] == 4) &&
846 "Invalid attribute group entry");
847 bool HasValue = (Record[i++] == 4);
848 SmallString<64> KindStr;
849 SmallString<64> ValStr;
851 while (Record[i] != 0 && i != e)
852 KindStr += Record[i++];
853 assert(Record[i] == 0 && "Kind string not null terminated");
856 // Has a value associated with it.
857 ++i; // Skip the '0' that terminates the "kind" string.
858 while (Record[i] != 0 && i != e)
859 ValStr += Record[i++];
860 assert(Record[i] == 0 && "Value string not null terminated");
863 B.addAttribute(KindStr.str(), ValStr.str());
867 MAttributeGroups[GrpID] = AttributeSet::get(Context, Idx, B);
874 std::error_code BitcodeReader::ParseTypeTable() {
875 if (Stream.EnterSubBlock(bitc::TYPE_BLOCK_ID_NEW))
876 return Error("Invalid record");
878 return ParseTypeTableBody();
881 std::error_code BitcodeReader::ParseTypeTableBody() {
882 if (!TypeList.empty())
883 return Error("Invalid multiple blocks");
885 SmallVector<uint64_t, 64> Record;
886 unsigned NumRecords = 0;
888 SmallString<64> TypeName;
890 // Read all the records for this type table.
892 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
894 switch (Entry.Kind) {
895 case BitstreamEntry::SubBlock: // Handled for us already.
896 case BitstreamEntry::Error:
897 return Error("Malformed block");
898 case BitstreamEntry::EndBlock:
899 if (NumRecords != TypeList.size())
900 return Error("Malformed block");
901 return std::error_code();
902 case BitstreamEntry::Record:
903 // The interesting case.
909 Type *ResultTy = nullptr;
910 switch (Stream.readRecord(Entry.ID, Record)) {
912 return Error("Invalid value");
913 case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries]
914 // TYPE_CODE_NUMENTRY contains a count of the number of types in the
915 // type list. This allows us to reserve space.
916 if (Record.size() < 1)
917 return Error("Invalid record");
918 TypeList.resize(Record[0]);
920 case bitc::TYPE_CODE_VOID: // VOID
921 ResultTy = Type::getVoidTy(Context);
923 case bitc::TYPE_CODE_HALF: // HALF
924 ResultTy = Type::getHalfTy(Context);
926 case bitc::TYPE_CODE_FLOAT: // FLOAT
927 ResultTy = Type::getFloatTy(Context);
929 case bitc::TYPE_CODE_DOUBLE: // DOUBLE
930 ResultTy = Type::getDoubleTy(Context);
932 case bitc::TYPE_CODE_X86_FP80: // X86_FP80
933 ResultTy = Type::getX86_FP80Ty(Context);
935 case bitc::TYPE_CODE_FP128: // FP128
936 ResultTy = Type::getFP128Ty(Context);
938 case bitc::TYPE_CODE_PPC_FP128: // PPC_FP128
939 ResultTy = Type::getPPC_FP128Ty(Context);
941 case bitc::TYPE_CODE_LABEL: // LABEL
942 ResultTy = Type::getLabelTy(Context);
944 case bitc::TYPE_CODE_METADATA: // METADATA
945 ResultTy = Type::getMetadataTy(Context);
947 case bitc::TYPE_CODE_X86_MMX: // X86_MMX
948 ResultTy = Type::getX86_MMXTy(Context);
950 case bitc::TYPE_CODE_INTEGER: // INTEGER: [width]
951 if (Record.size() < 1)
952 return Error("Invalid record");
954 ResultTy = IntegerType::get(Context, Record[0]);
956 case bitc::TYPE_CODE_POINTER: { // POINTER: [pointee type] or
957 // [pointee type, address space]
958 if (Record.size() < 1)
959 return Error("Invalid record");
960 unsigned AddressSpace = 0;
961 if (Record.size() == 2)
962 AddressSpace = Record[1];
963 ResultTy = getTypeByID(Record[0]);
965 return Error("Invalid type");
966 ResultTy = PointerType::get(ResultTy, AddressSpace);
969 case bitc::TYPE_CODE_FUNCTION_OLD: {
970 // FIXME: attrid is dead, remove it in LLVM 4.0
971 // FUNCTION: [vararg, attrid, retty, paramty x N]
972 if (Record.size() < 3)
973 return Error("Invalid record");
974 SmallVector<Type*, 8> ArgTys;
975 for (unsigned i = 3, e = Record.size(); i != e; ++i) {
976 if (Type *T = getTypeByID(Record[i]))
982 ResultTy = getTypeByID(Record[2]);
983 if (!ResultTy || ArgTys.size() < Record.size()-3)
984 return Error("Invalid type");
986 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
989 case bitc::TYPE_CODE_FUNCTION: {
990 // FUNCTION: [vararg, retty, paramty x N]
991 if (Record.size() < 2)
992 return Error("Invalid record");
993 SmallVector<Type*, 8> ArgTys;
994 for (unsigned i = 2, e = Record.size(); i != e; ++i) {
995 if (Type *T = getTypeByID(Record[i]))
1001 ResultTy = getTypeByID(Record[1]);
1002 if (!ResultTy || ArgTys.size() < Record.size()-2)
1003 return Error("Invalid type");
1005 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
1008 case bitc::TYPE_CODE_STRUCT_ANON: { // STRUCT: [ispacked, eltty x N]
1009 if (Record.size() < 1)
1010 return Error("Invalid record");
1011 SmallVector<Type*, 8> EltTys;
1012 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
1013 if (Type *T = getTypeByID(Record[i]))
1014 EltTys.push_back(T);
1018 if (EltTys.size() != Record.size()-1)
1019 return Error("Invalid type");
1020 ResultTy = StructType::get(Context, EltTys, Record[0]);
1023 case bitc::TYPE_CODE_STRUCT_NAME: // STRUCT_NAME: [strchr x N]
1024 if (ConvertToString(Record, 0, TypeName))
1025 return Error("Invalid record");
1028 case bitc::TYPE_CODE_STRUCT_NAMED: { // STRUCT: [ispacked, eltty x N]
1029 if (Record.size() < 1)
1030 return Error("Invalid record");
1032 if (NumRecords >= TypeList.size())
1033 return Error("Invalid TYPE table");
1035 // Check to see if this was forward referenced, if so fill in the temp.
1036 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
1038 Res->setName(TypeName);
1039 TypeList[NumRecords] = nullptr;
1040 } else // Otherwise, create a new struct.
1041 Res = createIdentifiedStructType(Context, TypeName);
1044 SmallVector<Type*, 8> EltTys;
1045 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
1046 if (Type *T = getTypeByID(Record[i]))
1047 EltTys.push_back(T);
1051 if (EltTys.size() != Record.size()-1)
1052 return Error("Invalid record");
1053 Res->setBody(EltTys, Record[0]);
1057 case bitc::TYPE_CODE_OPAQUE: { // OPAQUE: []
1058 if (Record.size() != 1)
1059 return Error("Invalid record");
1061 if (NumRecords >= TypeList.size())
1062 return Error("Invalid TYPE table");
1064 // Check to see if this was forward referenced, if so fill in the temp.
1065 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
1067 Res->setName(TypeName);
1068 TypeList[NumRecords] = nullptr;
1069 } else // Otherwise, create a new struct with no body.
1070 Res = createIdentifiedStructType(Context, TypeName);
1075 case bitc::TYPE_CODE_ARRAY: // ARRAY: [numelts, eltty]
1076 if (Record.size() < 2)
1077 return Error("Invalid record");
1078 if ((ResultTy = getTypeByID(Record[1])))
1079 ResultTy = ArrayType::get(ResultTy, Record[0]);
1081 return Error("Invalid type");
1083 case bitc::TYPE_CODE_VECTOR: // VECTOR: [numelts, eltty]
1084 if (Record.size() < 2)
1085 return Error("Invalid record");
1086 if ((ResultTy = getTypeByID(Record[1])))
1087 ResultTy = VectorType::get(ResultTy, Record[0]);
1089 return Error("Invalid type");
1093 if (NumRecords >= TypeList.size())
1094 return Error("Invalid TYPE table");
1095 assert(ResultTy && "Didn't read a type?");
1096 assert(!TypeList[NumRecords] && "Already read type?");
1097 TypeList[NumRecords++] = ResultTy;
1101 std::error_code BitcodeReader::ParseValueSymbolTable() {
1102 if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
1103 return Error("Invalid record");
1105 SmallVector<uint64_t, 64> Record;
1107 // Read all the records for this value table.
1108 SmallString<128> ValueName;
1110 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1112 switch (Entry.Kind) {
1113 case BitstreamEntry::SubBlock: // Handled for us already.
1114 case BitstreamEntry::Error:
1115 return Error("Malformed block");
1116 case BitstreamEntry::EndBlock:
1117 return std::error_code();
1118 case BitstreamEntry::Record:
1119 // The interesting case.
1125 switch (Stream.readRecord(Entry.ID, Record)) {
1126 default: // Default behavior: unknown type.
1128 case bitc::VST_CODE_ENTRY: { // VST_ENTRY: [valueid, namechar x N]
1129 if (ConvertToString(Record, 1, ValueName))
1130 return Error("Invalid record");
1131 unsigned ValueID = Record[0];
1132 if (ValueID >= ValueList.size() || !ValueList[ValueID])
1133 return Error("Invalid record");
1134 Value *V = ValueList[ValueID];
1136 V->setName(StringRef(ValueName.data(), ValueName.size()));
1137 if (auto *GO = dyn_cast<GlobalObject>(V)) {
1138 if (GO->getComdat() == reinterpret_cast<Comdat *>(1))
1139 GO->setComdat(TheModule->getOrInsertComdat(V->getName()));
1144 case bitc::VST_CODE_BBENTRY: {
1145 if (ConvertToString(Record, 1, ValueName))
1146 return Error("Invalid record");
1147 BasicBlock *BB = getBasicBlock(Record[0]);
1149 return Error("Invalid record");
1151 BB->setName(StringRef(ValueName.data(), ValueName.size()));
1159 std::error_code BitcodeReader::ParseMetadata() {
1160 unsigned NextMDValueNo = MDValueList.size();
1162 if (Stream.EnterSubBlock(bitc::METADATA_BLOCK_ID))
1163 return Error("Invalid record");
1165 SmallVector<uint64_t, 64> Record;
1167 // Read all the records.
1169 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1171 switch (Entry.Kind) {
1172 case BitstreamEntry::SubBlock: // Handled for us already.
1173 case BitstreamEntry::Error:
1174 return Error("Malformed block");
1175 case BitstreamEntry::EndBlock:
1176 MDValueList.tryToResolveCycles();
1177 return std::error_code();
1178 case BitstreamEntry::Record:
1179 // The interesting case.
1185 unsigned Code = Stream.readRecord(Entry.ID, Record);
1186 bool IsDistinct = false;
1188 default: // Default behavior: ignore.
1190 case bitc::METADATA_NAME: {
1191 // Read name of the named metadata.
1192 SmallString<8> Name(Record.begin(), Record.end());
1194 Code = Stream.ReadCode();
1196 // METADATA_NAME is always followed by METADATA_NAMED_NODE.
1197 unsigned NextBitCode = Stream.readRecord(Code, Record);
1198 assert(NextBitCode == bitc::METADATA_NAMED_NODE); (void)NextBitCode;
1200 // Read named metadata elements.
1201 unsigned Size = Record.size();
1202 NamedMDNode *NMD = TheModule->getOrInsertNamedMetadata(Name);
1203 for (unsigned i = 0; i != Size; ++i) {
1204 MDNode *MD = dyn_cast_or_null<MDNode>(MDValueList.getValueFwdRef(Record[i]));
1206 return Error("Invalid record");
1207 NMD->addOperand(MD);
1211 case bitc::METADATA_OLD_FN_NODE: {
1212 // FIXME: Remove in 4.0.
1213 // This is a LocalAsMetadata record, the only type of function-local
1215 if (Record.size() % 2 == 1)
1216 return Error("Invalid record");
1218 // If this isn't a LocalAsMetadata record, we're dropping it. This used
1219 // to be legal, but there's no upgrade path.
1220 auto dropRecord = [&] {
1221 MDValueList.AssignValue(MDNode::get(Context, None), NextMDValueNo++);
1223 if (Record.size() != 2) {
1228 Type *Ty = getTypeByID(Record[0]);
1229 if (Ty->isMetadataTy() || Ty->isVoidTy()) {
1234 MDValueList.AssignValue(
1235 LocalAsMetadata::get(ValueList.getValueFwdRef(Record[1], Ty)),
1239 case bitc::METADATA_OLD_NODE: {
1240 // FIXME: Remove in 4.0.
1241 if (Record.size() % 2 == 1)
1242 return Error("Invalid record");
1244 unsigned Size = Record.size();
1245 SmallVector<Metadata *, 8> Elts;
1246 for (unsigned i = 0; i != Size; i += 2) {
1247 Type *Ty = getTypeByID(Record[i]);
1249 return Error("Invalid record");
1250 if (Ty->isMetadataTy())
1251 Elts.push_back(MDValueList.getValueFwdRef(Record[i+1]));
1252 else if (!Ty->isVoidTy()) {
1254 ValueAsMetadata::get(ValueList.getValueFwdRef(Record[i + 1], Ty));
1255 assert(isa<ConstantAsMetadata>(MD) &&
1256 "Expected non-function-local metadata");
1259 Elts.push_back(nullptr);
1261 MDValueList.AssignValue(MDNode::get(Context, Elts), NextMDValueNo++);
1264 case bitc::METADATA_VALUE: {
1265 if (Record.size() != 2)
1266 return Error("Invalid record");
1268 Type *Ty = getTypeByID(Record[0]);
1269 if (Ty->isMetadataTy() || Ty->isVoidTy())
1270 return Error("Invalid record");
1272 MDValueList.AssignValue(
1273 ValueAsMetadata::get(ValueList.getValueFwdRef(Record[1], Ty)),
1277 case bitc::METADATA_DISTINCT_NODE:
1280 case bitc::METADATA_NODE: {
1281 SmallVector<Metadata *, 8> Elts;
1282 Elts.reserve(Record.size());
1283 for (unsigned ID : Record)
1284 Elts.push_back(ID ? MDValueList.getValueFwdRef(ID - 1) : nullptr);
1285 MDValueList.AssignValue(IsDistinct ? MDNode::getDistinct(Context, Elts)
1286 : MDNode::get(Context, Elts),
1290 case bitc::METADATA_LOCATION: {
1291 if (Record.size() != 5)
1292 return Error("Invalid record");
1294 auto get = Record[0] ? MDLocation::getDistinct : MDLocation::get;
1295 unsigned Line = Record[1];
1296 unsigned Column = Record[2];
1297 MDNode *Scope = cast<MDNode>(MDValueList.getValueFwdRef(Record[3]));
1298 Metadata *InlinedAt =
1299 Record[4] ? MDValueList.getValueFwdRef(Record[4] - 1) : nullptr;
1300 MDValueList.AssignValue(get(Context, Line, Column, Scope, InlinedAt),
1304 case bitc::METADATA_STRING: {
1305 std::string String(Record.begin(), Record.end());
1306 llvm::UpgradeMDStringConstant(String);
1307 Metadata *MD = MDString::get(Context, String);
1308 MDValueList.AssignValue(MD, NextMDValueNo++);
1311 case bitc::METADATA_KIND: {
1312 if (Record.size() < 2)
1313 return Error("Invalid record");
1315 unsigned Kind = Record[0];
1316 SmallString<8> Name(Record.begin()+1, Record.end());
1318 unsigned NewKind = TheModule->getMDKindID(Name.str());
1319 if (!MDKindMap.insert(std::make_pair(Kind, NewKind)).second)
1320 return Error("Conflicting METADATA_KIND records");
1327 /// decodeSignRotatedValue - Decode a signed value stored with the sign bit in
1328 /// the LSB for dense VBR encoding.
1329 uint64_t BitcodeReader::decodeSignRotatedValue(uint64_t V) {
1334 // There is no such thing as -0 with integers. "-0" really means MININT.
1338 /// ResolveGlobalAndAliasInits - Resolve all of the initializers for global
1339 /// values and aliases that we can.
1340 std::error_code BitcodeReader::ResolveGlobalAndAliasInits() {
1341 std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInitWorklist;
1342 std::vector<std::pair<GlobalAlias*, unsigned> > AliasInitWorklist;
1343 std::vector<std::pair<Function*, unsigned> > FunctionPrefixWorklist;
1344 std::vector<std::pair<Function*, unsigned> > FunctionPrologueWorklist;
1346 GlobalInitWorklist.swap(GlobalInits);
1347 AliasInitWorklist.swap(AliasInits);
1348 FunctionPrefixWorklist.swap(FunctionPrefixes);
1349 FunctionPrologueWorklist.swap(FunctionPrologues);
1351 while (!GlobalInitWorklist.empty()) {
1352 unsigned ValID = GlobalInitWorklist.back().second;
1353 if (ValID >= ValueList.size()) {
1354 // Not ready to resolve this yet, it requires something later in the file.
1355 GlobalInits.push_back(GlobalInitWorklist.back());
1357 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
1358 GlobalInitWorklist.back().first->setInitializer(C);
1360 return Error("Expected a constant");
1362 GlobalInitWorklist.pop_back();
1365 while (!AliasInitWorklist.empty()) {
1366 unsigned ValID = AliasInitWorklist.back().second;
1367 if (ValID >= ValueList.size()) {
1368 AliasInits.push_back(AliasInitWorklist.back());
1370 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
1371 AliasInitWorklist.back().first->setAliasee(C);
1373 return Error("Expected a constant");
1375 AliasInitWorklist.pop_back();
1378 while (!FunctionPrefixWorklist.empty()) {
1379 unsigned ValID = FunctionPrefixWorklist.back().second;
1380 if (ValID >= ValueList.size()) {
1381 FunctionPrefixes.push_back(FunctionPrefixWorklist.back());
1383 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
1384 FunctionPrefixWorklist.back().first->setPrefixData(C);
1386 return Error("Expected a constant");
1388 FunctionPrefixWorklist.pop_back();
1391 while (!FunctionPrologueWorklist.empty()) {
1392 unsigned ValID = FunctionPrologueWorklist.back().second;
1393 if (ValID >= ValueList.size()) {
1394 FunctionPrologues.push_back(FunctionPrologueWorklist.back());
1396 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
1397 FunctionPrologueWorklist.back().first->setPrologueData(C);
1399 return Error("Expected a constant");
1401 FunctionPrologueWorklist.pop_back();
1404 return std::error_code();
1407 static APInt ReadWideAPInt(ArrayRef<uint64_t> Vals, unsigned TypeBits) {
1408 SmallVector<uint64_t, 8> Words(Vals.size());
1409 std::transform(Vals.begin(), Vals.end(), Words.begin(),
1410 BitcodeReader::decodeSignRotatedValue);
1412 return APInt(TypeBits, Words);
1415 std::error_code BitcodeReader::ParseConstants() {
1416 if (Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID))
1417 return Error("Invalid record");
1419 SmallVector<uint64_t, 64> Record;
1421 // Read all the records for this value table.
1422 Type *CurTy = Type::getInt32Ty(Context);
1423 unsigned NextCstNo = ValueList.size();
1425 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1427 switch (Entry.Kind) {
1428 case BitstreamEntry::SubBlock: // Handled for us already.
1429 case BitstreamEntry::Error:
1430 return Error("Malformed block");
1431 case BitstreamEntry::EndBlock:
1432 if (NextCstNo != ValueList.size())
1433 return Error("Invalid ronstant reference");
1435 // Once all the constants have been read, go through and resolve forward
1437 ValueList.ResolveConstantForwardRefs();
1438 return std::error_code();
1439 case BitstreamEntry::Record:
1440 // The interesting case.
1447 unsigned BitCode = Stream.readRecord(Entry.ID, Record);
1449 default: // Default behavior: unknown constant
1450 case bitc::CST_CODE_UNDEF: // UNDEF
1451 V = UndefValue::get(CurTy);
1453 case bitc::CST_CODE_SETTYPE: // SETTYPE: [typeid]
1455 return Error("Invalid record");
1456 if (Record[0] >= TypeList.size() || !TypeList[Record[0]])
1457 return Error("Invalid record");
1458 CurTy = TypeList[Record[0]];
1459 continue; // Skip the ValueList manipulation.
1460 case bitc::CST_CODE_NULL: // NULL
1461 V = Constant::getNullValue(CurTy);
1463 case bitc::CST_CODE_INTEGER: // INTEGER: [intval]
1464 if (!CurTy->isIntegerTy() || Record.empty())
1465 return Error("Invalid record");
1466 V = ConstantInt::get(CurTy, decodeSignRotatedValue(Record[0]));
1468 case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval]
1469 if (!CurTy->isIntegerTy() || Record.empty())
1470 return Error("Invalid record");
1472 APInt VInt = ReadWideAPInt(Record,
1473 cast<IntegerType>(CurTy)->getBitWidth());
1474 V = ConstantInt::get(Context, VInt);
1478 case bitc::CST_CODE_FLOAT: { // FLOAT: [fpval]
1480 return Error("Invalid record");
1481 if (CurTy->isHalfTy())
1482 V = ConstantFP::get(Context, APFloat(APFloat::IEEEhalf,
1483 APInt(16, (uint16_t)Record[0])));
1484 else if (CurTy->isFloatTy())
1485 V = ConstantFP::get(Context, APFloat(APFloat::IEEEsingle,
1486 APInt(32, (uint32_t)Record[0])));
1487 else if (CurTy->isDoubleTy())
1488 V = ConstantFP::get(Context, APFloat(APFloat::IEEEdouble,
1489 APInt(64, Record[0])));
1490 else if (CurTy->isX86_FP80Ty()) {
1491 // Bits are not stored the same way as a normal i80 APInt, compensate.
1492 uint64_t Rearrange[2];
1493 Rearrange[0] = (Record[1] & 0xffffLL) | (Record[0] << 16);
1494 Rearrange[1] = Record[0] >> 48;
1495 V = ConstantFP::get(Context, APFloat(APFloat::x87DoubleExtended,
1496 APInt(80, Rearrange)));
1497 } else if (CurTy->isFP128Ty())
1498 V = ConstantFP::get(Context, APFloat(APFloat::IEEEquad,
1499 APInt(128, Record)));
1500 else if (CurTy->isPPC_FP128Ty())
1501 V = ConstantFP::get(Context, APFloat(APFloat::PPCDoubleDouble,
1502 APInt(128, Record)));
1504 V = UndefValue::get(CurTy);
1508 case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number]
1510 return Error("Invalid record");
1512 unsigned Size = Record.size();
1513 SmallVector<Constant*, 16> Elts;
1515 if (StructType *STy = dyn_cast<StructType>(CurTy)) {
1516 for (unsigned i = 0; i != Size; ++i)
1517 Elts.push_back(ValueList.getConstantFwdRef(Record[i],
1518 STy->getElementType(i)));
1519 V = ConstantStruct::get(STy, Elts);
1520 } else if (ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) {
1521 Type *EltTy = ATy->getElementType();
1522 for (unsigned i = 0; i != Size; ++i)
1523 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
1524 V = ConstantArray::get(ATy, Elts);
1525 } else if (VectorType *VTy = dyn_cast<VectorType>(CurTy)) {
1526 Type *EltTy = VTy->getElementType();
1527 for (unsigned i = 0; i != Size; ++i)
1528 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
1529 V = ConstantVector::get(Elts);
1531 V = UndefValue::get(CurTy);
1535 case bitc::CST_CODE_STRING: // STRING: [values]
1536 case bitc::CST_CODE_CSTRING: { // CSTRING: [values]
1538 return Error("Invalid record");
1540 SmallString<16> Elts(Record.begin(), Record.end());
1541 V = ConstantDataArray::getString(Context, Elts,
1542 BitCode == bitc::CST_CODE_CSTRING);
1545 case bitc::CST_CODE_DATA: {// DATA: [n x value]
1547 return Error("Invalid record");
1549 Type *EltTy = cast<SequentialType>(CurTy)->getElementType();
1550 unsigned Size = Record.size();
1552 if (EltTy->isIntegerTy(8)) {
1553 SmallVector<uint8_t, 16> Elts(Record.begin(), Record.end());
1554 if (isa<VectorType>(CurTy))
1555 V = ConstantDataVector::get(Context, Elts);
1557 V = ConstantDataArray::get(Context, Elts);
1558 } else if (EltTy->isIntegerTy(16)) {
1559 SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end());
1560 if (isa<VectorType>(CurTy))
1561 V = ConstantDataVector::get(Context, Elts);
1563 V = ConstantDataArray::get(Context, Elts);
1564 } else if (EltTy->isIntegerTy(32)) {
1565 SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end());
1566 if (isa<VectorType>(CurTy))
1567 V = ConstantDataVector::get(Context, Elts);
1569 V = ConstantDataArray::get(Context, Elts);
1570 } else if (EltTy->isIntegerTy(64)) {
1571 SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end());
1572 if (isa<VectorType>(CurTy))
1573 V = ConstantDataVector::get(Context, Elts);
1575 V = ConstantDataArray::get(Context, Elts);
1576 } else if (EltTy->isFloatTy()) {
1577 SmallVector<float, 16> Elts(Size);
1578 std::transform(Record.begin(), Record.end(), Elts.begin(), BitsToFloat);
1579 if (isa<VectorType>(CurTy))
1580 V = ConstantDataVector::get(Context, Elts);
1582 V = ConstantDataArray::get(Context, Elts);
1583 } else if (EltTy->isDoubleTy()) {
1584 SmallVector<double, 16> Elts(Size);
1585 std::transform(Record.begin(), Record.end(), Elts.begin(),
1587 if (isa<VectorType>(CurTy))
1588 V = ConstantDataVector::get(Context, Elts);
1590 V = ConstantDataArray::get(Context, Elts);
1592 return Error("Invalid type for value");
1597 case bitc::CST_CODE_CE_BINOP: { // CE_BINOP: [opcode, opval, opval]
1598 if (Record.size() < 3)
1599 return Error("Invalid record");
1600 int Opc = GetDecodedBinaryOpcode(Record[0], CurTy);
1602 V = UndefValue::get(CurTy); // Unknown binop.
1604 Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy);
1605 Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy);
1607 if (Record.size() >= 4) {
1608 if (Opc == Instruction::Add ||
1609 Opc == Instruction::Sub ||
1610 Opc == Instruction::Mul ||
1611 Opc == Instruction::Shl) {
1612 if (Record[3] & (1 << bitc::OBO_NO_SIGNED_WRAP))
1613 Flags |= OverflowingBinaryOperator::NoSignedWrap;
1614 if (Record[3] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
1615 Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
1616 } else if (Opc == Instruction::SDiv ||
1617 Opc == Instruction::UDiv ||
1618 Opc == Instruction::LShr ||
1619 Opc == Instruction::AShr) {
1620 if (Record[3] & (1 << bitc::PEO_EXACT))
1621 Flags |= SDivOperator::IsExact;
1624 V = ConstantExpr::get(Opc, LHS, RHS, Flags);
1628 case bitc::CST_CODE_CE_CAST: { // CE_CAST: [opcode, opty, opval]
1629 if (Record.size() < 3)
1630 return Error("Invalid record");
1631 int Opc = GetDecodedCastOpcode(Record[0]);
1633 V = UndefValue::get(CurTy); // Unknown cast.
1635 Type *OpTy = getTypeByID(Record[1]);
1637 return Error("Invalid record");
1638 Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy);
1639 V = UpgradeBitCastExpr(Opc, Op, CurTy);
1640 if (!V) V = ConstantExpr::getCast(Opc, Op, CurTy);
1644 case bitc::CST_CODE_CE_INBOUNDS_GEP:
1645 case bitc::CST_CODE_CE_GEP: { // CE_GEP: [n x operands]
1646 if (Record.size() & 1)
1647 return Error("Invalid record");
1648 SmallVector<Constant*, 16> Elts;
1649 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
1650 Type *ElTy = getTypeByID(Record[i]);
1652 return Error("Invalid record");
1653 Elts.push_back(ValueList.getConstantFwdRef(Record[i+1], ElTy));
1655 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
1656 V = ConstantExpr::getGetElementPtr(Elts[0], Indices,
1658 bitc::CST_CODE_CE_INBOUNDS_GEP);
1661 case bitc::CST_CODE_CE_SELECT: { // CE_SELECT: [opval#, opval#, opval#]
1662 if (Record.size() < 3)
1663 return Error("Invalid record");
1665 Type *SelectorTy = Type::getInt1Ty(Context);
1667 // If CurTy is a vector of length n, then Record[0] must be a <n x i1>
1668 // vector. Otherwise, it must be a single bit.
1669 if (VectorType *VTy = dyn_cast<VectorType>(CurTy))
1670 SelectorTy = VectorType::get(Type::getInt1Ty(Context),
1671 VTy->getNumElements());
1673 V = ConstantExpr::getSelect(ValueList.getConstantFwdRef(Record[0],
1675 ValueList.getConstantFwdRef(Record[1],CurTy),
1676 ValueList.getConstantFwdRef(Record[2],CurTy));
1679 case bitc::CST_CODE_CE_EXTRACTELT
1680 : { // CE_EXTRACTELT: [opty, opval, opty, opval]
1681 if (Record.size() < 3)
1682 return Error("Invalid record");
1684 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
1686 return Error("Invalid record");
1687 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
1688 Constant *Op1 = nullptr;
1689 if (Record.size() == 4) {
1690 Type *IdxTy = getTypeByID(Record[2]);
1692 return Error("Invalid record");
1693 Op1 = ValueList.getConstantFwdRef(Record[3], IdxTy);
1694 } else // TODO: Remove with llvm 4.0
1695 Op1 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
1697 return Error("Invalid record");
1698 V = ConstantExpr::getExtractElement(Op0, Op1);
1701 case bitc::CST_CODE_CE_INSERTELT
1702 : { // CE_INSERTELT: [opval, opval, opty, opval]
1703 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
1704 if (Record.size() < 3 || !OpTy)
1705 return Error("Invalid record");
1706 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
1707 Constant *Op1 = ValueList.getConstantFwdRef(Record[1],
1708 OpTy->getElementType());
1709 Constant *Op2 = nullptr;
1710 if (Record.size() == 4) {
1711 Type *IdxTy = getTypeByID(Record[2]);
1713 return Error("Invalid record");
1714 Op2 = ValueList.getConstantFwdRef(Record[3], IdxTy);
1715 } else // TODO: Remove with llvm 4.0
1716 Op2 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
1718 return Error("Invalid record");
1719 V = ConstantExpr::getInsertElement(Op0, Op1, Op2);
1722 case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval]
1723 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
1724 if (Record.size() < 3 || !OpTy)
1725 return Error("Invalid record");
1726 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
1727 Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy);
1728 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
1729 OpTy->getNumElements());
1730 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy);
1731 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
1734 case bitc::CST_CODE_CE_SHUFVEC_EX: { // [opty, opval, opval, opval]
1735 VectorType *RTy = dyn_cast<VectorType>(CurTy);
1737 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
1738 if (Record.size() < 4 || !RTy || !OpTy)
1739 return Error("Invalid record");
1740 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
1741 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
1742 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
1743 RTy->getNumElements());
1744 Constant *Op2 = ValueList.getConstantFwdRef(Record[3], ShufTy);
1745 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
1748 case bitc::CST_CODE_CE_CMP: { // CE_CMP: [opty, opval, opval, pred]
1749 if (Record.size() < 4)
1750 return Error("Invalid record");
1751 Type *OpTy = getTypeByID(Record[0]);
1753 return Error("Invalid record");
1754 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
1755 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
1757 if (OpTy->isFPOrFPVectorTy())
1758 V = ConstantExpr::getFCmp(Record[3], Op0, Op1);
1760 V = ConstantExpr::getICmp(Record[3], Op0, Op1);
1763 // This maintains backward compatibility, pre-asm dialect keywords.
1764 // FIXME: Remove with the 4.0 release.
1765 case bitc::CST_CODE_INLINEASM_OLD: {
1766 if (Record.size() < 2)
1767 return Error("Invalid record");
1768 std::string AsmStr, ConstrStr;
1769 bool HasSideEffects = Record[0] & 1;
1770 bool IsAlignStack = Record[0] >> 1;
1771 unsigned AsmStrSize = Record[1];
1772 if (2+AsmStrSize >= Record.size())
1773 return Error("Invalid record");
1774 unsigned ConstStrSize = Record[2+AsmStrSize];
1775 if (3+AsmStrSize+ConstStrSize > Record.size())
1776 return Error("Invalid record");
1778 for (unsigned i = 0; i != AsmStrSize; ++i)
1779 AsmStr += (char)Record[2+i];
1780 for (unsigned i = 0; i != ConstStrSize; ++i)
1781 ConstrStr += (char)Record[3+AsmStrSize+i];
1782 PointerType *PTy = cast<PointerType>(CurTy);
1783 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
1784 AsmStr, ConstrStr, HasSideEffects, IsAlignStack);
1787 // This version adds support for the asm dialect keywords (e.g.,
1789 case bitc::CST_CODE_INLINEASM: {
1790 if (Record.size() < 2)
1791 return Error("Invalid record");
1792 std::string AsmStr, ConstrStr;
1793 bool HasSideEffects = Record[0] & 1;
1794 bool IsAlignStack = (Record[0] >> 1) & 1;
1795 unsigned AsmDialect = Record[0] >> 2;
1796 unsigned AsmStrSize = Record[1];
1797 if (2+AsmStrSize >= Record.size())
1798 return Error("Invalid record");
1799 unsigned ConstStrSize = Record[2+AsmStrSize];
1800 if (3+AsmStrSize+ConstStrSize > Record.size())
1801 return Error("Invalid record");
1803 for (unsigned i = 0; i != AsmStrSize; ++i)
1804 AsmStr += (char)Record[2+i];
1805 for (unsigned i = 0; i != ConstStrSize; ++i)
1806 ConstrStr += (char)Record[3+AsmStrSize+i];
1807 PointerType *PTy = cast<PointerType>(CurTy);
1808 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
1809 AsmStr, ConstrStr, HasSideEffects, IsAlignStack,
1810 InlineAsm::AsmDialect(AsmDialect));
1813 case bitc::CST_CODE_BLOCKADDRESS:{
1814 if (Record.size() < 3)
1815 return Error("Invalid record");
1816 Type *FnTy = getTypeByID(Record[0]);
1818 return Error("Invalid record");
1820 dyn_cast_or_null<Function>(ValueList.getConstantFwdRef(Record[1],FnTy));
1822 return Error("Invalid record");
1824 // Don't let Fn get dematerialized.
1825 BlockAddressesTaken.insert(Fn);
1827 // If the function is already parsed we can insert the block address right
1830 unsigned BBID = Record[2];
1832 // Invalid reference to entry block.
1833 return Error("Invalid ID");
1835 Function::iterator BBI = Fn->begin(), BBE = Fn->end();
1836 for (size_t I = 0, E = BBID; I != E; ++I) {
1838 return Error("Invalid ID");
1843 // Otherwise insert a placeholder and remember it so it can be inserted
1844 // when the function is parsed.
1845 auto &FwdBBs = BasicBlockFwdRefs[Fn];
1847 BasicBlockFwdRefQueue.push_back(Fn);
1848 if (FwdBBs.size() < BBID + 1)
1849 FwdBBs.resize(BBID + 1);
1851 FwdBBs[BBID] = BasicBlock::Create(Context);
1854 V = BlockAddress::get(Fn, BB);
1859 ValueList.AssignValue(V, NextCstNo);
1864 std::error_code BitcodeReader::ParseUseLists() {
1865 if (Stream.EnterSubBlock(bitc::USELIST_BLOCK_ID))
1866 return Error("Invalid record");
1868 // Read all the records.
1869 SmallVector<uint64_t, 64> Record;
1871 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1873 switch (Entry.Kind) {
1874 case BitstreamEntry::SubBlock: // Handled for us already.
1875 case BitstreamEntry::Error:
1876 return Error("Malformed block");
1877 case BitstreamEntry::EndBlock:
1878 return std::error_code();
1879 case BitstreamEntry::Record:
1880 // The interesting case.
1884 // Read a use list record.
1887 switch (Stream.readRecord(Entry.ID, Record)) {
1888 default: // Default behavior: unknown type.
1890 case bitc::USELIST_CODE_BB:
1893 case bitc::USELIST_CODE_DEFAULT: {
1894 unsigned RecordLength = Record.size();
1895 if (RecordLength < 3)
1896 // Records should have at least an ID and two indexes.
1897 return Error("Invalid record");
1898 unsigned ID = Record.back();
1903 assert(ID < FunctionBBs.size() && "Basic block not found");
1904 V = FunctionBBs[ID];
1907 unsigned NumUses = 0;
1908 SmallDenseMap<const Use *, unsigned, 16> Order;
1909 for (const Use &U : V->uses()) {
1910 if (++NumUses > Record.size())
1912 Order[&U] = Record[NumUses - 1];
1914 if (Order.size() != Record.size() || NumUses > Record.size())
1915 // Mismatches can happen if the functions are being materialized lazily
1916 // (out-of-order), or a value has been upgraded.
1919 V->sortUseList([&](const Use &L, const Use &R) {
1920 return Order.lookup(&L) < Order.lookup(&R);
1928 /// RememberAndSkipFunctionBody - When we see the block for a function body,
1929 /// remember where it is and then skip it. This lets us lazily deserialize the
1931 std::error_code BitcodeReader::RememberAndSkipFunctionBody() {
1932 // Get the function we are talking about.
1933 if (FunctionsWithBodies.empty())
1934 return Error("Insufficient function protos");
1936 Function *Fn = FunctionsWithBodies.back();
1937 FunctionsWithBodies.pop_back();
1939 // Save the current stream state.
1940 uint64_t CurBit = Stream.GetCurrentBitNo();
1941 DeferredFunctionInfo[Fn] = CurBit;
1943 // Skip over the function block for now.
1944 if (Stream.SkipBlock())
1945 return Error("Invalid record");
1946 return std::error_code();
1949 std::error_code BitcodeReader::GlobalCleanup() {
1950 // Patch the initializers for globals and aliases up.
1951 ResolveGlobalAndAliasInits();
1952 if (!GlobalInits.empty() || !AliasInits.empty())
1953 return Error("Malformed global initializer set");
1955 // Look for intrinsic functions which need to be upgraded at some point
1956 for (Module::iterator FI = TheModule->begin(), FE = TheModule->end();
1959 if (UpgradeIntrinsicFunction(FI, NewFn))
1960 UpgradedIntrinsics.push_back(std::make_pair(FI, NewFn));
1963 // Look for global variables which need to be renamed.
1964 for (Module::global_iterator
1965 GI = TheModule->global_begin(), GE = TheModule->global_end();
1967 GlobalVariable *GV = GI++;
1968 UpgradeGlobalVariable(GV);
1971 // Force deallocation of memory for these vectors to favor the client that
1972 // want lazy deserialization.
1973 std::vector<std::pair<GlobalVariable*, unsigned> >().swap(GlobalInits);
1974 std::vector<std::pair<GlobalAlias*, unsigned> >().swap(AliasInits);
1975 return std::error_code();
1978 std::error_code BitcodeReader::ParseModule(bool Resume) {
1980 Stream.JumpToBit(NextUnreadBit);
1981 else if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
1982 return Error("Invalid record");
1984 SmallVector<uint64_t, 64> Record;
1985 std::vector<std::string> SectionTable;
1986 std::vector<std::string> GCTable;
1988 // Read all the records for this module.
1990 BitstreamEntry Entry = Stream.advance();
1992 switch (Entry.Kind) {
1993 case BitstreamEntry::Error:
1994 return Error("Malformed block");
1995 case BitstreamEntry::EndBlock:
1996 return GlobalCleanup();
1998 case BitstreamEntry::SubBlock:
2000 default: // Skip unknown content.
2001 if (Stream.SkipBlock())
2002 return Error("Invalid record");
2004 case bitc::BLOCKINFO_BLOCK_ID:
2005 if (Stream.ReadBlockInfoBlock())
2006 return Error("Malformed block");
2008 case bitc::PARAMATTR_BLOCK_ID:
2009 if (std::error_code EC = ParseAttributeBlock())
2012 case bitc::PARAMATTR_GROUP_BLOCK_ID:
2013 if (std::error_code EC = ParseAttributeGroupBlock())
2016 case bitc::TYPE_BLOCK_ID_NEW:
2017 if (std::error_code EC = ParseTypeTable())
2020 case bitc::VALUE_SYMTAB_BLOCK_ID:
2021 if (std::error_code EC = ParseValueSymbolTable())
2023 SeenValueSymbolTable = true;
2025 case bitc::CONSTANTS_BLOCK_ID:
2026 if (std::error_code EC = ParseConstants())
2028 if (std::error_code EC = ResolveGlobalAndAliasInits())
2031 case bitc::METADATA_BLOCK_ID:
2032 if (std::error_code EC = ParseMetadata())
2035 case bitc::FUNCTION_BLOCK_ID:
2036 // If this is the first function body we've seen, reverse the
2037 // FunctionsWithBodies list.
2038 if (!SeenFirstFunctionBody) {
2039 std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
2040 if (std::error_code EC = GlobalCleanup())
2042 SeenFirstFunctionBody = true;
2045 if (std::error_code EC = RememberAndSkipFunctionBody())
2047 // For streaming bitcode, suspend parsing when we reach the function
2048 // bodies. Subsequent materialization calls will resume it when
2049 // necessary. For streaming, the function bodies must be at the end of
2050 // the bitcode. If the bitcode file is old, the symbol table will be
2051 // at the end instead and will not have been seen yet. In this case,
2052 // just finish the parse now.
2053 if (LazyStreamer && SeenValueSymbolTable) {
2054 NextUnreadBit = Stream.GetCurrentBitNo();
2055 return std::error_code();
2058 case bitc::USELIST_BLOCK_ID:
2059 if (std::error_code EC = ParseUseLists())
2065 case BitstreamEntry::Record:
2066 // The interesting case.
2072 switch (Stream.readRecord(Entry.ID, Record)) {
2073 default: break; // Default behavior, ignore unknown content.
2074 case bitc::MODULE_CODE_VERSION: { // VERSION: [version#]
2075 if (Record.size() < 1)
2076 return Error("Invalid record");
2077 // Only version #0 and #1 are supported so far.
2078 unsigned module_version = Record[0];
2079 switch (module_version) {
2081 return Error("Invalid value");
2083 UseRelativeIDs = false;
2086 UseRelativeIDs = true;
2091 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
2093 if (ConvertToString(Record, 0, S))
2094 return Error("Invalid record");
2095 TheModule->setTargetTriple(S);
2098 case bitc::MODULE_CODE_DATALAYOUT: { // DATALAYOUT: [strchr x N]
2100 if (ConvertToString(Record, 0, S))
2101 return Error("Invalid record");
2102 TheModule->setDataLayout(S);
2105 case bitc::MODULE_CODE_ASM: { // ASM: [strchr x N]
2107 if (ConvertToString(Record, 0, S))
2108 return Error("Invalid record");
2109 TheModule->setModuleInlineAsm(S);
2112 case bitc::MODULE_CODE_DEPLIB: { // DEPLIB: [strchr x N]
2113 // FIXME: Remove in 4.0.
2115 if (ConvertToString(Record, 0, S))
2116 return Error("Invalid record");
2120 case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N]
2122 if (ConvertToString(Record, 0, S))
2123 return Error("Invalid record");
2124 SectionTable.push_back(S);
2127 case bitc::MODULE_CODE_GCNAME: { // SECTIONNAME: [strchr x N]
2129 if (ConvertToString(Record, 0, S))
2130 return Error("Invalid record");
2131 GCTable.push_back(S);
2134 case bitc::MODULE_CODE_COMDAT: { // COMDAT: [selection_kind, name]
2135 if (Record.size() < 2)
2136 return Error("Invalid record");
2137 Comdat::SelectionKind SK = getDecodedComdatSelectionKind(Record[0]);
2138 unsigned ComdatNameSize = Record[1];
2139 std::string ComdatName;
2140 ComdatName.reserve(ComdatNameSize);
2141 for (unsigned i = 0; i != ComdatNameSize; ++i)
2142 ComdatName += (char)Record[2 + i];
2143 Comdat *C = TheModule->getOrInsertComdat(ComdatName);
2144 C->setSelectionKind(SK);
2145 ComdatList.push_back(C);
2148 // GLOBALVAR: [pointer type, isconst, initid,
2149 // linkage, alignment, section, visibility, threadlocal,
2150 // unnamed_addr, dllstorageclass]
2151 case bitc::MODULE_CODE_GLOBALVAR: {
2152 if (Record.size() < 6)
2153 return Error("Invalid record");
2154 Type *Ty = getTypeByID(Record[0]);
2156 return Error("Invalid record");
2157 if (!Ty->isPointerTy())
2158 return Error("Invalid type for value");
2159 unsigned AddressSpace = cast<PointerType>(Ty)->getAddressSpace();
2160 Ty = cast<PointerType>(Ty)->getElementType();
2162 bool isConstant = Record[1];
2163 uint64_t RawLinkage = Record[3];
2164 GlobalValue::LinkageTypes Linkage = getDecodedLinkage(RawLinkage);
2165 unsigned Alignment = (1 << Record[4]) >> 1;
2166 std::string Section;
2168 if (Record[5]-1 >= SectionTable.size())
2169 return Error("Invalid ID");
2170 Section = SectionTable[Record[5]-1];
2172 GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;
2173 // Local linkage must have default visibility.
2174 if (Record.size() > 6 && !GlobalValue::isLocalLinkage(Linkage))
2175 // FIXME: Change to an error if non-default in 4.0.
2176 Visibility = GetDecodedVisibility(Record[6]);
2178 GlobalVariable::ThreadLocalMode TLM = GlobalVariable::NotThreadLocal;
2179 if (Record.size() > 7)
2180 TLM = GetDecodedThreadLocalMode(Record[7]);
2182 bool UnnamedAddr = false;
2183 if (Record.size() > 8)
2184 UnnamedAddr = Record[8];
2186 bool ExternallyInitialized = false;
2187 if (Record.size() > 9)
2188 ExternallyInitialized = Record[9];
2190 GlobalVariable *NewGV =
2191 new GlobalVariable(*TheModule, Ty, isConstant, Linkage, nullptr, "", nullptr,
2192 TLM, AddressSpace, ExternallyInitialized);
2193 NewGV->setAlignment(Alignment);
2194 if (!Section.empty())
2195 NewGV->setSection(Section);
2196 NewGV->setVisibility(Visibility);
2197 NewGV->setUnnamedAddr(UnnamedAddr);
2199 if (Record.size() > 10)
2200 NewGV->setDLLStorageClass(GetDecodedDLLStorageClass(Record[10]));
2202 UpgradeDLLImportExportLinkage(NewGV, RawLinkage);
2204 ValueList.push_back(NewGV);
2206 // Remember which value to use for the global initializer.
2207 if (unsigned InitID = Record[2])
2208 GlobalInits.push_back(std::make_pair(NewGV, InitID-1));
2210 if (Record.size() > 11) {
2211 if (unsigned ComdatID = Record[11]) {
2212 assert(ComdatID <= ComdatList.size());
2213 NewGV->setComdat(ComdatList[ComdatID - 1]);
2215 } else if (hasImplicitComdat(RawLinkage)) {
2216 NewGV->setComdat(reinterpret_cast<Comdat *>(1));
2220 // FUNCTION: [type, callingconv, isproto, linkage, paramattr,
2221 // alignment, section, visibility, gc, unnamed_addr,
2222 // prologuedata, dllstorageclass, comdat, prefixdata]
2223 case bitc::MODULE_CODE_FUNCTION: {
2224 if (Record.size() < 8)
2225 return Error("Invalid record");
2226 Type *Ty = getTypeByID(Record[0]);
2228 return Error("Invalid record");
2229 if (!Ty->isPointerTy())
2230 return Error("Invalid type for value");
2232 dyn_cast<FunctionType>(cast<PointerType>(Ty)->getElementType());
2234 return Error("Invalid type for value");
2236 Function *Func = Function::Create(FTy, GlobalValue::ExternalLinkage,
2239 Func->setCallingConv(static_cast<CallingConv::ID>(Record[1]));
2240 bool isProto = Record[2];
2241 uint64_t RawLinkage = Record[3];
2242 Func->setLinkage(getDecodedLinkage(RawLinkage));
2243 Func->setAttributes(getAttributes(Record[4]));
2245 Func->setAlignment((1 << Record[5]) >> 1);
2247 if (Record[6]-1 >= SectionTable.size())
2248 return Error("Invalid ID");
2249 Func->setSection(SectionTable[Record[6]-1]);
2251 // Local linkage must have default visibility.
2252 if (!Func->hasLocalLinkage())
2253 // FIXME: Change to an error if non-default in 4.0.
2254 Func->setVisibility(GetDecodedVisibility(Record[7]));
2255 if (Record.size() > 8 && Record[8]) {
2256 if (Record[8]-1 > GCTable.size())
2257 return Error("Invalid ID");
2258 Func->setGC(GCTable[Record[8]-1].c_str());
2260 bool UnnamedAddr = false;
2261 if (Record.size() > 9)
2262 UnnamedAddr = Record[9];
2263 Func->setUnnamedAddr(UnnamedAddr);
2264 if (Record.size() > 10 && Record[10] != 0)
2265 FunctionPrologues.push_back(std::make_pair(Func, Record[10]-1));
2267 if (Record.size() > 11)
2268 Func->setDLLStorageClass(GetDecodedDLLStorageClass(Record[11]));
2270 UpgradeDLLImportExportLinkage(Func, RawLinkage);
2272 if (Record.size() > 12) {
2273 if (unsigned ComdatID = Record[12]) {
2274 assert(ComdatID <= ComdatList.size());
2275 Func->setComdat(ComdatList[ComdatID - 1]);
2277 } else if (hasImplicitComdat(RawLinkage)) {
2278 Func->setComdat(reinterpret_cast<Comdat *>(1));
2281 if (Record.size() > 13 && Record[13] != 0)
2282 FunctionPrefixes.push_back(std::make_pair(Func, Record[13]-1));
2284 ValueList.push_back(Func);
2286 // If this is a function with a body, remember the prototype we are
2287 // creating now, so that we can match up the body with them later.
2289 Func->setIsMaterializable(true);
2290 FunctionsWithBodies.push_back(Func);
2292 DeferredFunctionInfo[Func] = 0;
2296 // ALIAS: [alias type, aliasee val#, linkage]
2297 // ALIAS: [alias type, aliasee val#, linkage, visibility, dllstorageclass]
2298 case bitc::MODULE_CODE_ALIAS: {
2299 if (Record.size() < 3)
2300 return Error("Invalid record");
2301 Type *Ty = getTypeByID(Record[0]);
2303 return Error("Invalid record");
2304 auto *PTy = dyn_cast<PointerType>(Ty);
2306 return Error("Invalid type for value");
2309 GlobalAlias::create(PTy->getElementType(), PTy->getAddressSpace(),
2310 getDecodedLinkage(Record[2]), "", TheModule);
2311 // Old bitcode files didn't have visibility field.
2312 // Local linkage must have default visibility.
2313 if (Record.size() > 3 && !NewGA->hasLocalLinkage())
2314 // FIXME: Change to an error if non-default in 4.0.
2315 NewGA->setVisibility(GetDecodedVisibility(Record[3]));
2316 if (Record.size() > 4)
2317 NewGA->setDLLStorageClass(GetDecodedDLLStorageClass(Record[4]));
2319 UpgradeDLLImportExportLinkage(NewGA, Record[2]);
2320 if (Record.size() > 5)
2321 NewGA->setThreadLocalMode(GetDecodedThreadLocalMode(Record[5]));
2322 if (Record.size() > 6)
2323 NewGA->setUnnamedAddr(Record[6]);
2324 ValueList.push_back(NewGA);
2325 AliasInits.push_back(std::make_pair(NewGA, Record[1]));
2328 /// MODULE_CODE_PURGEVALS: [numvals]
2329 case bitc::MODULE_CODE_PURGEVALS:
2330 // Trim down the value list to the specified size.
2331 if (Record.size() < 1 || Record[0] > ValueList.size())
2332 return Error("Invalid record");
2333 ValueList.shrinkTo(Record[0]);
2340 std::error_code BitcodeReader::ParseBitcodeInto(Module *M) {
2341 TheModule = nullptr;
2343 if (std::error_code EC = InitStream())
2346 // Sniff for the signature.
2347 if (Stream.Read(8) != 'B' ||
2348 Stream.Read(8) != 'C' ||
2349 Stream.Read(4) != 0x0 ||
2350 Stream.Read(4) != 0xC ||
2351 Stream.Read(4) != 0xE ||
2352 Stream.Read(4) != 0xD)
2353 return Error("Invalid bitcode signature");
2355 // We expect a number of well-defined blocks, though we don't necessarily
2356 // need to understand them all.
2358 if (Stream.AtEndOfStream())
2359 return std::error_code();
2361 BitstreamEntry Entry =
2362 Stream.advance(BitstreamCursor::AF_DontAutoprocessAbbrevs);
2364 switch (Entry.Kind) {
2365 case BitstreamEntry::Error:
2366 return Error("Malformed block");
2367 case BitstreamEntry::EndBlock:
2368 return std::error_code();
2370 case BitstreamEntry::SubBlock:
2372 case bitc::BLOCKINFO_BLOCK_ID:
2373 if (Stream.ReadBlockInfoBlock())
2374 return Error("Malformed block");
2376 case bitc::MODULE_BLOCK_ID:
2377 // Reject multiple MODULE_BLOCK's in a single bitstream.
2379 return Error("Invalid multiple blocks");
2381 if (std::error_code EC = ParseModule(false))
2384 return std::error_code();
2387 if (Stream.SkipBlock())
2388 return Error("Invalid record");
2392 case BitstreamEntry::Record:
2393 // There should be no records in the top-level of blocks.
2395 // The ranlib in Xcode 4 will align archive members by appending newlines
2396 // to the end of them. If this file size is a multiple of 4 but not 8, we
2397 // have to read and ignore these final 4 bytes :-(
2398 if (Stream.getAbbrevIDWidth() == 2 && Entry.ID == 2 &&
2399 Stream.Read(6) == 2 && Stream.Read(24) == 0xa0a0a &&
2400 Stream.AtEndOfStream())
2401 return std::error_code();
2403 return Error("Invalid record");
2408 ErrorOr<std::string> BitcodeReader::parseModuleTriple() {
2409 if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
2410 return Error("Invalid record");
2412 SmallVector<uint64_t, 64> Record;
2415 // Read all the records for this module.
2417 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
2419 switch (Entry.Kind) {
2420 case BitstreamEntry::SubBlock: // Handled for us already.
2421 case BitstreamEntry::Error:
2422 return Error("Malformed block");
2423 case BitstreamEntry::EndBlock:
2425 case BitstreamEntry::Record:
2426 // The interesting case.
2431 switch (Stream.readRecord(Entry.ID, Record)) {
2432 default: break; // Default behavior, ignore unknown content.
2433 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
2435 if (ConvertToString(Record, 0, S))
2436 return Error("Invalid record");
2443 llvm_unreachable("Exit infinite loop");
2446 ErrorOr<std::string> BitcodeReader::parseTriple() {
2447 if (std::error_code EC = InitStream())
2450 // Sniff for the signature.
2451 if (Stream.Read(8) != 'B' ||
2452 Stream.Read(8) != 'C' ||
2453 Stream.Read(4) != 0x0 ||
2454 Stream.Read(4) != 0xC ||
2455 Stream.Read(4) != 0xE ||
2456 Stream.Read(4) != 0xD)
2457 return Error("Invalid bitcode signature");
2459 // We expect a number of well-defined blocks, though we don't necessarily
2460 // need to understand them all.
2462 BitstreamEntry Entry = Stream.advance();
2464 switch (Entry.Kind) {
2465 case BitstreamEntry::Error:
2466 return Error("Malformed block");
2467 case BitstreamEntry::EndBlock:
2468 return std::error_code();
2470 case BitstreamEntry::SubBlock:
2471 if (Entry.ID == bitc::MODULE_BLOCK_ID)
2472 return parseModuleTriple();
2474 // Ignore other sub-blocks.
2475 if (Stream.SkipBlock())
2476 return Error("Malformed block");
2479 case BitstreamEntry::Record:
2480 Stream.skipRecord(Entry.ID);
2486 /// ParseMetadataAttachment - Parse metadata attachments.
2487 std::error_code BitcodeReader::ParseMetadataAttachment() {
2488 if (Stream.EnterSubBlock(bitc::METADATA_ATTACHMENT_ID))
2489 return Error("Invalid record");
2491 SmallVector<uint64_t, 64> Record;
2493 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
2495 switch (Entry.Kind) {
2496 case BitstreamEntry::SubBlock: // Handled for us already.
2497 case BitstreamEntry::Error:
2498 return Error("Malformed block");
2499 case BitstreamEntry::EndBlock:
2500 return std::error_code();
2501 case BitstreamEntry::Record:
2502 // The interesting case.
2506 // Read a metadata attachment record.
2508 switch (Stream.readRecord(Entry.ID, Record)) {
2509 default: // Default behavior: ignore.
2511 case bitc::METADATA_ATTACHMENT: {
2512 unsigned RecordLength = Record.size();
2513 if (Record.empty() || (RecordLength - 1) % 2 == 1)
2514 return Error("Invalid record");
2515 Instruction *Inst = InstructionList[Record[0]];
2516 for (unsigned i = 1; i != RecordLength; i = i+2) {
2517 unsigned Kind = Record[i];
2518 DenseMap<unsigned, unsigned>::iterator I =
2519 MDKindMap.find(Kind);
2520 if (I == MDKindMap.end())
2521 return Error("Invalid ID");
2522 Metadata *Node = MDValueList.getValueFwdRef(Record[i + 1]);
2523 if (isa<LocalAsMetadata>(Node))
2524 // Drop the attachment. This used to be legal, but there's no
2527 Inst->setMetadata(I->second, cast<MDNode>(Node));
2528 if (I->second == LLVMContext::MD_tbaa)
2529 InstsWithTBAATag.push_back(Inst);
2537 /// ParseFunctionBody - Lazily parse the specified function body block.
2538 std::error_code BitcodeReader::ParseFunctionBody(Function *F) {
2539 if (Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID))
2540 return Error("Invalid record");
2542 InstructionList.clear();
2543 unsigned ModuleValueListSize = ValueList.size();
2544 unsigned ModuleMDValueListSize = MDValueList.size();
2546 // Add all the function arguments to the value table.
2547 for(Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
2548 ValueList.push_back(I);
2550 unsigned NextValueNo = ValueList.size();
2551 BasicBlock *CurBB = nullptr;
2552 unsigned CurBBNo = 0;
2555 auto getLastInstruction = [&]() -> Instruction * {
2556 if (CurBB && !CurBB->empty())
2557 return &CurBB->back();
2558 else if (CurBBNo && FunctionBBs[CurBBNo - 1] &&
2559 !FunctionBBs[CurBBNo - 1]->empty())
2560 return &FunctionBBs[CurBBNo - 1]->back();
2564 // Read all the records.
2565 SmallVector<uint64_t, 64> Record;
2567 BitstreamEntry Entry = Stream.advance();
2569 switch (Entry.Kind) {
2570 case BitstreamEntry::Error:
2571 return Error("Malformed block");
2572 case BitstreamEntry::EndBlock:
2573 goto OutOfRecordLoop;
2575 case BitstreamEntry::SubBlock:
2577 default: // Skip unknown content.
2578 if (Stream.SkipBlock())
2579 return Error("Invalid record");
2581 case bitc::CONSTANTS_BLOCK_ID:
2582 if (std::error_code EC = ParseConstants())
2584 NextValueNo = ValueList.size();
2586 case bitc::VALUE_SYMTAB_BLOCK_ID:
2587 if (std::error_code EC = ParseValueSymbolTable())
2590 case bitc::METADATA_ATTACHMENT_ID:
2591 if (std::error_code EC = ParseMetadataAttachment())
2594 case bitc::METADATA_BLOCK_ID:
2595 if (std::error_code EC = ParseMetadata())
2598 case bitc::USELIST_BLOCK_ID:
2599 if (std::error_code EC = ParseUseLists())
2605 case BitstreamEntry::Record:
2606 // The interesting case.
2612 Instruction *I = nullptr;
2613 unsigned BitCode = Stream.readRecord(Entry.ID, Record);
2615 default: // Default behavior: reject
2616 return Error("Invalid value");
2617 case bitc::FUNC_CODE_DECLAREBLOCKS: { // DECLAREBLOCKS: [nblocks]
2618 if (Record.size() < 1 || Record[0] == 0)
2619 return Error("Invalid record");
2620 // Create all the basic blocks for the function.
2621 FunctionBBs.resize(Record[0]);
2623 // See if anything took the address of blocks in this function.
2624 auto BBFRI = BasicBlockFwdRefs.find(F);
2625 if (BBFRI == BasicBlockFwdRefs.end()) {
2626 for (unsigned i = 0, e = FunctionBBs.size(); i != e; ++i)
2627 FunctionBBs[i] = BasicBlock::Create(Context, "", F);
2629 auto &BBRefs = BBFRI->second;
2630 // Check for invalid basic block references.
2631 if (BBRefs.size() > FunctionBBs.size())
2632 return Error("Invalid ID");
2633 assert(!BBRefs.empty() && "Unexpected empty array");
2634 assert(!BBRefs.front() && "Invalid reference to entry block");
2635 for (unsigned I = 0, E = FunctionBBs.size(), RE = BBRefs.size(); I != E;
2637 if (I < RE && BBRefs[I]) {
2638 BBRefs[I]->insertInto(F);
2639 FunctionBBs[I] = BBRefs[I];
2641 FunctionBBs[I] = BasicBlock::Create(Context, "", F);
2644 // Erase from the table.
2645 BasicBlockFwdRefs.erase(BBFRI);
2648 CurBB = FunctionBBs[0];
2652 case bitc::FUNC_CODE_DEBUG_LOC_AGAIN: // DEBUG_LOC_AGAIN
2653 // This record indicates that the last instruction is at the same
2654 // location as the previous instruction with a location.
2655 I = getLastInstruction();
2658 return Error("Invalid record");
2659 I->setDebugLoc(LastLoc);
2663 case bitc::FUNC_CODE_DEBUG_LOC: { // DEBUG_LOC: [line, col, scope, ia]
2664 I = getLastInstruction();
2665 if (!I || Record.size() < 4)
2666 return Error("Invalid record");
2668 unsigned Line = Record[0], Col = Record[1];
2669 unsigned ScopeID = Record[2], IAID = Record[3];
2671 MDNode *Scope = nullptr, *IA = nullptr;
2672 if (ScopeID) Scope = cast<MDNode>(MDValueList.getValueFwdRef(ScopeID-1));
2673 if (IAID) IA = cast<MDNode>(MDValueList.getValueFwdRef(IAID-1));
2674 LastLoc = DebugLoc::get(Line, Col, Scope, IA);
2675 I->setDebugLoc(LastLoc);
2680 case bitc::FUNC_CODE_INST_BINOP: { // BINOP: [opval, ty, opval, opcode]
2683 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
2684 popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) ||
2685 OpNum+1 > Record.size())
2686 return Error("Invalid record");
2688 int Opc = GetDecodedBinaryOpcode(Record[OpNum++], LHS->getType());
2690 return Error("Invalid record");
2691 I = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
2692 InstructionList.push_back(I);
2693 if (OpNum < Record.size()) {
2694 if (Opc == Instruction::Add ||
2695 Opc == Instruction::Sub ||
2696 Opc == Instruction::Mul ||
2697 Opc == Instruction::Shl) {
2698 if (Record[OpNum] & (1 << bitc::OBO_NO_SIGNED_WRAP))
2699 cast<BinaryOperator>(I)->setHasNoSignedWrap(true);
2700 if (Record[OpNum] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
2701 cast<BinaryOperator>(I)->setHasNoUnsignedWrap(true);
2702 } else if (Opc == Instruction::SDiv ||
2703 Opc == Instruction::UDiv ||
2704 Opc == Instruction::LShr ||
2705 Opc == Instruction::AShr) {
2706 if (Record[OpNum] & (1 << bitc::PEO_EXACT))
2707 cast<BinaryOperator>(I)->setIsExact(true);
2708 } else if (isa<FPMathOperator>(I)) {
2710 if (0 != (Record[OpNum] & FastMathFlags::UnsafeAlgebra))
2711 FMF.setUnsafeAlgebra();
2712 if (0 != (Record[OpNum] & FastMathFlags::NoNaNs))
2714 if (0 != (Record[OpNum] & FastMathFlags::NoInfs))
2716 if (0 != (Record[OpNum] & FastMathFlags::NoSignedZeros))
2717 FMF.setNoSignedZeros();
2718 if (0 != (Record[OpNum] & FastMathFlags::AllowReciprocal))
2719 FMF.setAllowReciprocal();
2721 I->setFastMathFlags(FMF);
2727 case bitc::FUNC_CODE_INST_CAST: { // CAST: [opval, opty, destty, castopc]
2730 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
2731 OpNum+2 != Record.size())
2732 return Error("Invalid record");
2734 Type *ResTy = getTypeByID(Record[OpNum]);
2735 int Opc = GetDecodedCastOpcode(Record[OpNum+1]);
2736 if (Opc == -1 || !ResTy)
2737 return Error("Invalid record");
2738 Instruction *Temp = nullptr;
2739 if ((I = UpgradeBitCastInst(Opc, Op, ResTy, Temp))) {
2741 InstructionList.push_back(Temp);
2742 CurBB->getInstList().push_back(Temp);
2745 I = CastInst::Create((Instruction::CastOps)Opc, Op, ResTy);
2747 InstructionList.push_back(I);
2750 case bitc::FUNC_CODE_INST_INBOUNDS_GEP:
2751 case bitc::FUNC_CODE_INST_GEP: { // GEP: [n x operands]
2754 if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr))
2755 return Error("Invalid record");
2757 SmallVector<Value*, 16> GEPIdx;
2758 while (OpNum != Record.size()) {
2760 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2761 return Error("Invalid record");
2762 GEPIdx.push_back(Op);
2765 I = GetElementPtrInst::Create(BasePtr, GEPIdx);
2766 InstructionList.push_back(I);
2767 if (BitCode == bitc::FUNC_CODE_INST_INBOUNDS_GEP)
2768 cast<GetElementPtrInst>(I)->setIsInBounds(true);
2772 case bitc::FUNC_CODE_INST_EXTRACTVAL: {
2773 // EXTRACTVAL: [opty, opval, n x indices]
2776 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
2777 return Error("Invalid record");
2779 SmallVector<unsigned, 4> EXTRACTVALIdx;
2780 for (unsigned RecSize = Record.size();
2781 OpNum != RecSize; ++OpNum) {
2782 uint64_t Index = Record[OpNum];
2783 if ((unsigned)Index != Index)
2784 return Error("Invalid value");
2785 EXTRACTVALIdx.push_back((unsigned)Index);
2788 I = ExtractValueInst::Create(Agg, EXTRACTVALIdx);
2789 InstructionList.push_back(I);
2793 case bitc::FUNC_CODE_INST_INSERTVAL: {
2794 // INSERTVAL: [opty, opval, opty, opval, n x indices]
2797 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
2798 return Error("Invalid record");
2800 if (getValueTypePair(Record, OpNum, NextValueNo, Val))
2801 return Error("Invalid record");
2803 SmallVector<unsigned, 4> INSERTVALIdx;
2804 for (unsigned RecSize = Record.size();
2805 OpNum != RecSize; ++OpNum) {
2806 uint64_t Index = Record[OpNum];
2807 if ((unsigned)Index != Index)
2808 return Error("Invalid value");
2809 INSERTVALIdx.push_back((unsigned)Index);
2812 I = InsertValueInst::Create(Agg, Val, INSERTVALIdx);
2813 InstructionList.push_back(I);
2817 case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval]
2818 // obsolete form of select
2819 // handles select i1 ... in old bitcode
2821 Value *TrueVal, *FalseVal, *Cond;
2822 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
2823 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
2824 popValue(Record, OpNum, NextValueNo, Type::getInt1Ty(Context), Cond))
2825 return Error("Invalid record");
2827 I = SelectInst::Create(Cond, TrueVal, FalseVal);
2828 InstructionList.push_back(I);
2832 case bitc::FUNC_CODE_INST_VSELECT: {// VSELECT: [ty,opval,opval,predty,pred]
2833 // new form of select
2834 // handles select i1 or select [N x i1]
2836 Value *TrueVal, *FalseVal, *Cond;
2837 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
2838 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
2839 getValueTypePair(Record, OpNum, NextValueNo, Cond))
2840 return Error("Invalid record");
2842 // select condition can be either i1 or [N x i1]
2843 if (VectorType* vector_type =
2844 dyn_cast<VectorType>(Cond->getType())) {
2846 if (vector_type->getElementType() != Type::getInt1Ty(Context))
2847 return Error("Invalid type for value");
2850 if (Cond->getType() != Type::getInt1Ty(Context))
2851 return Error("Invalid type for value");
2854 I = SelectInst::Create(Cond, TrueVal, FalseVal);
2855 InstructionList.push_back(I);
2859 case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval]
2862 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
2863 getValueTypePair(Record, OpNum, NextValueNo, Idx))
2864 return Error("Invalid record");
2865 I = ExtractElementInst::Create(Vec, Idx);
2866 InstructionList.push_back(I);
2870 case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval]
2872 Value *Vec, *Elt, *Idx;
2873 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
2874 popValue(Record, OpNum, NextValueNo,
2875 cast<VectorType>(Vec->getType())->getElementType(), Elt) ||
2876 getValueTypePair(Record, OpNum, NextValueNo, Idx))
2877 return Error("Invalid record");
2878 I = InsertElementInst::Create(Vec, Elt, Idx);
2879 InstructionList.push_back(I);
2883 case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval]
2885 Value *Vec1, *Vec2, *Mask;
2886 if (getValueTypePair(Record, OpNum, NextValueNo, Vec1) ||
2887 popValue(Record, OpNum, NextValueNo, Vec1->getType(), Vec2))
2888 return Error("Invalid record");
2890 if (getValueTypePair(Record, OpNum, NextValueNo, Mask))
2891 return Error("Invalid record");
2892 I = new ShuffleVectorInst(Vec1, Vec2, Mask);
2893 InstructionList.push_back(I);
2897 case bitc::FUNC_CODE_INST_CMP: // CMP: [opty, opval, opval, pred]
2898 // Old form of ICmp/FCmp returning bool
2899 // Existed to differentiate between icmp/fcmp and vicmp/vfcmp which were
2900 // both legal on vectors but had different behaviour.
2901 case bitc::FUNC_CODE_INST_CMP2: { // CMP2: [opty, opval, opval, pred]
2902 // FCmp/ICmp returning bool or vector of bool
2906 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
2907 popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) ||
2908 OpNum+1 != Record.size())
2909 return Error("Invalid record");
2911 if (LHS->getType()->isFPOrFPVectorTy())
2912 I = new FCmpInst((FCmpInst::Predicate)Record[OpNum], LHS, RHS);
2914 I = new ICmpInst((ICmpInst::Predicate)Record[OpNum], LHS, RHS);
2915 InstructionList.push_back(I);
2919 case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>]
2921 unsigned Size = Record.size();
2923 I = ReturnInst::Create(Context);
2924 InstructionList.push_back(I);
2929 Value *Op = nullptr;
2930 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2931 return Error("Invalid record");
2932 if (OpNum != Record.size())
2933 return Error("Invalid record");
2935 I = ReturnInst::Create(Context, Op);
2936 InstructionList.push_back(I);
2939 case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#]
2940 if (Record.size() != 1 && Record.size() != 3)
2941 return Error("Invalid record");
2942 BasicBlock *TrueDest = getBasicBlock(Record[0]);
2944 return Error("Invalid record");
2946 if (Record.size() == 1) {
2947 I = BranchInst::Create(TrueDest);
2948 InstructionList.push_back(I);
2951 BasicBlock *FalseDest = getBasicBlock(Record[1]);
2952 Value *Cond = getValue(Record, 2, NextValueNo,
2953 Type::getInt1Ty(Context));
2954 if (!FalseDest || !Cond)
2955 return Error("Invalid record");
2956 I = BranchInst::Create(TrueDest, FalseDest, Cond);
2957 InstructionList.push_back(I);
2961 case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, op0, op1, ...]
2963 if ((Record[0] >> 16) == SWITCH_INST_MAGIC) {
2964 // "New" SwitchInst format with case ranges. The changes to write this
2965 // format were reverted but we still recognize bitcode that uses it.
2966 // Hopefully someday we will have support for case ranges and can use
2967 // this format again.
2969 Type *OpTy = getTypeByID(Record[1]);
2970 unsigned ValueBitWidth = cast<IntegerType>(OpTy)->getBitWidth();
2972 Value *Cond = getValue(Record, 2, NextValueNo, OpTy);
2973 BasicBlock *Default = getBasicBlock(Record[3]);
2974 if (!OpTy || !Cond || !Default)
2975 return Error("Invalid record");
2977 unsigned NumCases = Record[4];
2979 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
2980 InstructionList.push_back(SI);
2982 unsigned CurIdx = 5;
2983 for (unsigned i = 0; i != NumCases; ++i) {
2984 SmallVector<ConstantInt*, 1> CaseVals;
2985 unsigned NumItems = Record[CurIdx++];
2986 for (unsigned ci = 0; ci != NumItems; ++ci) {
2987 bool isSingleNumber = Record[CurIdx++];
2990 unsigned ActiveWords = 1;
2991 if (ValueBitWidth > 64)
2992 ActiveWords = Record[CurIdx++];
2993 Low = ReadWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords),
2995 CurIdx += ActiveWords;
2997 if (!isSingleNumber) {
2999 if (ValueBitWidth > 64)
3000 ActiveWords = Record[CurIdx++];
3002 ReadWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords),
3004 CurIdx += ActiveWords;
3006 // FIXME: It is not clear whether values in the range should be
3007 // compared as signed or unsigned values. The partially
3008 // implemented changes that used this format in the past used
3009 // unsigned comparisons.
3010 for ( ; Low.ule(High); ++Low)
3011 CaseVals.push_back(ConstantInt::get(Context, Low));
3013 CaseVals.push_back(ConstantInt::get(Context, Low));
3015 BasicBlock *DestBB = getBasicBlock(Record[CurIdx++]);
3016 for (SmallVector<ConstantInt*, 1>::iterator cvi = CaseVals.begin(),
3017 cve = CaseVals.end(); cvi != cve; ++cvi)
3018 SI->addCase(*cvi, DestBB);
3024 // Old SwitchInst format without case ranges.
3026 if (Record.size() < 3 || (Record.size() & 1) == 0)
3027 return Error("Invalid record");
3028 Type *OpTy = getTypeByID(Record[0]);
3029 Value *Cond = getValue(Record, 1, NextValueNo, OpTy);
3030 BasicBlock *Default = getBasicBlock(Record[2]);
3031 if (!OpTy || !Cond || !Default)
3032 return Error("Invalid record");
3033 unsigned NumCases = (Record.size()-3)/2;
3034 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
3035 InstructionList.push_back(SI);
3036 for (unsigned i = 0, e = NumCases; i != e; ++i) {
3037 ConstantInt *CaseVal =
3038 dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy));
3039 BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]);
3040 if (!CaseVal || !DestBB) {
3042 return Error("Invalid record");
3044 SI->addCase(CaseVal, DestBB);
3049 case bitc::FUNC_CODE_INST_INDIRECTBR: { // INDIRECTBR: [opty, op0, op1, ...]
3050 if (Record.size() < 2)
3051 return Error("Invalid record");
3052 Type *OpTy = getTypeByID(Record[0]);
3053 Value *Address = getValue(Record, 1, NextValueNo, OpTy);
3054 if (!OpTy || !Address)
3055 return Error("Invalid record");
3056 unsigned NumDests = Record.size()-2;
3057 IndirectBrInst *IBI = IndirectBrInst::Create(Address, NumDests);
3058 InstructionList.push_back(IBI);
3059 for (unsigned i = 0, e = NumDests; i != e; ++i) {
3060 if (BasicBlock *DestBB = getBasicBlock(Record[2+i])) {
3061 IBI->addDestination(DestBB);
3064 return Error("Invalid record");
3071 case bitc::FUNC_CODE_INST_INVOKE: {
3072 // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...]
3073 if (Record.size() < 4)
3074 return Error("Invalid record");
3075 AttributeSet PAL = getAttributes(Record[0]);
3076 unsigned CCInfo = Record[1];
3077 BasicBlock *NormalBB = getBasicBlock(Record[2]);
3078 BasicBlock *UnwindBB = getBasicBlock(Record[3]);
3082 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
3083 return Error("Invalid record");
3085 PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType());
3086 FunctionType *FTy = !CalleeTy ? nullptr :
3087 dyn_cast<FunctionType>(CalleeTy->getElementType());
3089 // Check that the right number of fixed parameters are here.
3090 if (!FTy || !NormalBB || !UnwindBB ||
3091 Record.size() < OpNum+FTy->getNumParams())
3092 return Error("Invalid record");
3094 SmallVector<Value*, 16> Ops;
3095 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
3096 Ops.push_back(getValue(Record, OpNum, NextValueNo,
3097 FTy->getParamType(i)));
3099 return Error("Invalid record");
3102 if (!FTy->isVarArg()) {
3103 if (Record.size() != OpNum)
3104 return Error("Invalid record");
3106 // Read type/value pairs for varargs params.
3107 while (OpNum != Record.size()) {
3109 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
3110 return Error("Invalid record");
3115 I = InvokeInst::Create(Callee, NormalBB, UnwindBB, Ops);
3116 InstructionList.push_back(I);
3117 cast<InvokeInst>(I)->setCallingConv(
3118 static_cast<CallingConv::ID>(CCInfo));
3119 cast<InvokeInst>(I)->setAttributes(PAL);
3122 case bitc::FUNC_CODE_INST_RESUME: { // RESUME: [opval]
3124 Value *Val = nullptr;
3125 if (getValueTypePair(Record, Idx, NextValueNo, Val))
3126 return Error("Invalid record");
3127 I = ResumeInst::Create(Val);
3128 InstructionList.push_back(I);
3131 case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE
3132 I = new UnreachableInst(Context);
3133 InstructionList.push_back(I);
3135 case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...]
3136 if (Record.size() < 1 || ((Record.size()-1)&1))
3137 return Error("Invalid record");
3138 Type *Ty = getTypeByID(Record[0]);
3140 return Error("Invalid record");
3142 PHINode *PN = PHINode::Create(Ty, (Record.size()-1)/2);
3143 InstructionList.push_back(PN);
3145 for (unsigned i = 0, e = Record.size()-1; i != e; i += 2) {
3147 // With the new function encoding, it is possible that operands have
3148 // negative IDs (for forward references). Use a signed VBR
3149 // representation to keep the encoding small.
3151 V = getValueSigned(Record, 1+i, NextValueNo, Ty);
3153 V = getValue(Record, 1+i, NextValueNo, Ty);
3154 BasicBlock *BB = getBasicBlock(Record[2+i]);
3156 return Error("Invalid record");
3157 PN->addIncoming(V, BB);
3163 case bitc::FUNC_CODE_INST_LANDINGPAD: {
3164 // LANDINGPAD: [ty, val, val, num, (id0,val0 ...)?]
3166 if (Record.size() < 4)
3167 return Error("Invalid record");
3168 Type *Ty = getTypeByID(Record[Idx++]);
3170 return Error("Invalid record");
3171 Value *PersFn = nullptr;
3172 if (getValueTypePair(Record, Idx, NextValueNo, PersFn))
3173 return Error("Invalid record");
3175 bool IsCleanup = !!Record[Idx++];
3176 unsigned NumClauses = Record[Idx++];
3177 LandingPadInst *LP = LandingPadInst::Create(Ty, PersFn, NumClauses);
3178 LP->setCleanup(IsCleanup);
3179 for (unsigned J = 0; J != NumClauses; ++J) {
3180 LandingPadInst::ClauseType CT =
3181 LandingPadInst::ClauseType(Record[Idx++]); (void)CT;
3184 if (getValueTypePair(Record, Idx, NextValueNo, Val)) {
3186 return Error("Invalid record");
3189 assert((CT != LandingPadInst::Catch ||
3190 !isa<ArrayType>(Val->getType())) &&
3191 "Catch clause has a invalid type!");
3192 assert((CT != LandingPadInst::Filter ||
3193 isa<ArrayType>(Val->getType())) &&
3194 "Filter clause has invalid type!");
3195 LP->addClause(cast<Constant>(Val));
3199 InstructionList.push_back(I);
3203 case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, opty, op, align]
3204 if (Record.size() != 4)
3205 return Error("Invalid record");
3207 dyn_cast_or_null<PointerType>(getTypeByID(Record[0]));
3208 Type *OpTy = getTypeByID(Record[1]);
3209 Value *Size = getFnValueByID(Record[2], OpTy);
3210 unsigned AlignRecord = Record[3];
3211 bool InAlloca = AlignRecord & (1 << 5);
3212 unsigned Align = AlignRecord & ((1 << 5) - 1);
3214 return Error("Invalid record");
3215 AllocaInst *AI = new AllocaInst(Ty->getElementType(), Size, (1 << Align) >> 1);
3216 AI->setUsedWithInAlloca(InAlloca);
3218 InstructionList.push_back(I);
3221 case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol]
3224 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
3225 OpNum+2 != Record.size())
3226 return Error("Invalid record");
3228 I = new LoadInst(Op, "", Record[OpNum+1], (1 << Record[OpNum]) >> 1);
3229 InstructionList.push_back(I);
3232 case bitc::FUNC_CODE_INST_LOADATOMIC: {
3233 // LOADATOMIC: [opty, op, align, vol, ordering, synchscope]
3236 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
3237 OpNum+4 != Record.size())
3238 return Error("Invalid record");
3240 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
3241 if (Ordering == NotAtomic || Ordering == Release ||
3242 Ordering == AcquireRelease)
3243 return Error("Invalid record");
3244 if (Ordering != NotAtomic && Record[OpNum] == 0)
3245 return Error("Invalid record");
3246 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
3248 I = new LoadInst(Op, "", Record[OpNum+1], (1 << Record[OpNum]) >> 1,
3249 Ordering, SynchScope);
3250 InstructionList.push_back(I);
3253 case bitc::FUNC_CODE_INST_STORE: { // STORE2:[ptrty, ptr, val, align, vol]
3256 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
3257 popValue(Record, OpNum, NextValueNo,
3258 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
3259 OpNum+2 != Record.size())
3260 return Error("Invalid record");
3262 I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1);
3263 InstructionList.push_back(I);
3266 case bitc::FUNC_CODE_INST_STOREATOMIC: {
3267 // STOREATOMIC: [ptrty, ptr, val, align, vol, ordering, synchscope]
3270 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
3271 popValue(Record, OpNum, NextValueNo,
3272 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
3273 OpNum+4 != Record.size())
3274 return Error("Invalid record");
3276 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
3277 if (Ordering == NotAtomic || Ordering == Acquire ||
3278 Ordering == AcquireRelease)
3279 return Error("Invalid record");
3280 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
3281 if (Ordering != NotAtomic && Record[OpNum] == 0)
3282 return Error("Invalid record");
3284 I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1,
3285 Ordering, SynchScope);
3286 InstructionList.push_back(I);
3289 case bitc::FUNC_CODE_INST_CMPXCHG: {
3290 // CMPXCHG:[ptrty, ptr, cmp, new, vol, successordering, synchscope,
3291 // failureordering?, isweak?]
3293 Value *Ptr, *Cmp, *New;
3294 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
3295 popValue(Record, OpNum, NextValueNo,
3296 cast<PointerType>(Ptr->getType())->getElementType(), Cmp) ||
3297 popValue(Record, OpNum, NextValueNo,
3298 cast<PointerType>(Ptr->getType())->getElementType(), New) ||
3299 (Record.size() < OpNum + 3 || Record.size() > OpNum + 5))
3300 return Error("Invalid record");
3301 AtomicOrdering SuccessOrdering = GetDecodedOrdering(Record[OpNum+1]);
3302 if (SuccessOrdering == NotAtomic || SuccessOrdering == Unordered)
3303 return Error("Invalid record");
3304 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+2]);
3306 AtomicOrdering FailureOrdering;
3307 if (Record.size() < 7)
3309 AtomicCmpXchgInst::getStrongestFailureOrdering(SuccessOrdering);
3311 FailureOrdering = GetDecodedOrdering(Record[OpNum+3]);
3313 I = new AtomicCmpXchgInst(Ptr, Cmp, New, SuccessOrdering, FailureOrdering,
3315 cast<AtomicCmpXchgInst>(I)->setVolatile(Record[OpNum]);
3317 if (Record.size() < 8) {
3318 // Before weak cmpxchgs existed, the instruction simply returned the
3319 // value loaded from memory, so bitcode files from that era will be
3320 // expecting the first component of a modern cmpxchg.
3321 CurBB->getInstList().push_back(I);
3322 I = ExtractValueInst::Create(I, 0);
3324 cast<AtomicCmpXchgInst>(I)->setWeak(Record[OpNum+4]);
3327 InstructionList.push_back(I);
3330 case bitc::FUNC_CODE_INST_ATOMICRMW: {
3331 // ATOMICRMW:[ptrty, ptr, val, op, vol, ordering, synchscope]
3334 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
3335 popValue(Record, OpNum, NextValueNo,
3336 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
3337 OpNum+4 != Record.size())
3338 return Error("Invalid record");
3339 AtomicRMWInst::BinOp Operation = GetDecodedRMWOperation(Record[OpNum]);
3340 if (Operation < AtomicRMWInst::FIRST_BINOP ||
3341 Operation > AtomicRMWInst::LAST_BINOP)
3342 return Error("Invalid record");
3343 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
3344 if (Ordering == NotAtomic || Ordering == Unordered)
3345 return Error("Invalid record");
3346 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
3347 I = new AtomicRMWInst(Operation, Ptr, Val, Ordering, SynchScope);
3348 cast<AtomicRMWInst>(I)->setVolatile(Record[OpNum+1]);
3349 InstructionList.push_back(I);
3352 case bitc::FUNC_CODE_INST_FENCE: { // FENCE:[ordering, synchscope]
3353 if (2 != Record.size())
3354 return Error("Invalid record");
3355 AtomicOrdering Ordering = GetDecodedOrdering(Record[0]);
3356 if (Ordering == NotAtomic || Ordering == Unordered ||
3357 Ordering == Monotonic)
3358 return Error("Invalid record");
3359 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[1]);
3360 I = new FenceInst(Context, Ordering, SynchScope);
3361 InstructionList.push_back(I);
3364 case bitc::FUNC_CODE_INST_CALL: {
3365 // CALL: [paramattrs, cc, fnty, fnid, arg0, arg1...]
3366 if (Record.size() < 3)
3367 return Error("Invalid record");
3369 AttributeSet PAL = getAttributes(Record[0]);
3370 unsigned CCInfo = Record[1];
3374 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
3375 return Error("Invalid record");
3377 PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());
3378 FunctionType *FTy = nullptr;
3379 if (OpTy) FTy = dyn_cast<FunctionType>(OpTy->getElementType());
3380 if (!FTy || Record.size() < FTy->getNumParams()+OpNum)
3381 return Error("Invalid record");
3383 SmallVector<Value*, 16> Args;
3384 // Read the fixed params.
3385 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
3386 if (FTy->getParamType(i)->isLabelTy())
3387 Args.push_back(getBasicBlock(Record[OpNum]));
3389 Args.push_back(getValue(Record, OpNum, NextValueNo,
3390 FTy->getParamType(i)));
3392 return Error("Invalid record");
3395 // Read type/value pairs for varargs params.
3396 if (!FTy->isVarArg()) {
3397 if (OpNum != Record.size())
3398 return Error("Invalid record");
3400 while (OpNum != Record.size()) {
3402 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
3403 return Error("Invalid record");
3408 I = CallInst::Create(Callee, Args);
3409 InstructionList.push_back(I);
3410 cast<CallInst>(I)->setCallingConv(
3411 static_cast<CallingConv::ID>((~(1U << 14) & CCInfo) >> 1));
3412 CallInst::TailCallKind TCK = CallInst::TCK_None;
3414 TCK = CallInst::TCK_Tail;
3415 if (CCInfo & (1 << 14))
3416 TCK = CallInst::TCK_MustTail;
3417 cast<CallInst>(I)->setTailCallKind(TCK);
3418 cast<CallInst>(I)->setAttributes(PAL);
3421 case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty]
3422 if (Record.size() < 3)
3423 return Error("Invalid record");
3424 Type *OpTy = getTypeByID(Record[0]);
3425 Value *Op = getValue(Record, 1, NextValueNo, OpTy);
3426 Type *ResTy = getTypeByID(Record[2]);
3427 if (!OpTy || !Op || !ResTy)
3428 return Error("Invalid record");
3429 I = new VAArgInst(Op, ResTy);
3430 InstructionList.push_back(I);
3435 // Add instruction to end of current BB. If there is no current BB, reject
3439 return Error("Invalid instruction with no BB");
3441 CurBB->getInstList().push_back(I);
3443 // If this was a terminator instruction, move to the next block.
3444 if (isa<TerminatorInst>(I)) {
3446 CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : nullptr;
3449 // Non-void values get registered in the value table for future use.
3450 if (I && !I->getType()->isVoidTy())
3451 ValueList.AssignValue(I, NextValueNo++);
3456 // Check the function list for unresolved values.
3457 if (Argument *A = dyn_cast<Argument>(ValueList.back())) {
3458 if (!A->getParent()) {
3459 // We found at least one unresolved value. Nuke them all to avoid leaks.
3460 for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){
3461 if ((A = dyn_cast_or_null<Argument>(ValueList[i])) && !A->getParent()) {
3462 A->replaceAllUsesWith(UndefValue::get(A->getType()));
3466 return Error("Never resolved value found in function");
3470 // FIXME: Check for unresolved forward-declared metadata references
3471 // and clean up leaks.
3473 // Trim the value list down to the size it was before we parsed this function.
3474 ValueList.shrinkTo(ModuleValueListSize);
3475 MDValueList.shrinkTo(ModuleMDValueListSize);
3476 std::vector<BasicBlock*>().swap(FunctionBBs);
3477 return std::error_code();
3480 /// Find the function body in the bitcode stream
3481 std::error_code BitcodeReader::FindFunctionInStream(
3483 DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator) {
3484 while (DeferredFunctionInfoIterator->second == 0) {
3485 if (Stream.AtEndOfStream())
3486 return Error("Could not find function in stream");
3487 // ParseModule will parse the next body in the stream and set its
3488 // position in the DeferredFunctionInfo map.
3489 if (std::error_code EC = ParseModule(true))
3492 return std::error_code();
3495 //===----------------------------------------------------------------------===//
3496 // GVMaterializer implementation
3497 //===----------------------------------------------------------------------===//
3499 void BitcodeReader::releaseBuffer() { Buffer.release(); }
3501 std::error_code BitcodeReader::materialize(GlobalValue *GV) {
3502 Function *F = dyn_cast<Function>(GV);
3503 // If it's not a function or is already material, ignore the request.
3504 if (!F || !F->isMaterializable())
3505 return std::error_code();
3507 DenseMap<Function*, uint64_t>::iterator DFII = DeferredFunctionInfo.find(F);
3508 assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!");
3509 // If its position is recorded as 0, its body is somewhere in the stream
3510 // but we haven't seen it yet.
3511 if (DFII->second == 0 && LazyStreamer)
3512 if (std::error_code EC = FindFunctionInStream(F, DFII))
3515 // Move the bit stream to the saved position of the deferred function body.
3516 Stream.JumpToBit(DFII->second);
3518 if (std::error_code EC = ParseFunctionBody(F))
3520 F->setIsMaterializable(false);
3522 // Upgrade any old intrinsic calls in the function.
3523 for (UpgradedIntrinsicMap::iterator I = UpgradedIntrinsics.begin(),
3524 E = UpgradedIntrinsics.end(); I != E; ++I) {
3525 if (I->first != I->second) {
3526 for (auto UI = I->first->user_begin(), UE = I->first->user_end();
3528 if (CallInst* CI = dyn_cast<CallInst>(*UI++))
3529 UpgradeIntrinsicCall(CI, I->second);
3534 // Bring in any functions that this function forward-referenced via
3536 return materializeForwardReferencedFunctions();
3539 bool BitcodeReader::isDematerializable(const GlobalValue *GV) const {
3540 const Function *F = dyn_cast<Function>(GV);
3541 if (!F || F->isDeclaration())
3544 // Dematerializing F would leave dangling references that wouldn't be
3545 // reconnected on re-materialization.
3546 if (BlockAddressesTaken.count(F))
3549 return DeferredFunctionInfo.count(const_cast<Function*>(F));
3552 void BitcodeReader::Dematerialize(GlobalValue *GV) {
3553 Function *F = dyn_cast<Function>(GV);
3554 // If this function isn't dematerializable, this is a noop.
3555 if (!F || !isDematerializable(F))
3558 assert(DeferredFunctionInfo.count(F) && "No info to read function later?");
3560 // Just forget the function body, we can remat it later.
3561 F->dropAllReferences();
3562 F->setIsMaterializable(true);
3565 std::error_code BitcodeReader::MaterializeModule(Module *M) {
3566 assert(M == TheModule &&
3567 "Can only Materialize the Module this BitcodeReader is attached to.");
3569 // Promise to materialize all forward references.
3570 WillMaterializeAllForwardRefs = true;
3572 // Iterate over the module, deserializing any functions that are still on
3574 for (Module::iterator F = TheModule->begin(), E = TheModule->end();
3576 if (std::error_code EC = materialize(F))
3579 // At this point, if there are any function bodies, the current bit is
3580 // pointing to the END_BLOCK record after them. Now make sure the rest
3581 // of the bits in the module have been read.
3585 // Check that all block address forward references got resolved (as we
3587 if (!BasicBlockFwdRefs.empty())
3588 return Error("Never resolved function from blockaddress");
3590 // Upgrade any intrinsic calls that slipped through (should not happen!) and
3591 // delete the old functions to clean up. We can't do this unless the entire
3592 // module is materialized because there could always be another function body
3593 // with calls to the old function.
3594 for (std::vector<std::pair<Function*, Function*> >::iterator I =
3595 UpgradedIntrinsics.begin(), E = UpgradedIntrinsics.end(); I != E; ++I) {
3596 if (I->first != I->second) {
3597 for (auto UI = I->first->user_begin(), UE = I->first->user_end();
3599 if (CallInst* CI = dyn_cast<CallInst>(*UI++))
3600 UpgradeIntrinsicCall(CI, I->second);
3602 if (!I->first->use_empty())
3603 I->first->replaceAllUsesWith(I->second);
3604 I->first->eraseFromParent();
3607 std::vector<std::pair<Function*, Function*> >().swap(UpgradedIntrinsics);
3609 for (unsigned I = 0, E = InstsWithTBAATag.size(); I < E; I++)
3610 UpgradeInstWithTBAATag(InstsWithTBAATag[I]);
3612 UpgradeDebugInfo(*M);
3613 return std::error_code();
3616 std::vector<StructType *> BitcodeReader::getIdentifiedStructTypes() const {
3617 return IdentifiedStructTypes;
3620 std::error_code BitcodeReader::InitStream() {
3622 return InitLazyStream();
3623 return InitStreamFromBuffer();
3626 std::error_code BitcodeReader::InitStreamFromBuffer() {
3627 const unsigned char *BufPtr = (const unsigned char*)Buffer->getBufferStart();
3628 const unsigned char *BufEnd = BufPtr+Buffer->getBufferSize();
3630 if (Buffer->getBufferSize() & 3)
3631 return Error("Invalid bitcode signature");
3633 // If we have a wrapper header, parse it and ignore the non-bc file contents.
3634 // The magic number is 0x0B17C0DE stored in little endian.
3635 if (isBitcodeWrapper(BufPtr, BufEnd))
3636 if (SkipBitcodeWrapperHeader(BufPtr, BufEnd, true))
3637 return Error("Invalid bitcode wrapper header");
3639 StreamFile.reset(new BitstreamReader(BufPtr, BufEnd));
3640 Stream.init(&*StreamFile);
3642 return std::error_code();
3645 std::error_code BitcodeReader::InitLazyStream() {
3646 // Check and strip off the bitcode wrapper; BitstreamReader expects never to
3648 auto OwnedBytes = llvm::make_unique<StreamingMemoryObject>(LazyStreamer);
3649 StreamingMemoryObject &Bytes = *OwnedBytes;
3650 StreamFile = llvm::make_unique<BitstreamReader>(std::move(OwnedBytes));
3651 Stream.init(&*StreamFile);
3653 unsigned char buf[16];
3654 if (Bytes.readBytes(buf, 16, 0) != 16)
3655 return Error("Invalid bitcode signature");
3657 if (!isBitcode(buf, buf + 16))
3658 return Error("Invalid bitcode signature");
3660 if (isBitcodeWrapper(buf, buf + 4)) {
3661 const unsigned char *bitcodeStart = buf;
3662 const unsigned char *bitcodeEnd = buf + 16;
3663 SkipBitcodeWrapperHeader(bitcodeStart, bitcodeEnd, false);
3664 Bytes.dropLeadingBytes(bitcodeStart - buf);
3665 Bytes.setKnownObjectSize(bitcodeEnd - bitcodeStart);
3667 return std::error_code();
3671 class BitcodeErrorCategoryType : public std::error_category {
3672 const char *name() const LLVM_NOEXCEPT override {
3673 return "llvm.bitcode";
3675 std::string message(int IE) const override {
3676 BitcodeError E = static_cast<BitcodeError>(IE);
3678 case BitcodeError::InvalidBitcodeSignature:
3679 return "Invalid bitcode signature";
3680 case BitcodeError::CorruptedBitcode:
3681 return "Corrupted bitcode";
3683 llvm_unreachable("Unknown error type!");
3688 static ManagedStatic<BitcodeErrorCategoryType> ErrorCategory;
3690 const std::error_category &llvm::BitcodeErrorCategory() {
3691 return *ErrorCategory;
3694 //===----------------------------------------------------------------------===//
3695 // External interface
3696 //===----------------------------------------------------------------------===//
3698 /// \brief Get a lazy one-at-time loading module from bitcode.
3700 /// This isn't always used in a lazy context. In particular, it's also used by
3701 /// \a parseBitcodeFile(). If this is truly lazy, then we need to eagerly pull
3702 /// in forward-referenced functions from block address references.
3704 /// \param[in] WillMaterializeAll Set to \c true if the caller promises to
3705 /// materialize everything -- in particular, if this isn't truly lazy.
3706 static ErrorOr<Module *>
3707 getLazyBitcodeModuleImpl(std::unique_ptr<MemoryBuffer> &&Buffer,
3708 LLVMContext &Context, bool WillMaterializeAll,
3709 DiagnosticHandlerFunction DiagnosticHandler) {
3710 Module *M = new Module(Buffer->getBufferIdentifier(), Context);
3712 new BitcodeReader(Buffer.get(), Context, DiagnosticHandler);
3713 M->setMaterializer(R);
3715 auto cleanupOnError = [&](std::error_code EC) {
3716 R->releaseBuffer(); // Never take ownership on error.
3717 delete M; // Also deletes R.
3721 if (std::error_code EC = R->ParseBitcodeInto(M))
3722 return cleanupOnError(EC);
3724 if (!WillMaterializeAll)
3725 // Resolve forward references from blockaddresses.
3726 if (std::error_code EC = R->materializeForwardReferencedFunctions())
3727 return cleanupOnError(EC);
3729 Buffer.release(); // The BitcodeReader owns it now.
3734 llvm::getLazyBitcodeModule(std::unique_ptr<MemoryBuffer> &&Buffer,
3735 LLVMContext &Context,
3736 DiagnosticHandlerFunction DiagnosticHandler) {
3737 return getLazyBitcodeModuleImpl(std::move(Buffer), Context, false,
3741 ErrorOr<std::unique_ptr<Module>>
3742 llvm::getStreamedBitcodeModule(StringRef Name, DataStreamer *Streamer,
3743 LLVMContext &Context,
3744 DiagnosticHandlerFunction DiagnosticHandler) {
3745 std::unique_ptr<Module> M = make_unique<Module>(Name, Context);
3746 BitcodeReader *R = new BitcodeReader(Streamer, Context, DiagnosticHandler);
3747 M->setMaterializer(R);
3748 if (std::error_code EC = R->ParseBitcodeInto(M.get()))
3750 return std::move(M);
3754 llvm::parseBitcodeFile(MemoryBufferRef Buffer, LLVMContext &Context,
3755 DiagnosticHandlerFunction DiagnosticHandler) {
3756 std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
3757 ErrorOr<Module *> ModuleOrErr = getLazyBitcodeModuleImpl(
3758 std::move(Buf), Context, true, DiagnosticHandler);
3761 Module *M = ModuleOrErr.get();
3762 // Read in the entire module, and destroy the BitcodeReader.
3763 if (std::error_code EC = M->materializeAllPermanently()) {
3768 // TODO: Restore the use-lists to the in-memory state when the bitcode was
3769 // written. We must defer until the Module has been fully materialized.
3775 llvm::getBitcodeTargetTriple(MemoryBufferRef Buffer, LLVMContext &Context,
3776 DiagnosticHandlerFunction DiagnosticHandler) {
3777 std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
3778 auto R = llvm::make_unique<BitcodeReader>(Buf.release(), Context,
3780 ErrorOr<std::string> Triple = R->parseTriple();
3781 if (Triple.getError())
3783 return Triple.get();