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 class BitcodeReaderValueList {
45 std::vector<WeakVH> ValuePtrs;
47 /// ResolveConstants - As we resolve forward-referenced constants, we add
48 /// information about them to this vector. This allows us to resolve them in
49 /// bulk instead of resolving each reference at a time. See the code in
50 /// ResolveConstantForwardRefs for more information about this.
52 /// The key of this vector is the placeholder constant, the value is the slot
53 /// number that holds the resolved value.
54 typedef std::vector<std::pair<Constant*, unsigned> > ResolveConstantsTy;
55 ResolveConstantsTy ResolveConstants;
58 BitcodeReaderValueList(LLVMContext &C) : Context(C) {}
59 ~BitcodeReaderValueList() {
60 assert(ResolveConstants.empty() && "Constants not resolved?");
63 // vector compatibility methods
64 unsigned size() const { return ValuePtrs.size(); }
65 void resize(unsigned N) { ValuePtrs.resize(N); }
66 void push_back(Value *V) { ValuePtrs.emplace_back(V); }
69 assert(ResolveConstants.empty() && "Constants not resolved?");
73 Value *operator[](unsigned i) const {
74 assert(i < ValuePtrs.size());
78 Value *back() const { return ValuePtrs.back(); }
79 void pop_back() { ValuePtrs.pop_back(); }
80 bool empty() const { return ValuePtrs.empty(); }
81 void shrinkTo(unsigned N) {
82 assert(N <= size() && "Invalid shrinkTo request!");
86 Constant *getConstantFwdRef(unsigned Idx, Type *Ty);
87 Value *getValueFwdRef(unsigned Idx, Type *Ty);
89 void AssignValue(Value *V, unsigned Idx);
91 /// ResolveConstantForwardRefs - Once all constants are read, this method bulk
92 /// resolves any forward references.
93 void ResolveConstantForwardRefs();
96 class BitcodeReaderMDValueList {
101 std::vector<TrackingMDRef> MDValuePtrs;
103 LLVMContext &Context;
105 BitcodeReaderMDValueList(LLVMContext &C)
106 : NumFwdRefs(0), AnyFwdRefs(false), Context(C) {}
108 // vector compatibility methods
109 unsigned size() const { return MDValuePtrs.size(); }
110 void resize(unsigned N) { MDValuePtrs.resize(N); }
111 void push_back(Metadata *MD) { MDValuePtrs.emplace_back(MD); }
112 void clear() { MDValuePtrs.clear(); }
113 Metadata *back() const { return MDValuePtrs.back(); }
114 void pop_back() { MDValuePtrs.pop_back(); }
115 bool empty() const { return MDValuePtrs.empty(); }
117 Metadata *operator[](unsigned i) const {
118 assert(i < MDValuePtrs.size());
119 return MDValuePtrs[i];
122 void shrinkTo(unsigned N) {
123 assert(N <= size() && "Invalid shrinkTo request!");
124 MDValuePtrs.resize(N);
127 Metadata *getValueFwdRef(unsigned Idx);
128 void AssignValue(Metadata *MD, unsigned Idx);
129 void tryToResolveCycles();
132 class BitcodeReader : public GVMaterializer {
133 LLVMContext &Context;
134 DiagnosticHandlerFunction DiagnosticHandler;
136 std::unique_ptr<MemoryBuffer> Buffer;
137 std::unique_ptr<BitstreamReader> StreamFile;
138 BitstreamCursor Stream;
139 DataStreamer *LazyStreamer;
140 uint64_t NextUnreadBit;
141 bool SeenValueSymbolTable;
143 std::vector<Type*> TypeList;
144 BitcodeReaderValueList ValueList;
145 BitcodeReaderMDValueList MDValueList;
146 std::vector<Comdat *> ComdatList;
147 SmallVector<Instruction *, 64> InstructionList;
149 std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInits;
150 std::vector<std::pair<GlobalAlias*, unsigned> > AliasInits;
151 std::vector<std::pair<Function*, unsigned> > FunctionPrefixes;
152 std::vector<std::pair<Function*, unsigned> > FunctionPrologues;
154 SmallVector<Instruction*, 64> InstsWithTBAATag;
156 /// MAttributes - The set of attributes by index. Index zero in the
157 /// file is for null, and is thus not represented here. As such all indices
159 std::vector<AttributeSet> MAttributes;
161 /// \brief The set of attribute groups.
162 std::map<unsigned, AttributeSet> MAttributeGroups;
164 /// FunctionBBs - While parsing a function body, this is a list of the basic
165 /// blocks for the function.
166 std::vector<BasicBlock*> FunctionBBs;
168 // When reading the module header, this list is populated with functions that
169 // have bodies later in the file.
170 std::vector<Function*> FunctionsWithBodies;
172 // When intrinsic functions are encountered which require upgrading they are
173 // stored here with their replacement function.
174 typedef std::vector<std::pair<Function*, Function*> > UpgradedIntrinsicMap;
175 UpgradedIntrinsicMap UpgradedIntrinsics;
177 // Map the bitcode's custom MDKind ID to the Module's MDKind ID.
178 DenseMap<unsigned, unsigned> MDKindMap;
180 // Several operations happen after the module header has been read, but
181 // before function bodies are processed. This keeps track of whether
182 // we've done this yet.
183 bool SeenFirstFunctionBody;
185 /// DeferredFunctionInfo - When function bodies are initially scanned, this
186 /// map contains info about where to find deferred function body in the
188 DenseMap<Function*, uint64_t> DeferredFunctionInfo;
190 /// When Metadata block is initially scanned when parsing the module, we may
191 /// choose to defer parsing of the metadata. This vector contains info about
192 /// which Metadata blocks are deferred.
193 std::vector<uint64_t> DeferredMetadataInfo;
195 /// These are basic blocks forward-referenced by block addresses. They are
196 /// inserted lazily into functions when they're loaded. The basic block ID is
197 /// its index into the vector.
198 DenseMap<Function *, std::vector<BasicBlock *>> BasicBlockFwdRefs;
199 std::deque<Function *> BasicBlockFwdRefQueue;
201 /// UseRelativeIDs - Indicates that we are using a new encoding for
202 /// instruction operands where most operands in the current
203 /// FUNCTION_BLOCK are encoded relative to the instruction number,
204 /// for a more compact encoding. Some instruction operands are not
205 /// relative to the instruction ID: basic block numbers, and types.
206 /// Once the old style function blocks have been phased out, we would
207 /// not need this flag.
210 /// True if all functions will be materialized, negating the need to process
211 /// (e.g.) blockaddress forward references.
212 bool WillMaterializeAllForwardRefs;
214 /// Functions that have block addresses taken. This is usually empty.
215 SmallPtrSet<const Function *, 4> BlockAddressesTaken;
217 /// True if any Metadata block has been materialized.
218 bool IsMetadataMaterialized;
220 bool StripDebugInfo = false;
223 std::error_code Error(BitcodeError E, const Twine &Message);
224 std::error_code Error(BitcodeError E);
225 std::error_code Error(const Twine &Message);
227 explicit BitcodeReader(MemoryBuffer *buffer, LLVMContext &C,
228 DiagnosticHandlerFunction DiagnosticHandler);
229 explicit BitcodeReader(DataStreamer *streamer, LLVMContext &C,
230 DiagnosticHandlerFunction DiagnosticHandler);
231 ~BitcodeReader() override { FreeState(); }
233 std::error_code materializeForwardReferencedFunctions();
237 void releaseBuffer();
239 bool isDematerializable(const GlobalValue *GV) const override;
240 std::error_code materialize(GlobalValue *GV) override;
241 std::error_code materializeModule(Module *M) override;
242 std::vector<StructType *> getIdentifiedStructTypes() const override;
243 void dematerialize(GlobalValue *GV) override;
245 /// @brief Main interface to parsing a bitcode buffer.
246 /// @returns true if an error occurred.
247 std::error_code ParseBitcodeInto(Module *M,
248 bool ShouldLazyLoadMetadata = false);
250 /// @brief Cheap mechanism to just extract module triple
251 /// @returns true if an error occurred.
252 ErrorOr<std::string> parseTriple();
254 static uint64_t decodeSignRotatedValue(uint64_t V);
256 /// Materialize any deferred Metadata block.
257 std::error_code materializeMetadata() override;
259 void setStripDebugInfo() override;
262 std::vector<StructType *> IdentifiedStructTypes;
263 StructType *createIdentifiedStructType(LLVMContext &Context, StringRef Name);
264 StructType *createIdentifiedStructType(LLVMContext &Context);
266 Type *getTypeByID(unsigned ID);
267 Value *getFnValueByID(unsigned ID, Type *Ty) {
268 if (Ty && Ty->isMetadataTy())
269 return MetadataAsValue::get(Ty->getContext(), getFnMetadataByID(ID));
270 return ValueList.getValueFwdRef(ID, Ty);
272 Metadata *getFnMetadataByID(unsigned ID) {
273 return MDValueList.getValueFwdRef(ID);
275 BasicBlock *getBasicBlock(unsigned ID) const {
276 if (ID >= FunctionBBs.size()) return nullptr; // Invalid ID
277 return FunctionBBs[ID];
279 AttributeSet getAttributes(unsigned i) const {
280 if (i-1 < MAttributes.size())
281 return MAttributes[i-1];
282 return AttributeSet();
285 /// getValueTypePair - Read a value/type pair out of the specified record from
286 /// slot 'Slot'. Increment Slot past the number of slots used in the record.
287 /// Return true on failure.
288 bool getValueTypePair(SmallVectorImpl<uint64_t> &Record, unsigned &Slot,
289 unsigned InstNum, Value *&ResVal) {
290 if (Slot == Record.size()) return true;
291 unsigned ValNo = (unsigned)Record[Slot++];
292 // Adjust the ValNo, if it was encoded relative to the InstNum.
294 ValNo = InstNum - ValNo;
295 if (ValNo < InstNum) {
296 // If this is not a forward reference, just return the value we already
298 ResVal = getFnValueByID(ValNo, nullptr);
299 return ResVal == nullptr;
301 if (Slot == Record.size())
304 unsigned TypeNo = (unsigned)Record[Slot++];
305 ResVal = getFnValueByID(ValNo, getTypeByID(TypeNo));
306 return ResVal == nullptr;
309 /// popValue - Read a value out of the specified record from slot 'Slot'.
310 /// Increment Slot past the number of slots used by the value in the record.
311 /// Return true if there is an error.
312 bool popValue(SmallVectorImpl<uint64_t> &Record, unsigned &Slot,
313 unsigned InstNum, Type *Ty, Value *&ResVal) {
314 if (getValue(Record, Slot, InstNum, Ty, ResVal))
316 // All values currently take a single record slot.
321 /// getValue -- Like popValue, but does not increment the Slot number.
322 bool getValue(SmallVectorImpl<uint64_t> &Record, unsigned Slot,
323 unsigned InstNum, Type *Ty, Value *&ResVal) {
324 ResVal = getValue(Record, Slot, InstNum, Ty);
325 return ResVal == nullptr;
328 /// getValue -- Version of getValue that returns ResVal directly,
329 /// or 0 if there is an error.
330 Value *getValue(SmallVectorImpl<uint64_t> &Record, unsigned Slot,
331 unsigned InstNum, Type *Ty) {
332 if (Slot == Record.size()) return nullptr;
333 unsigned ValNo = (unsigned)Record[Slot];
334 // Adjust the ValNo, if it was encoded relative to the InstNum.
336 ValNo = InstNum - ValNo;
337 return getFnValueByID(ValNo, Ty);
340 /// getValueSigned -- Like getValue, but decodes signed VBRs.
341 Value *getValueSigned(SmallVectorImpl<uint64_t> &Record, unsigned Slot,
342 unsigned InstNum, Type *Ty) {
343 if (Slot == Record.size()) return nullptr;
344 unsigned ValNo = (unsigned)decodeSignRotatedValue(Record[Slot]);
345 // Adjust the ValNo, if it was encoded relative to the InstNum.
347 ValNo = InstNum - ValNo;
348 return getFnValueByID(ValNo, Ty);
351 /// Converts alignment exponent (i.e. power of two (or zero)) to the
352 /// corresponding alignment to use. If alignment is too large, returns
353 /// a corresponding error code.
354 std::error_code parseAlignmentValue(uint64_t Exponent, unsigned &Alignment);
355 std::error_code ParseAttrKind(uint64_t Code, Attribute::AttrKind *Kind);
356 std::error_code ParseModule(bool Resume, bool ShouldLazyLoadMetadata = false);
357 std::error_code ParseAttributeBlock();
358 std::error_code ParseAttributeGroupBlock();
359 std::error_code ParseTypeTable();
360 std::error_code ParseTypeTableBody();
362 std::error_code ParseValueSymbolTable();
363 std::error_code ParseConstants();
364 std::error_code RememberAndSkipFunctionBody();
365 /// Save the positions of the Metadata blocks and skip parsing the blocks.
366 std::error_code rememberAndSkipMetadata();
367 std::error_code ParseFunctionBody(Function *F);
368 std::error_code GlobalCleanup();
369 std::error_code ResolveGlobalAndAliasInits();
370 std::error_code ParseMetadata();
371 std::error_code ParseMetadataAttachment(Function &F);
372 ErrorOr<std::string> parseModuleTriple();
373 std::error_code ParseUseLists();
374 std::error_code InitStream();
375 std::error_code InitStreamFromBuffer();
376 std::error_code InitLazyStream();
377 std::error_code FindFunctionInStream(
379 DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator);
383 BitcodeDiagnosticInfo::BitcodeDiagnosticInfo(std::error_code EC,
384 DiagnosticSeverity Severity,
386 : DiagnosticInfo(DK_Bitcode, Severity), Msg(Msg), EC(EC) {}
388 void BitcodeDiagnosticInfo::print(DiagnosticPrinter &DP) const { DP << Msg; }
390 static std::error_code Error(DiagnosticHandlerFunction DiagnosticHandler,
391 std::error_code EC, const Twine &Message) {
392 BitcodeDiagnosticInfo DI(EC, DS_Error, Message);
393 DiagnosticHandler(DI);
397 static std::error_code Error(DiagnosticHandlerFunction DiagnosticHandler,
398 std::error_code EC) {
399 return Error(DiagnosticHandler, EC, EC.message());
402 static std::error_code Error(DiagnosticHandlerFunction DiagnosticHandler,
403 const Twine &Message) {
404 return Error(DiagnosticHandler,
405 make_error_code(BitcodeError::CorruptedBitcode), Message);
408 std::error_code BitcodeReader::Error(BitcodeError E, const Twine &Message) {
409 return ::Error(DiagnosticHandler, make_error_code(E), Message);
412 std::error_code BitcodeReader::Error(const Twine &Message) {
413 return ::Error(DiagnosticHandler,
414 make_error_code(BitcodeError::CorruptedBitcode), Message);
417 std::error_code BitcodeReader::Error(BitcodeError E) {
418 return ::Error(DiagnosticHandler, make_error_code(E));
421 static DiagnosticHandlerFunction getDiagHandler(DiagnosticHandlerFunction F,
425 return [&C](const DiagnosticInfo &DI) { C.diagnose(DI); };
428 BitcodeReader::BitcodeReader(MemoryBuffer *buffer, LLVMContext &C,
429 DiagnosticHandlerFunction DiagnosticHandler)
430 : Context(C), DiagnosticHandler(getDiagHandler(DiagnosticHandler, C)),
431 TheModule(nullptr), Buffer(buffer), LazyStreamer(nullptr),
432 NextUnreadBit(0), SeenValueSymbolTable(false), ValueList(C),
433 MDValueList(C), SeenFirstFunctionBody(false), UseRelativeIDs(false),
434 WillMaterializeAllForwardRefs(false), IsMetadataMaterialized(false) {}
436 BitcodeReader::BitcodeReader(DataStreamer *streamer, LLVMContext &C,
437 DiagnosticHandlerFunction DiagnosticHandler)
438 : Context(C), DiagnosticHandler(getDiagHandler(DiagnosticHandler, C)),
439 TheModule(nullptr), Buffer(nullptr), LazyStreamer(streamer),
440 NextUnreadBit(0), SeenValueSymbolTable(false), ValueList(C),
441 MDValueList(C), SeenFirstFunctionBody(false), UseRelativeIDs(false),
442 WillMaterializeAllForwardRefs(false), IsMetadataMaterialized(false) {}
444 std::error_code BitcodeReader::materializeForwardReferencedFunctions() {
445 if (WillMaterializeAllForwardRefs)
446 return std::error_code();
448 // Prevent recursion.
449 WillMaterializeAllForwardRefs = true;
451 while (!BasicBlockFwdRefQueue.empty()) {
452 Function *F = BasicBlockFwdRefQueue.front();
453 BasicBlockFwdRefQueue.pop_front();
454 assert(F && "Expected valid function");
455 if (!BasicBlockFwdRefs.count(F))
456 // Already materialized.
459 // Check for a function that isn't materializable to prevent an infinite
460 // loop. When parsing a blockaddress stored in a global variable, there
461 // isn't a trivial way to check if a function will have a body without a
462 // linear search through FunctionsWithBodies, so just check it here.
463 if (!F->isMaterializable())
464 return Error("Never resolved function from blockaddress");
466 // Try to materialize F.
467 if (std::error_code EC = materialize(F))
470 assert(BasicBlockFwdRefs.empty() && "Function missing from queue");
473 WillMaterializeAllForwardRefs = false;
474 return std::error_code();
477 void BitcodeReader::FreeState() {
479 std::vector<Type*>().swap(TypeList);
482 std::vector<Comdat *>().swap(ComdatList);
484 std::vector<AttributeSet>().swap(MAttributes);
485 std::vector<BasicBlock*>().swap(FunctionBBs);
486 std::vector<Function*>().swap(FunctionsWithBodies);
487 DeferredFunctionInfo.clear();
488 DeferredMetadataInfo.clear();
491 assert(BasicBlockFwdRefs.empty() && "Unresolved blockaddress fwd references");
492 BasicBlockFwdRefQueue.clear();
495 //===----------------------------------------------------------------------===//
496 // Helper functions to implement forward reference resolution, etc.
497 //===----------------------------------------------------------------------===//
499 /// ConvertToString - Convert a string from a record into an std::string, return
501 template<typename StrTy>
502 static bool ConvertToString(ArrayRef<uint64_t> Record, unsigned Idx,
504 if (Idx > Record.size())
507 for (unsigned i = Idx, e = Record.size(); i != e; ++i)
508 Result += (char)Record[i];
512 static bool hasImplicitComdat(size_t Val) {
516 case 1: // Old WeakAnyLinkage
517 case 4: // Old LinkOnceAnyLinkage
518 case 10: // Old WeakODRLinkage
519 case 11: // Old LinkOnceODRLinkage
524 static GlobalValue::LinkageTypes getDecodedLinkage(unsigned Val) {
526 default: // Map unknown/new linkages to external
528 return GlobalValue::ExternalLinkage;
530 return GlobalValue::AppendingLinkage;
532 return GlobalValue::InternalLinkage;
534 return GlobalValue::ExternalLinkage; // Obsolete DLLImportLinkage
536 return GlobalValue::ExternalLinkage; // Obsolete DLLExportLinkage
538 return GlobalValue::ExternalWeakLinkage;
540 return GlobalValue::CommonLinkage;
542 return GlobalValue::PrivateLinkage;
544 return GlobalValue::AvailableExternallyLinkage;
546 return GlobalValue::PrivateLinkage; // Obsolete LinkerPrivateLinkage
548 return GlobalValue::PrivateLinkage; // Obsolete LinkerPrivateWeakLinkage
550 return GlobalValue::ExternalLinkage; // Obsolete LinkOnceODRAutoHideLinkage
551 case 1: // Old value with implicit comdat.
553 return GlobalValue::WeakAnyLinkage;
554 case 10: // Old value with implicit comdat.
556 return GlobalValue::WeakODRLinkage;
557 case 4: // Old value with implicit comdat.
559 return GlobalValue::LinkOnceAnyLinkage;
560 case 11: // Old value with implicit comdat.
562 return GlobalValue::LinkOnceODRLinkage;
566 static GlobalValue::VisibilityTypes GetDecodedVisibility(unsigned Val) {
568 default: // Map unknown visibilities to default.
569 case 0: return GlobalValue::DefaultVisibility;
570 case 1: return GlobalValue::HiddenVisibility;
571 case 2: return GlobalValue::ProtectedVisibility;
575 static GlobalValue::DLLStorageClassTypes
576 GetDecodedDLLStorageClass(unsigned Val) {
578 default: // Map unknown values to default.
579 case 0: return GlobalValue::DefaultStorageClass;
580 case 1: return GlobalValue::DLLImportStorageClass;
581 case 2: return GlobalValue::DLLExportStorageClass;
585 static GlobalVariable::ThreadLocalMode GetDecodedThreadLocalMode(unsigned Val) {
587 case 0: return GlobalVariable::NotThreadLocal;
588 default: // Map unknown non-zero value to general dynamic.
589 case 1: return GlobalVariable::GeneralDynamicTLSModel;
590 case 2: return GlobalVariable::LocalDynamicTLSModel;
591 case 3: return GlobalVariable::InitialExecTLSModel;
592 case 4: return GlobalVariable::LocalExecTLSModel;
596 static int GetDecodedCastOpcode(unsigned Val) {
599 case bitc::CAST_TRUNC : return Instruction::Trunc;
600 case bitc::CAST_ZEXT : return Instruction::ZExt;
601 case bitc::CAST_SEXT : return Instruction::SExt;
602 case bitc::CAST_FPTOUI : return Instruction::FPToUI;
603 case bitc::CAST_FPTOSI : return Instruction::FPToSI;
604 case bitc::CAST_UITOFP : return Instruction::UIToFP;
605 case bitc::CAST_SITOFP : return Instruction::SIToFP;
606 case bitc::CAST_FPTRUNC : return Instruction::FPTrunc;
607 case bitc::CAST_FPEXT : return Instruction::FPExt;
608 case bitc::CAST_PTRTOINT: return Instruction::PtrToInt;
609 case bitc::CAST_INTTOPTR: return Instruction::IntToPtr;
610 case bitc::CAST_BITCAST : return Instruction::BitCast;
611 case bitc::CAST_ADDRSPACECAST: return Instruction::AddrSpaceCast;
615 static int GetDecodedBinaryOpcode(unsigned Val, Type *Ty) {
616 bool IsFP = Ty->isFPOrFPVectorTy();
617 // BinOps are only valid for int/fp or vector of int/fp types
618 if (!IsFP && !Ty->isIntOrIntVectorTy())
624 case bitc::BINOP_ADD:
625 return IsFP ? Instruction::FAdd : Instruction::Add;
626 case bitc::BINOP_SUB:
627 return IsFP ? Instruction::FSub : Instruction::Sub;
628 case bitc::BINOP_MUL:
629 return IsFP ? Instruction::FMul : Instruction::Mul;
630 case bitc::BINOP_UDIV:
631 return IsFP ? -1 : Instruction::UDiv;
632 case bitc::BINOP_SDIV:
633 return IsFP ? Instruction::FDiv : Instruction::SDiv;
634 case bitc::BINOP_UREM:
635 return IsFP ? -1 : Instruction::URem;
636 case bitc::BINOP_SREM:
637 return IsFP ? Instruction::FRem : Instruction::SRem;
638 case bitc::BINOP_SHL:
639 return IsFP ? -1 : Instruction::Shl;
640 case bitc::BINOP_LSHR:
641 return IsFP ? -1 : Instruction::LShr;
642 case bitc::BINOP_ASHR:
643 return IsFP ? -1 : Instruction::AShr;
644 case bitc::BINOP_AND:
645 return IsFP ? -1 : Instruction::And;
647 return IsFP ? -1 : Instruction::Or;
648 case bitc::BINOP_XOR:
649 return IsFP ? -1 : Instruction::Xor;
653 static AtomicRMWInst::BinOp GetDecodedRMWOperation(unsigned Val) {
655 default: return AtomicRMWInst::BAD_BINOP;
656 case bitc::RMW_XCHG: return AtomicRMWInst::Xchg;
657 case bitc::RMW_ADD: return AtomicRMWInst::Add;
658 case bitc::RMW_SUB: return AtomicRMWInst::Sub;
659 case bitc::RMW_AND: return AtomicRMWInst::And;
660 case bitc::RMW_NAND: return AtomicRMWInst::Nand;
661 case bitc::RMW_OR: return AtomicRMWInst::Or;
662 case bitc::RMW_XOR: return AtomicRMWInst::Xor;
663 case bitc::RMW_MAX: return AtomicRMWInst::Max;
664 case bitc::RMW_MIN: return AtomicRMWInst::Min;
665 case bitc::RMW_UMAX: return AtomicRMWInst::UMax;
666 case bitc::RMW_UMIN: return AtomicRMWInst::UMin;
670 static AtomicOrdering GetDecodedOrdering(unsigned Val) {
672 case bitc::ORDERING_NOTATOMIC: return NotAtomic;
673 case bitc::ORDERING_UNORDERED: return Unordered;
674 case bitc::ORDERING_MONOTONIC: return Monotonic;
675 case bitc::ORDERING_ACQUIRE: return Acquire;
676 case bitc::ORDERING_RELEASE: return Release;
677 case bitc::ORDERING_ACQREL: return AcquireRelease;
678 default: // Map unknown orderings to sequentially-consistent.
679 case bitc::ORDERING_SEQCST: return SequentiallyConsistent;
683 static SynchronizationScope GetDecodedSynchScope(unsigned Val) {
685 case bitc::SYNCHSCOPE_SINGLETHREAD: return SingleThread;
686 default: // Map unknown scopes to cross-thread.
687 case bitc::SYNCHSCOPE_CROSSTHREAD: return CrossThread;
691 static Comdat::SelectionKind getDecodedComdatSelectionKind(unsigned Val) {
693 default: // Map unknown selection kinds to any.
694 case bitc::COMDAT_SELECTION_KIND_ANY:
696 case bitc::COMDAT_SELECTION_KIND_EXACT_MATCH:
697 return Comdat::ExactMatch;
698 case bitc::COMDAT_SELECTION_KIND_LARGEST:
699 return Comdat::Largest;
700 case bitc::COMDAT_SELECTION_KIND_NO_DUPLICATES:
701 return Comdat::NoDuplicates;
702 case bitc::COMDAT_SELECTION_KIND_SAME_SIZE:
703 return Comdat::SameSize;
707 static void UpgradeDLLImportExportLinkage(llvm::GlobalValue *GV, unsigned Val) {
709 case 5: GV->setDLLStorageClass(GlobalValue::DLLImportStorageClass); break;
710 case 6: GV->setDLLStorageClass(GlobalValue::DLLExportStorageClass); break;
716 /// @brief A class for maintaining the slot number definition
717 /// as a placeholder for the actual definition for forward constants defs.
718 class ConstantPlaceHolder : public ConstantExpr {
719 void operator=(const ConstantPlaceHolder &) = delete;
721 // allocate space for exactly one operand
722 void *operator new(size_t s) {
723 return User::operator new(s, 1);
725 explicit ConstantPlaceHolder(Type *Ty, LLVMContext& Context)
726 : ConstantExpr(Ty, Instruction::UserOp1, &Op<0>(), 1) {
727 Op<0>() = UndefValue::get(Type::getInt32Ty(Context));
730 /// @brief Methods to support type inquiry through isa, cast, and dyn_cast.
731 static bool classof(const Value *V) {
732 return isa<ConstantExpr>(V) &&
733 cast<ConstantExpr>(V)->getOpcode() == Instruction::UserOp1;
737 /// Provide fast operand accessors
738 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
742 // FIXME: can we inherit this from ConstantExpr?
744 struct OperandTraits<ConstantPlaceHolder> :
745 public FixedNumOperandTraits<ConstantPlaceHolder, 1> {
747 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ConstantPlaceHolder, Value)
751 void BitcodeReaderValueList::AssignValue(Value *V, unsigned Idx) {
760 WeakVH &OldV = ValuePtrs[Idx];
766 // Handle constants and non-constants (e.g. instrs) differently for
768 if (Constant *PHC = dyn_cast<Constant>(&*OldV)) {
769 ResolveConstants.push_back(std::make_pair(PHC, Idx));
772 // If there was a forward reference to this value, replace it.
773 Value *PrevVal = OldV;
774 OldV->replaceAllUsesWith(V);
780 Constant *BitcodeReaderValueList::getConstantFwdRef(unsigned Idx,
785 if (Value *V = ValuePtrs[Idx]) {
786 if (Ty != V->getType())
787 report_fatal_error("Type mismatch in constant table!");
788 return cast<Constant>(V);
791 // Create and return a placeholder, which will later be RAUW'd.
792 Constant *C = new ConstantPlaceHolder(Ty, Context);
797 Value *BitcodeReaderValueList::getValueFwdRef(unsigned Idx, Type *Ty) {
798 // Bail out for a clearly invalid value. This would make us call resize(0)
805 if (Value *V = ValuePtrs[Idx]) {
806 // If the types don't match, it's invalid.
807 if (Ty && Ty != V->getType())
812 // No type specified, must be invalid reference.
813 if (!Ty) return nullptr;
815 // Create and return a placeholder, which will later be RAUW'd.
816 Value *V = new Argument(Ty);
821 /// ResolveConstantForwardRefs - Once all constants are read, this method bulk
822 /// resolves any forward references. The idea behind this is that we sometimes
823 /// get constants (such as large arrays) which reference *many* forward ref
824 /// constants. Replacing each of these causes a lot of thrashing when
825 /// building/reuniquing the constant. Instead of doing this, we look at all the
826 /// uses and rewrite all the place holders at once for any constant that uses
828 void BitcodeReaderValueList::ResolveConstantForwardRefs() {
829 // Sort the values by-pointer so that they are efficient to look up with a
831 std::sort(ResolveConstants.begin(), ResolveConstants.end());
833 SmallVector<Constant*, 64> NewOps;
835 while (!ResolveConstants.empty()) {
836 Value *RealVal = operator[](ResolveConstants.back().second);
837 Constant *Placeholder = ResolveConstants.back().first;
838 ResolveConstants.pop_back();
840 // Loop over all users of the placeholder, updating them to reference the
841 // new value. If they reference more than one placeholder, update them all
843 while (!Placeholder->use_empty()) {
844 auto UI = Placeholder->user_begin();
847 // If the using object isn't uniqued, just update the operands. This
848 // handles instructions and initializers for global variables.
849 if (!isa<Constant>(U) || isa<GlobalValue>(U)) {
850 UI.getUse().set(RealVal);
854 // Otherwise, we have a constant that uses the placeholder. Replace that
855 // constant with a new constant that has *all* placeholder uses updated.
856 Constant *UserC = cast<Constant>(U);
857 for (User::op_iterator I = UserC->op_begin(), E = UserC->op_end();
860 if (!isa<ConstantPlaceHolder>(*I)) {
861 // Not a placeholder reference.
863 } else if (*I == Placeholder) {
864 // Common case is that it just references this one placeholder.
867 // Otherwise, look up the placeholder in ResolveConstants.
868 ResolveConstantsTy::iterator It =
869 std::lower_bound(ResolveConstants.begin(), ResolveConstants.end(),
870 std::pair<Constant*, unsigned>(cast<Constant>(*I),
872 assert(It != ResolveConstants.end() && It->first == *I);
873 NewOp = operator[](It->second);
876 NewOps.push_back(cast<Constant>(NewOp));
879 // Make the new constant.
881 if (ConstantArray *UserCA = dyn_cast<ConstantArray>(UserC)) {
882 NewC = ConstantArray::get(UserCA->getType(), NewOps);
883 } else if (ConstantStruct *UserCS = dyn_cast<ConstantStruct>(UserC)) {
884 NewC = ConstantStruct::get(UserCS->getType(), NewOps);
885 } else if (isa<ConstantVector>(UserC)) {
886 NewC = ConstantVector::get(NewOps);
888 assert(isa<ConstantExpr>(UserC) && "Must be a ConstantExpr.");
889 NewC = cast<ConstantExpr>(UserC)->getWithOperands(NewOps);
892 UserC->replaceAllUsesWith(NewC);
893 UserC->destroyConstant();
897 // Update all ValueHandles, they should be the only users at this point.
898 Placeholder->replaceAllUsesWith(RealVal);
903 void BitcodeReaderMDValueList::AssignValue(Metadata *MD, unsigned Idx) {
912 TrackingMDRef &OldMD = MDValuePtrs[Idx];
918 // If there was a forward reference to this value, replace it.
919 TempMDTuple PrevMD(cast<MDTuple>(OldMD.get()));
920 PrevMD->replaceAllUsesWith(MD);
924 Metadata *BitcodeReaderMDValueList::getValueFwdRef(unsigned Idx) {
928 if (Metadata *MD = MDValuePtrs[Idx])
931 // Track forward refs to be resolved later.
933 MinFwdRef = std::min(MinFwdRef, Idx);
934 MaxFwdRef = std::max(MaxFwdRef, Idx);
937 MinFwdRef = MaxFwdRef = Idx;
941 // Create and return a placeholder, which will later be RAUW'd.
942 Metadata *MD = MDNode::getTemporary(Context, None).release();
943 MDValuePtrs[Idx].reset(MD);
947 void BitcodeReaderMDValueList::tryToResolveCycles() {
953 // Still forward references... can't resolve cycles.
956 // Resolve any cycles.
957 for (unsigned I = MinFwdRef, E = MaxFwdRef + 1; I != E; ++I) {
958 auto &MD = MDValuePtrs[I];
959 auto *N = dyn_cast_or_null<MDNode>(MD);
963 assert(!N->isTemporary() && "Unexpected forward reference");
967 // Make sure we return early again until there's another forward ref.
971 Type *BitcodeReader::getTypeByID(unsigned ID) {
972 // The type table size is always specified correctly.
973 if (ID >= TypeList.size())
976 if (Type *Ty = TypeList[ID])
979 // If we have a forward reference, the only possible case is when it is to a
980 // named struct. Just create a placeholder for now.
981 return TypeList[ID] = createIdentifiedStructType(Context);
984 StructType *BitcodeReader::createIdentifiedStructType(LLVMContext &Context,
986 auto *Ret = StructType::create(Context, Name);
987 IdentifiedStructTypes.push_back(Ret);
991 StructType *BitcodeReader::createIdentifiedStructType(LLVMContext &Context) {
992 auto *Ret = StructType::create(Context);
993 IdentifiedStructTypes.push_back(Ret);
998 //===----------------------------------------------------------------------===//
999 // Functions for parsing blocks from the bitcode file
1000 //===----------------------------------------------------------------------===//
1003 /// \brief This fills an AttrBuilder object with the LLVM attributes that have
1004 /// been decoded from the given integer. This function must stay in sync with
1005 /// 'encodeLLVMAttributesForBitcode'.
1006 static void decodeLLVMAttributesForBitcode(AttrBuilder &B,
1007 uint64_t EncodedAttrs) {
1008 // FIXME: Remove in 4.0.
1010 // The alignment is stored as a 16-bit raw value from bits 31--16. We shift
1011 // the bits above 31 down by 11 bits.
1012 unsigned Alignment = (EncodedAttrs & (0xffffULL << 16)) >> 16;
1013 assert((!Alignment || isPowerOf2_32(Alignment)) &&
1014 "Alignment must be a power of two.");
1017 B.addAlignmentAttr(Alignment);
1018 B.addRawValue(((EncodedAttrs & (0xfffffULL << 32)) >> 11) |
1019 (EncodedAttrs & 0xffff));
1022 std::error_code BitcodeReader::ParseAttributeBlock() {
1023 if (Stream.EnterSubBlock(bitc::PARAMATTR_BLOCK_ID))
1024 return Error("Invalid record");
1026 if (!MAttributes.empty())
1027 return Error("Invalid multiple blocks");
1029 SmallVector<uint64_t, 64> Record;
1031 SmallVector<AttributeSet, 8> Attrs;
1033 // Read all the records.
1035 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1037 switch (Entry.Kind) {
1038 case BitstreamEntry::SubBlock: // Handled for us already.
1039 case BitstreamEntry::Error:
1040 return Error("Malformed block");
1041 case BitstreamEntry::EndBlock:
1042 return std::error_code();
1043 case BitstreamEntry::Record:
1044 // The interesting case.
1050 switch (Stream.readRecord(Entry.ID, Record)) {
1051 default: // Default behavior: ignore.
1053 case bitc::PARAMATTR_CODE_ENTRY_OLD: { // ENTRY: [paramidx0, attr0, ...]
1054 // FIXME: Remove in 4.0.
1055 if (Record.size() & 1)
1056 return Error("Invalid record");
1058 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
1060 decodeLLVMAttributesForBitcode(B, Record[i+1]);
1061 Attrs.push_back(AttributeSet::get(Context, Record[i], B));
1064 MAttributes.push_back(AttributeSet::get(Context, Attrs));
1068 case bitc::PARAMATTR_CODE_ENTRY: { // ENTRY: [attrgrp0, attrgrp1, ...]
1069 for (unsigned i = 0, e = Record.size(); i != e; ++i)
1070 Attrs.push_back(MAttributeGroups[Record[i]]);
1072 MAttributes.push_back(AttributeSet::get(Context, Attrs));
1080 // Returns Attribute::None on unrecognized codes.
1081 static Attribute::AttrKind GetAttrFromCode(uint64_t Code) {
1084 return Attribute::None;
1085 case bitc::ATTR_KIND_ALIGNMENT:
1086 return Attribute::Alignment;
1087 case bitc::ATTR_KIND_ALWAYS_INLINE:
1088 return Attribute::AlwaysInline;
1089 case bitc::ATTR_KIND_BUILTIN:
1090 return Attribute::Builtin;
1091 case bitc::ATTR_KIND_BY_VAL:
1092 return Attribute::ByVal;
1093 case bitc::ATTR_KIND_IN_ALLOCA:
1094 return Attribute::InAlloca;
1095 case bitc::ATTR_KIND_COLD:
1096 return Attribute::Cold;
1097 case bitc::ATTR_KIND_CONVERGENT:
1098 return Attribute::Convergent;
1099 case bitc::ATTR_KIND_INLINE_HINT:
1100 return Attribute::InlineHint;
1101 case bitc::ATTR_KIND_IN_REG:
1102 return Attribute::InReg;
1103 case bitc::ATTR_KIND_JUMP_TABLE:
1104 return Attribute::JumpTable;
1105 case bitc::ATTR_KIND_MIN_SIZE:
1106 return Attribute::MinSize;
1107 case bitc::ATTR_KIND_NAKED:
1108 return Attribute::Naked;
1109 case bitc::ATTR_KIND_NEST:
1110 return Attribute::Nest;
1111 case bitc::ATTR_KIND_NO_ALIAS:
1112 return Attribute::NoAlias;
1113 case bitc::ATTR_KIND_NO_BUILTIN:
1114 return Attribute::NoBuiltin;
1115 case bitc::ATTR_KIND_NO_CAPTURE:
1116 return Attribute::NoCapture;
1117 case bitc::ATTR_KIND_NO_DUPLICATE:
1118 return Attribute::NoDuplicate;
1119 case bitc::ATTR_KIND_NO_IMPLICIT_FLOAT:
1120 return Attribute::NoImplicitFloat;
1121 case bitc::ATTR_KIND_NO_INLINE:
1122 return Attribute::NoInline;
1123 case bitc::ATTR_KIND_NON_LAZY_BIND:
1124 return Attribute::NonLazyBind;
1125 case bitc::ATTR_KIND_NON_NULL:
1126 return Attribute::NonNull;
1127 case bitc::ATTR_KIND_DEREFERENCEABLE:
1128 return Attribute::Dereferenceable;
1129 case bitc::ATTR_KIND_DEREFERENCEABLE_OR_NULL:
1130 return Attribute::DereferenceableOrNull;
1131 case bitc::ATTR_KIND_NO_RED_ZONE:
1132 return Attribute::NoRedZone;
1133 case bitc::ATTR_KIND_NO_RETURN:
1134 return Attribute::NoReturn;
1135 case bitc::ATTR_KIND_NO_UNWIND:
1136 return Attribute::NoUnwind;
1137 case bitc::ATTR_KIND_OPTIMIZE_FOR_SIZE:
1138 return Attribute::OptimizeForSize;
1139 case bitc::ATTR_KIND_OPTIMIZE_NONE:
1140 return Attribute::OptimizeNone;
1141 case bitc::ATTR_KIND_READ_NONE:
1142 return Attribute::ReadNone;
1143 case bitc::ATTR_KIND_READ_ONLY:
1144 return Attribute::ReadOnly;
1145 case bitc::ATTR_KIND_RETURNED:
1146 return Attribute::Returned;
1147 case bitc::ATTR_KIND_RETURNS_TWICE:
1148 return Attribute::ReturnsTwice;
1149 case bitc::ATTR_KIND_S_EXT:
1150 return Attribute::SExt;
1151 case bitc::ATTR_KIND_STACK_ALIGNMENT:
1152 return Attribute::StackAlignment;
1153 case bitc::ATTR_KIND_STACK_PROTECT:
1154 return Attribute::StackProtect;
1155 case bitc::ATTR_KIND_STACK_PROTECT_REQ:
1156 return Attribute::StackProtectReq;
1157 case bitc::ATTR_KIND_STACK_PROTECT_STRONG:
1158 return Attribute::StackProtectStrong;
1159 case bitc::ATTR_KIND_STRUCT_RET:
1160 return Attribute::StructRet;
1161 case bitc::ATTR_KIND_SANITIZE_ADDRESS:
1162 return Attribute::SanitizeAddress;
1163 case bitc::ATTR_KIND_SANITIZE_THREAD:
1164 return Attribute::SanitizeThread;
1165 case bitc::ATTR_KIND_SANITIZE_MEMORY:
1166 return Attribute::SanitizeMemory;
1167 case bitc::ATTR_KIND_UW_TABLE:
1168 return Attribute::UWTable;
1169 case bitc::ATTR_KIND_Z_EXT:
1170 return Attribute::ZExt;
1174 std::error_code BitcodeReader::parseAlignmentValue(uint64_t Exponent,
1175 unsigned &Alignment) {
1176 // Note: Alignment in bitcode files is incremented by 1, so that zero
1177 // can be used for default alignment.
1178 if (Exponent > Value::MaxAlignmentExponent + 1)
1179 return Error("Invalid alignment value");
1180 Alignment = (1 << static_cast<unsigned>(Exponent)) >> 1;
1181 return std::error_code();
1184 std::error_code BitcodeReader::ParseAttrKind(uint64_t Code,
1185 Attribute::AttrKind *Kind) {
1186 *Kind = GetAttrFromCode(Code);
1187 if (*Kind == Attribute::None)
1188 return Error(BitcodeError::CorruptedBitcode,
1189 "Unknown attribute kind (" + Twine(Code) + ")");
1190 return std::error_code();
1193 std::error_code BitcodeReader::ParseAttributeGroupBlock() {
1194 if (Stream.EnterSubBlock(bitc::PARAMATTR_GROUP_BLOCK_ID))
1195 return Error("Invalid record");
1197 if (!MAttributeGroups.empty())
1198 return Error("Invalid multiple blocks");
1200 SmallVector<uint64_t, 64> Record;
1202 // Read all the records.
1204 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1206 switch (Entry.Kind) {
1207 case BitstreamEntry::SubBlock: // Handled for us already.
1208 case BitstreamEntry::Error:
1209 return Error("Malformed block");
1210 case BitstreamEntry::EndBlock:
1211 return std::error_code();
1212 case BitstreamEntry::Record:
1213 // The interesting case.
1219 switch (Stream.readRecord(Entry.ID, Record)) {
1220 default: // Default behavior: ignore.
1222 case bitc::PARAMATTR_GRP_CODE_ENTRY: { // ENTRY: [grpid, idx, a0, a1, ...]
1223 if (Record.size() < 3)
1224 return Error("Invalid record");
1226 uint64_t GrpID = Record[0];
1227 uint64_t Idx = Record[1]; // Index of the object this attribute refers to.
1230 for (unsigned i = 2, e = Record.size(); i != e; ++i) {
1231 if (Record[i] == 0) { // Enum attribute
1232 Attribute::AttrKind Kind;
1233 if (std::error_code EC = ParseAttrKind(Record[++i], &Kind))
1236 B.addAttribute(Kind);
1237 } else if (Record[i] == 1) { // Integer attribute
1238 Attribute::AttrKind Kind;
1239 if (std::error_code EC = ParseAttrKind(Record[++i], &Kind))
1241 if (Kind == Attribute::Alignment)
1242 B.addAlignmentAttr(Record[++i]);
1243 else if (Kind == Attribute::StackAlignment)
1244 B.addStackAlignmentAttr(Record[++i]);
1245 else if (Kind == Attribute::Dereferenceable)
1246 B.addDereferenceableAttr(Record[++i]);
1247 else if (Kind == Attribute::DereferenceableOrNull)
1248 B.addDereferenceableOrNullAttr(Record[++i]);
1249 } else { // String attribute
1250 assert((Record[i] == 3 || Record[i] == 4) &&
1251 "Invalid attribute group entry");
1252 bool HasValue = (Record[i++] == 4);
1253 SmallString<64> KindStr;
1254 SmallString<64> ValStr;
1256 while (Record[i] != 0 && i != e)
1257 KindStr += Record[i++];
1258 assert(Record[i] == 0 && "Kind string not null terminated");
1261 // Has a value associated with it.
1262 ++i; // Skip the '0' that terminates the "kind" string.
1263 while (Record[i] != 0 && i != e)
1264 ValStr += Record[i++];
1265 assert(Record[i] == 0 && "Value string not null terminated");
1268 B.addAttribute(KindStr.str(), ValStr.str());
1272 MAttributeGroups[GrpID] = AttributeSet::get(Context, Idx, B);
1279 std::error_code BitcodeReader::ParseTypeTable() {
1280 if (Stream.EnterSubBlock(bitc::TYPE_BLOCK_ID_NEW))
1281 return Error("Invalid record");
1283 return ParseTypeTableBody();
1286 std::error_code BitcodeReader::ParseTypeTableBody() {
1287 if (!TypeList.empty())
1288 return Error("Invalid multiple blocks");
1290 SmallVector<uint64_t, 64> Record;
1291 unsigned NumRecords = 0;
1293 SmallString<64> TypeName;
1295 // Read all the records for this type table.
1297 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1299 switch (Entry.Kind) {
1300 case BitstreamEntry::SubBlock: // Handled for us already.
1301 case BitstreamEntry::Error:
1302 return Error("Malformed block");
1303 case BitstreamEntry::EndBlock:
1304 if (NumRecords != TypeList.size())
1305 return Error("Malformed block");
1306 return std::error_code();
1307 case BitstreamEntry::Record:
1308 // The interesting case.
1314 Type *ResultTy = nullptr;
1315 switch (Stream.readRecord(Entry.ID, Record)) {
1317 return Error("Invalid value");
1318 case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries]
1319 // TYPE_CODE_NUMENTRY contains a count of the number of types in the
1320 // type list. This allows us to reserve space.
1321 if (Record.size() < 1)
1322 return Error("Invalid record");
1323 TypeList.resize(Record[0]);
1325 case bitc::TYPE_CODE_VOID: // VOID
1326 ResultTy = Type::getVoidTy(Context);
1328 case bitc::TYPE_CODE_HALF: // HALF
1329 ResultTy = Type::getHalfTy(Context);
1331 case bitc::TYPE_CODE_FLOAT: // FLOAT
1332 ResultTy = Type::getFloatTy(Context);
1334 case bitc::TYPE_CODE_DOUBLE: // DOUBLE
1335 ResultTy = Type::getDoubleTy(Context);
1337 case bitc::TYPE_CODE_X86_FP80: // X86_FP80
1338 ResultTy = Type::getX86_FP80Ty(Context);
1340 case bitc::TYPE_CODE_FP128: // FP128
1341 ResultTy = Type::getFP128Ty(Context);
1343 case bitc::TYPE_CODE_PPC_FP128: // PPC_FP128
1344 ResultTy = Type::getPPC_FP128Ty(Context);
1346 case bitc::TYPE_CODE_LABEL: // LABEL
1347 ResultTy = Type::getLabelTy(Context);
1349 case bitc::TYPE_CODE_METADATA: // METADATA
1350 ResultTy = Type::getMetadataTy(Context);
1352 case bitc::TYPE_CODE_X86_MMX: // X86_MMX
1353 ResultTy = Type::getX86_MMXTy(Context);
1355 case bitc::TYPE_CODE_INTEGER: { // INTEGER: [width]
1356 if (Record.size() < 1)
1357 return Error("Invalid record");
1359 uint64_t NumBits = Record[0];
1360 if (NumBits < IntegerType::MIN_INT_BITS ||
1361 NumBits > IntegerType::MAX_INT_BITS)
1362 return Error("Bitwidth for integer type out of range");
1363 ResultTy = IntegerType::get(Context, NumBits);
1366 case bitc::TYPE_CODE_POINTER: { // POINTER: [pointee type] or
1367 // [pointee type, address space]
1368 if (Record.size() < 1)
1369 return Error("Invalid record");
1370 unsigned AddressSpace = 0;
1371 if (Record.size() == 2)
1372 AddressSpace = Record[1];
1373 ResultTy = getTypeByID(Record[0]);
1375 !PointerType::isValidElementType(ResultTy))
1376 return Error("Invalid type");
1377 ResultTy = PointerType::get(ResultTy, AddressSpace);
1380 case bitc::TYPE_CODE_FUNCTION_OLD: {
1381 // FIXME: attrid is dead, remove it in LLVM 4.0
1382 // FUNCTION: [vararg, attrid, retty, paramty x N]
1383 if (Record.size() < 3)
1384 return Error("Invalid record");
1385 SmallVector<Type*, 8> ArgTys;
1386 for (unsigned i = 3, e = Record.size(); i != e; ++i) {
1387 if (Type *T = getTypeByID(Record[i]))
1388 ArgTys.push_back(T);
1393 ResultTy = getTypeByID(Record[2]);
1394 if (!ResultTy || ArgTys.size() < Record.size()-3)
1395 return Error("Invalid type");
1397 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
1400 case bitc::TYPE_CODE_FUNCTION: {
1401 // FUNCTION: [vararg, retty, paramty x N]
1402 if (Record.size() < 2)
1403 return Error("Invalid record");
1404 SmallVector<Type*, 8> ArgTys;
1405 for (unsigned i = 2, e = Record.size(); i != e; ++i) {
1406 if (Type *T = getTypeByID(Record[i])) {
1407 if (!FunctionType::isValidArgumentType(T))
1408 return Error("Invalid function argument type");
1409 ArgTys.push_back(T);
1415 ResultTy = getTypeByID(Record[1]);
1416 if (!ResultTy || ArgTys.size() < Record.size()-2)
1417 return Error("Invalid type");
1419 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
1422 case bitc::TYPE_CODE_STRUCT_ANON: { // STRUCT: [ispacked, eltty x N]
1423 if (Record.size() < 1)
1424 return Error("Invalid record");
1425 SmallVector<Type*, 8> EltTys;
1426 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
1427 if (Type *T = getTypeByID(Record[i]))
1428 EltTys.push_back(T);
1432 if (EltTys.size() != Record.size()-1)
1433 return Error("Invalid type");
1434 ResultTy = StructType::get(Context, EltTys, Record[0]);
1437 case bitc::TYPE_CODE_STRUCT_NAME: // STRUCT_NAME: [strchr x N]
1438 if (ConvertToString(Record, 0, TypeName))
1439 return Error("Invalid record");
1442 case bitc::TYPE_CODE_STRUCT_NAMED: { // STRUCT: [ispacked, eltty x N]
1443 if (Record.size() < 1)
1444 return Error("Invalid record");
1446 if (NumRecords >= TypeList.size())
1447 return Error("Invalid TYPE table");
1449 // Check to see if this was forward referenced, if so fill in the temp.
1450 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
1452 Res->setName(TypeName);
1453 TypeList[NumRecords] = nullptr;
1454 } else // Otherwise, create a new struct.
1455 Res = createIdentifiedStructType(Context, TypeName);
1458 SmallVector<Type*, 8> EltTys;
1459 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
1460 if (Type *T = getTypeByID(Record[i]))
1461 EltTys.push_back(T);
1465 if (EltTys.size() != Record.size()-1)
1466 return Error("Invalid record");
1467 Res->setBody(EltTys, Record[0]);
1471 case bitc::TYPE_CODE_OPAQUE: { // OPAQUE: []
1472 if (Record.size() != 1)
1473 return Error("Invalid record");
1475 if (NumRecords >= TypeList.size())
1476 return Error("Invalid TYPE table");
1478 // Check to see if this was forward referenced, if so fill in the temp.
1479 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
1481 Res->setName(TypeName);
1482 TypeList[NumRecords] = nullptr;
1483 } else // Otherwise, create a new struct with no body.
1484 Res = createIdentifiedStructType(Context, TypeName);
1489 case bitc::TYPE_CODE_ARRAY: // ARRAY: [numelts, eltty]
1490 if (Record.size() < 2)
1491 return Error("Invalid record");
1492 ResultTy = getTypeByID(Record[1]);
1493 if (!ResultTy || !ArrayType::isValidElementType(ResultTy))
1494 return Error("Invalid type");
1495 ResultTy = ArrayType::get(ResultTy, Record[0]);
1497 case bitc::TYPE_CODE_VECTOR: // VECTOR: [numelts, eltty]
1498 if (Record.size() < 2)
1499 return Error("Invalid record");
1500 ResultTy = getTypeByID(Record[1]);
1501 if (!ResultTy || !StructType::isValidElementType(ResultTy))
1502 return Error("Invalid type");
1503 ResultTy = VectorType::get(ResultTy, Record[0]);
1507 if (NumRecords >= TypeList.size())
1508 return Error("Invalid TYPE table");
1509 if (TypeList[NumRecords])
1511 "Invalid TYPE table: Only named structs can be forward referenced");
1512 assert(ResultTy && "Didn't read a type?");
1513 TypeList[NumRecords++] = ResultTy;
1517 std::error_code BitcodeReader::ParseValueSymbolTable() {
1518 if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
1519 return Error("Invalid record");
1521 SmallVector<uint64_t, 64> Record;
1523 Triple TT(TheModule->getTargetTriple());
1525 // Read all the records for this value table.
1526 SmallString<128> ValueName;
1528 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1530 switch (Entry.Kind) {
1531 case BitstreamEntry::SubBlock: // Handled for us already.
1532 case BitstreamEntry::Error:
1533 return Error("Malformed block");
1534 case BitstreamEntry::EndBlock:
1535 return std::error_code();
1536 case BitstreamEntry::Record:
1537 // The interesting case.
1543 switch (Stream.readRecord(Entry.ID, Record)) {
1544 default: // Default behavior: unknown type.
1546 case bitc::VST_CODE_ENTRY: { // VST_ENTRY: [valueid, namechar x N]
1547 if (ConvertToString(Record, 1, ValueName))
1548 return Error("Invalid record");
1549 unsigned ValueID = Record[0];
1550 if (ValueID >= ValueList.size() || !ValueList[ValueID])
1551 return Error("Invalid record");
1552 Value *V = ValueList[ValueID];
1554 V->setName(StringRef(ValueName.data(), ValueName.size()));
1555 if (auto *GO = dyn_cast<GlobalObject>(V)) {
1556 if (GO->getComdat() == reinterpret_cast<Comdat *>(1)) {
1557 if (TT.isOSBinFormatMachO())
1558 GO->setComdat(nullptr);
1560 GO->setComdat(TheModule->getOrInsertComdat(V->getName()));
1566 case bitc::VST_CODE_BBENTRY: {
1567 if (ConvertToString(Record, 1, ValueName))
1568 return Error("Invalid record");
1569 BasicBlock *BB = getBasicBlock(Record[0]);
1571 return Error("Invalid record");
1573 BB->setName(StringRef(ValueName.data(), ValueName.size()));
1581 static int64_t unrotateSign(uint64_t U) { return U & 1 ? ~(U >> 1) : U >> 1; }
1583 std::error_code BitcodeReader::ParseMetadata() {
1584 IsMetadataMaterialized = true;
1585 unsigned NextMDValueNo = MDValueList.size();
1587 if (Stream.EnterSubBlock(bitc::METADATA_BLOCK_ID))
1588 return Error("Invalid record");
1590 SmallVector<uint64_t, 64> Record;
1593 [&](unsigned ID) -> Metadata *{ return MDValueList.getValueFwdRef(ID); };
1594 auto getMDOrNull = [&](unsigned ID) -> Metadata *{
1596 return getMD(ID - 1);
1599 auto getMDString = [&](unsigned ID) -> MDString *{
1600 // This requires that the ID is not really a forward reference. In
1601 // particular, the MDString must already have been resolved.
1602 return cast_or_null<MDString>(getMDOrNull(ID));
1605 #define GET_OR_DISTINCT(CLASS, DISTINCT, ARGS) \
1606 (DISTINCT ? CLASS::getDistinct ARGS : CLASS::get ARGS)
1608 // Read all the records.
1610 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1612 switch (Entry.Kind) {
1613 case BitstreamEntry::SubBlock: // Handled for us already.
1614 case BitstreamEntry::Error:
1615 return Error("Malformed block");
1616 case BitstreamEntry::EndBlock:
1617 MDValueList.tryToResolveCycles();
1618 return std::error_code();
1619 case BitstreamEntry::Record:
1620 // The interesting case.
1626 unsigned Code = Stream.readRecord(Entry.ID, Record);
1627 bool IsDistinct = false;
1629 default: // Default behavior: ignore.
1631 case bitc::METADATA_NAME: {
1632 // Read name of the named metadata.
1633 SmallString<8> Name(Record.begin(), Record.end());
1635 Code = Stream.ReadCode();
1637 // METADATA_NAME is always followed by METADATA_NAMED_NODE.
1638 unsigned NextBitCode = Stream.readRecord(Code, Record);
1639 assert(NextBitCode == bitc::METADATA_NAMED_NODE); (void)NextBitCode;
1641 // Read named metadata elements.
1642 unsigned Size = Record.size();
1643 NamedMDNode *NMD = TheModule->getOrInsertNamedMetadata(Name);
1644 for (unsigned i = 0; i != Size; ++i) {
1645 MDNode *MD = dyn_cast_or_null<MDNode>(MDValueList.getValueFwdRef(Record[i]));
1647 return Error("Invalid record");
1648 NMD->addOperand(MD);
1652 case bitc::METADATA_OLD_FN_NODE: {
1653 // FIXME: Remove in 4.0.
1654 // This is a LocalAsMetadata record, the only type of function-local
1656 if (Record.size() % 2 == 1)
1657 return Error("Invalid record");
1659 // If this isn't a LocalAsMetadata record, we're dropping it. This used
1660 // to be legal, but there's no upgrade path.
1661 auto dropRecord = [&] {
1662 MDValueList.AssignValue(MDNode::get(Context, None), NextMDValueNo++);
1664 if (Record.size() != 2) {
1669 Type *Ty = getTypeByID(Record[0]);
1670 if (Ty->isMetadataTy() || Ty->isVoidTy()) {
1675 MDValueList.AssignValue(
1676 LocalAsMetadata::get(ValueList.getValueFwdRef(Record[1], Ty)),
1680 case bitc::METADATA_OLD_NODE: {
1681 // FIXME: Remove in 4.0.
1682 if (Record.size() % 2 == 1)
1683 return Error("Invalid record");
1685 unsigned Size = Record.size();
1686 SmallVector<Metadata *, 8> Elts;
1687 for (unsigned i = 0; i != Size; i += 2) {
1688 Type *Ty = getTypeByID(Record[i]);
1690 return Error("Invalid record");
1691 if (Ty->isMetadataTy())
1692 Elts.push_back(MDValueList.getValueFwdRef(Record[i+1]));
1693 else if (!Ty->isVoidTy()) {
1695 ValueAsMetadata::get(ValueList.getValueFwdRef(Record[i + 1], Ty));
1696 assert(isa<ConstantAsMetadata>(MD) &&
1697 "Expected non-function-local metadata");
1700 Elts.push_back(nullptr);
1702 MDValueList.AssignValue(MDNode::get(Context, Elts), NextMDValueNo++);
1705 case bitc::METADATA_VALUE: {
1706 if (Record.size() != 2)
1707 return Error("Invalid record");
1709 Type *Ty = getTypeByID(Record[0]);
1710 if (Ty->isMetadataTy() || Ty->isVoidTy())
1711 return Error("Invalid record");
1713 MDValueList.AssignValue(
1714 ValueAsMetadata::get(ValueList.getValueFwdRef(Record[1], Ty)),
1718 case bitc::METADATA_DISTINCT_NODE:
1721 case bitc::METADATA_NODE: {
1722 SmallVector<Metadata *, 8> Elts;
1723 Elts.reserve(Record.size());
1724 for (unsigned ID : Record)
1725 Elts.push_back(ID ? MDValueList.getValueFwdRef(ID - 1) : nullptr);
1726 MDValueList.AssignValue(IsDistinct ? MDNode::getDistinct(Context, Elts)
1727 : MDNode::get(Context, Elts),
1731 case bitc::METADATA_LOCATION: {
1732 if (Record.size() != 5)
1733 return Error("Invalid record");
1735 unsigned Line = Record[1];
1736 unsigned Column = Record[2];
1737 MDNode *Scope = cast<MDNode>(MDValueList.getValueFwdRef(Record[3]));
1738 Metadata *InlinedAt =
1739 Record[4] ? MDValueList.getValueFwdRef(Record[4] - 1) : nullptr;
1740 MDValueList.AssignValue(
1741 GET_OR_DISTINCT(DILocation, Record[0],
1742 (Context, Line, Column, Scope, InlinedAt)),
1746 case bitc::METADATA_GENERIC_DEBUG: {
1747 if (Record.size() < 4)
1748 return Error("Invalid record");
1750 unsigned Tag = Record[1];
1751 unsigned Version = Record[2];
1753 if (Tag >= 1u << 16 || Version != 0)
1754 return Error("Invalid record");
1756 auto *Header = getMDString(Record[3]);
1757 SmallVector<Metadata *, 8> DwarfOps;
1758 for (unsigned I = 4, E = Record.size(); I != E; ++I)
1759 DwarfOps.push_back(Record[I] ? MDValueList.getValueFwdRef(Record[I] - 1)
1761 MDValueList.AssignValue(GET_OR_DISTINCT(GenericDINode, Record[0],
1762 (Context, Tag, Header, DwarfOps)),
1766 case bitc::METADATA_SUBRANGE: {
1767 if (Record.size() != 3)
1768 return Error("Invalid record");
1770 MDValueList.AssignValue(
1771 GET_OR_DISTINCT(DISubrange, Record[0],
1772 (Context, Record[1], unrotateSign(Record[2]))),
1776 case bitc::METADATA_ENUMERATOR: {
1777 if (Record.size() != 3)
1778 return Error("Invalid record");
1780 MDValueList.AssignValue(GET_OR_DISTINCT(DIEnumerator, Record[0],
1781 (Context, unrotateSign(Record[1]),
1782 getMDString(Record[2]))),
1786 case bitc::METADATA_BASIC_TYPE: {
1787 if (Record.size() != 6)
1788 return Error("Invalid record");
1790 MDValueList.AssignValue(
1791 GET_OR_DISTINCT(DIBasicType, Record[0],
1792 (Context, Record[1], getMDString(Record[2]),
1793 Record[3], Record[4], Record[5])),
1797 case bitc::METADATA_DERIVED_TYPE: {
1798 if (Record.size() != 12)
1799 return Error("Invalid record");
1801 MDValueList.AssignValue(
1802 GET_OR_DISTINCT(DIDerivedType, Record[0],
1803 (Context, Record[1], getMDString(Record[2]),
1804 getMDOrNull(Record[3]), Record[4],
1805 getMDOrNull(Record[5]), getMDOrNull(Record[6]),
1806 Record[7], Record[8], Record[9], Record[10],
1807 getMDOrNull(Record[11]))),
1811 case bitc::METADATA_COMPOSITE_TYPE: {
1812 if (Record.size() != 16)
1813 return Error("Invalid record");
1815 MDValueList.AssignValue(
1816 GET_OR_DISTINCT(DICompositeType, Record[0],
1817 (Context, Record[1], getMDString(Record[2]),
1818 getMDOrNull(Record[3]), Record[4],
1819 getMDOrNull(Record[5]), getMDOrNull(Record[6]),
1820 Record[7], Record[8], Record[9], Record[10],
1821 getMDOrNull(Record[11]), Record[12],
1822 getMDOrNull(Record[13]), getMDOrNull(Record[14]),
1823 getMDString(Record[15]))),
1827 case bitc::METADATA_SUBROUTINE_TYPE: {
1828 if (Record.size() != 3)
1829 return Error("Invalid record");
1831 MDValueList.AssignValue(
1832 GET_OR_DISTINCT(DISubroutineType, Record[0],
1833 (Context, Record[1], getMDOrNull(Record[2]))),
1837 case bitc::METADATA_FILE: {
1838 if (Record.size() != 3)
1839 return Error("Invalid record");
1841 MDValueList.AssignValue(
1842 GET_OR_DISTINCT(DIFile, Record[0], (Context, getMDString(Record[1]),
1843 getMDString(Record[2]))),
1847 case bitc::METADATA_COMPILE_UNIT: {
1848 if (Record.size() < 14 || Record.size() > 15)
1849 return Error("Invalid record");
1851 MDValueList.AssignValue(
1852 GET_OR_DISTINCT(DICompileUnit, Record[0],
1853 (Context, Record[1], getMDOrNull(Record[2]),
1854 getMDString(Record[3]), Record[4],
1855 getMDString(Record[5]), Record[6],
1856 getMDString(Record[7]), Record[8],
1857 getMDOrNull(Record[9]), getMDOrNull(Record[10]),
1858 getMDOrNull(Record[11]), getMDOrNull(Record[12]),
1859 getMDOrNull(Record[13]),
1860 Record.size() == 14 ? 0 : Record[14])),
1864 case bitc::METADATA_SUBPROGRAM: {
1865 if (Record.size() != 19)
1866 return Error("Invalid record");
1868 MDValueList.AssignValue(
1870 DISubprogram, Record[0],
1871 (Context, getMDOrNull(Record[1]), getMDString(Record[2]),
1872 getMDString(Record[3]), getMDOrNull(Record[4]), Record[5],
1873 getMDOrNull(Record[6]), Record[7], Record[8], Record[9],
1874 getMDOrNull(Record[10]), Record[11], Record[12], Record[13],
1875 Record[14], getMDOrNull(Record[15]), getMDOrNull(Record[16]),
1876 getMDOrNull(Record[17]), getMDOrNull(Record[18]))),
1880 case bitc::METADATA_LEXICAL_BLOCK: {
1881 if (Record.size() != 5)
1882 return Error("Invalid record");
1884 MDValueList.AssignValue(
1885 GET_OR_DISTINCT(DILexicalBlock, Record[0],
1886 (Context, getMDOrNull(Record[1]),
1887 getMDOrNull(Record[2]), Record[3], Record[4])),
1891 case bitc::METADATA_LEXICAL_BLOCK_FILE: {
1892 if (Record.size() != 4)
1893 return Error("Invalid record");
1895 MDValueList.AssignValue(
1896 GET_OR_DISTINCT(DILexicalBlockFile, Record[0],
1897 (Context, getMDOrNull(Record[1]),
1898 getMDOrNull(Record[2]), Record[3])),
1902 case bitc::METADATA_NAMESPACE: {
1903 if (Record.size() != 5)
1904 return Error("Invalid record");
1906 MDValueList.AssignValue(
1907 GET_OR_DISTINCT(DINamespace, Record[0],
1908 (Context, getMDOrNull(Record[1]),
1909 getMDOrNull(Record[2]), getMDString(Record[3]),
1914 case bitc::METADATA_TEMPLATE_TYPE: {
1915 if (Record.size() != 3)
1916 return Error("Invalid record");
1918 MDValueList.AssignValue(GET_OR_DISTINCT(DITemplateTypeParameter,
1920 (Context, getMDString(Record[1]),
1921 getMDOrNull(Record[2]))),
1925 case bitc::METADATA_TEMPLATE_VALUE: {
1926 if (Record.size() != 5)
1927 return Error("Invalid record");
1929 MDValueList.AssignValue(
1930 GET_OR_DISTINCT(DITemplateValueParameter, Record[0],
1931 (Context, Record[1], getMDString(Record[2]),
1932 getMDOrNull(Record[3]), getMDOrNull(Record[4]))),
1936 case bitc::METADATA_GLOBAL_VAR: {
1937 if (Record.size() != 11)
1938 return Error("Invalid record");
1940 MDValueList.AssignValue(
1941 GET_OR_DISTINCT(DIGlobalVariable, Record[0],
1942 (Context, getMDOrNull(Record[1]),
1943 getMDString(Record[2]), getMDString(Record[3]),
1944 getMDOrNull(Record[4]), Record[5],
1945 getMDOrNull(Record[6]), Record[7], Record[8],
1946 getMDOrNull(Record[9]), getMDOrNull(Record[10]))),
1950 case bitc::METADATA_LOCAL_VAR: {
1951 // 10th field is for the obseleted 'inlinedAt:' field.
1952 if (Record.size() != 9 && Record.size() != 10)
1953 return Error("Invalid record");
1955 MDValueList.AssignValue(
1956 GET_OR_DISTINCT(DILocalVariable, Record[0],
1957 (Context, Record[1], getMDOrNull(Record[2]),
1958 getMDString(Record[3]), getMDOrNull(Record[4]),
1959 Record[5], getMDOrNull(Record[6]), Record[7],
1964 case bitc::METADATA_EXPRESSION: {
1965 if (Record.size() < 1)
1966 return Error("Invalid record");
1968 MDValueList.AssignValue(
1969 GET_OR_DISTINCT(DIExpression, Record[0],
1970 (Context, makeArrayRef(Record).slice(1))),
1974 case bitc::METADATA_OBJC_PROPERTY: {
1975 if (Record.size() != 8)
1976 return Error("Invalid record");
1978 MDValueList.AssignValue(
1979 GET_OR_DISTINCT(DIObjCProperty, Record[0],
1980 (Context, getMDString(Record[1]),
1981 getMDOrNull(Record[2]), Record[3],
1982 getMDString(Record[4]), getMDString(Record[5]),
1983 Record[6], getMDOrNull(Record[7]))),
1987 case bitc::METADATA_IMPORTED_ENTITY: {
1988 if (Record.size() != 6)
1989 return Error("Invalid record");
1991 MDValueList.AssignValue(
1992 GET_OR_DISTINCT(DIImportedEntity, Record[0],
1993 (Context, Record[1], getMDOrNull(Record[2]),
1994 getMDOrNull(Record[3]), Record[4],
1995 getMDString(Record[5]))),
1999 case bitc::METADATA_STRING: {
2000 std::string String(Record.begin(), Record.end());
2001 llvm::UpgradeMDStringConstant(String);
2002 Metadata *MD = MDString::get(Context, String);
2003 MDValueList.AssignValue(MD, NextMDValueNo++);
2006 case bitc::METADATA_KIND: {
2007 if (Record.size() < 2)
2008 return Error("Invalid record");
2010 unsigned Kind = Record[0];
2011 SmallString<8> Name(Record.begin()+1, Record.end());
2013 unsigned NewKind = TheModule->getMDKindID(Name.str());
2014 if (!MDKindMap.insert(std::make_pair(Kind, NewKind)).second)
2015 return Error("Conflicting METADATA_KIND records");
2020 #undef GET_OR_DISTINCT
2023 /// decodeSignRotatedValue - Decode a signed value stored with the sign bit in
2024 /// the LSB for dense VBR encoding.
2025 uint64_t BitcodeReader::decodeSignRotatedValue(uint64_t V) {
2030 // There is no such thing as -0 with integers. "-0" really means MININT.
2034 /// ResolveGlobalAndAliasInits - Resolve all of the initializers for global
2035 /// values and aliases that we can.
2036 std::error_code BitcodeReader::ResolveGlobalAndAliasInits() {
2037 std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInitWorklist;
2038 std::vector<std::pair<GlobalAlias*, unsigned> > AliasInitWorklist;
2039 std::vector<std::pair<Function*, unsigned> > FunctionPrefixWorklist;
2040 std::vector<std::pair<Function*, unsigned> > FunctionPrologueWorklist;
2042 GlobalInitWorklist.swap(GlobalInits);
2043 AliasInitWorklist.swap(AliasInits);
2044 FunctionPrefixWorklist.swap(FunctionPrefixes);
2045 FunctionPrologueWorklist.swap(FunctionPrologues);
2047 while (!GlobalInitWorklist.empty()) {
2048 unsigned ValID = GlobalInitWorklist.back().second;
2049 if (ValID >= ValueList.size()) {
2050 // Not ready to resolve this yet, it requires something later in the file.
2051 GlobalInits.push_back(GlobalInitWorklist.back());
2053 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
2054 GlobalInitWorklist.back().first->setInitializer(C);
2056 return Error("Expected a constant");
2058 GlobalInitWorklist.pop_back();
2061 while (!AliasInitWorklist.empty()) {
2062 unsigned ValID = AliasInitWorklist.back().second;
2063 if (ValID >= ValueList.size()) {
2064 AliasInits.push_back(AliasInitWorklist.back());
2066 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
2067 AliasInitWorklist.back().first->setAliasee(C);
2069 return Error("Expected a constant");
2071 AliasInitWorklist.pop_back();
2074 while (!FunctionPrefixWorklist.empty()) {
2075 unsigned ValID = FunctionPrefixWorklist.back().second;
2076 if (ValID >= ValueList.size()) {
2077 FunctionPrefixes.push_back(FunctionPrefixWorklist.back());
2079 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
2080 FunctionPrefixWorklist.back().first->setPrefixData(C);
2082 return Error("Expected a constant");
2084 FunctionPrefixWorklist.pop_back();
2087 while (!FunctionPrologueWorklist.empty()) {
2088 unsigned ValID = FunctionPrologueWorklist.back().second;
2089 if (ValID >= ValueList.size()) {
2090 FunctionPrologues.push_back(FunctionPrologueWorklist.back());
2092 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
2093 FunctionPrologueWorklist.back().first->setPrologueData(C);
2095 return Error("Expected a constant");
2097 FunctionPrologueWorklist.pop_back();
2100 return std::error_code();
2103 static APInt ReadWideAPInt(ArrayRef<uint64_t> Vals, unsigned TypeBits) {
2104 SmallVector<uint64_t, 8> Words(Vals.size());
2105 std::transform(Vals.begin(), Vals.end(), Words.begin(),
2106 BitcodeReader::decodeSignRotatedValue);
2108 return APInt(TypeBits, Words);
2111 std::error_code BitcodeReader::ParseConstants() {
2112 if (Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID))
2113 return Error("Invalid record");
2115 SmallVector<uint64_t, 64> Record;
2117 // Read all the records for this value table.
2118 Type *CurTy = Type::getInt32Ty(Context);
2119 unsigned NextCstNo = ValueList.size();
2121 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
2123 switch (Entry.Kind) {
2124 case BitstreamEntry::SubBlock: // Handled for us already.
2125 case BitstreamEntry::Error:
2126 return Error("Malformed block");
2127 case BitstreamEntry::EndBlock:
2128 if (NextCstNo != ValueList.size())
2129 return Error("Invalid ronstant reference");
2131 // Once all the constants have been read, go through and resolve forward
2133 ValueList.ResolveConstantForwardRefs();
2134 return std::error_code();
2135 case BitstreamEntry::Record:
2136 // The interesting case.
2143 unsigned BitCode = Stream.readRecord(Entry.ID, Record);
2145 default: // Default behavior: unknown constant
2146 case bitc::CST_CODE_UNDEF: // UNDEF
2147 V = UndefValue::get(CurTy);
2149 case bitc::CST_CODE_SETTYPE: // SETTYPE: [typeid]
2151 return Error("Invalid record");
2152 if (Record[0] >= TypeList.size() || !TypeList[Record[0]])
2153 return Error("Invalid record");
2154 CurTy = TypeList[Record[0]];
2155 continue; // Skip the ValueList manipulation.
2156 case bitc::CST_CODE_NULL: // NULL
2157 V = Constant::getNullValue(CurTy);
2159 case bitc::CST_CODE_INTEGER: // INTEGER: [intval]
2160 if (!CurTy->isIntegerTy() || Record.empty())
2161 return Error("Invalid record");
2162 V = ConstantInt::get(CurTy, decodeSignRotatedValue(Record[0]));
2164 case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval]
2165 if (!CurTy->isIntegerTy() || Record.empty())
2166 return Error("Invalid record");
2168 APInt VInt = ReadWideAPInt(Record,
2169 cast<IntegerType>(CurTy)->getBitWidth());
2170 V = ConstantInt::get(Context, VInt);
2174 case bitc::CST_CODE_FLOAT: { // FLOAT: [fpval]
2176 return Error("Invalid record");
2177 if (CurTy->isHalfTy())
2178 V = ConstantFP::get(Context, APFloat(APFloat::IEEEhalf,
2179 APInt(16, (uint16_t)Record[0])));
2180 else if (CurTy->isFloatTy())
2181 V = ConstantFP::get(Context, APFloat(APFloat::IEEEsingle,
2182 APInt(32, (uint32_t)Record[0])));
2183 else if (CurTy->isDoubleTy())
2184 V = ConstantFP::get(Context, APFloat(APFloat::IEEEdouble,
2185 APInt(64, Record[0])));
2186 else if (CurTy->isX86_FP80Ty()) {
2187 // Bits are not stored the same way as a normal i80 APInt, compensate.
2188 uint64_t Rearrange[2];
2189 Rearrange[0] = (Record[1] & 0xffffLL) | (Record[0] << 16);
2190 Rearrange[1] = Record[0] >> 48;
2191 V = ConstantFP::get(Context, APFloat(APFloat::x87DoubleExtended,
2192 APInt(80, Rearrange)));
2193 } else if (CurTy->isFP128Ty())
2194 V = ConstantFP::get(Context, APFloat(APFloat::IEEEquad,
2195 APInt(128, Record)));
2196 else if (CurTy->isPPC_FP128Ty())
2197 V = ConstantFP::get(Context, APFloat(APFloat::PPCDoubleDouble,
2198 APInt(128, Record)));
2200 V = UndefValue::get(CurTy);
2204 case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number]
2206 return Error("Invalid record");
2208 unsigned Size = Record.size();
2209 SmallVector<Constant*, 16> Elts;
2211 if (StructType *STy = dyn_cast<StructType>(CurTy)) {
2212 for (unsigned i = 0; i != Size; ++i)
2213 Elts.push_back(ValueList.getConstantFwdRef(Record[i],
2214 STy->getElementType(i)));
2215 V = ConstantStruct::get(STy, Elts);
2216 } else if (ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) {
2217 Type *EltTy = ATy->getElementType();
2218 for (unsigned i = 0; i != Size; ++i)
2219 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
2220 V = ConstantArray::get(ATy, Elts);
2221 } else if (VectorType *VTy = dyn_cast<VectorType>(CurTy)) {
2222 Type *EltTy = VTy->getElementType();
2223 for (unsigned i = 0; i != Size; ++i)
2224 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
2225 V = ConstantVector::get(Elts);
2227 V = UndefValue::get(CurTy);
2231 case bitc::CST_CODE_STRING: // STRING: [values]
2232 case bitc::CST_CODE_CSTRING: { // CSTRING: [values]
2234 return Error("Invalid record");
2236 SmallString<16> Elts(Record.begin(), Record.end());
2237 V = ConstantDataArray::getString(Context, Elts,
2238 BitCode == bitc::CST_CODE_CSTRING);
2241 case bitc::CST_CODE_DATA: {// DATA: [n x value]
2243 return Error("Invalid record");
2245 Type *EltTy = cast<SequentialType>(CurTy)->getElementType();
2246 unsigned Size = Record.size();
2248 if (EltTy->isIntegerTy(8)) {
2249 SmallVector<uint8_t, 16> Elts(Record.begin(), Record.end());
2250 if (isa<VectorType>(CurTy))
2251 V = ConstantDataVector::get(Context, Elts);
2253 V = ConstantDataArray::get(Context, Elts);
2254 } else if (EltTy->isIntegerTy(16)) {
2255 SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end());
2256 if (isa<VectorType>(CurTy))
2257 V = ConstantDataVector::get(Context, Elts);
2259 V = ConstantDataArray::get(Context, Elts);
2260 } else if (EltTy->isIntegerTy(32)) {
2261 SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end());
2262 if (isa<VectorType>(CurTy))
2263 V = ConstantDataVector::get(Context, Elts);
2265 V = ConstantDataArray::get(Context, Elts);
2266 } else if (EltTy->isIntegerTy(64)) {
2267 SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end());
2268 if (isa<VectorType>(CurTy))
2269 V = ConstantDataVector::get(Context, Elts);
2271 V = ConstantDataArray::get(Context, Elts);
2272 } else if (EltTy->isFloatTy()) {
2273 SmallVector<float, 16> Elts(Size);
2274 std::transform(Record.begin(), Record.end(), Elts.begin(), BitsToFloat);
2275 if (isa<VectorType>(CurTy))
2276 V = ConstantDataVector::get(Context, Elts);
2278 V = ConstantDataArray::get(Context, Elts);
2279 } else if (EltTy->isDoubleTy()) {
2280 SmallVector<double, 16> Elts(Size);
2281 std::transform(Record.begin(), Record.end(), Elts.begin(),
2283 if (isa<VectorType>(CurTy))
2284 V = ConstantDataVector::get(Context, Elts);
2286 V = ConstantDataArray::get(Context, Elts);
2288 return Error("Invalid type for value");
2293 case bitc::CST_CODE_CE_BINOP: { // CE_BINOP: [opcode, opval, opval]
2294 if (Record.size() < 3)
2295 return Error("Invalid record");
2296 int Opc = GetDecodedBinaryOpcode(Record[0], CurTy);
2298 V = UndefValue::get(CurTy); // Unknown binop.
2300 Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy);
2301 Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy);
2303 if (Record.size() >= 4) {
2304 if (Opc == Instruction::Add ||
2305 Opc == Instruction::Sub ||
2306 Opc == Instruction::Mul ||
2307 Opc == Instruction::Shl) {
2308 if (Record[3] & (1 << bitc::OBO_NO_SIGNED_WRAP))
2309 Flags |= OverflowingBinaryOperator::NoSignedWrap;
2310 if (Record[3] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
2311 Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
2312 } else if (Opc == Instruction::SDiv ||
2313 Opc == Instruction::UDiv ||
2314 Opc == Instruction::LShr ||
2315 Opc == Instruction::AShr) {
2316 if (Record[3] & (1 << bitc::PEO_EXACT))
2317 Flags |= SDivOperator::IsExact;
2320 V = ConstantExpr::get(Opc, LHS, RHS, Flags);
2324 case bitc::CST_CODE_CE_CAST: { // CE_CAST: [opcode, opty, opval]
2325 if (Record.size() < 3)
2326 return Error("Invalid record");
2327 int Opc = GetDecodedCastOpcode(Record[0]);
2329 V = UndefValue::get(CurTy); // Unknown cast.
2331 Type *OpTy = getTypeByID(Record[1]);
2333 return Error("Invalid record");
2334 Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy);
2335 V = UpgradeBitCastExpr(Opc, Op, CurTy);
2336 if (!V) V = ConstantExpr::getCast(Opc, Op, CurTy);
2340 case bitc::CST_CODE_CE_INBOUNDS_GEP:
2341 case bitc::CST_CODE_CE_GEP: { // CE_GEP: [n x operands]
2343 Type *PointeeType = nullptr;
2344 if (Record.size() % 2)
2345 PointeeType = getTypeByID(Record[OpNum++]);
2346 SmallVector<Constant*, 16> Elts;
2347 while (OpNum != Record.size()) {
2348 Type *ElTy = getTypeByID(Record[OpNum++]);
2350 return Error("Invalid record");
2351 Elts.push_back(ValueList.getConstantFwdRef(Record[OpNum++], ElTy));
2356 cast<SequentialType>(Elts[0]->getType()->getScalarType())
2358 return Error("Explicit gep operator type does not match pointee type "
2359 "of pointer operand");
2361 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
2362 V = ConstantExpr::getGetElementPtr(PointeeType, Elts[0], Indices,
2364 bitc::CST_CODE_CE_INBOUNDS_GEP);
2367 case bitc::CST_CODE_CE_SELECT: { // CE_SELECT: [opval#, opval#, opval#]
2368 if (Record.size() < 3)
2369 return Error("Invalid record");
2371 Type *SelectorTy = Type::getInt1Ty(Context);
2373 // If CurTy is a vector of length n, then Record[0] must be a <n x i1>
2374 // vector. Otherwise, it must be a single bit.
2375 if (VectorType *VTy = dyn_cast<VectorType>(CurTy))
2376 SelectorTy = VectorType::get(Type::getInt1Ty(Context),
2377 VTy->getNumElements());
2379 V = ConstantExpr::getSelect(ValueList.getConstantFwdRef(Record[0],
2381 ValueList.getConstantFwdRef(Record[1],CurTy),
2382 ValueList.getConstantFwdRef(Record[2],CurTy));
2385 case bitc::CST_CODE_CE_EXTRACTELT
2386 : { // CE_EXTRACTELT: [opty, opval, opty, opval]
2387 if (Record.size() < 3)
2388 return Error("Invalid record");
2390 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
2392 return Error("Invalid record");
2393 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
2394 Constant *Op1 = nullptr;
2395 if (Record.size() == 4) {
2396 Type *IdxTy = getTypeByID(Record[2]);
2398 return Error("Invalid record");
2399 Op1 = ValueList.getConstantFwdRef(Record[3], IdxTy);
2400 } else // TODO: Remove with llvm 4.0
2401 Op1 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
2403 return Error("Invalid record");
2404 V = ConstantExpr::getExtractElement(Op0, Op1);
2407 case bitc::CST_CODE_CE_INSERTELT
2408 : { // CE_INSERTELT: [opval, opval, opty, opval]
2409 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
2410 if (Record.size() < 3 || !OpTy)
2411 return Error("Invalid record");
2412 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
2413 Constant *Op1 = ValueList.getConstantFwdRef(Record[1],
2414 OpTy->getElementType());
2415 Constant *Op2 = nullptr;
2416 if (Record.size() == 4) {
2417 Type *IdxTy = getTypeByID(Record[2]);
2419 return Error("Invalid record");
2420 Op2 = ValueList.getConstantFwdRef(Record[3], IdxTy);
2421 } else // TODO: Remove with llvm 4.0
2422 Op2 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
2424 return Error("Invalid record");
2425 V = ConstantExpr::getInsertElement(Op0, Op1, Op2);
2428 case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval]
2429 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
2430 if (Record.size() < 3 || !OpTy)
2431 return Error("Invalid record");
2432 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
2433 Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy);
2434 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
2435 OpTy->getNumElements());
2436 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy);
2437 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
2440 case bitc::CST_CODE_CE_SHUFVEC_EX: { // [opty, opval, opval, opval]
2441 VectorType *RTy = dyn_cast<VectorType>(CurTy);
2443 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
2444 if (Record.size() < 4 || !RTy || !OpTy)
2445 return Error("Invalid record");
2446 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
2447 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
2448 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
2449 RTy->getNumElements());
2450 Constant *Op2 = ValueList.getConstantFwdRef(Record[3], ShufTy);
2451 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
2454 case bitc::CST_CODE_CE_CMP: { // CE_CMP: [opty, opval, opval, pred]
2455 if (Record.size() < 4)
2456 return Error("Invalid record");
2457 Type *OpTy = getTypeByID(Record[0]);
2459 return Error("Invalid record");
2460 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
2461 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
2463 if (OpTy->isFPOrFPVectorTy())
2464 V = ConstantExpr::getFCmp(Record[3], Op0, Op1);
2466 V = ConstantExpr::getICmp(Record[3], Op0, Op1);
2469 // This maintains backward compatibility, pre-asm dialect keywords.
2470 // FIXME: Remove with the 4.0 release.
2471 case bitc::CST_CODE_INLINEASM_OLD: {
2472 if (Record.size() < 2)
2473 return Error("Invalid record");
2474 std::string AsmStr, ConstrStr;
2475 bool HasSideEffects = Record[0] & 1;
2476 bool IsAlignStack = Record[0] >> 1;
2477 unsigned AsmStrSize = Record[1];
2478 if (2+AsmStrSize >= Record.size())
2479 return Error("Invalid record");
2480 unsigned ConstStrSize = Record[2+AsmStrSize];
2481 if (3+AsmStrSize+ConstStrSize > Record.size())
2482 return Error("Invalid record");
2484 for (unsigned i = 0; i != AsmStrSize; ++i)
2485 AsmStr += (char)Record[2+i];
2486 for (unsigned i = 0; i != ConstStrSize; ++i)
2487 ConstrStr += (char)Record[3+AsmStrSize+i];
2488 PointerType *PTy = cast<PointerType>(CurTy);
2489 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
2490 AsmStr, ConstrStr, HasSideEffects, IsAlignStack);
2493 // This version adds support for the asm dialect keywords (e.g.,
2495 case bitc::CST_CODE_INLINEASM: {
2496 if (Record.size() < 2)
2497 return Error("Invalid record");
2498 std::string AsmStr, ConstrStr;
2499 bool HasSideEffects = Record[0] & 1;
2500 bool IsAlignStack = (Record[0] >> 1) & 1;
2501 unsigned AsmDialect = Record[0] >> 2;
2502 unsigned AsmStrSize = Record[1];
2503 if (2+AsmStrSize >= Record.size())
2504 return Error("Invalid record");
2505 unsigned ConstStrSize = Record[2+AsmStrSize];
2506 if (3+AsmStrSize+ConstStrSize > Record.size())
2507 return Error("Invalid record");
2509 for (unsigned i = 0; i != AsmStrSize; ++i)
2510 AsmStr += (char)Record[2+i];
2511 for (unsigned i = 0; i != ConstStrSize; ++i)
2512 ConstrStr += (char)Record[3+AsmStrSize+i];
2513 PointerType *PTy = cast<PointerType>(CurTy);
2514 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
2515 AsmStr, ConstrStr, HasSideEffects, IsAlignStack,
2516 InlineAsm::AsmDialect(AsmDialect));
2519 case bitc::CST_CODE_BLOCKADDRESS:{
2520 if (Record.size() < 3)
2521 return Error("Invalid record");
2522 Type *FnTy = getTypeByID(Record[0]);
2524 return Error("Invalid record");
2526 dyn_cast_or_null<Function>(ValueList.getConstantFwdRef(Record[1],FnTy));
2528 return Error("Invalid record");
2530 // Don't let Fn get dematerialized.
2531 BlockAddressesTaken.insert(Fn);
2533 // If the function is already parsed we can insert the block address right
2536 unsigned BBID = Record[2];
2538 // Invalid reference to entry block.
2539 return Error("Invalid ID");
2541 Function::iterator BBI = Fn->begin(), BBE = Fn->end();
2542 for (size_t I = 0, E = BBID; I != E; ++I) {
2544 return Error("Invalid ID");
2549 // Otherwise insert a placeholder and remember it so it can be inserted
2550 // when the function is parsed.
2551 auto &FwdBBs = BasicBlockFwdRefs[Fn];
2553 BasicBlockFwdRefQueue.push_back(Fn);
2554 if (FwdBBs.size() < BBID + 1)
2555 FwdBBs.resize(BBID + 1);
2557 FwdBBs[BBID] = BasicBlock::Create(Context);
2560 V = BlockAddress::get(Fn, BB);
2565 ValueList.AssignValue(V, NextCstNo);
2570 std::error_code BitcodeReader::ParseUseLists() {
2571 if (Stream.EnterSubBlock(bitc::USELIST_BLOCK_ID))
2572 return Error("Invalid record");
2574 // Read all the records.
2575 SmallVector<uint64_t, 64> Record;
2577 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
2579 switch (Entry.Kind) {
2580 case BitstreamEntry::SubBlock: // Handled for us already.
2581 case BitstreamEntry::Error:
2582 return Error("Malformed block");
2583 case BitstreamEntry::EndBlock:
2584 return std::error_code();
2585 case BitstreamEntry::Record:
2586 // The interesting case.
2590 // Read a use list record.
2593 switch (Stream.readRecord(Entry.ID, Record)) {
2594 default: // Default behavior: unknown type.
2596 case bitc::USELIST_CODE_BB:
2599 case bitc::USELIST_CODE_DEFAULT: {
2600 unsigned RecordLength = Record.size();
2601 if (RecordLength < 3)
2602 // Records should have at least an ID and two indexes.
2603 return Error("Invalid record");
2604 unsigned ID = Record.back();
2609 assert(ID < FunctionBBs.size() && "Basic block not found");
2610 V = FunctionBBs[ID];
2613 unsigned NumUses = 0;
2614 SmallDenseMap<const Use *, unsigned, 16> Order;
2615 for (const Use &U : V->uses()) {
2616 if (++NumUses > Record.size())
2618 Order[&U] = Record[NumUses - 1];
2620 if (Order.size() != Record.size() || NumUses > Record.size())
2621 // Mismatches can happen if the functions are being materialized lazily
2622 // (out-of-order), or a value has been upgraded.
2625 V->sortUseList([&](const Use &L, const Use &R) {
2626 return Order.lookup(&L) < Order.lookup(&R);
2634 /// When we see the block for metadata, remember where it is and then skip it.
2635 /// This lets us lazily deserialize the metadata.
2636 std::error_code BitcodeReader::rememberAndSkipMetadata() {
2637 // Save the current stream state.
2638 uint64_t CurBit = Stream.GetCurrentBitNo();
2639 DeferredMetadataInfo.push_back(CurBit);
2641 // Skip over the block for now.
2642 if (Stream.SkipBlock())
2643 return Error("Invalid record");
2644 return std::error_code();
2647 std::error_code BitcodeReader::materializeMetadata() {
2648 for (uint64_t BitPos : DeferredMetadataInfo) {
2649 // Move the bit stream to the saved position.
2650 Stream.JumpToBit(BitPos);
2651 if (std::error_code EC = ParseMetadata())
2654 DeferredMetadataInfo.clear();
2655 return std::error_code();
2658 void BitcodeReader::setStripDebugInfo() { StripDebugInfo = true; }
2660 /// RememberAndSkipFunctionBody - When we see the block for a function body,
2661 /// remember where it is and then skip it. This lets us lazily deserialize the
2663 std::error_code BitcodeReader::RememberAndSkipFunctionBody() {
2664 // Get the function we are talking about.
2665 if (FunctionsWithBodies.empty())
2666 return Error("Insufficient function protos");
2668 Function *Fn = FunctionsWithBodies.back();
2669 FunctionsWithBodies.pop_back();
2671 // Save the current stream state.
2672 uint64_t CurBit = Stream.GetCurrentBitNo();
2673 DeferredFunctionInfo[Fn] = CurBit;
2675 // Skip over the function block for now.
2676 if (Stream.SkipBlock())
2677 return Error("Invalid record");
2678 return std::error_code();
2681 std::error_code BitcodeReader::GlobalCleanup() {
2682 // Patch the initializers for globals and aliases up.
2683 ResolveGlobalAndAliasInits();
2684 if (!GlobalInits.empty() || !AliasInits.empty())
2685 return Error("Malformed global initializer set");
2687 // Look for intrinsic functions which need to be upgraded at some point
2688 for (Module::iterator FI = TheModule->begin(), FE = TheModule->end();
2691 if (UpgradeIntrinsicFunction(FI, NewFn))
2692 UpgradedIntrinsics.push_back(std::make_pair(FI, NewFn));
2695 // Look for global variables which need to be renamed.
2696 for (Module::global_iterator
2697 GI = TheModule->global_begin(), GE = TheModule->global_end();
2699 GlobalVariable *GV = GI++;
2700 UpgradeGlobalVariable(GV);
2703 // Force deallocation of memory for these vectors to favor the client that
2704 // want lazy deserialization.
2705 std::vector<std::pair<GlobalVariable*, unsigned> >().swap(GlobalInits);
2706 std::vector<std::pair<GlobalAlias*, unsigned> >().swap(AliasInits);
2707 return std::error_code();
2710 std::error_code BitcodeReader::ParseModule(bool Resume,
2711 bool ShouldLazyLoadMetadata) {
2713 Stream.JumpToBit(NextUnreadBit);
2714 else if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
2715 return Error("Invalid record");
2717 SmallVector<uint64_t, 64> Record;
2718 std::vector<std::string> SectionTable;
2719 std::vector<std::string> GCTable;
2721 // Read all the records for this module.
2723 BitstreamEntry Entry = Stream.advance();
2725 switch (Entry.Kind) {
2726 case BitstreamEntry::Error:
2727 return Error("Malformed block");
2728 case BitstreamEntry::EndBlock:
2729 return GlobalCleanup();
2731 case BitstreamEntry::SubBlock:
2733 default: // Skip unknown content.
2734 if (Stream.SkipBlock())
2735 return Error("Invalid record");
2737 case bitc::BLOCKINFO_BLOCK_ID:
2738 if (Stream.ReadBlockInfoBlock())
2739 return Error("Malformed block");
2741 case bitc::PARAMATTR_BLOCK_ID:
2742 if (std::error_code EC = ParseAttributeBlock())
2745 case bitc::PARAMATTR_GROUP_BLOCK_ID:
2746 if (std::error_code EC = ParseAttributeGroupBlock())
2749 case bitc::TYPE_BLOCK_ID_NEW:
2750 if (std::error_code EC = ParseTypeTable())
2753 case bitc::VALUE_SYMTAB_BLOCK_ID:
2754 if (std::error_code EC = ParseValueSymbolTable())
2756 SeenValueSymbolTable = true;
2758 case bitc::CONSTANTS_BLOCK_ID:
2759 if (std::error_code EC = ParseConstants())
2761 if (std::error_code EC = ResolveGlobalAndAliasInits())
2764 case bitc::METADATA_BLOCK_ID:
2765 if (ShouldLazyLoadMetadata && !IsMetadataMaterialized) {
2766 if (std::error_code EC = rememberAndSkipMetadata())
2770 assert(DeferredMetadataInfo.empty() && "Unexpected deferred metadata");
2771 if (std::error_code EC = ParseMetadata())
2774 case bitc::FUNCTION_BLOCK_ID:
2775 // If this is the first function body we've seen, reverse the
2776 // FunctionsWithBodies list.
2777 if (!SeenFirstFunctionBody) {
2778 std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
2779 if (std::error_code EC = GlobalCleanup())
2781 SeenFirstFunctionBody = true;
2784 if (std::error_code EC = RememberAndSkipFunctionBody())
2786 // For streaming bitcode, suspend parsing when we reach the function
2787 // bodies. Subsequent materialization calls will resume it when
2788 // necessary. For streaming, the function bodies must be at the end of
2789 // the bitcode. If the bitcode file is old, the symbol table will be
2790 // at the end instead and will not have been seen yet. In this case,
2791 // just finish the parse now.
2792 if (LazyStreamer && SeenValueSymbolTable) {
2793 NextUnreadBit = Stream.GetCurrentBitNo();
2794 return std::error_code();
2797 case bitc::USELIST_BLOCK_ID:
2798 if (std::error_code EC = ParseUseLists())
2804 case BitstreamEntry::Record:
2805 // The interesting case.
2811 switch (Stream.readRecord(Entry.ID, Record)) {
2812 default: break; // Default behavior, ignore unknown content.
2813 case bitc::MODULE_CODE_VERSION: { // VERSION: [version#]
2814 if (Record.size() < 1)
2815 return Error("Invalid record");
2816 // Only version #0 and #1 are supported so far.
2817 unsigned module_version = Record[0];
2818 switch (module_version) {
2820 return Error("Invalid value");
2822 UseRelativeIDs = false;
2825 UseRelativeIDs = true;
2830 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
2832 if (ConvertToString(Record, 0, S))
2833 return Error("Invalid record");
2834 TheModule->setTargetTriple(S);
2837 case bitc::MODULE_CODE_DATALAYOUT: { // DATALAYOUT: [strchr x N]
2839 if (ConvertToString(Record, 0, S))
2840 return Error("Invalid record");
2841 TheModule->setDataLayout(S);
2844 case bitc::MODULE_CODE_ASM: { // ASM: [strchr x N]
2846 if (ConvertToString(Record, 0, S))
2847 return Error("Invalid record");
2848 TheModule->setModuleInlineAsm(S);
2851 case bitc::MODULE_CODE_DEPLIB: { // DEPLIB: [strchr x N]
2852 // FIXME: Remove in 4.0.
2854 if (ConvertToString(Record, 0, S))
2855 return Error("Invalid record");
2859 case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N]
2861 if (ConvertToString(Record, 0, S))
2862 return Error("Invalid record");
2863 SectionTable.push_back(S);
2866 case bitc::MODULE_CODE_GCNAME: { // SECTIONNAME: [strchr x N]
2868 if (ConvertToString(Record, 0, S))
2869 return Error("Invalid record");
2870 GCTable.push_back(S);
2873 case bitc::MODULE_CODE_COMDAT: { // COMDAT: [selection_kind, name]
2874 if (Record.size() < 2)
2875 return Error("Invalid record");
2876 Comdat::SelectionKind SK = getDecodedComdatSelectionKind(Record[0]);
2877 unsigned ComdatNameSize = Record[1];
2878 std::string ComdatName;
2879 ComdatName.reserve(ComdatNameSize);
2880 for (unsigned i = 0; i != ComdatNameSize; ++i)
2881 ComdatName += (char)Record[2 + i];
2882 Comdat *C = TheModule->getOrInsertComdat(ComdatName);
2883 C->setSelectionKind(SK);
2884 ComdatList.push_back(C);
2887 // GLOBALVAR: [pointer type, isconst, initid,
2888 // linkage, alignment, section, visibility, threadlocal,
2889 // unnamed_addr, externally_initialized, dllstorageclass,
2891 case bitc::MODULE_CODE_GLOBALVAR: {
2892 if (Record.size() < 6)
2893 return Error("Invalid record");
2894 Type *Ty = getTypeByID(Record[0]);
2896 return Error("Invalid record");
2897 bool isConstant = Record[1] & 1;
2898 bool explicitType = Record[1] & 2;
2899 unsigned AddressSpace;
2901 AddressSpace = Record[1] >> 2;
2903 if (!Ty->isPointerTy())
2904 return Error("Invalid type for value");
2905 AddressSpace = cast<PointerType>(Ty)->getAddressSpace();
2906 Ty = cast<PointerType>(Ty)->getElementType();
2909 uint64_t RawLinkage = Record[3];
2910 GlobalValue::LinkageTypes Linkage = getDecodedLinkage(RawLinkage);
2912 if (std::error_code EC = parseAlignmentValue(Record[4], Alignment))
2914 std::string Section;
2916 if (Record[5]-1 >= SectionTable.size())
2917 return Error("Invalid ID");
2918 Section = SectionTable[Record[5]-1];
2920 GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;
2921 // Local linkage must have default visibility.
2922 if (Record.size() > 6 && !GlobalValue::isLocalLinkage(Linkage))
2923 // FIXME: Change to an error if non-default in 4.0.
2924 Visibility = GetDecodedVisibility(Record[6]);
2926 GlobalVariable::ThreadLocalMode TLM = GlobalVariable::NotThreadLocal;
2927 if (Record.size() > 7)
2928 TLM = GetDecodedThreadLocalMode(Record[7]);
2930 bool UnnamedAddr = false;
2931 if (Record.size() > 8)
2932 UnnamedAddr = Record[8];
2934 bool ExternallyInitialized = false;
2935 if (Record.size() > 9)
2936 ExternallyInitialized = Record[9];
2938 GlobalVariable *NewGV =
2939 new GlobalVariable(*TheModule, Ty, isConstant, Linkage, nullptr, "", nullptr,
2940 TLM, AddressSpace, ExternallyInitialized);
2941 NewGV->setAlignment(Alignment);
2942 if (!Section.empty())
2943 NewGV->setSection(Section);
2944 NewGV->setVisibility(Visibility);
2945 NewGV->setUnnamedAddr(UnnamedAddr);
2947 if (Record.size() > 10)
2948 NewGV->setDLLStorageClass(GetDecodedDLLStorageClass(Record[10]));
2950 UpgradeDLLImportExportLinkage(NewGV, RawLinkage);
2952 ValueList.push_back(NewGV);
2954 // Remember which value to use for the global initializer.
2955 if (unsigned InitID = Record[2])
2956 GlobalInits.push_back(std::make_pair(NewGV, InitID-1));
2958 if (Record.size() > 11) {
2959 if (unsigned ComdatID = Record[11]) {
2960 if (ComdatID > ComdatList.size())
2961 return Error("Invalid global variable comdat ID");
2962 NewGV->setComdat(ComdatList[ComdatID - 1]);
2964 } else if (hasImplicitComdat(RawLinkage)) {
2965 NewGV->setComdat(reinterpret_cast<Comdat *>(1));
2969 // FUNCTION: [type, callingconv, isproto, linkage, paramattr,
2970 // alignment, section, visibility, gc, unnamed_addr,
2971 // prologuedata, dllstorageclass, comdat, prefixdata]
2972 case bitc::MODULE_CODE_FUNCTION: {
2973 if (Record.size() < 8)
2974 return Error("Invalid record");
2975 Type *Ty = getTypeByID(Record[0]);
2977 return Error("Invalid record");
2978 if (auto *PTy = dyn_cast<PointerType>(Ty))
2979 Ty = PTy->getElementType();
2980 auto *FTy = dyn_cast<FunctionType>(Ty);
2982 return Error("Invalid type for value");
2984 Function *Func = Function::Create(FTy, GlobalValue::ExternalLinkage,
2987 Func->setCallingConv(static_cast<CallingConv::ID>(Record[1]));
2988 bool isProto = Record[2];
2989 uint64_t RawLinkage = Record[3];
2990 Func->setLinkage(getDecodedLinkage(RawLinkage));
2991 Func->setAttributes(getAttributes(Record[4]));
2994 if (std::error_code EC = parseAlignmentValue(Record[5], Alignment))
2996 Func->setAlignment(Alignment);
2998 if (Record[6]-1 >= SectionTable.size())
2999 return Error("Invalid ID");
3000 Func->setSection(SectionTable[Record[6]-1]);
3002 // Local linkage must have default visibility.
3003 if (!Func->hasLocalLinkage())
3004 // FIXME: Change to an error if non-default in 4.0.
3005 Func->setVisibility(GetDecodedVisibility(Record[7]));
3006 if (Record.size() > 8 && Record[8]) {
3007 if (Record[8]-1 >= GCTable.size())
3008 return Error("Invalid ID");
3009 Func->setGC(GCTable[Record[8]-1].c_str());
3011 bool UnnamedAddr = false;
3012 if (Record.size() > 9)
3013 UnnamedAddr = Record[9];
3014 Func->setUnnamedAddr(UnnamedAddr);
3015 if (Record.size() > 10 && Record[10] != 0)
3016 FunctionPrologues.push_back(std::make_pair(Func, Record[10]-1));
3018 if (Record.size() > 11)
3019 Func->setDLLStorageClass(GetDecodedDLLStorageClass(Record[11]));
3021 UpgradeDLLImportExportLinkage(Func, RawLinkage);
3023 if (Record.size() > 12) {
3024 if (unsigned ComdatID = Record[12]) {
3025 if (ComdatID > ComdatList.size())
3026 return Error("Invalid function comdat ID");
3027 Func->setComdat(ComdatList[ComdatID - 1]);
3029 } else if (hasImplicitComdat(RawLinkage)) {
3030 Func->setComdat(reinterpret_cast<Comdat *>(1));
3033 if (Record.size() > 13 && Record[13] != 0)
3034 FunctionPrefixes.push_back(std::make_pair(Func, Record[13]-1));
3036 ValueList.push_back(Func);
3038 // If this is a function with a body, remember the prototype we are
3039 // creating now, so that we can match up the body with them later.
3041 Func->setIsMaterializable(true);
3042 FunctionsWithBodies.push_back(Func);
3044 DeferredFunctionInfo[Func] = 0;
3048 // ALIAS: [alias type, aliasee val#, linkage]
3049 // ALIAS: [alias type, aliasee val#, linkage, visibility, dllstorageclass]
3050 case bitc::MODULE_CODE_ALIAS: {
3051 if (Record.size() < 3)
3052 return Error("Invalid record");
3053 Type *Ty = getTypeByID(Record[0]);
3055 return Error("Invalid record");
3056 auto *PTy = dyn_cast<PointerType>(Ty);
3058 return Error("Invalid type for value");
3061 GlobalAlias::create(PTy, getDecodedLinkage(Record[2]), "", TheModule);
3062 // Old bitcode files didn't have visibility field.
3063 // Local linkage must have default visibility.
3064 if (Record.size() > 3 && !NewGA->hasLocalLinkage())
3065 // FIXME: Change to an error if non-default in 4.0.
3066 NewGA->setVisibility(GetDecodedVisibility(Record[3]));
3067 if (Record.size() > 4)
3068 NewGA->setDLLStorageClass(GetDecodedDLLStorageClass(Record[4]));
3070 UpgradeDLLImportExportLinkage(NewGA, Record[2]);
3071 if (Record.size() > 5)
3072 NewGA->setThreadLocalMode(GetDecodedThreadLocalMode(Record[5]));
3073 if (Record.size() > 6)
3074 NewGA->setUnnamedAddr(Record[6]);
3075 ValueList.push_back(NewGA);
3076 AliasInits.push_back(std::make_pair(NewGA, Record[1]));
3079 /// MODULE_CODE_PURGEVALS: [numvals]
3080 case bitc::MODULE_CODE_PURGEVALS:
3081 // Trim down the value list to the specified size.
3082 if (Record.size() < 1 || Record[0] > ValueList.size())
3083 return Error("Invalid record");
3084 ValueList.shrinkTo(Record[0]);
3091 std::error_code BitcodeReader::ParseBitcodeInto(Module *M,
3092 bool ShouldLazyLoadMetadata) {
3093 TheModule = nullptr;
3095 if (std::error_code EC = InitStream())
3098 // Sniff for the signature.
3099 if (Stream.Read(8) != 'B' ||
3100 Stream.Read(8) != 'C' ||
3101 Stream.Read(4) != 0x0 ||
3102 Stream.Read(4) != 0xC ||
3103 Stream.Read(4) != 0xE ||
3104 Stream.Read(4) != 0xD)
3105 return Error("Invalid bitcode signature");
3107 // We expect a number of well-defined blocks, though we don't necessarily
3108 // need to understand them all.
3110 if (Stream.AtEndOfStream()) {
3112 return std::error_code();
3113 // We didn't really read a proper Module.
3114 return Error("Malformed IR file");
3117 BitstreamEntry Entry =
3118 Stream.advance(BitstreamCursor::AF_DontAutoprocessAbbrevs);
3120 switch (Entry.Kind) {
3121 case BitstreamEntry::Error:
3122 return Error("Malformed block");
3123 case BitstreamEntry::EndBlock:
3124 return std::error_code();
3126 case BitstreamEntry::SubBlock:
3128 case bitc::BLOCKINFO_BLOCK_ID:
3129 if (Stream.ReadBlockInfoBlock())
3130 return Error("Malformed block");
3132 case bitc::MODULE_BLOCK_ID:
3133 // Reject multiple MODULE_BLOCK's in a single bitstream.
3135 return Error("Invalid multiple blocks");
3137 if (std::error_code EC = ParseModule(false, ShouldLazyLoadMetadata))
3140 return std::error_code();
3143 if (Stream.SkipBlock())
3144 return Error("Invalid record");
3148 case BitstreamEntry::Record:
3149 // There should be no records in the top-level of blocks.
3151 // The ranlib in Xcode 4 will align archive members by appending newlines
3152 // to the end of them. If this file size is a multiple of 4 but not 8, we
3153 // have to read and ignore these final 4 bytes :-(
3154 if (Stream.getAbbrevIDWidth() == 2 && Entry.ID == 2 &&
3155 Stream.Read(6) == 2 && Stream.Read(24) == 0xa0a0a &&
3156 Stream.AtEndOfStream())
3157 return std::error_code();
3159 return Error("Invalid record");
3164 ErrorOr<std::string> BitcodeReader::parseModuleTriple() {
3165 if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
3166 return Error("Invalid record");
3168 SmallVector<uint64_t, 64> Record;
3171 // Read all the records for this module.
3173 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
3175 switch (Entry.Kind) {
3176 case BitstreamEntry::SubBlock: // Handled for us already.
3177 case BitstreamEntry::Error:
3178 return Error("Malformed block");
3179 case BitstreamEntry::EndBlock:
3181 case BitstreamEntry::Record:
3182 // The interesting case.
3187 switch (Stream.readRecord(Entry.ID, Record)) {
3188 default: break; // Default behavior, ignore unknown content.
3189 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
3191 if (ConvertToString(Record, 0, S))
3192 return Error("Invalid record");
3199 llvm_unreachable("Exit infinite loop");
3202 ErrorOr<std::string> BitcodeReader::parseTriple() {
3203 if (std::error_code EC = InitStream())
3206 // Sniff for the signature.
3207 if (Stream.Read(8) != 'B' ||
3208 Stream.Read(8) != 'C' ||
3209 Stream.Read(4) != 0x0 ||
3210 Stream.Read(4) != 0xC ||
3211 Stream.Read(4) != 0xE ||
3212 Stream.Read(4) != 0xD)
3213 return Error("Invalid bitcode signature");
3215 // We expect a number of well-defined blocks, though we don't necessarily
3216 // need to understand them all.
3218 BitstreamEntry Entry = Stream.advance();
3220 switch (Entry.Kind) {
3221 case BitstreamEntry::Error:
3222 return Error("Malformed block");
3223 case BitstreamEntry::EndBlock:
3224 return std::error_code();
3226 case BitstreamEntry::SubBlock:
3227 if (Entry.ID == bitc::MODULE_BLOCK_ID)
3228 return parseModuleTriple();
3230 // Ignore other sub-blocks.
3231 if (Stream.SkipBlock())
3232 return Error("Malformed block");
3235 case BitstreamEntry::Record:
3236 Stream.skipRecord(Entry.ID);
3242 /// ParseMetadataAttachment - Parse metadata attachments.
3243 std::error_code BitcodeReader::ParseMetadataAttachment(Function &F) {
3244 if (Stream.EnterSubBlock(bitc::METADATA_ATTACHMENT_ID))
3245 return Error("Invalid record");
3247 SmallVector<uint64_t, 64> Record;
3249 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
3251 switch (Entry.Kind) {
3252 case BitstreamEntry::SubBlock: // Handled for us already.
3253 case BitstreamEntry::Error:
3254 return Error("Malformed block");
3255 case BitstreamEntry::EndBlock:
3256 return std::error_code();
3257 case BitstreamEntry::Record:
3258 // The interesting case.
3262 // Read a metadata attachment record.
3264 switch (Stream.readRecord(Entry.ID, Record)) {
3265 default: // Default behavior: ignore.
3267 case bitc::METADATA_ATTACHMENT: {
3268 unsigned RecordLength = Record.size();
3270 return Error("Invalid record");
3271 if (RecordLength % 2 == 0) {
3272 // A function attachment.
3273 for (unsigned I = 0; I != RecordLength; I += 2) {
3274 auto K = MDKindMap.find(Record[I]);
3275 if (K == MDKindMap.end())
3276 return Error("Invalid ID");
3277 Metadata *MD = MDValueList.getValueFwdRef(Record[I + 1]);
3278 F.setMetadata(K->second, cast<MDNode>(MD));
3283 // An instruction attachment.
3284 Instruction *Inst = InstructionList[Record[0]];
3285 for (unsigned i = 1; i != RecordLength; i = i+2) {
3286 unsigned Kind = Record[i];
3287 DenseMap<unsigned, unsigned>::iterator I =
3288 MDKindMap.find(Kind);
3289 if (I == MDKindMap.end())
3290 return Error("Invalid ID");
3291 Metadata *Node = MDValueList.getValueFwdRef(Record[i + 1]);
3292 if (isa<LocalAsMetadata>(Node))
3293 // Drop the attachment. This used to be legal, but there's no
3296 Inst->setMetadata(I->second, cast<MDNode>(Node));
3297 if (I->second == LLVMContext::MD_tbaa)
3298 InstsWithTBAATag.push_back(Inst);
3306 static std::error_code TypeCheckLoadStoreInst(DiagnosticHandlerFunction DH,
3307 Type *ValType, Type *PtrType) {
3308 if (!isa<PointerType>(PtrType))
3309 return Error(DH, "Load/Store operand is not a pointer type");
3310 Type *ElemType = cast<PointerType>(PtrType)->getElementType();
3312 if (ValType && ValType != ElemType)
3313 return Error(DH, "Explicit load/store type does not match pointee type of "
3315 if (!PointerType::isLoadableOrStorableType(ElemType))
3316 return Error(DH, "Cannot load/store from pointer");
3317 return std::error_code();
3320 /// ParseFunctionBody - Lazily parse the specified function body block.
3321 std::error_code BitcodeReader::ParseFunctionBody(Function *F) {
3322 if (Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID))
3323 return Error("Invalid record");
3325 InstructionList.clear();
3326 unsigned ModuleValueListSize = ValueList.size();
3327 unsigned ModuleMDValueListSize = MDValueList.size();
3329 // Add all the function arguments to the value table.
3330 for(Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
3331 ValueList.push_back(I);
3333 unsigned NextValueNo = ValueList.size();
3334 BasicBlock *CurBB = nullptr;
3335 unsigned CurBBNo = 0;
3338 auto getLastInstruction = [&]() -> Instruction * {
3339 if (CurBB && !CurBB->empty())
3340 return &CurBB->back();
3341 else if (CurBBNo && FunctionBBs[CurBBNo - 1] &&
3342 !FunctionBBs[CurBBNo - 1]->empty())
3343 return &FunctionBBs[CurBBNo - 1]->back();
3347 // Read all the records.
3348 SmallVector<uint64_t, 64> Record;
3350 BitstreamEntry Entry = Stream.advance();
3352 switch (Entry.Kind) {
3353 case BitstreamEntry::Error:
3354 return Error("Malformed block");
3355 case BitstreamEntry::EndBlock:
3356 goto OutOfRecordLoop;
3358 case BitstreamEntry::SubBlock:
3360 default: // Skip unknown content.
3361 if (Stream.SkipBlock())
3362 return Error("Invalid record");
3364 case bitc::CONSTANTS_BLOCK_ID:
3365 if (std::error_code EC = ParseConstants())
3367 NextValueNo = ValueList.size();
3369 case bitc::VALUE_SYMTAB_BLOCK_ID:
3370 if (std::error_code EC = ParseValueSymbolTable())
3373 case bitc::METADATA_ATTACHMENT_ID:
3374 if (std::error_code EC = ParseMetadataAttachment(*F))
3377 case bitc::METADATA_BLOCK_ID:
3378 if (std::error_code EC = ParseMetadata())
3381 case bitc::USELIST_BLOCK_ID:
3382 if (std::error_code EC = ParseUseLists())
3388 case BitstreamEntry::Record:
3389 // The interesting case.
3395 Instruction *I = nullptr;
3396 unsigned BitCode = Stream.readRecord(Entry.ID, Record);
3398 default: // Default behavior: reject
3399 return Error("Invalid value");
3400 case bitc::FUNC_CODE_DECLAREBLOCKS: { // DECLAREBLOCKS: [nblocks]
3401 if (Record.size() < 1 || Record[0] == 0)
3402 return Error("Invalid record");
3403 // Create all the basic blocks for the function.
3404 FunctionBBs.resize(Record[0]);
3406 // See if anything took the address of blocks in this function.
3407 auto BBFRI = BasicBlockFwdRefs.find(F);
3408 if (BBFRI == BasicBlockFwdRefs.end()) {
3409 for (unsigned i = 0, e = FunctionBBs.size(); i != e; ++i)
3410 FunctionBBs[i] = BasicBlock::Create(Context, "", F);
3412 auto &BBRefs = BBFRI->second;
3413 // Check for invalid basic block references.
3414 if (BBRefs.size() > FunctionBBs.size())
3415 return Error("Invalid ID");
3416 assert(!BBRefs.empty() && "Unexpected empty array");
3417 assert(!BBRefs.front() && "Invalid reference to entry block");
3418 for (unsigned I = 0, E = FunctionBBs.size(), RE = BBRefs.size(); I != E;
3420 if (I < RE && BBRefs[I]) {
3421 BBRefs[I]->insertInto(F);
3422 FunctionBBs[I] = BBRefs[I];
3424 FunctionBBs[I] = BasicBlock::Create(Context, "", F);
3427 // Erase from the table.
3428 BasicBlockFwdRefs.erase(BBFRI);
3431 CurBB = FunctionBBs[0];
3435 case bitc::FUNC_CODE_DEBUG_LOC_AGAIN: // DEBUG_LOC_AGAIN
3436 // This record indicates that the last instruction is at the same
3437 // location as the previous instruction with a location.
3438 I = getLastInstruction();
3441 return Error("Invalid record");
3442 I->setDebugLoc(LastLoc);
3446 case bitc::FUNC_CODE_DEBUG_LOC: { // DEBUG_LOC: [line, col, scope, ia]
3447 I = getLastInstruction();
3448 if (!I || Record.size() < 4)
3449 return Error("Invalid record");
3451 unsigned Line = Record[0], Col = Record[1];
3452 unsigned ScopeID = Record[2], IAID = Record[3];
3454 MDNode *Scope = nullptr, *IA = nullptr;
3455 if (ScopeID) Scope = cast<MDNode>(MDValueList.getValueFwdRef(ScopeID-1));
3456 if (IAID) IA = cast<MDNode>(MDValueList.getValueFwdRef(IAID-1));
3457 LastLoc = DebugLoc::get(Line, Col, Scope, IA);
3458 I->setDebugLoc(LastLoc);
3463 case bitc::FUNC_CODE_INST_BINOP: { // BINOP: [opval, ty, opval, opcode]
3466 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
3467 popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) ||
3468 OpNum+1 > Record.size())
3469 return Error("Invalid record");
3471 int Opc = GetDecodedBinaryOpcode(Record[OpNum++], LHS->getType());
3473 return Error("Invalid record");
3474 I = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3475 InstructionList.push_back(I);
3476 if (OpNum < Record.size()) {
3477 if (Opc == Instruction::Add ||
3478 Opc == Instruction::Sub ||
3479 Opc == Instruction::Mul ||
3480 Opc == Instruction::Shl) {
3481 if (Record[OpNum] & (1 << bitc::OBO_NO_SIGNED_WRAP))
3482 cast<BinaryOperator>(I)->setHasNoSignedWrap(true);
3483 if (Record[OpNum] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
3484 cast<BinaryOperator>(I)->setHasNoUnsignedWrap(true);
3485 } else if (Opc == Instruction::SDiv ||
3486 Opc == Instruction::UDiv ||
3487 Opc == Instruction::LShr ||
3488 Opc == Instruction::AShr) {
3489 if (Record[OpNum] & (1 << bitc::PEO_EXACT))
3490 cast<BinaryOperator>(I)->setIsExact(true);
3491 } else if (isa<FPMathOperator>(I)) {
3493 if (0 != (Record[OpNum] & FastMathFlags::UnsafeAlgebra))
3494 FMF.setUnsafeAlgebra();
3495 if (0 != (Record[OpNum] & FastMathFlags::NoNaNs))
3497 if (0 != (Record[OpNum] & FastMathFlags::NoInfs))
3499 if (0 != (Record[OpNum] & FastMathFlags::NoSignedZeros))
3500 FMF.setNoSignedZeros();
3501 if (0 != (Record[OpNum] & FastMathFlags::AllowReciprocal))
3502 FMF.setAllowReciprocal();
3504 I->setFastMathFlags(FMF);
3510 case bitc::FUNC_CODE_INST_CAST: { // CAST: [opval, opty, destty, castopc]
3513 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
3514 OpNum+2 != Record.size())
3515 return Error("Invalid record");
3517 Type *ResTy = getTypeByID(Record[OpNum]);
3518 int Opc = GetDecodedCastOpcode(Record[OpNum+1]);
3519 if (Opc == -1 || !ResTy)
3520 return Error("Invalid record");
3521 Instruction *Temp = nullptr;
3522 if ((I = UpgradeBitCastInst(Opc, Op, ResTy, Temp))) {
3524 InstructionList.push_back(Temp);
3525 CurBB->getInstList().push_back(Temp);
3528 I = CastInst::Create((Instruction::CastOps)Opc, Op, ResTy);
3530 InstructionList.push_back(I);
3533 case bitc::FUNC_CODE_INST_INBOUNDS_GEP_OLD:
3534 case bitc::FUNC_CODE_INST_GEP_OLD:
3535 case bitc::FUNC_CODE_INST_GEP: { // GEP: type, [n x operands]
3541 if (BitCode == bitc::FUNC_CODE_INST_GEP) {
3542 InBounds = Record[OpNum++];
3543 Ty = getTypeByID(Record[OpNum++]);
3545 InBounds = BitCode == bitc::FUNC_CODE_INST_INBOUNDS_GEP_OLD;
3550 if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr))
3551 return Error("Invalid record");
3554 Ty = cast<SequentialType>(BasePtr->getType()->getScalarType())
3557 cast<SequentialType>(BasePtr->getType()->getScalarType())
3560 "Explicit gep type does not match pointee type of pointer operand");
3562 SmallVector<Value*, 16> GEPIdx;
3563 while (OpNum != Record.size()) {
3565 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
3566 return Error("Invalid record");
3567 GEPIdx.push_back(Op);
3570 I = GetElementPtrInst::Create(Ty, BasePtr, GEPIdx);
3572 InstructionList.push_back(I);
3574 cast<GetElementPtrInst>(I)->setIsInBounds(true);
3578 case bitc::FUNC_CODE_INST_EXTRACTVAL: {
3579 // EXTRACTVAL: [opty, opval, n x indices]
3582 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
3583 return Error("Invalid record");
3585 unsigned RecSize = Record.size();
3586 if (OpNum == RecSize)
3587 return Error("EXTRACTVAL: Invalid instruction with 0 indices");
3589 SmallVector<unsigned, 4> EXTRACTVALIdx;
3590 Type *CurTy = Agg->getType();
3591 for (; OpNum != RecSize; ++OpNum) {
3592 bool IsArray = CurTy->isArrayTy();
3593 bool IsStruct = CurTy->isStructTy();
3594 uint64_t Index = Record[OpNum];
3596 if (!IsStruct && !IsArray)
3597 return Error("EXTRACTVAL: Invalid type");
3598 if ((unsigned)Index != Index)
3599 return Error("Invalid value");
3600 if (IsStruct && Index >= CurTy->subtypes().size())
3601 return Error("EXTRACTVAL: Invalid struct index");
3602 if (IsArray && Index >= CurTy->getArrayNumElements())
3603 return Error("EXTRACTVAL: Invalid array index");
3604 EXTRACTVALIdx.push_back((unsigned)Index);
3607 CurTy = CurTy->subtypes()[Index];
3609 CurTy = CurTy->subtypes()[0];
3612 I = ExtractValueInst::Create(Agg, EXTRACTVALIdx);
3613 InstructionList.push_back(I);
3617 case bitc::FUNC_CODE_INST_INSERTVAL: {
3618 // INSERTVAL: [opty, opval, opty, opval, n x indices]
3621 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
3622 return Error("Invalid record");
3624 if (getValueTypePair(Record, OpNum, NextValueNo, Val))
3625 return Error("Invalid record");
3627 unsigned RecSize = Record.size();
3628 if (OpNum == RecSize)
3629 return Error("INSERTVAL: Invalid instruction with 0 indices");
3631 SmallVector<unsigned, 4> INSERTVALIdx;
3632 Type *CurTy = Agg->getType();
3633 for (; OpNum != RecSize; ++OpNum) {
3634 bool IsArray = CurTy->isArrayTy();
3635 bool IsStruct = CurTy->isStructTy();
3636 uint64_t Index = Record[OpNum];
3638 if (!IsStruct && !IsArray)
3639 return Error("INSERTVAL: Invalid type");
3640 if ((unsigned)Index != Index)
3641 return Error("Invalid value");
3642 if (IsStruct && Index >= CurTy->subtypes().size())
3643 return Error("INSERTVAL: Invalid struct index");
3644 if (IsArray && Index >= CurTy->getArrayNumElements())
3645 return Error("INSERTVAL: Invalid array index");
3647 INSERTVALIdx.push_back((unsigned)Index);
3649 CurTy = CurTy->subtypes()[Index];
3651 CurTy = CurTy->subtypes()[0];
3654 if (CurTy != Val->getType())
3655 return Error("Inserted value type doesn't match aggregate type");
3657 I = InsertValueInst::Create(Agg, Val, INSERTVALIdx);
3658 InstructionList.push_back(I);
3662 case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval]
3663 // obsolete form of select
3664 // handles select i1 ... in old bitcode
3666 Value *TrueVal, *FalseVal, *Cond;
3667 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
3668 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
3669 popValue(Record, OpNum, NextValueNo, Type::getInt1Ty(Context), Cond))
3670 return Error("Invalid record");
3672 I = SelectInst::Create(Cond, TrueVal, FalseVal);
3673 InstructionList.push_back(I);
3677 case bitc::FUNC_CODE_INST_VSELECT: {// VSELECT: [ty,opval,opval,predty,pred]
3678 // new form of select
3679 // handles select i1 or select [N x i1]
3681 Value *TrueVal, *FalseVal, *Cond;
3682 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
3683 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
3684 getValueTypePair(Record, OpNum, NextValueNo, Cond))
3685 return Error("Invalid record");
3687 // select condition can be either i1 or [N x i1]
3688 if (VectorType* vector_type =
3689 dyn_cast<VectorType>(Cond->getType())) {
3691 if (vector_type->getElementType() != Type::getInt1Ty(Context))
3692 return Error("Invalid type for value");
3695 if (Cond->getType() != Type::getInt1Ty(Context))
3696 return Error("Invalid type for value");
3699 I = SelectInst::Create(Cond, TrueVal, FalseVal);
3700 InstructionList.push_back(I);
3704 case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval]
3707 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
3708 getValueTypePair(Record, OpNum, NextValueNo, Idx))
3709 return Error("Invalid record");
3710 if (!Vec->getType()->isVectorTy())
3711 return Error("Invalid type for value");
3712 I = ExtractElementInst::Create(Vec, Idx);
3713 InstructionList.push_back(I);
3717 case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval]
3719 Value *Vec, *Elt, *Idx;
3720 if (getValueTypePair(Record, OpNum, NextValueNo, Vec))
3721 return Error("Invalid record");
3722 if (!Vec->getType()->isVectorTy())
3723 return Error("Invalid type for value");
3724 if (popValue(Record, OpNum, NextValueNo,
3725 cast<VectorType>(Vec->getType())->getElementType(), Elt) ||
3726 getValueTypePair(Record, OpNum, NextValueNo, Idx))
3727 return Error("Invalid record");
3728 I = InsertElementInst::Create(Vec, Elt, Idx);
3729 InstructionList.push_back(I);
3733 case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval]
3735 Value *Vec1, *Vec2, *Mask;
3736 if (getValueTypePair(Record, OpNum, NextValueNo, Vec1) ||
3737 popValue(Record, OpNum, NextValueNo, Vec1->getType(), Vec2))
3738 return Error("Invalid record");
3740 if (getValueTypePair(Record, OpNum, NextValueNo, Mask))
3741 return Error("Invalid record");
3742 if (!Vec1->getType()->isVectorTy() || !Vec2->getType()->isVectorTy())
3743 return Error("Invalid type for value");
3744 I = new ShuffleVectorInst(Vec1, Vec2, Mask);
3745 InstructionList.push_back(I);
3749 case bitc::FUNC_CODE_INST_CMP: // CMP: [opty, opval, opval, pred]
3750 // Old form of ICmp/FCmp returning bool
3751 // Existed to differentiate between icmp/fcmp and vicmp/vfcmp which were
3752 // both legal on vectors but had different behaviour.
3753 case bitc::FUNC_CODE_INST_CMP2: { // CMP2: [opty, opval, opval, pred]
3754 // FCmp/ICmp returning bool or vector of bool
3758 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
3759 popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) ||
3760 OpNum+1 != Record.size())
3761 return Error("Invalid record");
3763 if (LHS->getType()->isFPOrFPVectorTy())
3764 I = new FCmpInst((FCmpInst::Predicate)Record[OpNum], LHS, RHS);
3766 I = new ICmpInst((ICmpInst::Predicate)Record[OpNum], LHS, RHS);
3767 InstructionList.push_back(I);
3771 case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>]
3773 unsigned Size = Record.size();
3775 I = ReturnInst::Create(Context);
3776 InstructionList.push_back(I);
3781 Value *Op = nullptr;
3782 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
3783 return Error("Invalid record");
3784 if (OpNum != Record.size())
3785 return Error("Invalid record");
3787 I = ReturnInst::Create(Context, Op);
3788 InstructionList.push_back(I);
3791 case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#]
3792 if (Record.size() != 1 && Record.size() != 3)
3793 return Error("Invalid record");
3794 BasicBlock *TrueDest = getBasicBlock(Record[0]);
3796 return Error("Invalid record");
3798 if (Record.size() == 1) {
3799 I = BranchInst::Create(TrueDest);
3800 InstructionList.push_back(I);
3803 BasicBlock *FalseDest = getBasicBlock(Record[1]);
3804 Value *Cond = getValue(Record, 2, NextValueNo,
3805 Type::getInt1Ty(Context));
3806 if (!FalseDest || !Cond)
3807 return Error("Invalid record");
3808 I = BranchInst::Create(TrueDest, FalseDest, Cond);
3809 InstructionList.push_back(I);
3813 case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, op0, op1, ...]
3815 if ((Record[0] >> 16) == SWITCH_INST_MAGIC) {
3816 // "New" SwitchInst format with case ranges. The changes to write this
3817 // format were reverted but we still recognize bitcode that uses it.
3818 // Hopefully someday we will have support for case ranges and can use
3819 // this format again.
3821 Type *OpTy = getTypeByID(Record[1]);
3822 unsigned ValueBitWidth = cast<IntegerType>(OpTy)->getBitWidth();
3824 Value *Cond = getValue(Record, 2, NextValueNo, OpTy);
3825 BasicBlock *Default = getBasicBlock(Record[3]);
3826 if (!OpTy || !Cond || !Default)
3827 return Error("Invalid record");
3829 unsigned NumCases = Record[4];
3831 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
3832 InstructionList.push_back(SI);
3834 unsigned CurIdx = 5;
3835 for (unsigned i = 0; i != NumCases; ++i) {
3836 SmallVector<ConstantInt*, 1> CaseVals;
3837 unsigned NumItems = Record[CurIdx++];
3838 for (unsigned ci = 0; ci != NumItems; ++ci) {
3839 bool isSingleNumber = Record[CurIdx++];
3842 unsigned ActiveWords = 1;
3843 if (ValueBitWidth > 64)
3844 ActiveWords = Record[CurIdx++];
3845 Low = ReadWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords),
3847 CurIdx += ActiveWords;
3849 if (!isSingleNumber) {
3851 if (ValueBitWidth > 64)
3852 ActiveWords = Record[CurIdx++];
3854 ReadWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords),
3856 CurIdx += ActiveWords;
3858 // FIXME: It is not clear whether values in the range should be
3859 // compared as signed or unsigned values. The partially
3860 // implemented changes that used this format in the past used
3861 // unsigned comparisons.
3862 for ( ; Low.ule(High); ++Low)
3863 CaseVals.push_back(ConstantInt::get(Context, Low));
3865 CaseVals.push_back(ConstantInt::get(Context, Low));
3867 BasicBlock *DestBB = getBasicBlock(Record[CurIdx++]);
3868 for (SmallVector<ConstantInt*, 1>::iterator cvi = CaseVals.begin(),
3869 cve = CaseVals.end(); cvi != cve; ++cvi)
3870 SI->addCase(*cvi, DestBB);
3876 // Old SwitchInst format without case ranges.
3878 if (Record.size() < 3 || (Record.size() & 1) == 0)
3879 return Error("Invalid record");
3880 Type *OpTy = getTypeByID(Record[0]);
3881 Value *Cond = getValue(Record, 1, NextValueNo, OpTy);
3882 BasicBlock *Default = getBasicBlock(Record[2]);
3883 if (!OpTy || !Cond || !Default)
3884 return Error("Invalid record");
3885 unsigned NumCases = (Record.size()-3)/2;
3886 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
3887 InstructionList.push_back(SI);
3888 for (unsigned i = 0, e = NumCases; i != e; ++i) {
3889 ConstantInt *CaseVal =
3890 dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy));
3891 BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]);
3892 if (!CaseVal || !DestBB) {
3894 return Error("Invalid record");
3896 SI->addCase(CaseVal, DestBB);
3901 case bitc::FUNC_CODE_INST_INDIRECTBR: { // INDIRECTBR: [opty, op0, op1, ...]
3902 if (Record.size() < 2)
3903 return Error("Invalid record");
3904 Type *OpTy = getTypeByID(Record[0]);
3905 Value *Address = getValue(Record, 1, NextValueNo, OpTy);
3906 if (!OpTy || !Address)
3907 return Error("Invalid record");
3908 unsigned NumDests = Record.size()-2;
3909 IndirectBrInst *IBI = IndirectBrInst::Create(Address, NumDests);
3910 InstructionList.push_back(IBI);
3911 for (unsigned i = 0, e = NumDests; i != e; ++i) {
3912 if (BasicBlock *DestBB = getBasicBlock(Record[2+i])) {
3913 IBI->addDestination(DestBB);
3916 return Error("Invalid record");
3923 case bitc::FUNC_CODE_INST_INVOKE: {
3924 // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...]
3925 if (Record.size() < 4)
3926 return Error("Invalid record");
3928 AttributeSet PAL = getAttributes(Record[OpNum++]);
3929 unsigned CCInfo = Record[OpNum++];
3930 BasicBlock *NormalBB = getBasicBlock(Record[OpNum++]);
3931 BasicBlock *UnwindBB = getBasicBlock(Record[OpNum++]);
3933 FunctionType *FTy = nullptr;
3934 if (CCInfo >> 13 & 1 &&
3935 !(FTy = dyn_cast<FunctionType>(getTypeByID(Record[OpNum++]))))
3936 return Error("Explicit invoke type is not a function type");
3939 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
3940 return Error("Invalid record");
3942 PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType());
3944 return Error("Callee is not a pointer");
3946 FTy = dyn_cast<FunctionType>(CalleeTy->getElementType());
3948 return Error("Callee is not of pointer to function type");
3949 } else if (CalleeTy->getElementType() != FTy)
3950 return Error("Explicit invoke type does not match pointee type of "
3952 if (Record.size() < FTy->getNumParams() + OpNum)
3953 return Error("Insufficient operands to call");
3955 SmallVector<Value*, 16> Ops;
3956 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
3957 Ops.push_back(getValue(Record, OpNum, NextValueNo,
3958 FTy->getParamType(i)));
3960 return Error("Invalid record");
3963 if (!FTy->isVarArg()) {
3964 if (Record.size() != OpNum)
3965 return Error("Invalid record");
3967 // Read type/value pairs for varargs params.
3968 while (OpNum != Record.size()) {
3970 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
3971 return Error("Invalid record");
3976 I = InvokeInst::Create(Callee, NormalBB, UnwindBB, Ops);
3977 InstructionList.push_back(I);
3979 ->setCallingConv(static_cast<CallingConv::ID>(~(1U << 13) & CCInfo));
3980 cast<InvokeInst>(I)->setAttributes(PAL);
3983 case bitc::FUNC_CODE_INST_RESUME: { // RESUME: [opval]
3985 Value *Val = nullptr;
3986 if (getValueTypePair(Record, Idx, NextValueNo, Val))
3987 return Error("Invalid record");
3988 I = ResumeInst::Create(Val);
3989 InstructionList.push_back(I);
3992 case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE
3993 I = new UnreachableInst(Context);
3994 InstructionList.push_back(I);
3996 case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...]
3997 if (Record.size() < 1 || ((Record.size()-1)&1))
3998 return Error("Invalid record");
3999 Type *Ty = getTypeByID(Record[0]);
4001 return Error("Invalid record");
4003 PHINode *PN = PHINode::Create(Ty, (Record.size()-1)/2);
4004 InstructionList.push_back(PN);
4006 for (unsigned i = 0, e = Record.size()-1; i != e; i += 2) {
4008 // With the new function encoding, it is possible that operands have
4009 // negative IDs (for forward references). Use a signed VBR
4010 // representation to keep the encoding small.
4012 V = getValueSigned(Record, 1+i, NextValueNo, Ty);
4014 V = getValue(Record, 1+i, NextValueNo, Ty);
4015 BasicBlock *BB = getBasicBlock(Record[2+i]);
4017 return Error("Invalid record");
4018 PN->addIncoming(V, BB);
4024 case bitc::FUNC_CODE_INST_LANDINGPAD: {
4025 // LANDINGPAD: [ty, val, val, num, (id0,val0 ...)?]
4027 if (Record.size() < 4)
4028 return Error("Invalid record");
4029 Type *Ty = getTypeByID(Record[Idx++]);
4031 return Error("Invalid record");
4032 Value *PersFn = nullptr;
4033 if (getValueTypePair(Record, Idx, NextValueNo, PersFn))
4034 return Error("Invalid record");
4036 bool IsCleanup = !!Record[Idx++];
4037 unsigned NumClauses = Record[Idx++];
4038 LandingPadInst *LP = LandingPadInst::Create(Ty, PersFn, NumClauses);
4039 LP->setCleanup(IsCleanup);
4040 for (unsigned J = 0; J != NumClauses; ++J) {
4041 LandingPadInst::ClauseType CT =
4042 LandingPadInst::ClauseType(Record[Idx++]); (void)CT;
4045 if (getValueTypePair(Record, Idx, NextValueNo, Val)) {
4047 return Error("Invalid record");
4050 assert((CT != LandingPadInst::Catch ||
4051 !isa<ArrayType>(Val->getType())) &&
4052 "Catch clause has a invalid type!");
4053 assert((CT != LandingPadInst::Filter ||
4054 isa<ArrayType>(Val->getType())) &&
4055 "Filter clause has invalid type!");
4056 LP->addClause(cast<Constant>(Val));
4060 InstructionList.push_back(I);
4064 case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, opty, op, align]
4065 if (Record.size() != 4)
4066 return Error("Invalid record");
4067 uint64_t AlignRecord = Record[3];
4068 const uint64_t InAllocaMask = uint64_t(1) << 5;
4069 const uint64_t ExplicitTypeMask = uint64_t(1) << 6;
4070 const uint64_t FlagMask = InAllocaMask | ExplicitTypeMask;
4071 bool InAlloca = AlignRecord & InAllocaMask;
4072 Type *Ty = getTypeByID(Record[0]);
4073 if ((AlignRecord & ExplicitTypeMask) == 0) {
4074 auto *PTy = dyn_cast_or_null<PointerType>(Ty);
4076 return Error("Old-style alloca with a non-pointer type");
4077 Ty = PTy->getElementType();
4079 Type *OpTy = getTypeByID(Record[1]);
4080 Value *Size = getFnValueByID(Record[2], OpTy);
4082 if (std::error_code EC =
4083 parseAlignmentValue(AlignRecord & ~FlagMask, Align)) {
4087 return Error("Invalid record");
4088 AllocaInst *AI = new AllocaInst(Ty, Size, Align);
4089 AI->setUsedWithInAlloca(InAlloca);
4091 InstructionList.push_back(I);
4094 case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol]
4097 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
4098 (OpNum + 2 != Record.size() && OpNum + 3 != Record.size()))
4099 return Error("Invalid record");
4102 if (OpNum + 3 == Record.size())
4103 Ty = getTypeByID(Record[OpNum++]);
4104 if (std::error_code EC =
4105 TypeCheckLoadStoreInst(DiagnosticHandler, Ty, Op->getType()))
4108 Ty = cast<PointerType>(Op->getType())->getElementType();
4111 if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align))
4113 I = new LoadInst(Ty, Op, "", Record[OpNum + 1], Align);
4115 InstructionList.push_back(I);
4118 case bitc::FUNC_CODE_INST_LOADATOMIC: {
4119 // LOADATOMIC: [opty, op, align, vol, ordering, synchscope]
4122 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
4123 (OpNum + 4 != Record.size() && OpNum + 5 != Record.size()))
4124 return Error("Invalid record");
4127 if (OpNum + 5 == Record.size())
4128 Ty = getTypeByID(Record[OpNum++]);
4129 if (std::error_code EC =
4130 TypeCheckLoadStoreInst(DiagnosticHandler, Ty, Op->getType()))
4133 Ty = cast<PointerType>(Op->getType())->getElementType();
4135 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
4136 if (Ordering == NotAtomic || Ordering == Release ||
4137 Ordering == AcquireRelease)
4138 return Error("Invalid record");
4139 if (Ordering != NotAtomic && Record[OpNum] == 0)
4140 return Error("Invalid record");
4141 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
4144 if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align))
4146 I = new LoadInst(Op, "", Record[OpNum+1], Align, Ordering, SynchScope);
4148 InstructionList.push_back(I);
4151 case bitc::FUNC_CODE_INST_STORE:
4152 case bitc::FUNC_CODE_INST_STORE_OLD: { // STORE2:[ptrty, ptr, val, align, vol]
4155 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
4156 (BitCode == bitc::FUNC_CODE_INST_STORE
4157 ? getValueTypePair(Record, OpNum, NextValueNo, Val)
4158 : popValue(Record, OpNum, NextValueNo,
4159 cast<PointerType>(Ptr->getType())->getElementType(),
4161 OpNum + 2 != Record.size())
4162 return Error("Invalid record");
4164 if (std::error_code EC = TypeCheckLoadStoreInst(
4165 DiagnosticHandler, Val->getType(), Ptr->getType()))
4168 if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align))
4170 I = new StoreInst(Val, Ptr, Record[OpNum+1], Align);
4171 InstructionList.push_back(I);
4174 case bitc::FUNC_CODE_INST_STOREATOMIC:
4175 case bitc::FUNC_CODE_INST_STOREATOMIC_OLD: {
4176 // STOREATOMIC: [ptrty, ptr, val, align, vol, ordering, synchscope]
4179 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
4180 (BitCode == bitc::FUNC_CODE_INST_STOREATOMIC
4181 ? getValueTypePair(Record, OpNum, NextValueNo, Val)
4182 : popValue(Record, OpNum, NextValueNo,
4183 cast<PointerType>(Ptr->getType())->getElementType(),
4185 OpNum + 4 != Record.size())
4186 return Error("Invalid record");
4188 if (std::error_code EC = TypeCheckLoadStoreInst(
4189 DiagnosticHandler, Val->getType(), Ptr->getType()))
4191 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
4192 if (Ordering == NotAtomic || Ordering == Acquire ||
4193 Ordering == AcquireRelease)
4194 return Error("Invalid record");
4195 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
4196 if (Ordering != NotAtomic && Record[OpNum] == 0)
4197 return Error("Invalid record");
4200 if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align))
4202 I = new StoreInst(Val, Ptr, Record[OpNum+1], Align, Ordering, SynchScope);
4203 InstructionList.push_back(I);
4206 case bitc::FUNC_CODE_INST_CMPXCHG_OLD:
4207 case bitc::FUNC_CODE_INST_CMPXCHG: {
4208 // CMPXCHG:[ptrty, ptr, cmp, new, vol, successordering, synchscope,
4209 // failureordering?, isweak?]
4211 Value *Ptr, *Cmp, *New;
4212 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
4213 (BitCode == bitc::FUNC_CODE_INST_CMPXCHG
4214 ? getValueTypePair(Record, OpNum, NextValueNo, Cmp)
4215 : popValue(Record, OpNum, NextValueNo,
4216 cast<PointerType>(Ptr->getType())->getElementType(),
4218 popValue(Record, OpNum, NextValueNo, Cmp->getType(), New) ||
4219 Record.size() < OpNum + 3 || Record.size() > OpNum + 5)
4220 return Error("Invalid record");
4221 AtomicOrdering SuccessOrdering = GetDecodedOrdering(Record[OpNum+1]);
4222 if (SuccessOrdering == NotAtomic || SuccessOrdering == Unordered)
4223 return Error("Invalid record");
4224 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+2]);
4226 if (std::error_code EC = TypeCheckLoadStoreInst(
4227 DiagnosticHandler, Cmp->getType(), Ptr->getType()))
4229 AtomicOrdering FailureOrdering;
4230 if (Record.size() < 7)
4232 AtomicCmpXchgInst::getStrongestFailureOrdering(SuccessOrdering);
4234 FailureOrdering = GetDecodedOrdering(Record[OpNum+3]);
4236 I = new AtomicCmpXchgInst(Ptr, Cmp, New, SuccessOrdering, FailureOrdering,
4238 cast<AtomicCmpXchgInst>(I)->setVolatile(Record[OpNum]);
4240 if (Record.size() < 8) {
4241 // Before weak cmpxchgs existed, the instruction simply returned the
4242 // value loaded from memory, so bitcode files from that era will be
4243 // expecting the first component of a modern cmpxchg.
4244 CurBB->getInstList().push_back(I);
4245 I = ExtractValueInst::Create(I, 0);
4247 cast<AtomicCmpXchgInst>(I)->setWeak(Record[OpNum+4]);
4250 InstructionList.push_back(I);
4253 case bitc::FUNC_CODE_INST_ATOMICRMW: {
4254 // ATOMICRMW:[ptrty, ptr, val, op, vol, ordering, synchscope]
4257 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
4258 popValue(Record, OpNum, NextValueNo,
4259 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
4260 OpNum+4 != Record.size())
4261 return Error("Invalid record");
4262 AtomicRMWInst::BinOp Operation = GetDecodedRMWOperation(Record[OpNum]);
4263 if (Operation < AtomicRMWInst::FIRST_BINOP ||
4264 Operation > AtomicRMWInst::LAST_BINOP)
4265 return Error("Invalid record");
4266 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
4267 if (Ordering == NotAtomic || Ordering == Unordered)
4268 return Error("Invalid record");
4269 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
4270 I = new AtomicRMWInst(Operation, Ptr, Val, Ordering, SynchScope);
4271 cast<AtomicRMWInst>(I)->setVolatile(Record[OpNum+1]);
4272 InstructionList.push_back(I);
4275 case bitc::FUNC_CODE_INST_FENCE: { // FENCE:[ordering, synchscope]
4276 if (2 != Record.size())
4277 return Error("Invalid record");
4278 AtomicOrdering Ordering = GetDecodedOrdering(Record[0]);
4279 if (Ordering == NotAtomic || Ordering == Unordered ||
4280 Ordering == Monotonic)
4281 return Error("Invalid record");
4282 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[1]);
4283 I = new FenceInst(Context, Ordering, SynchScope);
4284 InstructionList.push_back(I);
4287 case bitc::FUNC_CODE_INST_CALL: {
4288 // CALL: [paramattrs, cc, fnty, fnid, arg0, arg1...]
4289 if (Record.size() < 3)
4290 return Error("Invalid record");
4293 AttributeSet PAL = getAttributes(Record[OpNum++]);
4294 unsigned CCInfo = Record[OpNum++];
4296 FunctionType *FTy = nullptr;
4297 if (CCInfo >> 15 & 1 &&
4298 !(FTy = dyn_cast<FunctionType>(getTypeByID(Record[OpNum++]))))
4299 return Error("Explicit call type is not a function type");
4302 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
4303 return Error("Invalid record");
4305 PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());
4307 return Error("Callee is not a pointer type");
4309 FTy = dyn_cast<FunctionType>(OpTy->getElementType());
4311 return Error("Callee is not of pointer to function type");
4312 } else if (OpTy->getElementType() != FTy)
4313 return Error("Explicit call type does not match pointee type of "
4315 if (Record.size() < FTy->getNumParams() + OpNum)
4316 return Error("Insufficient operands to call");
4318 SmallVector<Value*, 16> Args;
4319 // Read the fixed params.
4320 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
4321 if (FTy->getParamType(i)->isLabelTy())
4322 Args.push_back(getBasicBlock(Record[OpNum]));
4324 Args.push_back(getValue(Record, OpNum, NextValueNo,
4325 FTy->getParamType(i)));
4327 return Error("Invalid record");
4330 // Read type/value pairs for varargs params.
4331 if (!FTy->isVarArg()) {
4332 if (OpNum != Record.size())
4333 return Error("Invalid record");
4335 while (OpNum != Record.size()) {
4337 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
4338 return Error("Invalid record");
4343 I = CallInst::Create(FTy, Callee, Args);
4344 InstructionList.push_back(I);
4345 cast<CallInst>(I)->setCallingConv(
4346 static_cast<CallingConv::ID>((~(1U << 14) & CCInfo) >> 1));
4347 CallInst::TailCallKind TCK = CallInst::TCK_None;
4349 TCK = CallInst::TCK_Tail;
4350 if (CCInfo & (1 << 14))
4351 TCK = CallInst::TCK_MustTail;
4352 cast<CallInst>(I)->setTailCallKind(TCK);
4353 cast<CallInst>(I)->setAttributes(PAL);
4356 case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty]
4357 if (Record.size() < 3)
4358 return Error("Invalid record");
4359 Type *OpTy = getTypeByID(Record[0]);
4360 Value *Op = getValue(Record, 1, NextValueNo, OpTy);
4361 Type *ResTy = getTypeByID(Record[2]);
4362 if (!OpTy || !Op || !ResTy)
4363 return Error("Invalid record");
4364 I = new VAArgInst(Op, ResTy);
4365 InstructionList.push_back(I);
4370 // Add instruction to end of current BB. If there is no current BB, reject
4374 return Error("Invalid instruction with no BB");
4376 CurBB->getInstList().push_back(I);
4378 // If this was a terminator instruction, move to the next block.
4379 if (isa<TerminatorInst>(I)) {
4381 CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : nullptr;
4384 // Non-void values get registered in the value table for future use.
4385 if (I && !I->getType()->isVoidTy())
4386 ValueList.AssignValue(I, NextValueNo++);
4391 // Check the function list for unresolved values.
4392 if (Argument *A = dyn_cast<Argument>(ValueList.back())) {
4393 if (!A->getParent()) {
4394 // We found at least one unresolved value. Nuke them all to avoid leaks.
4395 for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){
4396 if ((A = dyn_cast_or_null<Argument>(ValueList[i])) && !A->getParent()) {
4397 A->replaceAllUsesWith(UndefValue::get(A->getType()));
4401 return Error("Never resolved value found in function");
4405 // FIXME: Check for unresolved forward-declared metadata references
4406 // and clean up leaks.
4408 // Trim the value list down to the size it was before we parsed this function.
4409 ValueList.shrinkTo(ModuleValueListSize);
4410 MDValueList.shrinkTo(ModuleMDValueListSize);
4411 std::vector<BasicBlock*>().swap(FunctionBBs);
4412 return std::error_code();
4415 /// Find the function body in the bitcode stream
4416 std::error_code BitcodeReader::FindFunctionInStream(
4418 DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator) {
4419 while (DeferredFunctionInfoIterator->second == 0) {
4420 if (Stream.AtEndOfStream())
4421 return Error("Could not find function in stream");
4422 // ParseModule will parse the next body in the stream and set its
4423 // position in the DeferredFunctionInfo map.
4424 if (std::error_code EC = ParseModule(true))
4427 return std::error_code();
4430 //===----------------------------------------------------------------------===//
4431 // GVMaterializer implementation
4432 //===----------------------------------------------------------------------===//
4434 void BitcodeReader::releaseBuffer() { Buffer.release(); }
4436 std::error_code BitcodeReader::materialize(GlobalValue *GV) {
4437 if (std::error_code EC = materializeMetadata())
4440 Function *F = dyn_cast<Function>(GV);
4441 // If it's not a function or is already material, ignore the request.
4442 if (!F || !F->isMaterializable())
4443 return std::error_code();
4445 DenseMap<Function*, uint64_t>::iterator DFII = DeferredFunctionInfo.find(F);
4446 assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!");
4447 // If its position is recorded as 0, its body is somewhere in the stream
4448 // but we haven't seen it yet.
4449 if (DFII->second == 0 && LazyStreamer)
4450 if (std::error_code EC = FindFunctionInStream(F, DFII))
4453 // Move the bit stream to the saved position of the deferred function body.
4454 Stream.JumpToBit(DFII->second);
4456 if (std::error_code EC = ParseFunctionBody(F))
4458 F->setIsMaterializable(false);
4463 // Upgrade any old intrinsic calls in the function.
4464 for (UpgradedIntrinsicMap::iterator I = UpgradedIntrinsics.begin(),
4465 E = UpgradedIntrinsics.end(); I != E; ++I) {
4466 if (I->first != I->second) {
4467 for (auto UI = I->first->user_begin(), UE = I->first->user_end();
4469 if (CallInst* CI = dyn_cast<CallInst>(*UI++))
4470 UpgradeIntrinsicCall(CI, I->second);
4475 // Bring in any functions that this function forward-referenced via
4477 return materializeForwardReferencedFunctions();
4480 bool BitcodeReader::isDematerializable(const GlobalValue *GV) const {
4481 const Function *F = dyn_cast<Function>(GV);
4482 if (!F || F->isDeclaration())
4485 // Dematerializing F would leave dangling references that wouldn't be
4486 // reconnected on re-materialization.
4487 if (BlockAddressesTaken.count(F))
4490 return DeferredFunctionInfo.count(const_cast<Function*>(F));
4493 void BitcodeReader::dematerialize(GlobalValue *GV) {
4494 Function *F = dyn_cast<Function>(GV);
4495 // If this function isn't dematerializable, this is a noop.
4496 if (!F || !isDematerializable(F))
4499 assert(DeferredFunctionInfo.count(F) && "No info to read function later?");
4501 // Just forget the function body, we can remat it later.
4502 F->dropAllReferences();
4503 F->setIsMaterializable(true);
4506 std::error_code BitcodeReader::materializeModule(Module *M) {
4507 assert(M == TheModule &&
4508 "Can only Materialize the Module this BitcodeReader is attached to.");
4510 if (std::error_code EC = materializeMetadata())
4513 // Promise to materialize all forward references.
4514 WillMaterializeAllForwardRefs = true;
4516 // Iterate over the module, deserializing any functions that are still on
4518 for (Module::iterator F = TheModule->begin(), E = TheModule->end();
4520 if (std::error_code EC = materialize(F))
4523 // At this point, if there are any function bodies, the current bit is
4524 // pointing to the END_BLOCK record after them. Now make sure the rest
4525 // of the bits in the module have been read.
4529 // Check that all block address forward references got resolved (as we
4531 if (!BasicBlockFwdRefs.empty())
4532 return Error("Never resolved function from blockaddress");
4534 // Upgrade any intrinsic calls that slipped through (should not happen!) and
4535 // delete the old functions to clean up. We can't do this unless the entire
4536 // module is materialized because there could always be another function body
4537 // with calls to the old function.
4538 for (std::vector<std::pair<Function*, Function*> >::iterator I =
4539 UpgradedIntrinsics.begin(), E = UpgradedIntrinsics.end(); I != E; ++I) {
4540 if (I->first != I->second) {
4541 for (auto UI = I->first->user_begin(), UE = I->first->user_end();
4543 if (CallInst* CI = dyn_cast<CallInst>(*UI++))
4544 UpgradeIntrinsicCall(CI, I->second);
4546 if (!I->first->use_empty())
4547 I->first->replaceAllUsesWith(I->second);
4548 I->first->eraseFromParent();
4551 std::vector<std::pair<Function*, Function*> >().swap(UpgradedIntrinsics);
4553 for (unsigned I = 0, E = InstsWithTBAATag.size(); I < E; I++)
4554 UpgradeInstWithTBAATag(InstsWithTBAATag[I]);
4556 UpgradeDebugInfo(*M);
4557 return std::error_code();
4560 std::vector<StructType *> BitcodeReader::getIdentifiedStructTypes() const {
4561 return IdentifiedStructTypes;
4564 std::error_code BitcodeReader::InitStream() {
4566 return InitLazyStream();
4567 return InitStreamFromBuffer();
4570 std::error_code BitcodeReader::InitStreamFromBuffer() {
4571 const unsigned char *BufPtr = (const unsigned char*)Buffer->getBufferStart();
4572 const unsigned char *BufEnd = BufPtr+Buffer->getBufferSize();
4574 if (Buffer->getBufferSize() & 3)
4575 return Error("Invalid bitcode signature");
4577 // If we have a wrapper header, parse it and ignore the non-bc file contents.
4578 // The magic number is 0x0B17C0DE stored in little endian.
4579 if (isBitcodeWrapper(BufPtr, BufEnd))
4580 if (SkipBitcodeWrapperHeader(BufPtr, BufEnd, true))
4581 return Error("Invalid bitcode wrapper header");
4583 StreamFile.reset(new BitstreamReader(BufPtr, BufEnd));
4584 Stream.init(&*StreamFile);
4586 return std::error_code();
4589 std::error_code BitcodeReader::InitLazyStream() {
4590 // Check and strip off the bitcode wrapper; BitstreamReader expects never to
4592 auto OwnedBytes = llvm::make_unique<StreamingMemoryObject>(LazyStreamer);
4593 StreamingMemoryObject &Bytes = *OwnedBytes;
4594 StreamFile = llvm::make_unique<BitstreamReader>(std::move(OwnedBytes));
4595 Stream.init(&*StreamFile);
4597 unsigned char buf[16];
4598 if (Bytes.readBytes(buf, 16, 0) != 16)
4599 return Error("Invalid bitcode signature");
4601 if (!isBitcode(buf, buf + 16))
4602 return Error("Invalid bitcode signature");
4604 if (isBitcodeWrapper(buf, buf + 4)) {
4605 const unsigned char *bitcodeStart = buf;
4606 const unsigned char *bitcodeEnd = buf + 16;
4607 SkipBitcodeWrapperHeader(bitcodeStart, bitcodeEnd, false);
4608 Bytes.dropLeadingBytes(bitcodeStart - buf);
4609 Bytes.setKnownObjectSize(bitcodeEnd - bitcodeStart);
4611 return std::error_code();
4615 class BitcodeErrorCategoryType : public std::error_category {
4616 const char *name() const LLVM_NOEXCEPT override {
4617 return "llvm.bitcode";
4619 std::string message(int IE) const override {
4620 BitcodeError E = static_cast<BitcodeError>(IE);
4622 case BitcodeError::InvalidBitcodeSignature:
4623 return "Invalid bitcode signature";
4624 case BitcodeError::CorruptedBitcode:
4625 return "Corrupted bitcode";
4627 llvm_unreachable("Unknown error type!");
4632 static ManagedStatic<BitcodeErrorCategoryType> ErrorCategory;
4634 const std::error_category &llvm::BitcodeErrorCategory() {
4635 return *ErrorCategory;
4638 //===----------------------------------------------------------------------===//
4639 // External interface
4640 //===----------------------------------------------------------------------===//
4642 /// \brief Get a lazy one-at-time loading module from bitcode.
4644 /// This isn't always used in a lazy context. In particular, it's also used by
4645 /// \a parseBitcodeFile(). If this is truly lazy, then we need to eagerly pull
4646 /// in forward-referenced functions from block address references.
4648 /// \param[in] WillMaterializeAll Set to \c true if the caller promises to
4649 /// materialize everything -- in particular, if this isn't truly lazy.
4650 static ErrorOr<Module *>
4651 getLazyBitcodeModuleImpl(std::unique_ptr<MemoryBuffer> &&Buffer,
4652 LLVMContext &Context, bool WillMaterializeAll,
4653 DiagnosticHandlerFunction DiagnosticHandler,
4654 bool ShouldLazyLoadMetadata = false) {
4655 Module *M = new Module(Buffer->getBufferIdentifier(), Context);
4657 new BitcodeReader(Buffer.get(), Context, DiagnosticHandler);
4658 M->setMaterializer(R);
4660 auto cleanupOnError = [&](std::error_code EC) {
4661 R->releaseBuffer(); // Never take ownership on error.
4662 delete M; // Also deletes R.
4666 // Delay parsing Metadata if ShouldLazyLoadMetadata is true.
4667 if (std::error_code EC = R->ParseBitcodeInto(M, ShouldLazyLoadMetadata))
4668 return cleanupOnError(EC);
4670 if (!WillMaterializeAll)
4671 // Resolve forward references from blockaddresses.
4672 if (std::error_code EC = R->materializeForwardReferencedFunctions())
4673 return cleanupOnError(EC);
4675 Buffer.release(); // The BitcodeReader owns it now.
4680 llvm::getLazyBitcodeModule(std::unique_ptr<MemoryBuffer> &&Buffer,
4681 LLVMContext &Context,
4682 DiagnosticHandlerFunction DiagnosticHandler,
4683 bool ShouldLazyLoadMetadata) {
4684 return getLazyBitcodeModuleImpl(std::move(Buffer), Context, false,
4685 DiagnosticHandler, ShouldLazyLoadMetadata);
4688 ErrorOr<std::unique_ptr<Module>>
4689 llvm::getStreamedBitcodeModule(StringRef Name, DataStreamer *Streamer,
4690 LLVMContext &Context,
4691 DiagnosticHandlerFunction DiagnosticHandler) {
4692 std::unique_ptr<Module> M = make_unique<Module>(Name, Context);
4693 BitcodeReader *R = new BitcodeReader(Streamer, Context, DiagnosticHandler);
4694 M->setMaterializer(R);
4695 if (std::error_code EC = R->ParseBitcodeInto(M.get()))
4697 return std::move(M);
4701 llvm::parseBitcodeFile(MemoryBufferRef Buffer, LLVMContext &Context,
4702 DiagnosticHandlerFunction DiagnosticHandler) {
4703 std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
4704 ErrorOr<Module *> ModuleOrErr = getLazyBitcodeModuleImpl(
4705 std::move(Buf), Context, true, DiagnosticHandler);
4708 Module *M = ModuleOrErr.get();
4709 // Read in the entire module, and destroy the BitcodeReader.
4710 if (std::error_code EC = M->materializeAllPermanently()) {
4715 // TODO: Restore the use-lists to the in-memory state when the bitcode was
4716 // written. We must defer until the Module has been fully materialized.
4722 llvm::getBitcodeTargetTriple(MemoryBufferRef Buffer, LLVMContext &Context,
4723 DiagnosticHandlerFunction DiagnosticHandler) {
4724 std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
4725 auto R = llvm::make_unique<BitcodeReader>(Buf.release(), Context,
4727 ErrorOr<std::string> Triple = R->parseTriple();
4728 if (Triple.getError())
4730 return Triple.get();