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) {
67 ValuePtrs.push_back(V);
71 assert(ResolveConstants.empty() && "Constants not resolved?");
75 Value *operator[](unsigned i) const {
76 assert(i < ValuePtrs.size());
80 Value *back() const { return ValuePtrs.back(); }
81 void pop_back() { ValuePtrs.pop_back(); }
82 bool empty() const { return ValuePtrs.empty(); }
83 void shrinkTo(unsigned N) {
84 assert(N <= size() && "Invalid shrinkTo request!");
88 Constant *getConstantFwdRef(unsigned Idx, Type *Ty);
89 Value *getValueFwdRef(unsigned Idx, Type *Ty);
91 void AssignValue(Value *V, unsigned Idx);
93 /// ResolveConstantForwardRefs - Once all constants are read, this method bulk
94 /// resolves any forward references.
95 void ResolveConstantForwardRefs();
98 class BitcodeReaderMDValueList {
103 std::vector<TrackingMDRef> MDValuePtrs;
105 LLVMContext &Context;
107 BitcodeReaderMDValueList(LLVMContext &C)
108 : NumFwdRefs(0), AnyFwdRefs(false), Context(C) {}
110 // vector compatibility methods
111 unsigned size() const { return MDValuePtrs.size(); }
112 void resize(unsigned N) { MDValuePtrs.resize(N); }
113 void push_back(Metadata *MD) { MDValuePtrs.emplace_back(MD); }
114 void clear() { MDValuePtrs.clear(); }
115 Metadata *back() const { return MDValuePtrs.back(); }
116 void pop_back() { MDValuePtrs.pop_back(); }
117 bool empty() const { return MDValuePtrs.empty(); }
119 Metadata *operator[](unsigned i) const {
120 assert(i < MDValuePtrs.size());
121 return MDValuePtrs[i];
124 void shrinkTo(unsigned N) {
125 assert(N <= size() && "Invalid shrinkTo request!");
126 MDValuePtrs.resize(N);
129 Metadata *getValueFwdRef(unsigned Idx);
130 void AssignValue(Metadata *MD, unsigned Idx);
131 void tryToResolveCycles();
134 class BitcodeReader : public GVMaterializer {
135 LLVMContext &Context;
136 DiagnosticHandlerFunction DiagnosticHandler;
138 std::unique_ptr<MemoryBuffer> Buffer;
139 std::unique_ptr<BitstreamReader> StreamFile;
140 BitstreamCursor Stream;
141 DataStreamer *LazyStreamer;
142 uint64_t NextUnreadBit;
143 bool SeenValueSymbolTable;
145 std::vector<Type*> TypeList;
146 BitcodeReaderValueList ValueList;
147 BitcodeReaderMDValueList MDValueList;
148 std::vector<Comdat *> ComdatList;
149 SmallVector<Instruction *, 64> InstructionList;
151 std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInits;
152 std::vector<std::pair<GlobalAlias*, unsigned> > AliasInits;
153 std::vector<std::pair<Function*, unsigned> > FunctionPrefixes;
154 std::vector<std::pair<Function*, unsigned> > FunctionPrologues;
156 SmallVector<Instruction*, 64> InstsWithTBAATag;
158 /// MAttributes - The set of attributes by index. Index zero in the
159 /// file is for null, and is thus not represented here. As such all indices
161 std::vector<AttributeSet> MAttributes;
163 /// \brief The set of attribute groups.
164 std::map<unsigned, AttributeSet> MAttributeGroups;
166 /// FunctionBBs - While parsing a function body, this is a list of the basic
167 /// blocks for the function.
168 std::vector<BasicBlock*> FunctionBBs;
170 // When reading the module header, this list is populated with functions that
171 // have bodies later in the file.
172 std::vector<Function*> FunctionsWithBodies;
174 // When intrinsic functions are encountered which require upgrading they are
175 // stored here with their replacement function.
176 typedef std::vector<std::pair<Function*, Function*> > UpgradedIntrinsicMap;
177 UpgradedIntrinsicMap UpgradedIntrinsics;
179 // Map the bitcode's custom MDKind ID to the Module's MDKind ID.
180 DenseMap<unsigned, unsigned> MDKindMap;
182 // Several operations happen after the module header has been read, but
183 // before function bodies are processed. This keeps track of whether
184 // we've done this yet.
185 bool SeenFirstFunctionBody;
187 /// DeferredFunctionInfo - When function bodies are initially scanned, this
188 /// map contains info about where to find deferred function body in the
190 DenseMap<Function*, uint64_t> DeferredFunctionInfo;
192 /// When Metadata block is initially scanned when parsing the module, we may
193 /// choose to defer parsing of the metadata. This vector contains info about
194 /// which Metadata blocks are deferred.
195 std::vector<uint64_t> DeferredMetadataInfo;
197 /// These are basic blocks forward-referenced by block addresses. They are
198 /// inserted lazily into functions when they're loaded. The basic block ID is
199 /// its index into the vector.
200 DenseMap<Function *, std::vector<BasicBlock *>> BasicBlockFwdRefs;
201 std::deque<Function *> BasicBlockFwdRefQueue;
203 /// UseRelativeIDs - Indicates that we are using a new encoding for
204 /// instruction operands where most operands in the current
205 /// FUNCTION_BLOCK are encoded relative to the instruction number,
206 /// for a more compact encoding. Some instruction operands are not
207 /// relative to the instruction ID: basic block numbers, and types.
208 /// Once the old style function blocks have been phased out, we would
209 /// not need this flag.
212 /// True if all functions will be materialized, negating the need to process
213 /// (e.g.) blockaddress forward references.
214 bool WillMaterializeAllForwardRefs;
216 /// Functions that have block addresses taken. This is usually empty.
217 SmallPtrSet<const Function *, 4> BlockAddressesTaken;
219 /// True if any Metadata block has been materialized.
220 bool IsMetadataMaterialized;
222 bool StripDebugInfo = false;
225 std::error_code Error(BitcodeError E, const Twine &Message);
226 std::error_code Error(BitcodeError E);
227 std::error_code Error(const Twine &Message);
229 explicit BitcodeReader(MemoryBuffer *buffer, LLVMContext &C,
230 DiagnosticHandlerFunction DiagnosticHandler);
231 explicit BitcodeReader(DataStreamer *streamer, LLVMContext &C,
232 DiagnosticHandlerFunction DiagnosticHandler);
233 ~BitcodeReader() override { FreeState(); }
235 std::error_code materializeForwardReferencedFunctions();
239 void releaseBuffer();
241 bool isDematerializable(const GlobalValue *GV) const override;
242 std::error_code materialize(GlobalValue *GV) override;
243 std::error_code MaterializeModule(Module *M) override;
244 std::vector<StructType *> getIdentifiedStructTypes() const override;
245 void Dematerialize(GlobalValue *GV) override;
247 /// @brief Main interface to parsing a bitcode buffer.
248 /// @returns true if an error occurred.
249 std::error_code ParseBitcodeInto(Module *M,
250 bool ShouldLazyLoadMetadata = false);
252 /// @brief Cheap mechanism to just extract module triple
253 /// @returns true if an error occurred.
254 ErrorOr<std::string> parseTriple();
256 static uint64_t decodeSignRotatedValue(uint64_t V);
258 /// Materialize any deferred Metadata block.
259 std::error_code materializeMetadata() override;
261 void setStripDebugInfo() override;
264 std::vector<StructType *> IdentifiedStructTypes;
265 StructType *createIdentifiedStructType(LLVMContext &Context, StringRef Name);
266 StructType *createIdentifiedStructType(LLVMContext &Context);
268 Type *getTypeByID(unsigned ID);
269 Value *getFnValueByID(unsigned ID, Type *Ty) {
270 if (Ty && Ty->isMetadataTy())
271 return MetadataAsValue::get(Ty->getContext(), getFnMetadataByID(ID));
272 return ValueList.getValueFwdRef(ID, Ty);
274 Metadata *getFnMetadataByID(unsigned ID) {
275 return MDValueList.getValueFwdRef(ID);
277 BasicBlock *getBasicBlock(unsigned ID) const {
278 if (ID >= FunctionBBs.size()) return nullptr; // Invalid ID
279 return FunctionBBs[ID];
281 AttributeSet getAttributes(unsigned i) const {
282 if (i-1 < MAttributes.size())
283 return MAttributes[i-1];
284 return AttributeSet();
287 /// getValueTypePair - Read a value/type pair out of the specified record from
288 /// slot 'Slot'. Increment Slot past the number of slots used in the record.
289 /// Return true on failure.
290 bool getValueTypePair(SmallVectorImpl<uint64_t> &Record, unsigned &Slot,
291 unsigned InstNum, Value *&ResVal) {
292 if (Slot == Record.size()) return true;
293 unsigned ValNo = (unsigned)Record[Slot++];
294 // Adjust the ValNo, if it was encoded relative to the InstNum.
296 ValNo = InstNum - ValNo;
297 if (ValNo < InstNum) {
298 // If this is not a forward reference, just return the value we already
300 ResVal = getFnValueByID(ValNo, nullptr);
301 return ResVal == nullptr;
302 } else if (Slot == Record.size()) {
306 unsigned TypeNo = (unsigned)Record[Slot++];
307 ResVal = getFnValueByID(ValNo, getTypeByID(TypeNo));
308 return ResVal == nullptr;
311 /// popValue - Read a value out of the specified record from slot 'Slot'.
312 /// Increment Slot past the number of slots used by the value in the record.
313 /// Return true if there is an error.
314 bool popValue(SmallVectorImpl<uint64_t> &Record, unsigned &Slot,
315 unsigned InstNum, Type *Ty, Value *&ResVal) {
316 if (getValue(Record, Slot, InstNum, Ty, ResVal))
318 // All values currently take a single record slot.
323 /// getValue -- Like popValue, but does not increment the Slot number.
324 bool getValue(SmallVectorImpl<uint64_t> &Record, unsigned Slot,
325 unsigned InstNum, Type *Ty, Value *&ResVal) {
326 ResVal = getValue(Record, Slot, InstNum, Ty);
327 return ResVal == nullptr;
330 /// getValue -- Version of getValue that returns ResVal directly,
331 /// or 0 if there is an error.
332 Value *getValue(SmallVectorImpl<uint64_t> &Record, unsigned Slot,
333 unsigned InstNum, Type *Ty) {
334 if (Slot == Record.size()) return nullptr;
335 unsigned ValNo = (unsigned)Record[Slot];
336 // Adjust the ValNo, if it was encoded relative to the InstNum.
338 ValNo = InstNum - ValNo;
339 return getFnValueByID(ValNo, Ty);
342 /// getValueSigned -- Like getValue, but decodes signed VBRs.
343 Value *getValueSigned(SmallVectorImpl<uint64_t> &Record, unsigned Slot,
344 unsigned InstNum, Type *Ty) {
345 if (Slot == Record.size()) return nullptr;
346 unsigned ValNo = (unsigned)decodeSignRotatedValue(Record[Slot]);
347 // Adjust the ValNo, if it was encoded relative to the InstNum.
349 ValNo = InstNum - ValNo;
350 return getFnValueByID(ValNo, Ty);
353 /// Converts alignment exponent (i.e. power of two (or zero)) to the
354 /// corresponding alignment to use. If alignment is too large, returns
355 /// a corresponding error code.
356 std::error_code parseAlignmentValue(uint64_t Exponent, unsigned &Alignment);
357 std::error_code ParseAttrKind(uint64_t Code, Attribute::AttrKind *Kind);
358 std::error_code ParseModule(bool Resume, bool ShouldLazyLoadMetadata = false);
359 std::error_code ParseAttributeBlock();
360 std::error_code ParseAttributeGroupBlock();
361 std::error_code ParseTypeTable();
362 std::error_code ParseTypeTableBody();
364 std::error_code ParseValueSymbolTable();
365 std::error_code ParseConstants();
366 std::error_code RememberAndSkipFunctionBody();
367 /// Save the positions of the Metadata blocks and skip parsing the blocks.
368 std::error_code rememberAndSkipMetadata();
369 std::error_code ParseFunctionBody(Function *F);
370 std::error_code GlobalCleanup();
371 std::error_code ResolveGlobalAndAliasInits();
372 std::error_code ParseMetadata();
373 std::error_code ParseMetadataAttachment();
374 ErrorOr<std::string> parseModuleTriple();
375 std::error_code ParseUseLists();
376 std::error_code InitStream();
377 std::error_code InitStreamFromBuffer();
378 std::error_code InitLazyStream();
379 std::error_code FindFunctionInStream(
381 DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator);
385 BitcodeDiagnosticInfo::BitcodeDiagnosticInfo(std::error_code EC,
386 DiagnosticSeverity Severity,
388 : DiagnosticInfo(DK_Bitcode, Severity), Msg(Msg), EC(EC) {}
390 void BitcodeDiagnosticInfo::print(DiagnosticPrinter &DP) const { DP << Msg; }
392 static std::error_code Error(DiagnosticHandlerFunction DiagnosticHandler,
393 std::error_code EC, const Twine &Message) {
394 BitcodeDiagnosticInfo DI(EC, DS_Error, Message);
395 DiagnosticHandler(DI);
399 static std::error_code Error(DiagnosticHandlerFunction DiagnosticHandler,
400 std::error_code EC) {
401 return Error(DiagnosticHandler, EC, EC.message());
404 std::error_code BitcodeReader::Error(BitcodeError E, const Twine &Message) {
405 return ::Error(DiagnosticHandler, make_error_code(E), Message);
408 std::error_code BitcodeReader::Error(const Twine &Message) {
409 return ::Error(DiagnosticHandler,
410 make_error_code(BitcodeError::CorruptedBitcode), Message);
413 std::error_code BitcodeReader::Error(BitcodeError E) {
414 return ::Error(DiagnosticHandler, make_error_code(E));
417 static DiagnosticHandlerFunction getDiagHandler(DiagnosticHandlerFunction F,
421 return [&C](const DiagnosticInfo &DI) { C.diagnose(DI); };
424 BitcodeReader::BitcodeReader(MemoryBuffer *buffer, LLVMContext &C,
425 DiagnosticHandlerFunction DiagnosticHandler)
426 : Context(C), DiagnosticHandler(getDiagHandler(DiagnosticHandler, C)),
427 TheModule(nullptr), Buffer(buffer), LazyStreamer(nullptr),
428 NextUnreadBit(0), SeenValueSymbolTable(false), ValueList(C),
429 MDValueList(C), SeenFirstFunctionBody(false), UseRelativeIDs(false),
430 WillMaterializeAllForwardRefs(false), IsMetadataMaterialized(false) {}
432 BitcodeReader::BitcodeReader(DataStreamer *streamer, LLVMContext &C,
433 DiagnosticHandlerFunction DiagnosticHandler)
434 : Context(C), DiagnosticHandler(getDiagHandler(DiagnosticHandler, C)),
435 TheModule(nullptr), Buffer(nullptr), LazyStreamer(streamer),
436 NextUnreadBit(0), SeenValueSymbolTable(false), ValueList(C),
437 MDValueList(C), SeenFirstFunctionBody(false), UseRelativeIDs(false),
438 WillMaterializeAllForwardRefs(false), IsMetadataMaterialized(false) {}
440 std::error_code BitcodeReader::materializeForwardReferencedFunctions() {
441 if (WillMaterializeAllForwardRefs)
442 return std::error_code();
444 // Prevent recursion.
445 WillMaterializeAllForwardRefs = true;
447 while (!BasicBlockFwdRefQueue.empty()) {
448 Function *F = BasicBlockFwdRefQueue.front();
449 BasicBlockFwdRefQueue.pop_front();
450 assert(F && "Expected valid function");
451 if (!BasicBlockFwdRefs.count(F))
452 // Already materialized.
455 // Check for a function that isn't materializable to prevent an infinite
456 // loop. When parsing a blockaddress stored in a global variable, there
457 // isn't a trivial way to check if a function will have a body without a
458 // linear search through FunctionsWithBodies, so just check it here.
459 if (!F->isMaterializable())
460 return Error("Never resolved function from blockaddress");
462 // Try to materialize F.
463 if (std::error_code EC = materialize(F))
466 assert(BasicBlockFwdRefs.empty() && "Function missing from queue");
469 WillMaterializeAllForwardRefs = false;
470 return std::error_code();
473 void BitcodeReader::FreeState() {
475 std::vector<Type*>().swap(TypeList);
478 std::vector<Comdat *>().swap(ComdatList);
480 std::vector<AttributeSet>().swap(MAttributes);
481 std::vector<BasicBlock*>().swap(FunctionBBs);
482 std::vector<Function*>().swap(FunctionsWithBodies);
483 DeferredFunctionInfo.clear();
484 DeferredMetadataInfo.clear();
487 assert(BasicBlockFwdRefs.empty() && "Unresolved blockaddress fwd references");
488 BasicBlockFwdRefQueue.clear();
491 //===----------------------------------------------------------------------===//
492 // Helper functions to implement forward reference resolution, etc.
493 //===----------------------------------------------------------------------===//
495 /// ConvertToString - Convert a string from a record into an std::string, return
497 template<typename StrTy>
498 static bool ConvertToString(ArrayRef<uint64_t> Record, unsigned Idx,
500 if (Idx > Record.size())
503 for (unsigned i = Idx, e = Record.size(); i != e; ++i)
504 Result += (char)Record[i];
508 static bool hasImplicitComdat(size_t Val) {
512 case 1: // Old WeakAnyLinkage
513 case 4: // Old LinkOnceAnyLinkage
514 case 10: // Old WeakODRLinkage
515 case 11: // Old LinkOnceODRLinkage
520 static GlobalValue::LinkageTypes getDecodedLinkage(unsigned Val) {
522 default: // Map unknown/new linkages to external
524 return GlobalValue::ExternalLinkage;
526 return GlobalValue::AppendingLinkage;
528 return GlobalValue::InternalLinkage;
530 return GlobalValue::ExternalLinkage; // Obsolete DLLImportLinkage
532 return GlobalValue::ExternalLinkage; // Obsolete DLLExportLinkage
534 return GlobalValue::ExternalWeakLinkage;
536 return GlobalValue::CommonLinkage;
538 return GlobalValue::PrivateLinkage;
540 return GlobalValue::AvailableExternallyLinkage;
542 return GlobalValue::PrivateLinkage; // Obsolete LinkerPrivateLinkage
544 return GlobalValue::PrivateLinkage; // Obsolete LinkerPrivateWeakLinkage
546 return GlobalValue::ExternalLinkage; // Obsolete LinkOnceODRAutoHideLinkage
547 case 1: // Old value with implicit comdat.
549 return GlobalValue::WeakAnyLinkage;
550 case 10: // Old value with implicit comdat.
552 return GlobalValue::WeakODRLinkage;
553 case 4: // Old value with implicit comdat.
555 return GlobalValue::LinkOnceAnyLinkage;
556 case 11: // Old value with implicit comdat.
558 return GlobalValue::LinkOnceODRLinkage;
562 static GlobalValue::VisibilityTypes GetDecodedVisibility(unsigned Val) {
564 default: // Map unknown visibilities to default.
565 case 0: return GlobalValue::DefaultVisibility;
566 case 1: return GlobalValue::HiddenVisibility;
567 case 2: return GlobalValue::ProtectedVisibility;
571 static GlobalValue::DLLStorageClassTypes
572 GetDecodedDLLStorageClass(unsigned Val) {
574 default: // Map unknown values to default.
575 case 0: return GlobalValue::DefaultStorageClass;
576 case 1: return GlobalValue::DLLImportStorageClass;
577 case 2: return GlobalValue::DLLExportStorageClass;
581 static GlobalVariable::ThreadLocalMode GetDecodedThreadLocalMode(unsigned Val) {
583 case 0: return GlobalVariable::NotThreadLocal;
584 default: // Map unknown non-zero value to general dynamic.
585 case 1: return GlobalVariable::GeneralDynamicTLSModel;
586 case 2: return GlobalVariable::LocalDynamicTLSModel;
587 case 3: return GlobalVariable::InitialExecTLSModel;
588 case 4: return GlobalVariable::LocalExecTLSModel;
592 static int GetDecodedCastOpcode(unsigned Val) {
595 case bitc::CAST_TRUNC : return Instruction::Trunc;
596 case bitc::CAST_ZEXT : return Instruction::ZExt;
597 case bitc::CAST_SEXT : return Instruction::SExt;
598 case bitc::CAST_FPTOUI : return Instruction::FPToUI;
599 case bitc::CAST_FPTOSI : return Instruction::FPToSI;
600 case bitc::CAST_UITOFP : return Instruction::UIToFP;
601 case bitc::CAST_SITOFP : return Instruction::SIToFP;
602 case bitc::CAST_FPTRUNC : return Instruction::FPTrunc;
603 case bitc::CAST_FPEXT : return Instruction::FPExt;
604 case bitc::CAST_PTRTOINT: return Instruction::PtrToInt;
605 case bitc::CAST_INTTOPTR: return Instruction::IntToPtr;
606 case bitc::CAST_BITCAST : return Instruction::BitCast;
607 case bitc::CAST_ADDRSPACECAST: return Instruction::AddrSpaceCast;
610 static int GetDecodedBinaryOpcode(unsigned Val, Type *Ty) {
613 case bitc::BINOP_ADD:
614 return Ty->isFPOrFPVectorTy() ? Instruction::FAdd : Instruction::Add;
615 case bitc::BINOP_SUB:
616 return Ty->isFPOrFPVectorTy() ? Instruction::FSub : Instruction::Sub;
617 case bitc::BINOP_MUL:
618 return Ty->isFPOrFPVectorTy() ? Instruction::FMul : Instruction::Mul;
619 case bitc::BINOP_UDIV: return Instruction::UDiv;
620 case bitc::BINOP_SDIV:
621 return Ty->isFPOrFPVectorTy() ? Instruction::FDiv : Instruction::SDiv;
622 case bitc::BINOP_UREM: return Instruction::URem;
623 case bitc::BINOP_SREM:
624 return Ty->isFPOrFPVectorTy() ? Instruction::FRem : Instruction::SRem;
625 case bitc::BINOP_SHL: return Instruction::Shl;
626 case bitc::BINOP_LSHR: return Instruction::LShr;
627 case bitc::BINOP_ASHR: return Instruction::AShr;
628 case bitc::BINOP_AND: return Instruction::And;
629 case bitc::BINOP_OR: return Instruction::Or;
630 case bitc::BINOP_XOR: return Instruction::Xor;
634 static AtomicRMWInst::BinOp GetDecodedRMWOperation(unsigned Val) {
636 default: return AtomicRMWInst::BAD_BINOP;
637 case bitc::RMW_XCHG: return AtomicRMWInst::Xchg;
638 case bitc::RMW_ADD: return AtomicRMWInst::Add;
639 case bitc::RMW_SUB: return AtomicRMWInst::Sub;
640 case bitc::RMW_AND: return AtomicRMWInst::And;
641 case bitc::RMW_NAND: return AtomicRMWInst::Nand;
642 case bitc::RMW_OR: return AtomicRMWInst::Or;
643 case bitc::RMW_XOR: return AtomicRMWInst::Xor;
644 case bitc::RMW_MAX: return AtomicRMWInst::Max;
645 case bitc::RMW_MIN: return AtomicRMWInst::Min;
646 case bitc::RMW_UMAX: return AtomicRMWInst::UMax;
647 case bitc::RMW_UMIN: return AtomicRMWInst::UMin;
651 static AtomicOrdering GetDecodedOrdering(unsigned Val) {
653 case bitc::ORDERING_NOTATOMIC: return NotAtomic;
654 case bitc::ORDERING_UNORDERED: return Unordered;
655 case bitc::ORDERING_MONOTONIC: return Monotonic;
656 case bitc::ORDERING_ACQUIRE: return Acquire;
657 case bitc::ORDERING_RELEASE: return Release;
658 case bitc::ORDERING_ACQREL: return AcquireRelease;
659 default: // Map unknown orderings to sequentially-consistent.
660 case bitc::ORDERING_SEQCST: return SequentiallyConsistent;
664 static SynchronizationScope GetDecodedSynchScope(unsigned Val) {
666 case bitc::SYNCHSCOPE_SINGLETHREAD: return SingleThread;
667 default: // Map unknown scopes to cross-thread.
668 case bitc::SYNCHSCOPE_CROSSTHREAD: return CrossThread;
672 static Comdat::SelectionKind getDecodedComdatSelectionKind(unsigned Val) {
674 default: // Map unknown selection kinds to any.
675 case bitc::COMDAT_SELECTION_KIND_ANY:
677 case bitc::COMDAT_SELECTION_KIND_EXACT_MATCH:
678 return Comdat::ExactMatch;
679 case bitc::COMDAT_SELECTION_KIND_LARGEST:
680 return Comdat::Largest;
681 case bitc::COMDAT_SELECTION_KIND_NO_DUPLICATES:
682 return Comdat::NoDuplicates;
683 case bitc::COMDAT_SELECTION_KIND_SAME_SIZE:
684 return Comdat::SameSize;
688 static void UpgradeDLLImportExportLinkage(llvm::GlobalValue *GV, unsigned Val) {
690 case 5: GV->setDLLStorageClass(GlobalValue::DLLImportStorageClass); break;
691 case 6: GV->setDLLStorageClass(GlobalValue::DLLExportStorageClass); break;
697 /// @brief A class for maintaining the slot number definition
698 /// as a placeholder for the actual definition for forward constants defs.
699 class ConstantPlaceHolder : public ConstantExpr {
700 void operator=(const ConstantPlaceHolder &) = delete;
702 // allocate space for exactly one operand
703 void *operator new(size_t s) {
704 return User::operator new(s, 1);
706 explicit ConstantPlaceHolder(Type *Ty, LLVMContext& Context)
707 : ConstantExpr(Ty, Instruction::UserOp1, &Op<0>(), 1) {
708 Op<0>() = UndefValue::get(Type::getInt32Ty(Context));
711 /// @brief Methods to support type inquiry through isa, cast, and dyn_cast.
712 static bool classof(const Value *V) {
713 return isa<ConstantExpr>(V) &&
714 cast<ConstantExpr>(V)->getOpcode() == Instruction::UserOp1;
718 /// Provide fast operand accessors
719 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
723 // FIXME: can we inherit this from ConstantExpr?
725 struct OperandTraits<ConstantPlaceHolder> :
726 public FixedNumOperandTraits<ConstantPlaceHolder, 1> {
728 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ConstantPlaceHolder, Value)
732 void BitcodeReaderValueList::AssignValue(Value *V, unsigned Idx) {
741 WeakVH &OldV = ValuePtrs[Idx];
747 // Handle constants and non-constants (e.g. instrs) differently for
749 if (Constant *PHC = dyn_cast<Constant>(&*OldV)) {
750 ResolveConstants.push_back(std::make_pair(PHC, Idx));
753 // If there was a forward reference to this value, replace it.
754 Value *PrevVal = OldV;
755 OldV->replaceAllUsesWith(V);
761 Constant *BitcodeReaderValueList::getConstantFwdRef(unsigned Idx,
766 if (Value *V = ValuePtrs[Idx]) {
767 assert(Ty == V->getType() && "Type mismatch in constant table!");
768 return cast<Constant>(V);
771 // Create and return a placeholder, which will later be RAUW'd.
772 Constant *C = new ConstantPlaceHolder(Ty, Context);
777 Value *BitcodeReaderValueList::getValueFwdRef(unsigned Idx, Type *Ty) {
781 if (Value *V = ValuePtrs[Idx]) {
782 assert((!Ty || Ty == V->getType()) && "Type mismatch in value table!");
786 // No type specified, must be invalid reference.
787 if (!Ty) return nullptr;
789 // Create and return a placeholder, which will later be RAUW'd.
790 Value *V = new Argument(Ty);
795 /// ResolveConstantForwardRefs - Once all constants are read, this method bulk
796 /// resolves any forward references. The idea behind this is that we sometimes
797 /// get constants (such as large arrays) which reference *many* forward ref
798 /// constants. Replacing each of these causes a lot of thrashing when
799 /// building/reuniquing the constant. Instead of doing this, we look at all the
800 /// uses and rewrite all the place holders at once for any constant that uses
802 void BitcodeReaderValueList::ResolveConstantForwardRefs() {
803 // Sort the values by-pointer so that they are efficient to look up with a
805 std::sort(ResolveConstants.begin(), ResolveConstants.end());
807 SmallVector<Constant*, 64> NewOps;
809 while (!ResolveConstants.empty()) {
810 Value *RealVal = operator[](ResolveConstants.back().second);
811 Constant *Placeholder = ResolveConstants.back().first;
812 ResolveConstants.pop_back();
814 // Loop over all users of the placeholder, updating them to reference the
815 // new value. If they reference more than one placeholder, update them all
817 while (!Placeholder->use_empty()) {
818 auto UI = Placeholder->user_begin();
821 // If the using object isn't uniqued, just update the operands. This
822 // handles instructions and initializers for global variables.
823 if (!isa<Constant>(U) || isa<GlobalValue>(U)) {
824 UI.getUse().set(RealVal);
828 // Otherwise, we have a constant that uses the placeholder. Replace that
829 // constant with a new constant that has *all* placeholder uses updated.
830 Constant *UserC = cast<Constant>(U);
831 for (User::op_iterator I = UserC->op_begin(), E = UserC->op_end();
834 if (!isa<ConstantPlaceHolder>(*I)) {
835 // Not a placeholder reference.
837 } else if (*I == Placeholder) {
838 // Common case is that it just references this one placeholder.
841 // Otherwise, look up the placeholder in ResolveConstants.
842 ResolveConstantsTy::iterator It =
843 std::lower_bound(ResolveConstants.begin(), ResolveConstants.end(),
844 std::pair<Constant*, unsigned>(cast<Constant>(*I),
846 assert(It != ResolveConstants.end() && It->first == *I);
847 NewOp = operator[](It->second);
850 NewOps.push_back(cast<Constant>(NewOp));
853 // Make the new constant.
855 if (ConstantArray *UserCA = dyn_cast<ConstantArray>(UserC)) {
856 NewC = ConstantArray::get(UserCA->getType(), NewOps);
857 } else if (ConstantStruct *UserCS = dyn_cast<ConstantStruct>(UserC)) {
858 NewC = ConstantStruct::get(UserCS->getType(), NewOps);
859 } else if (isa<ConstantVector>(UserC)) {
860 NewC = ConstantVector::get(NewOps);
862 assert(isa<ConstantExpr>(UserC) && "Must be a ConstantExpr.");
863 NewC = cast<ConstantExpr>(UserC)->getWithOperands(NewOps);
866 UserC->replaceAllUsesWith(NewC);
867 UserC->destroyConstant();
871 // Update all ValueHandles, they should be the only users at this point.
872 Placeholder->replaceAllUsesWith(RealVal);
877 void BitcodeReaderMDValueList::AssignValue(Metadata *MD, unsigned Idx) {
886 TrackingMDRef &OldMD = MDValuePtrs[Idx];
892 // If there was a forward reference to this value, replace it.
893 TempMDTuple PrevMD(cast<MDTuple>(OldMD.get()));
894 PrevMD->replaceAllUsesWith(MD);
898 Metadata *BitcodeReaderMDValueList::getValueFwdRef(unsigned Idx) {
902 if (Metadata *MD = MDValuePtrs[Idx])
905 // Track forward refs to be resolved later.
907 MinFwdRef = std::min(MinFwdRef, Idx);
908 MaxFwdRef = std::max(MaxFwdRef, Idx);
911 MinFwdRef = MaxFwdRef = Idx;
915 // Create and return a placeholder, which will later be RAUW'd.
916 Metadata *MD = MDNode::getTemporary(Context, None).release();
917 MDValuePtrs[Idx].reset(MD);
921 void BitcodeReaderMDValueList::tryToResolveCycles() {
927 // Still forward references... can't resolve cycles.
930 // Resolve any cycles.
931 for (unsigned I = MinFwdRef, E = MaxFwdRef + 1; I != E; ++I) {
932 auto &MD = MDValuePtrs[I];
933 auto *N = dyn_cast_or_null<MDNode>(MD);
937 assert(!N->isTemporary() && "Unexpected forward reference");
941 // Make sure we return early again until there's another forward ref.
945 Type *BitcodeReader::getTypeByID(unsigned ID) {
946 // The type table size is always specified correctly.
947 if (ID >= TypeList.size())
950 if (Type *Ty = TypeList[ID])
953 // If we have a forward reference, the only possible case is when it is to a
954 // named struct. Just create a placeholder for now.
955 return TypeList[ID] = createIdentifiedStructType(Context);
958 StructType *BitcodeReader::createIdentifiedStructType(LLVMContext &Context,
960 auto *Ret = StructType::create(Context, Name);
961 IdentifiedStructTypes.push_back(Ret);
965 StructType *BitcodeReader::createIdentifiedStructType(LLVMContext &Context) {
966 auto *Ret = StructType::create(Context);
967 IdentifiedStructTypes.push_back(Ret);
972 //===----------------------------------------------------------------------===//
973 // Functions for parsing blocks from the bitcode file
974 //===----------------------------------------------------------------------===//
977 /// \brief This fills an AttrBuilder object with the LLVM attributes that have
978 /// been decoded from the given integer. This function must stay in sync with
979 /// 'encodeLLVMAttributesForBitcode'.
980 static void decodeLLVMAttributesForBitcode(AttrBuilder &B,
981 uint64_t EncodedAttrs) {
982 // FIXME: Remove in 4.0.
984 // The alignment is stored as a 16-bit raw value from bits 31--16. We shift
985 // the bits above 31 down by 11 bits.
986 unsigned Alignment = (EncodedAttrs & (0xffffULL << 16)) >> 16;
987 assert((!Alignment || isPowerOf2_32(Alignment)) &&
988 "Alignment must be a power of two.");
991 B.addAlignmentAttr(Alignment);
992 B.addRawValue(((EncodedAttrs & (0xfffffULL << 32)) >> 11) |
993 (EncodedAttrs & 0xffff));
996 std::error_code BitcodeReader::ParseAttributeBlock() {
997 if (Stream.EnterSubBlock(bitc::PARAMATTR_BLOCK_ID))
998 return Error("Invalid record");
1000 if (!MAttributes.empty())
1001 return Error("Invalid multiple blocks");
1003 SmallVector<uint64_t, 64> Record;
1005 SmallVector<AttributeSet, 8> Attrs;
1007 // Read all the records.
1009 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1011 switch (Entry.Kind) {
1012 case BitstreamEntry::SubBlock: // Handled for us already.
1013 case BitstreamEntry::Error:
1014 return Error("Malformed block");
1015 case BitstreamEntry::EndBlock:
1016 return std::error_code();
1017 case BitstreamEntry::Record:
1018 // The interesting case.
1024 switch (Stream.readRecord(Entry.ID, Record)) {
1025 default: // Default behavior: ignore.
1027 case bitc::PARAMATTR_CODE_ENTRY_OLD: { // ENTRY: [paramidx0, attr0, ...]
1028 // FIXME: Remove in 4.0.
1029 if (Record.size() & 1)
1030 return Error("Invalid record");
1032 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
1034 decodeLLVMAttributesForBitcode(B, Record[i+1]);
1035 Attrs.push_back(AttributeSet::get(Context, Record[i], B));
1038 MAttributes.push_back(AttributeSet::get(Context, Attrs));
1042 case bitc::PARAMATTR_CODE_ENTRY: { // ENTRY: [attrgrp0, attrgrp1, ...]
1043 for (unsigned i = 0, e = Record.size(); i != e; ++i)
1044 Attrs.push_back(MAttributeGroups[Record[i]]);
1046 MAttributes.push_back(AttributeSet::get(Context, Attrs));
1054 // Returns Attribute::None on unrecognized codes.
1055 static Attribute::AttrKind GetAttrFromCode(uint64_t Code) {
1058 return Attribute::None;
1059 case bitc::ATTR_KIND_ALIGNMENT:
1060 return Attribute::Alignment;
1061 case bitc::ATTR_KIND_ALWAYS_INLINE:
1062 return Attribute::AlwaysInline;
1063 case bitc::ATTR_KIND_BUILTIN:
1064 return Attribute::Builtin;
1065 case bitc::ATTR_KIND_BY_VAL:
1066 return Attribute::ByVal;
1067 case bitc::ATTR_KIND_IN_ALLOCA:
1068 return Attribute::InAlloca;
1069 case bitc::ATTR_KIND_COLD:
1070 return Attribute::Cold;
1071 case bitc::ATTR_KIND_INLINE_HINT:
1072 return Attribute::InlineHint;
1073 case bitc::ATTR_KIND_IN_REG:
1074 return Attribute::InReg;
1075 case bitc::ATTR_KIND_JUMP_TABLE:
1076 return Attribute::JumpTable;
1077 case bitc::ATTR_KIND_MIN_SIZE:
1078 return Attribute::MinSize;
1079 case bitc::ATTR_KIND_NAKED:
1080 return Attribute::Naked;
1081 case bitc::ATTR_KIND_NEST:
1082 return Attribute::Nest;
1083 case bitc::ATTR_KIND_NO_ALIAS:
1084 return Attribute::NoAlias;
1085 case bitc::ATTR_KIND_NO_BUILTIN:
1086 return Attribute::NoBuiltin;
1087 case bitc::ATTR_KIND_NO_CAPTURE:
1088 return Attribute::NoCapture;
1089 case bitc::ATTR_KIND_NO_DUPLICATE:
1090 return Attribute::NoDuplicate;
1091 case bitc::ATTR_KIND_NO_IMPLICIT_FLOAT:
1092 return Attribute::NoImplicitFloat;
1093 case bitc::ATTR_KIND_NO_INLINE:
1094 return Attribute::NoInline;
1095 case bitc::ATTR_KIND_NON_LAZY_BIND:
1096 return Attribute::NonLazyBind;
1097 case bitc::ATTR_KIND_NON_NULL:
1098 return Attribute::NonNull;
1099 case bitc::ATTR_KIND_DEREFERENCEABLE:
1100 return Attribute::Dereferenceable;
1101 case bitc::ATTR_KIND_DEREFERENCEABLE_OR_NULL:
1102 return Attribute::DereferenceableOrNull;
1103 case bitc::ATTR_KIND_NO_RED_ZONE:
1104 return Attribute::NoRedZone;
1105 case bitc::ATTR_KIND_NO_RETURN:
1106 return Attribute::NoReturn;
1107 case bitc::ATTR_KIND_NO_UNWIND:
1108 return Attribute::NoUnwind;
1109 case bitc::ATTR_KIND_OPTIMIZE_FOR_SIZE:
1110 return Attribute::OptimizeForSize;
1111 case bitc::ATTR_KIND_OPTIMIZE_NONE:
1112 return Attribute::OptimizeNone;
1113 case bitc::ATTR_KIND_READ_NONE:
1114 return Attribute::ReadNone;
1115 case bitc::ATTR_KIND_READ_ONLY:
1116 return Attribute::ReadOnly;
1117 case bitc::ATTR_KIND_RETURNED:
1118 return Attribute::Returned;
1119 case bitc::ATTR_KIND_RETURNS_TWICE:
1120 return Attribute::ReturnsTwice;
1121 case bitc::ATTR_KIND_S_EXT:
1122 return Attribute::SExt;
1123 case bitc::ATTR_KIND_STACK_ALIGNMENT:
1124 return Attribute::StackAlignment;
1125 case bitc::ATTR_KIND_STACK_PROTECT:
1126 return Attribute::StackProtect;
1127 case bitc::ATTR_KIND_STACK_PROTECT_REQ:
1128 return Attribute::StackProtectReq;
1129 case bitc::ATTR_KIND_STACK_PROTECT_STRONG:
1130 return Attribute::StackProtectStrong;
1131 case bitc::ATTR_KIND_STRUCT_RET:
1132 return Attribute::StructRet;
1133 case bitc::ATTR_KIND_SANITIZE_ADDRESS:
1134 return Attribute::SanitizeAddress;
1135 case bitc::ATTR_KIND_SANITIZE_THREAD:
1136 return Attribute::SanitizeThread;
1137 case bitc::ATTR_KIND_SANITIZE_MEMORY:
1138 return Attribute::SanitizeMemory;
1139 case bitc::ATTR_KIND_UW_TABLE:
1140 return Attribute::UWTable;
1141 case bitc::ATTR_KIND_Z_EXT:
1142 return Attribute::ZExt;
1146 std::error_code BitcodeReader::parseAlignmentValue(uint64_t Exponent,
1147 unsigned &Alignment) {
1148 // Note: Alignment in bitcode files is incremented by 1, so that zero
1149 // can be used for default alignment.
1150 if (Exponent > Value::MaxAlignmentExponent + 1)
1151 return Error("Invalid alignment value");
1152 Alignment = (1 << static_cast<unsigned>(Exponent)) >> 1;
1153 return std::error_code();
1156 std::error_code BitcodeReader::ParseAttrKind(uint64_t Code,
1157 Attribute::AttrKind *Kind) {
1158 *Kind = GetAttrFromCode(Code);
1159 if (*Kind == Attribute::None)
1160 return Error(BitcodeError::CorruptedBitcode,
1161 "Unknown attribute kind (" + Twine(Code) + ")");
1162 return std::error_code();
1165 std::error_code BitcodeReader::ParseAttributeGroupBlock() {
1166 if (Stream.EnterSubBlock(bitc::PARAMATTR_GROUP_BLOCK_ID))
1167 return Error("Invalid record");
1169 if (!MAttributeGroups.empty())
1170 return Error("Invalid multiple blocks");
1172 SmallVector<uint64_t, 64> Record;
1174 // Read all the records.
1176 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1178 switch (Entry.Kind) {
1179 case BitstreamEntry::SubBlock: // Handled for us already.
1180 case BitstreamEntry::Error:
1181 return Error("Malformed block");
1182 case BitstreamEntry::EndBlock:
1183 return std::error_code();
1184 case BitstreamEntry::Record:
1185 // The interesting case.
1191 switch (Stream.readRecord(Entry.ID, Record)) {
1192 default: // Default behavior: ignore.
1194 case bitc::PARAMATTR_GRP_CODE_ENTRY: { // ENTRY: [grpid, idx, a0, a1, ...]
1195 if (Record.size() < 3)
1196 return Error("Invalid record");
1198 uint64_t GrpID = Record[0];
1199 uint64_t Idx = Record[1]; // Index of the object this attribute refers to.
1202 for (unsigned i = 2, e = Record.size(); i != e; ++i) {
1203 if (Record[i] == 0) { // Enum attribute
1204 Attribute::AttrKind Kind;
1205 if (std::error_code EC = ParseAttrKind(Record[++i], &Kind))
1208 B.addAttribute(Kind);
1209 } else if (Record[i] == 1) { // Integer attribute
1210 Attribute::AttrKind Kind;
1211 if (std::error_code EC = ParseAttrKind(Record[++i], &Kind))
1213 if (Kind == Attribute::Alignment)
1214 B.addAlignmentAttr(Record[++i]);
1215 else if (Kind == Attribute::StackAlignment)
1216 B.addStackAlignmentAttr(Record[++i]);
1217 else if (Kind == Attribute::Dereferenceable)
1218 B.addDereferenceableAttr(Record[++i]);
1219 else if (Kind == Attribute::DereferenceableOrNull)
1220 B.addDereferenceableOrNullAttr(Record[++i]);
1221 } else { // String attribute
1222 assert((Record[i] == 3 || Record[i] == 4) &&
1223 "Invalid attribute group entry");
1224 bool HasValue = (Record[i++] == 4);
1225 SmallString<64> KindStr;
1226 SmallString<64> ValStr;
1228 while (Record[i] != 0 && i != e)
1229 KindStr += Record[i++];
1230 assert(Record[i] == 0 && "Kind string not null terminated");
1233 // Has a value associated with it.
1234 ++i; // Skip the '0' that terminates the "kind" string.
1235 while (Record[i] != 0 && i != e)
1236 ValStr += Record[i++];
1237 assert(Record[i] == 0 && "Value string not null terminated");
1240 B.addAttribute(KindStr.str(), ValStr.str());
1244 MAttributeGroups[GrpID] = AttributeSet::get(Context, Idx, B);
1251 std::error_code BitcodeReader::ParseTypeTable() {
1252 if (Stream.EnterSubBlock(bitc::TYPE_BLOCK_ID_NEW))
1253 return Error("Invalid record");
1255 return ParseTypeTableBody();
1258 std::error_code BitcodeReader::ParseTypeTableBody() {
1259 if (!TypeList.empty())
1260 return Error("Invalid multiple blocks");
1262 SmallVector<uint64_t, 64> Record;
1263 unsigned NumRecords = 0;
1265 SmallString<64> TypeName;
1267 // Read all the records for this type table.
1269 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1271 switch (Entry.Kind) {
1272 case BitstreamEntry::SubBlock: // Handled for us already.
1273 case BitstreamEntry::Error:
1274 return Error("Malformed block");
1275 case BitstreamEntry::EndBlock:
1276 if (NumRecords != TypeList.size())
1277 return Error("Malformed block");
1278 return std::error_code();
1279 case BitstreamEntry::Record:
1280 // The interesting case.
1286 Type *ResultTy = nullptr;
1287 switch (Stream.readRecord(Entry.ID, Record)) {
1289 return Error("Invalid value");
1290 case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries]
1291 // TYPE_CODE_NUMENTRY contains a count of the number of types in the
1292 // type list. This allows us to reserve space.
1293 if (Record.size() < 1)
1294 return Error("Invalid record");
1295 TypeList.resize(Record[0]);
1297 case bitc::TYPE_CODE_VOID: // VOID
1298 ResultTy = Type::getVoidTy(Context);
1300 case bitc::TYPE_CODE_HALF: // HALF
1301 ResultTy = Type::getHalfTy(Context);
1303 case bitc::TYPE_CODE_FLOAT: // FLOAT
1304 ResultTy = Type::getFloatTy(Context);
1306 case bitc::TYPE_CODE_DOUBLE: // DOUBLE
1307 ResultTy = Type::getDoubleTy(Context);
1309 case bitc::TYPE_CODE_X86_FP80: // X86_FP80
1310 ResultTy = Type::getX86_FP80Ty(Context);
1312 case bitc::TYPE_CODE_FP128: // FP128
1313 ResultTy = Type::getFP128Ty(Context);
1315 case bitc::TYPE_CODE_PPC_FP128: // PPC_FP128
1316 ResultTy = Type::getPPC_FP128Ty(Context);
1318 case bitc::TYPE_CODE_LABEL: // LABEL
1319 ResultTy = Type::getLabelTy(Context);
1321 case bitc::TYPE_CODE_METADATA: // METADATA
1322 ResultTy = Type::getMetadataTy(Context);
1324 case bitc::TYPE_CODE_X86_MMX: // X86_MMX
1325 ResultTy = Type::getX86_MMXTy(Context);
1327 case bitc::TYPE_CODE_INTEGER: { // INTEGER: [width]
1328 if (Record.size() < 1)
1329 return Error("Invalid record");
1331 uint64_t NumBits = Record[0];
1332 if (NumBits < IntegerType::MIN_INT_BITS ||
1333 NumBits > IntegerType::MAX_INT_BITS)
1334 return Error("Bitwidth for integer type out of range");
1335 ResultTy = IntegerType::get(Context, NumBits);
1338 case bitc::TYPE_CODE_POINTER: { // POINTER: [pointee type] or
1339 // [pointee type, address space]
1340 if (Record.size() < 1)
1341 return Error("Invalid record");
1342 unsigned AddressSpace = 0;
1343 if (Record.size() == 2)
1344 AddressSpace = Record[1];
1345 ResultTy = getTypeByID(Record[0]);
1347 return Error("Invalid type");
1348 ResultTy = PointerType::get(ResultTy, AddressSpace);
1351 case bitc::TYPE_CODE_FUNCTION_OLD: {
1352 // FIXME: attrid is dead, remove it in LLVM 4.0
1353 // FUNCTION: [vararg, attrid, retty, paramty x N]
1354 if (Record.size() < 3)
1355 return Error("Invalid record");
1356 SmallVector<Type*, 8> ArgTys;
1357 for (unsigned i = 3, e = Record.size(); i != e; ++i) {
1358 if (Type *T = getTypeByID(Record[i]))
1359 ArgTys.push_back(T);
1364 ResultTy = getTypeByID(Record[2]);
1365 if (!ResultTy || ArgTys.size() < Record.size()-3)
1366 return Error("Invalid type");
1368 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
1371 case bitc::TYPE_CODE_FUNCTION: {
1372 // FUNCTION: [vararg, retty, paramty x N]
1373 if (Record.size() < 2)
1374 return Error("Invalid record");
1375 SmallVector<Type*, 8> ArgTys;
1376 for (unsigned i = 2, e = Record.size(); i != e; ++i) {
1377 if (Type *T = getTypeByID(Record[i]))
1378 ArgTys.push_back(T);
1383 ResultTy = getTypeByID(Record[1]);
1384 if (!ResultTy || ArgTys.size() < Record.size()-2)
1385 return Error("Invalid type");
1387 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
1390 case bitc::TYPE_CODE_STRUCT_ANON: { // STRUCT: [ispacked, eltty x N]
1391 if (Record.size() < 1)
1392 return Error("Invalid record");
1393 SmallVector<Type*, 8> EltTys;
1394 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
1395 if (Type *T = getTypeByID(Record[i]))
1396 EltTys.push_back(T);
1400 if (EltTys.size() != Record.size()-1)
1401 return Error("Invalid type");
1402 ResultTy = StructType::get(Context, EltTys, Record[0]);
1405 case bitc::TYPE_CODE_STRUCT_NAME: // STRUCT_NAME: [strchr x N]
1406 if (ConvertToString(Record, 0, TypeName))
1407 return Error("Invalid record");
1410 case bitc::TYPE_CODE_STRUCT_NAMED: { // STRUCT: [ispacked, eltty x N]
1411 if (Record.size() < 1)
1412 return Error("Invalid record");
1414 if (NumRecords >= TypeList.size())
1415 return Error("Invalid TYPE table");
1417 // Check to see if this was forward referenced, if so fill in the temp.
1418 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
1420 Res->setName(TypeName);
1421 TypeList[NumRecords] = nullptr;
1422 } else // Otherwise, create a new struct.
1423 Res = createIdentifiedStructType(Context, TypeName);
1426 SmallVector<Type*, 8> EltTys;
1427 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
1428 if (Type *T = getTypeByID(Record[i]))
1429 EltTys.push_back(T);
1433 if (EltTys.size() != Record.size()-1)
1434 return Error("Invalid record");
1435 Res->setBody(EltTys, Record[0]);
1439 case bitc::TYPE_CODE_OPAQUE: { // OPAQUE: []
1440 if (Record.size() != 1)
1441 return Error("Invalid record");
1443 if (NumRecords >= TypeList.size())
1444 return Error("Invalid TYPE table");
1446 // Check to see if this was forward referenced, if so fill in the temp.
1447 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
1449 Res->setName(TypeName);
1450 TypeList[NumRecords] = nullptr;
1451 } else // Otherwise, create a new struct with no body.
1452 Res = createIdentifiedStructType(Context, TypeName);
1457 case bitc::TYPE_CODE_ARRAY: // ARRAY: [numelts, eltty]
1458 if (Record.size() < 2)
1459 return Error("Invalid record");
1460 if ((ResultTy = getTypeByID(Record[1])))
1461 ResultTy = ArrayType::get(ResultTy, Record[0]);
1463 return Error("Invalid type");
1465 case bitc::TYPE_CODE_VECTOR: // VECTOR: [numelts, eltty]
1466 if (Record.size() < 2)
1467 return Error("Invalid record");
1468 if ((ResultTy = getTypeByID(Record[1])))
1469 ResultTy = VectorType::get(ResultTy, Record[0]);
1471 return Error("Invalid type");
1475 if (NumRecords >= TypeList.size())
1476 return Error("Invalid TYPE table");
1477 if (TypeList[NumRecords])
1479 "Invalid TYPE table: Only named structs can be forward referenced");
1480 assert(ResultTy && "Didn't read a type?");
1481 TypeList[NumRecords++] = ResultTy;
1485 std::error_code BitcodeReader::ParseValueSymbolTable() {
1486 if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
1487 return Error("Invalid record");
1489 SmallVector<uint64_t, 64> Record;
1491 Triple TT(TheModule->getTargetTriple());
1493 // Read all the records for this value table.
1494 SmallString<128> ValueName;
1496 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1498 switch (Entry.Kind) {
1499 case BitstreamEntry::SubBlock: // Handled for us already.
1500 case BitstreamEntry::Error:
1501 return Error("Malformed block");
1502 case BitstreamEntry::EndBlock:
1503 return std::error_code();
1504 case BitstreamEntry::Record:
1505 // The interesting case.
1511 switch (Stream.readRecord(Entry.ID, Record)) {
1512 default: // Default behavior: unknown type.
1514 case bitc::VST_CODE_ENTRY: { // VST_ENTRY: [valueid, namechar x N]
1515 if (ConvertToString(Record, 1, ValueName))
1516 return Error("Invalid record");
1517 unsigned ValueID = Record[0];
1518 if (ValueID >= ValueList.size() || !ValueList[ValueID])
1519 return Error("Invalid record");
1520 Value *V = ValueList[ValueID];
1522 V->setName(StringRef(ValueName.data(), ValueName.size()));
1523 if (auto *GO = dyn_cast<GlobalObject>(V)) {
1524 if (GO->getComdat() == reinterpret_cast<Comdat *>(1)) {
1525 if (TT.isOSBinFormatMachO())
1526 GO->setComdat(nullptr);
1528 GO->setComdat(TheModule->getOrInsertComdat(V->getName()));
1534 case bitc::VST_CODE_BBENTRY: {
1535 if (ConvertToString(Record, 1, ValueName))
1536 return Error("Invalid record");
1537 BasicBlock *BB = getBasicBlock(Record[0]);
1539 return Error("Invalid record");
1541 BB->setName(StringRef(ValueName.data(), ValueName.size()));
1549 static int64_t unrotateSign(uint64_t U) { return U & 1 ? ~(U >> 1) : U >> 1; }
1551 std::error_code BitcodeReader::ParseMetadata() {
1552 IsMetadataMaterialized = true;
1553 unsigned NextMDValueNo = MDValueList.size();
1555 if (Stream.EnterSubBlock(bitc::METADATA_BLOCK_ID))
1556 return Error("Invalid record");
1558 SmallVector<uint64_t, 64> Record;
1561 [&](unsigned ID) -> Metadata *{ return MDValueList.getValueFwdRef(ID); };
1562 auto getMDOrNull = [&](unsigned ID) -> Metadata *{
1564 return getMD(ID - 1);
1567 auto getMDString = [&](unsigned ID) -> MDString *{
1568 // This requires that the ID is not really a forward reference. In
1569 // particular, the MDString must already have been resolved.
1570 return cast_or_null<MDString>(getMDOrNull(ID));
1573 #define GET_OR_DISTINCT(CLASS, DISTINCT, ARGS) \
1574 (DISTINCT ? CLASS::getDistinct ARGS : CLASS::get ARGS)
1576 // Read all the records.
1578 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1580 switch (Entry.Kind) {
1581 case BitstreamEntry::SubBlock: // Handled for us already.
1582 case BitstreamEntry::Error:
1583 return Error("Malformed block");
1584 case BitstreamEntry::EndBlock:
1585 MDValueList.tryToResolveCycles();
1586 return std::error_code();
1587 case BitstreamEntry::Record:
1588 // The interesting case.
1594 unsigned Code = Stream.readRecord(Entry.ID, Record);
1595 bool IsDistinct = false;
1597 default: // Default behavior: ignore.
1599 case bitc::METADATA_NAME: {
1600 // Read name of the named metadata.
1601 SmallString<8> Name(Record.begin(), Record.end());
1603 Code = Stream.ReadCode();
1605 // METADATA_NAME is always followed by METADATA_NAMED_NODE.
1606 unsigned NextBitCode = Stream.readRecord(Code, Record);
1607 assert(NextBitCode == bitc::METADATA_NAMED_NODE); (void)NextBitCode;
1609 // Read named metadata elements.
1610 unsigned Size = Record.size();
1611 NamedMDNode *NMD = TheModule->getOrInsertNamedMetadata(Name);
1612 for (unsigned i = 0; i != Size; ++i) {
1613 MDNode *MD = dyn_cast_or_null<MDNode>(MDValueList.getValueFwdRef(Record[i]));
1615 return Error("Invalid record");
1616 NMD->addOperand(MD);
1620 case bitc::METADATA_OLD_FN_NODE: {
1621 // FIXME: Remove in 4.0.
1622 // This is a LocalAsMetadata record, the only type of function-local
1624 if (Record.size() % 2 == 1)
1625 return Error("Invalid record");
1627 // If this isn't a LocalAsMetadata record, we're dropping it. This used
1628 // to be legal, but there's no upgrade path.
1629 auto dropRecord = [&] {
1630 MDValueList.AssignValue(MDNode::get(Context, None), NextMDValueNo++);
1632 if (Record.size() != 2) {
1637 Type *Ty = getTypeByID(Record[0]);
1638 if (Ty->isMetadataTy() || Ty->isVoidTy()) {
1643 MDValueList.AssignValue(
1644 LocalAsMetadata::get(ValueList.getValueFwdRef(Record[1], Ty)),
1648 case bitc::METADATA_OLD_NODE: {
1649 // FIXME: Remove in 4.0.
1650 if (Record.size() % 2 == 1)
1651 return Error("Invalid record");
1653 unsigned Size = Record.size();
1654 SmallVector<Metadata *, 8> Elts;
1655 for (unsigned i = 0; i != Size; i += 2) {
1656 Type *Ty = getTypeByID(Record[i]);
1658 return Error("Invalid record");
1659 if (Ty->isMetadataTy())
1660 Elts.push_back(MDValueList.getValueFwdRef(Record[i+1]));
1661 else if (!Ty->isVoidTy()) {
1663 ValueAsMetadata::get(ValueList.getValueFwdRef(Record[i + 1], Ty));
1664 assert(isa<ConstantAsMetadata>(MD) &&
1665 "Expected non-function-local metadata");
1668 Elts.push_back(nullptr);
1670 MDValueList.AssignValue(MDNode::get(Context, Elts), NextMDValueNo++);
1673 case bitc::METADATA_VALUE: {
1674 if (Record.size() != 2)
1675 return Error("Invalid record");
1677 Type *Ty = getTypeByID(Record[0]);
1678 if (Ty->isMetadataTy() || Ty->isVoidTy())
1679 return Error("Invalid record");
1681 MDValueList.AssignValue(
1682 ValueAsMetadata::get(ValueList.getValueFwdRef(Record[1], Ty)),
1686 case bitc::METADATA_DISTINCT_NODE:
1689 case bitc::METADATA_NODE: {
1690 SmallVector<Metadata *, 8> Elts;
1691 Elts.reserve(Record.size());
1692 for (unsigned ID : Record)
1693 Elts.push_back(ID ? MDValueList.getValueFwdRef(ID - 1) : nullptr);
1694 MDValueList.AssignValue(IsDistinct ? MDNode::getDistinct(Context, Elts)
1695 : MDNode::get(Context, Elts),
1699 case bitc::METADATA_LOCATION: {
1700 if (Record.size() != 5)
1701 return Error("Invalid record");
1703 unsigned Line = Record[1];
1704 unsigned Column = Record[2];
1705 MDNode *Scope = cast<MDNode>(MDValueList.getValueFwdRef(Record[3]));
1706 Metadata *InlinedAt =
1707 Record[4] ? MDValueList.getValueFwdRef(Record[4] - 1) : nullptr;
1708 MDValueList.AssignValue(
1709 GET_OR_DISTINCT(MDLocation, Record[0],
1710 (Context, Line, Column, Scope, InlinedAt)),
1714 case bitc::METADATA_GENERIC_DEBUG: {
1715 if (Record.size() < 4)
1716 return Error("Invalid record");
1718 unsigned Tag = Record[1];
1719 unsigned Version = Record[2];
1721 if (Tag >= 1u << 16 || Version != 0)
1722 return Error("Invalid record");
1724 auto *Header = getMDString(Record[3]);
1725 SmallVector<Metadata *, 8> DwarfOps;
1726 for (unsigned I = 4, E = Record.size(); I != E; ++I)
1727 DwarfOps.push_back(Record[I] ? MDValueList.getValueFwdRef(Record[I] - 1)
1729 MDValueList.AssignValue(GET_OR_DISTINCT(GenericDebugNode, Record[0],
1730 (Context, Tag, Header, DwarfOps)),
1734 case bitc::METADATA_SUBRANGE: {
1735 if (Record.size() != 3)
1736 return Error("Invalid record");
1738 MDValueList.AssignValue(
1739 GET_OR_DISTINCT(MDSubrange, Record[0],
1740 (Context, Record[1], unrotateSign(Record[2]))),
1744 case bitc::METADATA_ENUMERATOR: {
1745 if (Record.size() != 3)
1746 return Error("Invalid record");
1748 MDValueList.AssignValue(GET_OR_DISTINCT(MDEnumerator, Record[0],
1749 (Context, unrotateSign(Record[1]),
1750 getMDString(Record[2]))),
1754 case bitc::METADATA_BASIC_TYPE: {
1755 if (Record.size() != 6)
1756 return Error("Invalid record");
1758 MDValueList.AssignValue(
1759 GET_OR_DISTINCT(MDBasicType, Record[0],
1760 (Context, Record[1], getMDString(Record[2]),
1761 Record[3], Record[4], Record[5])),
1765 case bitc::METADATA_DERIVED_TYPE: {
1766 if (Record.size() != 12)
1767 return Error("Invalid record");
1769 MDValueList.AssignValue(
1770 GET_OR_DISTINCT(MDDerivedType, Record[0],
1771 (Context, Record[1], getMDString(Record[2]),
1772 getMDOrNull(Record[3]), Record[4],
1773 getMDOrNull(Record[5]), getMDOrNull(Record[6]),
1774 Record[7], Record[8], Record[9], Record[10],
1775 getMDOrNull(Record[11]))),
1779 case bitc::METADATA_COMPOSITE_TYPE: {
1780 if (Record.size() != 16)
1781 return Error("Invalid record");
1783 MDValueList.AssignValue(
1784 GET_OR_DISTINCT(MDCompositeType, Record[0],
1785 (Context, Record[1], getMDString(Record[2]),
1786 getMDOrNull(Record[3]), Record[4],
1787 getMDOrNull(Record[5]), getMDOrNull(Record[6]),
1788 Record[7], Record[8], Record[9], Record[10],
1789 getMDOrNull(Record[11]), Record[12],
1790 getMDOrNull(Record[13]), getMDOrNull(Record[14]),
1791 getMDString(Record[15]))),
1795 case bitc::METADATA_SUBROUTINE_TYPE: {
1796 if (Record.size() != 3)
1797 return Error("Invalid record");
1799 MDValueList.AssignValue(
1800 GET_OR_DISTINCT(MDSubroutineType, Record[0],
1801 (Context, Record[1], getMDOrNull(Record[2]))),
1805 case bitc::METADATA_FILE: {
1806 if (Record.size() != 3)
1807 return Error("Invalid record");
1809 MDValueList.AssignValue(
1810 GET_OR_DISTINCT(MDFile, Record[0], (Context, getMDString(Record[1]),
1811 getMDString(Record[2]))),
1815 case bitc::METADATA_COMPILE_UNIT: {
1816 if (Record.size() != 14)
1817 return Error("Invalid record");
1819 MDValueList.AssignValue(
1820 GET_OR_DISTINCT(MDCompileUnit, Record[0],
1821 (Context, Record[1], getMDOrNull(Record[2]),
1822 getMDString(Record[3]), Record[4],
1823 getMDString(Record[5]), Record[6],
1824 getMDString(Record[7]), Record[8],
1825 getMDOrNull(Record[9]), getMDOrNull(Record[10]),
1826 getMDOrNull(Record[11]), getMDOrNull(Record[12]),
1827 getMDOrNull(Record[13]))),
1831 case bitc::METADATA_SUBPROGRAM: {
1832 if (Record.size() != 19)
1833 return Error("Invalid record");
1835 MDValueList.AssignValue(
1837 MDSubprogram, Record[0],
1838 (Context, getMDOrNull(Record[1]), getMDString(Record[2]),
1839 getMDString(Record[3]), getMDOrNull(Record[4]), Record[5],
1840 getMDOrNull(Record[6]), Record[7], Record[8], Record[9],
1841 getMDOrNull(Record[10]), Record[11], Record[12], Record[13],
1842 Record[14], getMDOrNull(Record[15]), getMDOrNull(Record[16]),
1843 getMDOrNull(Record[17]), getMDOrNull(Record[18]))),
1847 case bitc::METADATA_LEXICAL_BLOCK: {
1848 if (Record.size() != 5)
1849 return Error("Invalid record");
1851 MDValueList.AssignValue(
1852 GET_OR_DISTINCT(MDLexicalBlock, Record[0],
1853 (Context, getMDOrNull(Record[1]),
1854 getMDOrNull(Record[2]), Record[3], Record[4])),
1858 case bitc::METADATA_LEXICAL_BLOCK_FILE: {
1859 if (Record.size() != 4)
1860 return Error("Invalid record");
1862 MDValueList.AssignValue(
1863 GET_OR_DISTINCT(MDLexicalBlockFile, Record[0],
1864 (Context, getMDOrNull(Record[1]),
1865 getMDOrNull(Record[2]), Record[3])),
1869 case bitc::METADATA_NAMESPACE: {
1870 if (Record.size() != 5)
1871 return Error("Invalid record");
1873 MDValueList.AssignValue(
1874 GET_OR_DISTINCT(MDNamespace, Record[0],
1875 (Context, getMDOrNull(Record[1]),
1876 getMDOrNull(Record[2]), getMDString(Record[3]),
1881 case bitc::METADATA_TEMPLATE_TYPE: {
1882 if (Record.size() != 3)
1883 return Error("Invalid record");
1885 MDValueList.AssignValue(GET_OR_DISTINCT(MDTemplateTypeParameter,
1887 (Context, getMDString(Record[1]),
1888 getMDOrNull(Record[2]))),
1892 case bitc::METADATA_TEMPLATE_VALUE: {
1893 if (Record.size() != 5)
1894 return Error("Invalid record");
1896 MDValueList.AssignValue(
1897 GET_OR_DISTINCT(MDTemplateValueParameter, Record[0],
1898 (Context, Record[1], getMDString(Record[2]),
1899 getMDOrNull(Record[3]), getMDOrNull(Record[4]))),
1903 case bitc::METADATA_GLOBAL_VAR: {
1904 if (Record.size() != 11)
1905 return Error("Invalid record");
1907 MDValueList.AssignValue(
1908 GET_OR_DISTINCT(MDGlobalVariable, Record[0],
1909 (Context, getMDOrNull(Record[1]),
1910 getMDString(Record[2]), getMDString(Record[3]),
1911 getMDOrNull(Record[4]), Record[5],
1912 getMDOrNull(Record[6]), Record[7], Record[8],
1913 getMDOrNull(Record[9]), getMDOrNull(Record[10]))),
1917 case bitc::METADATA_LOCAL_VAR: {
1918 // 10th field is for the obseleted 'inlinedAt:' field.
1919 if (Record.size() != 9 && Record.size() != 10)
1920 return Error("Invalid record");
1922 MDValueList.AssignValue(
1923 GET_OR_DISTINCT(MDLocalVariable, Record[0],
1924 (Context, Record[1], getMDOrNull(Record[2]),
1925 getMDString(Record[3]), getMDOrNull(Record[4]),
1926 Record[5], getMDOrNull(Record[6]), Record[7],
1931 case bitc::METADATA_EXPRESSION: {
1932 if (Record.size() < 1)
1933 return Error("Invalid record");
1935 MDValueList.AssignValue(
1936 GET_OR_DISTINCT(MDExpression, Record[0],
1937 (Context, makeArrayRef(Record).slice(1))),
1941 case bitc::METADATA_OBJC_PROPERTY: {
1942 if (Record.size() != 8)
1943 return Error("Invalid record");
1945 MDValueList.AssignValue(
1946 GET_OR_DISTINCT(MDObjCProperty, Record[0],
1947 (Context, getMDString(Record[1]),
1948 getMDOrNull(Record[2]), Record[3],
1949 getMDString(Record[4]), getMDString(Record[5]),
1950 Record[6], getMDOrNull(Record[7]))),
1954 case bitc::METADATA_IMPORTED_ENTITY: {
1955 if (Record.size() != 6)
1956 return Error("Invalid record");
1958 MDValueList.AssignValue(
1959 GET_OR_DISTINCT(MDImportedEntity, Record[0],
1960 (Context, Record[1], getMDOrNull(Record[2]),
1961 getMDOrNull(Record[3]), Record[4],
1962 getMDString(Record[5]))),
1966 case bitc::METADATA_STRING: {
1967 std::string String(Record.begin(), Record.end());
1968 llvm::UpgradeMDStringConstant(String);
1969 Metadata *MD = MDString::get(Context, String);
1970 MDValueList.AssignValue(MD, NextMDValueNo++);
1973 case bitc::METADATA_KIND: {
1974 if (Record.size() < 2)
1975 return Error("Invalid record");
1977 unsigned Kind = Record[0];
1978 SmallString<8> Name(Record.begin()+1, Record.end());
1980 unsigned NewKind = TheModule->getMDKindID(Name.str());
1981 if (!MDKindMap.insert(std::make_pair(Kind, NewKind)).second)
1982 return Error("Conflicting METADATA_KIND records");
1987 #undef GET_OR_DISTINCT
1990 /// decodeSignRotatedValue - Decode a signed value stored with the sign bit in
1991 /// the LSB for dense VBR encoding.
1992 uint64_t BitcodeReader::decodeSignRotatedValue(uint64_t V) {
1997 // There is no such thing as -0 with integers. "-0" really means MININT.
2001 /// ResolveGlobalAndAliasInits - Resolve all of the initializers for global
2002 /// values and aliases that we can.
2003 std::error_code BitcodeReader::ResolveGlobalAndAliasInits() {
2004 std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInitWorklist;
2005 std::vector<std::pair<GlobalAlias*, unsigned> > AliasInitWorklist;
2006 std::vector<std::pair<Function*, unsigned> > FunctionPrefixWorklist;
2007 std::vector<std::pair<Function*, unsigned> > FunctionPrologueWorklist;
2009 GlobalInitWorklist.swap(GlobalInits);
2010 AliasInitWorklist.swap(AliasInits);
2011 FunctionPrefixWorklist.swap(FunctionPrefixes);
2012 FunctionPrologueWorklist.swap(FunctionPrologues);
2014 while (!GlobalInitWorklist.empty()) {
2015 unsigned ValID = GlobalInitWorklist.back().second;
2016 if (ValID >= ValueList.size()) {
2017 // Not ready to resolve this yet, it requires something later in the file.
2018 GlobalInits.push_back(GlobalInitWorklist.back());
2020 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
2021 GlobalInitWorklist.back().first->setInitializer(C);
2023 return Error("Expected a constant");
2025 GlobalInitWorklist.pop_back();
2028 while (!AliasInitWorklist.empty()) {
2029 unsigned ValID = AliasInitWorklist.back().second;
2030 if (ValID >= ValueList.size()) {
2031 AliasInits.push_back(AliasInitWorklist.back());
2033 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
2034 AliasInitWorklist.back().first->setAliasee(C);
2036 return Error("Expected a constant");
2038 AliasInitWorklist.pop_back();
2041 while (!FunctionPrefixWorklist.empty()) {
2042 unsigned ValID = FunctionPrefixWorklist.back().second;
2043 if (ValID >= ValueList.size()) {
2044 FunctionPrefixes.push_back(FunctionPrefixWorklist.back());
2046 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
2047 FunctionPrefixWorklist.back().first->setPrefixData(C);
2049 return Error("Expected a constant");
2051 FunctionPrefixWorklist.pop_back();
2054 while (!FunctionPrologueWorklist.empty()) {
2055 unsigned ValID = FunctionPrologueWorklist.back().second;
2056 if (ValID >= ValueList.size()) {
2057 FunctionPrologues.push_back(FunctionPrologueWorklist.back());
2059 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
2060 FunctionPrologueWorklist.back().first->setPrologueData(C);
2062 return Error("Expected a constant");
2064 FunctionPrologueWorklist.pop_back();
2067 return std::error_code();
2070 static APInt ReadWideAPInt(ArrayRef<uint64_t> Vals, unsigned TypeBits) {
2071 SmallVector<uint64_t, 8> Words(Vals.size());
2072 std::transform(Vals.begin(), Vals.end(), Words.begin(),
2073 BitcodeReader::decodeSignRotatedValue);
2075 return APInt(TypeBits, Words);
2078 std::error_code BitcodeReader::ParseConstants() {
2079 if (Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID))
2080 return Error("Invalid record");
2082 SmallVector<uint64_t, 64> Record;
2084 // Read all the records for this value table.
2085 Type *CurTy = Type::getInt32Ty(Context);
2086 unsigned NextCstNo = ValueList.size();
2088 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
2090 switch (Entry.Kind) {
2091 case BitstreamEntry::SubBlock: // Handled for us already.
2092 case BitstreamEntry::Error:
2093 return Error("Malformed block");
2094 case BitstreamEntry::EndBlock:
2095 if (NextCstNo != ValueList.size())
2096 return Error("Invalid ronstant reference");
2098 // Once all the constants have been read, go through and resolve forward
2100 ValueList.ResolveConstantForwardRefs();
2101 return std::error_code();
2102 case BitstreamEntry::Record:
2103 // The interesting case.
2110 unsigned BitCode = Stream.readRecord(Entry.ID, Record);
2112 default: // Default behavior: unknown constant
2113 case bitc::CST_CODE_UNDEF: // UNDEF
2114 V = UndefValue::get(CurTy);
2116 case bitc::CST_CODE_SETTYPE: // SETTYPE: [typeid]
2118 return Error("Invalid record");
2119 if (Record[0] >= TypeList.size() || !TypeList[Record[0]])
2120 return Error("Invalid record");
2121 CurTy = TypeList[Record[0]];
2122 continue; // Skip the ValueList manipulation.
2123 case bitc::CST_CODE_NULL: // NULL
2124 V = Constant::getNullValue(CurTy);
2126 case bitc::CST_CODE_INTEGER: // INTEGER: [intval]
2127 if (!CurTy->isIntegerTy() || Record.empty())
2128 return Error("Invalid record");
2129 V = ConstantInt::get(CurTy, decodeSignRotatedValue(Record[0]));
2131 case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval]
2132 if (!CurTy->isIntegerTy() || Record.empty())
2133 return Error("Invalid record");
2135 APInt VInt = ReadWideAPInt(Record,
2136 cast<IntegerType>(CurTy)->getBitWidth());
2137 V = ConstantInt::get(Context, VInt);
2141 case bitc::CST_CODE_FLOAT: { // FLOAT: [fpval]
2143 return Error("Invalid record");
2144 if (CurTy->isHalfTy())
2145 V = ConstantFP::get(Context, APFloat(APFloat::IEEEhalf,
2146 APInt(16, (uint16_t)Record[0])));
2147 else if (CurTy->isFloatTy())
2148 V = ConstantFP::get(Context, APFloat(APFloat::IEEEsingle,
2149 APInt(32, (uint32_t)Record[0])));
2150 else if (CurTy->isDoubleTy())
2151 V = ConstantFP::get(Context, APFloat(APFloat::IEEEdouble,
2152 APInt(64, Record[0])));
2153 else if (CurTy->isX86_FP80Ty()) {
2154 // Bits are not stored the same way as a normal i80 APInt, compensate.
2155 uint64_t Rearrange[2];
2156 Rearrange[0] = (Record[1] & 0xffffLL) | (Record[0] << 16);
2157 Rearrange[1] = Record[0] >> 48;
2158 V = ConstantFP::get(Context, APFloat(APFloat::x87DoubleExtended,
2159 APInt(80, Rearrange)));
2160 } else if (CurTy->isFP128Ty())
2161 V = ConstantFP::get(Context, APFloat(APFloat::IEEEquad,
2162 APInt(128, Record)));
2163 else if (CurTy->isPPC_FP128Ty())
2164 V = ConstantFP::get(Context, APFloat(APFloat::PPCDoubleDouble,
2165 APInt(128, Record)));
2167 V = UndefValue::get(CurTy);
2171 case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number]
2173 return Error("Invalid record");
2175 unsigned Size = Record.size();
2176 SmallVector<Constant*, 16> Elts;
2178 if (StructType *STy = dyn_cast<StructType>(CurTy)) {
2179 for (unsigned i = 0; i != Size; ++i)
2180 Elts.push_back(ValueList.getConstantFwdRef(Record[i],
2181 STy->getElementType(i)));
2182 V = ConstantStruct::get(STy, Elts);
2183 } else if (ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) {
2184 Type *EltTy = ATy->getElementType();
2185 for (unsigned i = 0; i != Size; ++i)
2186 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
2187 V = ConstantArray::get(ATy, Elts);
2188 } else if (VectorType *VTy = dyn_cast<VectorType>(CurTy)) {
2189 Type *EltTy = VTy->getElementType();
2190 for (unsigned i = 0; i != Size; ++i)
2191 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
2192 V = ConstantVector::get(Elts);
2194 V = UndefValue::get(CurTy);
2198 case bitc::CST_CODE_STRING: // STRING: [values]
2199 case bitc::CST_CODE_CSTRING: { // CSTRING: [values]
2201 return Error("Invalid record");
2203 SmallString<16> Elts(Record.begin(), Record.end());
2204 V = ConstantDataArray::getString(Context, Elts,
2205 BitCode == bitc::CST_CODE_CSTRING);
2208 case bitc::CST_CODE_DATA: {// DATA: [n x value]
2210 return Error("Invalid record");
2212 Type *EltTy = cast<SequentialType>(CurTy)->getElementType();
2213 unsigned Size = Record.size();
2215 if (EltTy->isIntegerTy(8)) {
2216 SmallVector<uint8_t, 16> Elts(Record.begin(), Record.end());
2217 if (isa<VectorType>(CurTy))
2218 V = ConstantDataVector::get(Context, Elts);
2220 V = ConstantDataArray::get(Context, Elts);
2221 } else if (EltTy->isIntegerTy(16)) {
2222 SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end());
2223 if (isa<VectorType>(CurTy))
2224 V = ConstantDataVector::get(Context, Elts);
2226 V = ConstantDataArray::get(Context, Elts);
2227 } else if (EltTy->isIntegerTy(32)) {
2228 SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end());
2229 if (isa<VectorType>(CurTy))
2230 V = ConstantDataVector::get(Context, Elts);
2232 V = ConstantDataArray::get(Context, Elts);
2233 } else if (EltTy->isIntegerTy(64)) {
2234 SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end());
2235 if (isa<VectorType>(CurTy))
2236 V = ConstantDataVector::get(Context, Elts);
2238 V = ConstantDataArray::get(Context, Elts);
2239 } else if (EltTy->isFloatTy()) {
2240 SmallVector<float, 16> Elts(Size);
2241 std::transform(Record.begin(), Record.end(), Elts.begin(), BitsToFloat);
2242 if (isa<VectorType>(CurTy))
2243 V = ConstantDataVector::get(Context, Elts);
2245 V = ConstantDataArray::get(Context, Elts);
2246 } else if (EltTy->isDoubleTy()) {
2247 SmallVector<double, 16> Elts(Size);
2248 std::transform(Record.begin(), Record.end(), Elts.begin(),
2250 if (isa<VectorType>(CurTy))
2251 V = ConstantDataVector::get(Context, Elts);
2253 V = ConstantDataArray::get(Context, Elts);
2255 return Error("Invalid type for value");
2260 case bitc::CST_CODE_CE_BINOP: { // CE_BINOP: [opcode, opval, opval]
2261 if (Record.size() < 3)
2262 return Error("Invalid record");
2263 int Opc = GetDecodedBinaryOpcode(Record[0], CurTy);
2265 V = UndefValue::get(CurTy); // Unknown binop.
2267 Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy);
2268 Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy);
2270 if (Record.size() >= 4) {
2271 if (Opc == Instruction::Add ||
2272 Opc == Instruction::Sub ||
2273 Opc == Instruction::Mul ||
2274 Opc == Instruction::Shl) {
2275 if (Record[3] & (1 << bitc::OBO_NO_SIGNED_WRAP))
2276 Flags |= OverflowingBinaryOperator::NoSignedWrap;
2277 if (Record[3] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
2278 Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
2279 } else if (Opc == Instruction::SDiv ||
2280 Opc == Instruction::UDiv ||
2281 Opc == Instruction::LShr ||
2282 Opc == Instruction::AShr) {
2283 if (Record[3] & (1 << bitc::PEO_EXACT))
2284 Flags |= SDivOperator::IsExact;
2287 V = ConstantExpr::get(Opc, LHS, RHS, Flags);
2291 case bitc::CST_CODE_CE_CAST: { // CE_CAST: [opcode, opty, opval]
2292 if (Record.size() < 3)
2293 return Error("Invalid record");
2294 int Opc = GetDecodedCastOpcode(Record[0]);
2296 V = UndefValue::get(CurTy); // Unknown cast.
2298 Type *OpTy = getTypeByID(Record[1]);
2300 return Error("Invalid record");
2301 Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy);
2302 V = UpgradeBitCastExpr(Opc, Op, CurTy);
2303 if (!V) V = ConstantExpr::getCast(Opc, Op, CurTy);
2307 case bitc::CST_CODE_CE_INBOUNDS_GEP:
2308 case bitc::CST_CODE_CE_GEP: { // CE_GEP: [n x operands]
2310 Type *PointeeType = nullptr;
2311 if (Record.size() % 2)
2312 PointeeType = getTypeByID(Record[OpNum++]);
2313 SmallVector<Constant*, 16> Elts;
2314 while (OpNum != Record.size()) {
2315 Type *ElTy = getTypeByID(Record[OpNum++]);
2317 return Error("Invalid record");
2318 Elts.push_back(ValueList.getConstantFwdRef(Record[OpNum++], ElTy));
2323 cast<SequentialType>(Elts[0]->getType()->getScalarType())
2325 return Error("Explicit gep operator type does not match pointee type "
2326 "of pointer operand");
2328 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
2329 V = ConstantExpr::getGetElementPtr(PointeeType, Elts[0], Indices,
2331 bitc::CST_CODE_CE_INBOUNDS_GEP);
2334 case bitc::CST_CODE_CE_SELECT: { // CE_SELECT: [opval#, opval#, opval#]
2335 if (Record.size() < 3)
2336 return Error("Invalid record");
2338 Type *SelectorTy = Type::getInt1Ty(Context);
2340 // If CurTy is a vector of length n, then Record[0] must be a <n x i1>
2341 // vector. Otherwise, it must be a single bit.
2342 if (VectorType *VTy = dyn_cast<VectorType>(CurTy))
2343 SelectorTy = VectorType::get(Type::getInt1Ty(Context),
2344 VTy->getNumElements());
2346 V = ConstantExpr::getSelect(ValueList.getConstantFwdRef(Record[0],
2348 ValueList.getConstantFwdRef(Record[1],CurTy),
2349 ValueList.getConstantFwdRef(Record[2],CurTy));
2352 case bitc::CST_CODE_CE_EXTRACTELT
2353 : { // CE_EXTRACTELT: [opty, opval, opty, opval]
2354 if (Record.size() < 3)
2355 return Error("Invalid record");
2357 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
2359 return Error("Invalid record");
2360 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
2361 Constant *Op1 = nullptr;
2362 if (Record.size() == 4) {
2363 Type *IdxTy = getTypeByID(Record[2]);
2365 return Error("Invalid record");
2366 Op1 = ValueList.getConstantFwdRef(Record[3], IdxTy);
2367 } else // TODO: Remove with llvm 4.0
2368 Op1 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
2370 return Error("Invalid record");
2371 V = ConstantExpr::getExtractElement(Op0, Op1);
2374 case bitc::CST_CODE_CE_INSERTELT
2375 : { // CE_INSERTELT: [opval, opval, opty, opval]
2376 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
2377 if (Record.size() < 3 || !OpTy)
2378 return Error("Invalid record");
2379 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
2380 Constant *Op1 = ValueList.getConstantFwdRef(Record[1],
2381 OpTy->getElementType());
2382 Constant *Op2 = nullptr;
2383 if (Record.size() == 4) {
2384 Type *IdxTy = getTypeByID(Record[2]);
2386 return Error("Invalid record");
2387 Op2 = ValueList.getConstantFwdRef(Record[3], IdxTy);
2388 } else // TODO: Remove with llvm 4.0
2389 Op2 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
2391 return Error("Invalid record");
2392 V = ConstantExpr::getInsertElement(Op0, Op1, Op2);
2395 case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval]
2396 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
2397 if (Record.size() < 3 || !OpTy)
2398 return Error("Invalid record");
2399 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
2400 Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy);
2401 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
2402 OpTy->getNumElements());
2403 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy);
2404 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
2407 case bitc::CST_CODE_CE_SHUFVEC_EX: { // [opty, opval, opval, opval]
2408 VectorType *RTy = dyn_cast<VectorType>(CurTy);
2410 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
2411 if (Record.size() < 4 || !RTy || !OpTy)
2412 return Error("Invalid record");
2413 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
2414 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
2415 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
2416 RTy->getNumElements());
2417 Constant *Op2 = ValueList.getConstantFwdRef(Record[3], ShufTy);
2418 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
2421 case bitc::CST_CODE_CE_CMP: { // CE_CMP: [opty, opval, opval, pred]
2422 if (Record.size() < 4)
2423 return Error("Invalid record");
2424 Type *OpTy = getTypeByID(Record[0]);
2426 return Error("Invalid record");
2427 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
2428 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
2430 if (OpTy->isFPOrFPVectorTy())
2431 V = ConstantExpr::getFCmp(Record[3], Op0, Op1);
2433 V = ConstantExpr::getICmp(Record[3], Op0, Op1);
2436 // This maintains backward compatibility, pre-asm dialect keywords.
2437 // FIXME: Remove with the 4.0 release.
2438 case bitc::CST_CODE_INLINEASM_OLD: {
2439 if (Record.size() < 2)
2440 return Error("Invalid record");
2441 std::string AsmStr, ConstrStr;
2442 bool HasSideEffects = Record[0] & 1;
2443 bool IsAlignStack = Record[0] >> 1;
2444 unsigned AsmStrSize = Record[1];
2445 if (2+AsmStrSize >= Record.size())
2446 return Error("Invalid record");
2447 unsigned ConstStrSize = Record[2+AsmStrSize];
2448 if (3+AsmStrSize+ConstStrSize > Record.size())
2449 return Error("Invalid record");
2451 for (unsigned i = 0; i != AsmStrSize; ++i)
2452 AsmStr += (char)Record[2+i];
2453 for (unsigned i = 0; i != ConstStrSize; ++i)
2454 ConstrStr += (char)Record[3+AsmStrSize+i];
2455 PointerType *PTy = cast<PointerType>(CurTy);
2456 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
2457 AsmStr, ConstrStr, HasSideEffects, IsAlignStack);
2460 // This version adds support for the asm dialect keywords (e.g.,
2462 case bitc::CST_CODE_INLINEASM: {
2463 if (Record.size() < 2)
2464 return Error("Invalid record");
2465 std::string AsmStr, ConstrStr;
2466 bool HasSideEffects = Record[0] & 1;
2467 bool IsAlignStack = (Record[0] >> 1) & 1;
2468 unsigned AsmDialect = Record[0] >> 2;
2469 unsigned AsmStrSize = Record[1];
2470 if (2+AsmStrSize >= Record.size())
2471 return Error("Invalid record");
2472 unsigned ConstStrSize = Record[2+AsmStrSize];
2473 if (3+AsmStrSize+ConstStrSize > Record.size())
2474 return Error("Invalid record");
2476 for (unsigned i = 0; i != AsmStrSize; ++i)
2477 AsmStr += (char)Record[2+i];
2478 for (unsigned i = 0; i != ConstStrSize; ++i)
2479 ConstrStr += (char)Record[3+AsmStrSize+i];
2480 PointerType *PTy = cast<PointerType>(CurTy);
2481 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
2482 AsmStr, ConstrStr, HasSideEffects, IsAlignStack,
2483 InlineAsm::AsmDialect(AsmDialect));
2486 case bitc::CST_CODE_BLOCKADDRESS:{
2487 if (Record.size() < 3)
2488 return Error("Invalid record");
2489 Type *FnTy = getTypeByID(Record[0]);
2491 return Error("Invalid record");
2493 dyn_cast_or_null<Function>(ValueList.getConstantFwdRef(Record[1],FnTy));
2495 return Error("Invalid record");
2497 // Don't let Fn get dematerialized.
2498 BlockAddressesTaken.insert(Fn);
2500 // If the function is already parsed we can insert the block address right
2503 unsigned BBID = Record[2];
2505 // Invalid reference to entry block.
2506 return Error("Invalid ID");
2508 Function::iterator BBI = Fn->begin(), BBE = Fn->end();
2509 for (size_t I = 0, E = BBID; I != E; ++I) {
2511 return Error("Invalid ID");
2516 // Otherwise insert a placeholder and remember it so it can be inserted
2517 // when the function is parsed.
2518 auto &FwdBBs = BasicBlockFwdRefs[Fn];
2520 BasicBlockFwdRefQueue.push_back(Fn);
2521 if (FwdBBs.size() < BBID + 1)
2522 FwdBBs.resize(BBID + 1);
2524 FwdBBs[BBID] = BasicBlock::Create(Context);
2527 V = BlockAddress::get(Fn, BB);
2532 ValueList.AssignValue(V, NextCstNo);
2537 std::error_code BitcodeReader::ParseUseLists() {
2538 if (Stream.EnterSubBlock(bitc::USELIST_BLOCK_ID))
2539 return Error("Invalid record");
2541 // Read all the records.
2542 SmallVector<uint64_t, 64> Record;
2544 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
2546 switch (Entry.Kind) {
2547 case BitstreamEntry::SubBlock: // Handled for us already.
2548 case BitstreamEntry::Error:
2549 return Error("Malformed block");
2550 case BitstreamEntry::EndBlock:
2551 return std::error_code();
2552 case BitstreamEntry::Record:
2553 // The interesting case.
2557 // Read a use list record.
2560 switch (Stream.readRecord(Entry.ID, Record)) {
2561 default: // Default behavior: unknown type.
2563 case bitc::USELIST_CODE_BB:
2566 case bitc::USELIST_CODE_DEFAULT: {
2567 unsigned RecordLength = Record.size();
2568 if (RecordLength < 3)
2569 // Records should have at least an ID and two indexes.
2570 return Error("Invalid record");
2571 unsigned ID = Record.back();
2576 assert(ID < FunctionBBs.size() && "Basic block not found");
2577 V = FunctionBBs[ID];
2580 unsigned NumUses = 0;
2581 SmallDenseMap<const Use *, unsigned, 16> Order;
2582 for (const Use &U : V->uses()) {
2583 if (++NumUses > Record.size())
2585 Order[&U] = Record[NumUses - 1];
2587 if (Order.size() != Record.size() || NumUses > Record.size())
2588 // Mismatches can happen if the functions are being materialized lazily
2589 // (out-of-order), or a value has been upgraded.
2592 V->sortUseList([&](const Use &L, const Use &R) {
2593 return Order.lookup(&L) < Order.lookup(&R);
2601 /// When we see the block for metadata, remember where it is and then skip it.
2602 /// This lets us lazily deserialize the metadata.
2603 std::error_code BitcodeReader::rememberAndSkipMetadata() {
2604 // Save the current stream state.
2605 uint64_t CurBit = Stream.GetCurrentBitNo();
2606 DeferredMetadataInfo.push_back(CurBit);
2608 // Skip over the block for now.
2609 if (Stream.SkipBlock())
2610 return Error("Invalid record");
2611 return std::error_code();
2614 std::error_code BitcodeReader::materializeMetadata() {
2615 for (uint64_t BitPos : DeferredMetadataInfo) {
2616 // Move the bit stream to the saved position.
2617 Stream.JumpToBit(BitPos);
2618 if (std::error_code EC = ParseMetadata())
2621 DeferredMetadataInfo.clear();
2622 return std::error_code();
2625 void BitcodeReader::setStripDebugInfo() { StripDebugInfo = true; }
2627 /// RememberAndSkipFunctionBody - When we see the block for a function body,
2628 /// remember where it is and then skip it. This lets us lazily deserialize the
2630 std::error_code BitcodeReader::RememberAndSkipFunctionBody() {
2631 // Get the function we are talking about.
2632 if (FunctionsWithBodies.empty())
2633 return Error("Insufficient function protos");
2635 Function *Fn = FunctionsWithBodies.back();
2636 FunctionsWithBodies.pop_back();
2638 // Save the current stream state.
2639 uint64_t CurBit = Stream.GetCurrentBitNo();
2640 DeferredFunctionInfo[Fn] = CurBit;
2642 // Skip over the function block for now.
2643 if (Stream.SkipBlock())
2644 return Error("Invalid record");
2645 return std::error_code();
2648 std::error_code BitcodeReader::GlobalCleanup() {
2649 // Patch the initializers for globals and aliases up.
2650 ResolveGlobalAndAliasInits();
2651 if (!GlobalInits.empty() || !AliasInits.empty())
2652 return Error("Malformed global initializer set");
2654 // Look for intrinsic functions which need to be upgraded at some point
2655 for (Module::iterator FI = TheModule->begin(), FE = TheModule->end();
2658 if (UpgradeIntrinsicFunction(FI, NewFn))
2659 UpgradedIntrinsics.push_back(std::make_pair(FI, NewFn));
2662 // Look for global variables which need to be renamed.
2663 for (Module::global_iterator
2664 GI = TheModule->global_begin(), GE = TheModule->global_end();
2666 GlobalVariable *GV = GI++;
2667 UpgradeGlobalVariable(GV);
2670 // Force deallocation of memory for these vectors to favor the client that
2671 // want lazy deserialization.
2672 std::vector<std::pair<GlobalVariable*, unsigned> >().swap(GlobalInits);
2673 std::vector<std::pair<GlobalAlias*, unsigned> >().swap(AliasInits);
2674 return std::error_code();
2677 std::error_code BitcodeReader::ParseModule(bool Resume,
2678 bool ShouldLazyLoadMetadata) {
2680 Stream.JumpToBit(NextUnreadBit);
2681 else if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
2682 return Error("Invalid record");
2684 SmallVector<uint64_t, 64> Record;
2685 std::vector<std::string> SectionTable;
2686 std::vector<std::string> GCTable;
2688 // Read all the records for this module.
2690 BitstreamEntry Entry = Stream.advance();
2692 switch (Entry.Kind) {
2693 case BitstreamEntry::Error:
2694 return Error("Malformed block");
2695 case BitstreamEntry::EndBlock:
2696 return GlobalCleanup();
2698 case BitstreamEntry::SubBlock:
2700 default: // Skip unknown content.
2701 if (Stream.SkipBlock())
2702 return Error("Invalid record");
2704 case bitc::BLOCKINFO_BLOCK_ID:
2705 if (Stream.ReadBlockInfoBlock())
2706 return Error("Malformed block");
2708 case bitc::PARAMATTR_BLOCK_ID:
2709 if (std::error_code EC = ParseAttributeBlock())
2712 case bitc::PARAMATTR_GROUP_BLOCK_ID:
2713 if (std::error_code EC = ParseAttributeGroupBlock())
2716 case bitc::TYPE_BLOCK_ID_NEW:
2717 if (std::error_code EC = ParseTypeTable())
2720 case bitc::VALUE_SYMTAB_BLOCK_ID:
2721 if (std::error_code EC = ParseValueSymbolTable())
2723 SeenValueSymbolTable = true;
2725 case bitc::CONSTANTS_BLOCK_ID:
2726 if (std::error_code EC = ParseConstants())
2728 if (std::error_code EC = ResolveGlobalAndAliasInits())
2731 case bitc::METADATA_BLOCK_ID:
2732 if (ShouldLazyLoadMetadata && !IsMetadataMaterialized) {
2733 if (std::error_code EC = rememberAndSkipMetadata())
2737 assert(DeferredMetadataInfo.empty() && "Unexpected deferred metadata");
2738 if (std::error_code EC = ParseMetadata())
2741 case bitc::FUNCTION_BLOCK_ID:
2742 // If this is the first function body we've seen, reverse the
2743 // FunctionsWithBodies list.
2744 if (!SeenFirstFunctionBody) {
2745 std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
2746 if (std::error_code EC = GlobalCleanup())
2748 SeenFirstFunctionBody = true;
2751 if (std::error_code EC = RememberAndSkipFunctionBody())
2753 // For streaming bitcode, suspend parsing when we reach the function
2754 // bodies. Subsequent materialization calls will resume it when
2755 // necessary. For streaming, the function bodies must be at the end of
2756 // the bitcode. If the bitcode file is old, the symbol table will be
2757 // at the end instead and will not have been seen yet. In this case,
2758 // just finish the parse now.
2759 if (LazyStreamer && SeenValueSymbolTable) {
2760 NextUnreadBit = Stream.GetCurrentBitNo();
2761 return std::error_code();
2764 case bitc::USELIST_BLOCK_ID:
2765 if (std::error_code EC = ParseUseLists())
2771 case BitstreamEntry::Record:
2772 // The interesting case.
2778 switch (Stream.readRecord(Entry.ID, Record)) {
2779 default: break; // Default behavior, ignore unknown content.
2780 case bitc::MODULE_CODE_VERSION: { // VERSION: [version#]
2781 if (Record.size() < 1)
2782 return Error("Invalid record");
2783 // Only version #0 and #1 are supported so far.
2784 unsigned module_version = Record[0];
2785 switch (module_version) {
2787 return Error("Invalid value");
2789 UseRelativeIDs = false;
2792 UseRelativeIDs = true;
2797 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
2799 if (ConvertToString(Record, 0, S))
2800 return Error("Invalid record");
2801 TheModule->setTargetTriple(S);
2804 case bitc::MODULE_CODE_DATALAYOUT: { // DATALAYOUT: [strchr x N]
2806 if (ConvertToString(Record, 0, S))
2807 return Error("Invalid record");
2808 TheModule->setDataLayout(S);
2811 case bitc::MODULE_CODE_ASM: { // ASM: [strchr x N]
2813 if (ConvertToString(Record, 0, S))
2814 return Error("Invalid record");
2815 TheModule->setModuleInlineAsm(S);
2818 case bitc::MODULE_CODE_DEPLIB: { // DEPLIB: [strchr x N]
2819 // FIXME: Remove in 4.0.
2821 if (ConvertToString(Record, 0, S))
2822 return Error("Invalid record");
2826 case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N]
2828 if (ConvertToString(Record, 0, S))
2829 return Error("Invalid record");
2830 SectionTable.push_back(S);
2833 case bitc::MODULE_CODE_GCNAME: { // SECTIONNAME: [strchr x N]
2835 if (ConvertToString(Record, 0, S))
2836 return Error("Invalid record");
2837 GCTable.push_back(S);
2840 case bitc::MODULE_CODE_COMDAT: { // COMDAT: [selection_kind, name]
2841 if (Record.size() < 2)
2842 return Error("Invalid record");
2843 Comdat::SelectionKind SK = getDecodedComdatSelectionKind(Record[0]);
2844 unsigned ComdatNameSize = Record[1];
2845 std::string ComdatName;
2846 ComdatName.reserve(ComdatNameSize);
2847 for (unsigned i = 0; i != ComdatNameSize; ++i)
2848 ComdatName += (char)Record[2 + i];
2849 Comdat *C = TheModule->getOrInsertComdat(ComdatName);
2850 C->setSelectionKind(SK);
2851 ComdatList.push_back(C);
2854 // GLOBALVAR: [pointer type, isconst, initid,
2855 // linkage, alignment, section, visibility, threadlocal,
2856 // unnamed_addr, externally_initialized, dllstorageclass,
2858 case bitc::MODULE_CODE_GLOBALVAR: {
2859 if (Record.size() < 6)
2860 return Error("Invalid record");
2861 Type *Ty = getTypeByID(Record[0]);
2863 return Error("Invalid record");
2864 if (!Ty->isPointerTy())
2865 return Error("Invalid type for value");
2866 unsigned AddressSpace = cast<PointerType>(Ty)->getAddressSpace();
2867 Ty = cast<PointerType>(Ty)->getElementType();
2869 bool isConstant = Record[1];
2870 uint64_t RawLinkage = Record[3];
2871 GlobalValue::LinkageTypes Linkage = getDecodedLinkage(RawLinkage);
2873 if (std::error_code EC = parseAlignmentValue(Record[4], Alignment))
2875 std::string Section;
2877 if (Record[5]-1 >= SectionTable.size())
2878 return Error("Invalid ID");
2879 Section = SectionTable[Record[5]-1];
2881 GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;
2882 // Local linkage must have default visibility.
2883 if (Record.size() > 6 && !GlobalValue::isLocalLinkage(Linkage))
2884 // FIXME: Change to an error if non-default in 4.0.
2885 Visibility = GetDecodedVisibility(Record[6]);
2887 GlobalVariable::ThreadLocalMode TLM = GlobalVariable::NotThreadLocal;
2888 if (Record.size() > 7)
2889 TLM = GetDecodedThreadLocalMode(Record[7]);
2891 bool UnnamedAddr = false;
2892 if (Record.size() > 8)
2893 UnnamedAddr = Record[8];
2895 bool ExternallyInitialized = false;
2896 if (Record.size() > 9)
2897 ExternallyInitialized = Record[9];
2899 GlobalVariable *NewGV =
2900 new GlobalVariable(*TheModule, Ty, isConstant, Linkage, nullptr, "", nullptr,
2901 TLM, AddressSpace, ExternallyInitialized);
2902 NewGV->setAlignment(Alignment);
2903 if (!Section.empty())
2904 NewGV->setSection(Section);
2905 NewGV->setVisibility(Visibility);
2906 NewGV->setUnnamedAddr(UnnamedAddr);
2908 if (Record.size() > 10)
2909 NewGV->setDLLStorageClass(GetDecodedDLLStorageClass(Record[10]));
2911 UpgradeDLLImportExportLinkage(NewGV, RawLinkage);
2913 ValueList.push_back(NewGV);
2915 // Remember which value to use for the global initializer.
2916 if (unsigned InitID = Record[2])
2917 GlobalInits.push_back(std::make_pair(NewGV, InitID-1));
2919 if (Record.size() > 11) {
2920 if (unsigned ComdatID = Record[11]) {
2921 assert(ComdatID <= ComdatList.size());
2922 NewGV->setComdat(ComdatList[ComdatID - 1]);
2924 } else if (hasImplicitComdat(RawLinkage)) {
2925 NewGV->setComdat(reinterpret_cast<Comdat *>(1));
2929 // FUNCTION: [type, callingconv, isproto, linkage, paramattr,
2930 // alignment, section, visibility, gc, unnamed_addr,
2931 // prologuedata, dllstorageclass, comdat, prefixdata]
2932 case bitc::MODULE_CODE_FUNCTION: {
2933 if (Record.size() < 8)
2934 return Error("Invalid record");
2935 Type *Ty = getTypeByID(Record[0]);
2937 return Error("Invalid record");
2938 if (!Ty->isPointerTy())
2939 return Error("Invalid type for value");
2941 dyn_cast<FunctionType>(cast<PointerType>(Ty)->getElementType());
2943 return Error("Invalid type for value");
2945 Function *Func = Function::Create(FTy, GlobalValue::ExternalLinkage,
2948 Func->setCallingConv(static_cast<CallingConv::ID>(Record[1]));
2949 bool isProto = Record[2];
2950 uint64_t RawLinkage = Record[3];
2951 Func->setLinkage(getDecodedLinkage(RawLinkage));
2952 Func->setAttributes(getAttributes(Record[4]));
2955 if (std::error_code EC = parseAlignmentValue(Record[5], Alignment))
2957 Func->setAlignment(Alignment);
2959 if (Record[6]-1 >= SectionTable.size())
2960 return Error("Invalid ID");
2961 Func->setSection(SectionTable[Record[6]-1]);
2963 // Local linkage must have default visibility.
2964 if (!Func->hasLocalLinkage())
2965 // FIXME: Change to an error if non-default in 4.0.
2966 Func->setVisibility(GetDecodedVisibility(Record[7]));
2967 if (Record.size() > 8 && Record[8]) {
2968 if (Record[8]-1 > GCTable.size())
2969 return Error("Invalid ID");
2970 Func->setGC(GCTable[Record[8]-1].c_str());
2972 bool UnnamedAddr = false;
2973 if (Record.size() > 9)
2974 UnnamedAddr = Record[9];
2975 Func->setUnnamedAddr(UnnamedAddr);
2976 if (Record.size() > 10 && Record[10] != 0)
2977 FunctionPrologues.push_back(std::make_pair(Func, Record[10]-1));
2979 if (Record.size() > 11)
2980 Func->setDLLStorageClass(GetDecodedDLLStorageClass(Record[11]));
2982 UpgradeDLLImportExportLinkage(Func, RawLinkage);
2984 if (Record.size() > 12) {
2985 if (unsigned ComdatID = Record[12]) {
2986 assert(ComdatID <= ComdatList.size());
2987 Func->setComdat(ComdatList[ComdatID - 1]);
2989 } else if (hasImplicitComdat(RawLinkage)) {
2990 Func->setComdat(reinterpret_cast<Comdat *>(1));
2993 if (Record.size() > 13 && Record[13] != 0)
2994 FunctionPrefixes.push_back(std::make_pair(Func, Record[13]-1));
2996 ValueList.push_back(Func);
2998 // If this is a function with a body, remember the prototype we are
2999 // creating now, so that we can match up the body with them later.
3001 Func->setIsMaterializable(true);
3002 FunctionsWithBodies.push_back(Func);
3004 DeferredFunctionInfo[Func] = 0;
3008 // ALIAS: [alias type, aliasee val#, linkage]
3009 // ALIAS: [alias type, aliasee val#, linkage, visibility, dllstorageclass]
3010 case bitc::MODULE_CODE_ALIAS: {
3011 if (Record.size() < 3)
3012 return Error("Invalid record");
3013 Type *Ty = getTypeByID(Record[0]);
3015 return Error("Invalid record");
3016 auto *PTy = dyn_cast<PointerType>(Ty);
3018 return Error("Invalid type for value");
3021 GlobalAlias::create(PTy->getElementType(), PTy->getAddressSpace(),
3022 getDecodedLinkage(Record[2]), "", TheModule);
3023 // Old bitcode files didn't have visibility field.
3024 // Local linkage must have default visibility.
3025 if (Record.size() > 3 && !NewGA->hasLocalLinkage())
3026 // FIXME: Change to an error if non-default in 4.0.
3027 NewGA->setVisibility(GetDecodedVisibility(Record[3]));
3028 if (Record.size() > 4)
3029 NewGA->setDLLStorageClass(GetDecodedDLLStorageClass(Record[4]));
3031 UpgradeDLLImportExportLinkage(NewGA, Record[2]);
3032 if (Record.size() > 5)
3033 NewGA->setThreadLocalMode(GetDecodedThreadLocalMode(Record[5]));
3034 if (Record.size() > 6)
3035 NewGA->setUnnamedAddr(Record[6]);
3036 ValueList.push_back(NewGA);
3037 AliasInits.push_back(std::make_pair(NewGA, Record[1]));
3040 /// MODULE_CODE_PURGEVALS: [numvals]
3041 case bitc::MODULE_CODE_PURGEVALS:
3042 // Trim down the value list to the specified size.
3043 if (Record.size() < 1 || Record[0] > ValueList.size())
3044 return Error("Invalid record");
3045 ValueList.shrinkTo(Record[0]);
3052 std::error_code BitcodeReader::ParseBitcodeInto(Module *M,
3053 bool ShouldLazyLoadMetadata) {
3054 TheModule = nullptr;
3056 if (std::error_code EC = InitStream())
3059 // Sniff for the signature.
3060 if (Stream.Read(8) != 'B' ||
3061 Stream.Read(8) != 'C' ||
3062 Stream.Read(4) != 0x0 ||
3063 Stream.Read(4) != 0xC ||
3064 Stream.Read(4) != 0xE ||
3065 Stream.Read(4) != 0xD)
3066 return Error("Invalid bitcode signature");
3068 // We expect a number of well-defined blocks, though we don't necessarily
3069 // need to understand them all.
3071 if (Stream.AtEndOfStream()) {
3073 return std::error_code();
3074 // We didn't really read a proper Module.
3075 return Error("Malformed IR file");
3078 BitstreamEntry Entry =
3079 Stream.advance(BitstreamCursor::AF_DontAutoprocessAbbrevs);
3081 switch (Entry.Kind) {
3082 case BitstreamEntry::Error:
3083 return Error("Malformed block");
3084 case BitstreamEntry::EndBlock:
3085 return std::error_code();
3087 case BitstreamEntry::SubBlock:
3089 case bitc::BLOCKINFO_BLOCK_ID:
3090 if (Stream.ReadBlockInfoBlock())
3091 return Error("Malformed block");
3093 case bitc::MODULE_BLOCK_ID:
3094 // Reject multiple MODULE_BLOCK's in a single bitstream.
3096 return Error("Invalid multiple blocks");
3098 if (std::error_code EC = ParseModule(false, ShouldLazyLoadMetadata))
3101 return std::error_code();
3104 if (Stream.SkipBlock())
3105 return Error("Invalid record");
3109 case BitstreamEntry::Record:
3110 // There should be no records in the top-level of blocks.
3112 // The ranlib in Xcode 4 will align archive members by appending newlines
3113 // to the end of them. If this file size is a multiple of 4 but not 8, we
3114 // have to read and ignore these final 4 bytes :-(
3115 if (Stream.getAbbrevIDWidth() == 2 && Entry.ID == 2 &&
3116 Stream.Read(6) == 2 && Stream.Read(24) == 0xa0a0a &&
3117 Stream.AtEndOfStream())
3118 return std::error_code();
3120 return Error("Invalid record");
3125 ErrorOr<std::string> BitcodeReader::parseModuleTriple() {
3126 if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
3127 return Error("Invalid record");
3129 SmallVector<uint64_t, 64> Record;
3132 // Read all the records for this module.
3134 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
3136 switch (Entry.Kind) {
3137 case BitstreamEntry::SubBlock: // Handled for us already.
3138 case BitstreamEntry::Error:
3139 return Error("Malformed block");
3140 case BitstreamEntry::EndBlock:
3142 case BitstreamEntry::Record:
3143 // The interesting case.
3148 switch (Stream.readRecord(Entry.ID, Record)) {
3149 default: break; // Default behavior, ignore unknown content.
3150 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
3152 if (ConvertToString(Record, 0, S))
3153 return Error("Invalid record");
3160 llvm_unreachable("Exit infinite loop");
3163 ErrorOr<std::string> BitcodeReader::parseTriple() {
3164 if (std::error_code EC = InitStream())
3167 // Sniff for the signature.
3168 if (Stream.Read(8) != 'B' ||
3169 Stream.Read(8) != 'C' ||
3170 Stream.Read(4) != 0x0 ||
3171 Stream.Read(4) != 0xC ||
3172 Stream.Read(4) != 0xE ||
3173 Stream.Read(4) != 0xD)
3174 return Error("Invalid bitcode signature");
3176 // We expect a number of well-defined blocks, though we don't necessarily
3177 // need to understand them all.
3179 BitstreamEntry Entry = Stream.advance();
3181 switch (Entry.Kind) {
3182 case BitstreamEntry::Error:
3183 return Error("Malformed block");
3184 case BitstreamEntry::EndBlock:
3185 return std::error_code();
3187 case BitstreamEntry::SubBlock:
3188 if (Entry.ID == bitc::MODULE_BLOCK_ID)
3189 return parseModuleTriple();
3191 // Ignore other sub-blocks.
3192 if (Stream.SkipBlock())
3193 return Error("Malformed block");
3196 case BitstreamEntry::Record:
3197 Stream.skipRecord(Entry.ID);
3203 /// ParseMetadataAttachment - Parse metadata attachments.
3204 std::error_code BitcodeReader::ParseMetadataAttachment() {
3205 if (Stream.EnterSubBlock(bitc::METADATA_ATTACHMENT_ID))
3206 return Error("Invalid record");
3208 SmallVector<uint64_t, 64> Record;
3210 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
3212 switch (Entry.Kind) {
3213 case BitstreamEntry::SubBlock: // Handled for us already.
3214 case BitstreamEntry::Error:
3215 return Error("Malformed block");
3216 case BitstreamEntry::EndBlock:
3217 return std::error_code();
3218 case BitstreamEntry::Record:
3219 // The interesting case.
3223 // Read a metadata attachment record.
3225 switch (Stream.readRecord(Entry.ID, Record)) {
3226 default: // Default behavior: ignore.
3228 case bitc::METADATA_ATTACHMENT: {
3229 unsigned RecordLength = Record.size();
3230 if (Record.empty() || (RecordLength - 1) % 2 == 1)
3231 return Error("Invalid record");
3232 Instruction *Inst = InstructionList[Record[0]];
3233 for (unsigned i = 1; i != RecordLength; i = i+2) {
3234 unsigned Kind = Record[i];
3235 DenseMap<unsigned, unsigned>::iterator I =
3236 MDKindMap.find(Kind);
3237 if (I == MDKindMap.end())
3238 return Error("Invalid ID");
3239 Metadata *Node = MDValueList.getValueFwdRef(Record[i + 1]);
3240 if (isa<LocalAsMetadata>(Node))
3241 // Drop the attachment. This used to be legal, but there's no
3244 Inst->setMetadata(I->second, cast<MDNode>(Node));
3245 if (I->second == LLVMContext::MD_tbaa)
3246 InstsWithTBAATag.push_back(Inst);
3254 /// ParseFunctionBody - Lazily parse the specified function body block.
3255 std::error_code BitcodeReader::ParseFunctionBody(Function *F) {
3256 if (Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID))
3257 return Error("Invalid record");
3259 InstructionList.clear();
3260 unsigned ModuleValueListSize = ValueList.size();
3261 unsigned ModuleMDValueListSize = MDValueList.size();
3263 // Add all the function arguments to the value table.
3264 for(Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
3265 ValueList.push_back(I);
3267 unsigned NextValueNo = ValueList.size();
3268 BasicBlock *CurBB = nullptr;
3269 unsigned CurBBNo = 0;
3272 auto getLastInstruction = [&]() -> Instruction * {
3273 if (CurBB && !CurBB->empty())
3274 return &CurBB->back();
3275 else if (CurBBNo && FunctionBBs[CurBBNo - 1] &&
3276 !FunctionBBs[CurBBNo - 1]->empty())
3277 return &FunctionBBs[CurBBNo - 1]->back();
3281 // Read all the records.
3282 SmallVector<uint64_t, 64> Record;
3284 BitstreamEntry Entry = Stream.advance();
3286 switch (Entry.Kind) {
3287 case BitstreamEntry::Error:
3288 return Error("Malformed block");
3289 case BitstreamEntry::EndBlock:
3290 goto OutOfRecordLoop;
3292 case BitstreamEntry::SubBlock:
3294 default: // Skip unknown content.
3295 if (Stream.SkipBlock())
3296 return Error("Invalid record");
3298 case bitc::CONSTANTS_BLOCK_ID:
3299 if (std::error_code EC = ParseConstants())
3301 NextValueNo = ValueList.size();
3303 case bitc::VALUE_SYMTAB_BLOCK_ID:
3304 if (std::error_code EC = ParseValueSymbolTable())
3307 case bitc::METADATA_ATTACHMENT_ID:
3308 if (std::error_code EC = ParseMetadataAttachment())
3311 case bitc::METADATA_BLOCK_ID:
3312 if (std::error_code EC = ParseMetadata())
3315 case bitc::USELIST_BLOCK_ID:
3316 if (std::error_code EC = ParseUseLists())
3322 case BitstreamEntry::Record:
3323 // The interesting case.
3329 Instruction *I = nullptr;
3330 unsigned BitCode = Stream.readRecord(Entry.ID, Record);
3332 default: // Default behavior: reject
3333 return Error("Invalid value");
3334 case bitc::FUNC_CODE_DECLAREBLOCKS: { // DECLAREBLOCKS: [nblocks]
3335 if (Record.size() < 1 || Record[0] == 0)
3336 return Error("Invalid record");
3337 // Create all the basic blocks for the function.
3338 FunctionBBs.resize(Record[0]);
3340 // See if anything took the address of blocks in this function.
3341 auto BBFRI = BasicBlockFwdRefs.find(F);
3342 if (BBFRI == BasicBlockFwdRefs.end()) {
3343 for (unsigned i = 0, e = FunctionBBs.size(); i != e; ++i)
3344 FunctionBBs[i] = BasicBlock::Create(Context, "", F);
3346 auto &BBRefs = BBFRI->second;
3347 // Check for invalid basic block references.
3348 if (BBRefs.size() > FunctionBBs.size())
3349 return Error("Invalid ID");
3350 assert(!BBRefs.empty() && "Unexpected empty array");
3351 assert(!BBRefs.front() && "Invalid reference to entry block");
3352 for (unsigned I = 0, E = FunctionBBs.size(), RE = BBRefs.size(); I != E;
3354 if (I < RE && BBRefs[I]) {
3355 BBRefs[I]->insertInto(F);
3356 FunctionBBs[I] = BBRefs[I];
3358 FunctionBBs[I] = BasicBlock::Create(Context, "", F);
3361 // Erase from the table.
3362 BasicBlockFwdRefs.erase(BBFRI);
3365 CurBB = FunctionBBs[0];
3369 case bitc::FUNC_CODE_DEBUG_LOC_AGAIN: // DEBUG_LOC_AGAIN
3370 // This record indicates that the last instruction is at the same
3371 // location as the previous instruction with a location.
3372 I = getLastInstruction();
3375 return Error("Invalid record");
3376 I->setDebugLoc(LastLoc);
3380 case bitc::FUNC_CODE_DEBUG_LOC: { // DEBUG_LOC: [line, col, scope, ia]
3381 I = getLastInstruction();
3382 if (!I || Record.size() < 4)
3383 return Error("Invalid record");
3385 unsigned Line = Record[0], Col = Record[1];
3386 unsigned ScopeID = Record[2], IAID = Record[3];
3388 MDNode *Scope = nullptr, *IA = nullptr;
3389 if (ScopeID) Scope = cast<MDNode>(MDValueList.getValueFwdRef(ScopeID-1));
3390 if (IAID) IA = cast<MDNode>(MDValueList.getValueFwdRef(IAID-1));
3391 LastLoc = DebugLoc::get(Line, Col, Scope, IA);
3392 I->setDebugLoc(LastLoc);
3397 case bitc::FUNC_CODE_INST_BINOP: { // BINOP: [opval, ty, opval, opcode]
3400 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
3401 popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) ||
3402 OpNum+1 > Record.size())
3403 return Error("Invalid record");
3405 int Opc = GetDecodedBinaryOpcode(Record[OpNum++], LHS->getType());
3407 return Error("Invalid record");
3408 I = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3409 InstructionList.push_back(I);
3410 if (OpNum < Record.size()) {
3411 if (Opc == Instruction::Add ||
3412 Opc == Instruction::Sub ||
3413 Opc == Instruction::Mul ||
3414 Opc == Instruction::Shl) {
3415 if (Record[OpNum] & (1 << bitc::OBO_NO_SIGNED_WRAP))
3416 cast<BinaryOperator>(I)->setHasNoSignedWrap(true);
3417 if (Record[OpNum] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
3418 cast<BinaryOperator>(I)->setHasNoUnsignedWrap(true);
3419 } else if (Opc == Instruction::SDiv ||
3420 Opc == Instruction::UDiv ||
3421 Opc == Instruction::LShr ||
3422 Opc == Instruction::AShr) {
3423 if (Record[OpNum] & (1 << bitc::PEO_EXACT))
3424 cast<BinaryOperator>(I)->setIsExact(true);
3425 } else if (isa<FPMathOperator>(I)) {
3427 if (0 != (Record[OpNum] & FastMathFlags::UnsafeAlgebra))
3428 FMF.setUnsafeAlgebra();
3429 if (0 != (Record[OpNum] & FastMathFlags::NoNaNs))
3431 if (0 != (Record[OpNum] & FastMathFlags::NoInfs))
3433 if (0 != (Record[OpNum] & FastMathFlags::NoSignedZeros))
3434 FMF.setNoSignedZeros();
3435 if (0 != (Record[OpNum] & FastMathFlags::AllowReciprocal))
3436 FMF.setAllowReciprocal();
3438 I->setFastMathFlags(FMF);
3444 case bitc::FUNC_CODE_INST_CAST: { // CAST: [opval, opty, destty, castopc]
3447 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
3448 OpNum+2 != Record.size())
3449 return Error("Invalid record");
3451 Type *ResTy = getTypeByID(Record[OpNum]);
3452 int Opc = GetDecodedCastOpcode(Record[OpNum+1]);
3453 if (Opc == -1 || !ResTy)
3454 return Error("Invalid record");
3455 Instruction *Temp = nullptr;
3456 if ((I = UpgradeBitCastInst(Opc, Op, ResTy, Temp))) {
3458 InstructionList.push_back(Temp);
3459 CurBB->getInstList().push_back(Temp);
3462 I = CastInst::Create((Instruction::CastOps)Opc, Op, ResTy);
3464 InstructionList.push_back(I);
3467 case bitc::FUNC_CODE_INST_INBOUNDS_GEP_OLD:
3468 case bitc::FUNC_CODE_INST_GEP_OLD:
3469 case bitc::FUNC_CODE_INST_GEP: { // GEP: type, [n x operands]
3475 if (BitCode == bitc::FUNC_CODE_INST_GEP) {
3476 InBounds = Record[OpNum++];
3477 Ty = getTypeByID(Record[OpNum++]);
3479 InBounds = BitCode == bitc::FUNC_CODE_INST_INBOUNDS_GEP_OLD;
3484 if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr))
3485 return Error("Invalid record");
3489 cast<SequentialType>(BasePtr->getType()->getScalarType())
3492 "Explicit gep type does not match pointee type of pointer operand");
3494 SmallVector<Value*, 16> GEPIdx;
3495 while (OpNum != Record.size()) {
3497 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
3498 return Error("Invalid record");
3499 GEPIdx.push_back(Op);
3502 I = GetElementPtrInst::Create(Ty, BasePtr, GEPIdx);
3504 InstructionList.push_back(I);
3506 cast<GetElementPtrInst>(I)->setIsInBounds(true);
3510 case bitc::FUNC_CODE_INST_EXTRACTVAL: {
3511 // EXTRACTVAL: [opty, opval, n x indices]
3514 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
3515 return Error("Invalid record");
3517 SmallVector<unsigned, 4> EXTRACTVALIdx;
3518 Type *CurTy = Agg->getType();
3519 for (unsigned RecSize = Record.size();
3520 OpNum != RecSize; ++OpNum) {
3521 bool IsArray = CurTy->isArrayTy();
3522 bool IsStruct = CurTy->isStructTy();
3523 uint64_t Index = Record[OpNum];
3525 if (!IsStruct && !IsArray)
3526 return Error("EXTRACTVAL: Invalid type");
3527 if ((unsigned)Index != Index)
3528 return Error("Invalid value");
3529 if (IsStruct && Index >= CurTy->subtypes().size())
3530 return Error("EXTRACTVAL: Invalid struct index");
3531 if (IsArray && Index >= CurTy->getArrayNumElements())
3532 return Error("EXTRACTVAL: Invalid array index");
3533 EXTRACTVALIdx.push_back((unsigned)Index);
3536 CurTy = CurTy->subtypes()[Index];
3538 CurTy = CurTy->subtypes()[0];
3541 I = ExtractValueInst::Create(Agg, EXTRACTVALIdx);
3542 InstructionList.push_back(I);
3546 case bitc::FUNC_CODE_INST_INSERTVAL: {
3547 // INSERTVAL: [opty, opval, opty, opval, n x indices]
3550 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
3551 return Error("Invalid record");
3553 if (getValueTypePair(Record, OpNum, NextValueNo, Val))
3554 return Error("Invalid record");
3556 SmallVector<unsigned, 4> INSERTVALIdx;
3557 Type *CurTy = Agg->getType();
3558 for (unsigned RecSize = Record.size();
3559 OpNum != RecSize; ++OpNum) {
3560 bool IsArray = CurTy->isArrayTy();
3561 bool IsStruct = CurTy->isStructTy();
3562 uint64_t Index = Record[OpNum];
3564 if (!IsStruct && !IsArray)
3565 return Error("INSERTVAL: Invalid type");
3566 if (!CurTy->isStructTy() && !CurTy->isArrayTy())
3567 return Error("Invalid type");
3568 if ((unsigned)Index != Index)
3569 return Error("Invalid value");
3570 if (IsStruct && Index >= CurTy->subtypes().size())
3571 return Error("INSERTVAL: Invalid struct index");
3572 if (IsArray && Index >= CurTy->getArrayNumElements())
3573 return Error("INSERTVAL: Invalid array index");
3575 INSERTVALIdx.push_back((unsigned)Index);
3577 CurTy = CurTy->subtypes()[Index];
3579 CurTy = CurTy->subtypes()[0];
3582 I = InsertValueInst::Create(Agg, Val, INSERTVALIdx);
3583 InstructionList.push_back(I);
3587 case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval]
3588 // obsolete form of select
3589 // handles select i1 ... in old bitcode
3591 Value *TrueVal, *FalseVal, *Cond;
3592 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
3593 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
3594 popValue(Record, OpNum, NextValueNo, Type::getInt1Ty(Context), Cond))
3595 return Error("Invalid record");
3597 I = SelectInst::Create(Cond, TrueVal, FalseVal);
3598 InstructionList.push_back(I);
3602 case bitc::FUNC_CODE_INST_VSELECT: {// VSELECT: [ty,opval,opval,predty,pred]
3603 // new form of select
3604 // handles select i1 or select [N x i1]
3606 Value *TrueVal, *FalseVal, *Cond;
3607 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
3608 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
3609 getValueTypePair(Record, OpNum, NextValueNo, Cond))
3610 return Error("Invalid record");
3612 // select condition can be either i1 or [N x i1]
3613 if (VectorType* vector_type =
3614 dyn_cast<VectorType>(Cond->getType())) {
3616 if (vector_type->getElementType() != Type::getInt1Ty(Context))
3617 return Error("Invalid type for value");
3620 if (Cond->getType() != Type::getInt1Ty(Context))
3621 return Error("Invalid type for value");
3624 I = SelectInst::Create(Cond, TrueVal, FalseVal);
3625 InstructionList.push_back(I);
3629 case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval]
3632 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
3633 getValueTypePair(Record, OpNum, NextValueNo, Idx))
3634 return Error("Invalid record");
3635 I = ExtractElementInst::Create(Vec, Idx);
3636 InstructionList.push_back(I);
3640 case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval]
3642 Value *Vec, *Elt, *Idx;
3643 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
3644 popValue(Record, OpNum, NextValueNo,
3645 cast<VectorType>(Vec->getType())->getElementType(), Elt) ||
3646 getValueTypePair(Record, OpNum, NextValueNo, Idx))
3647 return Error("Invalid record");
3648 I = InsertElementInst::Create(Vec, Elt, Idx);
3649 InstructionList.push_back(I);
3653 case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval]
3655 Value *Vec1, *Vec2, *Mask;
3656 if (getValueTypePair(Record, OpNum, NextValueNo, Vec1) ||
3657 popValue(Record, OpNum, NextValueNo, Vec1->getType(), Vec2))
3658 return Error("Invalid record");
3660 if (getValueTypePair(Record, OpNum, NextValueNo, Mask))
3661 return Error("Invalid record");
3662 I = new ShuffleVectorInst(Vec1, Vec2, Mask);
3663 InstructionList.push_back(I);
3667 case bitc::FUNC_CODE_INST_CMP: // CMP: [opty, opval, opval, pred]
3668 // Old form of ICmp/FCmp returning bool
3669 // Existed to differentiate between icmp/fcmp and vicmp/vfcmp which were
3670 // both legal on vectors but had different behaviour.
3671 case bitc::FUNC_CODE_INST_CMP2: { // CMP2: [opty, opval, opval, pred]
3672 // FCmp/ICmp returning bool or vector of bool
3676 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
3677 popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) ||
3678 OpNum+1 != Record.size())
3679 return Error("Invalid record");
3681 if (LHS->getType()->isFPOrFPVectorTy())
3682 I = new FCmpInst((FCmpInst::Predicate)Record[OpNum], LHS, RHS);
3684 I = new ICmpInst((ICmpInst::Predicate)Record[OpNum], LHS, RHS);
3685 InstructionList.push_back(I);
3689 case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>]
3691 unsigned Size = Record.size();
3693 I = ReturnInst::Create(Context);
3694 InstructionList.push_back(I);
3699 Value *Op = nullptr;
3700 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
3701 return Error("Invalid record");
3702 if (OpNum != Record.size())
3703 return Error("Invalid record");
3705 I = ReturnInst::Create(Context, Op);
3706 InstructionList.push_back(I);
3709 case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#]
3710 if (Record.size() != 1 && Record.size() != 3)
3711 return Error("Invalid record");
3712 BasicBlock *TrueDest = getBasicBlock(Record[0]);
3714 return Error("Invalid record");
3716 if (Record.size() == 1) {
3717 I = BranchInst::Create(TrueDest);
3718 InstructionList.push_back(I);
3721 BasicBlock *FalseDest = getBasicBlock(Record[1]);
3722 Value *Cond = getValue(Record, 2, NextValueNo,
3723 Type::getInt1Ty(Context));
3724 if (!FalseDest || !Cond)
3725 return Error("Invalid record");
3726 I = BranchInst::Create(TrueDest, FalseDest, Cond);
3727 InstructionList.push_back(I);
3731 case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, op0, op1, ...]
3733 if ((Record[0] >> 16) == SWITCH_INST_MAGIC) {
3734 // "New" SwitchInst format with case ranges. The changes to write this
3735 // format were reverted but we still recognize bitcode that uses it.
3736 // Hopefully someday we will have support for case ranges and can use
3737 // this format again.
3739 Type *OpTy = getTypeByID(Record[1]);
3740 unsigned ValueBitWidth = cast<IntegerType>(OpTy)->getBitWidth();
3742 Value *Cond = getValue(Record, 2, NextValueNo, OpTy);
3743 BasicBlock *Default = getBasicBlock(Record[3]);
3744 if (!OpTy || !Cond || !Default)
3745 return Error("Invalid record");
3747 unsigned NumCases = Record[4];
3749 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
3750 InstructionList.push_back(SI);
3752 unsigned CurIdx = 5;
3753 for (unsigned i = 0; i != NumCases; ++i) {
3754 SmallVector<ConstantInt*, 1> CaseVals;
3755 unsigned NumItems = Record[CurIdx++];
3756 for (unsigned ci = 0; ci != NumItems; ++ci) {
3757 bool isSingleNumber = Record[CurIdx++];
3760 unsigned ActiveWords = 1;
3761 if (ValueBitWidth > 64)
3762 ActiveWords = Record[CurIdx++];
3763 Low = ReadWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords),
3765 CurIdx += ActiveWords;
3767 if (!isSingleNumber) {
3769 if (ValueBitWidth > 64)
3770 ActiveWords = Record[CurIdx++];
3772 ReadWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords),
3774 CurIdx += ActiveWords;
3776 // FIXME: It is not clear whether values in the range should be
3777 // compared as signed or unsigned values. The partially
3778 // implemented changes that used this format in the past used
3779 // unsigned comparisons.
3780 for ( ; Low.ule(High); ++Low)
3781 CaseVals.push_back(ConstantInt::get(Context, Low));
3783 CaseVals.push_back(ConstantInt::get(Context, Low));
3785 BasicBlock *DestBB = getBasicBlock(Record[CurIdx++]);
3786 for (SmallVector<ConstantInt*, 1>::iterator cvi = CaseVals.begin(),
3787 cve = CaseVals.end(); cvi != cve; ++cvi)
3788 SI->addCase(*cvi, DestBB);
3794 // Old SwitchInst format without case ranges.
3796 if (Record.size() < 3 || (Record.size() & 1) == 0)
3797 return Error("Invalid record");
3798 Type *OpTy = getTypeByID(Record[0]);
3799 Value *Cond = getValue(Record, 1, NextValueNo, OpTy);
3800 BasicBlock *Default = getBasicBlock(Record[2]);
3801 if (!OpTy || !Cond || !Default)
3802 return Error("Invalid record");
3803 unsigned NumCases = (Record.size()-3)/2;
3804 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
3805 InstructionList.push_back(SI);
3806 for (unsigned i = 0, e = NumCases; i != e; ++i) {
3807 ConstantInt *CaseVal =
3808 dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy));
3809 BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]);
3810 if (!CaseVal || !DestBB) {
3812 return Error("Invalid record");
3814 SI->addCase(CaseVal, DestBB);
3819 case bitc::FUNC_CODE_INST_INDIRECTBR: { // INDIRECTBR: [opty, op0, op1, ...]
3820 if (Record.size() < 2)
3821 return Error("Invalid record");
3822 Type *OpTy = getTypeByID(Record[0]);
3823 Value *Address = getValue(Record, 1, NextValueNo, OpTy);
3824 if (!OpTy || !Address)
3825 return Error("Invalid record");
3826 unsigned NumDests = Record.size()-2;
3827 IndirectBrInst *IBI = IndirectBrInst::Create(Address, NumDests);
3828 InstructionList.push_back(IBI);
3829 for (unsigned i = 0, e = NumDests; i != e; ++i) {
3830 if (BasicBlock *DestBB = getBasicBlock(Record[2+i])) {
3831 IBI->addDestination(DestBB);
3834 return Error("Invalid record");
3841 case bitc::FUNC_CODE_INST_INVOKE: {
3842 // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...]
3843 if (Record.size() < 4)
3844 return Error("Invalid record");
3845 AttributeSet PAL = getAttributes(Record[0]);
3846 unsigned CCInfo = Record[1];
3847 BasicBlock *NormalBB = getBasicBlock(Record[2]);
3848 BasicBlock *UnwindBB = getBasicBlock(Record[3]);
3852 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
3853 return Error("Invalid record");
3855 PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType());
3856 FunctionType *FTy = !CalleeTy ? nullptr :
3857 dyn_cast<FunctionType>(CalleeTy->getElementType());
3859 // Check that the right number of fixed parameters are here.
3860 if (!FTy || !NormalBB || !UnwindBB ||
3861 Record.size() < OpNum+FTy->getNumParams())
3862 return Error("Invalid record");
3864 SmallVector<Value*, 16> Ops;
3865 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
3866 Ops.push_back(getValue(Record, OpNum, NextValueNo,
3867 FTy->getParamType(i)));
3869 return Error("Invalid record");
3872 if (!FTy->isVarArg()) {
3873 if (Record.size() != OpNum)
3874 return Error("Invalid record");
3876 // Read type/value pairs for varargs params.
3877 while (OpNum != Record.size()) {
3879 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
3880 return Error("Invalid record");
3885 I = InvokeInst::Create(Callee, NormalBB, UnwindBB, Ops);
3886 InstructionList.push_back(I);
3887 cast<InvokeInst>(I)->setCallingConv(
3888 static_cast<CallingConv::ID>(CCInfo));
3889 cast<InvokeInst>(I)->setAttributes(PAL);
3892 case bitc::FUNC_CODE_INST_RESUME: { // RESUME: [opval]
3894 Value *Val = nullptr;
3895 if (getValueTypePair(Record, Idx, NextValueNo, Val))
3896 return Error("Invalid record");
3897 I = ResumeInst::Create(Val);
3898 InstructionList.push_back(I);
3901 case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE
3902 I = new UnreachableInst(Context);
3903 InstructionList.push_back(I);
3905 case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...]
3906 if (Record.size() < 1 || ((Record.size()-1)&1))
3907 return Error("Invalid record");
3908 Type *Ty = getTypeByID(Record[0]);
3910 return Error("Invalid record");
3912 PHINode *PN = PHINode::Create(Ty, (Record.size()-1)/2);
3913 InstructionList.push_back(PN);
3915 for (unsigned i = 0, e = Record.size()-1; i != e; i += 2) {
3917 // With the new function encoding, it is possible that operands have
3918 // negative IDs (for forward references). Use a signed VBR
3919 // representation to keep the encoding small.
3921 V = getValueSigned(Record, 1+i, NextValueNo, Ty);
3923 V = getValue(Record, 1+i, NextValueNo, Ty);
3924 BasicBlock *BB = getBasicBlock(Record[2+i]);
3926 return Error("Invalid record");
3927 PN->addIncoming(V, BB);
3933 case bitc::FUNC_CODE_INST_LANDINGPAD: {
3934 // LANDINGPAD: [ty, val, val, num, (id0,val0 ...)?]
3936 if (Record.size() < 4)
3937 return Error("Invalid record");
3938 Type *Ty = getTypeByID(Record[Idx++]);
3940 return Error("Invalid record");
3941 Value *PersFn = nullptr;
3942 if (getValueTypePair(Record, Idx, NextValueNo, PersFn))
3943 return Error("Invalid record");
3945 bool IsCleanup = !!Record[Idx++];
3946 unsigned NumClauses = Record[Idx++];
3947 LandingPadInst *LP = LandingPadInst::Create(Ty, PersFn, NumClauses);
3948 LP->setCleanup(IsCleanup);
3949 for (unsigned J = 0; J != NumClauses; ++J) {
3950 LandingPadInst::ClauseType CT =
3951 LandingPadInst::ClauseType(Record[Idx++]); (void)CT;
3954 if (getValueTypePair(Record, Idx, NextValueNo, Val)) {
3956 return Error("Invalid record");
3959 assert((CT != LandingPadInst::Catch ||
3960 !isa<ArrayType>(Val->getType())) &&
3961 "Catch clause has a invalid type!");
3962 assert((CT != LandingPadInst::Filter ||
3963 isa<ArrayType>(Val->getType())) &&
3964 "Filter clause has invalid type!");
3965 LP->addClause(cast<Constant>(Val));
3969 InstructionList.push_back(I);
3973 case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, opty, op, align]
3974 if (Record.size() != 4)
3975 return Error("Invalid record");
3977 dyn_cast_or_null<PointerType>(getTypeByID(Record[0]));
3978 Type *OpTy = getTypeByID(Record[1]);
3979 Value *Size = getFnValueByID(Record[2], OpTy);
3980 uint64_t AlignRecord = Record[3];
3981 const uint64_t InAllocaMask = uint64_t(1) << 5;
3982 bool InAlloca = AlignRecord & InAllocaMask;
3984 if (std::error_code EC =
3985 parseAlignmentValue(AlignRecord & ~InAllocaMask, Align)) {
3989 return Error("Invalid record");
3990 AllocaInst *AI = new AllocaInst(Ty->getElementType(), Size, Align);
3991 AI->setUsedWithInAlloca(InAlloca);
3993 InstructionList.push_back(I);
3996 case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol]
3999 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
4000 (OpNum + 2 != Record.size() && OpNum + 3 != Record.size()))
4001 return Error("Invalid record");
4004 if (OpNum + 3 == Record.size())
4005 Ty = getTypeByID(Record[OpNum++]);
4008 if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align))
4010 I = new LoadInst(Op, "", Record[OpNum+1], Align);
4012 if (Ty && Ty != I->getType())
4013 return Error("Explicit load type does not match pointee type of "
4016 InstructionList.push_back(I);
4019 case bitc::FUNC_CODE_INST_LOADATOMIC: {
4020 // LOADATOMIC: [opty, op, align, vol, ordering, synchscope]
4023 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
4024 (OpNum + 4 != Record.size() && OpNum + 5 != Record.size()))
4025 return Error("Invalid record");
4028 if (OpNum + 5 == Record.size())
4029 Ty = getTypeByID(Record[OpNum++]);
4031 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
4032 if (Ordering == NotAtomic || Ordering == Release ||
4033 Ordering == AcquireRelease)
4034 return Error("Invalid record");
4035 if (Ordering != NotAtomic && Record[OpNum] == 0)
4036 return Error("Invalid record");
4037 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
4040 if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align))
4042 I = new LoadInst(Op, "", Record[OpNum+1], Align, Ordering, SynchScope);
4045 assert((!Ty || Ty == I->getType()) &&
4046 "Explicit type doesn't match pointee type of the first operand");
4048 InstructionList.push_back(I);
4051 case bitc::FUNC_CODE_INST_STORE: { // STORE2:[ptrty, ptr, val, align, vol]
4054 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
4055 popValue(Record, OpNum, NextValueNo,
4056 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
4057 OpNum+2 != Record.size())
4058 return Error("Invalid record");
4060 if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align))
4062 I = new StoreInst(Val, Ptr, Record[OpNum+1], Align);
4063 InstructionList.push_back(I);
4066 case bitc::FUNC_CODE_INST_STOREATOMIC: {
4067 // STOREATOMIC: [ptrty, ptr, val, align, vol, ordering, synchscope]
4070 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
4071 popValue(Record, OpNum, NextValueNo,
4072 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
4073 OpNum+4 != Record.size())
4074 return Error("Invalid record");
4076 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
4077 if (Ordering == NotAtomic || Ordering == Acquire ||
4078 Ordering == AcquireRelease)
4079 return Error("Invalid record");
4080 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
4081 if (Ordering != NotAtomic && Record[OpNum] == 0)
4082 return Error("Invalid record");
4085 if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align))
4087 I = new StoreInst(Val, Ptr, Record[OpNum+1], Align, Ordering, SynchScope);
4088 InstructionList.push_back(I);
4091 case bitc::FUNC_CODE_INST_CMPXCHG: {
4092 // CMPXCHG:[ptrty, ptr, cmp, new, vol, successordering, synchscope,
4093 // failureordering?, isweak?]
4095 Value *Ptr, *Cmp, *New;
4096 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
4097 popValue(Record, OpNum, NextValueNo,
4098 cast<PointerType>(Ptr->getType())->getElementType(), Cmp) ||
4099 popValue(Record, OpNum, NextValueNo,
4100 cast<PointerType>(Ptr->getType())->getElementType(), New) ||
4101 (Record.size() < OpNum + 3 || Record.size() > OpNum + 5))
4102 return Error("Invalid record");
4103 AtomicOrdering SuccessOrdering = GetDecodedOrdering(Record[OpNum+1]);
4104 if (SuccessOrdering == NotAtomic || SuccessOrdering == Unordered)
4105 return Error("Invalid record");
4106 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+2]);
4108 AtomicOrdering FailureOrdering;
4109 if (Record.size() < 7)
4111 AtomicCmpXchgInst::getStrongestFailureOrdering(SuccessOrdering);
4113 FailureOrdering = GetDecodedOrdering(Record[OpNum+3]);
4115 I = new AtomicCmpXchgInst(Ptr, Cmp, New, SuccessOrdering, FailureOrdering,
4117 cast<AtomicCmpXchgInst>(I)->setVolatile(Record[OpNum]);
4119 if (Record.size() < 8) {
4120 // Before weak cmpxchgs existed, the instruction simply returned the
4121 // value loaded from memory, so bitcode files from that era will be
4122 // expecting the first component of a modern cmpxchg.
4123 CurBB->getInstList().push_back(I);
4124 I = ExtractValueInst::Create(I, 0);
4126 cast<AtomicCmpXchgInst>(I)->setWeak(Record[OpNum+4]);
4129 InstructionList.push_back(I);
4132 case bitc::FUNC_CODE_INST_ATOMICRMW: {
4133 // ATOMICRMW:[ptrty, ptr, val, op, vol, ordering, synchscope]
4136 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
4137 popValue(Record, OpNum, NextValueNo,
4138 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
4139 OpNum+4 != Record.size())
4140 return Error("Invalid record");
4141 AtomicRMWInst::BinOp Operation = GetDecodedRMWOperation(Record[OpNum]);
4142 if (Operation < AtomicRMWInst::FIRST_BINOP ||
4143 Operation > AtomicRMWInst::LAST_BINOP)
4144 return Error("Invalid record");
4145 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
4146 if (Ordering == NotAtomic || Ordering == Unordered)
4147 return Error("Invalid record");
4148 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
4149 I = new AtomicRMWInst(Operation, Ptr, Val, Ordering, SynchScope);
4150 cast<AtomicRMWInst>(I)->setVolatile(Record[OpNum+1]);
4151 InstructionList.push_back(I);
4154 case bitc::FUNC_CODE_INST_FENCE: { // FENCE:[ordering, synchscope]
4155 if (2 != Record.size())
4156 return Error("Invalid record");
4157 AtomicOrdering Ordering = GetDecodedOrdering(Record[0]);
4158 if (Ordering == NotAtomic || Ordering == Unordered ||
4159 Ordering == Monotonic)
4160 return Error("Invalid record");
4161 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[1]);
4162 I = new FenceInst(Context, Ordering, SynchScope);
4163 InstructionList.push_back(I);
4166 case bitc::FUNC_CODE_INST_CALL: {
4167 // CALL: [paramattrs, cc, fnty, fnid, arg0, arg1...]
4168 if (Record.size() < 3)
4169 return Error("Invalid record");
4171 AttributeSet PAL = getAttributes(Record[0]);
4172 unsigned CCInfo = Record[1];
4176 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
4177 return Error("Invalid record");
4179 PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());
4180 FunctionType *FTy = nullptr;
4181 if (OpTy) FTy = dyn_cast<FunctionType>(OpTy->getElementType());
4182 if (!FTy || Record.size() < FTy->getNumParams()+OpNum)
4183 return Error("Invalid record");
4185 SmallVector<Value*, 16> Args;
4186 // Read the fixed params.
4187 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
4188 if (FTy->getParamType(i)->isLabelTy())
4189 Args.push_back(getBasicBlock(Record[OpNum]));
4191 Args.push_back(getValue(Record, OpNum, NextValueNo,
4192 FTy->getParamType(i)));
4194 return Error("Invalid record");
4197 // Read type/value pairs for varargs params.
4198 if (!FTy->isVarArg()) {
4199 if (OpNum != Record.size())
4200 return Error("Invalid record");
4202 while (OpNum != Record.size()) {
4204 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
4205 return Error("Invalid record");
4210 I = CallInst::Create(Callee, Args);
4211 InstructionList.push_back(I);
4212 cast<CallInst>(I)->setCallingConv(
4213 static_cast<CallingConv::ID>((~(1U << 14) & CCInfo) >> 1));
4214 CallInst::TailCallKind TCK = CallInst::TCK_None;
4216 TCK = CallInst::TCK_Tail;
4217 if (CCInfo & (1 << 14))
4218 TCK = CallInst::TCK_MustTail;
4219 cast<CallInst>(I)->setTailCallKind(TCK);
4220 cast<CallInst>(I)->setAttributes(PAL);
4223 case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty]
4224 if (Record.size() < 3)
4225 return Error("Invalid record");
4226 Type *OpTy = getTypeByID(Record[0]);
4227 Value *Op = getValue(Record, 1, NextValueNo, OpTy);
4228 Type *ResTy = getTypeByID(Record[2]);
4229 if (!OpTy || !Op || !ResTy)
4230 return Error("Invalid record");
4231 I = new VAArgInst(Op, ResTy);
4232 InstructionList.push_back(I);
4237 // Add instruction to end of current BB. If there is no current BB, reject
4241 return Error("Invalid instruction with no BB");
4243 CurBB->getInstList().push_back(I);
4245 // If this was a terminator instruction, move to the next block.
4246 if (isa<TerminatorInst>(I)) {
4248 CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : nullptr;
4251 // Non-void values get registered in the value table for future use.
4252 if (I && !I->getType()->isVoidTy())
4253 ValueList.AssignValue(I, NextValueNo++);
4258 // Check the function list for unresolved values.
4259 if (Argument *A = dyn_cast<Argument>(ValueList.back())) {
4260 if (!A->getParent()) {
4261 // We found at least one unresolved value. Nuke them all to avoid leaks.
4262 for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){
4263 if ((A = dyn_cast_or_null<Argument>(ValueList[i])) && !A->getParent()) {
4264 A->replaceAllUsesWith(UndefValue::get(A->getType()));
4268 return Error("Never resolved value found in function");
4272 // FIXME: Check for unresolved forward-declared metadata references
4273 // and clean up leaks.
4275 // Trim the value list down to the size it was before we parsed this function.
4276 ValueList.shrinkTo(ModuleValueListSize);
4277 MDValueList.shrinkTo(ModuleMDValueListSize);
4278 std::vector<BasicBlock*>().swap(FunctionBBs);
4279 return std::error_code();
4282 /// Find the function body in the bitcode stream
4283 std::error_code BitcodeReader::FindFunctionInStream(
4285 DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator) {
4286 while (DeferredFunctionInfoIterator->second == 0) {
4287 if (Stream.AtEndOfStream())
4288 return Error("Could not find function in stream");
4289 // ParseModule will parse the next body in the stream and set its
4290 // position in the DeferredFunctionInfo map.
4291 if (std::error_code EC = ParseModule(true))
4294 return std::error_code();
4297 //===----------------------------------------------------------------------===//
4298 // GVMaterializer implementation
4299 //===----------------------------------------------------------------------===//
4301 void BitcodeReader::releaseBuffer() { Buffer.release(); }
4303 std::error_code BitcodeReader::materialize(GlobalValue *GV) {
4304 if (std::error_code EC = materializeMetadata())
4307 Function *F = dyn_cast<Function>(GV);
4308 // If it's not a function or is already material, ignore the request.
4309 if (!F || !F->isMaterializable())
4310 return std::error_code();
4312 DenseMap<Function*, uint64_t>::iterator DFII = DeferredFunctionInfo.find(F);
4313 assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!");
4314 // If its position is recorded as 0, its body is somewhere in the stream
4315 // but we haven't seen it yet.
4316 if (DFII->second == 0 && LazyStreamer)
4317 if (std::error_code EC = FindFunctionInStream(F, DFII))
4320 // Move the bit stream to the saved position of the deferred function body.
4321 Stream.JumpToBit(DFII->second);
4323 if (std::error_code EC = ParseFunctionBody(F))
4325 F->setIsMaterializable(false);
4330 // Upgrade any old intrinsic calls in the function.
4331 for (UpgradedIntrinsicMap::iterator I = UpgradedIntrinsics.begin(),
4332 E = UpgradedIntrinsics.end(); I != E; ++I) {
4333 if (I->first != I->second) {
4334 for (auto UI = I->first->user_begin(), UE = I->first->user_end();
4336 if (CallInst* CI = dyn_cast<CallInst>(*UI++))
4337 UpgradeIntrinsicCall(CI, I->second);
4342 // Bring in any functions that this function forward-referenced via
4344 return materializeForwardReferencedFunctions();
4347 bool BitcodeReader::isDematerializable(const GlobalValue *GV) const {
4348 const Function *F = dyn_cast<Function>(GV);
4349 if (!F || F->isDeclaration())
4352 // Dematerializing F would leave dangling references that wouldn't be
4353 // reconnected on re-materialization.
4354 if (BlockAddressesTaken.count(F))
4357 return DeferredFunctionInfo.count(const_cast<Function*>(F));
4360 void BitcodeReader::Dematerialize(GlobalValue *GV) {
4361 Function *F = dyn_cast<Function>(GV);
4362 // If this function isn't dematerializable, this is a noop.
4363 if (!F || !isDematerializable(F))
4366 assert(DeferredFunctionInfo.count(F) && "No info to read function later?");
4368 // Just forget the function body, we can remat it later.
4369 F->dropAllReferences();
4370 F->setIsMaterializable(true);
4373 std::error_code BitcodeReader::MaterializeModule(Module *M) {
4374 assert(M == TheModule &&
4375 "Can only Materialize the Module this BitcodeReader is attached to.");
4377 if (std::error_code EC = materializeMetadata())
4380 // Promise to materialize all forward references.
4381 WillMaterializeAllForwardRefs = true;
4383 // Iterate over the module, deserializing any functions that are still on
4385 for (Module::iterator F = TheModule->begin(), E = TheModule->end();
4387 if (std::error_code EC = materialize(F))
4390 // At this point, if there are any function bodies, the current bit is
4391 // pointing to the END_BLOCK record after them. Now make sure the rest
4392 // of the bits in the module have been read.
4396 // Check that all block address forward references got resolved (as we
4398 if (!BasicBlockFwdRefs.empty())
4399 return Error("Never resolved function from blockaddress");
4401 // Upgrade any intrinsic calls that slipped through (should not happen!) and
4402 // delete the old functions to clean up. We can't do this unless the entire
4403 // module is materialized because there could always be another function body
4404 // with calls to the old function.
4405 for (std::vector<std::pair<Function*, Function*> >::iterator I =
4406 UpgradedIntrinsics.begin(), E = UpgradedIntrinsics.end(); I != E; ++I) {
4407 if (I->first != I->second) {
4408 for (auto UI = I->first->user_begin(), UE = I->first->user_end();
4410 if (CallInst* CI = dyn_cast<CallInst>(*UI++))
4411 UpgradeIntrinsicCall(CI, I->second);
4413 if (!I->first->use_empty())
4414 I->first->replaceAllUsesWith(I->second);
4415 I->first->eraseFromParent();
4418 std::vector<std::pair<Function*, Function*> >().swap(UpgradedIntrinsics);
4420 for (unsigned I = 0, E = InstsWithTBAATag.size(); I < E; I++)
4421 UpgradeInstWithTBAATag(InstsWithTBAATag[I]);
4423 UpgradeDebugInfo(*M);
4424 return std::error_code();
4427 std::vector<StructType *> BitcodeReader::getIdentifiedStructTypes() const {
4428 return IdentifiedStructTypes;
4431 std::error_code BitcodeReader::InitStream() {
4433 return InitLazyStream();
4434 return InitStreamFromBuffer();
4437 std::error_code BitcodeReader::InitStreamFromBuffer() {
4438 const unsigned char *BufPtr = (const unsigned char*)Buffer->getBufferStart();
4439 const unsigned char *BufEnd = BufPtr+Buffer->getBufferSize();
4441 if (Buffer->getBufferSize() & 3)
4442 return Error("Invalid bitcode signature");
4444 // If we have a wrapper header, parse it and ignore the non-bc file contents.
4445 // The magic number is 0x0B17C0DE stored in little endian.
4446 if (isBitcodeWrapper(BufPtr, BufEnd))
4447 if (SkipBitcodeWrapperHeader(BufPtr, BufEnd, true))
4448 return Error("Invalid bitcode wrapper header");
4450 StreamFile.reset(new BitstreamReader(BufPtr, BufEnd));
4451 Stream.init(&*StreamFile);
4453 return std::error_code();
4456 std::error_code BitcodeReader::InitLazyStream() {
4457 // Check and strip off the bitcode wrapper; BitstreamReader expects never to
4459 auto OwnedBytes = llvm::make_unique<StreamingMemoryObject>(LazyStreamer);
4460 StreamingMemoryObject &Bytes = *OwnedBytes;
4461 StreamFile = llvm::make_unique<BitstreamReader>(std::move(OwnedBytes));
4462 Stream.init(&*StreamFile);
4464 unsigned char buf[16];
4465 if (Bytes.readBytes(buf, 16, 0) != 16)
4466 return Error("Invalid bitcode signature");
4468 if (!isBitcode(buf, buf + 16))
4469 return Error("Invalid bitcode signature");
4471 if (isBitcodeWrapper(buf, buf + 4)) {
4472 const unsigned char *bitcodeStart = buf;
4473 const unsigned char *bitcodeEnd = buf + 16;
4474 SkipBitcodeWrapperHeader(bitcodeStart, bitcodeEnd, false);
4475 Bytes.dropLeadingBytes(bitcodeStart - buf);
4476 Bytes.setKnownObjectSize(bitcodeEnd - bitcodeStart);
4478 return std::error_code();
4482 class BitcodeErrorCategoryType : public std::error_category {
4483 const char *name() const LLVM_NOEXCEPT override {
4484 return "llvm.bitcode";
4486 std::string message(int IE) const override {
4487 BitcodeError E = static_cast<BitcodeError>(IE);
4489 case BitcodeError::InvalidBitcodeSignature:
4490 return "Invalid bitcode signature";
4491 case BitcodeError::CorruptedBitcode:
4492 return "Corrupted bitcode";
4494 llvm_unreachable("Unknown error type!");
4499 static ManagedStatic<BitcodeErrorCategoryType> ErrorCategory;
4501 const std::error_category &llvm::BitcodeErrorCategory() {
4502 return *ErrorCategory;
4505 //===----------------------------------------------------------------------===//
4506 // External interface
4507 //===----------------------------------------------------------------------===//
4509 /// \brief Get a lazy one-at-time loading module from bitcode.
4511 /// This isn't always used in a lazy context. In particular, it's also used by
4512 /// \a parseBitcodeFile(). If this is truly lazy, then we need to eagerly pull
4513 /// in forward-referenced functions from block address references.
4515 /// \param[in] WillMaterializeAll Set to \c true if the caller promises to
4516 /// materialize everything -- in particular, if this isn't truly lazy.
4517 static ErrorOr<Module *>
4518 getLazyBitcodeModuleImpl(std::unique_ptr<MemoryBuffer> &&Buffer,
4519 LLVMContext &Context, bool WillMaterializeAll,
4520 DiagnosticHandlerFunction DiagnosticHandler,
4521 bool ShouldLazyLoadMetadata = false) {
4522 Module *M = new Module(Buffer->getBufferIdentifier(), Context);
4524 new BitcodeReader(Buffer.get(), Context, DiagnosticHandler);
4525 M->setMaterializer(R);
4527 auto cleanupOnError = [&](std::error_code EC) {
4528 R->releaseBuffer(); // Never take ownership on error.
4529 delete M; // Also deletes R.
4533 // Delay parsing Metadata if ShouldLazyLoadMetadata is true.
4534 if (std::error_code EC = R->ParseBitcodeInto(M, ShouldLazyLoadMetadata))
4535 return cleanupOnError(EC);
4537 if (!WillMaterializeAll)
4538 // Resolve forward references from blockaddresses.
4539 if (std::error_code EC = R->materializeForwardReferencedFunctions())
4540 return cleanupOnError(EC);
4542 Buffer.release(); // The BitcodeReader owns it now.
4547 llvm::getLazyBitcodeModule(std::unique_ptr<MemoryBuffer> &&Buffer,
4548 LLVMContext &Context,
4549 DiagnosticHandlerFunction DiagnosticHandler,
4550 bool ShouldLazyLoadMetadata) {
4551 return getLazyBitcodeModuleImpl(std::move(Buffer), Context, false,
4552 DiagnosticHandler, ShouldLazyLoadMetadata);
4555 ErrorOr<std::unique_ptr<Module>>
4556 llvm::getStreamedBitcodeModule(StringRef Name, DataStreamer *Streamer,
4557 LLVMContext &Context,
4558 DiagnosticHandlerFunction DiagnosticHandler) {
4559 std::unique_ptr<Module> M = make_unique<Module>(Name, Context);
4560 BitcodeReader *R = new BitcodeReader(Streamer, Context, DiagnosticHandler);
4561 M->setMaterializer(R);
4562 if (std::error_code EC = R->ParseBitcodeInto(M.get()))
4564 return std::move(M);
4568 llvm::parseBitcodeFile(MemoryBufferRef Buffer, LLVMContext &Context,
4569 DiagnosticHandlerFunction DiagnosticHandler) {
4570 std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
4571 ErrorOr<Module *> ModuleOrErr = getLazyBitcodeModuleImpl(
4572 std::move(Buf), Context, true, DiagnosticHandler);
4575 Module *M = ModuleOrErr.get();
4576 // Read in the entire module, and destroy the BitcodeReader.
4577 if (std::error_code EC = M->materializeAllPermanently()) {
4582 // TODO: Restore the use-lists to the in-memory state when the bitcode was
4583 // written. We must defer until the Module has been fully materialized.
4589 llvm::getBitcodeTargetTriple(MemoryBufferRef Buffer, LLVMContext &Context,
4590 DiagnosticHandlerFunction DiagnosticHandler) {
4591 std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
4592 auto R = llvm::make_unique<BitcodeReader>(Buf.release(), Context,
4594 ErrorOr<std::string> Triple = R->parseTriple();
4595 if (Triple.getError())
4597 return Triple.get();