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 "llvm/ADT/STLExtras.h"
12 #include "llvm/ADT/SmallString.h"
13 #include "llvm/ADT/SmallVector.h"
14 #include "llvm/ADT/Triple.h"
15 #include "llvm/Bitcode/BitstreamReader.h"
16 #include "llvm/Bitcode/LLVMBitCodes.h"
17 #include "llvm/IR/AutoUpgrade.h"
18 #include "llvm/IR/Constants.h"
19 #include "llvm/IR/DebugInfo.h"
20 #include "llvm/IR/DebugInfoMetadata.h"
21 #include "llvm/IR/DerivedTypes.h"
22 #include "llvm/IR/DiagnosticPrinter.h"
23 #include "llvm/IR/GVMaterializer.h"
24 #include "llvm/IR/InlineAsm.h"
25 #include "llvm/IR/IntrinsicInst.h"
26 #include "llvm/IR/LLVMContext.h"
27 #include "llvm/IR/Module.h"
28 #include "llvm/IR/OperandTraits.h"
29 #include "llvm/IR/Operator.h"
30 #include "llvm/IR/ValueHandle.h"
31 #include "llvm/Support/DataStream.h"
32 #include "llvm/Support/ManagedStatic.h"
33 #include "llvm/Support/MathExtras.h"
34 #include "llvm/Support/MemoryBuffer.h"
35 #include "llvm/Support/raw_ostream.h"
41 SWITCH_INST_MAGIC = 0x4B5 // May 2012 => 1205 => Hex
44 /// Indicates which operator an operand allows (for the few operands that may
45 /// only reference a certain operator).
46 enum OperatorConstraint {
47 OC_None = 0, // No constraint
48 OC_CatchPad, // Must be CatchPadInst
49 OC_CleanupPad // Must be CleanupPadInst
52 class BitcodeReaderValueList {
53 std::vector<WeakVH> ValuePtrs;
55 /// As we resolve forward-referenced constants, we add information about them
56 /// to this vector. This allows us to resolve them in bulk instead of
57 /// resolving each reference at a time. See the code in
58 /// ResolveConstantForwardRefs for more information about this.
60 /// The key of this vector is the placeholder constant, the value is the slot
61 /// number that holds the resolved value.
62 typedef std::vector<std::pair<Constant*, unsigned> > ResolveConstantsTy;
63 ResolveConstantsTy ResolveConstants;
66 BitcodeReaderValueList(LLVMContext &C) : Context(C) {}
67 ~BitcodeReaderValueList() {
68 assert(ResolveConstants.empty() && "Constants not resolved?");
71 // vector compatibility methods
72 unsigned size() const { return ValuePtrs.size(); }
73 void resize(unsigned N) { ValuePtrs.resize(N); }
74 void push_back(Value *V) { ValuePtrs.emplace_back(V); }
77 assert(ResolveConstants.empty() && "Constants not resolved?");
81 Value *operator[](unsigned i) const {
82 assert(i < ValuePtrs.size());
86 Value *back() const { return ValuePtrs.back(); }
87 void pop_back() { ValuePtrs.pop_back(); }
88 bool empty() const { return ValuePtrs.empty(); }
89 void shrinkTo(unsigned N) {
90 assert(N <= size() && "Invalid shrinkTo request!");
94 Constant *getConstantFwdRef(unsigned Idx, Type *Ty);
95 Value *getValueFwdRef(unsigned Idx, Type *Ty,
96 OperatorConstraint OC = OC_None);
98 bool assignValue(Value *V, unsigned Idx);
100 /// Once all constants are read, this method bulk resolves any forward
102 void resolveConstantForwardRefs();
105 class BitcodeReaderMDValueList {
110 std::vector<TrackingMDRef> MDValuePtrs;
112 LLVMContext &Context;
114 BitcodeReaderMDValueList(LLVMContext &C)
115 : NumFwdRefs(0), AnyFwdRefs(false), Context(C) {}
117 // vector compatibility methods
118 unsigned size() const { return MDValuePtrs.size(); }
119 void resize(unsigned N) { MDValuePtrs.resize(N); }
120 void push_back(Metadata *MD) { MDValuePtrs.emplace_back(MD); }
121 void clear() { MDValuePtrs.clear(); }
122 Metadata *back() const { return MDValuePtrs.back(); }
123 void pop_back() { MDValuePtrs.pop_back(); }
124 bool empty() const { return MDValuePtrs.empty(); }
126 Metadata *operator[](unsigned i) const {
127 assert(i < MDValuePtrs.size());
128 return MDValuePtrs[i];
131 void shrinkTo(unsigned N) {
132 assert(N <= size() && "Invalid shrinkTo request!");
133 MDValuePtrs.resize(N);
136 Metadata *getValueFwdRef(unsigned Idx);
137 void assignValue(Metadata *MD, unsigned Idx);
138 void tryToResolveCycles();
141 class BitcodeReader : public GVMaterializer {
142 LLVMContext &Context;
143 DiagnosticHandlerFunction DiagnosticHandler;
144 Module *TheModule = nullptr;
145 std::unique_ptr<MemoryBuffer> Buffer;
146 std::unique_ptr<BitstreamReader> StreamFile;
147 BitstreamCursor Stream;
148 uint64_t NextUnreadBit = 0;
149 bool SeenValueSymbolTable = false;
150 unsigned VSTOffset = 0;
152 std::vector<Type*> TypeList;
153 BitcodeReaderValueList ValueList;
154 BitcodeReaderMDValueList MDValueList;
155 std::vector<Comdat *> ComdatList;
156 SmallVector<Instruction *, 64> InstructionList;
158 std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInits;
159 std::vector<std::pair<GlobalAlias*, unsigned> > AliasInits;
160 std::vector<std::pair<Function*, unsigned> > FunctionPrefixes;
161 std::vector<std::pair<Function*, unsigned> > FunctionPrologues;
162 std::vector<std::pair<Function*, unsigned> > FunctionPersonalityFns;
164 SmallVector<Instruction*, 64> InstsWithTBAATag;
166 /// The set of attributes by index. Index zero in the file is for null, and
167 /// is thus not represented here. As such all indices are off by one.
168 std::vector<AttributeSet> MAttributes;
170 /// The set of attribute groups.
171 std::map<unsigned, AttributeSet> MAttributeGroups;
173 /// While parsing a function body, this is a list of the basic blocks for the
175 std::vector<BasicBlock*> FunctionBBs;
177 // When reading the module header, this list is populated with functions that
178 // have bodies later in the file.
179 std::vector<Function*> FunctionsWithBodies;
181 // When intrinsic functions are encountered which require upgrading they are
182 // stored here with their replacement function.
183 typedef DenseMap<Function*, Function*> UpgradedIntrinsicMap;
184 UpgradedIntrinsicMap UpgradedIntrinsics;
186 // Map the bitcode's custom MDKind ID to the Module's MDKind ID.
187 DenseMap<unsigned, unsigned> MDKindMap;
189 // Several operations happen after the module header has been read, but
190 // before function bodies are processed. This keeps track of whether
191 // we've done this yet.
192 bool SeenFirstFunctionBody = false;
194 /// When function bodies are initially scanned, this map contains info about
195 /// where to find deferred function body in the stream.
196 DenseMap<Function*, uint64_t> DeferredFunctionInfo;
198 /// When Metadata block is initially scanned when parsing the module, we may
199 /// choose to defer parsing of the metadata. This vector contains info about
200 /// which Metadata blocks are deferred.
201 std::vector<uint64_t> DeferredMetadataInfo;
203 /// These are basic blocks forward-referenced by block addresses. They are
204 /// inserted lazily into functions when they're loaded. The basic block ID is
205 /// its index into the vector.
206 DenseMap<Function *, std::vector<BasicBlock *>> BasicBlockFwdRefs;
207 std::deque<Function *> BasicBlockFwdRefQueue;
209 /// Indicates that we are using a new encoding for instruction operands where
210 /// most operands in the current FUNCTION_BLOCK are encoded relative to the
211 /// instruction number, for a more compact encoding. Some instruction
212 /// operands are not relative to the instruction ID: basic block numbers, and
213 /// types. Once the old style function blocks have been phased out, we would
214 /// not need this flag.
215 bool UseRelativeIDs = false;
217 /// True if all functions will be materialized, negating the need to process
218 /// (e.g.) blockaddress forward references.
219 bool WillMaterializeAllForwardRefs = false;
221 /// Functions that have block addresses taken. This is usually empty.
222 SmallPtrSet<const Function *, 4> BlockAddressesTaken;
224 /// True if any Metadata block has been materialized.
225 bool IsMetadataMaterialized = false;
227 bool StripDebugInfo = false;
230 std::error_code error(BitcodeError E, const Twine &Message);
231 std::error_code error(BitcodeError E);
232 std::error_code error(const Twine &Message);
234 BitcodeReader(MemoryBuffer *Buffer, LLVMContext &Context,
235 DiagnosticHandlerFunction DiagnosticHandler);
236 BitcodeReader(LLVMContext &Context,
237 DiagnosticHandlerFunction DiagnosticHandler);
238 ~BitcodeReader() override { freeState(); }
240 std::error_code materializeForwardReferencedFunctions();
244 void releaseBuffer();
246 bool isDematerializable(const GlobalValue *GV) const override;
247 std::error_code materialize(GlobalValue *GV) override;
248 std::error_code materializeModule(Module *M) override;
249 std::vector<StructType *> getIdentifiedStructTypes() const override;
250 void dematerialize(GlobalValue *GV) override;
252 /// \brief Main interface to parsing a bitcode buffer.
253 /// \returns true if an error occurred.
254 std::error_code parseBitcodeInto(std::unique_ptr<DataStreamer> Streamer,
256 bool ShouldLazyLoadMetadata = false);
258 /// \brief Cheap mechanism to just extract module triple
259 /// \returns true if an error occurred.
260 ErrorOr<std::string> parseTriple();
262 static uint64_t decodeSignRotatedValue(uint64_t V);
264 /// Materialize any deferred Metadata block.
265 std::error_code materializeMetadata() override;
267 void setStripDebugInfo() override;
270 std::vector<StructType *> IdentifiedStructTypes;
271 StructType *createIdentifiedStructType(LLVMContext &Context, StringRef Name);
272 StructType *createIdentifiedStructType(LLVMContext &Context);
274 Type *getTypeByID(unsigned ID);
275 Value *getFnValueByID(unsigned ID, Type *Ty,
276 OperatorConstraint OC = OC_None) {
277 if (Ty && Ty->isMetadataTy())
278 return MetadataAsValue::get(Ty->getContext(), getFnMetadataByID(ID));
279 return ValueList.getValueFwdRef(ID, Ty, OC);
281 Metadata *getFnMetadataByID(unsigned ID) {
282 return MDValueList.getValueFwdRef(ID);
284 BasicBlock *getBasicBlock(unsigned ID) const {
285 if (ID >= FunctionBBs.size()) return nullptr; // Invalid ID
286 return FunctionBBs[ID];
288 AttributeSet getAttributes(unsigned i) const {
289 if (i-1 < MAttributes.size())
290 return MAttributes[i-1];
291 return AttributeSet();
294 /// Read a value/type pair out of the specified record from slot 'Slot'.
295 /// Increment Slot past the number of slots used in the record. Return true on
297 bool getValueTypePair(SmallVectorImpl<uint64_t> &Record, unsigned &Slot,
298 unsigned InstNum, Value *&ResVal) {
299 if (Slot == Record.size()) return true;
300 unsigned ValNo = (unsigned)Record[Slot++];
301 // Adjust the ValNo, if it was encoded relative to the InstNum.
303 ValNo = InstNum - ValNo;
304 if (ValNo < InstNum) {
305 // If this is not a forward reference, just return the value we already
307 ResVal = getFnValueByID(ValNo, nullptr);
308 return ResVal == nullptr;
310 if (Slot == Record.size())
313 unsigned TypeNo = (unsigned)Record[Slot++];
314 ResVal = getFnValueByID(ValNo, getTypeByID(TypeNo));
315 return ResVal == nullptr;
318 /// Read a value out of the specified record from slot 'Slot'. Increment Slot
319 /// past the number of slots used by the value in the record. Return true if
320 /// there is an error.
321 bool popValue(SmallVectorImpl<uint64_t> &Record, unsigned &Slot,
322 unsigned InstNum, Type *Ty, Value *&ResVal,
323 OperatorConstraint OC = OC_None) {
324 if (getValue(Record, Slot, InstNum, Ty, ResVal, OC))
326 // All values currently take a single record slot.
331 /// Like popValue, but does not increment the Slot number.
332 bool getValue(SmallVectorImpl<uint64_t> &Record, unsigned Slot,
333 unsigned InstNum, Type *Ty, Value *&ResVal,
334 OperatorConstraint OC = OC_None) {
335 ResVal = getValue(Record, Slot, InstNum, Ty, OC);
336 return ResVal == nullptr;
339 /// Version of getValue that returns ResVal directly, or 0 if there is an
341 Value *getValue(SmallVectorImpl<uint64_t> &Record, unsigned Slot,
342 unsigned InstNum, Type *Ty, OperatorConstraint OC = OC_None) {
343 if (Slot == Record.size()) return nullptr;
344 unsigned ValNo = (unsigned)Record[Slot];
345 // Adjust the ValNo, if it was encoded relative to the InstNum.
347 ValNo = InstNum - ValNo;
348 return getFnValueByID(ValNo, Ty, OC);
351 /// Like getValue, but decodes signed VBRs.
352 Value *getValueSigned(SmallVectorImpl<uint64_t> &Record, unsigned Slot,
353 unsigned InstNum, Type *Ty,
354 OperatorConstraint OC = OC_None) {
355 if (Slot == Record.size()) return nullptr;
356 unsigned ValNo = (unsigned)decodeSignRotatedValue(Record[Slot]);
357 // Adjust the ValNo, if it was encoded relative to the InstNum.
359 ValNo = InstNum - ValNo;
360 return getFnValueByID(ValNo, Ty, OC);
363 /// Converts alignment exponent (i.e. power of two (or zero)) to the
364 /// corresponding alignment to use. If alignment is too large, returns
365 /// a corresponding error code.
366 std::error_code parseAlignmentValue(uint64_t Exponent, unsigned &Alignment);
367 std::error_code parseAttrKind(uint64_t Code, Attribute::AttrKind *Kind);
368 std::error_code parseModule(bool Resume, bool ShouldLazyLoadMetadata = false);
369 std::error_code parseAttributeBlock();
370 std::error_code parseAttributeGroupBlock();
371 std::error_code parseTypeTable();
372 std::error_code parseTypeTableBody();
374 ErrorOr<Value *> recordValue(SmallVectorImpl<uint64_t> &Record,
375 unsigned NameIndex, Triple &TT);
376 std::error_code parseValueSymbolTable(unsigned Offset = 0);
377 std::error_code parseConstants();
378 std::error_code rememberAndSkipFunctionBody();
379 /// Save the positions of the Metadata blocks and skip parsing the blocks.
380 std::error_code rememberAndSkipMetadata();
381 std::error_code parseFunctionBody(Function *F);
382 std::error_code globalCleanup();
383 std::error_code resolveGlobalAndAliasInits();
384 std::error_code parseMetadata();
385 std::error_code parseMetadataAttachment(Function &F);
386 ErrorOr<std::string> parseModuleTriple();
387 std::error_code parseUseLists();
388 std::error_code initStream(std::unique_ptr<DataStreamer> Streamer);
389 std::error_code initStreamFromBuffer();
390 std::error_code initLazyStream(std::unique_ptr<DataStreamer> Streamer);
391 std::error_code findFunctionInStream(
393 DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator);
397 BitcodeDiagnosticInfo::BitcodeDiagnosticInfo(std::error_code EC,
398 DiagnosticSeverity Severity,
400 : DiagnosticInfo(DK_Bitcode, Severity), Msg(Msg), EC(EC) {}
402 void BitcodeDiagnosticInfo::print(DiagnosticPrinter &DP) const { DP << Msg; }
404 static std::error_code error(DiagnosticHandlerFunction DiagnosticHandler,
405 std::error_code EC, const Twine &Message) {
406 BitcodeDiagnosticInfo DI(EC, DS_Error, Message);
407 DiagnosticHandler(DI);
411 static std::error_code error(DiagnosticHandlerFunction DiagnosticHandler,
412 std::error_code EC) {
413 return error(DiagnosticHandler, EC, EC.message());
416 static std::error_code error(DiagnosticHandlerFunction DiagnosticHandler,
417 const Twine &Message) {
418 return error(DiagnosticHandler,
419 make_error_code(BitcodeError::CorruptedBitcode), Message);
422 std::error_code BitcodeReader::error(BitcodeError E, const Twine &Message) {
423 return ::error(DiagnosticHandler, make_error_code(E), Message);
426 std::error_code BitcodeReader::error(const Twine &Message) {
427 return ::error(DiagnosticHandler,
428 make_error_code(BitcodeError::CorruptedBitcode), Message);
431 std::error_code BitcodeReader::error(BitcodeError E) {
432 return ::error(DiagnosticHandler, make_error_code(E));
435 static DiagnosticHandlerFunction getDiagHandler(DiagnosticHandlerFunction F,
439 return [&C](const DiagnosticInfo &DI) { C.diagnose(DI); };
442 BitcodeReader::BitcodeReader(MemoryBuffer *Buffer, LLVMContext &Context,
443 DiagnosticHandlerFunction DiagnosticHandler)
445 DiagnosticHandler(getDiagHandler(DiagnosticHandler, Context)),
446 Buffer(Buffer), ValueList(Context), MDValueList(Context) {}
448 BitcodeReader::BitcodeReader(LLVMContext &Context,
449 DiagnosticHandlerFunction DiagnosticHandler)
451 DiagnosticHandler(getDiagHandler(DiagnosticHandler, Context)),
452 Buffer(nullptr), ValueList(Context), MDValueList(Context) {}
454 std::error_code BitcodeReader::materializeForwardReferencedFunctions() {
455 if (WillMaterializeAllForwardRefs)
456 return std::error_code();
458 // Prevent recursion.
459 WillMaterializeAllForwardRefs = true;
461 while (!BasicBlockFwdRefQueue.empty()) {
462 Function *F = BasicBlockFwdRefQueue.front();
463 BasicBlockFwdRefQueue.pop_front();
464 assert(F && "Expected valid function");
465 if (!BasicBlockFwdRefs.count(F))
466 // Already materialized.
469 // Check for a function that isn't materializable to prevent an infinite
470 // loop. When parsing a blockaddress stored in a global variable, there
471 // isn't a trivial way to check if a function will have a body without a
472 // linear search through FunctionsWithBodies, so just check it here.
473 if (!F->isMaterializable())
474 return error("Never resolved function from blockaddress");
476 // Try to materialize F.
477 if (std::error_code EC = materialize(F))
480 assert(BasicBlockFwdRefs.empty() && "Function missing from queue");
483 WillMaterializeAllForwardRefs = false;
484 return std::error_code();
487 void BitcodeReader::freeState() {
489 std::vector<Type*>().swap(TypeList);
492 std::vector<Comdat *>().swap(ComdatList);
494 std::vector<AttributeSet>().swap(MAttributes);
495 std::vector<BasicBlock*>().swap(FunctionBBs);
496 std::vector<Function*>().swap(FunctionsWithBodies);
497 DeferredFunctionInfo.clear();
498 DeferredMetadataInfo.clear();
501 assert(BasicBlockFwdRefs.empty() && "Unresolved blockaddress fwd references");
502 BasicBlockFwdRefQueue.clear();
505 //===----------------------------------------------------------------------===//
506 // Helper functions to implement forward reference resolution, etc.
507 //===----------------------------------------------------------------------===//
509 /// Convert a string from a record into an std::string, return true on failure.
510 template <typename StrTy>
511 static bool convertToString(ArrayRef<uint64_t> Record, unsigned Idx,
513 if (Idx > Record.size())
516 for (unsigned i = Idx, e = Record.size(); i != e; ++i)
517 Result += (char)Record[i];
521 static bool hasImplicitComdat(size_t Val) {
525 case 1: // Old WeakAnyLinkage
526 case 4: // Old LinkOnceAnyLinkage
527 case 10: // Old WeakODRLinkage
528 case 11: // Old LinkOnceODRLinkage
533 static GlobalValue::LinkageTypes getDecodedLinkage(unsigned Val) {
535 default: // Map unknown/new linkages to external
537 return GlobalValue::ExternalLinkage;
539 return GlobalValue::AppendingLinkage;
541 return GlobalValue::InternalLinkage;
543 return GlobalValue::ExternalLinkage; // Obsolete DLLImportLinkage
545 return GlobalValue::ExternalLinkage; // Obsolete DLLExportLinkage
547 return GlobalValue::ExternalWeakLinkage;
549 return GlobalValue::CommonLinkage;
551 return GlobalValue::PrivateLinkage;
553 return GlobalValue::AvailableExternallyLinkage;
555 return GlobalValue::PrivateLinkage; // Obsolete LinkerPrivateLinkage
557 return GlobalValue::PrivateLinkage; // Obsolete LinkerPrivateWeakLinkage
559 return GlobalValue::ExternalLinkage; // Obsolete LinkOnceODRAutoHideLinkage
560 case 1: // Old value with implicit comdat.
562 return GlobalValue::WeakAnyLinkage;
563 case 10: // Old value with implicit comdat.
565 return GlobalValue::WeakODRLinkage;
566 case 4: // Old value with implicit comdat.
568 return GlobalValue::LinkOnceAnyLinkage;
569 case 11: // Old value with implicit comdat.
571 return GlobalValue::LinkOnceODRLinkage;
575 static GlobalValue::VisibilityTypes getDecodedVisibility(unsigned Val) {
577 default: // Map unknown visibilities to default.
578 case 0: return GlobalValue::DefaultVisibility;
579 case 1: return GlobalValue::HiddenVisibility;
580 case 2: return GlobalValue::ProtectedVisibility;
584 static GlobalValue::DLLStorageClassTypes
585 getDecodedDLLStorageClass(unsigned Val) {
587 default: // Map unknown values to default.
588 case 0: return GlobalValue::DefaultStorageClass;
589 case 1: return GlobalValue::DLLImportStorageClass;
590 case 2: return GlobalValue::DLLExportStorageClass;
594 static GlobalVariable::ThreadLocalMode getDecodedThreadLocalMode(unsigned Val) {
596 case 0: return GlobalVariable::NotThreadLocal;
597 default: // Map unknown non-zero value to general dynamic.
598 case 1: return GlobalVariable::GeneralDynamicTLSModel;
599 case 2: return GlobalVariable::LocalDynamicTLSModel;
600 case 3: return GlobalVariable::InitialExecTLSModel;
601 case 4: return GlobalVariable::LocalExecTLSModel;
605 static int getDecodedCastOpcode(unsigned Val) {
608 case bitc::CAST_TRUNC : return Instruction::Trunc;
609 case bitc::CAST_ZEXT : return Instruction::ZExt;
610 case bitc::CAST_SEXT : return Instruction::SExt;
611 case bitc::CAST_FPTOUI : return Instruction::FPToUI;
612 case bitc::CAST_FPTOSI : return Instruction::FPToSI;
613 case bitc::CAST_UITOFP : return Instruction::UIToFP;
614 case bitc::CAST_SITOFP : return Instruction::SIToFP;
615 case bitc::CAST_FPTRUNC : return Instruction::FPTrunc;
616 case bitc::CAST_FPEXT : return Instruction::FPExt;
617 case bitc::CAST_PTRTOINT: return Instruction::PtrToInt;
618 case bitc::CAST_INTTOPTR: return Instruction::IntToPtr;
619 case bitc::CAST_BITCAST : return Instruction::BitCast;
620 case bitc::CAST_ADDRSPACECAST: return Instruction::AddrSpaceCast;
624 static int getDecodedBinaryOpcode(unsigned Val, Type *Ty) {
625 bool IsFP = Ty->isFPOrFPVectorTy();
626 // BinOps are only valid for int/fp or vector of int/fp types
627 if (!IsFP && !Ty->isIntOrIntVectorTy())
633 case bitc::BINOP_ADD:
634 return IsFP ? Instruction::FAdd : Instruction::Add;
635 case bitc::BINOP_SUB:
636 return IsFP ? Instruction::FSub : Instruction::Sub;
637 case bitc::BINOP_MUL:
638 return IsFP ? Instruction::FMul : Instruction::Mul;
639 case bitc::BINOP_UDIV:
640 return IsFP ? -1 : Instruction::UDiv;
641 case bitc::BINOP_SDIV:
642 return IsFP ? Instruction::FDiv : Instruction::SDiv;
643 case bitc::BINOP_UREM:
644 return IsFP ? -1 : Instruction::URem;
645 case bitc::BINOP_SREM:
646 return IsFP ? Instruction::FRem : Instruction::SRem;
647 case bitc::BINOP_SHL:
648 return IsFP ? -1 : Instruction::Shl;
649 case bitc::BINOP_LSHR:
650 return IsFP ? -1 : Instruction::LShr;
651 case bitc::BINOP_ASHR:
652 return IsFP ? -1 : Instruction::AShr;
653 case bitc::BINOP_AND:
654 return IsFP ? -1 : Instruction::And;
656 return IsFP ? -1 : Instruction::Or;
657 case bitc::BINOP_XOR:
658 return IsFP ? -1 : Instruction::Xor;
662 static AtomicRMWInst::BinOp getDecodedRMWOperation(unsigned Val) {
664 default: return AtomicRMWInst::BAD_BINOP;
665 case bitc::RMW_XCHG: return AtomicRMWInst::Xchg;
666 case bitc::RMW_ADD: return AtomicRMWInst::Add;
667 case bitc::RMW_SUB: return AtomicRMWInst::Sub;
668 case bitc::RMW_AND: return AtomicRMWInst::And;
669 case bitc::RMW_NAND: return AtomicRMWInst::Nand;
670 case bitc::RMW_OR: return AtomicRMWInst::Or;
671 case bitc::RMW_XOR: return AtomicRMWInst::Xor;
672 case bitc::RMW_MAX: return AtomicRMWInst::Max;
673 case bitc::RMW_MIN: return AtomicRMWInst::Min;
674 case bitc::RMW_UMAX: return AtomicRMWInst::UMax;
675 case bitc::RMW_UMIN: return AtomicRMWInst::UMin;
679 static AtomicOrdering getDecodedOrdering(unsigned Val) {
681 case bitc::ORDERING_NOTATOMIC: return NotAtomic;
682 case bitc::ORDERING_UNORDERED: return Unordered;
683 case bitc::ORDERING_MONOTONIC: return Monotonic;
684 case bitc::ORDERING_ACQUIRE: return Acquire;
685 case bitc::ORDERING_RELEASE: return Release;
686 case bitc::ORDERING_ACQREL: return AcquireRelease;
687 default: // Map unknown orderings to sequentially-consistent.
688 case bitc::ORDERING_SEQCST: return SequentiallyConsistent;
692 static SynchronizationScope getDecodedSynchScope(unsigned Val) {
694 case bitc::SYNCHSCOPE_SINGLETHREAD: return SingleThread;
695 default: // Map unknown scopes to cross-thread.
696 case bitc::SYNCHSCOPE_CROSSTHREAD: return CrossThread;
700 static Comdat::SelectionKind getDecodedComdatSelectionKind(unsigned Val) {
702 default: // Map unknown selection kinds to any.
703 case bitc::COMDAT_SELECTION_KIND_ANY:
705 case bitc::COMDAT_SELECTION_KIND_EXACT_MATCH:
706 return Comdat::ExactMatch;
707 case bitc::COMDAT_SELECTION_KIND_LARGEST:
708 return Comdat::Largest;
709 case bitc::COMDAT_SELECTION_KIND_NO_DUPLICATES:
710 return Comdat::NoDuplicates;
711 case bitc::COMDAT_SELECTION_KIND_SAME_SIZE:
712 return Comdat::SameSize;
716 static FastMathFlags getDecodedFastMathFlags(unsigned Val) {
718 if (0 != (Val & FastMathFlags::UnsafeAlgebra))
719 FMF.setUnsafeAlgebra();
720 if (0 != (Val & FastMathFlags::NoNaNs))
722 if (0 != (Val & FastMathFlags::NoInfs))
724 if (0 != (Val & FastMathFlags::NoSignedZeros))
725 FMF.setNoSignedZeros();
726 if (0 != (Val & FastMathFlags::AllowReciprocal))
727 FMF.setAllowReciprocal();
731 static void upgradeDLLImportExportLinkage(llvm::GlobalValue *GV, unsigned Val) {
733 case 5: GV->setDLLStorageClass(GlobalValue::DLLImportStorageClass); break;
734 case 6: GV->setDLLStorageClass(GlobalValue::DLLExportStorageClass); break;
740 /// \brief A class for maintaining the slot number definition
741 /// as a placeholder for the actual definition for forward constants defs.
742 class ConstantPlaceHolder : public ConstantExpr {
743 void operator=(const ConstantPlaceHolder &) = delete;
746 // allocate space for exactly one operand
747 void *operator new(size_t s) { return User::operator new(s, 1); }
748 explicit ConstantPlaceHolder(Type *Ty, LLVMContext &Context)
749 : ConstantExpr(Ty, Instruction::UserOp1, &Op<0>(), 1) {
750 Op<0>() = UndefValue::get(Type::getInt32Ty(Context));
753 /// \brief Methods to support type inquiry through isa, cast, and dyn_cast.
754 static bool classof(const Value *V) {
755 return isa<ConstantExpr>(V) &&
756 cast<ConstantExpr>(V)->getOpcode() == Instruction::UserOp1;
759 /// Provide fast operand accessors
760 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
764 // FIXME: can we inherit this from ConstantExpr?
766 struct OperandTraits<ConstantPlaceHolder> :
767 public FixedNumOperandTraits<ConstantPlaceHolder, 1> {
769 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ConstantPlaceHolder, Value)
772 bool BitcodeReaderValueList::assignValue(Value *V, unsigned Idx) {
781 WeakVH &OldV = ValuePtrs[Idx];
787 // Handle constants and non-constants (e.g. instrs) differently for
789 if (Constant *PHC = dyn_cast<Constant>(&*OldV)) {
790 ResolveConstants.push_back(std::make_pair(PHC, Idx));
793 // If there was a forward reference to this value, replace it.
794 Value *PrevVal = OldV;
795 // Check operator constraints. We only put cleanuppads or catchpads in
796 // the forward value map if the value is constrained to match.
797 if (CatchPadInst *CatchPad = dyn_cast<CatchPadInst>(PrevVal)) {
798 if (!isa<CatchPadInst>(V))
800 // Delete the dummy basic block that was created with the sentinel
802 BasicBlock *DummyBlock = CatchPad->getUnwindDest();
803 assert(DummyBlock == CatchPad->getNormalDest());
804 CatchPad->dropAllReferences();
806 } else if (isa<CleanupPadInst>(PrevVal)) {
807 if (!isa<CleanupPadInst>(V))
810 OldV->replaceAllUsesWith(V);
818 Constant *BitcodeReaderValueList::getConstantFwdRef(unsigned Idx,
823 if (Value *V = ValuePtrs[Idx]) {
824 if (Ty != V->getType())
825 report_fatal_error("Type mismatch in constant table!");
826 return cast<Constant>(V);
829 // Create and return a placeholder, which will later be RAUW'd.
830 Constant *C = new ConstantPlaceHolder(Ty, Context);
835 Value *BitcodeReaderValueList::getValueFwdRef(unsigned Idx, Type *Ty,
836 OperatorConstraint OC) {
837 // Bail out for a clearly invalid value. This would make us call resize(0)
844 if (Value *V = ValuePtrs[Idx]) {
845 // If the types don't match, it's invalid.
846 if (Ty && Ty != V->getType())
850 // Use dyn_cast to enforce operator constraints
853 return dyn_cast<CatchPadInst>(V);
855 return dyn_cast<CleanupPadInst>(V);
857 llvm_unreachable("Unexpected operator constraint");
861 // No type specified, must be invalid reference.
862 if (!Ty) return nullptr;
864 // Create and return a placeholder, which will later be RAUW'd.
868 V = new Argument(Ty);
871 BasicBlock *BB = BasicBlock::Create(Context);
872 V = CatchPadInst::Create(BB, BB, {});
876 assert(OC == OC_CleanupPad && "unexpected operator constraint");
877 V = CleanupPadInst::Create(Context, {});
885 /// Once all constants are read, this method bulk resolves any forward
886 /// references. The idea behind this is that we sometimes get constants (such
887 /// as large arrays) which reference *many* forward ref constants. Replacing
888 /// each of these causes a lot of thrashing when building/reuniquing the
889 /// constant. Instead of doing this, we look at all the uses and rewrite all
890 /// the place holders at once for any constant that uses a placeholder.
891 void BitcodeReaderValueList::resolveConstantForwardRefs() {
892 // Sort the values by-pointer so that they are efficient to look up with a
894 std::sort(ResolveConstants.begin(), ResolveConstants.end());
896 SmallVector<Constant*, 64> NewOps;
898 while (!ResolveConstants.empty()) {
899 Value *RealVal = operator[](ResolveConstants.back().second);
900 Constant *Placeholder = ResolveConstants.back().first;
901 ResolveConstants.pop_back();
903 // Loop over all users of the placeholder, updating them to reference the
904 // new value. If they reference more than one placeholder, update them all
906 while (!Placeholder->use_empty()) {
907 auto UI = Placeholder->user_begin();
910 // If the using object isn't uniqued, just update the operands. This
911 // handles instructions and initializers for global variables.
912 if (!isa<Constant>(U) || isa<GlobalValue>(U)) {
913 UI.getUse().set(RealVal);
917 // Otherwise, we have a constant that uses the placeholder. Replace that
918 // constant with a new constant that has *all* placeholder uses updated.
919 Constant *UserC = cast<Constant>(U);
920 for (User::op_iterator I = UserC->op_begin(), E = UserC->op_end();
923 if (!isa<ConstantPlaceHolder>(*I)) {
924 // Not a placeholder reference.
926 } else if (*I == Placeholder) {
927 // Common case is that it just references this one placeholder.
930 // Otherwise, look up the placeholder in ResolveConstants.
931 ResolveConstantsTy::iterator It =
932 std::lower_bound(ResolveConstants.begin(), ResolveConstants.end(),
933 std::pair<Constant*, unsigned>(cast<Constant>(*I),
935 assert(It != ResolveConstants.end() && It->first == *I);
936 NewOp = operator[](It->second);
939 NewOps.push_back(cast<Constant>(NewOp));
942 // Make the new constant.
944 if (ConstantArray *UserCA = dyn_cast<ConstantArray>(UserC)) {
945 NewC = ConstantArray::get(UserCA->getType(), NewOps);
946 } else if (ConstantStruct *UserCS = dyn_cast<ConstantStruct>(UserC)) {
947 NewC = ConstantStruct::get(UserCS->getType(), NewOps);
948 } else if (isa<ConstantVector>(UserC)) {
949 NewC = ConstantVector::get(NewOps);
951 assert(isa<ConstantExpr>(UserC) && "Must be a ConstantExpr.");
952 NewC = cast<ConstantExpr>(UserC)->getWithOperands(NewOps);
955 UserC->replaceAllUsesWith(NewC);
956 UserC->destroyConstant();
960 // Update all ValueHandles, they should be the only users at this point.
961 Placeholder->replaceAllUsesWith(RealVal);
966 void BitcodeReaderMDValueList::assignValue(Metadata *MD, unsigned Idx) {
975 TrackingMDRef &OldMD = MDValuePtrs[Idx];
981 // If there was a forward reference to this value, replace it.
982 TempMDTuple PrevMD(cast<MDTuple>(OldMD.get()));
983 PrevMD->replaceAllUsesWith(MD);
987 Metadata *BitcodeReaderMDValueList::getValueFwdRef(unsigned Idx) {
991 if (Metadata *MD = MDValuePtrs[Idx])
994 // Track forward refs to be resolved later.
996 MinFwdRef = std::min(MinFwdRef, Idx);
997 MaxFwdRef = std::max(MaxFwdRef, Idx);
1000 MinFwdRef = MaxFwdRef = Idx;
1004 // Create and return a placeholder, which will later be RAUW'd.
1005 Metadata *MD = MDNode::getTemporary(Context, None).release();
1006 MDValuePtrs[Idx].reset(MD);
1010 void BitcodeReaderMDValueList::tryToResolveCycles() {
1016 // Still forward references... can't resolve cycles.
1019 // Resolve any cycles.
1020 for (unsigned I = MinFwdRef, E = MaxFwdRef + 1; I != E; ++I) {
1021 auto &MD = MDValuePtrs[I];
1022 auto *N = dyn_cast_or_null<MDNode>(MD);
1026 assert(!N->isTemporary() && "Unexpected forward reference");
1030 // Make sure we return early again until there's another forward ref.
1034 Type *BitcodeReader::getTypeByID(unsigned ID) {
1035 // The type table size is always specified correctly.
1036 if (ID >= TypeList.size())
1039 if (Type *Ty = TypeList[ID])
1042 // If we have a forward reference, the only possible case is when it is to a
1043 // named struct. Just create a placeholder for now.
1044 return TypeList[ID] = createIdentifiedStructType(Context);
1047 StructType *BitcodeReader::createIdentifiedStructType(LLVMContext &Context,
1049 auto *Ret = StructType::create(Context, Name);
1050 IdentifiedStructTypes.push_back(Ret);
1054 StructType *BitcodeReader::createIdentifiedStructType(LLVMContext &Context) {
1055 auto *Ret = StructType::create(Context);
1056 IdentifiedStructTypes.push_back(Ret);
1061 //===----------------------------------------------------------------------===//
1062 // Functions for parsing blocks from the bitcode file
1063 //===----------------------------------------------------------------------===//
1066 /// \brief This fills an AttrBuilder object with the LLVM attributes that have
1067 /// been decoded from the given integer. This function must stay in sync with
1068 /// 'encodeLLVMAttributesForBitcode'.
1069 static void decodeLLVMAttributesForBitcode(AttrBuilder &B,
1070 uint64_t EncodedAttrs) {
1071 // FIXME: Remove in 4.0.
1073 // The alignment is stored as a 16-bit raw value from bits 31--16. We shift
1074 // the bits above 31 down by 11 bits.
1075 unsigned Alignment = (EncodedAttrs & (0xffffULL << 16)) >> 16;
1076 assert((!Alignment || isPowerOf2_32(Alignment)) &&
1077 "Alignment must be a power of two.");
1080 B.addAlignmentAttr(Alignment);
1081 B.addRawValue(((EncodedAttrs & (0xfffffULL << 32)) >> 11) |
1082 (EncodedAttrs & 0xffff));
1085 std::error_code BitcodeReader::parseAttributeBlock() {
1086 if (Stream.EnterSubBlock(bitc::PARAMATTR_BLOCK_ID))
1087 return error("Invalid record");
1089 if (!MAttributes.empty())
1090 return error("Invalid multiple blocks");
1092 SmallVector<uint64_t, 64> Record;
1094 SmallVector<AttributeSet, 8> Attrs;
1096 // Read all the records.
1098 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1100 switch (Entry.Kind) {
1101 case BitstreamEntry::SubBlock: // Handled for us already.
1102 case BitstreamEntry::Error:
1103 return error("Malformed block");
1104 case BitstreamEntry::EndBlock:
1105 return std::error_code();
1106 case BitstreamEntry::Record:
1107 // The interesting case.
1113 switch (Stream.readRecord(Entry.ID, Record)) {
1114 default: // Default behavior: ignore.
1116 case bitc::PARAMATTR_CODE_ENTRY_OLD: { // ENTRY: [paramidx0, attr0, ...]
1117 // FIXME: Remove in 4.0.
1118 if (Record.size() & 1)
1119 return error("Invalid record");
1121 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
1123 decodeLLVMAttributesForBitcode(B, Record[i+1]);
1124 Attrs.push_back(AttributeSet::get(Context, Record[i], B));
1127 MAttributes.push_back(AttributeSet::get(Context, Attrs));
1131 case bitc::PARAMATTR_CODE_ENTRY: { // ENTRY: [attrgrp0, attrgrp1, ...]
1132 for (unsigned i = 0, e = Record.size(); i != e; ++i)
1133 Attrs.push_back(MAttributeGroups[Record[i]]);
1135 MAttributes.push_back(AttributeSet::get(Context, Attrs));
1143 // Returns Attribute::None on unrecognized codes.
1144 static Attribute::AttrKind getAttrFromCode(uint64_t Code) {
1147 return Attribute::None;
1148 case bitc::ATTR_KIND_ALIGNMENT:
1149 return Attribute::Alignment;
1150 case bitc::ATTR_KIND_ALWAYS_INLINE:
1151 return Attribute::AlwaysInline;
1152 case bitc::ATTR_KIND_ARGMEMONLY:
1153 return Attribute::ArgMemOnly;
1154 case bitc::ATTR_KIND_BUILTIN:
1155 return Attribute::Builtin;
1156 case bitc::ATTR_KIND_BY_VAL:
1157 return Attribute::ByVal;
1158 case bitc::ATTR_KIND_IN_ALLOCA:
1159 return Attribute::InAlloca;
1160 case bitc::ATTR_KIND_COLD:
1161 return Attribute::Cold;
1162 case bitc::ATTR_KIND_CONVERGENT:
1163 return Attribute::Convergent;
1164 case bitc::ATTR_KIND_INLINE_HINT:
1165 return Attribute::InlineHint;
1166 case bitc::ATTR_KIND_IN_REG:
1167 return Attribute::InReg;
1168 case bitc::ATTR_KIND_JUMP_TABLE:
1169 return Attribute::JumpTable;
1170 case bitc::ATTR_KIND_MIN_SIZE:
1171 return Attribute::MinSize;
1172 case bitc::ATTR_KIND_NAKED:
1173 return Attribute::Naked;
1174 case bitc::ATTR_KIND_NEST:
1175 return Attribute::Nest;
1176 case bitc::ATTR_KIND_NO_ALIAS:
1177 return Attribute::NoAlias;
1178 case bitc::ATTR_KIND_NO_BUILTIN:
1179 return Attribute::NoBuiltin;
1180 case bitc::ATTR_KIND_NO_CAPTURE:
1181 return Attribute::NoCapture;
1182 case bitc::ATTR_KIND_NO_DUPLICATE:
1183 return Attribute::NoDuplicate;
1184 case bitc::ATTR_KIND_NO_IMPLICIT_FLOAT:
1185 return Attribute::NoImplicitFloat;
1186 case bitc::ATTR_KIND_NO_INLINE:
1187 return Attribute::NoInline;
1188 case bitc::ATTR_KIND_NON_LAZY_BIND:
1189 return Attribute::NonLazyBind;
1190 case bitc::ATTR_KIND_NON_NULL:
1191 return Attribute::NonNull;
1192 case bitc::ATTR_KIND_DEREFERENCEABLE:
1193 return Attribute::Dereferenceable;
1194 case bitc::ATTR_KIND_DEREFERENCEABLE_OR_NULL:
1195 return Attribute::DereferenceableOrNull;
1196 case bitc::ATTR_KIND_NO_RED_ZONE:
1197 return Attribute::NoRedZone;
1198 case bitc::ATTR_KIND_NO_RETURN:
1199 return Attribute::NoReturn;
1200 case bitc::ATTR_KIND_NO_UNWIND:
1201 return Attribute::NoUnwind;
1202 case bitc::ATTR_KIND_OPTIMIZE_FOR_SIZE:
1203 return Attribute::OptimizeForSize;
1204 case bitc::ATTR_KIND_OPTIMIZE_NONE:
1205 return Attribute::OptimizeNone;
1206 case bitc::ATTR_KIND_READ_NONE:
1207 return Attribute::ReadNone;
1208 case bitc::ATTR_KIND_READ_ONLY:
1209 return Attribute::ReadOnly;
1210 case bitc::ATTR_KIND_RETURNED:
1211 return Attribute::Returned;
1212 case bitc::ATTR_KIND_RETURNS_TWICE:
1213 return Attribute::ReturnsTwice;
1214 case bitc::ATTR_KIND_S_EXT:
1215 return Attribute::SExt;
1216 case bitc::ATTR_KIND_STACK_ALIGNMENT:
1217 return Attribute::StackAlignment;
1218 case bitc::ATTR_KIND_STACK_PROTECT:
1219 return Attribute::StackProtect;
1220 case bitc::ATTR_KIND_STACK_PROTECT_REQ:
1221 return Attribute::StackProtectReq;
1222 case bitc::ATTR_KIND_STACK_PROTECT_STRONG:
1223 return Attribute::StackProtectStrong;
1224 case bitc::ATTR_KIND_SAFESTACK:
1225 return Attribute::SafeStack;
1226 case bitc::ATTR_KIND_STRUCT_RET:
1227 return Attribute::StructRet;
1228 case bitc::ATTR_KIND_SANITIZE_ADDRESS:
1229 return Attribute::SanitizeAddress;
1230 case bitc::ATTR_KIND_SANITIZE_THREAD:
1231 return Attribute::SanitizeThread;
1232 case bitc::ATTR_KIND_SANITIZE_MEMORY:
1233 return Attribute::SanitizeMemory;
1234 case bitc::ATTR_KIND_UW_TABLE:
1235 return Attribute::UWTable;
1236 case bitc::ATTR_KIND_Z_EXT:
1237 return Attribute::ZExt;
1241 std::error_code BitcodeReader::parseAlignmentValue(uint64_t Exponent,
1242 unsigned &Alignment) {
1243 // Note: Alignment in bitcode files is incremented by 1, so that zero
1244 // can be used for default alignment.
1245 if (Exponent > Value::MaxAlignmentExponent + 1)
1246 return error("Invalid alignment value");
1247 Alignment = (1 << static_cast<unsigned>(Exponent)) >> 1;
1248 return std::error_code();
1251 std::error_code BitcodeReader::parseAttrKind(uint64_t Code,
1252 Attribute::AttrKind *Kind) {
1253 *Kind = getAttrFromCode(Code);
1254 if (*Kind == Attribute::None)
1255 return error(BitcodeError::CorruptedBitcode,
1256 "Unknown attribute kind (" + Twine(Code) + ")");
1257 return std::error_code();
1260 std::error_code BitcodeReader::parseAttributeGroupBlock() {
1261 if (Stream.EnterSubBlock(bitc::PARAMATTR_GROUP_BLOCK_ID))
1262 return error("Invalid record");
1264 if (!MAttributeGroups.empty())
1265 return error("Invalid multiple blocks");
1267 SmallVector<uint64_t, 64> Record;
1269 // Read all the records.
1271 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1273 switch (Entry.Kind) {
1274 case BitstreamEntry::SubBlock: // Handled for us already.
1275 case BitstreamEntry::Error:
1276 return error("Malformed block");
1277 case BitstreamEntry::EndBlock:
1278 return std::error_code();
1279 case BitstreamEntry::Record:
1280 // The interesting case.
1286 switch (Stream.readRecord(Entry.ID, Record)) {
1287 default: // Default behavior: ignore.
1289 case bitc::PARAMATTR_GRP_CODE_ENTRY: { // ENTRY: [grpid, idx, a0, a1, ...]
1290 if (Record.size() < 3)
1291 return error("Invalid record");
1293 uint64_t GrpID = Record[0];
1294 uint64_t Idx = Record[1]; // Index of the object this attribute refers to.
1297 for (unsigned i = 2, e = Record.size(); i != e; ++i) {
1298 if (Record[i] == 0) { // Enum attribute
1299 Attribute::AttrKind Kind;
1300 if (std::error_code EC = parseAttrKind(Record[++i], &Kind))
1303 B.addAttribute(Kind);
1304 } else if (Record[i] == 1) { // Integer attribute
1305 Attribute::AttrKind Kind;
1306 if (std::error_code EC = parseAttrKind(Record[++i], &Kind))
1308 if (Kind == Attribute::Alignment)
1309 B.addAlignmentAttr(Record[++i]);
1310 else if (Kind == Attribute::StackAlignment)
1311 B.addStackAlignmentAttr(Record[++i]);
1312 else if (Kind == Attribute::Dereferenceable)
1313 B.addDereferenceableAttr(Record[++i]);
1314 else if (Kind == Attribute::DereferenceableOrNull)
1315 B.addDereferenceableOrNullAttr(Record[++i]);
1316 } else { // String attribute
1317 assert((Record[i] == 3 || Record[i] == 4) &&
1318 "Invalid attribute group entry");
1319 bool HasValue = (Record[i++] == 4);
1320 SmallString<64> KindStr;
1321 SmallString<64> ValStr;
1323 while (Record[i] != 0 && i != e)
1324 KindStr += Record[i++];
1325 assert(Record[i] == 0 && "Kind string not null terminated");
1328 // Has a value associated with it.
1329 ++i; // Skip the '0' that terminates the "kind" string.
1330 while (Record[i] != 0 && i != e)
1331 ValStr += Record[i++];
1332 assert(Record[i] == 0 && "Value string not null terminated");
1335 B.addAttribute(KindStr.str(), ValStr.str());
1339 MAttributeGroups[GrpID] = AttributeSet::get(Context, Idx, B);
1346 std::error_code BitcodeReader::parseTypeTable() {
1347 if (Stream.EnterSubBlock(bitc::TYPE_BLOCK_ID_NEW))
1348 return error("Invalid record");
1350 return parseTypeTableBody();
1353 std::error_code BitcodeReader::parseTypeTableBody() {
1354 if (!TypeList.empty())
1355 return error("Invalid multiple blocks");
1357 SmallVector<uint64_t, 64> Record;
1358 unsigned NumRecords = 0;
1360 SmallString<64> TypeName;
1362 // Read all the records for this type table.
1364 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1366 switch (Entry.Kind) {
1367 case BitstreamEntry::SubBlock: // Handled for us already.
1368 case BitstreamEntry::Error:
1369 return error("Malformed block");
1370 case BitstreamEntry::EndBlock:
1371 if (NumRecords != TypeList.size())
1372 return error("Malformed block");
1373 return std::error_code();
1374 case BitstreamEntry::Record:
1375 // The interesting case.
1381 Type *ResultTy = nullptr;
1382 switch (Stream.readRecord(Entry.ID, Record)) {
1384 return error("Invalid value");
1385 case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries]
1386 // TYPE_CODE_NUMENTRY contains a count of the number of types in the
1387 // type list. This allows us to reserve space.
1388 if (Record.size() < 1)
1389 return error("Invalid record");
1390 TypeList.resize(Record[0]);
1392 case bitc::TYPE_CODE_VOID: // VOID
1393 ResultTy = Type::getVoidTy(Context);
1395 case bitc::TYPE_CODE_HALF: // HALF
1396 ResultTy = Type::getHalfTy(Context);
1398 case bitc::TYPE_CODE_FLOAT: // FLOAT
1399 ResultTy = Type::getFloatTy(Context);
1401 case bitc::TYPE_CODE_DOUBLE: // DOUBLE
1402 ResultTy = Type::getDoubleTy(Context);
1404 case bitc::TYPE_CODE_X86_FP80: // X86_FP80
1405 ResultTy = Type::getX86_FP80Ty(Context);
1407 case bitc::TYPE_CODE_FP128: // FP128
1408 ResultTy = Type::getFP128Ty(Context);
1410 case bitc::TYPE_CODE_PPC_FP128: // PPC_FP128
1411 ResultTy = Type::getPPC_FP128Ty(Context);
1413 case bitc::TYPE_CODE_LABEL: // LABEL
1414 ResultTy = Type::getLabelTy(Context);
1416 case bitc::TYPE_CODE_METADATA: // METADATA
1417 ResultTy = Type::getMetadataTy(Context);
1419 case bitc::TYPE_CODE_X86_MMX: // X86_MMX
1420 ResultTy = Type::getX86_MMXTy(Context);
1422 case bitc::TYPE_CODE_TOKEN: // TOKEN
1423 ResultTy = Type::getTokenTy(Context);
1425 case bitc::TYPE_CODE_INTEGER: { // INTEGER: [width]
1426 if (Record.size() < 1)
1427 return error("Invalid record");
1429 uint64_t NumBits = Record[0];
1430 if (NumBits < IntegerType::MIN_INT_BITS ||
1431 NumBits > IntegerType::MAX_INT_BITS)
1432 return error("Bitwidth for integer type out of range");
1433 ResultTy = IntegerType::get(Context, NumBits);
1436 case bitc::TYPE_CODE_POINTER: { // POINTER: [pointee type] or
1437 // [pointee type, address space]
1438 if (Record.size() < 1)
1439 return error("Invalid record");
1440 unsigned AddressSpace = 0;
1441 if (Record.size() == 2)
1442 AddressSpace = Record[1];
1443 ResultTy = getTypeByID(Record[0]);
1445 !PointerType::isValidElementType(ResultTy))
1446 return error("Invalid type");
1447 ResultTy = PointerType::get(ResultTy, AddressSpace);
1450 case bitc::TYPE_CODE_FUNCTION_OLD: {
1451 // FIXME: attrid is dead, remove it in LLVM 4.0
1452 // FUNCTION: [vararg, attrid, retty, paramty x N]
1453 if (Record.size() < 3)
1454 return error("Invalid record");
1455 SmallVector<Type*, 8> ArgTys;
1456 for (unsigned i = 3, e = Record.size(); i != e; ++i) {
1457 if (Type *T = getTypeByID(Record[i]))
1458 ArgTys.push_back(T);
1463 ResultTy = getTypeByID(Record[2]);
1464 if (!ResultTy || ArgTys.size() < Record.size()-3)
1465 return error("Invalid type");
1467 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
1470 case bitc::TYPE_CODE_FUNCTION: {
1471 // FUNCTION: [vararg, retty, paramty x N]
1472 if (Record.size() < 2)
1473 return error("Invalid record");
1474 SmallVector<Type*, 8> ArgTys;
1475 for (unsigned i = 2, e = Record.size(); i != e; ++i) {
1476 if (Type *T = getTypeByID(Record[i])) {
1477 if (!FunctionType::isValidArgumentType(T))
1478 return error("Invalid function argument type");
1479 ArgTys.push_back(T);
1485 ResultTy = getTypeByID(Record[1]);
1486 if (!ResultTy || ArgTys.size() < Record.size()-2)
1487 return error("Invalid type");
1489 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
1492 case bitc::TYPE_CODE_STRUCT_ANON: { // STRUCT: [ispacked, eltty x N]
1493 if (Record.size() < 1)
1494 return error("Invalid record");
1495 SmallVector<Type*, 8> EltTys;
1496 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
1497 if (Type *T = getTypeByID(Record[i]))
1498 EltTys.push_back(T);
1502 if (EltTys.size() != Record.size()-1)
1503 return error("Invalid type");
1504 ResultTy = StructType::get(Context, EltTys, Record[0]);
1507 case bitc::TYPE_CODE_STRUCT_NAME: // STRUCT_NAME: [strchr x N]
1508 if (convertToString(Record, 0, TypeName))
1509 return error("Invalid record");
1512 case bitc::TYPE_CODE_STRUCT_NAMED: { // STRUCT: [ispacked, eltty x N]
1513 if (Record.size() < 1)
1514 return error("Invalid record");
1516 if (NumRecords >= TypeList.size())
1517 return error("Invalid TYPE table");
1519 // Check to see if this was forward referenced, if so fill in the temp.
1520 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
1522 Res->setName(TypeName);
1523 TypeList[NumRecords] = nullptr;
1524 } else // Otherwise, create a new struct.
1525 Res = createIdentifiedStructType(Context, TypeName);
1528 SmallVector<Type*, 8> EltTys;
1529 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
1530 if (Type *T = getTypeByID(Record[i]))
1531 EltTys.push_back(T);
1535 if (EltTys.size() != Record.size()-1)
1536 return error("Invalid record");
1537 Res->setBody(EltTys, Record[0]);
1541 case bitc::TYPE_CODE_OPAQUE: { // OPAQUE: []
1542 if (Record.size() != 1)
1543 return error("Invalid record");
1545 if (NumRecords >= TypeList.size())
1546 return error("Invalid TYPE table");
1548 // Check to see if this was forward referenced, if so fill in the temp.
1549 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
1551 Res->setName(TypeName);
1552 TypeList[NumRecords] = nullptr;
1553 } else // Otherwise, create a new struct with no body.
1554 Res = createIdentifiedStructType(Context, TypeName);
1559 case bitc::TYPE_CODE_ARRAY: // ARRAY: [numelts, eltty]
1560 if (Record.size() < 2)
1561 return error("Invalid record");
1562 ResultTy = getTypeByID(Record[1]);
1563 if (!ResultTy || !ArrayType::isValidElementType(ResultTy))
1564 return error("Invalid type");
1565 ResultTy = ArrayType::get(ResultTy, Record[0]);
1567 case bitc::TYPE_CODE_VECTOR: // VECTOR: [numelts, eltty]
1568 if (Record.size() < 2)
1569 return error("Invalid record");
1571 return error("Invalid vector length");
1572 ResultTy = getTypeByID(Record[1]);
1573 if (!ResultTy || !StructType::isValidElementType(ResultTy))
1574 return error("Invalid type");
1575 ResultTy = VectorType::get(ResultTy, Record[0]);
1579 if (NumRecords >= TypeList.size())
1580 return error("Invalid TYPE table");
1581 if (TypeList[NumRecords])
1583 "Invalid TYPE table: Only named structs can be forward referenced");
1584 assert(ResultTy && "Didn't read a type?");
1585 TypeList[NumRecords++] = ResultTy;
1589 /// Associate a value with its name from the given index in the provided record.
1590 ErrorOr<Value *> BitcodeReader::recordValue(SmallVectorImpl<uint64_t> &Record,
1591 unsigned NameIndex, Triple &TT) {
1592 SmallString<128> ValueName;
1593 if (convertToString(Record, NameIndex, ValueName))
1594 return error("Invalid record");
1595 unsigned ValueID = Record[0];
1596 if (ValueID >= ValueList.size() || !ValueList[ValueID])
1597 return error("Invalid record");
1598 Value *V = ValueList[ValueID];
1600 V->setName(StringRef(ValueName.data(), ValueName.size()));
1601 auto *GO = dyn_cast<GlobalObject>(V);
1603 if (GO->getComdat() == reinterpret_cast<Comdat *>(1)) {
1604 if (TT.isOSBinFormatMachO())
1605 GO->setComdat(nullptr);
1607 GO->setComdat(TheModule->getOrInsertComdat(V->getName()));
1613 /// Parse the value symbol table at either the current parsing location or
1614 /// at the given bit offset if provided.
1615 std::error_code BitcodeReader::parseValueSymbolTable(unsigned Offset) {
1616 uint64_t CurrentBit;
1617 // Pass in the Offset to distinguish between calling for the module-level
1618 // VST (where we want to jump to the VST offset) and the function-level
1619 // VST (where we don't).
1621 // Save the current parsing location so we can jump back at the end
1623 CurrentBit = Stream.GetCurrentBitNo();
1624 Stream.JumpToBit(Offset * 32);
1625 BitstreamEntry Entry = Stream.advance();
1626 assert(Entry.Kind == BitstreamEntry::SubBlock);
1627 assert(Entry.ID == bitc::VALUE_SYMTAB_BLOCK_ID);
1630 // Compute the delta between the bitcode indices in the VST (the word offset
1631 // to the word-aligned ENTER_SUBBLOCK for the function block, and that
1632 // expected by the lazy reader. The reader's EnterSubBlock expects to have
1633 // already read the ENTER_SUBBLOCK code (size getAbbrevIDWidth) and BlockID
1634 // (size BlockIDWidth). Note that we access the stream's AbbrevID width here
1635 // just before entering the VST subblock because: 1) the EnterSubBlock
1636 // changes the AbbrevID width; 2) the VST block is nested within the same
1637 // outer MODULE_BLOCK as the FUNCTION_BLOCKs and therefore have the same
1638 // AbbrevID width before calling EnterSubBlock; and 3) when we want to
1639 // jump to the FUNCTION_BLOCK using this offset later, we don't want
1640 // to rely on the stream's AbbrevID width being that of the MODULE_BLOCK.
1641 unsigned FuncBitcodeOffsetDelta =
1642 Stream.getAbbrevIDWidth() + bitc::BlockIDWidth;
1644 if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
1645 return error("Invalid record");
1647 SmallVector<uint64_t, 64> Record;
1649 Triple TT(TheModule->getTargetTriple());
1651 // Read all the records for this value table.
1652 SmallString<128> ValueName;
1654 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1656 switch (Entry.Kind) {
1657 case BitstreamEntry::SubBlock: // Handled for us already.
1658 case BitstreamEntry::Error:
1659 return error("Malformed block");
1660 case BitstreamEntry::EndBlock:
1662 Stream.JumpToBit(CurrentBit);
1663 return std::error_code();
1664 case BitstreamEntry::Record:
1665 // The interesting case.
1671 switch (Stream.readRecord(Entry.ID, Record)) {
1672 default: // Default behavior: unknown type.
1674 case bitc::VST_CODE_ENTRY: { // VST_ENTRY: [valueid, namechar x N]
1675 ErrorOr<Value *> ValOrErr = recordValue(Record, 1, TT);
1676 if (std::error_code EC = ValOrErr.getError())
1681 case bitc::VST_CODE_FNENTRY: {
1682 // VST_FNENTRY: [valueid, offset, namechar x N]
1683 ErrorOr<Value *> ValOrErr = recordValue(Record, 2, TT);
1684 if (std::error_code EC = ValOrErr.getError())
1686 Value *V = ValOrErr.get();
1688 auto *GO = dyn_cast<GlobalObject>(V);
1690 // If this is an alias, need to get the actual Function object
1691 // it aliases, in order to set up the DeferredFunctionInfo entry below.
1692 auto *GA = dyn_cast<GlobalAlias>(V);
1694 GO = GA->getBaseObject();
1698 uint64_t FuncWordOffset = Record[1];
1699 Function *F = dyn_cast<Function>(GO);
1701 uint64_t FuncBitOffset = FuncWordOffset * 32;
1702 DeferredFunctionInfo[F] = FuncBitOffset + FuncBitcodeOffsetDelta;
1703 // Set the NextUnreadBit to point to the last function block.
1704 // Later when parsing is resumed after function materialization,
1705 // we can simply skip that last function block.
1706 if (FuncBitOffset > NextUnreadBit)
1707 NextUnreadBit = FuncBitOffset;
1710 case bitc::VST_CODE_BBENTRY: {
1711 if (convertToString(Record, 1, ValueName))
1712 return error("Invalid record");
1713 BasicBlock *BB = getBasicBlock(Record[0]);
1715 return error("Invalid record");
1717 BB->setName(StringRef(ValueName.data(), ValueName.size()));
1725 static int64_t unrotateSign(uint64_t U) { return U & 1 ? ~(U >> 1) : U >> 1; }
1727 std::error_code BitcodeReader::parseMetadata() {
1728 IsMetadataMaterialized = true;
1729 unsigned NextMDValueNo = MDValueList.size();
1731 if (Stream.EnterSubBlock(bitc::METADATA_BLOCK_ID))
1732 return error("Invalid record");
1734 SmallVector<uint64_t, 64> Record;
1737 [&](unsigned ID) -> Metadata *{ return MDValueList.getValueFwdRef(ID); };
1738 auto getMDOrNull = [&](unsigned ID) -> Metadata *{
1740 return getMD(ID - 1);
1743 auto getMDString = [&](unsigned ID) -> MDString *{
1744 // This requires that the ID is not really a forward reference. In
1745 // particular, the MDString must already have been resolved.
1746 return cast_or_null<MDString>(getMDOrNull(ID));
1749 #define GET_OR_DISTINCT(CLASS, DISTINCT, ARGS) \
1750 (DISTINCT ? CLASS::getDistinct ARGS : CLASS::get ARGS)
1752 // Read all the records.
1754 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1756 switch (Entry.Kind) {
1757 case BitstreamEntry::SubBlock: // Handled for us already.
1758 case BitstreamEntry::Error:
1759 return error("Malformed block");
1760 case BitstreamEntry::EndBlock:
1761 MDValueList.tryToResolveCycles();
1762 return std::error_code();
1763 case BitstreamEntry::Record:
1764 // The interesting case.
1770 unsigned Code = Stream.readRecord(Entry.ID, Record);
1771 bool IsDistinct = false;
1773 default: // Default behavior: ignore.
1775 case bitc::METADATA_NAME: {
1776 // Read name of the named metadata.
1777 SmallString<8> Name(Record.begin(), Record.end());
1779 Code = Stream.ReadCode();
1781 unsigned NextBitCode = Stream.readRecord(Code, Record);
1782 if (NextBitCode != bitc::METADATA_NAMED_NODE)
1783 return error("METADATA_NAME not followed by METADATA_NAMED_NODE");
1785 // Read named metadata elements.
1786 unsigned Size = Record.size();
1787 NamedMDNode *NMD = TheModule->getOrInsertNamedMetadata(Name);
1788 for (unsigned i = 0; i != Size; ++i) {
1789 MDNode *MD = dyn_cast_or_null<MDNode>(MDValueList.getValueFwdRef(Record[i]));
1791 return error("Invalid record");
1792 NMD->addOperand(MD);
1796 case bitc::METADATA_OLD_FN_NODE: {
1797 // FIXME: Remove in 4.0.
1798 // This is a LocalAsMetadata record, the only type of function-local
1800 if (Record.size() % 2 == 1)
1801 return error("Invalid record");
1803 // If this isn't a LocalAsMetadata record, we're dropping it. This used
1804 // to be legal, but there's no upgrade path.
1805 auto dropRecord = [&] {
1806 MDValueList.assignValue(MDNode::get(Context, None), NextMDValueNo++);
1808 if (Record.size() != 2) {
1813 Type *Ty = getTypeByID(Record[0]);
1814 if (Ty->isMetadataTy() || Ty->isVoidTy()) {
1819 MDValueList.assignValue(
1820 LocalAsMetadata::get(ValueList.getValueFwdRef(Record[1], Ty)),
1824 case bitc::METADATA_OLD_NODE: {
1825 // FIXME: Remove in 4.0.
1826 if (Record.size() % 2 == 1)
1827 return error("Invalid record");
1829 unsigned Size = Record.size();
1830 SmallVector<Metadata *, 8> Elts;
1831 for (unsigned i = 0; i != Size; i += 2) {
1832 Type *Ty = getTypeByID(Record[i]);
1834 return error("Invalid record");
1835 if (Ty->isMetadataTy())
1836 Elts.push_back(MDValueList.getValueFwdRef(Record[i+1]));
1837 else if (!Ty->isVoidTy()) {
1839 ValueAsMetadata::get(ValueList.getValueFwdRef(Record[i + 1], Ty));
1840 assert(isa<ConstantAsMetadata>(MD) &&
1841 "Expected non-function-local metadata");
1844 Elts.push_back(nullptr);
1846 MDValueList.assignValue(MDNode::get(Context, Elts), NextMDValueNo++);
1849 case bitc::METADATA_VALUE: {
1850 if (Record.size() != 2)
1851 return error("Invalid record");
1853 Type *Ty = getTypeByID(Record[0]);
1854 if (Ty->isMetadataTy() || Ty->isVoidTy())
1855 return error("Invalid record");
1857 MDValueList.assignValue(
1858 ValueAsMetadata::get(ValueList.getValueFwdRef(Record[1], Ty)),
1862 case bitc::METADATA_DISTINCT_NODE:
1865 case bitc::METADATA_NODE: {
1866 SmallVector<Metadata *, 8> Elts;
1867 Elts.reserve(Record.size());
1868 for (unsigned ID : Record)
1869 Elts.push_back(ID ? MDValueList.getValueFwdRef(ID - 1) : nullptr);
1870 MDValueList.assignValue(IsDistinct ? MDNode::getDistinct(Context, Elts)
1871 : MDNode::get(Context, Elts),
1875 case bitc::METADATA_LOCATION: {
1876 if (Record.size() != 5)
1877 return error("Invalid record");
1879 unsigned Line = Record[1];
1880 unsigned Column = Record[2];
1881 MDNode *Scope = cast<MDNode>(MDValueList.getValueFwdRef(Record[3]));
1882 Metadata *InlinedAt =
1883 Record[4] ? MDValueList.getValueFwdRef(Record[4] - 1) : nullptr;
1884 MDValueList.assignValue(
1885 GET_OR_DISTINCT(DILocation, Record[0],
1886 (Context, Line, Column, Scope, InlinedAt)),
1890 case bitc::METADATA_GENERIC_DEBUG: {
1891 if (Record.size() < 4)
1892 return error("Invalid record");
1894 unsigned Tag = Record[1];
1895 unsigned Version = Record[2];
1897 if (Tag >= 1u << 16 || Version != 0)
1898 return error("Invalid record");
1900 auto *Header = getMDString(Record[3]);
1901 SmallVector<Metadata *, 8> DwarfOps;
1902 for (unsigned I = 4, E = Record.size(); I != E; ++I)
1903 DwarfOps.push_back(Record[I] ? MDValueList.getValueFwdRef(Record[I] - 1)
1905 MDValueList.assignValue(GET_OR_DISTINCT(GenericDINode, Record[0],
1906 (Context, Tag, Header, DwarfOps)),
1910 case bitc::METADATA_SUBRANGE: {
1911 if (Record.size() != 3)
1912 return error("Invalid record");
1914 MDValueList.assignValue(
1915 GET_OR_DISTINCT(DISubrange, Record[0],
1916 (Context, Record[1], unrotateSign(Record[2]))),
1920 case bitc::METADATA_ENUMERATOR: {
1921 if (Record.size() != 3)
1922 return error("Invalid record");
1924 MDValueList.assignValue(GET_OR_DISTINCT(DIEnumerator, Record[0],
1925 (Context, unrotateSign(Record[1]),
1926 getMDString(Record[2]))),
1930 case bitc::METADATA_BASIC_TYPE: {
1931 if (Record.size() != 6)
1932 return error("Invalid record");
1934 MDValueList.assignValue(
1935 GET_OR_DISTINCT(DIBasicType, Record[0],
1936 (Context, Record[1], getMDString(Record[2]),
1937 Record[3], Record[4], Record[5])),
1941 case bitc::METADATA_DERIVED_TYPE: {
1942 if (Record.size() != 12)
1943 return error("Invalid record");
1945 MDValueList.assignValue(
1946 GET_OR_DISTINCT(DIDerivedType, Record[0],
1947 (Context, Record[1], getMDString(Record[2]),
1948 getMDOrNull(Record[3]), Record[4],
1949 getMDOrNull(Record[5]), getMDOrNull(Record[6]),
1950 Record[7], Record[8], Record[9], Record[10],
1951 getMDOrNull(Record[11]))),
1955 case bitc::METADATA_COMPOSITE_TYPE: {
1956 if (Record.size() != 16)
1957 return error("Invalid record");
1959 MDValueList.assignValue(
1960 GET_OR_DISTINCT(DICompositeType, Record[0],
1961 (Context, Record[1], getMDString(Record[2]),
1962 getMDOrNull(Record[3]), Record[4],
1963 getMDOrNull(Record[5]), getMDOrNull(Record[6]),
1964 Record[7], Record[8], Record[9], Record[10],
1965 getMDOrNull(Record[11]), Record[12],
1966 getMDOrNull(Record[13]), getMDOrNull(Record[14]),
1967 getMDString(Record[15]))),
1971 case bitc::METADATA_SUBROUTINE_TYPE: {
1972 if (Record.size() != 3)
1973 return error("Invalid record");
1975 MDValueList.assignValue(
1976 GET_OR_DISTINCT(DISubroutineType, Record[0],
1977 (Context, Record[1], getMDOrNull(Record[2]))),
1982 case bitc::METADATA_MODULE: {
1983 if (Record.size() != 6)
1984 return error("Invalid record");
1986 MDValueList.assignValue(
1987 GET_OR_DISTINCT(DIModule, Record[0],
1988 (Context, getMDOrNull(Record[1]),
1989 getMDString(Record[2]), getMDString(Record[3]),
1990 getMDString(Record[4]), getMDString(Record[5]))),
1995 case bitc::METADATA_FILE: {
1996 if (Record.size() != 3)
1997 return error("Invalid record");
1999 MDValueList.assignValue(
2000 GET_OR_DISTINCT(DIFile, Record[0], (Context, getMDString(Record[1]),
2001 getMDString(Record[2]))),
2005 case bitc::METADATA_COMPILE_UNIT: {
2006 if (Record.size() < 14 || Record.size() > 15)
2007 return error("Invalid record");
2009 // Ignore Record[1], which indicates whether this compile unit is
2010 // distinct. It's always distinct.
2011 MDValueList.assignValue(
2012 DICompileUnit::getDistinct(
2013 Context, Record[1], getMDOrNull(Record[2]),
2014 getMDString(Record[3]), Record[4], getMDString(Record[5]),
2015 Record[6], getMDString(Record[7]), Record[8],
2016 getMDOrNull(Record[9]), getMDOrNull(Record[10]),
2017 getMDOrNull(Record[11]), getMDOrNull(Record[12]),
2018 getMDOrNull(Record[13]), Record.size() == 14 ? 0 : Record[14]),
2022 case bitc::METADATA_SUBPROGRAM: {
2023 if (Record.size() != 19)
2024 return error("Invalid record");
2026 MDValueList.assignValue(
2029 Record[0] || Record[8], // All definitions should be distinct.
2030 (Context, getMDOrNull(Record[1]), getMDString(Record[2]),
2031 getMDString(Record[3]), getMDOrNull(Record[4]), Record[5],
2032 getMDOrNull(Record[6]), Record[7], Record[8], Record[9],
2033 getMDOrNull(Record[10]), Record[11], Record[12], Record[13],
2034 Record[14], getMDOrNull(Record[15]), getMDOrNull(Record[16]),
2035 getMDOrNull(Record[17]), getMDOrNull(Record[18]))),
2039 case bitc::METADATA_LEXICAL_BLOCK: {
2040 if (Record.size() != 5)
2041 return error("Invalid record");
2043 MDValueList.assignValue(
2044 GET_OR_DISTINCT(DILexicalBlock, Record[0],
2045 (Context, getMDOrNull(Record[1]),
2046 getMDOrNull(Record[2]), Record[3], Record[4])),
2050 case bitc::METADATA_LEXICAL_BLOCK_FILE: {
2051 if (Record.size() != 4)
2052 return error("Invalid record");
2054 MDValueList.assignValue(
2055 GET_OR_DISTINCT(DILexicalBlockFile, Record[0],
2056 (Context, getMDOrNull(Record[1]),
2057 getMDOrNull(Record[2]), Record[3])),
2061 case bitc::METADATA_NAMESPACE: {
2062 if (Record.size() != 5)
2063 return error("Invalid record");
2065 MDValueList.assignValue(
2066 GET_OR_DISTINCT(DINamespace, Record[0],
2067 (Context, getMDOrNull(Record[1]),
2068 getMDOrNull(Record[2]), getMDString(Record[3]),
2073 case bitc::METADATA_TEMPLATE_TYPE: {
2074 if (Record.size() != 3)
2075 return error("Invalid record");
2077 MDValueList.assignValue(GET_OR_DISTINCT(DITemplateTypeParameter,
2079 (Context, getMDString(Record[1]),
2080 getMDOrNull(Record[2]))),
2084 case bitc::METADATA_TEMPLATE_VALUE: {
2085 if (Record.size() != 5)
2086 return error("Invalid record");
2088 MDValueList.assignValue(
2089 GET_OR_DISTINCT(DITemplateValueParameter, Record[0],
2090 (Context, Record[1], getMDString(Record[2]),
2091 getMDOrNull(Record[3]), getMDOrNull(Record[4]))),
2095 case bitc::METADATA_GLOBAL_VAR: {
2096 if (Record.size() != 11)
2097 return error("Invalid record");
2099 MDValueList.assignValue(
2100 GET_OR_DISTINCT(DIGlobalVariable, Record[0],
2101 (Context, getMDOrNull(Record[1]),
2102 getMDString(Record[2]), getMDString(Record[3]),
2103 getMDOrNull(Record[4]), Record[5],
2104 getMDOrNull(Record[6]), Record[7], Record[8],
2105 getMDOrNull(Record[9]), getMDOrNull(Record[10]))),
2109 case bitc::METADATA_LOCAL_VAR: {
2110 // 10th field is for the obseleted 'inlinedAt:' field.
2111 if (Record.size() < 8 || Record.size() > 10)
2112 return error("Invalid record");
2114 // 2nd field used to be an artificial tag, either DW_TAG_auto_variable or
2115 // DW_TAG_arg_variable.
2116 bool HasTag = Record.size() > 8;
2117 MDValueList.assignValue(
2118 GET_OR_DISTINCT(DILocalVariable, Record[0],
2119 (Context, getMDOrNull(Record[1 + HasTag]),
2120 getMDString(Record[2 + HasTag]),
2121 getMDOrNull(Record[3 + HasTag]), Record[4 + HasTag],
2122 getMDOrNull(Record[5 + HasTag]), Record[6 + HasTag],
2123 Record[7 + HasTag])),
2127 case bitc::METADATA_EXPRESSION: {
2128 if (Record.size() < 1)
2129 return error("Invalid record");
2131 MDValueList.assignValue(
2132 GET_OR_DISTINCT(DIExpression, Record[0],
2133 (Context, makeArrayRef(Record).slice(1))),
2137 case bitc::METADATA_OBJC_PROPERTY: {
2138 if (Record.size() != 8)
2139 return error("Invalid record");
2141 MDValueList.assignValue(
2142 GET_OR_DISTINCT(DIObjCProperty, Record[0],
2143 (Context, getMDString(Record[1]),
2144 getMDOrNull(Record[2]), Record[3],
2145 getMDString(Record[4]), getMDString(Record[5]),
2146 Record[6], getMDOrNull(Record[7]))),
2150 case bitc::METADATA_IMPORTED_ENTITY: {
2151 if (Record.size() != 6)
2152 return error("Invalid record");
2154 MDValueList.assignValue(
2155 GET_OR_DISTINCT(DIImportedEntity, Record[0],
2156 (Context, Record[1], getMDOrNull(Record[2]),
2157 getMDOrNull(Record[3]), Record[4],
2158 getMDString(Record[5]))),
2162 case bitc::METADATA_STRING: {
2163 std::string String(Record.begin(), Record.end());
2164 llvm::UpgradeMDStringConstant(String);
2165 Metadata *MD = MDString::get(Context, String);
2166 MDValueList.assignValue(MD, NextMDValueNo++);
2169 case bitc::METADATA_KIND: {
2170 if (Record.size() < 2)
2171 return error("Invalid record");
2173 unsigned Kind = Record[0];
2174 SmallString<8> Name(Record.begin()+1, Record.end());
2176 unsigned NewKind = TheModule->getMDKindID(Name.str());
2177 if (!MDKindMap.insert(std::make_pair(Kind, NewKind)).second)
2178 return error("Conflicting METADATA_KIND records");
2183 #undef GET_OR_DISTINCT
2186 /// Decode a signed value stored with the sign bit in the LSB for dense VBR
2188 uint64_t BitcodeReader::decodeSignRotatedValue(uint64_t V) {
2193 // There is no such thing as -0 with integers. "-0" really means MININT.
2197 /// Resolve all of the initializers for global values and aliases that we can.
2198 std::error_code BitcodeReader::resolveGlobalAndAliasInits() {
2199 std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInitWorklist;
2200 std::vector<std::pair<GlobalAlias*, unsigned> > AliasInitWorklist;
2201 std::vector<std::pair<Function*, unsigned> > FunctionPrefixWorklist;
2202 std::vector<std::pair<Function*, unsigned> > FunctionPrologueWorklist;
2203 std::vector<std::pair<Function*, unsigned> > FunctionPersonalityFnWorklist;
2205 GlobalInitWorklist.swap(GlobalInits);
2206 AliasInitWorklist.swap(AliasInits);
2207 FunctionPrefixWorklist.swap(FunctionPrefixes);
2208 FunctionPrologueWorklist.swap(FunctionPrologues);
2209 FunctionPersonalityFnWorklist.swap(FunctionPersonalityFns);
2211 while (!GlobalInitWorklist.empty()) {
2212 unsigned ValID = GlobalInitWorklist.back().second;
2213 if (ValID >= ValueList.size()) {
2214 // Not ready to resolve this yet, it requires something later in the file.
2215 GlobalInits.push_back(GlobalInitWorklist.back());
2217 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
2218 GlobalInitWorklist.back().first->setInitializer(C);
2220 return error("Expected a constant");
2222 GlobalInitWorklist.pop_back();
2225 while (!AliasInitWorklist.empty()) {
2226 unsigned ValID = AliasInitWorklist.back().second;
2227 if (ValID >= ValueList.size()) {
2228 AliasInits.push_back(AliasInitWorklist.back());
2230 Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]);
2232 return error("Expected a constant");
2233 GlobalAlias *Alias = AliasInitWorklist.back().first;
2234 if (C->getType() != Alias->getType())
2235 return error("Alias and aliasee types don't match");
2236 Alias->setAliasee(C);
2238 AliasInitWorklist.pop_back();
2241 while (!FunctionPrefixWorklist.empty()) {
2242 unsigned ValID = FunctionPrefixWorklist.back().second;
2243 if (ValID >= ValueList.size()) {
2244 FunctionPrefixes.push_back(FunctionPrefixWorklist.back());
2246 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
2247 FunctionPrefixWorklist.back().first->setPrefixData(C);
2249 return error("Expected a constant");
2251 FunctionPrefixWorklist.pop_back();
2254 while (!FunctionPrologueWorklist.empty()) {
2255 unsigned ValID = FunctionPrologueWorklist.back().second;
2256 if (ValID >= ValueList.size()) {
2257 FunctionPrologues.push_back(FunctionPrologueWorklist.back());
2259 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
2260 FunctionPrologueWorklist.back().first->setPrologueData(C);
2262 return error("Expected a constant");
2264 FunctionPrologueWorklist.pop_back();
2267 while (!FunctionPersonalityFnWorklist.empty()) {
2268 unsigned ValID = FunctionPersonalityFnWorklist.back().second;
2269 if (ValID >= ValueList.size()) {
2270 FunctionPersonalityFns.push_back(FunctionPersonalityFnWorklist.back());
2272 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
2273 FunctionPersonalityFnWorklist.back().first->setPersonalityFn(C);
2275 return error("Expected a constant");
2277 FunctionPersonalityFnWorklist.pop_back();
2280 return std::error_code();
2283 static APInt readWideAPInt(ArrayRef<uint64_t> Vals, unsigned TypeBits) {
2284 SmallVector<uint64_t, 8> Words(Vals.size());
2285 std::transform(Vals.begin(), Vals.end(), Words.begin(),
2286 BitcodeReader::decodeSignRotatedValue);
2288 return APInt(TypeBits, Words);
2291 std::error_code BitcodeReader::parseConstants() {
2292 if (Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID))
2293 return error("Invalid record");
2295 SmallVector<uint64_t, 64> Record;
2297 // Read all the records for this value table.
2298 Type *CurTy = Type::getInt32Ty(Context);
2299 unsigned NextCstNo = ValueList.size();
2301 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
2303 switch (Entry.Kind) {
2304 case BitstreamEntry::SubBlock: // Handled for us already.
2305 case BitstreamEntry::Error:
2306 return error("Malformed block");
2307 case BitstreamEntry::EndBlock:
2308 if (NextCstNo != ValueList.size())
2309 return error("Invalid ronstant reference");
2311 // Once all the constants have been read, go through and resolve forward
2313 ValueList.resolveConstantForwardRefs();
2314 return std::error_code();
2315 case BitstreamEntry::Record:
2316 // The interesting case.
2323 unsigned BitCode = Stream.readRecord(Entry.ID, Record);
2325 default: // Default behavior: unknown constant
2326 case bitc::CST_CODE_UNDEF: // UNDEF
2327 V = UndefValue::get(CurTy);
2329 case bitc::CST_CODE_SETTYPE: // SETTYPE: [typeid]
2331 return error("Invalid record");
2332 if (Record[0] >= TypeList.size() || !TypeList[Record[0]])
2333 return error("Invalid record");
2334 CurTy = TypeList[Record[0]];
2335 continue; // Skip the ValueList manipulation.
2336 case bitc::CST_CODE_NULL: // NULL
2337 V = Constant::getNullValue(CurTy);
2339 case bitc::CST_CODE_INTEGER: // INTEGER: [intval]
2340 if (!CurTy->isIntegerTy() || Record.empty())
2341 return error("Invalid record");
2342 V = ConstantInt::get(CurTy, decodeSignRotatedValue(Record[0]));
2344 case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval]
2345 if (!CurTy->isIntegerTy() || Record.empty())
2346 return error("Invalid record");
2349 readWideAPInt(Record, cast<IntegerType>(CurTy)->getBitWidth());
2350 V = ConstantInt::get(Context, VInt);
2354 case bitc::CST_CODE_FLOAT: { // FLOAT: [fpval]
2356 return error("Invalid record");
2357 if (CurTy->isHalfTy())
2358 V = ConstantFP::get(Context, APFloat(APFloat::IEEEhalf,
2359 APInt(16, (uint16_t)Record[0])));
2360 else if (CurTy->isFloatTy())
2361 V = ConstantFP::get(Context, APFloat(APFloat::IEEEsingle,
2362 APInt(32, (uint32_t)Record[0])));
2363 else if (CurTy->isDoubleTy())
2364 V = ConstantFP::get(Context, APFloat(APFloat::IEEEdouble,
2365 APInt(64, Record[0])));
2366 else if (CurTy->isX86_FP80Ty()) {
2367 // Bits are not stored the same way as a normal i80 APInt, compensate.
2368 uint64_t Rearrange[2];
2369 Rearrange[0] = (Record[1] & 0xffffLL) | (Record[0] << 16);
2370 Rearrange[1] = Record[0] >> 48;
2371 V = ConstantFP::get(Context, APFloat(APFloat::x87DoubleExtended,
2372 APInt(80, Rearrange)));
2373 } else if (CurTy->isFP128Ty())
2374 V = ConstantFP::get(Context, APFloat(APFloat::IEEEquad,
2375 APInt(128, Record)));
2376 else if (CurTy->isPPC_FP128Ty())
2377 V = ConstantFP::get(Context, APFloat(APFloat::PPCDoubleDouble,
2378 APInt(128, Record)));
2380 V = UndefValue::get(CurTy);
2384 case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number]
2386 return error("Invalid record");
2388 unsigned Size = Record.size();
2389 SmallVector<Constant*, 16> Elts;
2391 if (StructType *STy = dyn_cast<StructType>(CurTy)) {
2392 for (unsigned i = 0; i != Size; ++i)
2393 Elts.push_back(ValueList.getConstantFwdRef(Record[i],
2394 STy->getElementType(i)));
2395 V = ConstantStruct::get(STy, Elts);
2396 } else if (ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) {
2397 Type *EltTy = ATy->getElementType();
2398 for (unsigned i = 0; i != Size; ++i)
2399 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
2400 V = ConstantArray::get(ATy, Elts);
2401 } else if (VectorType *VTy = dyn_cast<VectorType>(CurTy)) {
2402 Type *EltTy = VTy->getElementType();
2403 for (unsigned i = 0; i != Size; ++i)
2404 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
2405 V = ConstantVector::get(Elts);
2407 V = UndefValue::get(CurTy);
2411 case bitc::CST_CODE_STRING: // STRING: [values]
2412 case bitc::CST_CODE_CSTRING: { // CSTRING: [values]
2414 return error("Invalid record");
2416 SmallString<16> Elts(Record.begin(), Record.end());
2417 V = ConstantDataArray::getString(Context, Elts,
2418 BitCode == bitc::CST_CODE_CSTRING);
2421 case bitc::CST_CODE_DATA: {// DATA: [n x value]
2423 return error("Invalid record");
2425 Type *EltTy = cast<SequentialType>(CurTy)->getElementType();
2426 unsigned Size = Record.size();
2428 if (EltTy->isIntegerTy(8)) {
2429 SmallVector<uint8_t, 16> Elts(Record.begin(), Record.end());
2430 if (isa<VectorType>(CurTy))
2431 V = ConstantDataVector::get(Context, Elts);
2433 V = ConstantDataArray::get(Context, Elts);
2434 } else if (EltTy->isIntegerTy(16)) {
2435 SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end());
2436 if (isa<VectorType>(CurTy))
2437 V = ConstantDataVector::get(Context, Elts);
2439 V = ConstantDataArray::get(Context, Elts);
2440 } else if (EltTy->isIntegerTy(32)) {
2441 SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end());
2442 if (isa<VectorType>(CurTy))
2443 V = ConstantDataVector::get(Context, Elts);
2445 V = ConstantDataArray::get(Context, Elts);
2446 } else if (EltTy->isIntegerTy(64)) {
2447 SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end());
2448 if (isa<VectorType>(CurTy))
2449 V = ConstantDataVector::get(Context, Elts);
2451 V = ConstantDataArray::get(Context, Elts);
2452 } else if (EltTy->isFloatTy()) {
2453 SmallVector<float, 16> Elts(Size);
2454 std::transform(Record.begin(), Record.end(), Elts.begin(), BitsToFloat);
2455 if (isa<VectorType>(CurTy))
2456 V = ConstantDataVector::get(Context, Elts);
2458 V = ConstantDataArray::get(Context, Elts);
2459 } else if (EltTy->isDoubleTy()) {
2460 SmallVector<double, 16> Elts(Size);
2461 std::transform(Record.begin(), Record.end(), Elts.begin(),
2463 if (isa<VectorType>(CurTy))
2464 V = ConstantDataVector::get(Context, Elts);
2466 V = ConstantDataArray::get(Context, Elts);
2468 return error("Invalid type for value");
2473 case bitc::CST_CODE_CE_BINOP: { // CE_BINOP: [opcode, opval, opval]
2474 if (Record.size() < 3)
2475 return error("Invalid record");
2476 int Opc = getDecodedBinaryOpcode(Record[0], CurTy);
2478 V = UndefValue::get(CurTy); // Unknown binop.
2480 Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy);
2481 Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy);
2483 if (Record.size() >= 4) {
2484 if (Opc == Instruction::Add ||
2485 Opc == Instruction::Sub ||
2486 Opc == Instruction::Mul ||
2487 Opc == Instruction::Shl) {
2488 if (Record[3] & (1 << bitc::OBO_NO_SIGNED_WRAP))
2489 Flags |= OverflowingBinaryOperator::NoSignedWrap;
2490 if (Record[3] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
2491 Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
2492 } else if (Opc == Instruction::SDiv ||
2493 Opc == Instruction::UDiv ||
2494 Opc == Instruction::LShr ||
2495 Opc == Instruction::AShr) {
2496 if (Record[3] & (1 << bitc::PEO_EXACT))
2497 Flags |= SDivOperator::IsExact;
2500 V = ConstantExpr::get(Opc, LHS, RHS, Flags);
2504 case bitc::CST_CODE_CE_CAST: { // CE_CAST: [opcode, opty, opval]
2505 if (Record.size() < 3)
2506 return error("Invalid record");
2507 int Opc = getDecodedCastOpcode(Record[0]);
2509 V = UndefValue::get(CurTy); // Unknown cast.
2511 Type *OpTy = getTypeByID(Record[1]);
2513 return error("Invalid record");
2514 Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy);
2515 V = UpgradeBitCastExpr(Opc, Op, CurTy);
2516 if (!V) V = ConstantExpr::getCast(Opc, Op, CurTy);
2520 case bitc::CST_CODE_CE_INBOUNDS_GEP:
2521 case bitc::CST_CODE_CE_GEP: { // CE_GEP: [n x operands]
2523 Type *PointeeType = nullptr;
2524 if (Record.size() % 2)
2525 PointeeType = getTypeByID(Record[OpNum++]);
2526 SmallVector<Constant*, 16> Elts;
2527 while (OpNum != Record.size()) {
2528 Type *ElTy = getTypeByID(Record[OpNum++]);
2530 return error("Invalid record");
2531 Elts.push_back(ValueList.getConstantFwdRef(Record[OpNum++], ElTy));
2536 cast<SequentialType>(Elts[0]->getType()->getScalarType())
2538 return error("Explicit gep operator type does not match pointee type "
2539 "of pointer operand");
2541 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
2542 V = ConstantExpr::getGetElementPtr(PointeeType, Elts[0], Indices,
2544 bitc::CST_CODE_CE_INBOUNDS_GEP);
2547 case bitc::CST_CODE_CE_SELECT: { // CE_SELECT: [opval#, opval#, opval#]
2548 if (Record.size() < 3)
2549 return error("Invalid record");
2551 Type *SelectorTy = Type::getInt1Ty(Context);
2553 // The selector might be an i1 or an <n x i1>
2554 // Get the type from the ValueList before getting a forward ref.
2555 if (VectorType *VTy = dyn_cast<VectorType>(CurTy))
2556 if (Value *V = ValueList[Record[0]])
2557 if (SelectorTy != V->getType())
2558 SelectorTy = VectorType::get(SelectorTy, VTy->getNumElements());
2560 V = ConstantExpr::getSelect(ValueList.getConstantFwdRef(Record[0],
2562 ValueList.getConstantFwdRef(Record[1],CurTy),
2563 ValueList.getConstantFwdRef(Record[2],CurTy));
2566 case bitc::CST_CODE_CE_EXTRACTELT
2567 : { // CE_EXTRACTELT: [opty, opval, opty, opval]
2568 if (Record.size() < 3)
2569 return error("Invalid record");
2571 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
2573 return error("Invalid record");
2574 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
2575 Constant *Op1 = nullptr;
2576 if (Record.size() == 4) {
2577 Type *IdxTy = getTypeByID(Record[2]);
2579 return error("Invalid record");
2580 Op1 = ValueList.getConstantFwdRef(Record[3], IdxTy);
2581 } else // TODO: Remove with llvm 4.0
2582 Op1 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
2584 return error("Invalid record");
2585 V = ConstantExpr::getExtractElement(Op0, Op1);
2588 case bitc::CST_CODE_CE_INSERTELT
2589 : { // CE_INSERTELT: [opval, opval, opty, opval]
2590 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
2591 if (Record.size() < 3 || !OpTy)
2592 return error("Invalid record");
2593 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
2594 Constant *Op1 = ValueList.getConstantFwdRef(Record[1],
2595 OpTy->getElementType());
2596 Constant *Op2 = nullptr;
2597 if (Record.size() == 4) {
2598 Type *IdxTy = getTypeByID(Record[2]);
2600 return error("Invalid record");
2601 Op2 = ValueList.getConstantFwdRef(Record[3], IdxTy);
2602 } else // TODO: Remove with llvm 4.0
2603 Op2 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
2605 return error("Invalid record");
2606 V = ConstantExpr::getInsertElement(Op0, Op1, Op2);
2609 case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval]
2610 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
2611 if (Record.size() < 3 || !OpTy)
2612 return error("Invalid record");
2613 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
2614 Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy);
2615 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
2616 OpTy->getNumElements());
2617 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy);
2618 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
2621 case bitc::CST_CODE_CE_SHUFVEC_EX: { // [opty, opval, opval, opval]
2622 VectorType *RTy = dyn_cast<VectorType>(CurTy);
2624 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
2625 if (Record.size() < 4 || !RTy || !OpTy)
2626 return error("Invalid record");
2627 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
2628 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
2629 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
2630 RTy->getNumElements());
2631 Constant *Op2 = ValueList.getConstantFwdRef(Record[3], ShufTy);
2632 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
2635 case bitc::CST_CODE_CE_CMP: { // CE_CMP: [opty, opval, opval, pred]
2636 if (Record.size() < 4)
2637 return error("Invalid record");
2638 Type *OpTy = getTypeByID(Record[0]);
2640 return error("Invalid record");
2641 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
2642 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
2644 if (OpTy->isFPOrFPVectorTy())
2645 V = ConstantExpr::getFCmp(Record[3], Op0, Op1);
2647 V = ConstantExpr::getICmp(Record[3], Op0, Op1);
2650 // This maintains backward compatibility, pre-asm dialect keywords.
2651 // FIXME: Remove with the 4.0 release.
2652 case bitc::CST_CODE_INLINEASM_OLD: {
2653 if (Record.size() < 2)
2654 return error("Invalid record");
2655 std::string AsmStr, ConstrStr;
2656 bool HasSideEffects = Record[0] & 1;
2657 bool IsAlignStack = Record[0] >> 1;
2658 unsigned AsmStrSize = Record[1];
2659 if (2+AsmStrSize >= Record.size())
2660 return error("Invalid record");
2661 unsigned ConstStrSize = Record[2+AsmStrSize];
2662 if (3+AsmStrSize+ConstStrSize > Record.size())
2663 return error("Invalid record");
2665 for (unsigned i = 0; i != AsmStrSize; ++i)
2666 AsmStr += (char)Record[2+i];
2667 for (unsigned i = 0; i != ConstStrSize; ++i)
2668 ConstrStr += (char)Record[3+AsmStrSize+i];
2669 PointerType *PTy = cast<PointerType>(CurTy);
2670 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
2671 AsmStr, ConstrStr, HasSideEffects, IsAlignStack);
2674 // This version adds support for the asm dialect keywords (e.g.,
2676 case bitc::CST_CODE_INLINEASM: {
2677 if (Record.size() < 2)
2678 return error("Invalid record");
2679 std::string AsmStr, ConstrStr;
2680 bool HasSideEffects = Record[0] & 1;
2681 bool IsAlignStack = (Record[0] >> 1) & 1;
2682 unsigned AsmDialect = Record[0] >> 2;
2683 unsigned AsmStrSize = Record[1];
2684 if (2+AsmStrSize >= Record.size())
2685 return error("Invalid record");
2686 unsigned ConstStrSize = Record[2+AsmStrSize];
2687 if (3+AsmStrSize+ConstStrSize > Record.size())
2688 return error("Invalid record");
2690 for (unsigned i = 0; i != AsmStrSize; ++i)
2691 AsmStr += (char)Record[2+i];
2692 for (unsigned i = 0; i != ConstStrSize; ++i)
2693 ConstrStr += (char)Record[3+AsmStrSize+i];
2694 PointerType *PTy = cast<PointerType>(CurTy);
2695 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
2696 AsmStr, ConstrStr, HasSideEffects, IsAlignStack,
2697 InlineAsm::AsmDialect(AsmDialect));
2700 case bitc::CST_CODE_BLOCKADDRESS:{
2701 if (Record.size() < 3)
2702 return error("Invalid record");
2703 Type *FnTy = getTypeByID(Record[0]);
2705 return error("Invalid record");
2707 dyn_cast_or_null<Function>(ValueList.getConstantFwdRef(Record[1],FnTy));
2709 return error("Invalid record");
2711 // Don't let Fn get dematerialized.
2712 BlockAddressesTaken.insert(Fn);
2714 // If the function is already parsed we can insert the block address right
2717 unsigned BBID = Record[2];
2719 // Invalid reference to entry block.
2720 return error("Invalid ID");
2722 Function::iterator BBI = Fn->begin(), BBE = Fn->end();
2723 for (size_t I = 0, E = BBID; I != E; ++I) {
2725 return error("Invalid ID");
2730 // Otherwise insert a placeholder and remember it so it can be inserted
2731 // when the function is parsed.
2732 auto &FwdBBs = BasicBlockFwdRefs[Fn];
2734 BasicBlockFwdRefQueue.push_back(Fn);
2735 if (FwdBBs.size() < BBID + 1)
2736 FwdBBs.resize(BBID + 1);
2738 FwdBBs[BBID] = BasicBlock::Create(Context);
2741 V = BlockAddress::get(Fn, BB);
2746 if (ValueList.assignValue(V, NextCstNo))
2747 return error("Invalid forward reference");
2752 std::error_code BitcodeReader::parseUseLists() {
2753 if (Stream.EnterSubBlock(bitc::USELIST_BLOCK_ID))
2754 return error("Invalid record");
2756 // Read all the records.
2757 SmallVector<uint64_t, 64> Record;
2759 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
2761 switch (Entry.Kind) {
2762 case BitstreamEntry::SubBlock: // Handled for us already.
2763 case BitstreamEntry::Error:
2764 return error("Malformed block");
2765 case BitstreamEntry::EndBlock:
2766 return std::error_code();
2767 case BitstreamEntry::Record:
2768 // The interesting case.
2772 // Read a use list record.
2775 switch (Stream.readRecord(Entry.ID, Record)) {
2776 default: // Default behavior: unknown type.
2778 case bitc::USELIST_CODE_BB:
2781 case bitc::USELIST_CODE_DEFAULT: {
2782 unsigned RecordLength = Record.size();
2783 if (RecordLength < 3)
2784 // Records should have at least an ID and two indexes.
2785 return error("Invalid record");
2786 unsigned ID = Record.back();
2791 assert(ID < FunctionBBs.size() && "Basic block not found");
2792 V = FunctionBBs[ID];
2795 unsigned NumUses = 0;
2796 SmallDenseMap<const Use *, unsigned, 16> Order;
2797 for (const Use &U : V->uses()) {
2798 if (++NumUses > Record.size())
2800 Order[&U] = Record[NumUses - 1];
2802 if (Order.size() != Record.size() || NumUses > Record.size())
2803 // Mismatches can happen if the functions are being materialized lazily
2804 // (out-of-order), or a value has been upgraded.
2807 V->sortUseList([&](const Use &L, const Use &R) {
2808 return Order.lookup(&L) < Order.lookup(&R);
2816 /// When we see the block for metadata, remember where it is and then skip it.
2817 /// This lets us lazily deserialize the metadata.
2818 std::error_code BitcodeReader::rememberAndSkipMetadata() {
2819 // Save the current stream state.
2820 uint64_t CurBit = Stream.GetCurrentBitNo();
2821 DeferredMetadataInfo.push_back(CurBit);
2823 // Skip over the block for now.
2824 if (Stream.SkipBlock())
2825 return error("Invalid record");
2826 return std::error_code();
2829 std::error_code BitcodeReader::materializeMetadata() {
2830 for (uint64_t BitPos : DeferredMetadataInfo) {
2831 // Move the bit stream to the saved position.
2832 Stream.JumpToBit(BitPos);
2833 if (std::error_code EC = parseMetadata())
2836 DeferredMetadataInfo.clear();
2837 return std::error_code();
2840 void BitcodeReader::setStripDebugInfo() { StripDebugInfo = true; }
2842 /// When we see the block for a function body, remember where it is and then
2843 /// skip it. This lets us lazily deserialize the functions.
2844 std::error_code BitcodeReader::rememberAndSkipFunctionBody() {
2845 // Get the function we are talking about.
2846 if (FunctionsWithBodies.empty())
2847 return error("Insufficient function protos");
2849 Function *Fn = FunctionsWithBodies.back();
2850 FunctionsWithBodies.pop_back();
2852 // Save the current stream state.
2853 uint64_t CurBit = Stream.GetCurrentBitNo();
2854 DeferredFunctionInfo[Fn] = CurBit;
2856 // Skip over the function block for now.
2857 if (Stream.SkipBlock())
2858 return error("Invalid record");
2859 return std::error_code();
2862 std::error_code BitcodeReader::globalCleanup() {
2863 // Patch the initializers for globals and aliases up.
2864 resolveGlobalAndAliasInits();
2865 if (!GlobalInits.empty() || !AliasInits.empty())
2866 return error("Malformed global initializer set");
2868 // Look for intrinsic functions which need to be upgraded at some point
2869 for (Function &F : *TheModule) {
2871 if (UpgradeIntrinsicFunction(&F, NewFn))
2872 UpgradedIntrinsics[&F] = NewFn;
2875 // Look for global variables which need to be renamed.
2876 for (GlobalVariable &GV : TheModule->globals())
2877 UpgradeGlobalVariable(&GV);
2879 // Force deallocation of memory for these vectors to favor the client that
2880 // want lazy deserialization.
2881 std::vector<std::pair<GlobalVariable*, unsigned> >().swap(GlobalInits);
2882 std::vector<std::pair<GlobalAlias*, unsigned> >().swap(AliasInits);
2883 return std::error_code();
2886 std::error_code BitcodeReader::parseModule(bool Resume,
2887 bool ShouldLazyLoadMetadata) {
2889 Stream.JumpToBit(NextUnreadBit);
2890 else if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
2891 return error("Invalid record");
2893 SmallVector<uint64_t, 64> Record;
2894 std::vector<std::string> SectionTable;
2895 std::vector<std::string> GCTable;
2897 // Read all the records for this module.
2899 BitstreamEntry Entry = Stream.advance();
2901 switch (Entry.Kind) {
2902 case BitstreamEntry::Error:
2903 return error("Malformed block");
2904 case BitstreamEntry::EndBlock:
2905 return globalCleanup();
2907 case BitstreamEntry::SubBlock:
2909 default: // Skip unknown content.
2910 if (Stream.SkipBlock())
2911 return error("Invalid record");
2913 case bitc::BLOCKINFO_BLOCK_ID:
2914 if (Stream.ReadBlockInfoBlock())
2915 return error("Malformed block");
2917 case bitc::PARAMATTR_BLOCK_ID:
2918 if (std::error_code EC = parseAttributeBlock())
2921 case bitc::PARAMATTR_GROUP_BLOCK_ID:
2922 if (std::error_code EC = parseAttributeGroupBlock())
2925 case bitc::TYPE_BLOCK_ID_NEW:
2926 if (std::error_code EC = parseTypeTable())
2929 case bitc::VALUE_SYMTAB_BLOCK_ID:
2930 if (!SeenValueSymbolTable) {
2931 // Either this is an old form VST without function index and an
2932 // associated VST forward declaration record (which would have caused
2933 // the VST to be jumped to and parsed before it was encountered
2934 // normally in the stream), or there were no function blocks to
2935 // trigger an earlier parsing of the VST.
2936 assert(VSTOffset == 0 || FunctionsWithBodies.empty());
2937 if (std::error_code EC = parseValueSymbolTable())
2939 SeenValueSymbolTable = true;
2941 // We must have had a VST forward declaration record, which caused
2942 // the parser to jump to and parse the VST earlier.
2943 assert(VSTOffset > 0);
2944 if (Stream.SkipBlock())
2945 return error("Invalid record");
2948 case bitc::CONSTANTS_BLOCK_ID:
2949 if (std::error_code EC = parseConstants())
2951 if (std::error_code EC = resolveGlobalAndAliasInits())
2954 case bitc::METADATA_BLOCK_ID:
2955 if (ShouldLazyLoadMetadata && !IsMetadataMaterialized) {
2956 if (std::error_code EC = rememberAndSkipMetadata())
2960 assert(DeferredMetadataInfo.empty() && "Unexpected deferred metadata");
2961 if (std::error_code EC = parseMetadata())
2964 case bitc::FUNCTION_BLOCK_ID:
2965 // If this is the first function body we've seen, reverse the
2966 // FunctionsWithBodies list.
2967 if (!SeenFirstFunctionBody) {
2968 std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
2969 if (std::error_code EC = globalCleanup())
2971 SeenFirstFunctionBody = true;
2974 if (VSTOffset > 0) {
2975 // If we have a VST forward declaration record, make sure we
2976 // parse the VST now if we haven't already. It is needed to
2977 // set up the DeferredFunctionInfo vector for lazy reading.
2978 if (!SeenValueSymbolTable) {
2979 if (std::error_code EC =
2980 BitcodeReader::parseValueSymbolTable(VSTOffset))
2982 SeenValueSymbolTable = true;
2983 return std::error_code();
2985 // If we have a VST forward declaration record, but have already
2986 // parsed the VST (just above, when the first function body was
2987 // encountered here), then we are resuming the parse after
2988 // materializing functions. The NextUnreadBit points to the start
2989 // of the last function block recorded in the VST (set when
2990 // parsing the VST function entries). Skip it.
2991 if (Stream.SkipBlock())
2992 return error("Invalid record");
2997 // Support older bitcode files that did not have the function
2998 // index in the VST, nor a VST forward declaration record.
2999 // Build the DeferredFunctionInfo vector on the fly.
3000 if (std::error_code EC = rememberAndSkipFunctionBody())
3002 // Suspend parsing when we reach the function bodies. Subsequent
3003 // materialization calls will resume it when necessary. If the bitcode
3004 // file is old, the symbol table will be at the end instead and will not
3005 // have been seen yet. In this case, just finish the parse now.
3006 if (SeenValueSymbolTable) {
3007 NextUnreadBit = Stream.GetCurrentBitNo();
3008 return std::error_code();
3011 case bitc::USELIST_BLOCK_ID:
3012 if (std::error_code EC = parseUseLists())
3018 case BitstreamEntry::Record:
3019 // The interesting case.
3025 switch (Stream.readRecord(Entry.ID, Record)) {
3026 default: break; // Default behavior, ignore unknown content.
3027 case bitc::MODULE_CODE_VERSION: { // VERSION: [version#]
3028 if (Record.size() < 1)
3029 return error("Invalid record");
3030 // Only version #0 and #1 are supported so far.
3031 unsigned module_version = Record[0];
3032 switch (module_version) {
3034 return error("Invalid value");
3036 UseRelativeIDs = false;
3039 UseRelativeIDs = true;
3044 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
3046 if (convertToString(Record, 0, S))
3047 return error("Invalid record");
3048 TheModule->setTargetTriple(S);
3051 case bitc::MODULE_CODE_DATALAYOUT: { // DATALAYOUT: [strchr x N]
3053 if (convertToString(Record, 0, S))
3054 return error("Invalid record");
3055 TheModule->setDataLayout(S);
3058 case bitc::MODULE_CODE_ASM: { // ASM: [strchr x N]
3060 if (convertToString(Record, 0, S))
3061 return error("Invalid record");
3062 TheModule->setModuleInlineAsm(S);
3065 case bitc::MODULE_CODE_DEPLIB: { // DEPLIB: [strchr x N]
3066 // FIXME: Remove in 4.0.
3068 if (convertToString(Record, 0, S))
3069 return error("Invalid record");
3073 case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N]
3075 if (convertToString(Record, 0, S))
3076 return error("Invalid record");
3077 SectionTable.push_back(S);
3080 case bitc::MODULE_CODE_GCNAME: { // SECTIONNAME: [strchr x N]
3082 if (convertToString(Record, 0, S))
3083 return error("Invalid record");
3084 GCTable.push_back(S);
3087 case bitc::MODULE_CODE_COMDAT: { // COMDAT: [selection_kind, name]
3088 if (Record.size() < 2)
3089 return error("Invalid record");
3090 Comdat::SelectionKind SK = getDecodedComdatSelectionKind(Record[0]);
3091 unsigned ComdatNameSize = Record[1];
3092 std::string ComdatName;
3093 ComdatName.reserve(ComdatNameSize);
3094 for (unsigned i = 0; i != ComdatNameSize; ++i)
3095 ComdatName += (char)Record[2 + i];
3096 Comdat *C = TheModule->getOrInsertComdat(ComdatName);
3097 C->setSelectionKind(SK);
3098 ComdatList.push_back(C);
3101 // GLOBALVAR: [pointer type, isconst, initid,
3102 // linkage, alignment, section, visibility, threadlocal,
3103 // unnamed_addr, externally_initialized, dllstorageclass,
3105 case bitc::MODULE_CODE_GLOBALVAR: {
3106 if (Record.size() < 6)
3107 return error("Invalid record");
3108 Type *Ty = getTypeByID(Record[0]);
3110 return error("Invalid record");
3111 bool isConstant = Record[1] & 1;
3112 bool explicitType = Record[1] & 2;
3113 unsigned AddressSpace;
3115 AddressSpace = Record[1] >> 2;
3117 if (!Ty->isPointerTy())
3118 return error("Invalid type for value");
3119 AddressSpace = cast<PointerType>(Ty)->getAddressSpace();
3120 Ty = cast<PointerType>(Ty)->getElementType();
3123 uint64_t RawLinkage = Record[3];
3124 GlobalValue::LinkageTypes Linkage = getDecodedLinkage(RawLinkage);
3126 if (std::error_code EC = parseAlignmentValue(Record[4], Alignment))
3128 std::string Section;
3130 if (Record[5]-1 >= SectionTable.size())
3131 return error("Invalid ID");
3132 Section = SectionTable[Record[5]-1];
3134 GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;
3135 // Local linkage must have default visibility.
3136 if (Record.size() > 6 && !GlobalValue::isLocalLinkage(Linkage))
3137 // FIXME: Change to an error if non-default in 4.0.
3138 Visibility = getDecodedVisibility(Record[6]);
3140 GlobalVariable::ThreadLocalMode TLM = GlobalVariable::NotThreadLocal;
3141 if (Record.size() > 7)
3142 TLM = getDecodedThreadLocalMode(Record[7]);
3144 bool UnnamedAddr = false;
3145 if (Record.size() > 8)
3146 UnnamedAddr = Record[8];
3148 bool ExternallyInitialized = false;
3149 if (Record.size() > 9)
3150 ExternallyInitialized = Record[9];
3152 GlobalVariable *NewGV =
3153 new GlobalVariable(*TheModule, Ty, isConstant, Linkage, nullptr, "", nullptr,
3154 TLM, AddressSpace, ExternallyInitialized);
3155 NewGV->setAlignment(Alignment);
3156 if (!Section.empty())
3157 NewGV->setSection(Section);
3158 NewGV->setVisibility(Visibility);
3159 NewGV->setUnnamedAddr(UnnamedAddr);
3161 if (Record.size() > 10)
3162 NewGV->setDLLStorageClass(getDecodedDLLStorageClass(Record[10]));
3164 upgradeDLLImportExportLinkage(NewGV, RawLinkage);
3166 ValueList.push_back(NewGV);
3168 // Remember which value to use for the global initializer.
3169 if (unsigned InitID = Record[2])
3170 GlobalInits.push_back(std::make_pair(NewGV, InitID-1));
3172 if (Record.size() > 11) {
3173 if (unsigned ComdatID = Record[11]) {
3174 if (ComdatID > ComdatList.size())
3175 return error("Invalid global variable comdat ID");
3176 NewGV->setComdat(ComdatList[ComdatID - 1]);
3178 } else if (hasImplicitComdat(RawLinkage)) {
3179 NewGV->setComdat(reinterpret_cast<Comdat *>(1));
3183 // FUNCTION: [type, callingconv, isproto, linkage, paramattr,
3184 // alignment, section, visibility, gc, unnamed_addr,
3185 // prologuedata, dllstorageclass, comdat, prefixdata]
3186 case bitc::MODULE_CODE_FUNCTION: {
3187 if (Record.size() < 8)
3188 return error("Invalid record");
3189 Type *Ty = getTypeByID(Record[0]);
3191 return error("Invalid record");
3192 if (auto *PTy = dyn_cast<PointerType>(Ty))
3193 Ty = PTy->getElementType();
3194 auto *FTy = dyn_cast<FunctionType>(Ty);
3196 return error("Invalid type for value");
3198 Function *Func = Function::Create(FTy, GlobalValue::ExternalLinkage,
3201 Func->setCallingConv(static_cast<CallingConv::ID>(Record[1]));
3202 bool isProto = Record[2];
3203 uint64_t RawLinkage = Record[3];
3204 Func->setLinkage(getDecodedLinkage(RawLinkage));
3205 Func->setAttributes(getAttributes(Record[4]));
3208 if (std::error_code EC = parseAlignmentValue(Record[5], Alignment))
3210 Func->setAlignment(Alignment);
3212 if (Record[6]-1 >= SectionTable.size())
3213 return error("Invalid ID");
3214 Func->setSection(SectionTable[Record[6]-1]);
3216 // Local linkage must have default visibility.
3217 if (!Func->hasLocalLinkage())
3218 // FIXME: Change to an error if non-default in 4.0.
3219 Func->setVisibility(getDecodedVisibility(Record[7]));
3220 if (Record.size() > 8 && Record[8]) {
3221 if (Record[8]-1 >= GCTable.size())
3222 return error("Invalid ID");
3223 Func->setGC(GCTable[Record[8]-1].c_str());
3225 bool UnnamedAddr = false;
3226 if (Record.size() > 9)
3227 UnnamedAddr = Record[9];
3228 Func->setUnnamedAddr(UnnamedAddr);
3229 if (Record.size() > 10 && Record[10] != 0)
3230 FunctionPrologues.push_back(std::make_pair(Func, Record[10]-1));
3232 if (Record.size() > 11)
3233 Func->setDLLStorageClass(getDecodedDLLStorageClass(Record[11]));
3235 upgradeDLLImportExportLinkage(Func, RawLinkage);
3237 if (Record.size() > 12) {
3238 if (unsigned ComdatID = Record[12]) {
3239 if (ComdatID > ComdatList.size())
3240 return error("Invalid function comdat ID");
3241 Func->setComdat(ComdatList[ComdatID - 1]);
3243 } else if (hasImplicitComdat(RawLinkage)) {
3244 Func->setComdat(reinterpret_cast<Comdat *>(1));
3247 if (Record.size() > 13 && Record[13] != 0)
3248 FunctionPrefixes.push_back(std::make_pair(Func, Record[13]-1));
3250 if (Record.size() > 14 && Record[14] != 0)
3251 FunctionPersonalityFns.push_back(std::make_pair(Func, Record[14] - 1));
3253 ValueList.push_back(Func);
3255 // If this is a function with a body, remember the prototype we are
3256 // creating now, so that we can match up the body with them later.
3258 Func->setIsMaterializable(true);
3259 FunctionsWithBodies.push_back(Func);
3260 DeferredFunctionInfo[Func] = 0;
3264 // ALIAS: [alias type, aliasee val#, linkage]
3265 // ALIAS: [alias type, aliasee val#, linkage, visibility, dllstorageclass]
3266 case bitc::MODULE_CODE_ALIAS: {
3267 if (Record.size() < 3)
3268 return error("Invalid record");
3269 Type *Ty = getTypeByID(Record[0]);
3271 return error("Invalid record");
3272 auto *PTy = dyn_cast<PointerType>(Ty);
3274 return error("Invalid type for value");
3277 GlobalAlias::create(PTy->getElementType(), PTy->getAddressSpace(),
3278 getDecodedLinkage(Record[2]), "", TheModule);
3279 // Old bitcode files didn't have visibility field.
3280 // Local linkage must have default visibility.
3281 if (Record.size() > 3 && !NewGA->hasLocalLinkage())
3282 // FIXME: Change to an error if non-default in 4.0.
3283 NewGA->setVisibility(getDecodedVisibility(Record[3]));
3284 if (Record.size() > 4)
3285 NewGA->setDLLStorageClass(getDecodedDLLStorageClass(Record[4]));
3287 upgradeDLLImportExportLinkage(NewGA, Record[2]);
3288 if (Record.size() > 5)
3289 NewGA->setThreadLocalMode(getDecodedThreadLocalMode(Record[5]));
3290 if (Record.size() > 6)
3291 NewGA->setUnnamedAddr(Record[6]);
3292 ValueList.push_back(NewGA);
3293 AliasInits.push_back(std::make_pair(NewGA, Record[1]));
3296 /// MODULE_CODE_PURGEVALS: [numvals]
3297 case bitc::MODULE_CODE_PURGEVALS:
3298 // Trim down the value list to the specified size.
3299 if (Record.size() < 1 || Record[0] > ValueList.size())
3300 return error("Invalid record");
3301 ValueList.shrinkTo(Record[0]);
3303 /// MODULE_CODE_VSTOFFSET: [offset]
3304 case bitc::MODULE_CODE_VSTOFFSET:
3305 if (Record.size() < 1)
3306 return error("Invalid record");
3307 VSTOffset = Record[0];
3315 BitcodeReader::parseBitcodeInto(std::unique_ptr<DataStreamer> Streamer,
3316 Module *M, bool ShouldLazyLoadMetadata) {
3319 if (std::error_code EC = initStream(std::move(Streamer)))
3322 // Sniff for the signature.
3323 if (Stream.Read(8) != 'B' ||
3324 Stream.Read(8) != 'C' ||
3325 Stream.Read(4) != 0x0 ||
3326 Stream.Read(4) != 0xC ||
3327 Stream.Read(4) != 0xE ||
3328 Stream.Read(4) != 0xD)
3329 return error("Invalid bitcode signature");
3331 // We expect a number of well-defined blocks, though we don't necessarily
3332 // need to understand them all.
3334 if (Stream.AtEndOfStream()) {
3335 // We didn't really read a proper Module.
3336 return error("Malformed IR file");
3339 BitstreamEntry Entry =
3340 Stream.advance(BitstreamCursor::AF_DontAutoprocessAbbrevs);
3342 if (Entry.Kind != BitstreamEntry::SubBlock)
3343 return error("Malformed block");
3345 if (Entry.ID == bitc::MODULE_BLOCK_ID)
3346 return parseModule(false, ShouldLazyLoadMetadata);
3348 if (Stream.SkipBlock())
3349 return error("Invalid record");
3353 ErrorOr<std::string> BitcodeReader::parseModuleTriple() {
3354 if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
3355 return error("Invalid record");
3357 SmallVector<uint64_t, 64> Record;
3360 // Read all the records for this module.
3362 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
3364 switch (Entry.Kind) {
3365 case BitstreamEntry::SubBlock: // Handled for us already.
3366 case BitstreamEntry::Error:
3367 return error("Malformed block");
3368 case BitstreamEntry::EndBlock:
3370 case BitstreamEntry::Record:
3371 // The interesting case.
3376 switch (Stream.readRecord(Entry.ID, Record)) {
3377 default: break; // Default behavior, ignore unknown content.
3378 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
3380 if (convertToString(Record, 0, S))
3381 return error("Invalid record");
3388 llvm_unreachable("Exit infinite loop");
3391 ErrorOr<std::string> BitcodeReader::parseTriple() {
3392 if (std::error_code EC = initStream(nullptr))
3395 // Sniff for the signature.
3396 if (Stream.Read(8) != 'B' ||
3397 Stream.Read(8) != 'C' ||
3398 Stream.Read(4) != 0x0 ||
3399 Stream.Read(4) != 0xC ||
3400 Stream.Read(4) != 0xE ||
3401 Stream.Read(4) != 0xD)
3402 return error("Invalid bitcode signature");
3404 // We expect a number of well-defined blocks, though we don't necessarily
3405 // need to understand them all.
3407 BitstreamEntry Entry = Stream.advance();
3409 switch (Entry.Kind) {
3410 case BitstreamEntry::Error:
3411 return error("Malformed block");
3412 case BitstreamEntry::EndBlock:
3413 return std::error_code();
3415 case BitstreamEntry::SubBlock:
3416 if (Entry.ID == bitc::MODULE_BLOCK_ID)
3417 return parseModuleTriple();
3419 // Ignore other sub-blocks.
3420 if (Stream.SkipBlock())
3421 return error("Malformed block");
3424 case BitstreamEntry::Record:
3425 Stream.skipRecord(Entry.ID);
3431 /// Parse metadata attachments.
3432 std::error_code BitcodeReader::parseMetadataAttachment(Function &F) {
3433 if (Stream.EnterSubBlock(bitc::METADATA_ATTACHMENT_ID))
3434 return error("Invalid record");
3436 SmallVector<uint64_t, 64> Record;
3438 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
3440 switch (Entry.Kind) {
3441 case BitstreamEntry::SubBlock: // Handled for us already.
3442 case BitstreamEntry::Error:
3443 return error("Malformed block");
3444 case BitstreamEntry::EndBlock:
3445 return std::error_code();
3446 case BitstreamEntry::Record:
3447 // The interesting case.
3451 // Read a metadata attachment record.
3453 switch (Stream.readRecord(Entry.ID, Record)) {
3454 default: // Default behavior: ignore.
3456 case bitc::METADATA_ATTACHMENT: {
3457 unsigned RecordLength = Record.size();
3459 return error("Invalid record");
3460 if (RecordLength % 2 == 0) {
3461 // A function attachment.
3462 for (unsigned I = 0; I != RecordLength; I += 2) {
3463 auto K = MDKindMap.find(Record[I]);
3464 if (K == MDKindMap.end())
3465 return error("Invalid ID");
3466 Metadata *MD = MDValueList.getValueFwdRef(Record[I + 1]);
3467 F.setMetadata(K->second, cast<MDNode>(MD));
3472 // An instruction attachment.
3473 Instruction *Inst = InstructionList[Record[0]];
3474 for (unsigned i = 1; i != RecordLength; i = i+2) {
3475 unsigned Kind = Record[i];
3476 DenseMap<unsigned, unsigned>::iterator I =
3477 MDKindMap.find(Kind);
3478 if (I == MDKindMap.end())
3479 return error("Invalid ID");
3480 Metadata *Node = MDValueList.getValueFwdRef(Record[i + 1]);
3481 if (isa<LocalAsMetadata>(Node))
3482 // Drop the attachment. This used to be legal, but there's no
3485 Inst->setMetadata(I->second, cast<MDNode>(Node));
3486 if (I->second == LLVMContext::MD_tbaa)
3487 InstsWithTBAATag.push_back(Inst);
3495 static std::error_code typeCheckLoadStoreInst(DiagnosticHandlerFunction DH,
3496 Type *ValType, Type *PtrType) {
3497 if (!isa<PointerType>(PtrType))
3498 return error(DH, "Load/Store operand is not a pointer type");
3499 Type *ElemType = cast<PointerType>(PtrType)->getElementType();
3501 if (ValType && ValType != ElemType)
3502 return error(DH, "Explicit load/store type does not match pointee type of "
3504 if (!PointerType::isLoadableOrStorableType(ElemType))
3505 return error(DH, "Cannot load/store from pointer");
3506 return std::error_code();
3509 /// Lazily parse the specified function body block.
3510 std::error_code BitcodeReader::parseFunctionBody(Function *F) {
3511 if (Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID))
3512 return error("Invalid record");
3514 InstructionList.clear();
3515 unsigned ModuleValueListSize = ValueList.size();
3516 unsigned ModuleMDValueListSize = MDValueList.size();
3518 // Add all the function arguments to the value table.
3519 for(Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
3520 ValueList.push_back(I);
3522 unsigned NextValueNo = ValueList.size();
3523 BasicBlock *CurBB = nullptr;
3524 unsigned CurBBNo = 0;
3527 auto getLastInstruction = [&]() -> Instruction * {
3528 if (CurBB && !CurBB->empty())
3529 return &CurBB->back();
3530 else if (CurBBNo && FunctionBBs[CurBBNo - 1] &&
3531 !FunctionBBs[CurBBNo - 1]->empty())
3532 return &FunctionBBs[CurBBNo - 1]->back();
3536 // Read all the records.
3537 SmallVector<uint64_t, 64> Record;
3539 BitstreamEntry Entry = Stream.advance();
3541 switch (Entry.Kind) {
3542 case BitstreamEntry::Error:
3543 return error("Malformed block");
3544 case BitstreamEntry::EndBlock:
3545 goto OutOfRecordLoop;
3547 case BitstreamEntry::SubBlock:
3549 default: // Skip unknown content.
3550 if (Stream.SkipBlock())
3551 return error("Invalid record");
3553 case bitc::CONSTANTS_BLOCK_ID:
3554 if (std::error_code EC = parseConstants())
3556 NextValueNo = ValueList.size();
3558 case bitc::VALUE_SYMTAB_BLOCK_ID:
3559 if (std::error_code EC = parseValueSymbolTable())
3562 case bitc::METADATA_ATTACHMENT_ID:
3563 if (std::error_code EC = parseMetadataAttachment(*F))
3566 case bitc::METADATA_BLOCK_ID:
3567 if (std::error_code EC = parseMetadata())
3570 case bitc::USELIST_BLOCK_ID:
3571 if (std::error_code EC = parseUseLists())
3577 case BitstreamEntry::Record:
3578 // The interesting case.
3584 Instruction *I = nullptr;
3585 unsigned BitCode = Stream.readRecord(Entry.ID, Record);
3587 default: // Default behavior: reject
3588 return error("Invalid value");
3589 case bitc::FUNC_CODE_DECLAREBLOCKS: { // DECLAREBLOCKS: [nblocks]
3590 if (Record.size() < 1 || Record[0] == 0)
3591 return error("Invalid record");
3592 // Create all the basic blocks for the function.
3593 FunctionBBs.resize(Record[0]);
3595 // See if anything took the address of blocks in this function.
3596 auto BBFRI = BasicBlockFwdRefs.find(F);
3597 if (BBFRI == BasicBlockFwdRefs.end()) {
3598 for (unsigned i = 0, e = FunctionBBs.size(); i != e; ++i)
3599 FunctionBBs[i] = BasicBlock::Create(Context, "", F);
3601 auto &BBRefs = BBFRI->second;
3602 // Check for invalid basic block references.
3603 if (BBRefs.size() > FunctionBBs.size())
3604 return error("Invalid ID");
3605 assert(!BBRefs.empty() && "Unexpected empty array");
3606 assert(!BBRefs.front() && "Invalid reference to entry block");
3607 for (unsigned I = 0, E = FunctionBBs.size(), RE = BBRefs.size(); I != E;
3609 if (I < RE && BBRefs[I]) {
3610 BBRefs[I]->insertInto(F);
3611 FunctionBBs[I] = BBRefs[I];
3613 FunctionBBs[I] = BasicBlock::Create(Context, "", F);
3616 // Erase from the table.
3617 BasicBlockFwdRefs.erase(BBFRI);
3620 CurBB = FunctionBBs[0];
3624 case bitc::FUNC_CODE_DEBUG_LOC_AGAIN: // DEBUG_LOC_AGAIN
3625 // This record indicates that the last instruction is at the same
3626 // location as the previous instruction with a location.
3627 I = getLastInstruction();
3630 return error("Invalid record");
3631 I->setDebugLoc(LastLoc);
3635 case bitc::FUNC_CODE_DEBUG_LOC: { // DEBUG_LOC: [line, col, scope, ia]
3636 I = getLastInstruction();
3637 if (!I || Record.size() < 4)
3638 return error("Invalid record");
3640 unsigned Line = Record[0], Col = Record[1];
3641 unsigned ScopeID = Record[2], IAID = Record[3];
3643 MDNode *Scope = nullptr, *IA = nullptr;
3644 if (ScopeID) Scope = cast<MDNode>(MDValueList.getValueFwdRef(ScopeID-1));
3645 if (IAID) IA = cast<MDNode>(MDValueList.getValueFwdRef(IAID-1));
3646 LastLoc = DebugLoc::get(Line, Col, Scope, IA);
3647 I->setDebugLoc(LastLoc);
3652 case bitc::FUNC_CODE_INST_BINOP: { // BINOP: [opval, ty, opval, opcode]
3655 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
3656 popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) ||
3657 OpNum+1 > Record.size())
3658 return error("Invalid record");
3660 int Opc = getDecodedBinaryOpcode(Record[OpNum++], LHS->getType());
3662 return error("Invalid record");
3663 I = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3664 InstructionList.push_back(I);
3665 if (OpNum < Record.size()) {
3666 if (Opc == Instruction::Add ||
3667 Opc == Instruction::Sub ||
3668 Opc == Instruction::Mul ||
3669 Opc == Instruction::Shl) {
3670 if (Record[OpNum] & (1 << bitc::OBO_NO_SIGNED_WRAP))
3671 cast<BinaryOperator>(I)->setHasNoSignedWrap(true);
3672 if (Record[OpNum] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
3673 cast<BinaryOperator>(I)->setHasNoUnsignedWrap(true);
3674 } else if (Opc == Instruction::SDiv ||
3675 Opc == Instruction::UDiv ||
3676 Opc == Instruction::LShr ||
3677 Opc == Instruction::AShr) {
3678 if (Record[OpNum] & (1 << bitc::PEO_EXACT))
3679 cast<BinaryOperator>(I)->setIsExact(true);
3680 } else if (isa<FPMathOperator>(I)) {
3681 FastMathFlags FMF = getDecodedFastMathFlags(Record[OpNum]);
3683 I->setFastMathFlags(FMF);
3689 case bitc::FUNC_CODE_INST_CAST: { // CAST: [opval, opty, destty, castopc]
3692 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
3693 OpNum+2 != Record.size())
3694 return error("Invalid record");
3696 Type *ResTy = getTypeByID(Record[OpNum]);
3697 int Opc = getDecodedCastOpcode(Record[OpNum + 1]);
3698 if (Opc == -1 || !ResTy)
3699 return error("Invalid record");
3700 Instruction *Temp = nullptr;
3701 if ((I = UpgradeBitCastInst(Opc, Op, ResTy, Temp))) {
3703 InstructionList.push_back(Temp);
3704 CurBB->getInstList().push_back(Temp);
3707 I = CastInst::Create((Instruction::CastOps)Opc, Op, ResTy);
3709 InstructionList.push_back(I);
3712 case bitc::FUNC_CODE_INST_INBOUNDS_GEP_OLD:
3713 case bitc::FUNC_CODE_INST_GEP_OLD:
3714 case bitc::FUNC_CODE_INST_GEP: { // GEP: type, [n x operands]
3720 if (BitCode == bitc::FUNC_CODE_INST_GEP) {
3721 InBounds = Record[OpNum++];
3722 Ty = getTypeByID(Record[OpNum++]);
3724 InBounds = BitCode == bitc::FUNC_CODE_INST_INBOUNDS_GEP_OLD;
3729 if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr))
3730 return error("Invalid record");
3733 Ty = cast<SequentialType>(BasePtr->getType()->getScalarType())
3736 cast<SequentialType>(BasePtr->getType()->getScalarType())
3739 "Explicit gep type does not match pointee type of pointer operand");
3741 SmallVector<Value*, 16> GEPIdx;
3742 while (OpNum != Record.size()) {
3744 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
3745 return error("Invalid record");
3746 GEPIdx.push_back(Op);
3749 I = GetElementPtrInst::Create(Ty, BasePtr, GEPIdx);
3751 InstructionList.push_back(I);
3753 cast<GetElementPtrInst>(I)->setIsInBounds(true);
3757 case bitc::FUNC_CODE_INST_EXTRACTVAL: {
3758 // EXTRACTVAL: [opty, opval, n x indices]
3761 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
3762 return error("Invalid record");
3764 unsigned RecSize = Record.size();
3765 if (OpNum == RecSize)
3766 return error("EXTRACTVAL: Invalid instruction with 0 indices");
3768 SmallVector<unsigned, 4> EXTRACTVALIdx;
3769 Type *CurTy = Agg->getType();
3770 for (; OpNum != RecSize; ++OpNum) {
3771 bool IsArray = CurTy->isArrayTy();
3772 bool IsStruct = CurTy->isStructTy();
3773 uint64_t Index = Record[OpNum];
3775 if (!IsStruct && !IsArray)
3776 return error("EXTRACTVAL: Invalid type");
3777 if ((unsigned)Index != Index)
3778 return error("Invalid value");
3779 if (IsStruct && Index >= CurTy->subtypes().size())
3780 return error("EXTRACTVAL: Invalid struct index");
3781 if (IsArray && Index >= CurTy->getArrayNumElements())
3782 return error("EXTRACTVAL: Invalid array index");
3783 EXTRACTVALIdx.push_back((unsigned)Index);
3786 CurTy = CurTy->subtypes()[Index];
3788 CurTy = CurTy->subtypes()[0];
3791 I = ExtractValueInst::Create(Agg, EXTRACTVALIdx);
3792 InstructionList.push_back(I);
3796 case bitc::FUNC_CODE_INST_INSERTVAL: {
3797 // INSERTVAL: [opty, opval, opty, opval, n x indices]
3800 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
3801 return error("Invalid record");
3803 if (getValueTypePair(Record, OpNum, NextValueNo, Val))
3804 return error("Invalid record");
3806 unsigned RecSize = Record.size();
3807 if (OpNum == RecSize)
3808 return error("INSERTVAL: Invalid instruction with 0 indices");
3810 SmallVector<unsigned, 4> INSERTVALIdx;
3811 Type *CurTy = Agg->getType();
3812 for (; OpNum != RecSize; ++OpNum) {
3813 bool IsArray = CurTy->isArrayTy();
3814 bool IsStruct = CurTy->isStructTy();
3815 uint64_t Index = Record[OpNum];
3817 if (!IsStruct && !IsArray)
3818 return error("INSERTVAL: Invalid type");
3819 if ((unsigned)Index != Index)
3820 return error("Invalid value");
3821 if (IsStruct && Index >= CurTy->subtypes().size())
3822 return error("INSERTVAL: Invalid struct index");
3823 if (IsArray && Index >= CurTy->getArrayNumElements())
3824 return error("INSERTVAL: Invalid array index");
3826 INSERTVALIdx.push_back((unsigned)Index);
3828 CurTy = CurTy->subtypes()[Index];
3830 CurTy = CurTy->subtypes()[0];
3833 if (CurTy != Val->getType())
3834 return error("Inserted value type doesn't match aggregate type");
3836 I = InsertValueInst::Create(Agg, Val, INSERTVALIdx);
3837 InstructionList.push_back(I);
3841 case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval]
3842 // obsolete form of select
3843 // handles select i1 ... in old bitcode
3845 Value *TrueVal, *FalseVal, *Cond;
3846 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
3847 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
3848 popValue(Record, OpNum, NextValueNo, Type::getInt1Ty(Context), Cond))
3849 return error("Invalid record");
3851 I = SelectInst::Create(Cond, TrueVal, FalseVal);
3852 InstructionList.push_back(I);
3856 case bitc::FUNC_CODE_INST_VSELECT: {// VSELECT: [ty,opval,opval,predty,pred]
3857 // new form of select
3858 // handles select i1 or select [N x i1]
3860 Value *TrueVal, *FalseVal, *Cond;
3861 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
3862 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
3863 getValueTypePair(Record, OpNum, NextValueNo, Cond))
3864 return error("Invalid record");
3866 // select condition can be either i1 or [N x i1]
3867 if (VectorType* vector_type =
3868 dyn_cast<VectorType>(Cond->getType())) {
3870 if (vector_type->getElementType() != Type::getInt1Ty(Context))
3871 return error("Invalid type for value");
3874 if (Cond->getType() != Type::getInt1Ty(Context))
3875 return error("Invalid type for value");
3878 I = SelectInst::Create(Cond, TrueVal, FalseVal);
3879 InstructionList.push_back(I);
3883 case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval]
3886 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
3887 getValueTypePair(Record, OpNum, NextValueNo, Idx))
3888 return error("Invalid record");
3889 if (!Vec->getType()->isVectorTy())
3890 return error("Invalid type for value");
3891 I = ExtractElementInst::Create(Vec, Idx);
3892 InstructionList.push_back(I);
3896 case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval]
3898 Value *Vec, *Elt, *Idx;
3899 if (getValueTypePair(Record, OpNum, NextValueNo, Vec))
3900 return error("Invalid record");
3901 if (!Vec->getType()->isVectorTy())
3902 return error("Invalid type for value");
3903 if (popValue(Record, OpNum, NextValueNo,
3904 cast<VectorType>(Vec->getType())->getElementType(), Elt) ||
3905 getValueTypePair(Record, OpNum, NextValueNo, Idx))
3906 return error("Invalid record");
3907 I = InsertElementInst::Create(Vec, Elt, Idx);
3908 InstructionList.push_back(I);
3912 case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval]
3914 Value *Vec1, *Vec2, *Mask;
3915 if (getValueTypePair(Record, OpNum, NextValueNo, Vec1) ||
3916 popValue(Record, OpNum, NextValueNo, Vec1->getType(), Vec2))
3917 return error("Invalid record");
3919 if (getValueTypePair(Record, OpNum, NextValueNo, Mask))
3920 return error("Invalid record");
3921 if (!Vec1->getType()->isVectorTy() || !Vec2->getType()->isVectorTy())
3922 return error("Invalid type for value");
3923 I = new ShuffleVectorInst(Vec1, Vec2, Mask);
3924 InstructionList.push_back(I);
3928 case bitc::FUNC_CODE_INST_CMP: // CMP: [opty, opval, opval, pred]
3929 // Old form of ICmp/FCmp returning bool
3930 // Existed to differentiate between icmp/fcmp and vicmp/vfcmp which were
3931 // both legal on vectors but had different behaviour.
3932 case bitc::FUNC_CODE_INST_CMP2: { // CMP2: [opty, opval, opval, pred]
3933 // FCmp/ICmp returning bool or vector of bool
3937 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
3938 popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS))
3939 return error("Invalid record");
3941 unsigned PredVal = Record[OpNum];
3942 bool IsFP = LHS->getType()->isFPOrFPVectorTy();
3944 if (IsFP && Record.size() > OpNum+1)
3945 FMF = getDecodedFastMathFlags(Record[++OpNum]);
3947 if (OpNum+1 != Record.size())
3948 return error("Invalid record");
3950 if (LHS->getType()->isFPOrFPVectorTy())
3951 I = new FCmpInst((FCmpInst::Predicate)PredVal, LHS, RHS);
3953 I = new ICmpInst((ICmpInst::Predicate)PredVal, LHS, RHS);
3956 I->setFastMathFlags(FMF);
3957 InstructionList.push_back(I);
3961 case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>]
3963 unsigned Size = Record.size();
3965 I = ReturnInst::Create(Context);
3966 InstructionList.push_back(I);
3971 Value *Op = nullptr;
3972 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
3973 return error("Invalid record");
3974 if (OpNum != Record.size())
3975 return error("Invalid record");
3977 I = ReturnInst::Create(Context, Op);
3978 InstructionList.push_back(I);
3981 case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#]
3982 if (Record.size() != 1 && Record.size() != 3)
3983 return error("Invalid record");
3984 BasicBlock *TrueDest = getBasicBlock(Record[0]);
3986 return error("Invalid record");
3988 if (Record.size() == 1) {
3989 I = BranchInst::Create(TrueDest);
3990 InstructionList.push_back(I);
3993 BasicBlock *FalseDest = getBasicBlock(Record[1]);
3994 Value *Cond = getValue(Record, 2, NextValueNo,
3995 Type::getInt1Ty(Context));
3996 if (!FalseDest || !Cond)
3997 return error("Invalid record");
3998 I = BranchInst::Create(TrueDest, FalseDest, Cond);
3999 InstructionList.push_back(I);
4003 case bitc::FUNC_CODE_INST_CLEANUPRET: { // CLEANUPRET: [val] or [val,bb#]
4004 if (Record.size() != 1 && Record.size() != 2)
4005 return error("Invalid record");
4007 Value *CleanupPad = getValue(Record, Idx++, NextValueNo,
4008 Type::getTokenTy(Context), OC_CleanupPad);
4010 return error("Invalid record");
4011 BasicBlock *UnwindDest = nullptr;
4012 if (Record.size() == 2) {
4013 UnwindDest = getBasicBlock(Record[Idx++]);
4015 return error("Invalid record");
4018 I = CleanupReturnInst::Create(cast<CleanupPadInst>(CleanupPad),
4020 InstructionList.push_back(I);
4023 case bitc::FUNC_CODE_INST_CATCHRET: { // CATCHRET: [val,bb#]
4024 if (Record.size() != 2)
4025 return error("Invalid record");
4027 Value *CatchPad = getValue(Record, Idx++, NextValueNo,
4028 Type::getTokenTy(Context), OC_CatchPad);
4030 return error("Invalid record");
4031 BasicBlock *BB = getBasicBlock(Record[Idx++]);
4033 return error("Invalid record");
4035 I = CatchReturnInst::Create(cast<CatchPadInst>(CatchPad), BB);
4036 InstructionList.push_back(I);
4039 case bitc::FUNC_CODE_INST_CATCHPAD: { // CATCHPAD: [bb#,bb#,num,(ty,val)*]
4040 if (Record.size() < 3)
4041 return error("Invalid record");
4043 BasicBlock *NormalBB = getBasicBlock(Record[Idx++]);
4045 return error("Invalid record");
4046 BasicBlock *UnwindBB = getBasicBlock(Record[Idx++]);
4048 return error("Invalid record");
4049 unsigned NumArgOperands = Record[Idx++];
4050 SmallVector<Value *, 2> Args;
4051 for (unsigned Op = 0; Op != NumArgOperands; ++Op) {
4053 if (getValueTypePair(Record, Idx, NextValueNo, Val))
4054 return error("Invalid record");
4055 Args.push_back(Val);
4057 if (Record.size() != Idx)
4058 return error("Invalid record");
4060 I = CatchPadInst::Create(NormalBB, UnwindBB, Args);
4061 InstructionList.push_back(I);
4064 case bitc::FUNC_CODE_INST_TERMINATEPAD: { // TERMINATEPAD: [bb#,num,(ty,val)*]
4065 if (Record.size() < 1)
4066 return error("Invalid record");
4068 bool HasUnwindDest = !!Record[Idx++];
4069 BasicBlock *UnwindDest = nullptr;
4070 if (HasUnwindDest) {
4071 if (Idx == Record.size())
4072 return error("Invalid record");
4073 UnwindDest = getBasicBlock(Record[Idx++]);
4075 return error("Invalid record");
4077 unsigned NumArgOperands = Record[Idx++];
4078 SmallVector<Value *, 2> Args;
4079 for (unsigned Op = 0; Op != NumArgOperands; ++Op) {
4081 if (getValueTypePair(Record, Idx, NextValueNo, Val))
4082 return error("Invalid record");
4083 Args.push_back(Val);
4085 if (Record.size() != Idx)
4086 return error("Invalid record");
4088 I = TerminatePadInst::Create(Context, UnwindDest, Args);
4089 InstructionList.push_back(I);
4092 case bitc::FUNC_CODE_INST_CLEANUPPAD: { // CLEANUPPAD: [num,(ty,val)*]
4093 if (Record.size() < 1)
4094 return error("Invalid record");
4096 unsigned NumArgOperands = Record[Idx++];
4097 SmallVector<Value *, 2> Args;
4098 for (unsigned Op = 0; Op != NumArgOperands; ++Op) {
4100 if (getValueTypePair(Record, Idx, NextValueNo, Val))
4101 return error("Invalid record");
4102 Args.push_back(Val);
4104 if (Record.size() != Idx)
4105 return error("Invalid record");
4107 I = CleanupPadInst::Create(Context, Args);
4108 InstructionList.push_back(I);
4111 case bitc::FUNC_CODE_INST_CATCHENDPAD: { // CATCHENDPADINST: [bb#] or []
4112 if (Record.size() > 1)
4113 return error("Invalid record");
4114 BasicBlock *BB = nullptr;
4115 if (Record.size() == 1) {
4116 BB = getBasicBlock(Record[0]);
4118 return error("Invalid record");
4120 I = CatchEndPadInst::Create(Context, BB);
4121 InstructionList.push_back(I);
4124 case bitc::FUNC_CODE_INST_CLEANUPENDPAD: { // CLEANUPENDPADINST: [val] or [val,bb#]
4125 if (Record.size() != 1 && Record.size() != 2)
4126 return error("Invalid record");
4128 Value *CleanupPad = getValue(Record, Idx++, NextValueNo,
4129 Type::getTokenTy(Context), OC_CleanupPad);
4131 return error("Invalid record");
4133 BasicBlock *BB = nullptr;
4134 if (Record.size() == 2) {
4135 BB = getBasicBlock(Record[Idx++]);
4137 return error("Invalid record");
4139 I = CleanupEndPadInst::Create(cast<CleanupPadInst>(CleanupPad), BB);
4140 InstructionList.push_back(I);
4143 case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, op0, op1, ...]
4145 if ((Record[0] >> 16) == SWITCH_INST_MAGIC) {
4146 // "New" SwitchInst format with case ranges. The changes to write this
4147 // format were reverted but we still recognize bitcode that uses it.
4148 // Hopefully someday we will have support for case ranges and can use
4149 // this format again.
4151 Type *OpTy = getTypeByID(Record[1]);
4152 unsigned ValueBitWidth = cast<IntegerType>(OpTy)->getBitWidth();
4154 Value *Cond = getValue(Record, 2, NextValueNo, OpTy);
4155 BasicBlock *Default = getBasicBlock(Record[3]);
4156 if (!OpTy || !Cond || !Default)
4157 return error("Invalid record");
4159 unsigned NumCases = Record[4];
4161 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
4162 InstructionList.push_back(SI);
4164 unsigned CurIdx = 5;
4165 for (unsigned i = 0; i != NumCases; ++i) {
4166 SmallVector<ConstantInt*, 1> CaseVals;
4167 unsigned NumItems = Record[CurIdx++];
4168 for (unsigned ci = 0; ci != NumItems; ++ci) {
4169 bool isSingleNumber = Record[CurIdx++];
4172 unsigned ActiveWords = 1;
4173 if (ValueBitWidth > 64)
4174 ActiveWords = Record[CurIdx++];
4175 Low = readWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords),
4177 CurIdx += ActiveWords;
4179 if (!isSingleNumber) {
4181 if (ValueBitWidth > 64)
4182 ActiveWords = Record[CurIdx++];
4183 APInt High = readWideAPInt(
4184 makeArrayRef(&Record[CurIdx], ActiveWords), ValueBitWidth);
4185 CurIdx += ActiveWords;
4187 // FIXME: It is not clear whether values in the range should be
4188 // compared as signed or unsigned values. The partially
4189 // implemented changes that used this format in the past used
4190 // unsigned comparisons.
4191 for ( ; Low.ule(High); ++Low)
4192 CaseVals.push_back(ConstantInt::get(Context, Low));
4194 CaseVals.push_back(ConstantInt::get(Context, Low));
4196 BasicBlock *DestBB = getBasicBlock(Record[CurIdx++]);
4197 for (SmallVector<ConstantInt*, 1>::iterator cvi = CaseVals.begin(),
4198 cve = CaseVals.end(); cvi != cve; ++cvi)
4199 SI->addCase(*cvi, DestBB);
4205 // Old SwitchInst format without case ranges.
4207 if (Record.size() < 3 || (Record.size() & 1) == 0)
4208 return error("Invalid record");
4209 Type *OpTy = getTypeByID(Record[0]);
4210 Value *Cond = getValue(Record, 1, NextValueNo, OpTy);
4211 BasicBlock *Default = getBasicBlock(Record[2]);
4212 if (!OpTy || !Cond || !Default)
4213 return error("Invalid record");
4214 unsigned NumCases = (Record.size()-3)/2;
4215 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
4216 InstructionList.push_back(SI);
4217 for (unsigned i = 0, e = NumCases; i != e; ++i) {
4218 ConstantInt *CaseVal =
4219 dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy));
4220 BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]);
4221 if (!CaseVal || !DestBB) {
4223 return error("Invalid record");
4225 SI->addCase(CaseVal, DestBB);
4230 case bitc::FUNC_CODE_INST_INDIRECTBR: { // INDIRECTBR: [opty, op0, op1, ...]
4231 if (Record.size() < 2)
4232 return error("Invalid record");
4233 Type *OpTy = getTypeByID(Record[0]);
4234 Value *Address = getValue(Record, 1, NextValueNo, OpTy);
4235 if (!OpTy || !Address)
4236 return error("Invalid record");
4237 unsigned NumDests = Record.size()-2;
4238 IndirectBrInst *IBI = IndirectBrInst::Create(Address, NumDests);
4239 InstructionList.push_back(IBI);
4240 for (unsigned i = 0, e = NumDests; i != e; ++i) {
4241 if (BasicBlock *DestBB = getBasicBlock(Record[2+i])) {
4242 IBI->addDestination(DestBB);
4245 return error("Invalid record");
4252 case bitc::FUNC_CODE_INST_INVOKE: {
4253 // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...]
4254 if (Record.size() < 4)
4255 return error("Invalid record");
4257 AttributeSet PAL = getAttributes(Record[OpNum++]);
4258 unsigned CCInfo = Record[OpNum++];
4259 BasicBlock *NormalBB = getBasicBlock(Record[OpNum++]);
4260 BasicBlock *UnwindBB = getBasicBlock(Record[OpNum++]);
4262 FunctionType *FTy = nullptr;
4263 if (CCInfo >> 13 & 1 &&
4264 !(FTy = dyn_cast<FunctionType>(getTypeByID(Record[OpNum++]))))
4265 return error("Explicit invoke type is not a function type");
4268 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
4269 return error("Invalid record");
4271 PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType());
4273 return error("Callee is not a pointer");
4275 FTy = dyn_cast<FunctionType>(CalleeTy->getElementType());
4277 return error("Callee is not of pointer to function type");
4278 } else if (CalleeTy->getElementType() != FTy)
4279 return error("Explicit invoke type does not match pointee type of "
4281 if (Record.size() < FTy->getNumParams() + OpNum)
4282 return error("Insufficient operands to call");
4284 SmallVector<Value*, 16> Ops;
4285 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
4286 Ops.push_back(getValue(Record, OpNum, NextValueNo,
4287 FTy->getParamType(i)));
4289 return error("Invalid record");
4292 if (!FTy->isVarArg()) {
4293 if (Record.size() != OpNum)
4294 return error("Invalid record");
4296 // Read type/value pairs for varargs params.
4297 while (OpNum != Record.size()) {
4299 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
4300 return error("Invalid record");
4305 I = InvokeInst::Create(Callee, NormalBB, UnwindBB, Ops);
4306 InstructionList.push_back(I);
4308 ->setCallingConv(static_cast<CallingConv::ID>(~(1U << 13) & CCInfo));
4309 cast<InvokeInst>(I)->setAttributes(PAL);
4312 case bitc::FUNC_CODE_INST_RESUME: { // RESUME: [opval]
4314 Value *Val = nullptr;
4315 if (getValueTypePair(Record, Idx, NextValueNo, Val))
4316 return error("Invalid record");
4317 I = ResumeInst::Create(Val);
4318 InstructionList.push_back(I);
4321 case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE
4322 I = new UnreachableInst(Context);
4323 InstructionList.push_back(I);
4325 case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...]
4326 if (Record.size() < 1 || ((Record.size()-1)&1))
4327 return error("Invalid record");
4328 Type *Ty = getTypeByID(Record[0]);
4330 return error("Invalid record");
4332 PHINode *PN = PHINode::Create(Ty, (Record.size()-1)/2);
4333 InstructionList.push_back(PN);
4335 for (unsigned i = 0, e = Record.size()-1; i != e; i += 2) {
4337 // With the new function encoding, it is possible that operands have
4338 // negative IDs (for forward references). Use a signed VBR
4339 // representation to keep the encoding small.
4341 V = getValueSigned(Record, 1+i, NextValueNo, Ty);
4343 V = getValue(Record, 1+i, NextValueNo, Ty);
4344 BasicBlock *BB = getBasicBlock(Record[2+i]);
4346 return error("Invalid record");
4347 PN->addIncoming(V, BB);
4353 case bitc::FUNC_CODE_INST_LANDINGPAD:
4354 case bitc::FUNC_CODE_INST_LANDINGPAD_OLD: {
4355 // LANDINGPAD: [ty, val, val, num, (id0,val0 ...)?]
4357 if (BitCode == bitc::FUNC_CODE_INST_LANDINGPAD) {
4358 if (Record.size() < 3)
4359 return error("Invalid record");
4361 assert(BitCode == bitc::FUNC_CODE_INST_LANDINGPAD_OLD);
4362 if (Record.size() < 4)
4363 return error("Invalid record");
4365 Type *Ty = getTypeByID(Record[Idx++]);
4367 return error("Invalid record");
4368 if (BitCode == bitc::FUNC_CODE_INST_LANDINGPAD_OLD) {
4369 Value *PersFn = nullptr;
4370 if (getValueTypePair(Record, Idx, NextValueNo, PersFn))
4371 return error("Invalid record");
4373 if (!F->hasPersonalityFn())
4374 F->setPersonalityFn(cast<Constant>(PersFn));
4375 else if (F->getPersonalityFn() != cast<Constant>(PersFn))
4376 return error("Personality function mismatch");
4379 bool IsCleanup = !!Record[Idx++];
4380 unsigned NumClauses = Record[Idx++];
4381 LandingPadInst *LP = LandingPadInst::Create(Ty, NumClauses);
4382 LP->setCleanup(IsCleanup);
4383 for (unsigned J = 0; J != NumClauses; ++J) {
4384 LandingPadInst::ClauseType CT =
4385 LandingPadInst::ClauseType(Record[Idx++]); (void)CT;
4388 if (getValueTypePair(Record, Idx, NextValueNo, Val)) {
4390 return error("Invalid record");
4393 assert((CT != LandingPadInst::Catch ||
4394 !isa<ArrayType>(Val->getType())) &&
4395 "Catch clause has a invalid type!");
4396 assert((CT != LandingPadInst::Filter ||
4397 isa<ArrayType>(Val->getType())) &&
4398 "Filter clause has invalid type!");
4399 LP->addClause(cast<Constant>(Val));
4403 InstructionList.push_back(I);
4407 case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, opty, op, align]
4408 if (Record.size() != 4)
4409 return error("Invalid record");
4410 uint64_t AlignRecord = Record[3];
4411 const uint64_t InAllocaMask = uint64_t(1) << 5;
4412 const uint64_t ExplicitTypeMask = uint64_t(1) << 6;
4413 // Reserve bit 7 for SwiftError flag.
4414 // const uint64_t SwiftErrorMask = uint64_t(1) << 7;
4415 const uint64_t FlagMask = InAllocaMask | ExplicitTypeMask;
4416 bool InAlloca = AlignRecord & InAllocaMask;
4417 Type *Ty = getTypeByID(Record[0]);
4418 if ((AlignRecord & ExplicitTypeMask) == 0) {
4419 auto *PTy = dyn_cast_or_null<PointerType>(Ty);
4421 return error("Old-style alloca with a non-pointer type");
4422 Ty = PTy->getElementType();
4424 Type *OpTy = getTypeByID(Record[1]);
4425 Value *Size = getFnValueByID(Record[2], OpTy);
4427 if (std::error_code EC =
4428 parseAlignmentValue(AlignRecord & ~FlagMask, Align)) {
4432 return error("Invalid record");
4433 AllocaInst *AI = new AllocaInst(Ty, Size, Align);
4434 AI->setUsedWithInAlloca(InAlloca);
4436 InstructionList.push_back(I);
4439 case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol]
4442 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
4443 (OpNum + 2 != Record.size() && OpNum + 3 != Record.size()))
4444 return error("Invalid record");
4447 if (OpNum + 3 == Record.size())
4448 Ty = getTypeByID(Record[OpNum++]);
4449 if (std::error_code EC =
4450 typeCheckLoadStoreInst(DiagnosticHandler, Ty, Op->getType()))
4453 Ty = cast<PointerType>(Op->getType())->getElementType();
4456 if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align))
4458 I = new LoadInst(Ty, Op, "", Record[OpNum + 1], Align);
4460 InstructionList.push_back(I);
4463 case bitc::FUNC_CODE_INST_LOADATOMIC: {
4464 // LOADATOMIC: [opty, op, align, vol, ordering, synchscope]
4467 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
4468 (OpNum + 4 != Record.size() && OpNum + 5 != Record.size()))
4469 return error("Invalid record");
4472 if (OpNum + 5 == Record.size())
4473 Ty = getTypeByID(Record[OpNum++]);
4474 if (std::error_code EC =
4475 typeCheckLoadStoreInst(DiagnosticHandler, Ty, Op->getType()))
4478 Ty = cast<PointerType>(Op->getType())->getElementType();
4480 AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]);
4481 if (Ordering == NotAtomic || Ordering == Release ||
4482 Ordering == AcquireRelease)
4483 return error("Invalid record");
4484 if (Ordering != NotAtomic && Record[OpNum] == 0)
4485 return error("Invalid record");
4486 SynchronizationScope SynchScope = getDecodedSynchScope(Record[OpNum + 3]);
4489 if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align))
4491 I = new LoadInst(Op, "", Record[OpNum+1], Align, Ordering, SynchScope);
4493 InstructionList.push_back(I);
4496 case bitc::FUNC_CODE_INST_STORE:
4497 case bitc::FUNC_CODE_INST_STORE_OLD: { // STORE2:[ptrty, ptr, val, align, vol]
4500 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
4501 (BitCode == bitc::FUNC_CODE_INST_STORE
4502 ? getValueTypePair(Record, OpNum, NextValueNo, Val)
4503 : popValue(Record, OpNum, NextValueNo,
4504 cast<PointerType>(Ptr->getType())->getElementType(),
4506 OpNum + 2 != Record.size())
4507 return error("Invalid record");
4509 if (std::error_code EC = typeCheckLoadStoreInst(
4510 DiagnosticHandler, Val->getType(), Ptr->getType()))
4513 if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align))
4515 I = new StoreInst(Val, Ptr, Record[OpNum+1], Align);
4516 InstructionList.push_back(I);
4519 case bitc::FUNC_CODE_INST_STOREATOMIC:
4520 case bitc::FUNC_CODE_INST_STOREATOMIC_OLD: {
4521 // STOREATOMIC: [ptrty, ptr, val, align, vol, ordering, synchscope]
4524 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
4525 (BitCode == bitc::FUNC_CODE_INST_STOREATOMIC
4526 ? getValueTypePair(Record, OpNum, NextValueNo, Val)
4527 : popValue(Record, OpNum, NextValueNo,
4528 cast<PointerType>(Ptr->getType())->getElementType(),
4530 OpNum + 4 != Record.size())
4531 return error("Invalid record");
4533 if (std::error_code EC = typeCheckLoadStoreInst(
4534 DiagnosticHandler, Val->getType(), Ptr->getType()))
4536 AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]);
4537 if (Ordering == NotAtomic || Ordering == Acquire ||
4538 Ordering == AcquireRelease)
4539 return error("Invalid record");
4540 SynchronizationScope SynchScope = getDecodedSynchScope(Record[OpNum + 3]);
4541 if (Ordering != NotAtomic && Record[OpNum] == 0)
4542 return error("Invalid record");
4545 if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align))
4547 I = new StoreInst(Val, Ptr, Record[OpNum+1], Align, Ordering, SynchScope);
4548 InstructionList.push_back(I);
4551 case bitc::FUNC_CODE_INST_CMPXCHG_OLD:
4552 case bitc::FUNC_CODE_INST_CMPXCHG: {
4553 // CMPXCHG:[ptrty, ptr, cmp, new, vol, successordering, synchscope,
4554 // failureordering?, isweak?]
4556 Value *Ptr, *Cmp, *New;
4557 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
4558 (BitCode == bitc::FUNC_CODE_INST_CMPXCHG
4559 ? getValueTypePair(Record, OpNum, NextValueNo, Cmp)
4560 : popValue(Record, OpNum, NextValueNo,
4561 cast<PointerType>(Ptr->getType())->getElementType(),
4563 popValue(Record, OpNum, NextValueNo, Cmp->getType(), New) ||
4564 Record.size() < OpNum + 3 || Record.size() > OpNum + 5)
4565 return error("Invalid record");
4566 AtomicOrdering SuccessOrdering = getDecodedOrdering(Record[OpNum + 1]);
4567 if (SuccessOrdering == NotAtomic || SuccessOrdering == Unordered)
4568 return error("Invalid record");
4569 SynchronizationScope SynchScope = getDecodedSynchScope(Record[OpNum + 2]);
4571 if (std::error_code EC = typeCheckLoadStoreInst(
4572 DiagnosticHandler, Cmp->getType(), Ptr->getType()))
4574 AtomicOrdering FailureOrdering;
4575 if (Record.size() < 7)
4577 AtomicCmpXchgInst::getStrongestFailureOrdering(SuccessOrdering);
4579 FailureOrdering = getDecodedOrdering(Record[OpNum + 3]);
4581 I = new AtomicCmpXchgInst(Ptr, Cmp, New, SuccessOrdering, FailureOrdering,
4583 cast<AtomicCmpXchgInst>(I)->setVolatile(Record[OpNum]);
4585 if (Record.size() < 8) {
4586 // Before weak cmpxchgs existed, the instruction simply returned the
4587 // value loaded from memory, so bitcode files from that era will be
4588 // expecting the first component of a modern cmpxchg.
4589 CurBB->getInstList().push_back(I);
4590 I = ExtractValueInst::Create(I, 0);
4592 cast<AtomicCmpXchgInst>(I)->setWeak(Record[OpNum+4]);
4595 InstructionList.push_back(I);
4598 case bitc::FUNC_CODE_INST_ATOMICRMW: {
4599 // ATOMICRMW:[ptrty, ptr, val, op, vol, ordering, synchscope]
4602 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
4603 popValue(Record, OpNum, NextValueNo,
4604 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
4605 OpNum+4 != Record.size())
4606 return error("Invalid record");
4607 AtomicRMWInst::BinOp Operation = getDecodedRMWOperation(Record[OpNum]);
4608 if (Operation < AtomicRMWInst::FIRST_BINOP ||
4609 Operation > AtomicRMWInst::LAST_BINOP)
4610 return error("Invalid record");
4611 AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]);
4612 if (Ordering == NotAtomic || Ordering == Unordered)
4613 return error("Invalid record");
4614 SynchronizationScope SynchScope = getDecodedSynchScope(Record[OpNum + 3]);
4615 I = new AtomicRMWInst(Operation, Ptr, Val, Ordering, SynchScope);
4616 cast<AtomicRMWInst>(I)->setVolatile(Record[OpNum+1]);
4617 InstructionList.push_back(I);
4620 case bitc::FUNC_CODE_INST_FENCE: { // FENCE:[ordering, synchscope]
4621 if (2 != Record.size())
4622 return error("Invalid record");
4623 AtomicOrdering Ordering = getDecodedOrdering(Record[0]);
4624 if (Ordering == NotAtomic || Ordering == Unordered ||
4625 Ordering == Monotonic)
4626 return error("Invalid record");
4627 SynchronizationScope SynchScope = getDecodedSynchScope(Record[1]);
4628 I = new FenceInst(Context, Ordering, SynchScope);
4629 InstructionList.push_back(I);
4632 case bitc::FUNC_CODE_INST_CALL: {
4633 // CALL: [paramattrs, cc, fnty, fnid, arg0, arg1...]
4634 if (Record.size() < 3)
4635 return error("Invalid record");
4638 AttributeSet PAL = getAttributes(Record[OpNum++]);
4639 unsigned CCInfo = Record[OpNum++];
4641 FunctionType *FTy = nullptr;
4642 if (CCInfo >> 15 & 1 &&
4643 !(FTy = dyn_cast<FunctionType>(getTypeByID(Record[OpNum++]))))
4644 return error("Explicit call type is not a function type");
4647 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
4648 return error("Invalid record");
4650 PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());
4652 return error("Callee is not a pointer type");
4654 FTy = dyn_cast<FunctionType>(OpTy->getElementType());
4656 return error("Callee is not of pointer to function type");
4657 } else if (OpTy->getElementType() != FTy)
4658 return error("Explicit call type does not match pointee type of "
4660 if (Record.size() < FTy->getNumParams() + OpNum)
4661 return error("Insufficient operands to call");
4663 SmallVector<Value*, 16> Args;
4664 // Read the fixed params.
4665 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
4666 if (FTy->getParamType(i)->isLabelTy())
4667 Args.push_back(getBasicBlock(Record[OpNum]));
4669 Args.push_back(getValue(Record, OpNum, NextValueNo,
4670 FTy->getParamType(i)));
4672 return error("Invalid record");
4675 // Read type/value pairs for varargs params.
4676 if (!FTy->isVarArg()) {
4677 if (OpNum != Record.size())
4678 return error("Invalid record");
4680 while (OpNum != Record.size()) {
4682 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
4683 return error("Invalid record");
4688 I = CallInst::Create(FTy, Callee, Args);
4689 InstructionList.push_back(I);
4690 cast<CallInst>(I)->setCallingConv(
4691 static_cast<CallingConv::ID>((~(1U << 14) & CCInfo) >> 1));
4692 CallInst::TailCallKind TCK = CallInst::TCK_None;
4694 TCK = CallInst::TCK_Tail;
4695 if (CCInfo & (1 << 14))
4696 TCK = CallInst::TCK_MustTail;
4697 cast<CallInst>(I)->setTailCallKind(TCK);
4698 cast<CallInst>(I)->setAttributes(PAL);
4701 case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty]
4702 if (Record.size() < 3)
4703 return error("Invalid record");
4704 Type *OpTy = getTypeByID(Record[0]);
4705 Value *Op = getValue(Record, 1, NextValueNo, OpTy);
4706 Type *ResTy = getTypeByID(Record[2]);
4707 if (!OpTy || !Op || !ResTy)
4708 return error("Invalid record");
4709 I = new VAArgInst(Op, ResTy);
4710 InstructionList.push_back(I);
4715 // Add instruction to end of current BB. If there is no current BB, reject
4719 return error("Invalid instruction with no BB");
4721 CurBB->getInstList().push_back(I);
4723 // If this was a terminator instruction, move to the next block.
4724 if (isa<TerminatorInst>(I)) {
4726 CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : nullptr;
4729 // Non-void values get registered in the value table for future use.
4730 if (I && !I->getType()->isVoidTy())
4731 if (ValueList.assignValue(I, NextValueNo++))
4732 return error("Invalid forward reference");
4737 // Check the function list for unresolved values.
4738 if (Argument *A = dyn_cast<Argument>(ValueList.back())) {
4739 if (!A->getParent()) {
4740 // We found at least one unresolved value. Nuke them all to avoid leaks.
4741 for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){
4742 if ((A = dyn_cast_or_null<Argument>(ValueList[i])) && !A->getParent()) {
4743 A->replaceAllUsesWith(UndefValue::get(A->getType()));
4747 return error("Never resolved value found in function");
4751 // FIXME: Check for unresolved forward-declared metadata references
4752 // and clean up leaks.
4754 // Trim the value list down to the size it was before we parsed this function.
4755 ValueList.shrinkTo(ModuleValueListSize);
4756 MDValueList.shrinkTo(ModuleMDValueListSize);
4757 std::vector<BasicBlock*>().swap(FunctionBBs);
4758 return std::error_code();
4761 /// Find the function body in the bitcode stream
4762 std::error_code BitcodeReader::findFunctionInStream(
4764 DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator) {
4765 while (DeferredFunctionInfoIterator->second == 0) {
4766 // This is the fallback handling for the old format bitcode that
4767 // didn't contain the function index in the VST. Assert if we end up
4768 // here for the new format (which is the only time the VSTOffset would
4770 assert(VSTOffset == 0);
4771 if (Stream.AtEndOfStream())
4772 return error("Could not find function in stream");
4773 // ParseModule will parse the next body in the stream and set its
4774 // position in the DeferredFunctionInfo map.
4775 if (std::error_code EC = parseModule(true))
4778 return std::error_code();
4781 //===----------------------------------------------------------------------===//
4782 // GVMaterializer implementation
4783 //===----------------------------------------------------------------------===//
4785 void BitcodeReader::releaseBuffer() { Buffer.release(); }
4787 std::error_code BitcodeReader::materialize(GlobalValue *GV) {
4788 if (std::error_code EC = materializeMetadata())
4791 Function *F = dyn_cast<Function>(GV);
4792 // If it's not a function or is already material, ignore the request.
4793 if (!F || !F->isMaterializable())
4794 return std::error_code();
4796 DenseMap<Function*, uint64_t>::iterator DFII = DeferredFunctionInfo.find(F);
4797 assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!");
4798 // If its position is recorded as 0, its body is somewhere in the stream
4799 // but we haven't seen it yet.
4800 if (DFII->second == 0)
4801 if (std::error_code EC = findFunctionInStream(F, DFII))
4804 // Move the bit stream to the saved position of the deferred function body.
4805 Stream.JumpToBit(DFII->second);
4807 if (std::error_code EC = parseFunctionBody(F))
4809 F->setIsMaterializable(false);
4814 // Upgrade any old intrinsic calls in the function.
4815 for (auto &I : UpgradedIntrinsics) {
4816 for (auto UI = I.first->user_begin(), UE = I.first->user_end(); UI != UE;) {
4819 if (CallInst *CI = dyn_cast<CallInst>(U))
4820 UpgradeIntrinsicCall(CI, I.second);
4824 // Bring in any functions that this function forward-referenced via
4826 return materializeForwardReferencedFunctions();
4829 bool BitcodeReader::isDematerializable(const GlobalValue *GV) const {
4830 const Function *F = dyn_cast<Function>(GV);
4831 if (!F || F->isDeclaration())
4834 // Dematerializing F would leave dangling references that wouldn't be
4835 // reconnected on re-materialization.
4836 if (BlockAddressesTaken.count(F))
4839 return DeferredFunctionInfo.count(const_cast<Function*>(F));
4842 void BitcodeReader::dematerialize(GlobalValue *GV) {
4843 Function *F = dyn_cast<Function>(GV);
4844 // If this function isn't dematerializable, this is a noop.
4845 if (!F || !isDematerializable(F))
4848 assert(DeferredFunctionInfo.count(F) && "No info to read function later?");
4850 // Just forget the function body, we can remat it later.
4851 F->dropAllReferences();
4852 F->setIsMaterializable(true);
4855 std::error_code BitcodeReader::materializeModule(Module *M) {
4856 assert(M == TheModule &&
4857 "Can only Materialize the Module this BitcodeReader is attached to.");
4859 if (std::error_code EC = materializeMetadata())
4862 // Promise to materialize all forward references.
4863 WillMaterializeAllForwardRefs = true;
4865 // Iterate over the module, deserializing any functions that are still on
4867 for (Module::iterator F = TheModule->begin(), E = TheModule->end();
4869 if (std::error_code EC = materialize(F))
4872 // At this point, if there are any function bodies, the current bit is
4873 // pointing to the END_BLOCK record after them. Now make sure the rest
4874 // of the bits in the module have been read.
4878 // Check that all block address forward references got resolved (as we
4880 if (!BasicBlockFwdRefs.empty())
4881 return error("Never resolved function from blockaddress");
4883 // Upgrade any intrinsic calls that slipped through (should not happen!) and
4884 // delete the old functions to clean up. We can't do this unless the entire
4885 // module is materialized because there could always be another function body
4886 // with calls to the old function.
4887 for (auto &I : UpgradedIntrinsics) {
4888 for (auto *U : I.first->users()) {
4889 if (CallInst *CI = dyn_cast<CallInst>(U))
4890 UpgradeIntrinsicCall(CI, I.second);
4892 if (!I.first->use_empty())
4893 I.first->replaceAllUsesWith(I.second);
4894 I.first->eraseFromParent();
4896 UpgradedIntrinsics.clear();
4898 for (unsigned I = 0, E = InstsWithTBAATag.size(); I < E; I++)
4899 UpgradeInstWithTBAATag(InstsWithTBAATag[I]);
4901 UpgradeDebugInfo(*M);
4902 return std::error_code();
4905 std::vector<StructType *> BitcodeReader::getIdentifiedStructTypes() const {
4906 return IdentifiedStructTypes;
4910 BitcodeReader::initStream(std::unique_ptr<DataStreamer> Streamer) {
4912 return initLazyStream(std::move(Streamer));
4913 return initStreamFromBuffer();
4916 std::error_code BitcodeReader::initStreamFromBuffer() {
4917 const unsigned char *BufPtr = (const unsigned char*)Buffer->getBufferStart();
4918 const unsigned char *BufEnd = BufPtr+Buffer->getBufferSize();
4920 if (Buffer->getBufferSize() & 3)
4921 return error("Invalid bitcode signature");
4923 // If we have a wrapper header, parse it and ignore the non-bc file contents.
4924 // The magic number is 0x0B17C0DE stored in little endian.
4925 if (isBitcodeWrapper(BufPtr, BufEnd))
4926 if (SkipBitcodeWrapperHeader(BufPtr, BufEnd, true))
4927 return error("Invalid bitcode wrapper header");
4929 StreamFile.reset(new BitstreamReader(BufPtr, BufEnd));
4930 Stream.init(&*StreamFile);
4932 return std::error_code();
4936 BitcodeReader::initLazyStream(std::unique_ptr<DataStreamer> Streamer) {
4937 // Check and strip off the bitcode wrapper; BitstreamReader expects never to
4940 llvm::make_unique<StreamingMemoryObject>(std::move(Streamer));
4941 StreamingMemoryObject &Bytes = *OwnedBytes;
4942 StreamFile = llvm::make_unique<BitstreamReader>(std::move(OwnedBytes));
4943 Stream.init(&*StreamFile);
4945 unsigned char buf[16];
4946 if (Bytes.readBytes(buf, 16, 0) != 16)
4947 return error("Invalid bitcode signature");
4949 if (!isBitcode(buf, buf + 16))
4950 return error("Invalid bitcode signature");
4952 if (isBitcodeWrapper(buf, buf + 4)) {
4953 const unsigned char *bitcodeStart = buf;
4954 const unsigned char *bitcodeEnd = buf + 16;
4955 SkipBitcodeWrapperHeader(bitcodeStart, bitcodeEnd, false);
4956 Bytes.dropLeadingBytes(bitcodeStart - buf);
4957 Bytes.setKnownObjectSize(bitcodeEnd - bitcodeStart);
4959 return std::error_code();
4963 class BitcodeErrorCategoryType : public std::error_category {
4964 const char *name() const LLVM_NOEXCEPT override {
4965 return "llvm.bitcode";
4967 std::string message(int IE) const override {
4968 BitcodeError E = static_cast<BitcodeError>(IE);
4970 case BitcodeError::InvalidBitcodeSignature:
4971 return "Invalid bitcode signature";
4972 case BitcodeError::CorruptedBitcode:
4973 return "Corrupted bitcode";
4975 llvm_unreachable("Unknown error type!");
4980 static ManagedStatic<BitcodeErrorCategoryType> ErrorCategory;
4982 const std::error_category &llvm::BitcodeErrorCategory() {
4983 return *ErrorCategory;
4986 //===----------------------------------------------------------------------===//
4987 // External interface
4988 //===----------------------------------------------------------------------===//
4990 static ErrorOr<std::unique_ptr<Module>>
4991 getBitcodeModuleImpl(std::unique_ptr<DataStreamer> Streamer, StringRef Name,
4992 BitcodeReader *R, LLVMContext &Context,
4993 bool MaterializeAll, bool ShouldLazyLoadMetadata) {
4994 std::unique_ptr<Module> M = make_unique<Module>(Name, Context);
4995 M->setMaterializer(R);
4997 auto cleanupOnError = [&](std::error_code EC) {
4998 R->releaseBuffer(); // Never take ownership on error.
5002 // Delay parsing Metadata if ShouldLazyLoadMetadata is true.
5003 if (std::error_code EC = R->parseBitcodeInto(std::move(Streamer), M.get(),
5004 ShouldLazyLoadMetadata))
5005 return cleanupOnError(EC);
5007 if (MaterializeAll) {
5008 // Read in the entire module, and destroy the BitcodeReader.
5009 if (std::error_code EC = M->materializeAllPermanently())
5010 return cleanupOnError(EC);
5012 // Resolve forward references from blockaddresses.
5013 if (std::error_code EC = R->materializeForwardReferencedFunctions())
5014 return cleanupOnError(EC);
5016 return std::move(M);
5019 /// \brief Get a lazy one-at-time loading module from bitcode.
5021 /// This isn't always used in a lazy context. In particular, it's also used by
5022 /// \a parseBitcodeFile(). If this is truly lazy, then we need to eagerly pull
5023 /// in forward-referenced functions from block address references.
5025 /// \param[in] MaterializeAll Set to \c true if we should materialize
5027 static ErrorOr<std::unique_ptr<Module>>
5028 getLazyBitcodeModuleImpl(std::unique_ptr<MemoryBuffer> &&Buffer,
5029 LLVMContext &Context, bool MaterializeAll,
5030 DiagnosticHandlerFunction DiagnosticHandler,
5031 bool ShouldLazyLoadMetadata = false) {
5033 new BitcodeReader(Buffer.get(), Context, DiagnosticHandler);
5035 ErrorOr<std::unique_ptr<Module>> Ret =
5036 getBitcodeModuleImpl(nullptr, Buffer->getBufferIdentifier(), R, Context,
5037 MaterializeAll, ShouldLazyLoadMetadata);
5041 Buffer.release(); // The BitcodeReader owns it now.
5045 ErrorOr<std::unique_ptr<Module>> llvm::getLazyBitcodeModule(
5046 std::unique_ptr<MemoryBuffer> &&Buffer, LLVMContext &Context,
5047 DiagnosticHandlerFunction DiagnosticHandler, bool ShouldLazyLoadMetadata) {
5048 return getLazyBitcodeModuleImpl(std::move(Buffer), Context, false,
5049 DiagnosticHandler, ShouldLazyLoadMetadata);
5052 ErrorOr<std::unique_ptr<Module>> llvm::getStreamedBitcodeModule(
5053 StringRef Name, std::unique_ptr<DataStreamer> Streamer,
5054 LLVMContext &Context, DiagnosticHandlerFunction DiagnosticHandler) {
5055 std::unique_ptr<Module> M = make_unique<Module>(Name, Context);
5056 BitcodeReader *R = new BitcodeReader(Context, DiagnosticHandler);
5058 return getBitcodeModuleImpl(std::move(Streamer), Name, R, Context, false,
5062 ErrorOr<std::unique_ptr<Module>>
5063 llvm::parseBitcodeFile(MemoryBufferRef Buffer, LLVMContext &Context,
5064 DiagnosticHandlerFunction DiagnosticHandler) {
5065 std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
5066 return getLazyBitcodeModuleImpl(std::move(Buf), Context, true,
5068 // TODO: Restore the use-lists to the in-memory state when the bitcode was
5069 // written. We must defer until the Module has been fully materialized.
5073 llvm::getBitcodeTargetTriple(MemoryBufferRef Buffer, LLVMContext &Context,
5074 DiagnosticHandlerFunction DiagnosticHandler) {
5075 std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
5076 auto R = llvm::make_unique<BitcodeReader>(Buf.release(), Context,
5078 ErrorOr<std::string> Triple = R->parseTriple();
5079 if (Triple.getError())
5081 return Triple.get();