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/FunctionInfo.h"
31 #include "llvm/IR/ValueHandle.h"
32 #include "llvm/Support/DataStream.h"
33 #include "llvm/Support/ManagedStatic.h"
34 #include "llvm/Support/MathExtras.h"
35 #include "llvm/Support/MemoryBuffer.h"
36 #include "llvm/Support/raw_ostream.h"
42 SWITCH_INST_MAGIC = 0x4B5 // May 2012 => 1205 => Hex
45 /// Indicates which operator an operand allows (for the few operands that may
46 /// only reference a certain operator).
47 enum OperatorConstraint {
48 OC_None = 0, // No constraint
49 OC_CatchPad, // Must be CatchPadInst
50 OC_CleanupPad // Must be CleanupPadInst
53 class BitcodeReaderValueList {
54 std::vector<WeakVH> ValuePtrs;
56 /// As we resolve forward-referenced constants, we add information about them
57 /// to this vector. This allows us to resolve them in bulk instead of
58 /// resolving each reference at a time. See the code in
59 /// ResolveConstantForwardRefs for more information about this.
61 /// The key of this vector is the placeholder constant, the value is the slot
62 /// number that holds the resolved value.
63 typedef std::vector<std::pair<Constant*, unsigned> > ResolveConstantsTy;
64 ResolveConstantsTy ResolveConstants;
67 BitcodeReaderValueList(LLVMContext &C) : Context(C) {}
68 ~BitcodeReaderValueList() {
69 assert(ResolveConstants.empty() && "Constants not resolved?");
72 // vector compatibility methods
73 unsigned size() const { return ValuePtrs.size(); }
74 void resize(unsigned N) { ValuePtrs.resize(N); }
75 void push_back(Value *V) { ValuePtrs.emplace_back(V); }
78 assert(ResolveConstants.empty() && "Constants not resolved?");
82 Value *operator[](unsigned i) const {
83 assert(i < ValuePtrs.size());
87 Value *back() const { return ValuePtrs.back(); }
88 void pop_back() { ValuePtrs.pop_back(); }
89 bool empty() const { return ValuePtrs.empty(); }
90 void shrinkTo(unsigned N) {
91 assert(N <= size() && "Invalid shrinkTo request!");
95 Constant *getConstantFwdRef(unsigned Idx, Type *Ty);
96 Value *getValueFwdRef(unsigned Idx, Type *Ty,
97 OperatorConstraint OC = OC_None);
99 bool assignValue(Value *V, unsigned Idx);
101 /// Once all constants are read, this method bulk resolves any forward
103 void resolveConstantForwardRefs();
106 class BitcodeReaderMDValueList {
111 std::vector<TrackingMDRef> MDValuePtrs;
113 LLVMContext &Context;
115 BitcodeReaderMDValueList(LLVMContext &C)
116 : NumFwdRefs(0), AnyFwdRefs(false), Context(C) {}
118 // vector compatibility methods
119 unsigned size() const { return MDValuePtrs.size(); }
120 void resize(unsigned N) { MDValuePtrs.resize(N); }
121 void push_back(Metadata *MD) { MDValuePtrs.emplace_back(MD); }
122 void clear() { MDValuePtrs.clear(); }
123 Metadata *back() const { return MDValuePtrs.back(); }
124 void pop_back() { MDValuePtrs.pop_back(); }
125 bool empty() const { return MDValuePtrs.empty(); }
127 Metadata *operator[](unsigned i) const {
128 assert(i < MDValuePtrs.size());
129 return MDValuePtrs[i];
132 void shrinkTo(unsigned N) {
133 assert(N <= size() && "Invalid shrinkTo request!");
134 MDValuePtrs.resize(N);
137 Metadata *getValueFwdRef(unsigned Idx);
138 void assignValue(Metadata *MD, unsigned Idx);
139 void tryToResolveCycles();
142 class BitcodeReader : public GVMaterializer {
143 LLVMContext &Context;
144 DiagnosticHandlerFunction DiagnosticHandler;
145 Module *TheModule = nullptr;
146 std::unique_ptr<MemoryBuffer> Buffer;
147 std::unique_ptr<BitstreamReader> StreamFile;
148 BitstreamCursor Stream;
149 // Next offset to start scanning for lazy parsing of function bodies.
150 uint64_t NextUnreadBit = 0;
151 // Last function offset found in the VST.
152 uint64_t LastFunctionBlockBit = 0;
153 bool SeenValueSymbolTable = false;
154 uint64_t VSTOffset = 0;
155 // Contains an arbitrary and optional string identifying the bitcode producer
156 std::string ProducerIdentification;
158 std::vector<Type*> TypeList;
159 BitcodeReaderValueList ValueList;
160 BitcodeReaderMDValueList MDValueList;
161 std::vector<Comdat *> ComdatList;
162 SmallVector<Instruction *, 64> InstructionList;
164 std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInits;
165 std::vector<std::pair<GlobalAlias*, unsigned> > AliasInits;
166 std::vector<std::pair<Function*, unsigned> > FunctionPrefixes;
167 std::vector<std::pair<Function*, unsigned> > FunctionPrologues;
168 std::vector<std::pair<Function*, unsigned> > FunctionPersonalityFns;
170 SmallVector<Instruction*, 64> InstsWithTBAATag;
172 /// The set of attributes by index. Index zero in the file is for null, and
173 /// is thus not represented here. As such all indices are off by one.
174 std::vector<AttributeSet> MAttributes;
176 /// The set of attribute groups.
177 std::map<unsigned, AttributeSet> MAttributeGroups;
179 /// While parsing a function body, this is a list of the basic blocks for the
181 std::vector<BasicBlock*> FunctionBBs;
183 // When reading the module header, this list is populated with functions that
184 // have bodies later in the file.
185 std::vector<Function*> FunctionsWithBodies;
187 // When intrinsic functions are encountered which require upgrading they are
188 // stored here with their replacement function.
189 typedef DenseMap<Function*, Function*> UpgradedIntrinsicMap;
190 UpgradedIntrinsicMap UpgradedIntrinsics;
192 // Map the bitcode's custom MDKind ID to the Module's MDKind ID.
193 DenseMap<unsigned, unsigned> MDKindMap;
195 // Several operations happen after the module header has been read, but
196 // before function bodies are processed. This keeps track of whether
197 // we've done this yet.
198 bool SeenFirstFunctionBody = false;
200 /// When function bodies are initially scanned, this map contains info about
201 /// where to find deferred function body in the stream.
202 DenseMap<Function*, uint64_t> DeferredFunctionInfo;
204 /// When Metadata block is initially scanned when parsing the module, we may
205 /// choose to defer parsing of the metadata. This vector contains info about
206 /// which Metadata blocks are deferred.
207 std::vector<uint64_t> DeferredMetadataInfo;
209 /// These are basic blocks forward-referenced by block addresses. They are
210 /// inserted lazily into functions when they're loaded. The basic block ID is
211 /// its index into the vector.
212 DenseMap<Function *, std::vector<BasicBlock *>> BasicBlockFwdRefs;
213 std::deque<Function *> BasicBlockFwdRefQueue;
215 /// Indicates that we are using a new encoding for instruction operands where
216 /// most operands in the current FUNCTION_BLOCK are encoded relative to the
217 /// instruction number, for a more compact encoding. Some instruction
218 /// operands are not relative to the instruction ID: basic block numbers, and
219 /// types. Once the old style function blocks have been phased out, we would
220 /// not need this flag.
221 bool UseRelativeIDs = false;
223 /// True if all functions will be materialized, negating the need to process
224 /// (e.g.) blockaddress forward references.
225 bool WillMaterializeAllForwardRefs = false;
227 /// Functions that have block addresses taken. This is usually empty.
228 SmallPtrSet<const Function *, 4> BlockAddressesTaken;
230 /// True if any Metadata block has been materialized.
231 bool IsMetadataMaterialized = false;
233 bool StripDebugInfo = false;
235 /// Functions that need to be matched with subprograms when upgrading old
237 SmallDenseMap<Function *, DISubprogram *, 16> FunctionsWithSPs;
239 std::vector<std::string> BundleTags;
242 std::error_code error(BitcodeError E, const Twine &Message);
243 std::error_code error(BitcodeError E);
244 std::error_code error(const Twine &Message);
246 BitcodeReader(MemoryBuffer *Buffer, LLVMContext &Context,
247 DiagnosticHandlerFunction DiagnosticHandler);
248 BitcodeReader(LLVMContext &Context,
249 DiagnosticHandlerFunction DiagnosticHandler);
250 ~BitcodeReader() override { freeState(); }
252 std::error_code materializeForwardReferencedFunctions();
256 void releaseBuffer();
258 bool isDematerializable(const GlobalValue *GV) const override;
259 std::error_code materialize(GlobalValue *GV) override;
260 std::error_code materializeModule(Module *M) override;
261 std::vector<StructType *> getIdentifiedStructTypes() const override;
262 void dematerialize(GlobalValue *GV) override;
264 /// \brief Main interface to parsing a bitcode buffer.
265 /// \returns true if an error occurred.
266 std::error_code parseBitcodeInto(std::unique_ptr<DataStreamer> Streamer,
268 bool ShouldLazyLoadMetadata = false);
270 /// \brief Cheap mechanism to just extract module triple
271 /// \returns true if an error occurred.
272 ErrorOr<std::string> parseTriple();
274 static uint64_t decodeSignRotatedValue(uint64_t V);
276 /// Materialize any deferred Metadata block.
277 std::error_code materializeMetadata() override;
279 void setStripDebugInfo() override;
282 /// Parse the "IDENTIFICATION_BLOCK_ID" block, populate the
283 // ProducerIdentification data member, and do some basic enforcement on the
284 // "epoch" encoded in the bitcode.
285 std::error_code parseBitcodeVersion();
287 std::vector<StructType *> IdentifiedStructTypes;
288 StructType *createIdentifiedStructType(LLVMContext &Context, StringRef Name);
289 StructType *createIdentifiedStructType(LLVMContext &Context);
291 Type *getTypeByID(unsigned ID);
292 Value *getFnValueByID(unsigned ID, Type *Ty,
293 OperatorConstraint OC = OC_None) {
294 if (Ty && Ty->isMetadataTy())
295 return MetadataAsValue::get(Ty->getContext(), getFnMetadataByID(ID));
296 return ValueList.getValueFwdRef(ID, Ty, OC);
298 Metadata *getFnMetadataByID(unsigned ID) {
299 return MDValueList.getValueFwdRef(ID);
301 BasicBlock *getBasicBlock(unsigned ID) const {
302 if (ID >= FunctionBBs.size()) return nullptr; // Invalid ID
303 return FunctionBBs[ID];
305 AttributeSet getAttributes(unsigned i) const {
306 if (i-1 < MAttributes.size())
307 return MAttributes[i-1];
308 return AttributeSet();
311 /// Read a value/type pair out of the specified record from slot 'Slot'.
312 /// Increment Slot past the number of slots used in the record. Return true on
314 bool getValueTypePair(SmallVectorImpl<uint64_t> &Record, unsigned &Slot,
315 unsigned InstNum, Value *&ResVal) {
316 if (Slot == Record.size()) return true;
317 unsigned ValNo = (unsigned)Record[Slot++];
318 // Adjust the ValNo, if it was encoded relative to the InstNum.
320 ValNo = InstNum - ValNo;
321 if (ValNo < InstNum) {
322 // If this is not a forward reference, just return the value we already
324 ResVal = getFnValueByID(ValNo, nullptr);
325 return ResVal == nullptr;
327 if (Slot == Record.size())
330 unsigned TypeNo = (unsigned)Record[Slot++];
331 ResVal = getFnValueByID(ValNo, getTypeByID(TypeNo));
332 return ResVal == nullptr;
335 /// Read a value out of the specified record from slot 'Slot'. Increment Slot
336 /// past the number of slots used by the value in the record. Return true if
337 /// there is an error.
338 bool popValue(SmallVectorImpl<uint64_t> &Record, unsigned &Slot,
339 unsigned InstNum, Type *Ty, Value *&ResVal,
340 OperatorConstraint OC = OC_None) {
341 if (getValue(Record, Slot, InstNum, Ty, ResVal, OC))
343 // All values currently take a single record slot.
348 /// Like popValue, but does not increment the Slot number.
349 bool getValue(SmallVectorImpl<uint64_t> &Record, unsigned Slot,
350 unsigned InstNum, Type *Ty, Value *&ResVal,
351 OperatorConstraint OC = OC_None) {
352 ResVal = getValue(Record, Slot, InstNum, Ty, OC);
353 return ResVal == nullptr;
356 /// Version of getValue that returns ResVal directly, or 0 if there is an
358 Value *getValue(SmallVectorImpl<uint64_t> &Record, unsigned Slot,
359 unsigned InstNum, Type *Ty, OperatorConstraint OC = OC_None) {
360 if (Slot == Record.size()) return nullptr;
361 unsigned ValNo = (unsigned)Record[Slot];
362 // Adjust the ValNo, if it was encoded relative to the InstNum.
364 ValNo = InstNum - ValNo;
365 return getFnValueByID(ValNo, Ty, OC);
368 /// Like getValue, but decodes signed VBRs.
369 Value *getValueSigned(SmallVectorImpl<uint64_t> &Record, unsigned Slot,
370 unsigned InstNum, Type *Ty,
371 OperatorConstraint OC = OC_None) {
372 if (Slot == Record.size()) return nullptr;
373 unsigned ValNo = (unsigned)decodeSignRotatedValue(Record[Slot]);
374 // Adjust the ValNo, if it was encoded relative to the InstNum.
376 ValNo = InstNum - ValNo;
377 return getFnValueByID(ValNo, Ty, OC);
380 /// Converts alignment exponent (i.e. power of two (or zero)) to the
381 /// corresponding alignment to use. If alignment is too large, returns
382 /// a corresponding error code.
383 std::error_code parseAlignmentValue(uint64_t Exponent, unsigned &Alignment);
384 std::error_code parseAttrKind(uint64_t Code, Attribute::AttrKind *Kind);
385 std::error_code parseModule(uint64_t ResumeBit,
386 bool ShouldLazyLoadMetadata = false);
387 std::error_code parseAttributeBlock();
388 std::error_code parseAttributeGroupBlock();
389 std::error_code parseTypeTable();
390 std::error_code parseTypeTableBody();
391 std::error_code parseOperandBundleTags();
393 ErrorOr<Value *> recordValue(SmallVectorImpl<uint64_t> &Record,
394 unsigned NameIndex, Triple &TT);
395 std::error_code parseValueSymbolTable(uint64_t Offset = 0);
396 std::error_code parseConstants();
397 std::error_code rememberAndSkipFunctionBodies();
398 std::error_code rememberAndSkipFunctionBody();
399 /// Save the positions of the Metadata blocks and skip parsing the blocks.
400 std::error_code rememberAndSkipMetadata();
401 std::error_code parseFunctionBody(Function *F);
402 std::error_code globalCleanup();
403 std::error_code resolveGlobalAndAliasInits();
404 std::error_code parseMetadata();
405 std::error_code parseMetadataAttachment(Function &F);
406 ErrorOr<std::string> parseModuleTriple();
407 std::error_code parseUseLists();
408 std::error_code initStream(std::unique_ptr<DataStreamer> Streamer);
409 std::error_code initStreamFromBuffer();
410 std::error_code initLazyStream(std::unique_ptr<DataStreamer> Streamer);
411 std::error_code findFunctionInStream(
413 DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator);
416 /// Class to manage reading and parsing function summary index bitcode
418 class FunctionIndexBitcodeReader {
419 DiagnosticHandlerFunction DiagnosticHandler;
421 /// Eventually points to the function index built during parsing.
422 FunctionInfoIndex *TheIndex = nullptr;
424 std::unique_ptr<MemoryBuffer> Buffer;
425 std::unique_ptr<BitstreamReader> StreamFile;
426 BitstreamCursor Stream;
428 /// \brief Used to indicate whether we are doing lazy parsing of summary data.
430 /// If false, the summary section is fully parsed into the index during
431 /// the initial parse. Otherwise, if true, the caller is expected to
432 /// invoke \a readFunctionSummary for each summary needed, and the summary
433 /// section is thus parsed lazily.
436 /// Used to indicate whether caller only wants to check for the presence
437 /// of the function summary bitcode section. All blocks are skipped,
438 /// but the SeenFuncSummary boolean is set.
439 bool CheckFuncSummaryPresenceOnly = false;
441 /// Indicates whether we have encountered a function summary section
442 /// yet during parsing, used when checking if file contains function
444 bool SeenFuncSummary = false;
446 /// \brief Map populated during function summary section parsing, and
447 /// consumed during ValueSymbolTable parsing.
449 /// Used to correlate summary records with VST entries. For the per-module
450 /// index this maps the ValueID to the parsed function summary, and
451 /// for the combined index this maps the summary record's bitcode
452 /// offset to the function summary (since in the combined index the
453 /// VST records do not hold value IDs but rather hold the function
454 /// summary record offset).
455 DenseMap<uint64_t, std::unique_ptr<FunctionSummary>> SummaryMap;
457 /// Map populated during module path string table parsing, from the
458 /// module ID to a string reference owned by the index's module
459 /// path string table, used to correlate with combined index function
461 DenseMap<uint64_t, StringRef> ModuleIdMap;
464 std::error_code error(BitcodeError E, const Twine &Message);
465 std::error_code error(BitcodeError E);
466 std::error_code error(const Twine &Message);
468 FunctionIndexBitcodeReader(MemoryBuffer *Buffer, LLVMContext &Context,
469 DiagnosticHandlerFunction DiagnosticHandler,
471 bool CheckFuncSummaryPresenceOnly = false);
472 FunctionIndexBitcodeReader(LLVMContext &Context,
473 DiagnosticHandlerFunction DiagnosticHandler,
475 bool CheckFuncSummaryPresenceOnly = false);
476 ~FunctionIndexBitcodeReader() { freeState(); }
480 void releaseBuffer();
482 /// Check if the parser has encountered a function summary section.
483 bool foundFuncSummary() { return SeenFuncSummary; }
485 /// \brief Main interface to parsing a bitcode buffer.
486 /// \returns true if an error occurred.
487 std::error_code parseSummaryIndexInto(std::unique_ptr<DataStreamer> Streamer,
488 FunctionInfoIndex *I);
490 /// \brief Interface for parsing a function summary lazily.
491 std::error_code parseFunctionSummary(std::unique_ptr<DataStreamer> Streamer,
492 FunctionInfoIndex *I,
493 size_t FunctionSummaryOffset);
496 std::error_code parseModule();
497 std::error_code parseValueSymbolTable();
498 std::error_code parseEntireSummary();
499 std::error_code parseModuleStringTable();
500 std::error_code initStream(std::unique_ptr<DataStreamer> Streamer);
501 std::error_code initStreamFromBuffer();
502 std::error_code initLazyStream(std::unique_ptr<DataStreamer> Streamer);
506 BitcodeDiagnosticInfo::BitcodeDiagnosticInfo(std::error_code EC,
507 DiagnosticSeverity Severity,
509 : DiagnosticInfo(DK_Bitcode, Severity), Msg(Msg), EC(EC) {}
511 void BitcodeDiagnosticInfo::print(DiagnosticPrinter &DP) const { DP << Msg; }
513 static std::error_code error(DiagnosticHandlerFunction DiagnosticHandler,
514 std::error_code EC, const Twine &Message) {
515 BitcodeDiagnosticInfo DI(EC, DS_Error, Message);
516 DiagnosticHandler(DI);
520 static std::error_code error(DiagnosticHandlerFunction DiagnosticHandler,
521 std::error_code EC) {
522 return error(DiagnosticHandler, EC, EC.message());
525 static std::error_code error(DiagnosticHandlerFunction DiagnosticHandler,
526 const Twine &Message) {
527 return error(DiagnosticHandler,
528 make_error_code(BitcodeError::CorruptedBitcode), Message);
531 std::error_code BitcodeReader::error(BitcodeError E, const Twine &Message) {
532 if (!ProducerIdentification.empty()) {
533 return ::error(DiagnosticHandler, make_error_code(E),
534 Message + " (Producer: '" + ProducerIdentification +
535 "' Reader: 'LLVM " + LLVM_VERSION_STRING "')");
537 return ::error(DiagnosticHandler, make_error_code(E), Message);
540 std::error_code BitcodeReader::error(const Twine &Message) {
541 if (!ProducerIdentification.empty()) {
542 return ::error(DiagnosticHandler,
543 make_error_code(BitcodeError::CorruptedBitcode),
544 Message + " (Producer: '" + ProducerIdentification +
545 "' Reader: 'LLVM " + LLVM_VERSION_STRING "')");
547 return ::error(DiagnosticHandler,
548 make_error_code(BitcodeError::CorruptedBitcode), Message);
551 std::error_code BitcodeReader::error(BitcodeError E) {
552 return ::error(DiagnosticHandler, make_error_code(E));
555 static DiagnosticHandlerFunction getDiagHandler(DiagnosticHandlerFunction F,
559 return [&C](const DiagnosticInfo &DI) { C.diagnose(DI); };
562 BitcodeReader::BitcodeReader(MemoryBuffer *Buffer, LLVMContext &Context,
563 DiagnosticHandlerFunction DiagnosticHandler)
565 DiagnosticHandler(getDiagHandler(DiagnosticHandler, Context)),
566 Buffer(Buffer), ValueList(Context), MDValueList(Context) {}
568 BitcodeReader::BitcodeReader(LLVMContext &Context,
569 DiagnosticHandlerFunction DiagnosticHandler)
571 DiagnosticHandler(getDiagHandler(DiagnosticHandler, Context)),
572 Buffer(nullptr), ValueList(Context), MDValueList(Context) {}
574 std::error_code BitcodeReader::materializeForwardReferencedFunctions() {
575 if (WillMaterializeAllForwardRefs)
576 return std::error_code();
578 // Prevent recursion.
579 WillMaterializeAllForwardRefs = true;
581 while (!BasicBlockFwdRefQueue.empty()) {
582 Function *F = BasicBlockFwdRefQueue.front();
583 BasicBlockFwdRefQueue.pop_front();
584 assert(F && "Expected valid function");
585 if (!BasicBlockFwdRefs.count(F))
586 // Already materialized.
589 // Check for a function that isn't materializable to prevent an infinite
590 // loop. When parsing a blockaddress stored in a global variable, there
591 // isn't a trivial way to check if a function will have a body without a
592 // linear search through FunctionsWithBodies, so just check it here.
593 if (!F->isMaterializable())
594 return error("Never resolved function from blockaddress");
596 // Try to materialize F.
597 if (std::error_code EC = materialize(F))
600 assert(BasicBlockFwdRefs.empty() && "Function missing from queue");
603 WillMaterializeAllForwardRefs = false;
604 return std::error_code();
607 void BitcodeReader::freeState() {
609 std::vector<Type*>().swap(TypeList);
612 std::vector<Comdat *>().swap(ComdatList);
614 std::vector<AttributeSet>().swap(MAttributes);
615 std::vector<BasicBlock*>().swap(FunctionBBs);
616 std::vector<Function*>().swap(FunctionsWithBodies);
617 DeferredFunctionInfo.clear();
618 DeferredMetadataInfo.clear();
621 assert(BasicBlockFwdRefs.empty() && "Unresolved blockaddress fwd references");
622 BasicBlockFwdRefQueue.clear();
625 //===----------------------------------------------------------------------===//
626 // Helper functions to implement forward reference resolution, etc.
627 //===----------------------------------------------------------------------===//
629 /// Convert a string from a record into an std::string, return true on failure.
630 template <typename StrTy>
631 static bool convertToString(ArrayRef<uint64_t> Record, unsigned Idx,
633 if (Idx > Record.size())
636 for (unsigned i = Idx, e = Record.size(); i != e; ++i)
637 Result += (char)Record[i];
641 static bool hasImplicitComdat(size_t Val) {
645 case 1: // Old WeakAnyLinkage
646 case 4: // Old LinkOnceAnyLinkage
647 case 10: // Old WeakODRLinkage
648 case 11: // Old LinkOnceODRLinkage
653 static GlobalValue::LinkageTypes getDecodedLinkage(unsigned Val) {
655 default: // Map unknown/new linkages to external
657 return GlobalValue::ExternalLinkage;
659 return GlobalValue::AppendingLinkage;
661 return GlobalValue::InternalLinkage;
663 return GlobalValue::ExternalLinkage; // Obsolete DLLImportLinkage
665 return GlobalValue::ExternalLinkage; // Obsolete DLLExportLinkage
667 return GlobalValue::ExternalWeakLinkage;
669 return GlobalValue::CommonLinkage;
671 return GlobalValue::PrivateLinkage;
673 return GlobalValue::AvailableExternallyLinkage;
675 return GlobalValue::PrivateLinkage; // Obsolete LinkerPrivateLinkage
677 return GlobalValue::PrivateLinkage; // Obsolete LinkerPrivateWeakLinkage
679 return GlobalValue::ExternalLinkage; // Obsolete LinkOnceODRAutoHideLinkage
680 case 1: // Old value with implicit comdat.
682 return GlobalValue::WeakAnyLinkage;
683 case 10: // Old value with implicit comdat.
685 return GlobalValue::WeakODRLinkage;
686 case 4: // Old value with implicit comdat.
688 return GlobalValue::LinkOnceAnyLinkage;
689 case 11: // Old value with implicit comdat.
691 return GlobalValue::LinkOnceODRLinkage;
695 static GlobalValue::VisibilityTypes getDecodedVisibility(unsigned Val) {
697 default: // Map unknown visibilities to default.
698 case 0: return GlobalValue::DefaultVisibility;
699 case 1: return GlobalValue::HiddenVisibility;
700 case 2: return GlobalValue::ProtectedVisibility;
704 static GlobalValue::DLLStorageClassTypes
705 getDecodedDLLStorageClass(unsigned Val) {
707 default: // Map unknown values to default.
708 case 0: return GlobalValue::DefaultStorageClass;
709 case 1: return GlobalValue::DLLImportStorageClass;
710 case 2: return GlobalValue::DLLExportStorageClass;
714 static GlobalVariable::ThreadLocalMode getDecodedThreadLocalMode(unsigned Val) {
716 case 0: return GlobalVariable::NotThreadLocal;
717 default: // Map unknown non-zero value to general dynamic.
718 case 1: return GlobalVariable::GeneralDynamicTLSModel;
719 case 2: return GlobalVariable::LocalDynamicTLSModel;
720 case 3: return GlobalVariable::InitialExecTLSModel;
721 case 4: return GlobalVariable::LocalExecTLSModel;
725 static int getDecodedCastOpcode(unsigned Val) {
728 case bitc::CAST_TRUNC : return Instruction::Trunc;
729 case bitc::CAST_ZEXT : return Instruction::ZExt;
730 case bitc::CAST_SEXT : return Instruction::SExt;
731 case bitc::CAST_FPTOUI : return Instruction::FPToUI;
732 case bitc::CAST_FPTOSI : return Instruction::FPToSI;
733 case bitc::CAST_UITOFP : return Instruction::UIToFP;
734 case bitc::CAST_SITOFP : return Instruction::SIToFP;
735 case bitc::CAST_FPTRUNC : return Instruction::FPTrunc;
736 case bitc::CAST_FPEXT : return Instruction::FPExt;
737 case bitc::CAST_PTRTOINT: return Instruction::PtrToInt;
738 case bitc::CAST_INTTOPTR: return Instruction::IntToPtr;
739 case bitc::CAST_BITCAST : return Instruction::BitCast;
740 case bitc::CAST_ADDRSPACECAST: return Instruction::AddrSpaceCast;
744 static int getDecodedBinaryOpcode(unsigned Val, Type *Ty) {
745 bool IsFP = Ty->isFPOrFPVectorTy();
746 // BinOps are only valid for int/fp or vector of int/fp types
747 if (!IsFP && !Ty->isIntOrIntVectorTy())
753 case bitc::BINOP_ADD:
754 return IsFP ? Instruction::FAdd : Instruction::Add;
755 case bitc::BINOP_SUB:
756 return IsFP ? Instruction::FSub : Instruction::Sub;
757 case bitc::BINOP_MUL:
758 return IsFP ? Instruction::FMul : Instruction::Mul;
759 case bitc::BINOP_UDIV:
760 return IsFP ? -1 : Instruction::UDiv;
761 case bitc::BINOP_SDIV:
762 return IsFP ? Instruction::FDiv : Instruction::SDiv;
763 case bitc::BINOP_UREM:
764 return IsFP ? -1 : Instruction::URem;
765 case bitc::BINOP_SREM:
766 return IsFP ? Instruction::FRem : Instruction::SRem;
767 case bitc::BINOP_SHL:
768 return IsFP ? -1 : Instruction::Shl;
769 case bitc::BINOP_LSHR:
770 return IsFP ? -1 : Instruction::LShr;
771 case bitc::BINOP_ASHR:
772 return IsFP ? -1 : Instruction::AShr;
773 case bitc::BINOP_AND:
774 return IsFP ? -1 : Instruction::And;
776 return IsFP ? -1 : Instruction::Or;
777 case bitc::BINOP_XOR:
778 return IsFP ? -1 : Instruction::Xor;
782 static AtomicRMWInst::BinOp getDecodedRMWOperation(unsigned Val) {
784 default: return AtomicRMWInst::BAD_BINOP;
785 case bitc::RMW_XCHG: return AtomicRMWInst::Xchg;
786 case bitc::RMW_ADD: return AtomicRMWInst::Add;
787 case bitc::RMW_SUB: return AtomicRMWInst::Sub;
788 case bitc::RMW_AND: return AtomicRMWInst::And;
789 case bitc::RMW_NAND: return AtomicRMWInst::Nand;
790 case bitc::RMW_OR: return AtomicRMWInst::Or;
791 case bitc::RMW_XOR: return AtomicRMWInst::Xor;
792 case bitc::RMW_MAX: return AtomicRMWInst::Max;
793 case bitc::RMW_MIN: return AtomicRMWInst::Min;
794 case bitc::RMW_UMAX: return AtomicRMWInst::UMax;
795 case bitc::RMW_UMIN: return AtomicRMWInst::UMin;
799 static AtomicOrdering getDecodedOrdering(unsigned Val) {
801 case bitc::ORDERING_NOTATOMIC: return NotAtomic;
802 case bitc::ORDERING_UNORDERED: return Unordered;
803 case bitc::ORDERING_MONOTONIC: return Monotonic;
804 case bitc::ORDERING_ACQUIRE: return Acquire;
805 case bitc::ORDERING_RELEASE: return Release;
806 case bitc::ORDERING_ACQREL: return AcquireRelease;
807 default: // Map unknown orderings to sequentially-consistent.
808 case bitc::ORDERING_SEQCST: return SequentiallyConsistent;
812 static SynchronizationScope getDecodedSynchScope(unsigned Val) {
814 case bitc::SYNCHSCOPE_SINGLETHREAD: return SingleThread;
815 default: // Map unknown scopes to cross-thread.
816 case bitc::SYNCHSCOPE_CROSSTHREAD: return CrossThread;
820 static Comdat::SelectionKind getDecodedComdatSelectionKind(unsigned Val) {
822 default: // Map unknown selection kinds to any.
823 case bitc::COMDAT_SELECTION_KIND_ANY:
825 case bitc::COMDAT_SELECTION_KIND_EXACT_MATCH:
826 return Comdat::ExactMatch;
827 case bitc::COMDAT_SELECTION_KIND_LARGEST:
828 return Comdat::Largest;
829 case bitc::COMDAT_SELECTION_KIND_NO_DUPLICATES:
830 return Comdat::NoDuplicates;
831 case bitc::COMDAT_SELECTION_KIND_SAME_SIZE:
832 return Comdat::SameSize;
836 static FastMathFlags getDecodedFastMathFlags(unsigned Val) {
838 if (0 != (Val & FastMathFlags::UnsafeAlgebra))
839 FMF.setUnsafeAlgebra();
840 if (0 != (Val & FastMathFlags::NoNaNs))
842 if (0 != (Val & FastMathFlags::NoInfs))
844 if (0 != (Val & FastMathFlags::NoSignedZeros))
845 FMF.setNoSignedZeros();
846 if (0 != (Val & FastMathFlags::AllowReciprocal))
847 FMF.setAllowReciprocal();
851 static void upgradeDLLImportExportLinkage(llvm::GlobalValue *GV, unsigned Val) {
853 case 5: GV->setDLLStorageClass(GlobalValue::DLLImportStorageClass); break;
854 case 6: GV->setDLLStorageClass(GlobalValue::DLLExportStorageClass); break;
860 /// \brief A class for maintaining the slot number definition
861 /// as a placeholder for the actual definition for forward constants defs.
862 class ConstantPlaceHolder : public ConstantExpr {
863 void operator=(const ConstantPlaceHolder &) = delete;
866 // allocate space for exactly one operand
867 void *operator new(size_t s) { return User::operator new(s, 1); }
868 explicit ConstantPlaceHolder(Type *Ty, LLVMContext &Context)
869 : ConstantExpr(Ty, Instruction::UserOp1, &Op<0>(), 1) {
870 Op<0>() = UndefValue::get(Type::getInt32Ty(Context));
873 /// \brief Methods to support type inquiry through isa, cast, and dyn_cast.
874 static bool classof(const Value *V) {
875 return isa<ConstantExpr>(V) &&
876 cast<ConstantExpr>(V)->getOpcode() == Instruction::UserOp1;
879 /// Provide fast operand accessors
880 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
884 // FIXME: can we inherit this from ConstantExpr?
886 struct OperandTraits<ConstantPlaceHolder> :
887 public FixedNumOperandTraits<ConstantPlaceHolder, 1> {
889 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ConstantPlaceHolder, Value)
892 bool BitcodeReaderValueList::assignValue(Value *V, unsigned Idx) {
901 WeakVH &OldV = ValuePtrs[Idx];
907 // Handle constants and non-constants (e.g. instrs) differently for
909 if (Constant *PHC = dyn_cast<Constant>(&*OldV)) {
910 ResolveConstants.push_back(std::make_pair(PHC, Idx));
913 // If there was a forward reference to this value, replace it.
914 Value *PrevVal = OldV;
915 // Check operator constraints. We only put cleanuppads or catchpads in
916 // the forward value map if the value is constrained to match.
917 if (CatchPadInst *CatchPad = dyn_cast<CatchPadInst>(PrevVal)) {
918 if (!isa<CatchPadInst>(V))
920 // Delete the dummy basic block that was created with the sentinel
922 BasicBlock *DummyBlock = CatchPad->getUnwindDest();
923 assert(DummyBlock == CatchPad->getNormalDest());
924 CatchPad->dropAllReferences();
926 } else if (isa<CleanupPadInst>(PrevVal)) {
927 if (!isa<CleanupPadInst>(V))
930 OldV->replaceAllUsesWith(V);
938 Constant *BitcodeReaderValueList::getConstantFwdRef(unsigned Idx,
943 if (Value *V = ValuePtrs[Idx]) {
944 if (Ty != V->getType())
945 report_fatal_error("Type mismatch in constant table!");
946 return cast<Constant>(V);
949 // Create and return a placeholder, which will later be RAUW'd.
950 Constant *C = new ConstantPlaceHolder(Ty, Context);
955 Value *BitcodeReaderValueList::getValueFwdRef(unsigned Idx, Type *Ty,
956 OperatorConstraint OC) {
957 // Bail out for a clearly invalid value. This would make us call resize(0)
964 if (Value *V = ValuePtrs[Idx]) {
965 // If the types don't match, it's invalid.
966 if (Ty && Ty != V->getType())
970 // Use dyn_cast to enforce operator constraints
973 return dyn_cast<CatchPadInst>(V);
975 return dyn_cast<CleanupPadInst>(V);
977 llvm_unreachable("Unexpected operator constraint");
981 // No type specified, must be invalid reference.
982 if (!Ty) return nullptr;
984 // Create and return a placeholder, which will later be RAUW'd.
988 V = new Argument(Ty);
991 BasicBlock *BB = BasicBlock::Create(Context);
992 V = CatchPadInst::Create(BB, BB, {});
996 assert(OC == OC_CleanupPad && "unexpected operator constraint");
997 V = CleanupPadInst::Create(Context, {});
1005 /// Once all constants are read, this method bulk resolves any forward
1006 /// references. The idea behind this is that we sometimes get constants (such
1007 /// as large arrays) which reference *many* forward ref constants. Replacing
1008 /// each of these causes a lot of thrashing when building/reuniquing the
1009 /// constant. Instead of doing this, we look at all the uses and rewrite all
1010 /// the place holders at once for any constant that uses a placeholder.
1011 void BitcodeReaderValueList::resolveConstantForwardRefs() {
1012 // Sort the values by-pointer so that they are efficient to look up with a
1014 std::sort(ResolveConstants.begin(), ResolveConstants.end());
1016 SmallVector<Constant*, 64> NewOps;
1018 while (!ResolveConstants.empty()) {
1019 Value *RealVal = operator[](ResolveConstants.back().second);
1020 Constant *Placeholder = ResolveConstants.back().first;
1021 ResolveConstants.pop_back();
1023 // Loop over all users of the placeholder, updating them to reference the
1024 // new value. If they reference more than one placeholder, update them all
1026 while (!Placeholder->use_empty()) {
1027 auto UI = Placeholder->user_begin();
1030 // If the using object isn't uniqued, just update the operands. This
1031 // handles instructions and initializers for global variables.
1032 if (!isa<Constant>(U) || isa<GlobalValue>(U)) {
1033 UI.getUse().set(RealVal);
1037 // Otherwise, we have a constant that uses the placeholder. Replace that
1038 // constant with a new constant that has *all* placeholder uses updated.
1039 Constant *UserC = cast<Constant>(U);
1040 for (User::op_iterator I = UserC->op_begin(), E = UserC->op_end();
1043 if (!isa<ConstantPlaceHolder>(*I)) {
1044 // Not a placeholder reference.
1046 } else if (*I == Placeholder) {
1047 // Common case is that it just references this one placeholder.
1050 // Otherwise, look up the placeholder in ResolveConstants.
1051 ResolveConstantsTy::iterator It =
1052 std::lower_bound(ResolveConstants.begin(), ResolveConstants.end(),
1053 std::pair<Constant*, unsigned>(cast<Constant>(*I),
1055 assert(It != ResolveConstants.end() && It->first == *I);
1056 NewOp = operator[](It->second);
1059 NewOps.push_back(cast<Constant>(NewOp));
1062 // Make the new constant.
1064 if (ConstantArray *UserCA = dyn_cast<ConstantArray>(UserC)) {
1065 NewC = ConstantArray::get(UserCA->getType(), NewOps);
1066 } else if (ConstantStruct *UserCS = dyn_cast<ConstantStruct>(UserC)) {
1067 NewC = ConstantStruct::get(UserCS->getType(), NewOps);
1068 } else if (isa<ConstantVector>(UserC)) {
1069 NewC = ConstantVector::get(NewOps);
1071 assert(isa<ConstantExpr>(UserC) && "Must be a ConstantExpr.");
1072 NewC = cast<ConstantExpr>(UserC)->getWithOperands(NewOps);
1075 UserC->replaceAllUsesWith(NewC);
1076 UserC->destroyConstant();
1080 // Update all ValueHandles, they should be the only users at this point.
1081 Placeholder->replaceAllUsesWith(RealVal);
1086 void BitcodeReaderMDValueList::assignValue(Metadata *MD, unsigned Idx) {
1087 if (Idx == size()) {
1095 TrackingMDRef &OldMD = MDValuePtrs[Idx];
1101 // If there was a forward reference to this value, replace it.
1102 TempMDTuple PrevMD(cast<MDTuple>(OldMD.get()));
1103 PrevMD->replaceAllUsesWith(MD);
1107 Metadata *BitcodeReaderMDValueList::getValueFwdRef(unsigned Idx) {
1111 if (Metadata *MD = MDValuePtrs[Idx])
1114 // Track forward refs to be resolved later.
1116 MinFwdRef = std::min(MinFwdRef, Idx);
1117 MaxFwdRef = std::max(MaxFwdRef, Idx);
1120 MinFwdRef = MaxFwdRef = Idx;
1124 // Create and return a placeholder, which will later be RAUW'd.
1125 Metadata *MD = MDNode::getTemporary(Context, None).release();
1126 MDValuePtrs[Idx].reset(MD);
1130 void BitcodeReaderMDValueList::tryToResolveCycles() {
1136 // Still forward references... can't resolve cycles.
1139 // Resolve any cycles.
1140 for (unsigned I = MinFwdRef, E = MaxFwdRef + 1; I != E; ++I) {
1141 auto &MD = MDValuePtrs[I];
1142 auto *N = dyn_cast_or_null<MDNode>(MD);
1146 assert(!N->isTemporary() && "Unexpected forward reference");
1150 // Make sure we return early again until there's another forward ref.
1154 Type *BitcodeReader::getTypeByID(unsigned ID) {
1155 // The type table size is always specified correctly.
1156 if (ID >= TypeList.size())
1159 if (Type *Ty = TypeList[ID])
1162 // If we have a forward reference, the only possible case is when it is to a
1163 // named struct. Just create a placeholder for now.
1164 return TypeList[ID] = createIdentifiedStructType(Context);
1167 StructType *BitcodeReader::createIdentifiedStructType(LLVMContext &Context,
1169 auto *Ret = StructType::create(Context, Name);
1170 IdentifiedStructTypes.push_back(Ret);
1174 StructType *BitcodeReader::createIdentifiedStructType(LLVMContext &Context) {
1175 auto *Ret = StructType::create(Context);
1176 IdentifiedStructTypes.push_back(Ret);
1181 //===----------------------------------------------------------------------===//
1182 // Functions for parsing blocks from the bitcode file
1183 //===----------------------------------------------------------------------===//
1186 /// \brief This fills an AttrBuilder object with the LLVM attributes that have
1187 /// been decoded from the given integer. This function must stay in sync with
1188 /// 'encodeLLVMAttributesForBitcode'.
1189 static void decodeLLVMAttributesForBitcode(AttrBuilder &B,
1190 uint64_t EncodedAttrs) {
1191 // FIXME: Remove in 4.0.
1193 // The alignment is stored as a 16-bit raw value from bits 31--16. We shift
1194 // the bits above 31 down by 11 bits.
1195 unsigned Alignment = (EncodedAttrs & (0xffffULL << 16)) >> 16;
1196 assert((!Alignment || isPowerOf2_32(Alignment)) &&
1197 "Alignment must be a power of two.");
1200 B.addAlignmentAttr(Alignment);
1201 B.addRawValue(((EncodedAttrs & (0xfffffULL << 32)) >> 11) |
1202 (EncodedAttrs & 0xffff));
1205 std::error_code BitcodeReader::parseAttributeBlock() {
1206 if (Stream.EnterSubBlock(bitc::PARAMATTR_BLOCK_ID))
1207 return error("Invalid record");
1209 if (!MAttributes.empty())
1210 return error("Invalid multiple blocks");
1212 SmallVector<uint64_t, 64> Record;
1214 SmallVector<AttributeSet, 8> Attrs;
1216 // Read all the records.
1218 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1220 switch (Entry.Kind) {
1221 case BitstreamEntry::SubBlock: // Handled for us already.
1222 case BitstreamEntry::Error:
1223 return error("Malformed block");
1224 case BitstreamEntry::EndBlock:
1225 return std::error_code();
1226 case BitstreamEntry::Record:
1227 // The interesting case.
1233 switch (Stream.readRecord(Entry.ID, Record)) {
1234 default: // Default behavior: ignore.
1236 case bitc::PARAMATTR_CODE_ENTRY_OLD: { // ENTRY: [paramidx0, attr0, ...]
1237 // FIXME: Remove in 4.0.
1238 if (Record.size() & 1)
1239 return error("Invalid record");
1241 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
1243 decodeLLVMAttributesForBitcode(B, Record[i+1]);
1244 Attrs.push_back(AttributeSet::get(Context, Record[i], B));
1247 MAttributes.push_back(AttributeSet::get(Context, Attrs));
1251 case bitc::PARAMATTR_CODE_ENTRY: { // ENTRY: [attrgrp0, attrgrp1, ...]
1252 for (unsigned i = 0, e = Record.size(); i != e; ++i)
1253 Attrs.push_back(MAttributeGroups[Record[i]]);
1255 MAttributes.push_back(AttributeSet::get(Context, Attrs));
1263 // Returns Attribute::None on unrecognized codes.
1264 static Attribute::AttrKind getAttrFromCode(uint64_t Code) {
1267 return Attribute::None;
1268 case bitc::ATTR_KIND_ALIGNMENT:
1269 return Attribute::Alignment;
1270 case bitc::ATTR_KIND_ALWAYS_INLINE:
1271 return Attribute::AlwaysInline;
1272 case bitc::ATTR_KIND_ARGMEMONLY:
1273 return Attribute::ArgMemOnly;
1274 case bitc::ATTR_KIND_BUILTIN:
1275 return Attribute::Builtin;
1276 case bitc::ATTR_KIND_BY_VAL:
1277 return Attribute::ByVal;
1278 case bitc::ATTR_KIND_IN_ALLOCA:
1279 return Attribute::InAlloca;
1280 case bitc::ATTR_KIND_COLD:
1281 return Attribute::Cold;
1282 case bitc::ATTR_KIND_CONVERGENT:
1283 return Attribute::Convergent;
1284 case bitc::ATTR_KIND_INLINE_HINT:
1285 return Attribute::InlineHint;
1286 case bitc::ATTR_KIND_IN_REG:
1287 return Attribute::InReg;
1288 case bitc::ATTR_KIND_JUMP_TABLE:
1289 return Attribute::JumpTable;
1290 case bitc::ATTR_KIND_MIN_SIZE:
1291 return Attribute::MinSize;
1292 case bitc::ATTR_KIND_NAKED:
1293 return Attribute::Naked;
1294 case bitc::ATTR_KIND_NEST:
1295 return Attribute::Nest;
1296 case bitc::ATTR_KIND_NO_ALIAS:
1297 return Attribute::NoAlias;
1298 case bitc::ATTR_KIND_NO_BUILTIN:
1299 return Attribute::NoBuiltin;
1300 case bitc::ATTR_KIND_NO_CAPTURE:
1301 return Attribute::NoCapture;
1302 case bitc::ATTR_KIND_NO_DUPLICATE:
1303 return Attribute::NoDuplicate;
1304 case bitc::ATTR_KIND_NO_IMPLICIT_FLOAT:
1305 return Attribute::NoImplicitFloat;
1306 case bitc::ATTR_KIND_NO_INLINE:
1307 return Attribute::NoInline;
1308 case bitc::ATTR_KIND_NON_LAZY_BIND:
1309 return Attribute::NonLazyBind;
1310 case bitc::ATTR_KIND_NON_NULL:
1311 return Attribute::NonNull;
1312 case bitc::ATTR_KIND_DEREFERENCEABLE:
1313 return Attribute::Dereferenceable;
1314 case bitc::ATTR_KIND_DEREFERENCEABLE_OR_NULL:
1315 return Attribute::DereferenceableOrNull;
1316 case bitc::ATTR_KIND_NO_RED_ZONE:
1317 return Attribute::NoRedZone;
1318 case bitc::ATTR_KIND_NO_RETURN:
1319 return Attribute::NoReturn;
1320 case bitc::ATTR_KIND_NO_UNWIND:
1321 return Attribute::NoUnwind;
1322 case bitc::ATTR_KIND_OPTIMIZE_FOR_SIZE:
1323 return Attribute::OptimizeForSize;
1324 case bitc::ATTR_KIND_OPTIMIZE_NONE:
1325 return Attribute::OptimizeNone;
1326 case bitc::ATTR_KIND_READ_NONE:
1327 return Attribute::ReadNone;
1328 case bitc::ATTR_KIND_READ_ONLY:
1329 return Attribute::ReadOnly;
1330 case bitc::ATTR_KIND_RETURNED:
1331 return Attribute::Returned;
1332 case bitc::ATTR_KIND_RETURNS_TWICE:
1333 return Attribute::ReturnsTwice;
1334 case bitc::ATTR_KIND_S_EXT:
1335 return Attribute::SExt;
1336 case bitc::ATTR_KIND_STACK_ALIGNMENT:
1337 return Attribute::StackAlignment;
1338 case bitc::ATTR_KIND_STACK_PROTECT:
1339 return Attribute::StackProtect;
1340 case bitc::ATTR_KIND_STACK_PROTECT_REQ:
1341 return Attribute::StackProtectReq;
1342 case bitc::ATTR_KIND_STACK_PROTECT_STRONG:
1343 return Attribute::StackProtectStrong;
1344 case bitc::ATTR_KIND_SAFESTACK:
1345 return Attribute::SafeStack;
1346 case bitc::ATTR_KIND_STRUCT_RET:
1347 return Attribute::StructRet;
1348 case bitc::ATTR_KIND_SANITIZE_ADDRESS:
1349 return Attribute::SanitizeAddress;
1350 case bitc::ATTR_KIND_SANITIZE_THREAD:
1351 return Attribute::SanitizeThread;
1352 case bitc::ATTR_KIND_SANITIZE_MEMORY:
1353 return Attribute::SanitizeMemory;
1354 case bitc::ATTR_KIND_UW_TABLE:
1355 return Attribute::UWTable;
1356 case bitc::ATTR_KIND_Z_EXT:
1357 return Attribute::ZExt;
1361 std::error_code BitcodeReader::parseAlignmentValue(uint64_t Exponent,
1362 unsigned &Alignment) {
1363 // Note: Alignment in bitcode files is incremented by 1, so that zero
1364 // can be used for default alignment.
1365 if (Exponent > Value::MaxAlignmentExponent + 1)
1366 return error("Invalid alignment value");
1367 Alignment = (1 << static_cast<unsigned>(Exponent)) >> 1;
1368 return std::error_code();
1371 std::error_code BitcodeReader::parseAttrKind(uint64_t Code,
1372 Attribute::AttrKind *Kind) {
1373 *Kind = getAttrFromCode(Code);
1374 if (*Kind == Attribute::None)
1375 return error(BitcodeError::CorruptedBitcode,
1376 "Unknown attribute kind (" + Twine(Code) + ")");
1377 return std::error_code();
1380 std::error_code BitcodeReader::parseAttributeGroupBlock() {
1381 if (Stream.EnterSubBlock(bitc::PARAMATTR_GROUP_BLOCK_ID))
1382 return error("Invalid record");
1384 if (!MAttributeGroups.empty())
1385 return error("Invalid multiple blocks");
1387 SmallVector<uint64_t, 64> Record;
1389 // Read all the records.
1391 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1393 switch (Entry.Kind) {
1394 case BitstreamEntry::SubBlock: // Handled for us already.
1395 case BitstreamEntry::Error:
1396 return error("Malformed block");
1397 case BitstreamEntry::EndBlock:
1398 return std::error_code();
1399 case BitstreamEntry::Record:
1400 // The interesting case.
1406 switch (Stream.readRecord(Entry.ID, Record)) {
1407 default: // Default behavior: ignore.
1409 case bitc::PARAMATTR_GRP_CODE_ENTRY: { // ENTRY: [grpid, idx, a0, a1, ...]
1410 if (Record.size() < 3)
1411 return error("Invalid record");
1413 uint64_t GrpID = Record[0];
1414 uint64_t Idx = Record[1]; // Index of the object this attribute refers to.
1417 for (unsigned i = 2, e = Record.size(); i != e; ++i) {
1418 if (Record[i] == 0) { // Enum attribute
1419 Attribute::AttrKind Kind;
1420 if (std::error_code EC = parseAttrKind(Record[++i], &Kind))
1423 B.addAttribute(Kind);
1424 } else if (Record[i] == 1) { // Integer attribute
1425 Attribute::AttrKind Kind;
1426 if (std::error_code EC = parseAttrKind(Record[++i], &Kind))
1428 if (Kind == Attribute::Alignment)
1429 B.addAlignmentAttr(Record[++i]);
1430 else if (Kind == Attribute::StackAlignment)
1431 B.addStackAlignmentAttr(Record[++i]);
1432 else if (Kind == Attribute::Dereferenceable)
1433 B.addDereferenceableAttr(Record[++i]);
1434 else if (Kind == Attribute::DereferenceableOrNull)
1435 B.addDereferenceableOrNullAttr(Record[++i]);
1436 } else { // String attribute
1437 assert((Record[i] == 3 || Record[i] == 4) &&
1438 "Invalid attribute group entry");
1439 bool HasValue = (Record[i++] == 4);
1440 SmallString<64> KindStr;
1441 SmallString<64> ValStr;
1443 while (Record[i] != 0 && i != e)
1444 KindStr += Record[i++];
1445 assert(Record[i] == 0 && "Kind string not null terminated");
1448 // Has a value associated with it.
1449 ++i; // Skip the '0' that terminates the "kind" string.
1450 while (Record[i] != 0 && i != e)
1451 ValStr += Record[i++];
1452 assert(Record[i] == 0 && "Value string not null terminated");
1455 B.addAttribute(KindStr.str(), ValStr.str());
1459 MAttributeGroups[GrpID] = AttributeSet::get(Context, Idx, B);
1466 std::error_code BitcodeReader::parseTypeTable() {
1467 if (Stream.EnterSubBlock(bitc::TYPE_BLOCK_ID_NEW))
1468 return error("Invalid record");
1470 return parseTypeTableBody();
1473 std::error_code BitcodeReader::parseTypeTableBody() {
1474 if (!TypeList.empty())
1475 return error("Invalid multiple blocks");
1477 SmallVector<uint64_t, 64> Record;
1478 unsigned NumRecords = 0;
1480 SmallString<64> TypeName;
1482 // Read all the records for this type table.
1484 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1486 switch (Entry.Kind) {
1487 case BitstreamEntry::SubBlock: // Handled for us already.
1488 case BitstreamEntry::Error:
1489 return error("Malformed block");
1490 case BitstreamEntry::EndBlock:
1491 if (NumRecords != TypeList.size())
1492 return error("Malformed block");
1493 return std::error_code();
1494 case BitstreamEntry::Record:
1495 // The interesting case.
1501 Type *ResultTy = nullptr;
1502 switch (Stream.readRecord(Entry.ID, Record)) {
1504 return error("Invalid value");
1505 case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries]
1506 // TYPE_CODE_NUMENTRY contains a count of the number of types in the
1507 // type list. This allows us to reserve space.
1508 if (Record.size() < 1)
1509 return error("Invalid record");
1510 TypeList.resize(Record[0]);
1512 case bitc::TYPE_CODE_VOID: // VOID
1513 ResultTy = Type::getVoidTy(Context);
1515 case bitc::TYPE_CODE_HALF: // HALF
1516 ResultTy = Type::getHalfTy(Context);
1518 case bitc::TYPE_CODE_FLOAT: // FLOAT
1519 ResultTy = Type::getFloatTy(Context);
1521 case bitc::TYPE_CODE_DOUBLE: // DOUBLE
1522 ResultTy = Type::getDoubleTy(Context);
1524 case bitc::TYPE_CODE_X86_FP80: // X86_FP80
1525 ResultTy = Type::getX86_FP80Ty(Context);
1527 case bitc::TYPE_CODE_FP128: // FP128
1528 ResultTy = Type::getFP128Ty(Context);
1530 case bitc::TYPE_CODE_PPC_FP128: // PPC_FP128
1531 ResultTy = Type::getPPC_FP128Ty(Context);
1533 case bitc::TYPE_CODE_LABEL: // LABEL
1534 ResultTy = Type::getLabelTy(Context);
1536 case bitc::TYPE_CODE_METADATA: // METADATA
1537 ResultTy = Type::getMetadataTy(Context);
1539 case bitc::TYPE_CODE_X86_MMX: // X86_MMX
1540 ResultTy = Type::getX86_MMXTy(Context);
1542 case bitc::TYPE_CODE_TOKEN: // TOKEN
1543 ResultTy = Type::getTokenTy(Context);
1545 case bitc::TYPE_CODE_INTEGER: { // INTEGER: [width]
1546 if (Record.size() < 1)
1547 return error("Invalid record");
1549 uint64_t NumBits = Record[0];
1550 if (NumBits < IntegerType::MIN_INT_BITS ||
1551 NumBits > IntegerType::MAX_INT_BITS)
1552 return error("Bitwidth for integer type out of range");
1553 ResultTy = IntegerType::get(Context, NumBits);
1556 case bitc::TYPE_CODE_POINTER: { // POINTER: [pointee type] or
1557 // [pointee type, address space]
1558 if (Record.size() < 1)
1559 return error("Invalid record");
1560 unsigned AddressSpace = 0;
1561 if (Record.size() == 2)
1562 AddressSpace = Record[1];
1563 ResultTy = getTypeByID(Record[0]);
1565 !PointerType::isValidElementType(ResultTy))
1566 return error("Invalid type");
1567 ResultTy = PointerType::get(ResultTy, AddressSpace);
1570 case bitc::TYPE_CODE_FUNCTION_OLD: {
1571 // FIXME: attrid is dead, remove it in LLVM 4.0
1572 // FUNCTION: [vararg, attrid, retty, paramty x N]
1573 if (Record.size() < 3)
1574 return error("Invalid record");
1575 SmallVector<Type*, 8> ArgTys;
1576 for (unsigned i = 3, e = Record.size(); i != e; ++i) {
1577 if (Type *T = getTypeByID(Record[i]))
1578 ArgTys.push_back(T);
1583 ResultTy = getTypeByID(Record[2]);
1584 if (!ResultTy || ArgTys.size() < Record.size()-3)
1585 return error("Invalid type");
1587 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
1590 case bitc::TYPE_CODE_FUNCTION: {
1591 // FUNCTION: [vararg, retty, paramty x N]
1592 if (Record.size() < 2)
1593 return error("Invalid record");
1594 SmallVector<Type*, 8> ArgTys;
1595 for (unsigned i = 2, e = Record.size(); i != e; ++i) {
1596 if (Type *T = getTypeByID(Record[i])) {
1597 if (!FunctionType::isValidArgumentType(T))
1598 return error("Invalid function argument type");
1599 ArgTys.push_back(T);
1605 ResultTy = getTypeByID(Record[1]);
1606 if (!ResultTy || ArgTys.size() < Record.size()-2)
1607 return error("Invalid type");
1609 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
1612 case bitc::TYPE_CODE_STRUCT_ANON: { // STRUCT: [ispacked, eltty x N]
1613 if (Record.size() < 1)
1614 return error("Invalid record");
1615 SmallVector<Type*, 8> EltTys;
1616 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
1617 if (Type *T = getTypeByID(Record[i]))
1618 EltTys.push_back(T);
1622 if (EltTys.size() != Record.size()-1)
1623 return error("Invalid type");
1624 ResultTy = StructType::get(Context, EltTys, Record[0]);
1627 case bitc::TYPE_CODE_STRUCT_NAME: // STRUCT_NAME: [strchr x N]
1628 if (convertToString(Record, 0, TypeName))
1629 return error("Invalid record");
1632 case bitc::TYPE_CODE_STRUCT_NAMED: { // STRUCT: [ispacked, eltty x N]
1633 if (Record.size() < 1)
1634 return error("Invalid record");
1636 if (NumRecords >= TypeList.size())
1637 return error("Invalid TYPE table");
1639 // Check to see if this was forward referenced, if so fill in the temp.
1640 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
1642 Res->setName(TypeName);
1643 TypeList[NumRecords] = nullptr;
1644 } else // Otherwise, create a new struct.
1645 Res = createIdentifiedStructType(Context, TypeName);
1648 SmallVector<Type*, 8> EltTys;
1649 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
1650 if (Type *T = getTypeByID(Record[i]))
1651 EltTys.push_back(T);
1655 if (EltTys.size() != Record.size()-1)
1656 return error("Invalid record");
1657 Res->setBody(EltTys, Record[0]);
1661 case bitc::TYPE_CODE_OPAQUE: { // OPAQUE: []
1662 if (Record.size() != 1)
1663 return error("Invalid record");
1665 if (NumRecords >= TypeList.size())
1666 return error("Invalid TYPE table");
1668 // Check to see if this was forward referenced, if so fill in the temp.
1669 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
1671 Res->setName(TypeName);
1672 TypeList[NumRecords] = nullptr;
1673 } else // Otherwise, create a new struct with no body.
1674 Res = createIdentifiedStructType(Context, TypeName);
1679 case bitc::TYPE_CODE_ARRAY: // ARRAY: [numelts, eltty]
1680 if (Record.size() < 2)
1681 return error("Invalid record");
1682 ResultTy = getTypeByID(Record[1]);
1683 if (!ResultTy || !ArrayType::isValidElementType(ResultTy))
1684 return error("Invalid type");
1685 ResultTy = ArrayType::get(ResultTy, Record[0]);
1687 case bitc::TYPE_CODE_VECTOR: // VECTOR: [numelts, eltty]
1688 if (Record.size() < 2)
1689 return error("Invalid record");
1691 return error("Invalid vector length");
1692 ResultTy = getTypeByID(Record[1]);
1693 if (!ResultTy || !StructType::isValidElementType(ResultTy))
1694 return error("Invalid type");
1695 ResultTy = VectorType::get(ResultTy, Record[0]);
1699 if (NumRecords >= TypeList.size())
1700 return error("Invalid TYPE table");
1701 if (TypeList[NumRecords])
1703 "Invalid TYPE table: Only named structs can be forward referenced");
1704 assert(ResultTy && "Didn't read a type?");
1705 TypeList[NumRecords++] = ResultTy;
1709 std::error_code BitcodeReader::parseOperandBundleTags() {
1710 if (Stream.EnterSubBlock(bitc::OPERAND_BUNDLE_TAGS_BLOCK_ID))
1711 return error("Invalid record");
1713 if (!BundleTags.empty())
1714 return error("Invalid multiple blocks");
1716 SmallVector<uint64_t, 64> Record;
1719 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1721 switch (Entry.Kind) {
1722 case BitstreamEntry::SubBlock: // Handled for us already.
1723 case BitstreamEntry::Error:
1724 return error("Malformed block");
1725 case BitstreamEntry::EndBlock:
1726 return std::error_code();
1727 case BitstreamEntry::Record:
1728 // The interesting case.
1732 // Tags are implicitly mapped to integers by their order.
1734 if (Stream.readRecord(Entry.ID, Record) != bitc::OPERAND_BUNDLE_TAG)
1735 return error("Invalid record");
1737 // OPERAND_BUNDLE_TAG: [strchr x N]
1738 BundleTags.emplace_back();
1739 if (convertToString(Record, 0, BundleTags.back()))
1740 return error("Invalid record");
1745 /// Associate a value with its name from the given index in the provided record.
1746 ErrorOr<Value *> BitcodeReader::recordValue(SmallVectorImpl<uint64_t> &Record,
1747 unsigned NameIndex, Triple &TT) {
1748 SmallString<128> ValueName;
1749 if (convertToString(Record, NameIndex, ValueName))
1750 return error("Invalid record");
1751 unsigned ValueID = Record[0];
1752 if (ValueID >= ValueList.size() || !ValueList[ValueID])
1753 return error("Invalid record");
1754 Value *V = ValueList[ValueID];
1756 StringRef NameStr(ValueName.data(), ValueName.size());
1757 if (NameStr.find_first_of(0) != StringRef::npos)
1758 return error("Invalid value name");
1759 V->setName(NameStr);
1760 auto *GO = dyn_cast<GlobalObject>(V);
1762 if (GO->getComdat() == reinterpret_cast<Comdat *>(1)) {
1763 if (TT.isOSBinFormatMachO())
1764 GO->setComdat(nullptr);
1766 GO->setComdat(TheModule->getOrInsertComdat(V->getName()));
1772 /// Parse the value symbol table at either the current parsing location or
1773 /// at the given bit offset if provided.
1774 std::error_code BitcodeReader::parseValueSymbolTable(uint64_t Offset) {
1775 uint64_t CurrentBit;
1776 // Pass in the Offset to distinguish between calling for the module-level
1777 // VST (where we want to jump to the VST offset) and the function-level
1778 // VST (where we don't).
1780 // Save the current parsing location so we can jump back at the end
1782 CurrentBit = Stream.GetCurrentBitNo();
1783 Stream.JumpToBit(Offset * 32);
1785 // Do some checking if we are in debug mode.
1786 BitstreamEntry Entry = Stream.advance();
1787 assert(Entry.Kind == BitstreamEntry::SubBlock);
1788 assert(Entry.ID == bitc::VALUE_SYMTAB_BLOCK_ID);
1790 // In NDEBUG mode ignore the output so we don't get an unused variable
1796 // Compute the delta between the bitcode indices in the VST (the word offset
1797 // to the word-aligned ENTER_SUBBLOCK for the function block, and that
1798 // expected by the lazy reader. The reader's EnterSubBlock expects to have
1799 // already read the ENTER_SUBBLOCK code (size getAbbrevIDWidth) and BlockID
1800 // (size BlockIDWidth). Note that we access the stream's AbbrevID width here
1801 // just before entering the VST subblock because: 1) the EnterSubBlock
1802 // changes the AbbrevID width; 2) the VST block is nested within the same
1803 // outer MODULE_BLOCK as the FUNCTION_BLOCKs and therefore have the same
1804 // AbbrevID width before calling EnterSubBlock; and 3) when we want to
1805 // jump to the FUNCTION_BLOCK using this offset later, we don't want
1806 // to rely on the stream's AbbrevID width being that of the MODULE_BLOCK.
1807 unsigned FuncBitcodeOffsetDelta =
1808 Stream.getAbbrevIDWidth() + bitc::BlockIDWidth;
1810 if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
1811 return error("Invalid record");
1813 SmallVector<uint64_t, 64> Record;
1815 Triple TT(TheModule->getTargetTriple());
1817 // Read all the records for this value table.
1818 SmallString<128> ValueName;
1820 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1822 switch (Entry.Kind) {
1823 case BitstreamEntry::SubBlock: // Handled for us already.
1824 case BitstreamEntry::Error:
1825 return error("Malformed block");
1826 case BitstreamEntry::EndBlock:
1828 Stream.JumpToBit(CurrentBit);
1829 return std::error_code();
1830 case BitstreamEntry::Record:
1831 // The interesting case.
1837 switch (Stream.readRecord(Entry.ID, Record)) {
1838 default: // Default behavior: unknown type.
1840 case bitc::VST_CODE_ENTRY: { // VST_ENTRY: [valueid, namechar x N]
1841 ErrorOr<Value *> ValOrErr = recordValue(Record, 1, TT);
1842 if (std::error_code EC = ValOrErr.getError())
1847 case bitc::VST_CODE_FNENTRY: {
1848 // VST_FNENTRY: [valueid, offset, namechar x N]
1849 ErrorOr<Value *> ValOrErr = recordValue(Record, 2, TT);
1850 if (std::error_code EC = ValOrErr.getError())
1852 Value *V = ValOrErr.get();
1854 auto *GO = dyn_cast<GlobalObject>(V);
1856 // If this is an alias, need to get the actual Function object
1857 // it aliases, in order to set up the DeferredFunctionInfo entry below.
1858 auto *GA = dyn_cast<GlobalAlias>(V);
1860 GO = GA->getBaseObject();
1864 uint64_t FuncWordOffset = Record[1];
1865 Function *F = dyn_cast<Function>(GO);
1867 uint64_t FuncBitOffset = FuncWordOffset * 32;
1868 DeferredFunctionInfo[F] = FuncBitOffset + FuncBitcodeOffsetDelta;
1869 // Set the LastFunctionBlockBit to point to the last function block.
1870 // Later when parsing is resumed after function materialization,
1871 // we can simply skip that last function block.
1872 if (FuncBitOffset > LastFunctionBlockBit)
1873 LastFunctionBlockBit = FuncBitOffset;
1876 case bitc::VST_CODE_BBENTRY: {
1877 if (convertToString(Record, 1, ValueName))
1878 return error("Invalid record");
1879 BasicBlock *BB = getBasicBlock(Record[0]);
1881 return error("Invalid record");
1883 BB->setName(StringRef(ValueName.data(), ValueName.size()));
1891 static int64_t unrotateSign(uint64_t U) { return U & 1 ? ~(U >> 1) : U >> 1; }
1893 std::error_code BitcodeReader::parseMetadata() {
1894 IsMetadataMaterialized = true;
1895 unsigned NextMDValueNo = MDValueList.size();
1897 if (Stream.EnterSubBlock(bitc::METADATA_BLOCK_ID))
1898 return error("Invalid record");
1900 SmallVector<uint64_t, 64> Record;
1903 [&](unsigned ID) -> Metadata *{ return MDValueList.getValueFwdRef(ID); };
1904 auto getMDOrNull = [&](unsigned ID) -> Metadata *{
1906 return getMD(ID - 1);
1909 auto getMDString = [&](unsigned ID) -> MDString *{
1910 // This requires that the ID is not really a forward reference. In
1911 // particular, the MDString must already have been resolved.
1912 return cast_or_null<MDString>(getMDOrNull(ID));
1915 #define GET_OR_DISTINCT(CLASS, DISTINCT, ARGS) \
1916 (DISTINCT ? CLASS::getDistinct ARGS : CLASS::get ARGS)
1918 // Read all the records.
1920 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1922 switch (Entry.Kind) {
1923 case BitstreamEntry::SubBlock: // Handled for us already.
1924 case BitstreamEntry::Error:
1925 return error("Malformed block");
1926 case BitstreamEntry::EndBlock:
1927 MDValueList.tryToResolveCycles();
1928 return std::error_code();
1929 case BitstreamEntry::Record:
1930 // The interesting case.
1936 unsigned Code = Stream.readRecord(Entry.ID, Record);
1937 bool IsDistinct = false;
1939 default: // Default behavior: ignore.
1941 case bitc::METADATA_NAME: {
1942 // Read name of the named metadata.
1943 SmallString<8> Name(Record.begin(), Record.end());
1945 Code = Stream.ReadCode();
1947 unsigned NextBitCode = Stream.readRecord(Code, Record);
1948 if (NextBitCode != bitc::METADATA_NAMED_NODE)
1949 return error("METADATA_NAME not followed by METADATA_NAMED_NODE");
1951 // Read named metadata elements.
1952 unsigned Size = Record.size();
1953 NamedMDNode *NMD = TheModule->getOrInsertNamedMetadata(Name);
1954 for (unsigned i = 0; i != Size; ++i) {
1955 MDNode *MD = dyn_cast_or_null<MDNode>(MDValueList.getValueFwdRef(Record[i]));
1957 return error("Invalid record");
1958 NMD->addOperand(MD);
1962 case bitc::METADATA_OLD_FN_NODE: {
1963 // FIXME: Remove in 4.0.
1964 // This is a LocalAsMetadata record, the only type of function-local
1966 if (Record.size() % 2 == 1)
1967 return error("Invalid record");
1969 // If this isn't a LocalAsMetadata record, we're dropping it. This used
1970 // to be legal, but there's no upgrade path.
1971 auto dropRecord = [&] {
1972 MDValueList.assignValue(MDNode::get(Context, None), NextMDValueNo++);
1974 if (Record.size() != 2) {
1979 Type *Ty = getTypeByID(Record[0]);
1980 if (Ty->isMetadataTy() || Ty->isVoidTy()) {
1985 MDValueList.assignValue(
1986 LocalAsMetadata::get(ValueList.getValueFwdRef(Record[1], Ty)),
1990 case bitc::METADATA_OLD_NODE: {
1991 // FIXME: Remove in 4.0.
1992 if (Record.size() % 2 == 1)
1993 return error("Invalid record");
1995 unsigned Size = Record.size();
1996 SmallVector<Metadata *, 8> Elts;
1997 for (unsigned i = 0; i != Size; i += 2) {
1998 Type *Ty = getTypeByID(Record[i]);
2000 return error("Invalid record");
2001 if (Ty->isMetadataTy())
2002 Elts.push_back(MDValueList.getValueFwdRef(Record[i+1]));
2003 else if (!Ty->isVoidTy()) {
2005 ValueAsMetadata::get(ValueList.getValueFwdRef(Record[i + 1], Ty));
2006 assert(isa<ConstantAsMetadata>(MD) &&
2007 "Expected non-function-local metadata");
2010 Elts.push_back(nullptr);
2012 MDValueList.assignValue(MDNode::get(Context, Elts), NextMDValueNo++);
2015 case bitc::METADATA_VALUE: {
2016 if (Record.size() != 2)
2017 return error("Invalid record");
2019 Type *Ty = getTypeByID(Record[0]);
2020 if (Ty->isMetadataTy() || Ty->isVoidTy())
2021 return error("Invalid record");
2023 MDValueList.assignValue(
2024 ValueAsMetadata::get(ValueList.getValueFwdRef(Record[1], Ty)),
2028 case bitc::METADATA_DISTINCT_NODE:
2031 case bitc::METADATA_NODE: {
2032 SmallVector<Metadata *, 8> Elts;
2033 Elts.reserve(Record.size());
2034 for (unsigned ID : Record)
2035 Elts.push_back(ID ? MDValueList.getValueFwdRef(ID - 1) : nullptr);
2036 MDValueList.assignValue(IsDistinct ? MDNode::getDistinct(Context, Elts)
2037 : MDNode::get(Context, Elts),
2041 case bitc::METADATA_LOCATION: {
2042 if (Record.size() != 5)
2043 return error("Invalid record");
2045 unsigned Line = Record[1];
2046 unsigned Column = Record[2];
2047 MDNode *Scope = cast<MDNode>(MDValueList.getValueFwdRef(Record[3]));
2048 Metadata *InlinedAt =
2049 Record[4] ? MDValueList.getValueFwdRef(Record[4] - 1) : nullptr;
2050 MDValueList.assignValue(
2051 GET_OR_DISTINCT(DILocation, Record[0],
2052 (Context, Line, Column, Scope, InlinedAt)),
2056 case bitc::METADATA_GENERIC_DEBUG: {
2057 if (Record.size() < 4)
2058 return error("Invalid record");
2060 unsigned Tag = Record[1];
2061 unsigned Version = Record[2];
2063 if (Tag >= 1u << 16 || Version != 0)
2064 return error("Invalid record");
2066 auto *Header = getMDString(Record[3]);
2067 SmallVector<Metadata *, 8> DwarfOps;
2068 for (unsigned I = 4, E = Record.size(); I != E; ++I)
2069 DwarfOps.push_back(Record[I] ? MDValueList.getValueFwdRef(Record[I] - 1)
2071 MDValueList.assignValue(GET_OR_DISTINCT(GenericDINode, Record[0],
2072 (Context, Tag, Header, DwarfOps)),
2076 case bitc::METADATA_SUBRANGE: {
2077 if (Record.size() != 3)
2078 return error("Invalid record");
2080 MDValueList.assignValue(
2081 GET_OR_DISTINCT(DISubrange, Record[0],
2082 (Context, Record[1], unrotateSign(Record[2]))),
2086 case bitc::METADATA_ENUMERATOR: {
2087 if (Record.size() != 3)
2088 return error("Invalid record");
2090 MDValueList.assignValue(GET_OR_DISTINCT(DIEnumerator, Record[0],
2091 (Context, unrotateSign(Record[1]),
2092 getMDString(Record[2]))),
2096 case bitc::METADATA_BASIC_TYPE: {
2097 if (Record.size() != 6)
2098 return error("Invalid record");
2100 MDValueList.assignValue(
2101 GET_OR_DISTINCT(DIBasicType, Record[0],
2102 (Context, Record[1], getMDString(Record[2]),
2103 Record[3], Record[4], Record[5])),
2107 case bitc::METADATA_DERIVED_TYPE: {
2108 if (Record.size() != 12)
2109 return error("Invalid record");
2111 MDValueList.assignValue(
2112 GET_OR_DISTINCT(DIDerivedType, Record[0],
2113 (Context, Record[1], getMDString(Record[2]),
2114 getMDOrNull(Record[3]), Record[4],
2115 getMDOrNull(Record[5]), getMDOrNull(Record[6]),
2116 Record[7], Record[8], Record[9], Record[10],
2117 getMDOrNull(Record[11]))),
2121 case bitc::METADATA_COMPOSITE_TYPE: {
2122 if (Record.size() != 16)
2123 return error("Invalid record");
2125 MDValueList.assignValue(
2126 GET_OR_DISTINCT(DICompositeType, Record[0],
2127 (Context, Record[1], getMDString(Record[2]),
2128 getMDOrNull(Record[3]), Record[4],
2129 getMDOrNull(Record[5]), getMDOrNull(Record[6]),
2130 Record[7], Record[8], Record[9], Record[10],
2131 getMDOrNull(Record[11]), Record[12],
2132 getMDOrNull(Record[13]), getMDOrNull(Record[14]),
2133 getMDString(Record[15]))),
2137 case bitc::METADATA_SUBROUTINE_TYPE: {
2138 if (Record.size() != 3)
2139 return error("Invalid record");
2141 MDValueList.assignValue(
2142 GET_OR_DISTINCT(DISubroutineType, Record[0],
2143 (Context, Record[1], getMDOrNull(Record[2]))),
2148 case bitc::METADATA_MODULE: {
2149 if (Record.size() != 6)
2150 return error("Invalid record");
2152 MDValueList.assignValue(
2153 GET_OR_DISTINCT(DIModule, Record[0],
2154 (Context, getMDOrNull(Record[1]),
2155 getMDString(Record[2]), getMDString(Record[3]),
2156 getMDString(Record[4]), getMDString(Record[5]))),
2161 case bitc::METADATA_FILE: {
2162 if (Record.size() != 3)
2163 return error("Invalid record");
2165 MDValueList.assignValue(
2166 GET_OR_DISTINCT(DIFile, Record[0], (Context, getMDString(Record[1]),
2167 getMDString(Record[2]))),
2171 case bitc::METADATA_COMPILE_UNIT: {
2172 if (Record.size() < 14 || Record.size() > 15)
2173 return error("Invalid record");
2175 // Ignore Record[1], which indicates whether this compile unit is
2176 // distinct. It's always distinct.
2177 MDValueList.assignValue(
2178 DICompileUnit::getDistinct(
2179 Context, Record[1], getMDOrNull(Record[2]),
2180 getMDString(Record[3]), Record[4], getMDString(Record[5]),
2181 Record[6], getMDString(Record[7]), Record[8],
2182 getMDOrNull(Record[9]), getMDOrNull(Record[10]),
2183 getMDOrNull(Record[11]), getMDOrNull(Record[12]),
2184 getMDOrNull(Record[13]), Record.size() == 14 ? 0 : Record[14]),
2188 case bitc::METADATA_SUBPROGRAM: {
2189 if (Record.size() != 18 && Record.size() != 19)
2190 return error("Invalid record");
2192 bool HasFn = Record.size() == 19;
2193 DISubprogram *SP = GET_OR_DISTINCT(
2195 Record[0] || Record[8], // All definitions should be distinct.
2196 (Context, getMDOrNull(Record[1]), getMDString(Record[2]),
2197 getMDString(Record[3]), getMDOrNull(Record[4]), Record[5],
2198 getMDOrNull(Record[6]), Record[7], Record[8], Record[9],
2199 getMDOrNull(Record[10]), Record[11], Record[12], Record[13],
2200 Record[14], getMDOrNull(Record[15 + HasFn]),
2201 getMDOrNull(Record[16 + HasFn]), getMDOrNull(Record[17 + HasFn])));
2202 MDValueList.assignValue(SP, NextMDValueNo++);
2204 // Upgrade sp->function mapping to function->sp mapping.
2205 if (HasFn && Record[15]) {
2206 if (auto *CMD = dyn_cast<ConstantAsMetadata>(getMDOrNull(Record[15])))
2207 if (auto *F = dyn_cast<Function>(CMD->getValue())) {
2208 if (F->isMaterializable())
2209 // Defer until materialized; unmaterialized functions may not have
2211 FunctionsWithSPs[F] = SP;
2212 else if (!F->empty())
2213 F->setSubprogram(SP);
2218 case bitc::METADATA_LEXICAL_BLOCK: {
2219 if (Record.size() != 5)
2220 return error("Invalid record");
2222 MDValueList.assignValue(
2223 GET_OR_DISTINCT(DILexicalBlock, Record[0],
2224 (Context, getMDOrNull(Record[1]),
2225 getMDOrNull(Record[2]), Record[3], Record[4])),
2229 case bitc::METADATA_LEXICAL_BLOCK_FILE: {
2230 if (Record.size() != 4)
2231 return error("Invalid record");
2233 MDValueList.assignValue(
2234 GET_OR_DISTINCT(DILexicalBlockFile, Record[0],
2235 (Context, getMDOrNull(Record[1]),
2236 getMDOrNull(Record[2]), Record[3])),
2240 case bitc::METADATA_NAMESPACE: {
2241 if (Record.size() != 5)
2242 return error("Invalid record");
2244 MDValueList.assignValue(
2245 GET_OR_DISTINCT(DINamespace, Record[0],
2246 (Context, getMDOrNull(Record[1]),
2247 getMDOrNull(Record[2]), getMDString(Record[3]),
2252 case bitc::METADATA_TEMPLATE_TYPE: {
2253 if (Record.size() != 3)
2254 return error("Invalid record");
2256 MDValueList.assignValue(GET_OR_DISTINCT(DITemplateTypeParameter,
2258 (Context, getMDString(Record[1]),
2259 getMDOrNull(Record[2]))),
2263 case bitc::METADATA_TEMPLATE_VALUE: {
2264 if (Record.size() != 5)
2265 return error("Invalid record");
2267 MDValueList.assignValue(
2268 GET_OR_DISTINCT(DITemplateValueParameter, Record[0],
2269 (Context, Record[1], getMDString(Record[2]),
2270 getMDOrNull(Record[3]), getMDOrNull(Record[4]))),
2274 case bitc::METADATA_GLOBAL_VAR: {
2275 if (Record.size() != 11)
2276 return error("Invalid record");
2278 MDValueList.assignValue(
2279 GET_OR_DISTINCT(DIGlobalVariable, Record[0],
2280 (Context, getMDOrNull(Record[1]),
2281 getMDString(Record[2]), getMDString(Record[3]),
2282 getMDOrNull(Record[4]), Record[5],
2283 getMDOrNull(Record[6]), Record[7], Record[8],
2284 getMDOrNull(Record[9]), getMDOrNull(Record[10]))),
2288 case bitc::METADATA_LOCAL_VAR: {
2289 // 10th field is for the obseleted 'inlinedAt:' field.
2290 if (Record.size() < 8 || Record.size() > 10)
2291 return error("Invalid record");
2293 // 2nd field used to be an artificial tag, either DW_TAG_auto_variable or
2294 // DW_TAG_arg_variable.
2295 bool HasTag = Record.size() > 8;
2296 MDValueList.assignValue(
2297 GET_OR_DISTINCT(DILocalVariable, Record[0],
2298 (Context, getMDOrNull(Record[1 + HasTag]),
2299 getMDString(Record[2 + HasTag]),
2300 getMDOrNull(Record[3 + HasTag]), Record[4 + HasTag],
2301 getMDOrNull(Record[5 + HasTag]), Record[6 + HasTag],
2302 Record[7 + HasTag])),
2306 case bitc::METADATA_EXPRESSION: {
2307 if (Record.size() < 1)
2308 return error("Invalid record");
2310 MDValueList.assignValue(
2311 GET_OR_DISTINCT(DIExpression, Record[0],
2312 (Context, makeArrayRef(Record).slice(1))),
2316 case bitc::METADATA_OBJC_PROPERTY: {
2317 if (Record.size() != 8)
2318 return error("Invalid record");
2320 MDValueList.assignValue(
2321 GET_OR_DISTINCT(DIObjCProperty, Record[0],
2322 (Context, getMDString(Record[1]),
2323 getMDOrNull(Record[2]), Record[3],
2324 getMDString(Record[4]), getMDString(Record[5]),
2325 Record[6], getMDOrNull(Record[7]))),
2329 case bitc::METADATA_IMPORTED_ENTITY: {
2330 if (Record.size() != 6)
2331 return error("Invalid record");
2333 MDValueList.assignValue(
2334 GET_OR_DISTINCT(DIImportedEntity, Record[0],
2335 (Context, Record[1], getMDOrNull(Record[2]),
2336 getMDOrNull(Record[3]), Record[4],
2337 getMDString(Record[5]))),
2341 case bitc::METADATA_STRING: {
2342 std::string String(Record.begin(), Record.end());
2343 llvm::UpgradeMDStringConstant(String);
2344 Metadata *MD = MDString::get(Context, String);
2345 MDValueList.assignValue(MD, NextMDValueNo++);
2348 case bitc::METADATA_KIND: {
2349 if (Record.size() < 2)
2350 return error("Invalid record");
2352 unsigned Kind = Record[0];
2353 SmallString<8> Name(Record.begin()+1, Record.end());
2355 unsigned NewKind = TheModule->getMDKindID(Name.str());
2356 if (!MDKindMap.insert(std::make_pair(Kind, NewKind)).second)
2357 return error("Conflicting METADATA_KIND records");
2362 #undef GET_OR_DISTINCT
2365 /// Decode a signed value stored with the sign bit in the LSB for dense VBR
2367 uint64_t BitcodeReader::decodeSignRotatedValue(uint64_t V) {
2372 // There is no such thing as -0 with integers. "-0" really means MININT.
2376 /// Resolve all of the initializers for global values and aliases that we can.
2377 std::error_code BitcodeReader::resolveGlobalAndAliasInits() {
2378 std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInitWorklist;
2379 std::vector<std::pair<GlobalAlias*, unsigned> > AliasInitWorklist;
2380 std::vector<std::pair<Function*, unsigned> > FunctionPrefixWorklist;
2381 std::vector<std::pair<Function*, unsigned> > FunctionPrologueWorklist;
2382 std::vector<std::pair<Function*, unsigned> > FunctionPersonalityFnWorklist;
2384 GlobalInitWorklist.swap(GlobalInits);
2385 AliasInitWorklist.swap(AliasInits);
2386 FunctionPrefixWorklist.swap(FunctionPrefixes);
2387 FunctionPrologueWorklist.swap(FunctionPrologues);
2388 FunctionPersonalityFnWorklist.swap(FunctionPersonalityFns);
2390 while (!GlobalInitWorklist.empty()) {
2391 unsigned ValID = GlobalInitWorklist.back().second;
2392 if (ValID >= ValueList.size()) {
2393 // Not ready to resolve this yet, it requires something later in the file.
2394 GlobalInits.push_back(GlobalInitWorklist.back());
2396 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
2397 GlobalInitWorklist.back().first->setInitializer(C);
2399 return error("Expected a constant");
2401 GlobalInitWorklist.pop_back();
2404 while (!AliasInitWorklist.empty()) {
2405 unsigned ValID = AliasInitWorklist.back().second;
2406 if (ValID >= ValueList.size()) {
2407 AliasInits.push_back(AliasInitWorklist.back());
2409 Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]);
2411 return error("Expected a constant");
2412 GlobalAlias *Alias = AliasInitWorklist.back().first;
2413 if (C->getType() != Alias->getType())
2414 return error("Alias and aliasee types don't match");
2415 Alias->setAliasee(C);
2417 AliasInitWorklist.pop_back();
2420 while (!FunctionPrefixWorklist.empty()) {
2421 unsigned ValID = FunctionPrefixWorklist.back().second;
2422 if (ValID >= ValueList.size()) {
2423 FunctionPrefixes.push_back(FunctionPrefixWorklist.back());
2425 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
2426 FunctionPrefixWorklist.back().first->setPrefixData(C);
2428 return error("Expected a constant");
2430 FunctionPrefixWorklist.pop_back();
2433 while (!FunctionPrologueWorklist.empty()) {
2434 unsigned ValID = FunctionPrologueWorklist.back().second;
2435 if (ValID >= ValueList.size()) {
2436 FunctionPrologues.push_back(FunctionPrologueWorklist.back());
2438 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
2439 FunctionPrologueWorklist.back().first->setPrologueData(C);
2441 return error("Expected a constant");
2443 FunctionPrologueWorklist.pop_back();
2446 while (!FunctionPersonalityFnWorklist.empty()) {
2447 unsigned ValID = FunctionPersonalityFnWorklist.back().second;
2448 if (ValID >= ValueList.size()) {
2449 FunctionPersonalityFns.push_back(FunctionPersonalityFnWorklist.back());
2451 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
2452 FunctionPersonalityFnWorklist.back().first->setPersonalityFn(C);
2454 return error("Expected a constant");
2456 FunctionPersonalityFnWorklist.pop_back();
2459 return std::error_code();
2462 static APInt readWideAPInt(ArrayRef<uint64_t> Vals, unsigned TypeBits) {
2463 SmallVector<uint64_t, 8> Words(Vals.size());
2464 std::transform(Vals.begin(), Vals.end(), Words.begin(),
2465 BitcodeReader::decodeSignRotatedValue);
2467 return APInt(TypeBits, Words);
2470 std::error_code BitcodeReader::parseConstants() {
2471 if (Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID))
2472 return error("Invalid record");
2474 SmallVector<uint64_t, 64> Record;
2476 // Read all the records for this value table.
2477 Type *CurTy = Type::getInt32Ty(Context);
2478 unsigned NextCstNo = ValueList.size();
2480 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
2482 switch (Entry.Kind) {
2483 case BitstreamEntry::SubBlock: // Handled for us already.
2484 case BitstreamEntry::Error:
2485 return error("Malformed block");
2486 case BitstreamEntry::EndBlock:
2487 if (NextCstNo != ValueList.size())
2488 return error("Invalid ronstant reference");
2490 // Once all the constants have been read, go through and resolve forward
2492 ValueList.resolveConstantForwardRefs();
2493 return std::error_code();
2494 case BitstreamEntry::Record:
2495 // The interesting case.
2502 unsigned BitCode = Stream.readRecord(Entry.ID, Record);
2504 default: // Default behavior: unknown constant
2505 case bitc::CST_CODE_UNDEF: // UNDEF
2506 V = UndefValue::get(CurTy);
2508 case bitc::CST_CODE_SETTYPE: // SETTYPE: [typeid]
2510 return error("Invalid record");
2511 if (Record[0] >= TypeList.size() || !TypeList[Record[0]])
2512 return error("Invalid record");
2513 CurTy = TypeList[Record[0]];
2514 continue; // Skip the ValueList manipulation.
2515 case bitc::CST_CODE_NULL: // NULL
2516 V = Constant::getNullValue(CurTy);
2518 case bitc::CST_CODE_INTEGER: // INTEGER: [intval]
2519 if (!CurTy->isIntegerTy() || Record.empty())
2520 return error("Invalid record");
2521 V = ConstantInt::get(CurTy, decodeSignRotatedValue(Record[0]));
2523 case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval]
2524 if (!CurTy->isIntegerTy() || Record.empty())
2525 return error("Invalid record");
2528 readWideAPInt(Record, cast<IntegerType>(CurTy)->getBitWidth());
2529 V = ConstantInt::get(Context, VInt);
2533 case bitc::CST_CODE_FLOAT: { // FLOAT: [fpval]
2535 return error("Invalid record");
2536 if (CurTy->isHalfTy())
2537 V = ConstantFP::get(Context, APFloat(APFloat::IEEEhalf,
2538 APInt(16, (uint16_t)Record[0])));
2539 else if (CurTy->isFloatTy())
2540 V = ConstantFP::get(Context, APFloat(APFloat::IEEEsingle,
2541 APInt(32, (uint32_t)Record[0])));
2542 else if (CurTy->isDoubleTy())
2543 V = ConstantFP::get(Context, APFloat(APFloat::IEEEdouble,
2544 APInt(64, Record[0])));
2545 else if (CurTy->isX86_FP80Ty()) {
2546 // Bits are not stored the same way as a normal i80 APInt, compensate.
2547 uint64_t Rearrange[2];
2548 Rearrange[0] = (Record[1] & 0xffffLL) | (Record[0] << 16);
2549 Rearrange[1] = Record[0] >> 48;
2550 V = ConstantFP::get(Context, APFloat(APFloat::x87DoubleExtended,
2551 APInt(80, Rearrange)));
2552 } else if (CurTy->isFP128Ty())
2553 V = ConstantFP::get(Context, APFloat(APFloat::IEEEquad,
2554 APInt(128, Record)));
2555 else if (CurTy->isPPC_FP128Ty())
2556 V = ConstantFP::get(Context, APFloat(APFloat::PPCDoubleDouble,
2557 APInt(128, Record)));
2559 V = UndefValue::get(CurTy);
2563 case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number]
2565 return error("Invalid record");
2567 unsigned Size = Record.size();
2568 SmallVector<Constant*, 16> Elts;
2570 if (StructType *STy = dyn_cast<StructType>(CurTy)) {
2571 for (unsigned i = 0; i != Size; ++i)
2572 Elts.push_back(ValueList.getConstantFwdRef(Record[i],
2573 STy->getElementType(i)));
2574 V = ConstantStruct::get(STy, Elts);
2575 } else if (ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) {
2576 Type *EltTy = ATy->getElementType();
2577 for (unsigned i = 0; i != Size; ++i)
2578 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
2579 V = ConstantArray::get(ATy, Elts);
2580 } else if (VectorType *VTy = dyn_cast<VectorType>(CurTy)) {
2581 Type *EltTy = VTy->getElementType();
2582 for (unsigned i = 0; i != Size; ++i)
2583 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
2584 V = ConstantVector::get(Elts);
2586 V = UndefValue::get(CurTy);
2590 case bitc::CST_CODE_STRING: // STRING: [values]
2591 case bitc::CST_CODE_CSTRING: { // CSTRING: [values]
2593 return error("Invalid record");
2595 SmallString<16> Elts(Record.begin(), Record.end());
2596 V = ConstantDataArray::getString(Context, Elts,
2597 BitCode == bitc::CST_CODE_CSTRING);
2600 case bitc::CST_CODE_DATA: {// DATA: [n x value]
2602 return error("Invalid record");
2604 Type *EltTy = cast<SequentialType>(CurTy)->getElementType();
2605 unsigned Size = Record.size();
2607 if (EltTy->isIntegerTy(8)) {
2608 SmallVector<uint8_t, 16> Elts(Record.begin(), Record.end());
2609 if (isa<VectorType>(CurTy))
2610 V = ConstantDataVector::get(Context, Elts);
2612 V = ConstantDataArray::get(Context, Elts);
2613 } else if (EltTy->isIntegerTy(16)) {
2614 SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end());
2615 if (isa<VectorType>(CurTy))
2616 V = ConstantDataVector::get(Context, Elts);
2618 V = ConstantDataArray::get(Context, Elts);
2619 } else if (EltTy->isIntegerTy(32)) {
2620 SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end());
2621 if (isa<VectorType>(CurTy))
2622 V = ConstantDataVector::get(Context, Elts);
2624 V = ConstantDataArray::get(Context, Elts);
2625 } else if (EltTy->isIntegerTy(64)) {
2626 SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end());
2627 if (isa<VectorType>(CurTy))
2628 V = ConstantDataVector::get(Context, Elts);
2630 V = ConstantDataArray::get(Context, Elts);
2631 } else if (EltTy->isFloatTy()) {
2632 SmallVector<float, 16> Elts(Size);
2633 std::transform(Record.begin(), Record.end(), Elts.begin(), BitsToFloat);
2634 if (isa<VectorType>(CurTy))
2635 V = ConstantDataVector::get(Context, Elts);
2637 V = ConstantDataArray::get(Context, Elts);
2638 } else if (EltTy->isDoubleTy()) {
2639 SmallVector<double, 16> Elts(Size);
2640 std::transform(Record.begin(), Record.end(), Elts.begin(),
2642 if (isa<VectorType>(CurTy))
2643 V = ConstantDataVector::get(Context, Elts);
2645 V = ConstantDataArray::get(Context, Elts);
2647 return error("Invalid type for value");
2652 case bitc::CST_CODE_CE_BINOP: { // CE_BINOP: [opcode, opval, opval]
2653 if (Record.size() < 3)
2654 return error("Invalid record");
2655 int Opc = getDecodedBinaryOpcode(Record[0], CurTy);
2657 V = UndefValue::get(CurTy); // Unknown binop.
2659 Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy);
2660 Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy);
2662 if (Record.size() >= 4) {
2663 if (Opc == Instruction::Add ||
2664 Opc == Instruction::Sub ||
2665 Opc == Instruction::Mul ||
2666 Opc == Instruction::Shl) {
2667 if (Record[3] & (1 << bitc::OBO_NO_SIGNED_WRAP))
2668 Flags |= OverflowingBinaryOperator::NoSignedWrap;
2669 if (Record[3] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
2670 Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
2671 } else if (Opc == Instruction::SDiv ||
2672 Opc == Instruction::UDiv ||
2673 Opc == Instruction::LShr ||
2674 Opc == Instruction::AShr) {
2675 if (Record[3] & (1 << bitc::PEO_EXACT))
2676 Flags |= SDivOperator::IsExact;
2679 V = ConstantExpr::get(Opc, LHS, RHS, Flags);
2683 case bitc::CST_CODE_CE_CAST: { // CE_CAST: [opcode, opty, opval]
2684 if (Record.size() < 3)
2685 return error("Invalid record");
2686 int Opc = getDecodedCastOpcode(Record[0]);
2688 V = UndefValue::get(CurTy); // Unknown cast.
2690 Type *OpTy = getTypeByID(Record[1]);
2692 return error("Invalid record");
2693 Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy);
2694 V = UpgradeBitCastExpr(Opc, Op, CurTy);
2695 if (!V) V = ConstantExpr::getCast(Opc, Op, CurTy);
2699 case bitc::CST_CODE_CE_INBOUNDS_GEP:
2700 case bitc::CST_CODE_CE_GEP: { // CE_GEP: [n x operands]
2702 Type *PointeeType = nullptr;
2703 if (Record.size() % 2)
2704 PointeeType = getTypeByID(Record[OpNum++]);
2705 SmallVector<Constant*, 16> Elts;
2706 while (OpNum != Record.size()) {
2707 Type *ElTy = getTypeByID(Record[OpNum++]);
2709 return error("Invalid record");
2710 Elts.push_back(ValueList.getConstantFwdRef(Record[OpNum++], ElTy));
2715 cast<SequentialType>(Elts[0]->getType()->getScalarType())
2717 return error("Explicit gep operator type does not match pointee type "
2718 "of pointer operand");
2720 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
2721 V = ConstantExpr::getGetElementPtr(PointeeType, Elts[0], Indices,
2723 bitc::CST_CODE_CE_INBOUNDS_GEP);
2726 case bitc::CST_CODE_CE_SELECT: { // CE_SELECT: [opval#, opval#, opval#]
2727 if (Record.size() < 3)
2728 return error("Invalid record");
2730 Type *SelectorTy = Type::getInt1Ty(Context);
2732 // The selector might be an i1 or an <n x i1>
2733 // Get the type from the ValueList before getting a forward ref.
2734 if (VectorType *VTy = dyn_cast<VectorType>(CurTy))
2735 if (Value *V = ValueList[Record[0]])
2736 if (SelectorTy != V->getType())
2737 SelectorTy = VectorType::get(SelectorTy, VTy->getNumElements());
2739 V = ConstantExpr::getSelect(ValueList.getConstantFwdRef(Record[0],
2741 ValueList.getConstantFwdRef(Record[1],CurTy),
2742 ValueList.getConstantFwdRef(Record[2],CurTy));
2745 case bitc::CST_CODE_CE_EXTRACTELT
2746 : { // CE_EXTRACTELT: [opty, opval, opty, opval]
2747 if (Record.size() < 3)
2748 return error("Invalid record");
2750 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
2752 return error("Invalid record");
2753 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
2754 Constant *Op1 = nullptr;
2755 if (Record.size() == 4) {
2756 Type *IdxTy = getTypeByID(Record[2]);
2758 return error("Invalid record");
2759 Op1 = ValueList.getConstantFwdRef(Record[3], IdxTy);
2760 } else // TODO: Remove with llvm 4.0
2761 Op1 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
2763 return error("Invalid record");
2764 V = ConstantExpr::getExtractElement(Op0, Op1);
2767 case bitc::CST_CODE_CE_INSERTELT
2768 : { // CE_INSERTELT: [opval, opval, opty, opval]
2769 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
2770 if (Record.size() < 3 || !OpTy)
2771 return error("Invalid record");
2772 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
2773 Constant *Op1 = ValueList.getConstantFwdRef(Record[1],
2774 OpTy->getElementType());
2775 Constant *Op2 = nullptr;
2776 if (Record.size() == 4) {
2777 Type *IdxTy = getTypeByID(Record[2]);
2779 return error("Invalid record");
2780 Op2 = ValueList.getConstantFwdRef(Record[3], IdxTy);
2781 } else // TODO: Remove with llvm 4.0
2782 Op2 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
2784 return error("Invalid record");
2785 V = ConstantExpr::getInsertElement(Op0, Op1, Op2);
2788 case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval]
2789 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
2790 if (Record.size() < 3 || !OpTy)
2791 return error("Invalid record");
2792 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
2793 Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy);
2794 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
2795 OpTy->getNumElements());
2796 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy);
2797 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
2800 case bitc::CST_CODE_CE_SHUFVEC_EX: { // [opty, opval, opval, opval]
2801 VectorType *RTy = dyn_cast<VectorType>(CurTy);
2803 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
2804 if (Record.size() < 4 || !RTy || !OpTy)
2805 return error("Invalid record");
2806 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
2807 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
2808 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
2809 RTy->getNumElements());
2810 Constant *Op2 = ValueList.getConstantFwdRef(Record[3], ShufTy);
2811 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
2814 case bitc::CST_CODE_CE_CMP: { // CE_CMP: [opty, opval, opval, pred]
2815 if (Record.size() < 4)
2816 return error("Invalid record");
2817 Type *OpTy = getTypeByID(Record[0]);
2819 return error("Invalid record");
2820 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
2821 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
2823 if (OpTy->isFPOrFPVectorTy())
2824 V = ConstantExpr::getFCmp(Record[3], Op0, Op1);
2826 V = ConstantExpr::getICmp(Record[3], Op0, Op1);
2829 // This maintains backward compatibility, pre-asm dialect keywords.
2830 // FIXME: Remove with the 4.0 release.
2831 case bitc::CST_CODE_INLINEASM_OLD: {
2832 if (Record.size() < 2)
2833 return error("Invalid record");
2834 std::string AsmStr, ConstrStr;
2835 bool HasSideEffects = Record[0] & 1;
2836 bool IsAlignStack = Record[0] >> 1;
2837 unsigned AsmStrSize = Record[1];
2838 if (2+AsmStrSize >= Record.size())
2839 return error("Invalid record");
2840 unsigned ConstStrSize = Record[2+AsmStrSize];
2841 if (3+AsmStrSize+ConstStrSize > Record.size())
2842 return error("Invalid record");
2844 for (unsigned i = 0; i != AsmStrSize; ++i)
2845 AsmStr += (char)Record[2+i];
2846 for (unsigned i = 0; i != ConstStrSize; ++i)
2847 ConstrStr += (char)Record[3+AsmStrSize+i];
2848 PointerType *PTy = cast<PointerType>(CurTy);
2849 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
2850 AsmStr, ConstrStr, HasSideEffects, IsAlignStack);
2853 // This version adds support for the asm dialect keywords (e.g.,
2855 case bitc::CST_CODE_INLINEASM: {
2856 if (Record.size() < 2)
2857 return error("Invalid record");
2858 std::string AsmStr, ConstrStr;
2859 bool HasSideEffects = Record[0] & 1;
2860 bool IsAlignStack = (Record[0] >> 1) & 1;
2861 unsigned AsmDialect = Record[0] >> 2;
2862 unsigned AsmStrSize = Record[1];
2863 if (2+AsmStrSize >= Record.size())
2864 return error("Invalid record");
2865 unsigned ConstStrSize = Record[2+AsmStrSize];
2866 if (3+AsmStrSize+ConstStrSize > Record.size())
2867 return error("Invalid record");
2869 for (unsigned i = 0; i != AsmStrSize; ++i)
2870 AsmStr += (char)Record[2+i];
2871 for (unsigned i = 0; i != ConstStrSize; ++i)
2872 ConstrStr += (char)Record[3+AsmStrSize+i];
2873 PointerType *PTy = cast<PointerType>(CurTy);
2874 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
2875 AsmStr, ConstrStr, HasSideEffects, IsAlignStack,
2876 InlineAsm::AsmDialect(AsmDialect));
2879 case bitc::CST_CODE_BLOCKADDRESS:{
2880 if (Record.size() < 3)
2881 return error("Invalid record");
2882 Type *FnTy = getTypeByID(Record[0]);
2884 return error("Invalid record");
2886 dyn_cast_or_null<Function>(ValueList.getConstantFwdRef(Record[1],FnTy));
2888 return error("Invalid record");
2890 // Don't let Fn get dematerialized.
2891 BlockAddressesTaken.insert(Fn);
2893 // If the function is already parsed we can insert the block address right
2896 unsigned BBID = Record[2];
2898 // Invalid reference to entry block.
2899 return error("Invalid ID");
2901 Function::iterator BBI = Fn->begin(), BBE = Fn->end();
2902 for (size_t I = 0, E = BBID; I != E; ++I) {
2904 return error("Invalid ID");
2909 // Otherwise insert a placeholder and remember it so it can be inserted
2910 // when the function is parsed.
2911 auto &FwdBBs = BasicBlockFwdRefs[Fn];
2913 BasicBlockFwdRefQueue.push_back(Fn);
2914 if (FwdBBs.size() < BBID + 1)
2915 FwdBBs.resize(BBID + 1);
2917 FwdBBs[BBID] = BasicBlock::Create(Context);
2920 V = BlockAddress::get(Fn, BB);
2925 if (ValueList.assignValue(V, NextCstNo))
2926 return error("Invalid forward reference");
2931 std::error_code BitcodeReader::parseUseLists() {
2932 if (Stream.EnterSubBlock(bitc::USELIST_BLOCK_ID))
2933 return error("Invalid record");
2935 // Read all the records.
2936 SmallVector<uint64_t, 64> Record;
2938 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
2940 switch (Entry.Kind) {
2941 case BitstreamEntry::SubBlock: // Handled for us already.
2942 case BitstreamEntry::Error:
2943 return error("Malformed block");
2944 case BitstreamEntry::EndBlock:
2945 return std::error_code();
2946 case BitstreamEntry::Record:
2947 // The interesting case.
2951 // Read a use list record.
2954 switch (Stream.readRecord(Entry.ID, Record)) {
2955 default: // Default behavior: unknown type.
2957 case bitc::USELIST_CODE_BB:
2960 case bitc::USELIST_CODE_DEFAULT: {
2961 unsigned RecordLength = Record.size();
2962 if (RecordLength < 3)
2963 // Records should have at least an ID and two indexes.
2964 return error("Invalid record");
2965 unsigned ID = Record.back();
2970 assert(ID < FunctionBBs.size() && "Basic block not found");
2971 V = FunctionBBs[ID];
2974 unsigned NumUses = 0;
2975 SmallDenseMap<const Use *, unsigned, 16> Order;
2976 for (const Use &U : V->uses()) {
2977 if (++NumUses > Record.size())
2979 Order[&U] = Record[NumUses - 1];
2981 if (Order.size() != Record.size() || NumUses > Record.size())
2982 // Mismatches can happen if the functions are being materialized lazily
2983 // (out-of-order), or a value has been upgraded.
2986 V->sortUseList([&](const Use &L, const Use &R) {
2987 return Order.lookup(&L) < Order.lookup(&R);
2995 /// When we see the block for metadata, remember where it is and then skip it.
2996 /// This lets us lazily deserialize the metadata.
2997 std::error_code BitcodeReader::rememberAndSkipMetadata() {
2998 // Save the current stream state.
2999 uint64_t CurBit = Stream.GetCurrentBitNo();
3000 DeferredMetadataInfo.push_back(CurBit);
3002 // Skip over the block for now.
3003 if (Stream.SkipBlock())
3004 return error("Invalid record");
3005 return std::error_code();
3008 std::error_code BitcodeReader::materializeMetadata() {
3009 for (uint64_t BitPos : DeferredMetadataInfo) {
3010 // Move the bit stream to the saved position.
3011 Stream.JumpToBit(BitPos);
3012 if (std::error_code EC = parseMetadata())
3015 DeferredMetadataInfo.clear();
3016 return std::error_code();
3019 void BitcodeReader::setStripDebugInfo() { StripDebugInfo = true; }
3021 /// When we see the block for a function body, remember where it is and then
3022 /// skip it. This lets us lazily deserialize the functions.
3023 std::error_code BitcodeReader::rememberAndSkipFunctionBody() {
3024 // Get the function we are talking about.
3025 if (FunctionsWithBodies.empty())
3026 return error("Insufficient function protos");
3028 Function *Fn = FunctionsWithBodies.back();
3029 FunctionsWithBodies.pop_back();
3031 // Save the current stream state.
3032 uint64_t CurBit = Stream.GetCurrentBitNo();
3034 (DeferredFunctionInfo[Fn] == 0 || DeferredFunctionInfo[Fn] == CurBit) &&
3035 "Mismatch between VST and scanned function offsets");
3036 DeferredFunctionInfo[Fn] = CurBit;
3038 // Skip over the function block for now.
3039 if (Stream.SkipBlock())
3040 return error("Invalid record");
3041 return std::error_code();
3044 std::error_code BitcodeReader::globalCleanup() {
3045 // Patch the initializers for globals and aliases up.
3046 resolveGlobalAndAliasInits();
3047 if (!GlobalInits.empty() || !AliasInits.empty())
3048 return error("Malformed global initializer set");
3050 // Look for intrinsic functions which need to be upgraded at some point
3051 for (Function &F : *TheModule) {
3053 if (UpgradeIntrinsicFunction(&F, NewFn))
3054 UpgradedIntrinsics[&F] = NewFn;
3057 // Look for global variables which need to be renamed.
3058 for (GlobalVariable &GV : TheModule->globals())
3059 UpgradeGlobalVariable(&GV);
3061 // Force deallocation of memory for these vectors to favor the client that
3062 // want lazy deserialization.
3063 std::vector<std::pair<GlobalVariable*, unsigned> >().swap(GlobalInits);
3064 std::vector<std::pair<GlobalAlias*, unsigned> >().swap(AliasInits);
3065 return std::error_code();
3068 /// Support for lazy parsing of function bodies. This is required if we
3069 /// either have an old bitcode file without a VST forward declaration record,
3070 /// or if we have an anonymous function being materialized, since anonymous
3071 /// functions do not have a name and are therefore not in the VST.
3072 std::error_code BitcodeReader::rememberAndSkipFunctionBodies() {
3073 Stream.JumpToBit(NextUnreadBit);
3075 if (Stream.AtEndOfStream())
3076 return error("Could not find function in stream");
3078 if (!SeenFirstFunctionBody)
3079 return error("Trying to materialize functions before seeing function blocks");
3081 // An old bitcode file with the symbol table at the end would have
3082 // finished the parse greedily.
3083 assert(SeenValueSymbolTable);
3085 SmallVector<uint64_t, 64> Record;
3088 BitstreamEntry Entry = Stream.advance();
3089 switch (Entry.Kind) {
3091 return error("Expect SubBlock");
3092 case BitstreamEntry::SubBlock:
3095 return error("Expect function block");
3096 case bitc::FUNCTION_BLOCK_ID:
3097 if (std::error_code EC = rememberAndSkipFunctionBody())
3099 NextUnreadBit = Stream.GetCurrentBitNo();
3100 return std::error_code();
3106 std::error_code BitcodeReader::parseBitcodeVersion() {
3107 if (Stream.EnterSubBlock(bitc::IDENTIFICATION_BLOCK_ID))
3108 return error("Invalid record");
3110 // Read all the records.
3111 SmallVector<uint64_t, 64> Record;
3113 BitstreamEntry Entry = Stream.advance();
3115 switch (Entry.Kind) {
3117 case BitstreamEntry::Error:
3118 return error("Malformed block");
3119 case BitstreamEntry::EndBlock:
3120 return std::error_code();
3121 case BitstreamEntry::Record:
3122 // The interesting case.
3128 unsigned BitCode = Stream.readRecord(Entry.ID, Record);
3130 default: // Default behavior: reject
3131 return error("Invalid value");
3132 case bitc::IDENTIFICATION_CODE_STRING: { // IDENTIFICATION: [strchr x
3134 convertToString(Record, 0, ProducerIdentification);
3137 case bitc::IDENTIFICATION_CODE_EPOCH: { // EPOCH: [epoch#]
3138 unsigned epoch = (unsigned)Record[0];
3139 if (epoch != bitc::BITCODE_CURRENT_EPOCH) {
3141 Twine("Incompatible epoch: Bitcode '") + Twine(epoch) +
3142 "' vs current: '" + Twine(bitc::BITCODE_CURRENT_EPOCH) + "'");
3149 std::error_code BitcodeReader::parseModule(uint64_t ResumeBit,
3150 bool ShouldLazyLoadMetadata) {
3152 Stream.JumpToBit(ResumeBit);
3153 else if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
3154 return error("Invalid record");
3156 SmallVector<uint64_t, 64> Record;
3157 std::vector<std::string> SectionTable;
3158 std::vector<std::string> GCTable;
3160 // Read all the records for this module.
3162 BitstreamEntry Entry = Stream.advance();
3164 switch (Entry.Kind) {
3165 case BitstreamEntry::Error:
3166 return error("Malformed block");
3167 case BitstreamEntry::EndBlock:
3168 return globalCleanup();
3170 case BitstreamEntry::SubBlock:
3172 default: // Skip unknown content.
3173 if (Stream.SkipBlock())
3174 return error("Invalid record");
3176 case bitc::BLOCKINFO_BLOCK_ID:
3177 if (Stream.ReadBlockInfoBlock())
3178 return error("Malformed block");
3180 case bitc::PARAMATTR_BLOCK_ID:
3181 if (std::error_code EC = parseAttributeBlock())
3184 case bitc::PARAMATTR_GROUP_BLOCK_ID:
3185 if (std::error_code EC = parseAttributeGroupBlock())
3188 case bitc::TYPE_BLOCK_ID_NEW:
3189 if (std::error_code EC = parseTypeTable())
3192 case bitc::VALUE_SYMTAB_BLOCK_ID:
3193 if (!SeenValueSymbolTable) {
3194 // Either this is an old form VST without function index and an
3195 // associated VST forward declaration record (which would have caused
3196 // the VST to be jumped to and parsed before it was encountered
3197 // normally in the stream), or there were no function blocks to
3198 // trigger an earlier parsing of the VST.
3199 assert(VSTOffset == 0 || FunctionsWithBodies.empty());
3200 if (std::error_code EC = parseValueSymbolTable())
3202 SeenValueSymbolTable = true;
3204 // We must have had a VST forward declaration record, which caused
3205 // the parser to jump to and parse the VST earlier.
3206 assert(VSTOffset > 0);
3207 if (Stream.SkipBlock())
3208 return error("Invalid record");
3211 case bitc::CONSTANTS_BLOCK_ID:
3212 if (std::error_code EC = parseConstants())
3214 if (std::error_code EC = resolveGlobalAndAliasInits())
3217 case bitc::METADATA_BLOCK_ID:
3218 if (ShouldLazyLoadMetadata && !IsMetadataMaterialized) {
3219 if (std::error_code EC = rememberAndSkipMetadata())
3223 assert(DeferredMetadataInfo.empty() && "Unexpected deferred metadata");
3224 if (std::error_code EC = parseMetadata())
3227 case bitc::FUNCTION_BLOCK_ID:
3228 // If this is the first function body we've seen, reverse the
3229 // FunctionsWithBodies list.
3230 if (!SeenFirstFunctionBody) {
3231 std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
3232 if (std::error_code EC = globalCleanup())
3234 SeenFirstFunctionBody = true;
3237 if (VSTOffset > 0) {
3238 // If we have a VST forward declaration record, make sure we
3239 // parse the VST now if we haven't already. It is needed to
3240 // set up the DeferredFunctionInfo vector for lazy reading.
3241 if (!SeenValueSymbolTable) {
3242 if (std::error_code EC =
3243 BitcodeReader::parseValueSymbolTable(VSTOffset))
3245 SeenValueSymbolTable = true;
3246 // Fall through so that we record the NextUnreadBit below.
3247 // This is necessary in case we have an anonymous function that
3248 // is later materialized. Since it will not have a VST entry we
3249 // need to fall back to the lazy parse to find its offset.
3251 // If we have a VST forward declaration record, but have already
3252 // parsed the VST (just above, when the first function body was
3253 // encountered here), then we are resuming the parse after
3254 // materializing functions. The ResumeBit points to the
3255 // start of the last function block recorded in the
3256 // DeferredFunctionInfo map. Skip it.
3257 if (Stream.SkipBlock())
3258 return error("Invalid record");
3263 // Support older bitcode files that did not have the function
3264 // index in the VST, nor a VST forward declaration record, as
3265 // well as anonymous functions that do not have VST entries.
3266 // Build the DeferredFunctionInfo vector on the fly.
3267 if (std::error_code EC = rememberAndSkipFunctionBody())
3270 // Suspend parsing when we reach the function bodies. Subsequent
3271 // materialization calls will resume it when necessary. If the bitcode
3272 // file is old, the symbol table will be at the end instead and will not
3273 // have been seen yet. In this case, just finish the parse now.
3274 if (SeenValueSymbolTable) {
3275 NextUnreadBit = Stream.GetCurrentBitNo();
3276 return std::error_code();
3279 case bitc::USELIST_BLOCK_ID:
3280 if (std::error_code EC = parseUseLists())
3283 case bitc::OPERAND_BUNDLE_TAGS_BLOCK_ID:
3284 if (std::error_code EC = parseOperandBundleTags())
3290 case BitstreamEntry::Record:
3291 // The interesting case.
3297 auto BitCode = Stream.readRecord(Entry.ID, Record);
3299 default: break; // Default behavior, ignore unknown content.
3300 case bitc::MODULE_CODE_VERSION: { // VERSION: [version#]
3301 if (Record.size() < 1)
3302 return error("Invalid record");
3303 // Only version #0 and #1 are supported so far.
3304 unsigned module_version = Record[0];
3305 switch (module_version) {
3307 return error("Invalid value");
3309 UseRelativeIDs = false;
3312 UseRelativeIDs = true;
3317 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
3319 if (convertToString(Record, 0, S))
3320 return error("Invalid record");
3321 TheModule->setTargetTriple(S);
3324 case bitc::MODULE_CODE_DATALAYOUT: { // DATALAYOUT: [strchr x N]
3326 if (convertToString(Record, 0, S))
3327 return error("Invalid record");
3328 TheModule->setDataLayout(S);
3331 case bitc::MODULE_CODE_ASM: { // ASM: [strchr x N]
3333 if (convertToString(Record, 0, S))
3334 return error("Invalid record");
3335 TheModule->setModuleInlineAsm(S);
3338 case bitc::MODULE_CODE_DEPLIB: { // DEPLIB: [strchr x N]
3339 // FIXME: Remove in 4.0.
3341 if (convertToString(Record, 0, S))
3342 return error("Invalid record");
3346 case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N]
3348 if (convertToString(Record, 0, S))
3349 return error("Invalid record");
3350 SectionTable.push_back(S);
3353 case bitc::MODULE_CODE_GCNAME: { // SECTIONNAME: [strchr x N]
3355 if (convertToString(Record, 0, S))
3356 return error("Invalid record");
3357 GCTable.push_back(S);
3360 case bitc::MODULE_CODE_COMDAT: { // COMDAT: [selection_kind, name]
3361 if (Record.size() < 2)
3362 return error("Invalid record");
3363 Comdat::SelectionKind SK = getDecodedComdatSelectionKind(Record[0]);
3364 unsigned ComdatNameSize = Record[1];
3365 std::string ComdatName;
3366 ComdatName.reserve(ComdatNameSize);
3367 for (unsigned i = 0; i != ComdatNameSize; ++i)
3368 ComdatName += (char)Record[2 + i];
3369 Comdat *C = TheModule->getOrInsertComdat(ComdatName);
3370 C->setSelectionKind(SK);
3371 ComdatList.push_back(C);
3374 // GLOBALVAR: [pointer type, isconst, initid,
3375 // linkage, alignment, section, visibility, threadlocal,
3376 // unnamed_addr, externally_initialized, dllstorageclass,
3378 case bitc::MODULE_CODE_GLOBALVAR: {
3379 if (Record.size() < 6)
3380 return error("Invalid record");
3381 Type *Ty = getTypeByID(Record[0]);
3383 return error("Invalid record");
3384 bool isConstant = Record[1] & 1;
3385 bool explicitType = Record[1] & 2;
3386 unsigned AddressSpace;
3388 AddressSpace = Record[1] >> 2;
3390 if (!Ty->isPointerTy())
3391 return error("Invalid type for value");
3392 AddressSpace = cast<PointerType>(Ty)->getAddressSpace();
3393 Ty = cast<PointerType>(Ty)->getElementType();
3396 uint64_t RawLinkage = Record[3];
3397 GlobalValue::LinkageTypes Linkage = getDecodedLinkage(RawLinkage);
3399 if (std::error_code EC = parseAlignmentValue(Record[4], Alignment))
3401 std::string Section;
3403 if (Record[5]-1 >= SectionTable.size())
3404 return error("Invalid ID");
3405 Section = SectionTable[Record[5]-1];
3407 GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;
3408 // Local linkage must have default visibility.
3409 if (Record.size() > 6 && !GlobalValue::isLocalLinkage(Linkage))
3410 // FIXME: Change to an error if non-default in 4.0.
3411 Visibility = getDecodedVisibility(Record[6]);
3413 GlobalVariable::ThreadLocalMode TLM = GlobalVariable::NotThreadLocal;
3414 if (Record.size() > 7)
3415 TLM = getDecodedThreadLocalMode(Record[7]);
3417 bool UnnamedAddr = false;
3418 if (Record.size() > 8)
3419 UnnamedAddr = Record[8];
3421 bool ExternallyInitialized = false;
3422 if (Record.size() > 9)
3423 ExternallyInitialized = Record[9];
3425 GlobalVariable *NewGV =
3426 new GlobalVariable(*TheModule, Ty, isConstant, Linkage, nullptr, "", nullptr,
3427 TLM, AddressSpace, ExternallyInitialized);
3428 NewGV->setAlignment(Alignment);
3429 if (!Section.empty())
3430 NewGV->setSection(Section);
3431 NewGV->setVisibility(Visibility);
3432 NewGV->setUnnamedAddr(UnnamedAddr);
3434 if (Record.size() > 10)
3435 NewGV->setDLLStorageClass(getDecodedDLLStorageClass(Record[10]));
3437 upgradeDLLImportExportLinkage(NewGV, RawLinkage);
3439 ValueList.push_back(NewGV);
3441 // Remember which value to use for the global initializer.
3442 if (unsigned InitID = Record[2])
3443 GlobalInits.push_back(std::make_pair(NewGV, InitID-1));
3445 if (Record.size() > 11) {
3446 if (unsigned ComdatID = Record[11]) {
3447 if (ComdatID > ComdatList.size())
3448 return error("Invalid global variable comdat ID");
3449 NewGV->setComdat(ComdatList[ComdatID - 1]);
3451 } else if (hasImplicitComdat(RawLinkage)) {
3452 NewGV->setComdat(reinterpret_cast<Comdat *>(1));
3456 // FUNCTION: [type, callingconv, isproto, linkage, paramattr,
3457 // alignment, section, visibility, gc, unnamed_addr,
3458 // prologuedata, dllstorageclass, comdat, prefixdata]
3459 case bitc::MODULE_CODE_FUNCTION: {
3460 if (Record.size() < 8)
3461 return error("Invalid record");
3462 Type *Ty = getTypeByID(Record[0]);
3464 return error("Invalid record");
3465 if (auto *PTy = dyn_cast<PointerType>(Ty))
3466 Ty = PTy->getElementType();
3467 auto *FTy = dyn_cast<FunctionType>(Ty);
3469 return error("Invalid type for value");
3470 auto CC = static_cast<CallingConv::ID>(Record[1]);
3471 if (CC & ~CallingConv::MaxID)
3472 return error("Invalid calling convention ID");
3474 Function *Func = Function::Create(FTy, GlobalValue::ExternalLinkage,
3477 Func->setCallingConv(CC);
3478 bool isProto = Record[2];
3479 uint64_t RawLinkage = Record[3];
3480 Func->setLinkage(getDecodedLinkage(RawLinkage));
3481 Func->setAttributes(getAttributes(Record[4]));
3484 if (std::error_code EC = parseAlignmentValue(Record[5], Alignment))
3486 Func->setAlignment(Alignment);
3488 if (Record[6]-1 >= SectionTable.size())
3489 return error("Invalid ID");
3490 Func->setSection(SectionTable[Record[6]-1]);
3492 // Local linkage must have default visibility.
3493 if (!Func->hasLocalLinkage())
3494 // FIXME: Change to an error if non-default in 4.0.
3495 Func->setVisibility(getDecodedVisibility(Record[7]));
3496 if (Record.size() > 8 && Record[8]) {
3497 if (Record[8]-1 >= GCTable.size())
3498 return error("Invalid ID");
3499 Func->setGC(GCTable[Record[8]-1].c_str());
3501 bool UnnamedAddr = false;
3502 if (Record.size() > 9)
3503 UnnamedAddr = Record[9];
3504 Func->setUnnamedAddr(UnnamedAddr);
3505 if (Record.size() > 10 && Record[10] != 0)
3506 FunctionPrologues.push_back(std::make_pair(Func, Record[10]-1));
3508 if (Record.size() > 11)
3509 Func->setDLLStorageClass(getDecodedDLLStorageClass(Record[11]));
3511 upgradeDLLImportExportLinkage(Func, RawLinkage);
3513 if (Record.size() > 12) {
3514 if (unsigned ComdatID = Record[12]) {
3515 if (ComdatID > ComdatList.size())
3516 return error("Invalid function comdat ID");
3517 Func->setComdat(ComdatList[ComdatID - 1]);
3519 } else if (hasImplicitComdat(RawLinkage)) {
3520 Func->setComdat(reinterpret_cast<Comdat *>(1));
3523 if (Record.size() > 13 && Record[13] != 0)
3524 FunctionPrefixes.push_back(std::make_pair(Func, Record[13]-1));
3526 if (Record.size() > 14 && Record[14] != 0)
3527 FunctionPersonalityFns.push_back(std::make_pair(Func, Record[14] - 1));
3529 ValueList.push_back(Func);
3531 // If this is a function with a body, remember the prototype we are
3532 // creating now, so that we can match up the body with them later.
3534 Func->setIsMaterializable(true);
3535 FunctionsWithBodies.push_back(Func);
3536 DeferredFunctionInfo[Func] = 0;
3540 // ALIAS: [alias type, addrspace, aliasee val#, linkage]
3541 // ALIAS: [alias type, addrspace, aliasee val#, linkage, visibility, dllstorageclass]
3542 case bitc::MODULE_CODE_ALIAS:
3543 case bitc::MODULE_CODE_ALIAS_OLD: {
3544 bool NewRecord = BitCode == bitc::MODULE_CODE_ALIAS;
3545 if (Record.size() < (3 + (unsigned)NewRecord))
3546 return error("Invalid record");
3548 Type *Ty = getTypeByID(Record[OpNum++]);
3550 return error("Invalid record");
3554 auto *PTy = dyn_cast<PointerType>(Ty);
3556 return error("Invalid type for value");
3557 Ty = PTy->getElementType();
3558 AddrSpace = PTy->getAddressSpace();
3560 AddrSpace = Record[OpNum++];
3563 auto Val = Record[OpNum++];
3564 auto Linkage = Record[OpNum++];
3565 auto *NewGA = GlobalAlias::create(
3566 Ty, AddrSpace, getDecodedLinkage(Linkage), "", TheModule);
3567 // Old bitcode files didn't have visibility field.
3568 // Local linkage must have default visibility.
3569 if (OpNum != Record.size()) {
3570 auto VisInd = OpNum++;
3571 if (!NewGA->hasLocalLinkage())
3572 // FIXME: Change to an error if non-default in 4.0.
3573 NewGA->setVisibility(getDecodedVisibility(Record[VisInd]));
3575 if (OpNum != Record.size())
3576 NewGA->setDLLStorageClass(getDecodedDLLStorageClass(Record[OpNum++]));
3578 upgradeDLLImportExportLinkage(NewGA, Linkage);
3579 if (OpNum != Record.size())
3580 NewGA->setThreadLocalMode(getDecodedThreadLocalMode(Record[OpNum++]));
3581 if (OpNum != Record.size())
3582 NewGA->setUnnamedAddr(Record[OpNum++]);
3583 ValueList.push_back(NewGA);
3584 AliasInits.push_back(std::make_pair(NewGA, Val));
3587 /// MODULE_CODE_PURGEVALS: [numvals]
3588 case bitc::MODULE_CODE_PURGEVALS:
3589 // Trim down the value list to the specified size.
3590 if (Record.size() < 1 || Record[0] > ValueList.size())
3591 return error("Invalid record");
3592 ValueList.shrinkTo(Record[0]);
3594 /// MODULE_CODE_VSTOFFSET: [offset]
3595 case bitc::MODULE_CODE_VSTOFFSET:
3596 if (Record.size() < 1)
3597 return error("Invalid record");
3598 VSTOffset = Record[0];
3605 /// Helper to read the header common to all bitcode files.
3606 static bool hasValidBitcodeHeader(BitstreamCursor &Stream) {
3607 // Sniff for the signature.
3608 if (Stream.Read(8) != 'B' ||
3609 Stream.Read(8) != 'C' ||
3610 Stream.Read(4) != 0x0 ||
3611 Stream.Read(4) != 0xC ||
3612 Stream.Read(4) != 0xE ||
3613 Stream.Read(4) != 0xD)
3619 BitcodeReader::parseBitcodeInto(std::unique_ptr<DataStreamer> Streamer,
3620 Module *M, bool ShouldLazyLoadMetadata) {
3623 if (std::error_code EC = initStream(std::move(Streamer)))
3626 // Sniff for the signature.
3627 if (!hasValidBitcodeHeader(Stream))
3628 return error("Invalid bitcode signature");
3630 // We expect a number of well-defined blocks, though we don't necessarily
3631 // need to understand them all.
3633 if (Stream.AtEndOfStream()) {
3634 // We didn't really read a proper Module.
3635 return error("Malformed IR file");
3638 BitstreamEntry Entry =
3639 Stream.advance(BitstreamCursor::AF_DontAutoprocessAbbrevs);
3641 if (Entry.Kind != BitstreamEntry::SubBlock)
3642 return error("Malformed block");
3644 if (Entry.ID == bitc::IDENTIFICATION_BLOCK_ID) {
3645 parseBitcodeVersion();
3649 if (Entry.ID == bitc::MODULE_BLOCK_ID)
3650 return parseModule(0, ShouldLazyLoadMetadata);
3652 if (Stream.SkipBlock())
3653 return error("Invalid record");
3657 ErrorOr<std::string> BitcodeReader::parseModuleTriple() {
3658 if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
3659 return error("Invalid record");
3661 SmallVector<uint64_t, 64> Record;
3664 // Read all the records for this module.
3666 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
3668 switch (Entry.Kind) {
3669 case BitstreamEntry::SubBlock: // Handled for us already.
3670 case BitstreamEntry::Error:
3671 return error("Malformed block");
3672 case BitstreamEntry::EndBlock:
3674 case BitstreamEntry::Record:
3675 // The interesting case.
3680 switch (Stream.readRecord(Entry.ID, Record)) {
3681 default: break; // Default behavior, ignore unknown content.
3682 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
3684 if (convertToString(Record, 0, S))
3685 return error("Invalid record");
3692 llvm_unreachable("Exit infinite loop");
3695 ErrorOr<std::string> BitcodeReader::parseTriple() {
3696 if (std::error_code EC = initStream(nullptr))
3699 // Sniff for the signature.
3700 if (!hasValidBitcodeHeader(Stream))
3701 return error("Invalid bitcode signature");
3703 // We expect a number of well-defined blocks, though we don't necessarily
3704 // need to understand them all.
3706 BitstreamEntry Entry = Stream.advance();
3708 switch (Entry.Kind) {
3709 case BitstreamEntry::Error:
3710 return error("Malformed block");
3711 case BitstreamEntry::EndBlock:
3712 return std::error_code();
3714 case BitstreamEntry::SubBlock:
3715 if (Entry.ID == bitc::MODULE_BLOCK_ID)
3716 return parseModuleTriple();
3718 // Ignore other sub-blocks.
3719 if (Stream.SkipBlock())
3720 return error("Malformed block");
3723 case BitstreamEntry::Record:
3724 Stream.skipRecord(Entry.ID);
3730 /// Parse metadata attachments.
3731 std::error_code BitcodeReader::parseMetadataAttachment(Function &F) {
3732 if (Stream.EnterSubBlock(bitc::METADATA_ATTACHMENT_ID))
3733 return error("Invalid record");
3735 SmallVector<uint64_t, 64> Record;
3737 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
3739 switch (Entry.Kind) {
3740 case BitstreamEntry::SubBlock: // Handled for us already.
3741 case BitstreamEntry::Error:
3742 return error("Malformed block");
3743 case BitstreamEntry::EndBlock:
3744 return std::error_code();
3745 case BitstreamEntry::Record:
3746 // The interesting case.
3750 // Read a metadata attachment record.
3752 switch (Stream.readRecord(Entry.ID, Record)) {
3753 default: // Default behavior: ignore.
3755 case bitc::METADATA_ATTACHMENT: {
3756 unsigned RecordLength = Record.size();
3758 return error("Invalid record");
3759 if (RecordLength % 2 == 0) {
3760 // A function attachment.
3761 for (unsigned I = 0; I != RecordLength; I += 2) {
3762 auto K = MDKindMap.find(Record[I]);
3763 if (K == MDKindMap.end())
3764 return error("Invalid ID");
3765 Metadata *MD = MDValueList.getValueFwdRef(Record[I + 1]);
3766 F.setMetadata(K->second, cast<MDNode>(MD));
3771 // An instruction attachment.
3772 Instruction *Inst = InstructionList[Record[0]];
3773 for (unsigned i = 1; i != RecordLength; i = i+2) {
3774 unsigned Kind = Record[i];
3775 DenseMap<unsigned, unsigned>::iterator I =
3776 MDKindMap.find(Kind);
3777 if (I == MDKindMap.end())
3778 return error("Invalid ID");
3779 Metadata *Node = MDValueList.getValueFwdRef(Record[i + 1]);
3780 if (isa<LocalAsMetadata>(Node))
3781 // Drop the attachment. This used to be legal, but there's no
3784 Inst->setMetadata(I->second, cast<MDNode>(Node));
3785 if (I->second == LLVMContext::MD_tbaa)
3786 InstsWithTBAATag.push_back(Inst);
3794 static std::error_code typeCheckLoadStoreInst(DiagnosticHandlerFunction DH,
3795 Type *ValType, Type *PtrType) {
3796 if (!isa<PointerType>(PtrType))
3797 return error(DH, "Load/Store operand is not a pointer type");
3798 Type *ElemType = cast<PointerType>(PtrType)->getElementType();
3800 if (ValType && ValType != ElemType)
3801 return error(DH, "Explicit load/store type does not match pointee type of "
3803 if (!PointerType::isLoadableOrStorableType(ElemType))
3804 return error(DH, "Cannot load/store from pointer");
3805 return std::error_code();
3808 /// Lazily parse the specified function body block.
3809 std::error_code BitcodeReader::parseFunctionBody(Function *F) {
3810 if (Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID))
3811 return error("Invalid record");
3813 InstructionList.clear();
3814 unsigned ModuleValueListSize = ValueList.size();
3815 unsigned ModuleMDValueListSize = MDValueList.size();
3817 // Add all the function arguments to the value table.
3818 for (Argument &I : F->args())
3819 ValueList.push_back(&I);
3821 unsigned NextValueNo = ValueList.size();
3822 BasicBlock *CurBB = nullptr;
3823 unsigned CurBBNo = 0;
3826 auto getLastInstruction = [&]() -> Instruction * {
3827 if (CurBB && !CurBB->empty())
3828 return &CurBB->back();
3829 else if (CurBBNo && FunctionBBs[CurBBNo - 1] &&
3830 !FunctionBBs[CurBBNo - 1]->empty())
3831 return &FunctionBBs[CurBBNo - 1]->back();
3835 std::vector<OperandBundleDef> OperandBundles;
3837 // Read all the records.
3838 SmallVector<uint64_t, 64> Record;
3840 BitstreamEntry Entry = Stream.advance();
3842 switch (Entry.Kind) {
3843 case BitstreamEntry::Error:
3844 return error("Malformed block");
3845 case BitstreamEntry::EndBlock:
3846 goto OutOfRecordLoop;
3848 case BitstreamEntry::SubBlock:
3850 default: // Skip unknown content.
3851 if (Stream.SkipBlock())
3852 return error("Invalid record");
3854 case bitc::CONSTANTS_BLOCK_ID:
3855 if (std::error_code EC = parseConstants())
3857 NextValueNo = ValueList.size();
3859 case bitc::VALUE_SYMTAB_BLOCK_ID:
3860 if (std::error_code EC = parseValueSymbolTable())
3863 case bitc::METADATA_ATTACHMENT_ID:
3864 if (std::error_code EC = parseMetadataAttachment(*F))
3867 case bitc::METADATA_BLOCK_ID:
3868 if (std::error_code EC = parseMetadata())
3871 case bitc::USELIST_BLOCK_ID:
3872 if (std::error_code EC = parseUseLists())
3878 case BitstreamEntry::Record:
3879 // The interesting case.
3885 Instruction *I = nullptr;
3886 unsigned BitCode = Stream.readRecord(Entry.ID, Record);
3888 default: // Default behavior: reject
3889 return error("Invalid value");
3890 case bitc::FUNC_CODE_DECLAREBLOCKS: { // DECLAREBLOCKS: [nblocks]
3891 if (Record.size() < 1 || Record[0] == 0)
3892 return error("Invalid record");
3893 // Create all the basic blocks for the function.
3894 FunctionBBs.resize(Record[0]);
3896 // See if anything took the address of blocks in this function.
3897 auto BBFRI = BasicBlockFwdRefs.find(F);
3898 if (BBFRI == BasicBlockFwdRefs.end()) {
3899 for (unsigned i = 0, e = FunctionBBs.size(); i != e; ++i)
3900 FunctionBBs[i] = BasicBlock::Create(Context, "", F);
3902 auto &BBRefs = BBFRI->second;
3903 // Check for invalid basic block references.
3904 if (BBRefs.size() > FunctionBBs.size())
3905 return error("Invalid ID");
3906 assert(!BBRefs.empty() && "Unexpected empty array");
3907 assert(!BBRefs.front() && "Invalid reference to entry block");
3908 for (unsigned I = 0, E = FunctionBBs.size(), RE = BBRefs.size(); I != E;
3910 if (I < RE && BBRefs[I]) {
3911 BBRefs[I]->insertInto(F);
3912 FunctionBBs[I] = BBRefs[I];
3914 FunctionBBs[I] = BasicBlock::Create(Context, "", F);
3917 // Erase from the table.
3918 BasicBlockFwdRefs.erase(BBFRI);
3921 CurBB = FunctionBBs[0];
3925 case bitc::FUNC_CODE_DEBUG_LOC_AGAIN: // DEBUG_LOC_AGAIN
3926 // This record indicates that the last instruction is at the same
3927 // location as the previous instruction with a location.
3928 I = getLastInstruction();
3931 return error("Invalid record");
3932 I->setDebugLoc(LastLoc);
3936 case bitc::FUNC_CODE_DEBUG_LOC: { // DEBUG_LOC: [line, col, scope, ia]
3937 I = getLastInstruction();
3938 if (!I || Record.size() < 4)
3939 return error("Invalid record");
3941 unsigned Line = Record[0], Col = Record[1];
3942 unsigned ScopeID = Record[2], IAID = Record[3];
3944 MDNode *Scope = nullptr, *IA = nullptr;
3945 if (ScopeID) Scope = cast<MDNode>(MDValueList.getValueFwdRef(ScopeID-1));
3946 if (IAID) IA = cast<MDNode>(MDValueList.getValueFwdRef(IAID-1));
3947 LastLoc = DebugLoc::get(Line, Col, Scope, IA);
3948 I->setDebugLoc(LastLoc);
3953 case bitc::FUNC_CODE_INST_BINOP: { // BINOP: [opval, ty, opval, opcode]
3956 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
3957 popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) ||
3958 OpNum+1 > Record.size())
3959 return error("Invalid record");
3961 int Opc = getDecodedBinaryOpcode(Record[OpNum++], LHS->getType());
3963 return error("Invalid record");
3964 I = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3965 InstructionList.push_back(I);
3966 if (OpNum < Record.size()) {
3967 if (Opc == Instruction::Add ||
3968 Opc == Instruction::Sub ||
3969 Opc == Instruction::Mul ||
3970 Opc == Instruction::Shl) {
3971 if (Record[OpNum] & (1 << bitc::OBO_NO_SIGNED_WRAP))
3972 cast<BinaryOperator>(I)->setHasNoSignedWrap(true);
3973 if (Record[OpNum] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
3974 cast<BinaryOperator>(I)->setHasNoUnsignedWrap(true);
3975 } else if (Opc == Instruction::SDiv ||
3976 Opc == Instruction::UDiv ||
3977 Opc == Instruction::LShr ||
3978 Opc == Instruction::AShr) {
3979 if (Record[OpNum] & (1 << bitc::PEO_EXACT))
3980 cast<BinaryOperator>(I)->setIsExact(true);
3981 } else if (isa<FPMathOperator>(I)) {
3982 FastMathFlags FMF = getDecodedFastMathFlags(Record[OpNum]);
3984 I->setFastMathFlags(FMF);
3990 case bitc::FUNC_CODE_INST_CAST: { // CAST: [opval, opty, destty, castopc]
3993 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
3994 OpNum+2 != Record.size())
3995 return error("Invalid record");
3997 Type *ResTy = getTypeByID(Record[OpNum]);
3998 int Opc = getDecodedCastOpcode(Record[OpNum + 1]);
3999 if (Opc == -1 || !ResTy)
4000 return error("Invalid record");
4001 Instruction *Temp = nullptr;
4002 if ((I = UpgradeBitCastInst(Opc, Op, ResTy, Temp))) {
4004 InstructionList.push_back(Temp);
4005 CurBB->getInstList().push_back(Temp);
4008 auto CastOp = (Instruction::CastOps)Opc;
4009 if (!CastInst::castIsValid(CastOp, Op, ResTy))
4010 return error("Invalid cast");
4011 I = CastInst::Create(CastOp, Op, ResTy);
4013 InstructionList.push_back(I);
4016 case bitc::FUNC_CODE_INST_INBOUNDS_GEP_OLD:
4017 case bitc::FUNC_CODE_INST_GEP_OLD:
4018 case bitc::FUNC_CODE_INST_GEP: { // GEP: type, [n x operands]
4024 if (BitCode == bitc::FUNC_CODE_INST_GEP) {
4025 InBounds = Record[OpNum++];
4026 Ty = getTypeByID(Record[OpNum++]);
4028 InBounds = BitCode == bitc::FUNC_CODE_INST_INBOUNDS_GEP_OLD;
4033 if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr))
4034 return error("Invalid record");
4037 Ty = cast<SequentialType>(BasePtr->getType()->getScalarType())
4040 cast<SequentialType>(BasePtr->getType()->getScalarType())
4043 "Explicit gep type does not match pointee type of pointer operand");
4045 SmallVector<Value*, 16> GEPIdx;
4046 while (OpNum != Record.size()) {
4048 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
4049 return error("Invalid record");
4050 GEPIdx.push_back(Op);
4053 I = GetElementPtrInst::Create(Ty, BasePtr, GEPIdx);
4055 InstructionList.push_back(I);
4057 cast<GetElementPtrInst>(I)->setIsInBounds(true);
4061 case bitc::FUNC_CODE_INST_EXTRACTVAL: {
4062 // EXTRACTVAL: [opty, opval, n x indices]
4065 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
4066 return error("Invalid record");
4068 unsigned RecSize = Record.size();
4069 if (OpNum == RecSize)
4070 return error("EXTRACTVAL: Invalid instruction with 0 indices");
4072 SmallVector<unsigned, 4> EXTRACTVALIdx;
4073 Type *CurTy = Agg->getType();
4074 for (; OpNum != RecSize; ++OpNum) {
4075 bool IsArray = CurTy->isArrayTy();
4076 bool IsStruct = CurTy->isStructTy();
4077 uint64_t Index = Record[OpNum];
4079 if (!IsStruct && !IsArray)
4080 return error("EXTRACTVAL: Invalid type");
4081 if ((unsigned)Index != Index)
4082 return error("Invalid value");
4083 if (IsStruct && Index >= CurTy->subtypes().size())
4084 return error("EXTRACTVAL: Invalid struct index");
4085 if (IsArray && Index >= CurTy->getArrayNumElements())
4086 return error("EXTRACTVAL: Invalid array index");
4087 EXTRACTVALIdx.push_back((unsigned)Index);
4090 CurTy = CurTy->subtypes()[Index];
4092 CurTy = CurTy->subtypes()[0];
4095 I = ExtractValueInst::Create(Agg, EXTRACTVALIdx);
4096 InstructionList.push_back(I);
4100 case bitc::FUNC_CODE_INST_INSERTVAL: {
4101 // INSERTVAL: [opty, opval, opty, opval, n x indices]
4104 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
4105 return error("Invalid record");
4107 if (getValueTypePair(Record, OpNum, NextValueNo, Val))
4108 return error("Invalid record");
4110 unsigned RecSize = Record.size();
4111 if (OpNum == RecSize)
4112 return error("INSERTVAL: Invalid instruction with 0 indices");
4114 SmallVector<unsigned, 4> INSERTVALIdx;
4115 Type *CurTy = Agg->getType();
4116 for (; OpNum != RecSize; ++OpNum) {
4117 bool IsArray = CurTy->isArrayTy();
4118 bool IsStruct = CurTy->isStructTy();
4119 uint64_t Index = Record[OpNum];
4121 if (!IsStruct && !IsArray)
4122 return error("INSERTVAL: Invalid type");
4123 if ((unsigned)Index != Index)
4124 return error("Invalid value");
4125 if (IsStruct && Index >= CurTy->subtypes().size())
4126 return error("INSERTVAL: Invalid struct index");
4127 if (IsArray && Index >= CurTy->getArrayNumElements())
4128 return error("INSERTVAL: Invalid array index");
4130 INSERTVALIdx.push_back((unsigned)Index);
4132 CurTy = CurTy->subtypes()[Index];
4134 CurTy = CurTy->subtypes()[0];
4137 if (CurTy != Val->getType())
4138 return error("Inserted value type doesn't match aggregate type");
4140 I = InsertValueInst::Create(Agg, Val, INSERTVALIdx);
4141 InstructionList.push_back(I);
4145 case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval]
4146 // obsolete form of select
4147 // handles select i1 ... in old bitcode
4149 Value *TrueVal, *FalseVal, *Cond;
4150 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
4151 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
4152 popValue(Record, OpNum, NextValueNo, Type::getInt1Ty(Context), Cond))
4153 return error("Invalid record");
4155 I = SelectInst::Create(Cond, TrueVal, FalseVal);
4156 InstructionList.push_back(I);
4160 case bitc::FUNC_CODE_INST_VSELECT: {// VSELECT: [ty,opval,opval,predty,pred]
4161 // new form of select
4162 // handles select i1 or select [N x i1]
4164 Value *TrueVal, *FalseVal, *Cond;
4165 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
4166 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
4167 getValueTypePair(Record, OpNum, NextValueNo, Cond))
4168 return error("Invalid record");
4170 // select condition can be either i1 or [N x i1]
4171 if (VectorType* vector_type =
4172 dyn_cast<VectorType>(Cond->getType())) {
4174 if (vector_type->getElementType() != Type::getInt1Ty(Context))
4175 return error("Invalid type for value");
4178 if (Cond->getType() != Type::getInt1Ty(Context))
4179 return error("Invalid type for value");
4182 I = SelectInst::Create(Cond, TrueVal, FalseVal);
4183 InstructionList.push_back(I);
4187 case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval]
4190 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
4191 getValueTypePair(Record, OpNum, NextValueNo, Idx))
4192 return error("Invalid record");
4193 if (!Vec->getType()->isVectorTy())
4194 return error("Invalid type for value");
4195 I = ExtractElementInst::Create(Vec, Idx);
4196 InstructionList.push_back(I);
4200 case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval]
4202 Value *Vec, *Elt, *Idx;
4203 if (getValueTypePair(Record, OpNum, NextValueNo, Vec))
4204 return error("Invalid record");
4205 if (!Vec->getType()->isVectorTy())
4206 return error("Invalid type for value");
4207 if (popValue(Record, OpNum, NextValueNo,
4208 cast<VectorType>(Vec->getType())->getElementType(), Elt) ||
4209 getValueTypePair(Record, OpNum, NextValueNo, Idx))
4210 return error("Invalid record");
4211 I = InsertElementInst::Create(Vec, Elt, Idx);
4212 InstructionList.push_back(I);
4216 case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval]
4218 Value *Vec1, *Vec2, *Mask;
4219 if (getValueTypePair(Record, OpNum, NextValueNo, Vec1) ||
4220 popValue(Record, OpNum, NextValueNo, Vec1->getType(), Vec2))
4221 return error("Invalid record");
4223 if (getValueTypePair(Record, OpNum, NextValueNo, Mask))
4224 return error("Invalid record");
4225 if (!Vec1->getType()->isVectorTy() || !Vec2->getType()->isVectorTy())
4226 return error("Invalid type for value");
4227 I = new ShuffleVectorInst(Vec1, Vec2, Mask);
4228 InstructionList.push_back(I);
4232 case bitc::FUNC_CODE_INST_CMP: // CMP: [opty, opval, opval, pred]
4233 // Old form of ICmp/FCmp returning bool
4234 // Existed to differentiate between icmp/fcmp and vicmp/vfcmp which were
4235 // both legal on vectors but had different behaviour.
4236 case bitc::FUNC_CODE_INST_CMP2: { // CMP2: [opty, opval, opval, pred]
4237 // FCmp/ICmp returning bool or vector of bool
4241 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
4242 popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS))
4243 return error("Invalid record");
4245 unsigned PredVal = Record[OpNum];
4246 bool IsFP = LHS->getType()->isFPOrFPVectorTy();
4248 if (IsFP && Record.size() > OpNum+1)
4249 FMF = getDecodedFastMathFlags(Record[++OpNum]);
4251 if (OpNum+1 != Record.size())
4252 return error("Invalid record");
4254 if (LHS->getType()->isFPOrFPVectorTy())
4255 I = new FCmpInst((FCmpInst::Predicate)PredVal, LHS, RHS);
4257 I = new ICmpInst((ICmpInst::Predicate)PredVal, LHS, RHS);
4260 I->setFastMathFlags(FMF);
4261 InstructionList.push_back(I);
4265 case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>]
4267 unsigned Size = Record.size();
4269 I = ReturnInst::Create(Context);
4270 InstructionList.push_back(I);
4275 Value *Op = nullptr;
4276 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
4277 return error("Invalid record");
4278 if (OpNum != Record.size())
4279 return error("Invalid record");
4281 I = ReturnInst::Create(Context, Op);
4282 InstructionList.push_back(I);
4285 case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#]
4286 if (Record.size() != 1 && Record.size() != 3)
4287 return error("Invalid record");
4288 BasicBlock *TrueDest = getBasicBlock(Record[0]);
4290 return error("Invalid record");
4292 if (Record.size() == 1) {
4293 I = BranchInst::Create(TrueDest);
4294 InstructionList.push_back(I);
4297 BasicBlock *FalseDest = getBasicBlock(Record[1]);
4298 Value *Cond = getValue(Record, 2, NextValueNo,
4299 Type::getInt1Ty(Context));
4300 if (!FalseDest || !Cond)
4301 return error("Invalid record");
4302 I = BranchInst::Create(TrueDest, FalseDest, Cond);
4303 InstructionList.push_back(I);
4307 case bitc::FUNC_CODE_INST_CLEANUPRET: { // CLEANUPRET: [val] or [val,bb#]
4308 if (Record.size() != 1 && Record.size() != 2)
4309 return error("Invalid record");
4311 Value *CleanupPad = getValue(Record, Idx++, NextValueNo,
4312 Type::getTokenTy(Context), OC_CleanupPad);
4314 return error("Invalid record");
4315 BasicBlock *UnwindDest = nullptr;
4316 if (Record.size() == 2) {
4317 UnwindDest = getBasicBlock(Record[Idx++]);
4319 return error("Invalid record");
4322 I = CleanupReturnInst::Create(cast<CleanupPadInst>(CleanupPad),
4324 InstructionList.push_back(I);
4327 case bitc::FUNC_CODE_INST_CATCHRET: { // CATCHRET: [val,bb#]
4328 if (Record.size() != 2)
4329 return error("Invalid record");
4331 Value *CatchPad = getValue(Record, Idx++, NextValueNo,
4332 Type::getTokenTy(Context), OC_CatchPad);
4334 return error("Invalid record");
4335 BasicBlock *BB = getBasicBlock(Record[Idx++]);
4337 return error("Invalid record");
4339 I = CatchReturnInst::Create(cast<CatchPadInst>(CatchPad), BB);
4340 InstructionList.push_back(I);
4343 case bitc::FUNC_CODE_INST_CATCHPAD: { // CATCHPAD: [bb#,bb#,num,(ty,val)*]
4344 if (Record.size() < 3)
4345 return error("Invalid record");
4347 BasicBlock *NormalBB = getBasicBlock(Record[Idx++]);
4349 return error("Invalid record");
4350 BasicBlock *UnwindBB = getBasicBlock(Record[Idx++]);
4352 return error("Invalid record");
4353 unsigned NumArgOperands = Record[Idx++];
4354 SmallVector<Value *, 2> Args;
4355 for (unsigned Op = 0; Op != NumArgOperands; ++Op) {
4357 if (getValueTypePair(Record, Idx, NextValueNo, Val))
4358 return error("Invalid record");
4359 Args.push_back(Val);
4361 if (Record.size() != Idx)
4362 return error("Invalid record");
4364 I = CatchPadInst::Create(NormalBB, UnwindBB, Args);
4365 InstructionList.push_back(I);
4368 case bitc::FUNC_CODE_INST_TERMINATEPAD: { // TERMINATEPAD: [bb#,num,(ty,val)*]
4369 if (Record.size() < 1)
4370 return error("Invalid record");
4372 bool HasUnwindDest = !!Record[Idx++];
4373 BasicBlock *UnwindDest = nullptr;
4374 if (HasUnwindDest) {
4375 if (Idx == Record.size())
4376 return error("Invalid record");
4377 UnwindDest = getBasicBlock(Record[Idx++]);
4379 return error("Invalid record");
4381 unsigned NumArgOperands = Record[Idx++];
4382 SmallVector<Value *, 2> Args;
4383 for (unsigned Op = 0; Op != NumArgOperands; ++Op) {
4385 if (getValueTypePair(Record, Idx, NextValueNo, Val))
4386 return error("Invalid record");
4387 Args.push_back(Val);
4389 if (Record.size() != Idx)
4390 return error("Invalid record");
4392 I = TerminatePadInst::Create(Context, UnwindDest, Args);
4393 InstructionList.push_back(I);
4396 case bitc::FUNC_CODE_INST_CLEANUPPAD: { // CLEANUPPAD: [num,(ty,val)*]
4397 if (Record.size() < 1)
4398 return error("Invalid record");
4400 unsigned NumArgOperands = Record[Idx++];
4401 SmallVector<Value *, 2> Args;
4402 for (unsigned Op = 0; Op != NumArgOperands; ++Op) {
4404 if (getValueTypePair(Record, Idx, NextValueNo, Val))
4405 return error("Invalid record");
4406 Args.push_back(Val);
4408 if (Record.size() != Idx)
4409 return error("Invalid record");
4411 I = CleanupPadInst::Create(Context, Args);
4412 InstructionList.push_back(I);
4415 case bitc::FUNC_CODE_INST_CATCHENDPAD: { // CATCHENDPADINST: [bb#] or []
4416 if (Record.size() > 1)
4417 return error("Invalid record");
4418 BasicBlock *BB = nullptr;
4419 if (Record.size() == 1) {
4420 BB = getBasicBlock(Record[0]);
4422 return error("Invalid record");
4424 I = CatchEndPadInst::Create(Context, BB);
4425 InstructionList.push_back(I);
4428 case bitc::FUNC_CODE_INST_CLEANUPENDPAD: { // CLEANUPENDPADINST: [val] or [val,bb#]
4429 if (Record.size() != 1 && Record.size() != 2)
4430 return error("Invalid record");
4432 Value *CleanupPad = getValue(Record, Idx++, NextValueNo,
4433 Type::getTokenTy(Context), OC_CleanupPad);
4435 return error("Invalid record");
4437 BasicBlock *BB = nullptr;
4438 if (Record.size() == 2) {
4439 BB = getBasicBlock(Record[Idx++]);
4441 return error("Invalid record");
4443 I = CleanupEndPadInst::Create(cast<CleanupPadInst>(CleanupPad), BB);
4444 InstructionList.push_back(I);
4447 case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, op0, op1, ...]
4449 if ((Record[0] >> 16) == SWITCH_INST_MAGIC) {
4450 // "New" SwitchInst format with case ranges. The changes to write this
4451 // format were reverted but we still recognize bitcode that uses it.
4452 // Hopefully someday we will have support for case ranges and can use
4453 // this format again.
4455 Type *OpTy = getTypeByID(Record[1]);
4456 unsigned ValueBitWidth = cast<IntegerType>(OpTy)->getBitWidth();
4458 Value *Cond = getValue(Record, 2, NextValueNo, OpTy);
4459 BasicBlock *Default = getBasicBlock(Record[3]);
4460 if (!OpTy || !Cond || !Default)
4461 return error("Invalid record");
4463 unsigned NumCases = Record[4];
4465 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
4466 InstructionList.push_back(SI);
4468 unsigned CurIdx = 5;
4469 for (unsigned i = 0; i != NumCases; ++i) {
4470 SmallVector<ConstantInt*, 1> CaseVals;
4471 unsigned NumItems = Record[CurIdx++];
4472 for (unsigned ci = 0; ci != NumItems; ++ci) {
4473 bool isSingleNumber = Record[CurIdx++];
4476 unsigned ActiveWords = 1;
4477 if (ValueBitWidth > 64)
4478 ActiveWords = Record[CurIdx++];
4479 Low = readWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords),
4481 CurIdx += ActiveWords;
4483 if (!isSingleNumber) {
4485 if (ValueBitWidth > 64)
4486 ActiveWords = Record[CurIdx++];
4487 APInt High = readWideAPInt(
4488 makeArrayRef(&Record[CurIdx], ActiveWords), ValueBitWidth);
4489 CurIdx += ActiveWords;
4491 // FIXME: It is not clear whether values in the range should be
4492 // compared as signed or unsigned values. The partially
4493 // implemented changes that used this format in the past used
4494 // unsigned comparisons.
4495 for ( ; Low.ule(High); ++Low)
4496 CaseVals.push_back(ConstantInt::get(Context, Low));
4498 CaseVals.push_back(ConstantInt::get(Context, Low));
4500 BasicBlock *DestBB = getBasicBlock(Record[CurIdx++]);
4501 for (SmallVector<ConstantInt*, 1>::iterator cvi = CaseVals.begin(),
4502 cve = CaseVals.end(); cvi != cve; ++cvi)
4503 SI->addCase(*cvi, DestBB);
4509 // Old SwitchInst format without case ranges.
4511 if (Record.size() < 3 || (Record.size() & 1) == 0)
4512 return error("Invalid record");
4513 Type *OpTy = getTypeByID(Record[0]);
4514 Value *Cond = getValue(Record, 1, NextValueNo, OpTy);
4515 BasicBlock *Default = getBasicBlock(Record[2]);
4516 if (!OpTy || !Cond || !Default)
4517 return error("Invalid record");
4518 unsigned NumCases = (Record.size()-3)/2;
4519 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
4520 InstructionList.push_back(SI);
4521 for (unsigned i = 0, e = NumCases; i != e; ++i) {
4522 ConstantInt *CaseVal =
4523 dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy));
4524 BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]);
4525 if (!CaseVal || !DestBB) {
4527 return error("Invalid record");
4529 SI->addCase(CaseVal, DestBB);
4534 case bitc::FUNC_CODE_INST_INDIRECTBR: { // INDIRECTBR: [opty, op0, op1, ...]
4535 if (Record.size() < 2)
4536 return error("Invalid record");
4537 Type *OpTy = getTypeByID(Record[0]);
4538 Value *Address = getValue(Record, 1, NextValueNo, OpTy);
4539 if (!OpTy || !Address)
4540 return error("Invalid record");
4541 unsigned NumDests = Record.size()-2;
4542 IndirectBrInst *IBI = IndirectBrInst::Create(Address, NumDests);
4543 InstructionList.push_back(IBI);
4544 for (unsigned i = 0, e = NumDests; i != e; ++i) {
4545 if (BasicBlock *DestBB = getBasicBlock(Record[2+i])) {
4546 IBI->addDestination(DestBB);
4549 return error("Invalid record");
4556 case bitc::FUNC_CODE_INST_INVOKE: {
4557 // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...]
4558 if (Record.size() < 4)
4559 return error("Invalid record");
4561 AttributeSet PAL = getAttributes(Record[OpNum++]);
4562 unsigned CCInfo = Record[OpNum++];
4563 BasicBlock *NormalBB = getBasicBlock(Record[OpNum++]);
4564 BasicBlock *UnwindBB = getBasicBlock(Record[OpNum++]);
4566 FunctionType *FTy = nullptr;
4567 if (CCInfo >> 13 & 1 &&
4568 !(FTy = dyn_cast<FunctionType>(getTypeByID(Record[OpNum++]))))
4569 return error("Explicit invoke type is not a function type");
4572 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
4573 return error("Invalid record");
4575 PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType());
4577 return error("Callee is not a pointer");
4579 FTy = dyn_cast<FunctionType>(CalleeTy->getElementType());
4581 return error("Callee is not of pointer to function type");
4582 } else if (CalleeTy->getElementType() != FTy)
4583 return error("Explicit invoke type does not match pointee type of "
4585 if (Record.size() < FTy->getNumParams() + OpNum)
4586 return error("Insufficient operands to call");
4588 SmallVector<Value*, 16> Ops;
4589 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
4590 Ops.push_back(getValue(Record, OpNum, NextValueNo,
4591 FTy->getParamType(i)));
4593 return error("Invalid record");
4596 if (!FTy->isVarArg()) {
4597 if (Record.size() != OpNum)
4598 return error("Invalid record");
4600 // Read type/value pairs for varargs params.
4601 while (OpNum != Record.size()) {
4603 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
4604 return error("Invalid record");
4609 I = InvokeInst::Create(Callee, NormalBB, UnwindBB, Ops, OperandBundles);
4610 OperandBundles.clear();
4611 InstructionList.push_back(I);
4612 cast<InvokeInst>(I)->setCallingConv(
4613 static_cast<CallingConv::ID>(CallingConv::MaxID & CCInfo));
4614 cast<InvokeInst>(I)->setAttributes(PAL);
4617 case bitc::FUNC_CODE_INST_RESUME: { // RESUME: [opval]
4619 Value *Val = nullptr;
4620 if (getValueTypePair(Record, Idx, NextValueNo, Val))
4621 return error("Invalid record");
4622 I = ResumeInst::Create(Val);
4623 InstructionList.push_back(I);
4626 case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE
4627 I = new UnreachableInst(Context);
4628 InstructionList.push_back(I);
4630 case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...]
4631 if (Record.size() < 1 || ((Record.size()-1)&1))
4632 return error("Invalid record");
4633 Type *Ty = getTypeByID(Record[0]);
4635 return error("Invalid record");
4637 PHINode *PN = PHINode::Create(Ty, (Record.size()-1)/2);
4638 InstructionList.push_back(PN);
4640 for (unsigned i = 0, e = Record.size()-1; i != e; i += 2) {
4642 // With the new function encoding, it is possible that operands have
4643 // negative IDs (for forward references). Use a signed VBR
4644 // representation to keep the encoding small.
4646 V = getValueSigned(Record, 1+i, NextValueNo, Ty);
4648 V = getValue(Record, 1+i, NextValueNo, Ty);
4649 BasicBlock *BB = getBasicBlock(Record[2+i]);
4651 return error("Invalid record");
4652 PN->addIncoming(V, BB);
4658 case bitc::FUNC_CODE_INST_LANDINGPAD:
4659 case bitc::FUNC_CODE_INST_LANDINGPAD_OLD: {
4660 // LANDINGPAD: [ty, val, val, num, (id0,val0 ...)?]
4662 if (BitCode == bitc::FUNC_CODE_INST_LANDINGPAD) {
4663 if (Record.size() < 3)
4664 return error("Invalid record");
4666 assert(BitCode == bitc::FUNC_CODE_INST_LANDINGPAD_OLD);
4667 if (Record.size() < 4)
4668 return error("Invalid record");
4670 Type *Ty = getTypeByID(Record[Idx++]);
4672 return error("Invalid record");
4673 if (BitCode == bitc::FUNC_CODE_INST_LANDINGPAD_OLD) {
4674 Value *PersFn = nullptr;
4675 if (getValueTypePair(Record, Idx, NextValueNo, PersFn))
4676 return error("Invalid record");
4678 if (!F->hasPersonalityFn())
4679 F->setPersonalityFn(cast<Constant>(PersFn));
4680 else if (F->getPersonalityFn() != cast<Constant>(PersFn))
4681 return error("Personality function mismatch");
4684 bool IsCleanup = !!Record[Idx++];
4685 unsigned NumClauses = Record[Idx++];
4686 LandingPadInst *LP = LandingPadInst::Create(Ty, NumClauses);
4687 LP->setCleanup(IsCleanup);
4688 for (unsigned J = 0; J != NumClauses; ++J) {
4689 LandingPadInst::ClauseType CT =
4690 LandingPadInst::ClauseType(Record[Idx++]); (void)CT;
4693 if (getValueTypePair(Record, Idx, NextValueNo, Val)) {
4695 return error("Invalid record");
4698 assert((CT != LandingPadInst::Catch ||
4699 !isa<ArrayType>(Val->getType())) &&
4700 "Catch clause has a invalid type!");
4701 assert((CT != LandingPadInst::Filter ||
4702 isa<ArrayType>(Val->getType())) &&
4703 "Filter clause has invalid type!");
4704 LP->addClause(cast<Constant>(Val));
4708 InstructionList.push_back(I);
4712 case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, opty, op, align]
4713 if (Record.size() != 4)
4714 return error("Invalid record");
4715 uint64_t AlignRecord = Record[3];
4716 const uint64_t InAllocaMask = uint64_t(1) << 5;
4717 const uint64_t ExplicitTypeMask = uint64_t(1) << 6;
4718 // Reserve bit 7 for SwiftError flag.
4719 // const uint64_t SwiftErrorMask = uint64_t(1) << 7;
4720 const uint64_t FlagMask = InAllocaMask | ExplicitTypeMask;
4721 bool InAlloca = AlignRecord & InAllocaMask;
4722 Type *Ty = getTypeByID(Record[0]);
4723 if ((AlignRecord & ExplicitTypeMask) == 0) {
4724 auto *PTy = dyn_cast_or_null<PointerType>(Ty);
4726 return error("Old-style alloca with a non-pointer type");
4727 Ty = PTy->getElementType();
4729 Type *OpTy = getTypeByID(Record[1]);
4730 Value *Size = getFnValueByID(Record[2], OpTy);
4732 if (std::error_code EC =
4733 parseAlignmentValue(AlignRecord & ~FlagMask, Align)) {
4737 return error("Invalid record");
4738 AllocaInst *AI = new AllocaInst(Ty, Size, Align);
4739 AI->setUsedWithInAlloca(InAlloca);
4741 InstructionList.push_back(I);
4744 case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol]
4747 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
4748 (OpNum + 2 != Record.size() && OpNum + 3 != Record.size()))
4749 return error("Invalid record");
4752 if (OpNum + 3 == Record.size())
4753 Ty = getTypeByID(Record[OpNum++]);
4754 if (std::error_code EC =
4755 typeCheckLoadStoreInst(DiagnosticHandler, Ty, Op->getType()))
4758 Ty = cast<PointerType>(Op->getType())->getElementType();
4761 if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align))
4763 I = new LoadInst(Ty, Op, "", Record[OpNum + 1], Align);
4765 InstructionList.push_back(I);
4768 case bitc::FUNC_CODE_INST_LOADATOMIC: {
4769 // LOADATOMIC: [opty, op, align, vol, ordering, synchscope]
4772 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
4773 (OpNum + 4 != Record.size() && OpNum + 5 != Record.size()))
4774 return error("Invalid record");
4777 if (OpNum + 5 == Record.size())
4778 Ty = getTypeByID(Record[OpNum++]);
4779 if (std::error_code EC =
4780 typeCheckLoadStoreInst(DiagnosticHandler, Ty, Op->getType()))
4783 Ty = cast<PointerType>(Op->getType())->getElementType();
4785 AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]);
4786 if (Ordering == NotAtomic || Ordering == Release ||
4787 Ordering == AcquireRelease)
4788 return error("Invalid record");
4789 if (Ordering != NotAtomic && Record[OpNum] == 0)
4790 return error("Invalid record");
4791 SynchronizationScope SynchScope = getDecodedSynchScope(Record[OpNum + 3]);
4794 if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align))
4796 I = new LoadInst(Op, "", Record[OpNum+1], Align, Ordering, SynchScope);
4798 InstructionList.push_back(I);
4801 case bitc::FUNC_CODE_INST_STORE:
4802 case bitc::FUNC_CODE_INST_STORE_OLD: { // STORE2:[ptrty, ptr, val, align, vol]
4805 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
4806 (BitCode == bitc::FUNC_CODE_INST_STORE
4807 ? getValueTypePair(Record, OpNum, NextValueNo, Val)
4808 : popValue(Record, OpNum, NextValueNo,
4809 cast<PointerType>(Ptr->getType())->getElementType(),
4811 OpNum + 2 != Record.size())
4812 return error("Invalid record");
4814 if (std::error_code EC = typeCheckLoadStoreInst(
4815 DiagnosticHandler, Val->getType(), Ptr->getType()))
4818 if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align))
4820 I = new StoreInst(Val, Ptr, Record[OpNum+1], Align);
4821 InstructionList.push_back(I);
4824 case bitc::FUNC_CODE_INST_STOREATOMIC:
4825 case bitc::FUNC_CODE_INST_STOREATOMIC_OLD: {
4826 // STOREATOMIC: [ptrty, ptr, val, align, vol, ordering, synchscope]
4829 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
4830 (BitCode == bitc::FUNC_CODE_INST_STOREATOMIC
4831 ? getValueTypePair(Record, OpNum, NextValueNo, Val)
4832 : popValue(Record, OpNum, NextValueNo,
4833 cast<PointerType>(Ptr->getType())->getElementType(),
4835 OpNum + 4 != Record.size())
4836 return error("Invalid record");
4838 if (std::error_code EC = typeCheckLoadStoreInst(
4839 DiagnosticHandler, Val->getType(), Ptr->getType()))
4841 AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]);
4842 if (Ordering == NotAtomic || Ordering == Acquire ||
4843 Ordering == AcquireRelease)
4844 return error("Invalid record");
4845 SynchronizationScope SynchScope = getDecodedSynchScope(Record[OpNum + 3]);
4846 if (Ordering != NotAtomic && Record[OpNum] == 0)
4847 return error("Invalid record");
4850 if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align))
4852 I = new StoreInst(Val, Ptr, Record[OpNum+1], Align, Ordering, SynchScope);
4853 InstructionList.push_back(I);
4856 case bitc::FUNC_CODE_INST_CMPXCHG_OLD:
4857 case bitc::FUNC_CODE_INST_CMPXCHG: {
4858 // CMPXCHG:[ptrty, ptr, cmp, new, vol, successordering, synchscope,
4859 // failureordering?, isweak?]
4861 Value *Ptr, *Cmp, *New;
4862 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
4863 (BitCode == bitc::FUNC_CODE_INST_CMPXCHG
4864 ? getValueTypePair(Record, OpNum, NextValueNo, Cmp)
4865 : popValue(Record, OpNum, NextValueNo,
4866 cast<PointerType>(Ptr->getType())->getElementType(),
4868 popValue(Record, OpNum, NextValueNo, Cmp->getType(), New) ||
4869 Record.size() < OpNum + 3 || Record.size() > OpNum + 5)
4870 return error("Invalid record");
4871 AtomicOrdering SuccessOrdering = getDecodedOrdering(Record[OpNum + 1]);
4872 if (SuccessOrdering == NotAtomic || SuccessOrdering == Unordered)
4873 return error("Invalid record");
4874 SynchronizationScope SynchScope = getDecodedSynchScope(Record[OpNum + 2]);
4876 if (std::error_code EC = typeCheckLoadStoreInst(
4877 DiagnosticHandler, Cmp->getType(), Ptr->getType()))
4879 AtomicOrdering FailureOrdering;
4880 if (Record.size() < 7)
4882 AtomicCmpXchgInst::getStrongestFailureOrdering(SuccessOrdering);
4884 FailureOrdering = getDecodedOrdering(Record[OpNum + 3]);
4886 I = new AtomicCmpXchgInst(Ptr, Cmp, New, SuccessOrdering, FailureOrdering,
4888 cast<AtomicCmpXchgInst>(I)->setVolatile(Record[OpNum]);
4890 if (Record.size() < 8) {
4891 // Before weak cmpxchgs existed, the instruction simply returned the
4892 // value loaded from memory, so bitcode files from that era will be
4893 // expecting the first component of a modern cmpxchg.
4894 CurBB->getInstList().push_back(I);
4895 I = ExtractValueInst::Create(I, 0);
4897 cast<AtomicCmpXchgInst>(I)->setWeak(Record[OpNum+4]);
4900 InstructionList.push_back(I);
4903 case bitc::FUNC_CODE_INST_ATOMICRMW: {
4904 // ATOMICRMW:[ptrty, ptr, val, op, vol, ordering, synchscope]
4907 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
4908 popValue(Record, OpNum, NextValueNo,
4909 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
4910 OpNum+4 != Record.size())
4911 return error("Invalid record");
4912 AtomicRMWInst::BinOp Operation = getDecodedRMWOperation(Record[OpNum]);
4913 if (Operation < AtomicRMWInst::FIRST_BINOP ||
4914 Operation > AtomicRMWInst::LAST_BINOP)
4915 return error("Invalid record");
4916 AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]);
4917 if (Ordering == NotAtomic || Ordering == Unordered)
4918 return error("Invalid record");
4919 SynchronizationScope SynchScope = getDecodedSynchScope(Record[OpNum + 3]);
4920 I = new AtomicRMWInst(Operation, Ptr, Val, Ordering, SynchScope);
4921 cast<AtomicRMWInst>(I)->setVolatile(Record[OpNum+1]);
4922 InstructionList.push_back(I);
4925 case bitc::FUNC_CODE_INST_FENCE: { // FENCE:[ordering, synchscope]
4926 if (2 != Record.size())
4927 return error("Invalid record");
4928 AtomicOrdering Ordering = getDecodedOrdering(Record[0]);
4929 if (Ordering == NotAtomic || Ordering == Unordered ||
4930 Ordering == Monotonic)
4931 return error("Invalid record");
4932 SynchronizationScope SynchScope = getDecodedSynchScope(Record[1]);
4933 I = new FenceInst(Context, Ordering, SynchScope);
4934 InstructionList.push_back(I);
4937 case bitc::FUNC_CODE_INST_CALL: {
4938 // CALL: [paramattrs, cc, fnty, fnid, arg0, arg1...]
4939 if (Record.size() < 3)
4940 return error("Invalid record");
4943 AttributeSet PAL = getAttributes(Record[OpNum++]);
4944 unsigned CCInfo = Record[OpNum++];
4946 FunctionType *FTy = nullptr;
4947 if (CCInfo >> 15 & 1 &&
4948 !(FTy = dyn_cast<FunctionType>(getTypeByID(Record[OpNum++]))))
4949 return error("Explicit call type is not a function type");
4952 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
4953 return error("Invalid record");
4955 PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());
4957 return error("Callee is not a pointer type");
4959 FTy = dyn_cast<FunctionType>(OpTy->getElementType());
4961 return error("Callee is not of pointer to function type");
4962 } else if (OpTy->getElementType() != FTy)
4963 return error("Explicit call type does not match pointee type of "
4965 if (Record.size() < FTy->getNumParams() + OpNum)
4966 return error("Insufficient operands to call");
4968 SmallVector<Value*, 16> Args;
4969 // Read the fixed params.
4970 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
4971 if (FTy->getParamType(i)->isLabelTy())
4972 Args.push_back(getBasicBlock(Record[OpNum]));
4974 Args.push_back(getValue(Record, OpNum, NextValueNo,
4975 FTy->getParamType(i)));
4977 return error("Invalid record");
4980 // Read type/value pairs for varargs params.
4981 if (!FTy->isVarArg()) {
4982 if (OpNum != Record.size())
4983 return error("Invalid record");
4985 while (OpNum != Record.size()) {
4987 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
4988 return error("Invalid record");
4993 I = CallInst::Create(FTy, Callee, Args, OperandBundles);
4994 OperandBundles.clear();
4995 InstructionList.push_back(I);
4996 cast<CallInst>(I)->setCallingConv(
4997 static_cast<CallingConv::ID>((0x7ff & CCInfo) >> 1));
4998 CallInst::TailCallKind TCK = CallInst::TCK_None;
5000 TCK = CallInst::TCK_Tail;
5001 if (CCInfo & (1 << 14))
5002 TCK = CallInst::TCK_MustTail;
5003 cast<CallInst>(I)->setTailCallKind(TCK);
5004 cast<CallInst>(I)->setAttributes(PAL);
5007 case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty]
5008 if (Record.size() < 3)
5009 return error("Invalid record");
5010 Type *OpTy = getTypeByID(Record[0]);
5011 Value *Op = getValue(Record, 1, NextValueNo, OpTy);
5012 Type *ResTy = getTypeByID(Record[2]);
5013 if (!OpTy || !Op || !ResTy)
5014 return error("Invalid record");
5015 I = new VAArgInst(Op, ResTy);
5016 InstructionList.push_back(I);
5020 case bitc::FUNC_CODE_OPERAND_BUNDLE: {
5021 // A call or an invoke can be optionally prefixed with some variable
5022 // number of operand bundle blocks. These blocks are read into
5023 // OperandBundles and consumed at the next call or invoke instruction.
5025 if (Record.size() < 1 || Record[0] >= BundleTags.size())
5026 return error("Invalid record");
5028 OperandBundles.emplace_back();
5029 OperandBundles.back().Tag = BundleTags[Record[0]];
5031 std::vector<Value *> &Inputs = OperandBundles.back().Inputs;
5034 while (OpNum != Record.size()) {
5036 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
5037 return error("Invalid record");
5038 Inputs.push_back(Op);
5045 // Add instruction to end of current BB. If there is no current BB, reject
5049 return error("Invalid instruction with no BB");
5051 if (!OperandBundles.empty()) {
5053 return error("Operand bundles found with no consumer");
5055 CurBB->getInstList().push_back(I);
5057 // If this was a terminator instruction, move to the next block.
5058 if (isa<TerminatorInst>(I)) {
5060 CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : nullptr;
5063 // Non-void values get registered in the value table for future use.
5064 if (I && !I->getType()->isVoidTy())
5065 if (ValueList.assignValue(I, NextValueNo++))
5066 return error("Invalid forward reference");
5071 if (!OperandBundles.empty())
5072 return error("Operand bundles found with no consumer");
5074 // Check the function list for unresolved values.
5075 if (Argument *A = dyn_cast<Argument>(ValueList.back())) {
5076 if (!A->getParent()) {
5077 // We found at least one unresolved value. Nuke them all to avoid leaks.
5078 for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){
5079 if ((A = dyn_cast_or_null<Argument>(ValueList[i])) && !A->getParent()) {
5080 A->replaceAllUsesWith(UndefValue::get(A->getType()));
5084 return error("Never resolved value found in function");
5088 // FIXME: Check for unresolved forward-declared metadata references
5089 // and clean up leaks.
5091 // Trim the value list down to the size it was before we parsed this function.
5092 ValueList.shrinkTo(ModuleValueListSize);
5093 MDValueList.shrinkTo(ModuleMDValueListSize);
5094 std::vector<BasicBlock*>().swap(FunctionBBs);
5095 return std::error_code();
5098 /// Find the function body in the bitcode stream
5099 std::error_code BitcodeReader::findFunctionInStream(
5101 DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator) {
5102 while (DeferredFunctionInfoIterator->second == 0) {
5103 // This is the fallback handling for the old format bitcode that
5104 // didn't contain the function index in the VST, or when we have
5105 // an anonymous function which would not have a VST entry.
5106 // Assert that we have one of those two cases.
5107 assert(VSTOffset == 0 || !F->hasName());
5108 // Parse the next body in the stream and set its position in the
5109 // DeferredFunctionInfo map.
5110 if (std::error_code EC = rememberAndSkipFunctionBodies())
5113 return std::error_code();
5116 //===----------------------------------------------------------------------===//
5117 // GVMaterializer implementation
5118 //===----------------------------------------------------------------------===//
5120 void BitcodeReader::releaseBuffer() { Buffer.release(); }
5122 std::error_code BitcodeReader::materialize(GlobalValue *GV) {
5123 if (std::error_code EC = materializeMetadata())
5126 Function *F = dyn_cast<Function>(GV);
5127 // If it's not a function or is already material, ignore the request.
5128 if (!F || !F->isMaterializable())
5129 return std::error_code();
5131 DenseMap<Function*, uint64_t>::iterator DFII = DeferredFunctionInfo.find(F);
5132 assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!");
5133 // If its position is recorded as 0, its body is somewhere in the stream
5134 // but we haven't seen it yet.
5135 if (DFII->second == 0)
5136 if (std::error_code EC = findFunctionInStream(F, DFII))
5139 // Move the bit stream to the saved position of the deferred function body.
5140 Stream.JumpToBit(DFII->second);
5142 if (std::error_code EC = parseFunctionBody(F))
5144 F->setIsMaterializable(false);
5149 // Upgrade any old intrinsic calls in the function.
5150 for (auto &I : UpgradedIntrinsics) {
5151 for (auto UI = I.first->user_begin(), UE = I.first->user_end(); UI != UE;) {
5154 if (CallInst *CI = dyn_cast<CallInst>(U))
5155 UpgradeIntrinsicCall(CI, I.second);
5159 // Finish fn->subprogram upgrade for materialized functions.
5160 if (DISubprogram *SP = FunctionsWithSPs.lookup(F))
5161 F->setSubprogram(SP);
5163 // Bring in any functions that this function forward-referenced via
5165 return materializeForwardReferencedFunctions();
5168 bool BitcodeReader::isDematerializable(const GlobalValue *GV) const {
5169 const Function *F = dyn_cast<Function>(GV);
5170 if (!F || F->isDeclaration())
5173 // Dematerializing F would leave dangling references that wouldn't be
5174 // reconnected on re-materialization.
5175 if (BlockAddressesTaken.count(F))
5178 return DeferredFunctionInfo.count(const_cast<Function*>(F));
5181 void BitcodeReader::dematerialize(GlobalValue *GV) {
5182 Function *F = dyn_cast<Function>(GV);
5183 // If this function isn't dematerializable, this is a noop.
5184 if (!F || !isDematerializable(F))
5187 assert(DeferredFunctionInfo.count(F) && "No info to read function later?");
5189 // Just forget the function body, we can remat it later.
5190 F->dropAllReferences();
5191 F->setIsMaterializable(true);
5194 std::error_code BitcodeReader::materializeModule(Module *M) {
5195 assert(M == TheModule &&
5196 "Can only Materialize the Module this BitcodeReader is attached to.");
5198 if (std::error_code EC = materializeMetadata())
5201 // Promise to materialize all forward references.
5202 WillMaterializeAllForwardRefs = true;
5204 // Iterate over the module, deserializing any functions that are still on
5206 for (Function &F : *TheModule) {
5207 if (std::error_code EC = materialize(&F))
5210 // At this point, if there are any function bodies, parse the rest of
5211 // the bits in the module past the last function block we have recorded
5212 // through either lazy scanning or the VST.
5213 if (LastFunctionBlockBit || NextUnreadBit)
5214 parseModule(LastFunctionBlockBit > NextUnreadBit ? LastFunctionBlockBit
5217 // Check that all block address forward references got resolved (as we
5219 if (!BasicBlockFwdRefs.empty())
5220 return error("Never resolved function from blockaddress");
5222 // Upgrade any intrinsic calls that slipped through (should not happen!) and
5223 // delete the old functions to clean up. We can't do this unless the entire
5224 // module is materialized because there could always be another function body
5225 // with calls to the old function.
5226 for (auto &I : UpgradedIntrinsics) {
5227 for (auto *U : I.first->users()) {
5228 if (CallInst *CI = dyn_cast<CallInst>(U))
5229 UpgradeIntrinsicCall(CI, I.second);
5231 if (!I.first->use_empty())
5232 I.first->replaceAllUsesWith(I.second);
5233 I.first->eraseFromParent();
5235 UpgradedIntrinsics.clear();
5237 for (unsigned I = 0, E = InstsWithTBAATag.size(); I < E; I++)
5238 UpgradeInstWithTBAATag(InstsWithTBAATag[I]);
5240 UpgradeDebugInfo(*M);
5241 return std::error_code();
5244 std::vector<StructType *> BitcodeReader::getIdentifiedStructTypes() const {
5245 return IdentifiedStructTypes;
5249 BitcodeReader::initStream(std::unique_ptr<DataStreamer> Streamer) {
5251 return initLazyStream(std::move(Streamer));
5252 return initStreamFromBuffer();
5255 std::error_code BitcodeReader::initStreamFromBuffer() {
5256 const unsigned char *BufPtr = (const unsigned char*)Buffer->getBufferStart();
5257 const unsigned char *BufEnd = BufPtr+Buffer->getBufferSize();
5259 if (Buffer->getBufferSize() & 3)
5260 return error("Invalid bitcode signature");
5262 // If we have a wrapper header, parse it and ignore the non-bc file contents.
5263 // The magic number is 0x0B17C0DE stored in little endian.
5264 if (isBitcodeWrapper(BufPtr, BufEnd))
5265 if (SkipBitcodeWrapperHeader(BufPtr, BufEnd, true))
5266 return error("Invalid bitcode wrapper header");
5268 StreamFile.reset(new BitstreamReader(BufPtr, BufEnd));
5269 Stream.init(&*StreamFile);
5271 return std::error_code();
5275 BitcodeReader::initLazyStream(std::unique_ptr<DataStreamer> Streamer) {
5276 // Check and strip off the bitcode wrapper; BitstreamReader expects never to
5279 llvm::make_unique<StreamingMemoryObject>(std::move(Streamer));
5280 StreamingMemoryObject &Bytes = *OwnedBytes;
5281 StreamFile = llvm::make_unique<BitstreamReader>(std::move(OwnedBytes));
5282 Stream.init(&*StreamFile);
5284 unsigned char buf[16];
5285 if (Bytes.readBytes(buf, 16, 0) != 16)
5286 return error("Invalid bitcode signature");
5288 if (!isBitcode(buf, buf + 16))
5289 return error("Invalid bitcode signature");
5291 if (isBitcodeWrapper(buf, buf + 4)) {
5292 const unsigned char *bitcodeStart = buf;
5293 const unsigned char *bitcodeEnd = buf + 16;
5294 SkipBitcodeWrapperHeader(bitcodeStart, bitcodeEnd, false);
5295 Bytes.dropLeadingBytes(bitcodeStart - buf);
5296 Bytes.setKnownObjectSize(bitcodeEnd - bitcodeStart);
5298 return std::error_code();
5301 std::error_code FunctionIndexBitcodeReader::error(BitcodeError E,
5302 const Twine &Message) {
5303 return ::error(DiagnosticHandler, make_error_code(E), Message);
5306 std::error_code FunctionIndexBitcodeReader::error(const Twine &Message) {
5307 return ::error(DiagnosticHandler,
5308 make_error_code(BitcodeError::CorruptedBitcode), Message);
5311 std::error_code FunctionIndexBitcodeReader::error(BitcodeError E) {
5312 return ::error(DiagnosticHandler, make_error_code(E));
5315 FunctionIndexBitcodeReader::FunctionIndexBitcodeReader(
5316 MemoryBuffer *Buffer, LLVMContext &Context,
5317 DiagnosticHandlerFunction DiagnosticHandler, bool IsLazy,
5318 bool CheckFuncSummaryPresenceOnly)
5319 : DiagnosticHandler(getDiagHandler(DiagnosticHandler, Context)),
5320 Buffer(Buffer), IsLazy(IsLazy),
5321 CheckFuncSummaryPresenceOnly(CheckFuncSummaryPresenceOnly) {}
5323 FunctionIndexBitcodeReader::FunctionIndexBitcodeReader(
5324 LLVMContext &Context, DiagnosticHandlerFunction DiagnosticHandler,
5325 bool IsLazy, bool CheckFuncSummaryPresenceOnly)
5326 : DiagnosticHandler(getDiagHandler(DiagnosticHandler, Context)),
5327 Buffer(nullptr), IsLazy(IsLazy),
5328 CheckFuncSummaryPresenceOnly(CheckFuncSummaryPresenceOnly) {}
5330 void FunctionIndexBitcodeReader::freeState() { Buffer = nullptr; }
5332 void FunctionIndexBitcodeReader::releaseBuffer() { Buffer.release(); }
5334 // Specialized value symbol table parser used when reading function index
5335 // blocks where we don't actually create global values.
5336 // At the end of this routine the function index is populated with a map
5337 // from function name to FunctionInfo. The function info contains
5338 // the function block's bitcode offset as well as the offset into the
5339 // function summary section.
5340 std::error_code FunctionIndexBitcodeReader::parseValueSymbolTable() {
5341 if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
5342 return error("Invalid record");
5344 SmallVector<uint64_t, 64> Record;
5346 // Read all the records for this value table.
5347 SmallString<128> ValueName;
5349 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
5351 switch (Entry.Kind) {
5352 case BitstreamEntry::SubBlock: // Handled for us already.
5353 case BitstreamEntry::Error:
5354 return error("Malformed block");
5355 case BitstreamEntry::EndBlock:
5356 return std::error_code();
5357 case BitstreamEntry::Record:
5358 // The interesting case.
5364 switch (Stream.readRecord(Entry.ID, Record)) {
5365 default: // Default behavior: ignore (e.g. VST_CODE_BBENTRY records).
5367 case bitc::VST_CODE_FNENTRY: {
5368 // VST_FNENTRY: [valueid, offset, namechar x N]
5369 if (convertToString(Record, 2, ValueName))
5370 return error("Invalid record");
5371 unsigned ValueID = Record[0];
5372 uint64_t FuncOffset = Record[1];
5373 std::unique_ptr<FunctionInfo> FuncInfo =
5374 llvm::make_unique<FunctionInfo>(FuncOffset);
5375 if (foundFuncSummary() && !IsLazy) {
5376 DenseMap<uint64_t, std::unique_ptr<FunctionSummary>>::iterator SMI =
5377 SummaryMap.find(ValueID);
5378 assert(SMI != SummaryMap.end() && "Summary info not found");
5379 FuncInfo->setFunctionSummary(std::move(SMI->second));
5381 TheIndex->addFunctionInfo(ValueName, std::move(FuncInfo));
5386 case bitc::VST_CODE_COMBINED_FNENTRY: {
5387 // VST_FNENTRY: [offset, namechar x N]
5388 if (convertToString(Record, 1, ValueName))
5389 return error("Invalid record");
5390 uint64_t FuncSummaryOffset = Record[0];
5391 std::unique_ptr<FunctionInfo> FuncInfo =
5392 llvm::make_unique<FunctionInfo>(FuncSummaryOffset);
5393 if (foundFuncSummary() && !IsLazy) {
5394 DenseMap<uint64_t, std::unique_ptr<FunctionSummary>>::iterator SMI =
5395 SummaryMap.find(FuncSummaryOffset);
5396 assert(SMI != SummaryMap.end() && "Summary info not found");
5397 FuncInfo->setFunctionSummary(std::move(SMI->second));
5399 TheIndex->addFunctionInfo(ValueName, std::move(FuncInfo));
5408 // Parse just the blocks needed for function index building out of the module.
5409 // At the end of this routine the function Index is populated with a map
5410 // from function name to FunctionInfo. The function info contains
5411 // either the parsed function summary information (when parsing summaries
5412 // eagerly), or just to the function summary record's offset
5413 // if parsing lazily (IsLazy).
5414 std::error_code FunctionIndexBitcodeReader::parseModule() {
5415 if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
5416 return error("Invalid record");
5418 // Read the function index for this module.
5420 BitstreamEntry Entry = Stream.advance();
5422 switch (Entry.Kind) {
5423 case BitstreamEntry::Error:
5424 return error("Malformed block");
5425 case BitstreamEntry::EndBlock:
5426 return std::error_code();
5428 case BitstreamEntry::SubBlock:
5429 if (CheckFuncSummaryPresenceOnly) {
5430 if (Entry.ID == bitc::FUNCTION_SUMMARY_BLOCK_ID)
5431 SeenFuncSummary = true;
5432 if (Stream.SkipBlock())
5433 return error("Invalid record");
5434 // No need to parse the rest since we found the summary.
5435 return std::error_code();
5438 default: // Skip unknown content.
5439 if (Stream.SkipBlock())
5440 return error("Invalid record");
5442 case bitc::BLOCKINFO_BLOCK_ID:
5443 // Need to parse these to get abbrev ids (e.g. for VST)
5444 if (Stream.ReadBlockInfoBlock())
5445 return error("Malformed block");
5447 case bitc::VALUE_SYMTAB_BLOCK_ID:
5448 if (std::error_code EC = parseValueSymbolTable())
5451 case bitc::FUNCTION_SUMMARY_BLOCK_ID:
5452 SeenFuncSummary = true;
5454 // Lazy parsing of summary info, skip it.
5455 if (Stream.SkipBlock())
5456 return error("Invalid record");
5457 } else if (std::error_code EC = parseEntireSummary())
5460 case bitc::MODULE_STRTAB_BLOCK_ID:
5461 if (std::error_code EC = parseModuleStringTable())
5467 case BitstreamEntry::Record:
5468 Stream.skipRecord(Entry.ID);
5474 // Eagerly parse the entire function summary block (i.e. for all functions
5475 // in the index). This populates the FunctionSummary objects in
5477 std::error_code FunctionIndexBitcodeReader::parseEntireSummary() {
5478 if (Stream.EnterSubBlock(bitc::FUNCTION_SUMMARY_BLOCK_ID))
5479 return error("Invalid record");
5481 SmallVector<uint64_t, 64> Record;
5484 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
5486 switch (Entry.Kind) {
5487 case BitstreamEntry::SubBlock: // Handled for us already.
5488 case BitstreamEntry::Error:
5489 return error("Malformed block");
5490 case BitstreamEntry::EndBlock:
5491 return std::error_code();
5492 case BitstreamEntry::Record:
5493 // The interesting case.
5497 // Read a record. The record format depends on whether this
5498 // is a per-module index or a combined index file. In the per-module
5499 // case the records contain the associated value's ID for correlation
5500 // with VST entries. In the combined index the correlation is done
5501 // via the bitcode offset of the summary records (which were saved
5502 // in the combined index VST entries). The records also contain
5503 // information used for ThinLTO renaming and importing.
5505 uint64_t CurRecordBit = Stream.GetCurrentBitNo();
5506 switch (Stream.readRecord(Entry.ID, Record)) {
5507 default: // Default behavior: ignore.
5509 // FS_PERMODULE_ENTRY: [valueid, islocal, instcount]
5510 case bitc::FS_CODE_PERMODULE_ENTRY: {
5511 unsigned ValueID = Record[0];
5512 bool IsLocal = Record[1];
5513 unsigned InstCount = Record[2];
5514 std::unique_ptr<FunctionSummary> FS =
5515 llvm::make_unique<FunctionSummary>(InstCount);
5516 FS->setLocalFunction(IsLocal);
5517 // The module path string ref set in the summary must be owned by the
5518 // index's module string table. Since we don't have a module path
5519 // string table section in the per-module index, we create a single
5520 // module path string table entry with an empty (0) ID to take
5523 TheIndex->addModulePath(Buffer->getBufferIdentifier(), 0));
5524 SummaryMap[ValueID] = std::move(FS);
5526 // FS_COMBINED_ENTRY: [modid, instcount]
5527 case bitc::FS_CODE_COMBINED_ENTRY: {
5528 uint64_t ModuleId = Record[0];
5529 unsigned InstCount = Record[1];
5530 std::unique_ptr<FunctionSummary> FS =
5531 llvm::make_unique<FunctionSummary>(InstCount);
5532 FS->setModulePath(ModuleIdMap[ModuleId]);
5533 SummaryMap[CurRecordBit] = std::move(FS);
5537 llvm_unreachable("Exit infinite loop");
5540 // Parse the module string table block into the Index.
5541 // This populates the ModulePathStringTable map in the index.
5542 std::error_code FunctionIndexBitcodeReader::parseModuleStringTable() {
5543 if (Stream.EnterSubBlock(bitc::MODULE_STRTAB_BLOCK_ID))
5544 return error("Invalid record");
5546 SmallVector<uint64_t, 64> Record;
5548 SmallString<128> ModulePath;
5550 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
5552 switch (Entry.Kind) {
5553 case BitstreamEntry::SubBlock: // Handled for us already.
5554 case BitstreamEntry::Error:
5555 return error("Malformed block");
5556 case BitstreamEntry::EndBlock:
5557 return std::error_code();
5558 case BitstreamEntry::Record:
5559 // The interesting case.
5564 switch (Stream.readRecord(Entry.ID, Record)) {
5565 default: // Default behavior: ignore.
5567 case bitc::MST_CODE_ENTRY: {
5568 // MST_ENTRY: [modid, namechar x N]
5569 if (convertToString(Record, 1, ModulePath))
5570 return error("Invalid record");
5571 uint64_t ModuleId = Record[0];
5572 StringRef ModulePathInMap = TheIndex->addModulePath(ModulePath, ModuleId);
5573 ModuleIdMap[ModuleId] = ModulePathInMap;
5579 llvm_unreachable("Exit infinite loop");
5582 // Parse the function info index from the bitcode streamer into the given index.
5583 std::error_code FunctionIndexBitcodeReader::parseSummaryIndexInto(
5584 std::unique_ptr<DataStreamer> Streamer, FunctionInfoIndex *I) {
5587 if (std::error_code EC = initStream(std::move(Streamer)))
5590 // Sniff for the signature.
5591 if (!hasValidBitcodeHeader(Stream))
5592 return error("Invalid bitcode signature");
5594 // We expect a number of well-defined blocks, though we don't necessarily
5595 // need to understand them all.
5597 if (Stream.AtEndOfStream()) {
5598 // We didn't really read a proper Module block.
5599 return error("Malformed block");
5602 BitstreamEntry Entry =
5603 Stream.advance(BitstreamCursor::AF_DontAutoprocessAbbrevs);
5605 if (Entry.Kind != BitstreamEntry::SubBlock)
5606 return error("Malformed block");
5608 // If we see a MODULE_BLOCK, parse it to find the blocks needed for
5609 // building the function summary index.
5610 if (Entry.ID == bitc::MODULE_BLOCK_ID)
5611 return parseModule();
5613 if (Stream.SkipBlock())
5614 return error("Invalid record");
5618 // Parse the function information at the given offset in the buffer into
5619 // the index. Used to support lazy parsing of function summaries from the
5620 // combined index during importing.
5621 // TODO: This function is not yet complete as it won't have a consumer
5622 // until ThinLTO function importing is added.
5623 std::error_code FunctionIndexBitcodeReader::parseFunctionSummary(
5624 std::unique_ptr<DataStreamer> Streamer, FunctionInfoIndex *I,
5625 size_t FunctionSummaryOffset) {
5628 if (std::error_code EC = initStream(std::move(Streamer)))
5631 // Sniff for the signature.
5632 if (!hasValidBitcodeHeader(Stream))
5633 return error("Invalid bitcode signature");
5635 Stream.JumpToBit(FunctionSummaryOffset);
5637 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
5639 switch (Entry.Kind) {
5641 return error("Malformed block");
5642 case BitstreamEntry::Record:
5643 // The expected case.
5647 // TODO: Read a record. This interface will be completed when ThinLTO
5648 // importing is added so that it can be tested.
5649 SmallVector<uint64_t, 64> Record;
5650 switch (Stream.readRecord(Entry.ID, Record)) {
5651 case bitc::FS_CODE_COMBINED_ENTRY:
5653 return error("Invalid record");
5656 return std::error_code();
5660 FunctionIndexBitcodeReader::initStream(std::unique_ptr<DataStreamer> Streamer) {
5662 return initLazyStream(std::move(Streamer));
5663 return initStreamFromBuffer();
5666 std::error_code FunctionIndexBitcodeReader::initStreamFromBuffer() {
5667 const unsigned char *BufPtr = (const unsigned char *)Buffer->getBufferStart();
5668 const unsigned char *BufEnd = BufPtr + Buffer->getBufferSize();
5670 if (Buffer->getBufferSize() & 3)
5671 return error("Invalid bitcode signature");
5673 // If we have a wrapper header, parse it and ignore the non-bc file contents.
5674 // The magic number is 0x0B17C0DE stored in little endian.
5675 if (isBitcodeWrapper(BufPtr, BufEnd))
5676 if (SkipBitcodeWrapperHeader(BufPtr, BufEnd, true))
5677 return error("Invalid bitcode wrapper header");
5679 StreamFile.reset(new BitstreamReader(BufPtr, BufEnd));
5680 Stream.init(&*StreamFile);
5682 return std::error_code();
5685 std::error_code FunctionIndexBitcodeReader::initLazyStream(
5686 std::unique_ptr<DataStreamer> Streamer) {
5687 // Check and strip off the bitcode wrapper; BitstreamReader expects never to
5690 llvm::make_unique<StreamingMemoryObject>(std::move(Streamer));
5691 StreamingMemoryObject &Bytes = *OwnedBytes;
5692 StreamFile = llvm::make_unique<BitstreamReader>(std::move(OwnedBytes));
5693 Stream.init(&*StreamFile);
5695 unsigned char buf[16];
5696 if (Bytes.readBytes(buf, 16, 0) != 16)
5697 return error("Invalid bitcode signature");
5699 if (!isBitcode(buf, buf + 16))
5700 return error("Invalid bitcode signature");
5702 if (isBitcodeWrapper(buf, buf + 4)) {
5703 const unsigned char *bitcodeStart = buf;
5704 const unsigned char *bitcodeEnd = buf + 16;
5705 SkipBitcodeWrapperHeader(bitcodeStart, bitcodeEnd, false);
5706 Bytes.dropLeadingBytes(bitcodeStart - buf);
5707 Bytes.setKnownObjectSize(bitcodeEnd - bitcodeStart);
5709 return std::error_code();
5713 class BitcodeErrorCategoryType : public std::error_category {
5714 const char *name() const LLVM_NOEXCEPT override {
5715 return "llvm.bitcode";
5717 std::string message(int IE) const override {
5718 BitcodeError E = static_cast<BitcodeError>(IE);
5720 case BitcodeError::InvalidBitcodeSignature:
5721 return "Invalid bitcode signature";
5722 case BitcodeError::CorruptedBitcode:
5723 return "Corrupted bitcode";
5725 llvm_unreachable("Unknown error type!");
5730 static ManagedStatic<BitcodeErrorCategoryType> ErrorCategory;
5732 const std::error_category &llvm::BitcodeErrorCategory() {
5733 return *ErrorCategory;
5736 //===----------------------------------------------------------------------===//
5737 // External interface
5738 //===----------------------------------------------------------------------===//
5740 static ErrorOr<std::unique_ptr<Module>>
5741 getBitcodeModuleImpl(std::unique_ptr<DataStreamer> Streamer, StringRef Name,
5742 BitcodeReader *R, LLVMContext &Context,
5743 bool MaterializeAll, bool ShouldLazyLoadMetadata) {
5744 std::unique_ptr<Module> M = make_unique<Module>(Name, Context);
5745 M->setMaterializer(R);
5747 auto cleanupOnError = [&](std::error_code EC) {
5748 R->releaseBuffer(); // Never take ownership on error.
5752 // Delay parsing Metadata if ShouldLazyLoadMetadata is true.
5753 if (std::error_code EC = R->parseBitcodeInto(std::move(Streamer), M.get(),
5754 ShouldLazyLoadMetadata))
5755 return cleanupOnError(EC);
5757 if (MaterializeAll) {
5758 // Read in the entire module, and destroy the BitcodeReader.
5759 if (std::error_code EC = M->materializeAllPermanently())
5760 return cleanupOnError(EC);
5762 // Resolve forward references from blockaddresses.
5763 if (std::error_code EC = R->materializeForwardReferencedFunctions())
5764 return cleanupOnError(EC);
5766 return std::move(M);
5769 /// \brief Get a lazy one-at-time loading module from bitcode.
5771 /// This isn't always used in a lazy context. In particular, it's also used by
5772 /// \a parseBitcodeFile(). If this is truly lazy, then we need to eagerly pull
5773 /// in forward-referenced functions from block address references.
5775 /// \param[in] MaterializeAll Set to \c true if we should materialize
5777 static ErrorOr<std::unique_ptr<Module>>
5778 getLazyBitcodeModuleImpl(std::unique_ptr<MemoryBuffer> &&Buffer,
5779 LLVMContext &Context, bool MaterializeAll,
5780 DiagnosticHandlerFunction DiagnosticHandler,
5781 bool ShouldLazyLoadMetadata = false) {
5783 new BitcodeReader(Buffer.get(), Context, DiagnosticHandler);
5785 ErrorOr<std::unique_ptr<Module>> Ret =
5786 getBitcodeModuleImpl(nullptr, Buffer->getBufferIdentifier(), R, Context,
5787 MaterializeAll, ShouldLazyLoadMetadata);
5791 Buffer.release(); // The BitcodeReader owns it now.
5795 ErrorOr<std::unique_ptr<Module>> llvm::getLazyBitcodeModule(
5796 std::unique_ptr<MemoryBuffer> &&Buffer, LLVMContext &Context,
5797 DiagnosticHandlerFunction DiagnosticHandler, bool ShouldLazyLoadMetadata) {
5798 return getLazyBitcodeModuleImpl(std::move(Buffer), Context, false,
5799 DiagnosticHandler, ShouldLazyLoadMetadata);
5802 ErrorOr<std::unique_ptr<Module>> llvm::getStreamedBitcodeModule(
5803 StringRef Name, std::unique_ptr<DataStreamer> Streamer,
5804 LLVMContext &Context, DiagnosticHandlerFunction DiagnosticHandler) {
5805 std::unique_ptr<Module> M = make_unique<Module>(Name, Context);
5806 BitcodeReader *R = new BitcodeReader(Context, DiagnosticHandler);
5808 return getBitcodeModuleImpl(std::move(Streamer), Name, R, Context, false,
5812 ErrorOr<std::unique_ptr<Module>>
5813 llvm::parseBitcodeFile(MemoryBufferRef Buffer, LLVMContext &Context,
5814 DiagnosticHandlerFunction DiagnosticHandler) {
5815 std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
5816 return getLazyBitcodeModuleImpl(std::move(Buf), Context, true,
5818 // TODO: Restore the use-lists to the in-memory state when the bitcode was
5819 // written. We must defer until the Module has been fully materialized.
5823 llvm::getBitcodeTargetTriple(MemoryBufferRef Buffer, LLVMContext &Context,
5824 DiagnosticHandlerFunction DiagnosticHandler) {
5825 std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
5826 auto R = llvm::make_unique<BitcodeReader>(Buf.release(), Context,
5828 ErrorOr<std::string> Triple = R->parseTriple();
5829 if (Triple.getError())
5831 return Triple.get();
5834 // Parse the specified bitcode buffer, returning the function info index.
5835 // If IsLazy is false, parse the entire function summary into
5836 // the index. Otherwise skip the function summary section, and only create
5837 // an index object with a map from function name to function summary offset.
5838 // The index is used to perform lazy function summary reading later.
5839 ErrorOr<std::unique_ptr<FunctionInfoIndex>>
5840 llvm::getFunctionInfoIndex(MemoryBufferRef Buffer, LLVMContext &Context,
5841 DiagnosticHandlerFunction DiagnosticHandler,
5842 const Module *ExportingModule, bool IsLazy) {
5843 std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
5844 FunctionIndexBitcodeReader R(Buf.get(), Context, DiagnosticHandler, IsLazy);
5846 std::unique_ptr<FunctionInfoIndex> Index =
5847 llvm::make_unique<FunctionInfoIndex>(ExportingModule);
5849 auto cleanupOnError = [&](std::error_code EC) {
5850 R.releaseBuffer(); // Never take ownership on error.
5854 if (std::error_code EC = R.parseSummaryIndexInto(nullptr, Index.get()))
5855 return cleanupOnError(EC);
5857 Buf.release(); // The FunctionIndexBitcodeReader owns it now.
5858 return std::move(Index);
5861 // Check if the given bitcode buffer contains a function summary block.
5862 bool llvm::hasFunctionSummary(MemoryBufferRef Buffer, LLVMContext &Context,
5863 DiagnosticHandlerFunction DiagnosticHandler) {
5864 std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
5865 FunctionIndexBitcodeReader R(Buf.get(), Context, DiagnosticHandler, false,
5868 auto cleanupOnError = [&](std::error_code EC) {
5869 R.releaseBuffer(); // Never take ownership on error.
5873 if (std::error_code EC = R.parseSummaryIndexInto(nullptr, nullptr))
5874 return cleanupOnError(EC);
5876 Buf.release(); // The FunctionIndexBitcodeReader owns it now.
5877 return R.foundFuncSummary();
5880 // This method supports lazy reading of function summary data from the combined
5881 // index during ThinLTO function importing. When reading the combined index
5882 // file, getFunctionInfoIndex is first invoked with IsLazy=true.
5883 // Then this method is called for each function considered for importing,
5884 // to parse the summary information for the given function name into
5887 llvm::readFunctionSummary(MemoryBufferRef Buffer, LLVMContext &Context,
5888 DiagnosticHandlerFunction DiagnosticHandler,
5889 StringRef FunctionName,
5890 std::unique_ptr<FunctionInfoIndex> Index) {
5891 std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
5892 FunctionIndexBitcodeReader R(Buf.get(), Context, DiagnosticHandler);
5894 auto cleanupOnError = [&](std::error_code EC) {
5895 R.releaseBuffer(); // Never take ownership on error.
5899 // Lookup the given function name in the FunctionMap, which may
5900 // contain a list of function infos in the case of a COMDAT. Walk through
5901 // and parse each function summary info at the function summary offset
5902 // recorded when parsing the value symbol table.
5903 for (const auto &FI : Index->getFunctionInfoList(FunctionName)) {
5904 size_t FunctionSummaryOffset = FI->bitcodeIndex();
5905 if (std::error_code EC =
5906 R.parseFunctionSummary(nullptr, Index.get(), FunctionSummaryOffset))
5907 return cleanupOnError(EC);
5910 Buf.release(); // The FunctionIndexBitcodeReader owns it now.
5911 return std::error_code();