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_NO_RECURSE:
1309 return Attribute::NoRecurse;
1310 case bitc::ATTR_KIND_NON_LAZY_BIND:
1311 return Attribute::NonLazyBind;
1312 case bitc::ATTR_KIND_NON_NULL:
1313 return Attribute::NonNull;
1314 case bitc::ATTR_KIND_DEREFERENCEABLE:
1315 return Attribute::Dereferenceable;
1316 case bitc::ATTR_KIND_DEREFERENCEABLE_OR_NULL:
1317 return Attribute::DereferenceableOrNull;
1318 case bitc::ATTR_KIND_NO_RED_ZONE:
1319 return Attribute::NoRedZone;
1320 case bitc::ATTR_KIND_NO_RETURN:
1321 return Attribute::NoReturn;
1322 case bitc::ATTR_KIND_NO_UNWIND:
1323 return Attribute::NoUnwind;
1324 case bitc::ATTR_KIND_OPTIMIZE_FOR_SIZE:
1325 return Attribute::OptimizeForSize;
1326 case bitc::ATTR_KIND_OPTIMIZE_NONE:
1327 return Attribute::OptimizeNone;
1328 case bitc::ATTR_KIND_READ_NONE:
1329 return Attribute::ReadNone;
1330 case bitc::ATTR_KIND_READ_ONLY:
1331 return Attribute::ReadOnly;
1332 case bitc::ATTR_KIND_RETURNED:
1333 return Attribute::Returned;
1334 case bitc::ATTR_KIND_RETURNS_TWICE:
1335 return Attribute::ReturnsTwice;
1336 case bitc::ATTR_KIND_S_EXT:
1337 return Attribute::SExt;
1338 case bitc::ATTR_KIND_STACK_ALIGNMENT:
1339 return Attribute::StackAlignment;
1340 case bitc::ATTR_KIND_STACK_PROTECT:
1341 return Attribute::StackProtect;
1342 case bitc::ATTR_KIND_STACK_PROTECT_REQ:
1343 return Attribute::StackProtectReq;
1344 case bitc::ATTR_KIND_STACK_PROTECT_STRONG:
1345 return Attribute::StackProtectStrong;
1346 case bitc::ATTR_KIND_SAFESTACK:
1347 return Attribute::SafeStack;
1348 case bitc::ATTR_KIND_STRUCT_RET:
1349 return Attribute::StructRet;
1350 case bitc::ATTR_KIND_SANITIZE_ADDRESS:
1351 return Attribute::SanitizeAddress;
1352 case bitc::ATTR_KIND_SANITIZE_THREAD:
1353 return Attribute::SanitizeThread;
1354 case bitc::ATTR_KIND_SANITIZE_MEMORY:
1355 return Attribute::SanitizeMemory;
1356 case bitc::ATTR_KIND_UW_TABLE:
1357 return Attribute::UWTable;
1358 case bitc::ATTR_KIND_Z_EXT:
1359 return Attribute::ZExt;
1363 std::error_code BitcodeReader::parseAlignmentValue(uint64_t Exponent,
1364 unsigned &Alignment) {
1365 // Note: Alignment in bitcode files is incremented by 1, so that zero
1366 // can be used for default alignment.
1367 if (Exponent > Value::MaxAlignmentExponent + 1)
1368 return error("Invalid alignment value");
1369 Alignment = (1 << static_cast<unsigned>(Exponent)) >> 1;
1370 return std::error_code();
1373 std::error_code BitcodeReader::parseAttrKind(uint64_t Code,
1374 Attribute::AttrKind *Kind) {
1375 *Kind = getAttrFromCode(Code);
1376 if (*Kind == Attribute::None)
1377 return error(BitcodeError::CorruptedBitcode,
1378 "Unknown attribute kind (" + Twine(Code) + ")");
1379 return std::error_code();
1382 std::error_code BitcodeReader::parseAttributeGroupBlock() {
1383 if (Stream.EnterSubBlock(bitc::PARAMATTR_GROUP_BLOCK_ID))
1384 return error("Invalid record");
1386 if (!MAttributeGroups.empty())
1387 return error("Invalid multiple blocks");
1389 SmallVector<uint64_t, 64> Record;
1391 // Read all the records.
1393 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1395 switch (Entry.Kind) {
1396 case BitstreamEntry::SubBlock: // Handled for us already.
1397 case BitstreamEntry::Error:
1398 return error("Malformed block");
1399 case BitstreamEntry::EndBlock:
1400 return std::error_code();
1401 case BitstreamEntry::Record:
1402 // The interesting case.
1408 switch (Stream.readRecord(Entry.ID, Record)) {
1409 default: // Default behavior: ignore.
1411 case bitc::PARAMATTR_GRP_CODE_ENTRY: { // ENTRY: [grpid, idx, a0, a1, ...]
1412 if (Record.size() < 3)
1413 return error("Invalid record");
1415 uint64_t GrpID = Record[0];
1416 uint64_t Idx = Record[1]; // Index of the object this attribute refers to.
1419 for (unsigned i = 2, e = Record.size(); i != e; ++i) {
1420 if (Record[i] == 0) { // Enum attribute
1421 Attribute::AttrKind Kind;
1422 if (std::error_code EC = parseAttrKind(Record[++i], &Kind))
1425 B.addAttribute(Kind);
1426 } else if (Record[i] == 1) { // Integer attribute
1427 Attribute::AttrKind Kind;
1428 if (std::error_code EC = parseAttrKind(Record[++i], &Kind))
1430 if (Kind == Attribute::Alignment)
1431 B.addAlignmentAttr(Record[++i]);
1432 else if (Kind == Attribute::StackAlignment)
1433 B.addStackAlignmentAttr(Record[++i]);
1434 else if (Kind == Attribute::Dereferenceable)
1435 B.addDereferenceableAttr(Record[++i]);
1436 else if (Kind == Attribute::DereferenceableOrNull)
1437 B.addDereferenceableOrNullAttr(Record[++i]);
1438 } else { // String attribute
1439 assert((Record[i] == 3 || Record[i] == 4) &&
1440 "Invalid attribute group entry");
1441 bool HasValue = (Record[i++] == 4);
1442 SmallString<64> KindStr;
1443 SmallString<64> ValStr;
1445 while (Record[i] != 0 && i != e)
1446 KindStr += Record[i++];
1447 assert(Record[i] == 0 && "Kind string not null terminated");
1450 // Has a value associated with it.
1451 ++i; // Skip the '0' that terminates the "kind" string.
1452 while (Record[i] != 0 && i != e)
1453 ValStr += Record[i++];
1454 assert(Record[i] == 0 && "Value string not null terminated");
1457 B.addAttribute(KindStr.str(), ValStr.str());
1461 MAttributeGroups[GrpID] = AttributeSet::get(Context, Idx, B);
1468 std::error_code BitcodeReader::parseTypeTable() {
1469 if (Stream.EnterSubBlock(bitc::TYPE_BLOCK_ID_NEW))
1470 return error("Invalid record");
1472 return parseTypeTableBody();
1475 std::error_code BitcodeReader::parseTypeTableBody() {
1476 if (!TypeList.empty())
1477 return error("Invalid multiple blocks");
1479 SmallVector<uint64_t, 64> Record;
1480 unsigned NumRecords = 0;
1482 SmallString<64> TypeName;
1484 // Read all the records for this type table.
1486 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1488 switch (Entry.Kind) {
1489 case BitstreamEntry::SubBlock: // Handled for us already.
1490 case BitstreamEntry::Error:
1491 return error("Malformed block");
1492 case BitstreamEntry::EndBlock:
1493 if (NumRecords != TypeList.size())
1494 return error("Malformed block");
1495 return std::error_code();
1496 case BitstreamEntry::Record:
1497 // The interesting case.
1503 Type *ResultTy = nullptr;
1504 switch (Stream.readRecord(Entry.ID, Record)) {
1506 return error("Invalid value");
1507 case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries]
1508 // TYPE_CODE_NUMENTRY contains a count of the number of types in the
1509 // type list. This allows us to reserve space.
1510 if (Record.size() < 1)
1511 return error("Invalid record");
1512 TypeList.resize(Record[0]);
1514 case bitc::TYPE_CODE_VOID: // VOID
1515 ResultTy = Type::getVoidTy(Context);
1517 case bitc::TYPE_CODE_HALF: // HALF
1518 ResultTy = Type::getHalfTy(Context);
1520 case bitc::TYPE_CODE_FLOAT: // FLOAT
1521 ResultTy = Type::getFloatTy(Context);
1523 case bitc::TYPE_CODE_DOUBLE: // DOUBLE
1524 ResultTy = Type::getDoubleTy(Context);
1526 case bitc::TYPE_CODE_X86_FP80: // X86_FP80
1527 ResultTy = Type::getX86_FP80Ty(Context);
1529 case bitc::TYPE_CODE_FP128: // FP128
1530 ResultTy = Type::getFP128Ty(Context);
1532 case bitc::TYPE_CODE_PPC_FP128: // PPC_FP128
1533 ResultTy = Type::getPPC_FP128Ty(Context);
1535 case bitc::TYPE_CODE_LABEL: // LABEL
1536 ResultTy = Type::getLabelTy(Context);
1538 case bitc::TYPE_CODE_METADATA: // METADATA
1539 ResultTy = Type::getMetadataTy(Context);
1541 case bitc::TYPE_CODE_X86_MMX: // X86_MMX
1542 ResultTy = Type::getX86_MMXTy(Context);
1544 case bitc::TYPE_CODE_TOKEN: // TOKEN
1545 ResultTy = Type::getTokenTy(Context);
1547 case bitc::TYPE_CODE_INTEGER: { // INTEGER: [width]
1548 if (Record.size() < 1)
1549 return error("Invalid record");
1551 uint64_t NumBits = Record[0];
1552 if (NumBits < IntegerType::MIN_INT_BITS ||
1553 NumBits > IntegerType::MAX_INT_BITS)
1554 return error("Bitwidth for integer type out of range");
1555 ResultTy = IntegerType::get(Context, NumBits);
1558 case bitc::TYPE_CODE_POINTER: { // POINTER: [pointee type] or
1559 // [pointee type, address space]
1560 if (Record.size() < 1)
1561 return error("Invalid record");
1562 unsigned AddressSpace = 0;
1563 if (Record.size() == 2)
1564 AddressSpace = Record[1];
1565 ResultTy = getTypeByID(Record[0]);
1567 !PointerType::isValidElementType(ResultTy))
1568 return error("Invalid type");
1569 ResultTy = PointerType::get(ResultTy, AddressSpace);
1572 case bitc::TYPE_CODE_FUNCTION_OLD: {
1573 // FIXME: attrid is dead, remove it in LLVM 4.0
1574 // FUNCTION: [vararg, attrid, retty, paramty x N]
1575 if (Record.size() < 3)
1576 return error("Invalid record");
1577 SmallVector<Type*, 8> ArgTys;
1578 for (unsigned i = 3, e = Record.size(); i != e; ++i) {
1579 if (Type *T = getTypeByID(Record[i]))
1580 ArgTys.push_back(T);
1585 ResultTy = getTypeByID(Record[2]);
1586 if (!ResultTy || ArgTys.size() < Record.size()-3)
1587 return error("Invalid type");
1589 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
1592 case bitc::TYPE_CODE_FUNCTION: {
1593 // FUNCTION: [vararg, retty, paramty x N]
1594 if (Record.size() < 2)
1595 return error("Invalid record");
1596 SmallVector<Type*, 8> ArgTys;
1597 for (unsigned i = 2, e = Record.size(); i != e; ++i) {
1598 if (Type *T = getTypeByID(Record[i])) {
1599 if (!FunctionType::isValidArgumentType(T))
1600 return error("Invalid function argument type");
1601 ArgTys.push_back(T);
1607 ResultTy = getTypeByID(Record[1]);
1608 if (!ResultTy || ArgTys.size() < Record.size()-2)
1609 return error("Invalid type");
1611 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
1614 case bitc::TYPE_CODE_STRUCT_ANON: { // STRUCT: [ispacked, eltty x N]
1615 if (Record.size() < 1)
1616 return error("Invalid record");
1617 SmallVector<Type*, 8> EltTys;
1618 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
1619 if (Type *T = getTypeByID(Record[i]))
1620 EltTys.push_back(T);
1624 if (EltTys.size() != Record.size()-1)
1625 return error("Invalid type");
1626 ResultTy = StructType::get(Context, EltTys, Record[0]);
1629 case bitc::TYPE_CODE_STRUCT_NAME: // STRUCT_NAME: [strchr x N]
1630 if (convertToString(Record, 0, TypeName))
1631 return error("Invalid record");
1634 case bitc::TYPE_CODE_STRUCT_NAMED: { // STRUCT: [ispacked, eltty x N]
1635 if (Record.size() < 1)
1636 return error("Invalid record");
1638 if (NumRecords >= TypeList.size())
1639 return error("Invalid TYPE table");
1641 // Check to see if this was forward referenced, if so fill in the temp.
1642 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
1644 Res->setName(TypeName);
1645 TypeList[NumRecords] = nullptr;
1646 } else // Otherwise, create a new struct.
1647 Res = createIdentifiedStructType(Context, TypeName);
1650 SmallVector<Type*, 8> EltTys;
1651 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
1652 if (Type *T = getTypeByID(Record[i]))
1653 EltTys.push_back(T);
1657 if (EltTys.size() != Record.size()-1)
1658 return error("Invalid record");
1659 Res->setBody(EltTys, Record[0]);
1663 case bitc::TYPE_CODE_OPAQUE: { // OPAQUE: []
1664 if (Record.size() != 1)
1665 return error("Invalid record");
1667 if (NumRecords >= TypeList.size())
1668 return error("Invalid TYPE table");
1670 // Check to see if this was forward referenced, if so fill in the temp.
1671 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
1673 Res->setName(TypeName);
1674 TypeList[NumRecords] = nullptr;
1675 } else // Otherwise, create a new struct with no body.
1676 Res = createIdentifiedStructType(Context, TypeName);
1681 case bitc::TYPE_CODE_ARRAY: // ARRAY: [numelts, eltty]
1682 if (Record.size() < 2)
1683 return error("Invalid record");
1684 ResultTy = getTypeByID(Record[1]);
1685 if (!ResultTy || !ArrayType::isValidElementType(ResultTy))
1686 return error("Invalid type");
1687 ResultTy = ArrayType::get(ResultTy, Record[0]);
1689 case bitc::TYPE_CODE_VECTOR: // VECTOR: [numelts, eltty]
1690 if (Record.size() < 2)
1691 return error("Invalid record");
1693 return error("Invalid vector length");
1694 ResultTy = getTypeByID(Record[1]);
1695 if (!ResultTy || !StructType::isValidElementType(ResultTy))
1696 return error("Invalid type");
1697 ResultTy = VectorType::get(ResultTy, Record[0]);
1701 if (NumRecords >= TypeList.size())
1702 return error("Invalid TYPE table");
1703 if (TypeList[NumRecords])
1705 "Invalid TYPE table: Only named structs can be forward referenced");
1706 assert(ResultTy && "Didn't read a type?");
1707 TypeList[NumRecords++] = ResultTy;
1711 std::error_code BitcodeReader::parseOperandBundleTags() {
1712 if (Stream.EnterSubBlock(bitc::OPERAND_BUNDLE_TAGS_BLOCK_ID))
1713 return error("Invalid record");
1715 if (!BundleTags.empty())
1716 return error("Invalid multiple blocks");
1718 SmallVector<uint64_t, 64> Record;
1721 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1723 switch (Entry.Kind) {
1724 case BitstreamEntry::SubBlock: // Handled for us already.
1725 case BitstreamEntry::Error:
1726 return error("Malformed block");
1727 case BitstreamEntry::EndBlock:
1728 return std::error_code();
1729 case BitstreamEntry::Record:
1730 // The interesting case.
1734 // Tags are implicitly mapped to integers by their order.
1736 if (Stream.readRecord(Entry.ID, Record) != bitc::OPERAND_BUNDLE_TAG)
1737 return error("Invalid record");
1739 // OPERAND_BUNDLE_TAG: [strchr x N]
1740 BundleTags.emplace_back();
1741 if (convertToString(Record, 0, BundleTags.back()))
1742 return error("Invalid record");
1747 /// Associate a value with its name from the given index in the provided record.
1748 ErrorOr<Value *> BitcodeReader::recordValue(SmallVectorImpl<uint64_t> &Record,
1749 unsigned NameIndex, Triple &TT) {
1750 SmallString<128> ValueName;
1751 if (convertToString(Record, NameIndex, ValueName))
1752 return error("Invalid record");
1753 unsigned ValueID = Record[0];
1754 if (ValueID >= ValueList.size() || !ValueList[ValueID])
1755 return error("Invalid record");
1756 Value *V = ValueList[ValueID];
1758 StringRef NameStr(ValueName.data(), ValueName.size());
1759 if (NameStr.find_first_of(0) != StringRef::npos)
1760 return error("Invalid value name");
1761 V->setName(NameStr);
1762 auto *GO = dyn_cast<GlobalObject>(V);
1764 if (GO->getComdat() == reinterpret_cast<Comdat *>(1)) {
1765 if (TT.isOSBinFormatMachO())
1766 GO->setComdat(nullptr);
1768 GO->setComdat(TheModule->getOrInsertComdat(V->getName()));
1774 /// Parse the value symbol table at either the current parsing location or
1775 /// at the given bit offset if provided.
1776 std::error_code BitcodeReader::parseValueSymbolTable(uint64_t Offset) {
1777 uint64_t CurrentBit;
1778 // Pass in the Offset to distinguish between calling for the module-level
1779 // VST (where we want to jump to the VST offset) and the function-level
1780 // VST (where we don't).
1782 // Save the current parsing location so we can jump back at the end
1784 CurrentBit = Stream.GetCurrentBitNo();
1785 Stream.JumpToBit(Offset * 32);
1787 // Do some checking if we are in debug mode.
1788 BitstreamEntry Entry = Stream.advance();
1789 assert(Entry.Kind == BitstreamEntry::SubBlock);
1790 assert(Entry.ID == bitc::VALUE_SYMTAB_BLOCK_ID);
1792 // In NDEBUG mode ignore the output so we don't get an unused variable
1798 // Compute the delta between the bitcode indices in the VST (the word offset
1799 // to the word-aligned ENTER_SUBBLOCK for the function block, and that
1800 // expected by the lazy reader. The reader's EnterSubBlock expects to have
1801 // already read the ENTER_SUBBLOCK code (size getAbbrevIDWidth) and BlockID
1802 // (size BlockIDWidth). Note that we access the stream's AbbrevID width here
1803 // just before entering the VST subblock because: 1) the EnterSubBlock
1804 // changes the AbbrevID width; 2) the VST block is nested within the same
1805 // outer MODULE_BLOCK as the FUNCTION_BLOCKs and therefore have the same
1806 // AbbrevID width before calling EnterSubBlock; and 3) when we want to
1807 // jump to the FUNCTION_BLOCK using this offset later, we don't want
1808 // to rely on the stream's AbbrevID width being that of the MODULE_BLOCK.
1809 unsigned FuncBitcodeOffsetDelta =
1810 Stream.getAbbrevIDWidth() + bitc::BlockIDWidth;
1812 if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
1813 return error("Invalid record");
1815 SmallVector<uint64_t, 64> Record;
1817 Triple TT(TheModule->getTargetTriple());
1819 // Read all the records for this value table.
1820 SmallString<128> ValueName;
1822 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1824 switch (Entry.Kind) {
1825 case BitstreamEntry::SubBlock: // Handled for us already.
1826 case BitstreamEntry::Error:
1827 return error("Malformed block");
1828 case BitstreamEntry::EndBlock:
1830 Stream.JumpToBit(CurrentBit);
1831 return std::error_code();
1832 case BitstreamEntry::Record:
1833 // The interesting case.
1839 switch (Stream.readRecord(Entry.ID, Record)) {
1840 default: // Default behavior: unknown type.
1842 case bitc::VST_CODE_ENTRY: { // VST_ENTRY: [valueid, namechar x N]
1843 ErrorOr<Value *> ValOrErr = recordValue(Record, 1, TT);
1844 if (std::error_code EC = ValOrErr.getError())
1849 case bitc::VST_CODE_FNENTRY: {
1850 // VST_FNENTRY: [valueid, offset, namechar x N]
1851 ErrorOr<Value *> ValOrErr = recordValue(Record, 2, TT);
1852 if (std::error_code EC = ValOrErr.getError())
1854 Value *V = ValOrErr.get();
1856 auto *GO = dyn_cast<GlobalObject>(V);
1858 // If this is an alias, need to get the actual Function object
1859 // it aliases, in order to set up the DeferredFunctionInfo entry below.
1860 auto *GA = dyn_cast<GlobalAlias>(V);
1862 GO = GA->getBaseObject();
1866 uint64_t FuncWordOffset = Record[1];
1867 Function *F = dyn_cast<Function>(GO);
1869 uint64_t FuncBitOffset = FuncWordOffset * 32;
1870 DeferredFunctionInfo[F] = FuncBitOffset + FuncBitcodeOffsetDelta;
1871 // Set the LastFunctionBlockBit to point to the last function block.
1872 // Later when parsing is resumed after function materialization,
1873 // we can simply skip that last function block.
1874 if (FuncBitOffset > LastFunctionBlockBit)
1875 LastFunctionBlockBit = FuncBitOffset;
1878 case bitc::VST_CODE_BBENTRY: {
1879 if (convertToString(Record, 1, ValueName))
1880 return error("Invalid record");
1881 BasicBlock *BB = getBasicBlock(Record[0]);
1883 return error("Invalid record");
1885 BB->setName(StringRef(ValueName.data(), ValueName.size()));
1893 static int64_t unrotateSign(uint64_t U) { return U & 1 ? ~(U >> 1) : U >> 1; }
1895 std::error_code BitcodeReader::parseMetadata() {
1896 IsMetadataMaterialized = true;
1897 unsigned NextMDValueNo = MDValueList.size();
1899 if (Stream.EnterSubBlock(bitc::METADATA_BLOCK_ID))
1900 return error("Invalid record");
1902 SmallVector<uint64_t, 64> Record;
1905 [&](unsigned ID) -> Metadata *{ return MDValueList.getValueFwdRef(ID); };
1906 auto getMDOrNull = [&](unsigned ID) -> Metadata *{
1908 return getMD(ID - 1);
1911 auto getMDString = [&](unsigned ID) -> MDString *{
1912 // This requires that the ID is not really a forward reference. In
1913 // particular, the MDString must already have been resolved.
1914 return cast_or_null<MDString>(getMDOrNull(ID));
1917 #define GET_OR_DISTINCT(CLASS, DISTINCT, ARGS) \
1918 (DISTINCT ? CLASS::getDistinct ARGS : CLASS::get ARGS)
1920 // Read all the records.
1922 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1924 switch (Entry.Kind) {
1925 case BitstreamEntry::SubBlock: // Handled for us already.
1926 case BitstreamEntry::Error:
1927 return error("Malformed block");
1928 case BitstreamEntry::EndBlock:
1929 MDValueList.tryToResolveCycles();
1930 return std::error_code();
1931 case BitstreamEntry::Record:
1932 // The interesting case.
1938 unsigned Code = Stream.readRecord(Entry.ID, Record);
1939 bool IsDistinct = false;
1941 default: // Default behavior: ignore.
1943 case bitc::METADATA_NAME: {
1944 // Read name of the named metadata.
1945 SmallString<8> Name(Record.begin(), Record.end());
1947 Code = Stream.ReadCode();
1949 unsigned NextBitCode = Stream.readRecord(Code, Record);
1950 if (NextBitCode != bitc::METADATA_NAMED_NODE)
1951 return error("METADATA_NAME not followed by METADATA_NAMED_NODE");
1953 // Read named metadata elements.
1954 unsigned Size = Record.size();
1955 NamedMDNode *NMD = TheModule->getOrInsertNamedMetadata(Name);
1956 for (unsigned i = 0; i != Size; ++i) {
1957 MDNode *MD = dyn_cast_or_null<MDNode>(MDValueList.getValueFwdRef(Record[i]));
1959 return error("Invalid record");
1960 NMD->addOperand(MD);
1964 case bitc::METADATA_OLD_FN_NODE: {
1965 // FIXME: Remove in 4.0.
1966 // This is a LocalAsMetadata record, the only type of function-local
1968 if (Record.size() % 2 == 1)
1969 return error("Invalid record");
1971 // If this isn't a LocalAsMetadata record, we're dropping it. This used
1972 // to be legal, but there's no upgrade path.
1973 auto dropRecord = [&] {
1974 MDValueList.assignValue(MDNode::get(Context, None), NextMDValueNo++);
1976 if (Record.size() != 2) {
1981 Type *Ty = getTypeByID(Record[0]);
1982 if (Ty->isMetadataTy() || Ty->isVoidTy()) {
1987 MDValueList.assignValue(
1988 LocalAsMetadata::get(ValueList.getValueFwdRef(Record[1], Ty)),
1992 case bitc::METADATA_OLD_NODE: {
1993 // FIXME: Remove in 4.0.
1994 if (Record.size() % 2 == 1)
1995 return error("Invalid record");
1997 unsigned Size = Record.size();
1998 SmallVector<Metadata *, 8> Elts;
1999 for (unsigned i = 0; i != Size; i += 2) {
2000 Type *Ty = getTypeByID(Record[i]);
2002 return error("Invalid record");
2003 if (Ty->isMetadataTy())
2004 Elts.push_back(MDValueList.getValueFwdRef(Record[i+1]));
2005 else if (!Ty->isVoidTy()) {
2007 ValueAsMetadata::get(ValueList.getValueFwdRef(Record[i + 1], Ty));
2008 assert(isa<ConstantAsMetadata>(MD) &&
2009 "Expected non-function-local metadata");
2012 Elts.push_back(nullptr);
2014 MDValueList.assignValue(MDNode::get(Context, Elts), NextMDValueNo++);
2017 case bitc::METADATA_VALUE: {
2018 if (Record.size() != 2)
2019 return error("Invalid record");
2021 Type *Ty = getTypeByID(Record[0]);
2022 if (Ty->isMetadataTy() || Ty->isVoidTy())
2023 return error("Invalid record");
2025 MDValueList.assignValue(
2026 ValueAsMetadata::get(ValueList.getValueFwdRef(Record[1], Ty)),
2030 case bitc::METADATA_DISTINCT_NODE:
2033 case bitc::METADATA_NODE: {
2034 SmallVector<Metadata *, 8> Elts;
2035 Elts.reserve(Record.size());
2036 for (unsigned ID : Record)
2037 Elts.push_back(ID ? MDValueList.getValueFwdRef(ID - 1) : nullptr);
2038 MDValueList.assignValue(IsDistinct ? MDNode::getDistinct(Context, Elts)
2039 : MDNode::get(Context, Elts),
2043 case bitc::METADATA_LOCATION: {
2044 if (Record.size() != 5)
2045 return error("Invalid record");
2047 unsigned Line = Record[1];
2048 unsigned Column = Record[2];
2049 MDNode *Scope = cast<MDNode>(MDValueList.getValueFwdRef(Record[3]));
2050 Metadata *InlinedAt =
2051 Record[4] ? MDValueList.getValueFwdRef(Record[4] - 1) : nullptr;
2052 MDValueList.assignValue(
2053 GET_OR_DISTINCT(DILocation, Record[0],
2054 (Context, Line, Column, Scope, InlinedAt)),
2058 case bitc::METADATA_GENERIC_DEBUG: {
2059 if (Record.size() < 4)
2060 return error("Invalid record");
2062 unsigned Tag = Record[1];
2063 unsigned Version = Record[2];
2065 if (Tag >= 1u << 16 || Version != 0)
2066 return error("Invalid record");
2068 auto *Header = getMDString(Record[3]);
2069 SmallVector<Metadata *, 8> DwarfOps;
2070 for (unsigned I = 4, E = Record.size(); I != E; ++I)
2071 DwarfOps.push_back(Record[I] ? MDValueList.getValueFwdRef(Record[I] - 1)
2073 MDValueList.assignValue(GET_OR_DISTINCT(GenericDINode, Record[0],
2074 (Context, Tag, Header, DwarfOps)),
2078 case bitc::METADATA_SUBRANGE: {
2079 if (Record.size() != 3)
2080 return error("Invalid record");
2082 MDValueList.assignValue(
2083 GET_OR_DISTINCT(DISubrange, Record[0],
2084 (Context, Record[1], unrotateSign(Record[2]))),
2088 case bitc::METADATA_ENUMERATOR: {
2089 if (Record.size() != 3)
2090 return error("Invalid record");
2092 MDValueList.assignValue(GET_OR_DISTINCT(DIEnumerator, Record[0],
2093 (Context, unrotateSign(Record[1]),
2094 getMDString(Record[2]))),
2098 case bitc::METADATA_BASIC_TYPE: {
2099 if (Record.size() != 6)
2100 return error("Invalid record");
2102 MDValueList.assignValue(
2103 GET_OR_DISTINCT(DIBasicType, Record[0],
2104 (Context, Record[1], getMDString(Record[2]),
2105 Record[3], Record[4], Record[5])),
2109 case bitc::METADATA_DERIVED_TYPE: {
2110 if (Record.size() != 12)
2111 return error("Invalid record");
2113 MDValueList.assignValue(
2114 GET_OR_DISTINCT(DIDerivedType, Record[0],
2115 (Context, Record[1], getMDString(Record[2]),
2116 getMDOrNull(Record[3]), Record[4],
2117 getMDOrNull(Record[5]), getMDOrNull(Record[6]),
2118 Record[7], Record[8], Record[9], Record[10],
2119 getMDOrNull(Record[11]))),
2123 case bitc::METADATA_COMPOSITE_TYPE: {
2124 if (Record.size() != 16)
2125 return error("Invalid record");
2127 MDValueList.assignValue(
2128 GET_OR_DISTINCT(DICompositeType, Record[0],
2129 (Context, Record[1], getMDString(Record[2]),
2130 getMDOrNull(Record[3]), Record[4],
2131 getMDOrNull(Record[5]), getMDOrNull(Record[6]),
2132 Record[7], Record[8], Record[9], Record[10],
2133 getMDOrNull(Record[11]), Record[12],
2134 getMDOrNull(Record[13]), getMDOrNull(Record[14]),
2135 getMDString(Record[15]))),
2139 case bitc::METADATA_SUBROUTINE_TYPE: {
2140 if (Record.size() != 3)
2141 return error("Invalid record");
2143 MDValueList.assignValue(
2144 GET_OR_DISTINCT(DISubroutineType, Record[0],
2145 (Context, Record[1], getMDOrNull(Record[2]))),
2150 case bitc::METADATA_MODULE: {
2151 if (Record.size() != 6)
2152 return error("Invalid record");
2154 MDValueList.assignValue(
2155 GET_OR_DISTINCT(DIModule, Record[0],
2156 (Context, getMDOrNull(Record[1]),
2157 getMDString(Record[2]), getMDString(Record[3]),
2158 getMDString(Record[4]), getMDString(Record[5]))),
2163 case bitc::METADATA_FILE: {
2164 if (Record.size() != 3)
2165 return error("Invalid record");
2167 MDValueList.assignValue(
2168 GET_OR_DISTINCT(DIFile, Record[0], (Context, getMDString(Record[1]),
2169 getMDString(Record[2]))),
2173 case bitc::METADATA_COMPILE_UNIT: {
2174 if (Record.size() < 14 || Record.size() > 15)
2175 return error("Invalid record");
2177 // Ignore Record[1], which indicates whether this compile unit is
2178 // distinct. It's always distinct.
2179 MDValueList.assignValue(
2180 DICompileUnit::getDistinct(
2181 Context, Record[1], getMDOrNull(Record[2]),
2182 getMDString(Record[3]), Record[4], getMDString(Record[5]),
2183 Record[6], getMDString(Record[7]), Record[8],
2184 getMDOrNull(Record[9]), getMDOrNull(Record[10]),
2185 getMDOrNull(Record[11]), getMDOrNull(Record[12]),
2186 getMDOrNull(Record[13]), Record.size() == 14 ? 0 : Record[14]),
2190 case bitc::METADATA_SUBPROGRAM: {
2191 if (Record.size() != 18 && Record.size() != 19)
2192 return error("Invalid record");
2194 bool HasFn = Record.size() == 19;
2195 DISubprogram *SP = GET_OR_DISTINCT(
2197 Record[0] || Record[8], // All definitions should be distinct.
2198 (Context, getMDOrNull(Record[1]), getMDString(Record[2]),
2199 getMDString(Record[3]), getMDOrNull(Record[4]), Record[5],
2200 getMDOrNull(Record[6]), Record[7], Record[8], Record[9],
2201 getMDOrNull(Record[10]), Record[11], Record[12], Record[13],
2202 Record[14], getMDOrNull(Record[15 + HasFn]),
2203 getMDOrNull(Record[16 + HasFn]), getMDOrNull(Record[17 + HasFn])));
2204 MDValueList.assignValue(SP, NextMDValueNo++);
2206 // Upgrade sp->function mapping to function->sp mapping.
2207 if (HasFn && Record[15]) {
2208 if (auto *CMD = dyn_cast<ConstantAsMetadata>(getMDOrNull(Record[15])))
2209 if (auto *F = dyn_cast<Function>(CMD->getValue())) {
2210 if (F->isMaterializable())
2211 // Defer until materialized; unmaterialized functions may not have
2213 FunctionsWithSPs[F] = SP;
2214 else if (!F->empty())
2215 F->setSubprogram(SP);
2220 case bitc::METADATA_LEXICAL_BLOCK: {
2221 if (Record.size() != 5)
2222 return error("Invalid record");
2224 MDValueList.assignValue(
2225 GET_OR_DISTINCT(DILexicalBlock, Record[0],
2226 (Context, getMDOrNull(Record[1]),
2227 getMDOrNull(Record[2]), Record[3], Record[4])),
2231 case bitc::METADATA_LEXICAL_BLOCK_FILE: {
2232 if (Record.size() != 4)
2233 return error("Invalid record");
2235 MDValueList.assignValue(
2236 GET_OR_DISTINCT(DILexicalBlockFile, Record[0],
2237 (Context, getMDOrNull(Record[1]),
2238 getMDOrNull(Record[2]), Record[3])),
2242 case bitc::METADATA_NAMESPACE: {
2243 if (Record.size() != 5)
2244 return error("Invalid record");
2246 MDValueList.assignValue(
2247 GET_OR_DISTINCT(DINamespace, Record[0],
2248 (Context, getMDOrNull(Record[1]),
2249 getMDOrNull(Record[2]), getMDString(Record[3]),
2254 case bitc::METADATA_TEMPLATE_TYPE: {
2255 if (Record.size() != 3)
2256 return error("Invalid record");
2258 MDValueList.assignValue(GET_OR_DISTINCT(DITemplateTypeParameter,
2260 (Context, getMDString(Record[1]),
2261 getMDOrNull(Record[2]))),
2265 case bitc::METADATA_TEMPLATE_VALUE: {
2266 if (Record.size() != 5)
2267 return error("Invalid record");
2269 MDValueList.assignValue(
2270 GET_OR_DISTINCT(DITemplateValueParameter, Record[0],
2271 (Context, Record[1], getMDString(Record[2]),
2272 getMDOrNull(Record[3]), getMDOrNull(Record[4]))),
2276 case bitc::METADATA_GLOBAL_VAR: {
2277 if (Record.size() != 11)
2278 return error("Invalid record");
2280 MDValueList.assignValue(
2281 GET_OR_DISTINCT(DIGlobalVariable, Record[0],
2282 (Context, getMDOrNull(Record[1]),
2283 getMDString(Record[2]), getMDString(Record[3]),
2284 getMDOrNull(Record[4]), Record[5],
2285 getMDOrNull(Record[6]), Record[7], Record[8],
2286 getMDOrNull(Record[9]), getMDOrNull(Record[10]))),
2290 case bitc::METADATA_LOCAL_VAR: {
2291 // 10th field is for the obseleted 'inlinedAt:' field.
2292 if (Record.size() < 8 || Record.size() > 10)
2293 return error("Invalid record");
2295 // 2nd field used to be an artificial tag, either DW_TAG_auto_variable or
2296 // DW_TAG_arg_variable.
2297 bool HasTag = Record.size() > 8;
2298 MDValueList.assignValue(
2299 GET_OR_DISTINCT(DILocalVariable, Record[0],
2300 (Context, getMDOrNull(Record[1 + HasTag]),
2301 getMDString(Record[2 + HasTag]),
2302 getMDOrNull(Record[3 + HasTag]), Record[4 + HasTag],
2303 getMDOrNull(Record[5 + HasTag]), Record[6 + HasTag],
2304 Record[7 + HasTag])),
2308 case bitc::METADATA_EXPRESSION: {
2309 if (Record.size() < 1)
2310 return error("Invalid record");
2312 MDValueList.assignValue(
2313 GET_OR_DISTINCT(DIExpression, Record[0],
2314 (Context, makeArrayRef(Record).slice(1))),
2318 case bitc::METADATA_OBJC_PROPERTY: {
2319 if (Record.size() != 8)
2320 return error("Invalid record");
2322 MDValueList.assignValue(
2323 GET_OR_DISTINCT(DIObjCProperty, Record[0],
2324 (Context, getMDString(Record[1]),
2325 getMDOrNull(Record[2]), Record[3],
2326 getMDString(Record[4]), getMDString(Record[5]),
2327 Record[6], getMDOrNull(Record[7]))),
2331 case bitc::METADATA_IMPORTED_ENTITY: {
2332 if (Record.size() != 6)
2333 return error("Invalid record");
2335 MDValueList.assignValue(
2336 GET_OR_DISTINCT(DIImportedEntity, Record[0],
2337 (Context, Record[1], getMDOrNull(Record[2]),
2338 getMDOrNull(Record[3]), Record[4],
2339 getMDString(Record[5]))),
2343 case bitc::METADATA_STRING: {
2344 std::string String(Record.begin(), Record.end());
2345 llvm::UpgradeMDStringConstant(String);
2346 Metadata *MD = MDString::get(Context, String);
2347 MDValueList.assignValue(MD, NextMDValueNo++);
2350 case bitc::METADATA_KIND: {
2351 if (Record.size() < 2)
2352 return error("Invalid record");
2354 unsigned Kind = Record[0];
2355 SmallString<8> Name(Record.begin()+1, Record.end());
2357 unsigned NewKind = TheModule->getMDKindID(Name.str());
2358 if (!MDKindMap.insert(std::make_pair(Kind, NewKind)).second)
2359 return error("Conflicting METADATA_KIND records");
2364 #undef GET_OR_DISTINCT
2367 /// Decode a signed value stored with the sign bit in the LSB for dense VBR
2369 uint64_t BitcodeReader::decodeSignRotatedValue(uint64_t V) {
2374 // There is no such thing as -0 with integers. "-0" really means MININT.
2378 /// Resolve all of the initializers for global values and aliases that we can.
2379 std::error_code BitcodeReader::resolveGlobalAndAliasInits() {
2380 std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInitWorklist;
2381 std::vector<std::pair<GlobalAlias*, unsigned> > AliasInitWorklist;
2382 std::vector<std::pair<Function*, unsigned> > FunctionPrefixWorklist;
2383 std::vector<std::pair<Function*, unsigned> > FunctionPrologueWorklist;
2384 std::vector<std::pair<Function*, unsigned> > FunctionPersonalityFnWorklist;
2386 GlobalInitWorklist.swap(GlobalInits);
2387 AliasInitWorklist.swap(AliasInits);
2388 FunctionPrefixWorklist.swap(FunctionPrefixes);
2389 FunctionPrologueWorklist.swap(FunctionPrologues);
2390 FunctionPersonalityFnWorklist.swap(FunctionPersonalityFns);
2392 while (!GlobalInitWorklist.empty()) {
2393 unsigned ValID = GlobalInitWorklist.back().second;
2394 if (ValID >= ValueList.size()) {
2395 // Not ready to resolve this yet, it requires something later in the file.
2396 GlobalInits.push_back(GlobalInitWorklist.back());
2398 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
2399 GlobalInitWorklist.back().first->setInitializer(C);
2401 return error("Expected a constant");
2403 GlobalInitWorklist.pop_back();
2406 while (!AliasInitWorklist.empty()) {
2407 unsigned ValID = AliasInitWorklist.back().second;
2408 if (ValID >= ValueList.size()) {
2409 AliasInits.push_back(AliasInitWorklist.back());
2411 Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]);
2413 return error("Expected a constant");
2414 GlobalAlias *Alias = AliasInitWorklist.back().first;
2415 if (C->getType() != Alias->getType())
2416 return error("Alias and aliasee types don't match");
2417 Alias->setAliasee(C);
2419 AliasInitWorklist.pop_back();
2422 while (!FunctionPrefixWorklist.empty()) {
2423 unsigned ValID = FunctionPrefixWorklist.back().second;
2424 if (ValID >= ValueList.size()) {
2425 FunctionPrefixes.push_back(FunctionPrefixWorklist.back());
2427 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
2428 FunctionPrefixWorklist.back().first->setPrefixData(C);
2430 return error("Expected a constant");
2432 FunctionPrefixWorklist.pop_back();
2435 while (!FunctionPrologueWorklist.empty()) {
2436 unsigned ValID = FunctionPrologueWorklist.back().second;
2437 if (ValID >= ValueList.size()) {
2438 FunctionPrologues.push_back(FunctionPrologueWorklist.back());
2440 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
2441 FunctionPrologueWorklist.back().first->setPrologueData(C);
2443 return error("Expected a constant");
2445 FunctionPrologueWorklist.pop_back();
2448 while (!FunctionPersonalityFnWorklist.empty()) {
2449 unsigned ValID = FunctionPersonalityFnWorklist.back().second;
2450 if (ValID >= ValueList.size()) {
2451 FunctionPersonalityFns.push_back(FunctionPersonalityFnWorklist.back());
2453 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
2454 FunctionPersonalityFnWorklist.back().first->setPersonalityFn(C);
2456 return error("Expected a constant");
2458 FunctionPersonalityFnWorklist.pop_back();
2461 return std::error_code();
2464 static APInt readWideAPInt(ArrayRef<uint64_t> Vals, unsigned TypeBits) {
2465 SmallVector<uint64_t, 8> Words(Vals.size());
2466 std::transform(Vals.begin(), Vals.end(), Words.begin(),
2467 BitcodeReader::decodeSignRotatedValue);
2469 return APInt(TypeBits, Words);
2472 std::error_code BitcodeReader::parseConstants() {
2473 if (Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID))
2474 return error("Invalid record");
2476 SmallVector<uint64_t, 64> Record;
2478 // Read all the records for this value table.
2479 Type *CurTy = Type::getInt32Ty(Context);
2480 unsigned NextCstNo = ValueList.size();
2482 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
2484 switch (Entry.Kind) {
2485 case BitstreamEntry::SubBlock: // Handled for us already.
2486 case BitstreamEntry::Error:
2487 return error("Malformed block");
2488 case BitstreamEntry::EndBlock:
2489 if (NextCstNo != ValueList.size())
2490 return error("Invalid ronstant reference");
2492 // Once all the constants have been read, go through and resolve forward
2494 ValueList.resolveConstantForwardRefs();
2495 return std::error_code();
2496 case BitstreamEntry::Record:
2497 // The interesting case.
2504 unsigned BitCode = Stream.readRecord(Entry.ID, Record);
2506 default: // Default behavior: unknown constant
2507 case bitc::CST_CODE_UNDEF: // UNDEF
2508 V = UndefValue::get(CurTy);
2510 case bitc::CST_CODE_SETTYPE: // SETTYPE: [typeid]
2512 return error("Invalid record");
2513 if (Record[0] >= TypeList.size() || !TypeList[Record[0]])
2514 return error("Invalid record");
2515 CurTy = TypeList[Record[0]];
2516 continue; // Skip the ValueList manipulation.
2517 case bitc::CST_CODE_NULL: // NULL
2518 V = Constant::getNullValue(CurTy);
2520 case bitc::CST_CODE_INTEGER: // INTEGER: [intval]
2521 if (!CurTy->isIntegerTy() || Record.empty())
2522 return error("Invalid record");
2523 V = ConstantInt::get(CurTy, decodeSignRotatedValue(Record[0]));
2525 case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval]
2526 if (!CurTy->isIntegerTy() || Record.empty())
2527 return error("Invalid record");
2530 readWideAPInt(Record, cast<IntegerType>(CurTy)->getBitWidth());
2531 V = ConstantInt::get(Context, VInt);
2535 case bitc::CST_CODE_FLOAT: { // FLOAT: [fpval]
2537 return error("Invalid record");
2538 if (CurTy->isHalfTy())
2539 V = ConstantFP::get(Context, APFloat(APFloat::IEEEhalf,
2540 APInt(16, (uint16_t)Record[0])));
2541 else if (CurTy->isFloatTy())
2542 V = ConstantFP::get(Context, APFloat(APFloat::IEEEsingle,
2543 APInt(32, (uint32_t)Record[0])));
2544 else if (CurTy->isDoubleTy())
2545 V = ConstantFP::get(Context, APFloat(APFloat::IEEEdouble,
2546 APInt(64, Record[0])));
2547 else if (CurTy->isX86_FP80Ty()) {
2548 // Bits are not stored the same way as a normal i80 APInt, compensate.
2549 uint64_t Rearrange[2];
2550 Rearrange[0] = (Record[1] & 0xffffLL) | (Record[0] << 16);
2551 Rearrange[1] = Record[0] >> 48;
2552 V = ConstantFP::get(Context, APFloat(APFloat::x87DoubleExtended,
2553 APInt(80, Rearrange)));
2554 } else if (CurTy->isFP128Ty())
2555 V = ConstantFP::get(Context, APFloat(APFloat::IEEEquad,
2556 APInt(128, Record)));
2557 else if (CurTy->isPPC_FP128Ty())
2558 V = ConstantFP::get(Context, APFloat(APFloat::PPCDoubleDouble,
2559 APInt(128, Record)));
2561 V = UndefValue::get(CurTy);
2565 case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number]
2567 return error("Invalid record");
2569 unsigned Size = Record.size();
2570 SmallVector<Constant*, 16> Elts;
2572 if (StructType *STy = dyn_cast<StructType>(CurTy)) {
2573 for (unsigned i = 0; i != Size; ++i)
2574 Elts.push_back(ValueList.getConstantFwdRef(Record[i],
2575 STy->getElementType(i)));
2576 V = ConstantStruct::get(STy, Elts);
2577 } else if (ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) {
2578 Type *EltTy = ATy->getElementType();
2579 for (unsigned i = 0; i != Size; ++i)
2580 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
2581 V = ConstantArray::get(ATy, Elts);
2582 } else if (VectorType *VTy = dyn_cast<VectorType>(CurTy)) {
2583 Type *EltTy = VTy->getElementType();
2584 for (unsigned i = 0; i != Size; ++i)
2585 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
2586 V = ConstantVector::get(Elts);
2588 V = UndefValue::get(CurTy);
2592 case bitc::CST_CODE_STRING: // STRING: [values]
2593 case bitc::CST_CODE_CSTRING: { // CSTRING: [values]
2595 return error("Invalid record");
2597 SmallString<16> Elts(Record.begin(), Record.end());
2598 V = ConstantDataArray::getString(Context, Elts,
2599 BitCode == bitc::CST_CODE_CSTRING);
2602 case bitc::CST_CODE_DATA: {// DATA: [n x value]
2604 return error("Invalid record");
2606 Type *EltTy = cast<SequentialType>(CurTy)->getElementType();
2607 unsigned Size = Record.size();
2609 if (EltTy->isIntegerTy(8)) {
2610 SmallVector<uint8_t, 16> Elts(Record.begin(), Record.end());
2611 if (isa<VectorType>(CurTy))
2612 V = ConstantDataVector::get(Context, Elts);
2614 V = ConstantDataArray::get(Context, Elts);
2615 } else if (EltTy->isIntegerTy(16)) {
2616 SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end());
2617 if (isa<VectorType>(CurTy))
2618 V = ConstantDataVector::get(Context, Elts);
2620 V = ConstantDataArray::get(Context, Elts);
2621 } else if (EltTy->isIntegerTy(32)) {
2622 SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end());
2623 if (isa<VectorType>(CurTy))
2624 V = ConstantDataVector::get(Context, Elts);
2626 V = ConstantDataArray::get(Context, Elts);
2627 } else if (EltTy->isIntegerTy(64)) {
2628 SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end());
2629 if (isa<VectorType>(CurTy))
2630 V = ConstantDataVector::get(Context, Elts);
2632 V = ConstantDataArray::get(Context, Elts);
2633 } else if (EltTy->isFloatTy()) {
2634 SmallVector<float, 16> Elts(Size);
2635 std::transform(Record.begin(), Record.end(), Elts.begin(), BitsToFloat);
2636 if (isa<VectorType>(CurTy))
2637 V = ConstantDataVector::get(Context, Elts);
2639 V = ConstantDataArray::get(Context, Elts);
2640 } else if (EltTy->isDoubleTy()) {
2641 SmallVector<double, 16> Elts(Size);
2642 std::transform(Record.begin(), Record.end(), Elts.begin(),
2644 if (isa<VectorType>(CurTy))
2645 V = ConstantDataVector::get(Context, Elts);
2647 V = ConstantDataArray::get(Context, Elts);
2649 return error("Invalid type for value");
2654 case bitc::CST_CODE_CE_BINOP: { // CE_BINOP: [opcode, opval, opval]
2655 if (Record.size() < 3)
2656 return error("Invalid record");
2657 int Opc = getDecodedBinaryOpcode(Record[0], CurTy);
2659 V = UndefValue::get(CurTy); // Unknown binop.
2661 Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy);
2662 Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy);
2664 if (Record.size() >= 4) {
2665 if (Opc == Instruction::Add ||
2666 Opc == Instruction::Sub ||
2667 Opc == Instruction::Mul ||
2668 Opc == Instruction::Shl) {
2669 if (Record[3] & (1 << bitc::OBO_NO_SIGNED_WRAP))
2670 Flags |= OverflowingBinaryOperator::NoSignedWrap;
2671 if (Record[3] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
2672 Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
2673 } else if (Opc == Instruction::SDiv ||
2674 Opc == Instruction::UDiv ||
2675 Opc == Instruction::LShr ||
2676 Opc == Instruction::AShr) {
2677 if (Record[3] & (1 << bitc::PEO_EXACT))
2678 Flags |= SDivOperator::IsExact;
2681 V = ConstantExpr::get(Opc, LHS, RHS, Flags);
2685 case bitc::CST_CODE_CE_CAST: { // CE_CAST: [opcode, opty, opval]
2686 if (Record.size() < 3)
2687 return error("Invalid record");
2688 int Opc = getDecodedCastOpcode(Record[0]);
2690 V = UndefValue::get(CurTy); // Unknown cast.
2692 Type *OpTy = getTypeByID(Record[1]);
2694 return error("Invalid record");
2695 Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy);
2696 V = UpgradeBitCastExpr(Opc, Op, CurTy);
2697 if (!V) V = ConstantExpr::getCast(Opc, Op, CurTy);
2701 case bitc::CST_CODE_CE_INBOUNDS_GEP:
2702 case bitc::CST_CODE_CE_GEP: { // CE_GEP: [n x operands]
2704 Type *PointeeType = nullptr;
2705 if (Record.size() % 2)
2706 PointeeType = getTypeByID(Record[OpNum++]);
2707 SmallVector<Constant*, 16> Elts;
2708 while (OpNum != Record.size()) {
2709 Type *ElTy = getTypeByID(Record[OpNum++]);
2711 return error("Invalid record");
2712 Elts.push_back(ValueList.getConstantFwdRef(Record[OpNum++], ElTy));
2717 cast<SequentialType>(Elts[0]->getType()->getScalarType())
2719 return error("Explicit gep operator type does not match pointee type "
2720 "of pointer operand");
2722 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
2723 V = ConstantExpr::getGetElementPtr(PointeeType, Elts[0], Indices,
2725 bitc::CST_CODE_CE_INBOUNDS_GEP);
2728 case bitc::CST_CODE_CE_SELECT: { // CE_SELECT: [opval#, opval#, opval#]
2729 if (Record.size() < 3)
2730 return error("Invalid record");
2732 Type *SelectorTy = Type::getInt1Ty(Context);
2734 // The selector might be an i1 or an <n x i1>
2735 // Get the type from the ValueList before getting a forward ref.
2736 if (VectorType *VTy = dyn_cast<VectorType>(CurTy))
2737 if (Value *V = ValueList[Record[0]])
2738 if (SelectorTy != V->getType())
2739 SelectorTy = VectorType::get(SelectorTy, VTy->getNumElements());
2741 V = ConstantExpr::getSelect(ValueList.getConstantFwdRef(Record[0],
2743 ValueList.getConstantFwdRef(Record[1],CurTy),
2744 ValueList.getConstantFwdRef(Record[2],CurTy));
2747 case bitc::CST_CODE_CE_EXTRACTELT
2748 : { // CE_EXTRACTELT: [opty, opval, opty, opval]
2749 if (Record.size() < 3)
2750 return error("Invalid record");
2752 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
2754 return error("Invalid record");
2755 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
2756 Constant *Op1 = nullptr;
2757 if (Record.size() == 4) {
2758 Type *IdxTy = getTypeByID(Record[2]);
2760 return error("Invalid record");
2761 Op1 = ValueList.getConstantFwdRef(Record[3], IdxTy);
2762 } else // TODO: Remove with llvm 4.0
2763 Op1 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
2765 return error("Invalid record");
2766 V = ConstantExpr::getExtractElement(Op0, Op1);
2769 case bitc::CST_CODE_CE_INSERTELT
2770 : { // CE_INSERTELT: [opval, opval, opty, opval]
2771 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
2772 if (Record.size() < 3 || !OpTy)
2773 return error("Invalid record");
2774 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
2775 Constant *Op1 = ValueList.getConstantFwdRef(Record[1],
2776 OpTy->getElementType());
2777 Constant *Op2 = nullptr;
2778 if (Record.size() == 4) {
2779 Type *IdxTy = getTypeByID(Record[2]);
2781 return error("Invalid record");
2782 Op2 = ValueList.getConstantFwdRef(Record[3], IdxTy);
2783 } else // TODO: Remove with llvm 4.0
2784 Op2 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
2786 return error("Invalid record");
2787 V = ConstantExpr::getInsertElement(Op0, Op1, Op2);
2790 case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval]
2791 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
2792 if (Record.size() < 3 || !OpTy)
2793 return error("Invalid record");
2794 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
2795 Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy);
2796 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
2797 OpTy->getNumElements());
2798 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy);
2799 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
2802 case bitc::CST_CODE_CE_SHUFVEC_EX: { // [opty, opval, opval, opval]
2803 VectorType *RTy = dyn_cast<VectorType>(CurTy);
2805 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
2806 if (Record.size() < 4 || !RTy || !OpTy)
2807 return error("Invalid record");
2808 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
2809 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
2810 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
2811 RTy->getNumElements());
2812 Constant *Op2 = ValueList.getConstantFwdRef(Record[3], ShufTy);
2813 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
2816 case bitc::CST_CODE_CE_CMP: { // CE_CMP: [opty, opval, opval, pred]
2817 if (Record.size() < 4)
2818 return error("Invalid record");
2819 Type *OpTy = getTypeByID(Record[0]);
2821 return error("Invalid record");
2822 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
2823 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
2825 if (OpTy->isFPOrFPVectorTy())
2826 V = ConstantExpr::getFCmp(Record[3], Op0, Op1);
2828 V = ConstantExpr::getICmp(Record[3], Op0, Op1);
2831 // This maintains backward compatibility, pre-asm dialect keywords.
2832 // FIXME: Remove with the 4.0 release.
2833 case bitc::CST_CODE_INLINEASM_OLD: {
2834 if (Record.size() < 2)
2835 return error("Invalid record");
2836 std::string AsmStr, ConstrStr;
2837 bool HasSideEffects = Record[0] & 1;
2838 bool IsAlignStack = Record[0] >> 1;
2839 unsigned AsmStrSize = Record[1];
2840 if (2+AsmStrSize >= Record.size())
2841 return error("Invalid record");
2842 unsigned ConstStrSize = Record[2+AsmStrSize];
2843 if (3+AsmStrSize+ConstStrSize > Record.size())
2844 return error("Invalid record");
2846 for (unsigned i = 0; i != AsmStrSize; ++i)
2847 AsmStr += (char)Record[2+i];
2848 for (unsigned i = 0; i != ConstStrSize; ++i)
2849 ConstrStr += (char)Record[3+AsmStrSize+i];
2850 PointerType *PTy = cast<PointerType>(CurTy);
2851 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
2852 AsmStr, ConstrStr, HasSideEffects, IsAlignStack);
2855 // This version adds support for the asm dialect keywords (e.g.,
2857 case bitc::CST_CODE_INLINEASM: {
2858 if (Record.size() < 2)
2859 return error("Invalid record");
2860 std::string AsmStr, ConstrStr;
2861 bool HasSideEffects = Record[0] & 1;
2862 bool IsAlignStack = (Record[0] >> 1) & 1;
2863 unsigned AsmDialect = Record[0] >> 2;
2864 unsigned AsmStrSize = Record[1];
2865 if (2+AsmStrSize >= Record.size())
2866 return error("Invalid record");
2867 unsigned ConstStrSize = Record[2+AsmStrSize];
2868 if (3+AsmStrSize+ConstStrSize > Record.size())
2869 return error("Invalid record");
2871 for (unsigned i = 0; i != AsmStrSize; ++i)
2872 AsmStr += (char)Record[2+i];
2873 for (unsigned i = 0; i != ConstStrSize; ++i)
2874 ConstrStr += (char)Record[3+AsmStrSize+i];
2875 PointerType *PTy = cast<PointerType>(CurTy);
2876 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
2877 AsmStr, ConstrStr, HasSideEffects, IsAlignStack,
2878 InlineAsm::AsmDialect(AsmDialect));
2881 case bitc::CST_CODE_BLOCKADDRESS:{
2882 if (Record.size() < 3)
2883 return error("Invalid record");
2884 Type *FnTy = getTypeByID(Record[0]);
2886 return error("Invalid record");
2888 dyn_cast_or_null<Function>(ValueList.getConstantFwdRef(Record[1],FnTy));
2890 return error("Invalid record");
2892 // Don't let Fn get dematerialized.
2893 BlockAddressesTaken.insert(Fn);
2895 // If the function is already parsed we can insert the block address right
2898 unsigned BBID = Record[2];
2900 // Invalid reference to entry block.
2901 return error("Invalid ID");
2903 Function::iterator BBI = Fn->begin(), BBE = Fn->end();
2904 for (size_t I = 0, E = BBID; I != E; ++I) {
2906 return error("Invalid ID");
2911 // Otherwise insert a placeholder and remember it so it can be inserted
2912 // when the function is parsed.
2913 auto &FwdBBs = BasicBlockFwdRefs[Fn];
2915 BasicBlockFwdRefQueue.push_back(Fn);
2916 if (FwdBBs.size() < BBID + 1)
2917 FwdBBs.resize(BBID + 1);
2919 FwdBBs[BBID] = BasicBlock::Create(Context);
2922 V = BlockAddress::get(Fn, BB);
2927 if (ValueList.assignValue(V, NextCstNo))
2928 return error("Invalid forward reference");
2933 std::error_code BitcodeReader::parseUseLists() {
2934 if (Stream.EnterSubBlock(bitc::USELIST_BLOCK_ID))
2935 return error("Invalid record");
2937 // Read all the records.
2938 SmallVector<uint64_t, 64> Record;
2940 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
2942 switch (Entry.Kind) {
2943 case BitstreamEntry::SubBlock: // Handled for us already.
2944 case BitstreamEntry::Error:
2945 return error("Malformed block");
2946 case BitstreamEntry::EndBlock:
2947 return std::error_code();
2948 case BitstreamEntry::Record:
2949 // The interesting case.
2953 // Read a use list record.
2956 switch (Stream.readRecord(Entry.ID, Record)) {
2957 default: // Default behavior: unknown type.
2959 case bitc::USELIST_CODE_BB:
2962 case bitc::USELIST_CODE_DEFAULT: {
2963 unsigned RecordLength = Record.size();
2964 if (RecordLength < 3)
2965 // Records should have at least an ID and two indexes.
2966 return error("Invalid record");
2967 unsigned ID = Record.back();
2972 assert(ID < FunctionBBs.size() && "Basic block not found");
2973 V = FunctionBBs[ID];
2976 unsigned NumUses = 0;
2977 SmallDenseMap<const Use *, unsigned, 16> Order;
2978 for (const Use &U : V->uses()) {
2979 if (++NumUses > Record.size())
2981 Order[&U] = Record[NumUses - 1];
2983 if (Order.size() != Record.size() || NumUses > Record.size())
2984 // Mismatches can happen if the functions are being materialized lazily
2985 // (out-of-order), or a value has been upgraded.
2988 V->sortUseList([&](const Use &L, const Use &R) {
2989 return Order.lookup(&L) < Order.lookup(&R);
2997 /// When we see the block for metadata, remember where it is and then skip it.
2998 /// This lets us lazily deserialize the metadata.
2999 std::error_code BitcodeReader::rememberAndSkipMetadata() {
3000 // Save the current stream state.
3001 uint64_t CurBit = Stream.GetCurrentBitNo();
3002 DeferredMetadataInfo.push_back(CurBit);
3004 // Skip over the block for now.
3005 if (Stream.SkipBlock())
3006 return error("Invalid record");
3007 return std::error_code();
3010 std::error_code BitcodeReader::materializeMetadata() {
3011 for (uint64_t BitPos : DeferredMetadataInfo) {
3012 // Move the bit stream to the saved position.
3013 Stream.JumpToBit(BitPos);
3014 if (std::error_code EC = parseMetadata())
3017 DeferredMetadataInfo.clear();
3018 return std::error_code();
3021 void BitcodeReader::setStripDebugInfo() { StripDebugInfo = true; }
3023 /// When we see the block for a function body, remember where it is and then
3024 /// skip it. This lets us lazily deserialize the functions.
3025 std::error_code BitcodeReader::rememberAndSkipFunctionBody() {
3026 // Get the function we are talking about.
3027 if (FunctionsWithBodies.empty())
3028 return error("Insufficient function protos");
3030 Function *Fn = FunctionsWithBodies.back();
3031 FunctionsWithBodies.pop_back();
3033 // Save the current stream state.
3034 uint64_t CurBit = Stream.GetCurrentBitNo();
3036 (DeferredFunctionInfo[Fn] == 0 || DeferredFunctionInfo[Fn] == CurBit) &&
3037 "Mismatch between VST and scanned function offsets");
3038 DeferredFunctionInfo[Fn] = CurBit;
3040 // Skip over the function block for now.
3041 if (Stream.SkipBlock())
3042 return error("Invalid record");
3043 return std::error_code();
3046 std::error_code BitcodeReader::globalCleanup() {
3047 // Patch the initializers for globals and aliases up.
3048 resolveGlobalAndAliasInits();
3049 if (!GlobalInits.empty() || !AliasInits.empty())
3050 return error("Malformed global initializer set");
3052 // Look for intrinsic functions which need to be upgraded at some point
3053 for (Function &F : *TheModule) {
3055 if (UpgradeIntrinsicFunction(&F, NewFn))
3056 UpgradedIntrinsics[&F] = NewFn;
3059 // Look for global variables which need to be renamed.
3060 for (GlobalVariable &GV : TheModule->globals())
3061 UpgradeGlobalVariable(&GV);
3063 // Force deallocation of memory for these vectors to favor the client that
3064 // want lazy deserialization.
3065 std::vector<std::pair<GlobalVariable*, unsigned> >().swap(GlobalInits);
3066 std::vector<std::pair<GlobalAlias*, unsigned> >().swap(AliasInits);
3067 return std::error_code();
3070 /// Support for lazy parsing of function bodies. This is required if we
3071 /// either have an old bitcode file without a VST forward declaration record,
3072 /// or if we have an anonymous function being materialized, since anonymous
3073 /// functions do not have a name and are therefore not in the VST.
3074 std::error_code BitcodeReader::rememberAndSkipFunctionBodies() {
3075 Stream.JumpToBit(NextUnreadBit);
3077 if (Stream.AtEndOfStream())
3078 return error("Could not find function in stream");
3080 if (!SeenFirstFunctionBody)
3081 return error("Trying to materialize functions before seeing function blocks");
3083 // An old bitcode file with the symbol table at the end would have
3084 // finished the parse greedily.
3085 assert(SeenValueSymbolTable);
3087 SmallVector<uint64_t, 64> Record;
3090 BitstreamEntry Entry = Stream.advance();
3091 switch (Entry.Kind) {
3093 return error("Expect SubBlock");
3094 case BitstreamEntry::SubBlock:
3097 return error("Expect function block");
3098 case bitc::FUNCTION_BLOCK_ID:
3099 if (std::error_code EC = rememberAndSkipFunctionBody())
3101 NextUnreadBit = Stream.GetCurrentBitNo();
3102 return std::error_code();
3108 std::error_code BitcodeReader::parseBitcodeVersion() {
3109 if (Stream.EnterSubBlock(bitc::IDENTIFICATION_BLOCK_ID))
3110 return error("Invalid record");
3112 // Read all the records.
3113 SmallVector<uint64_t, 64> Record;
3115 BitstreamEntry Entry = Stream.advance();
3117 switch (Entry.Kind) {
3119 case BitstreamEntry::Error:
3120 return error("Malformed block");
3121 case BitstreamEntry::EndBlock:
3122 return std::error_code();
3123 case BitstreamEntry::Record:
3124 // The interesting case.
3130 unsigned BitCode = Stream.readRecord(Entry.ID, Record);
3132 default: // Default behavior: reject
3133 return error("Invalid value");
3134 case bitc::IDENTIFICATION_CODE_STRING: { // IDENTIFICATION: [strchr x
3136 convertToString(Record, 0, ProducerIdentification);
3139 case bitc::IDENTIFICATION_CODE_EPOCH: { // EPOCH: [epoch#]
3140 unsigned epoch = (unsigned)Record[0];
3141 if (epoch != bitc::BITCODE_CURRENT_EPOCH) {
3143 Twine("Incompatible epoch: Bitcode '") + Twine(epoch) +
3144 "' vs current: '" + Twine(bitc::BITCODE_CURRENT_EPOCH) + "'");
3151 std::error_code BitcodeReader::parseModule(uint64_t ResumeBit,
3152 bool ShouldLazyLoadMetadata) {
3154 Stream.JumpToBit(ResumeBit);
3155 else if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
3156 return error("Invalid record");
3158 SmallVector<uint64_t, 64> Record;
3159 std::vector<std::string> SectionTable;
3160 std::vector<std::string> GCTable;
3162 // Read all the records for this module.
3164 BitstreamEntry Entry = Stream.advance();
3166 switch (Entry.Kind) {
3167 case BitstreamEntry::Error:
3168 return error("Malformed block");
3169 case BitstreamEntry::EndBlock:
3170 return globalCleanup();
3172 case BitstreamEntry::SubBlock:
3174 default: // Skip unknown content.
3175 if (Stream.SkipBlock())
3176 return error("Invalid record");
3178 case bitc::BLOCKINFO_BLOCK_ID:
3179 if (Stream.ReadBlockInfoBlock())
3180 return error("Malformed block");
3182 case bitc::PARAMATTR_BLOCK_ID:
3183 if (std::error_code EC = parseAttributeBlock())
3186 case bitc::PARAMATTR_GROUP_BLOCK_ID:
3187 if (std::error_code EC = parseAttributeGroupBlock())
3190 case bitc::TYPE_BLOCK_ID_NEW:
3191 if (std::error_code EC = parseTypeTable())
3194 case bitc::VALUE_SYMTAB_BLOCK_ID:
3195 if (!SeenValueSymbolTable) {
3196 // Either this is an old form VST without function index and an
3197 // associated VST forward declaration record (which would have caused
3198 // the VST to be jumped to and parsed before it was encountered
3199 // normally in the stream), or there were no function blocks to
3200 // trigger an earlier parsing of the VST.
3201 assert(VSTOffset == 0 || FunctionsWithBodies.empty());
3202 if (std::error_code EC = parseValueSymbolTable())
3204 SeenValueSymbolTable = true;
3206 // We must have had a VST forward declaration record, which caused
3207 // the parser to jump to and parse the VST earlier.
3208 assert(VSTOffset > 0);
3209 if (Stream.SkipBlock())
3210 return error("Invalid record");
3213 case bitc::CONSTANTS_BLOCK_ID:
3214 if (std::error_code EC = parseConstants())
3216 if (std::error_code EC = resolveGlobalAndAliasInits())
3219 case bitc::METADATA_BLOCK_ID:
3220 if (ShouldLazyLoadMetadata && !IsMetadataMaterialized) {
3221 if (std::error_code EC = rememberAndSkipMetadata())
3225 assert(DeferredMetadataInfo.empty() && "Unexpected deferred metadata");
3226 if (std::error_code EC = parseMetadata())
3229 case bitc::FUNCTION_BLOCK_ID:
3230 // If this is the first function body we've seen, reverse the
3231 // FunctionsWithBodies list.
3232 if (!SeenFirstFunctionBody) {
3233 std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
3234 if (std::error_code EC = globalCleanup())
3236 SeenFirstFunctionBody = true;
3239 if (VSTOffset > 0) {
3240 // If we have a VST forward declaration record, make sure we
3241 // parse the VST now if we haven't already. It is needed to
3242 // set up the DeferredFunctionInfo vector for lazy reading.
3243 if (!SeenValueSymbolTable) {
3244 if (std::error_code EC =
3245 BitcodeReader::parseValueSymbolTable(VSTOffset))
3247 SeenValueSymbolTable = true;
3248 // Fall through so that we record the NextUnreadBit below.
3249 // This is necessary in case we have an anonymous function that
3250 // is later materialized. Since it will not have a VST entry we
3251 // need to fall back to the lazy parse to find its offset.
3253 // If we have a VST forward declaration record, but have already
3254 // parsed the VST (just above, when the first function body was
3255 // encountered here), then we are resuming the parse after
3256 // materializing functions. The ResumeBit points to the
3257 // start of the last function block recorded in the
3258 // DeferredFunctionInfo map. Skip it.
3259 if (Stream.SkipBlock())
3260 return error("Invalid record");
3265 // Support older bitcode files that did not have the function
3266 // index in the VST, nor a VST forward declaration record, as
3267 // well as anonymous functions that do not have VST entries.
3268 // Build the DeferredFunctionInfo vector on the fly.
3269 if (std::error_code EC = rememberAndSkipFunctionBody())
3272 // Suspend parsing when we reach the function bodies. Subsequent
3273 // materialization calls will resume it when necessary. If the bitcode
3274 // file is old, the symbol table will be at the end instead and will not
3275 // have been seen yet. In this case, just finish the parse now.
3276 if (SeenValueSymbolTable) {
3277 NextUnreadBit = Stream.GetCurrentBitNo();
3278 return std::error_code();
3281 case bitc::USELIST_BLOCK_ID:
3282 if (std::error_code EC = parseUseLists())
3285 case bitc::OPERAND_BUNDLE_TAGS_BLOCK_ID:
3286 if (std::error_code EC = parseOperandBundleTags())
3292 case BitstreamEntry::Record:
3293 // The interesting case.
3299 auto BitCode = Stream.readRecord(Entry.ID, Record);
3301 default: break; // Default behavior, ignore unknown content.
3302 case bitc::MODULE_CODE_VERSION: { // VERSION: [version#]
3303 if (Record.size() < 1)
3304 return error("Invalid record");
3305 // Only version #0 and #1 are supported so far.
3306 unsigned module_version = Record[0];
3307 switch (module_version) {
3309 return error("Invalid value");
3311 UseRelativeIDs = false;
3314 UseRelativeIDs = true;
3319 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
3321 if (convertToString(Record, 0, S))
3322 return error("Invalid record");
3323 TheModule->setTargetTriple(S);
3326 case bitc::MODULE_CODE_DATALAYOUT: { // DATALAYOUT: [strchr x N]
3328 if (convertToString(Record, 0, S))
3329 return error("Invalid record");
3330 TheModule->setDataLayout(S);
3333 case bitc::MODULE_CODE_ASM: { // ASM: [strchr x N]
3335 if (convertToString(Record, 0, S))
3336 return error("Invalid record");
3337 TheModule->setModuleInlineAsm(S);
3340 case bitc::MODULE_CODE_DEPLIB: { // DEPLIB: [strchr x N]
3341 // FIXME: Remove in 4.0.
3343 if (convertToString(Record, 0, S))
3344 return error("Invalid record");
3348 case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N]
3350 if (convertToString(Record, 0, S))
3351 return error("Invalid record");
3352 SectionTable.push_back(S);
3355 case bitc::MODULE_CODE_GCNAME: { // SECTIONNAME: [strchr x N]
3357 if (convertToString(Record, 0, S))
3358 return error("Invalid record");
3359 GCTable.push_back(S);
3362 case bitc::MODULE_CODE_COMDAT: { // COMDAT: [selection_kind, name]
3363 if (Record.size() < 2)
3364 return error("Invalid record");
3365 Comdat::SelectionKind SK = getDecodedComdatSelectionKind(Record[0]);
3366 unsigned ComdatNameSize = Record[1];
3367 std::string ComdatName;
3368 ComdatName.reserve(ComdatNameSize);
3369 for (unsigned i = 0; i != ComdatNameSize; ++i)
3370 ComdatName += (char)Record[2 + i];
3371 Comdat *C = TheModule->getOrInsertComdat(ComdatName);
3372 C->setSelectionKind(SK);
3373 ComdatList.push_back(C);
3376 // GLOBALVAR: [pointer type, isconst, initid,
3377 // linkage, alignment, section, visibility, threadlocal,
3378 // unnamed_addr, externally_initialized, dllstorageclass,
3380 case bitc::MODULE_CODE_GLOBALVAR: {
3381 if (Record.size() < 6)
3382 return error("Invalid record");
3383 Type *Ty = getTypeByID(Record[0]);
3385 return error("Invalid record");
3386 bool isConstant = Record[1] & 1;
3387 bool explicitType = Record[1] & 2;
3388 unsigned AddressSpace;
3390 AddressSpace = Record[1] >> 2;
3392 if (!Ty->isPointerTy())
3393 return error("Invalid type for value");
3394 AddressSpace = cast<PointerType>(Ty)->getAddressSpace();
3395 Ty = cast<PointerType>(Ty)->getElementType();
3398 uint64_t RawLinkage = Record[3];
3399 GlobalValue::LinkageTypes Linkage = getDecodedLinkage(RawLinkage);
3401 if (std::error_code EC = parseAlignmentValue(Record[4], Alignment))
3403 std::string Section;
3405 if (Record[5]-1 >= SectionTable.size())
3406 return error("Invalid ID");
3407 Section = SectionTable[Record[5]-1];
3409 GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;
3410 // Local linkage must have default visibility.
3411 if (Record.size() > 6 && !GlobalValue::isLocalLinkage(Linkage))
3412 // FIXME: Change to an error if non-default in 4.0.
3413 Visibility = getDecodedVisibility(Record[6]);
3415 GlobalVariable::ThreadLocalMode TLM = GlobalVariable::NotThreadLocal;
3416 if (Record.size() > 7)
3417 TLM = getDecodedThreadLocalMode(Record[7]);
3419 bool UnnamedAddr = false;
3420 if (Record.size() > 8)
3421 UnnamedAddr = Record[8];
3423 bool ExternallyInitialized = false;
3424 if (Record.size() > 9)
3425 ExternallyInitialized = Record[9];
3427 GlobalVariable *NewGV =
3428 new GlobalVariable(*TheModule, Ty, isConstant, Linkage, nullptr, "", nullptr,
3429 TLM, AddressSpace, ExternallyInitialized);
3430 NewGV->setAlignment(Alignment);
3431 if (!Section.empty())
3432 NewGV->setSection(Section);
3433 NewGV->setVisibility(Visibility);
3434 NewGV->setUnnamedAddr(UnnamedAddr);
3436 if (Record.size() > 10)
3437 NewGV->setDLLStorageClass(getDecodedDLLStorageClass(Record[10]));
3439 upgradeDLLImportExportLinkage(NewGV, RawLinkage);
3441 ValueList.push_back(NewGV);
3443 // Remember which value to use for the global initializer.
3444 if (unsigned InitID = Record[2])
3445 GlobalInits.push_back(std::make_pair(NewGV, InitID-1));
3447 if (Record.size() > 11) {
3448 if (unsigned ComdatID = Record[11]) {
3449 if (ComdatID > ComdatList.size())
3450 return error("Invalid global variable comdat ID");
3451 NewGV->setComdat(ComdatList[ComdatID - 1]);
3453 } else if (hasImplicitComdat(RawLinkage)) {
3454 NewGV->setComdat(reinterpret_cast<Comdat *>(1));
3458 // FUNCTION: [type, callingconv, isproto, linkage, paramattr,
3459 // alignment, section, visibility, gc, unnamed_addr,
3460 // prologuedata, dllstorageclass, comdat, prefixdata]
3461 case bitc::MODULE_CODE_FUNCTION: {
3462 if (Record.size() < 8)
3463 return error("Invalid record");
3464 Type *Ty = getTypeByID(Record[0]);
3466 return error("Invalid record");
3467 if (auto *PTy = dyn_cast<PointerType>(Ty))
3468 Ty = PTy->getElementType();
3469 auto *FTy = dyn_cast<FunctionType>(Ty);
3471 return error("Invalid type for value");
3472 auto CC = static_cast<CallingConv::ID>(Record[1]);
3473 if (CC & ~CallingConv::MaxID)
3474 return error("Invalid calling convention ID");
3476 Function *Func = Function::Create(FTy, GlobalValue::ExternalLinkage,
3479 Func->setCallingConv(CC);
3480 bool isProto = Record[2];
3481 uint64_t RawLinkage = Record[3];
3482 Func->setLinkage(getDecodedLinkage(RawLinkage));
3483 Func->setAttributes(getAttributes(Record[4]));
3486 if (std::error_code EC = parseAlignmentValue(Record[5], Alignment))
3488 Func->setAlignment(Alignment);
3490 if (Record[6]-1 >= SectionTable.size())
3491 return error("Invalid ID");
3492 Func->setSection(SectionTable[Record[6]-1]);
3494 // Local linkage must have default visibility.
3495 if (!Func->hasLocalLinkage())
3496 // FIXME: Change to an error if non-default in 4.0.
3497 Func->setVisibility(getDecodedVisibility(Record[7]));
3498 if (Record.size() > 8 && Record[8]) {
3499 if (Record[8]-1 >= GCTable.size())
3500 return error("Invalid ID");
3501 Func->setGC(GCTable[Record[8]-1].c_str());
3503 bool UnnamedAddr = false;
3504 if (Record.size() > 9)
3505 UnnamedAddr = Record[9];
3506 Func->setUnnamedAddr(UnnamedAddr);
3507 if (Record.size() > 10 && Record[10] != 0)
3508 FunctionPrologues.push_back(std::make_pair(Func, Record[10]-1));
3510 if (Record.size() > 11)
3511 Func->setDLLStorageClass(getDecodedDLLStorageClass(Record[11]));
3513 upgradeDLLImportExportLinkage(Func, RawLinkage);
3515 if (Record.size() > 12) {
3516 if (unsigned ComdatID = Record[12]) {
3517 if (ComdatID > ComdatList.size())
3518 return error("Invalid function comdat ID");
3519 Func->setComdat(ComdatList[ComdatID - 1]);
3521 } else if (hasImplicitComdat(RawLinkage)) {
3522 Func->setComdat(reinterpret_cast<Comdat *>(1));
3525 if (Record.size() > 13 && Record[13] != 0)
3526 FunctionPrefixes.push_back(std::make_pair(Func, Record[13]-1));
3528 if (Record.size() > 14 && Record[14] != 0)
3529 FunctionPersonalityFns.push_back(std::make_pair(Func, Record[14] - 1));
3531 ValueList.push_back(Func);
3533 // If this is a function with a body, remember the prototype we are
3534 // creating now, so that we can match up the body with them later.
3536 Func->setIsMaterializable(true);
3537 FunctionsWithBodies.push_back(Func);
3538 DeferredFunctionInfo[Func] = 0;
3542 // ALIAS: [alias type, addrspace, aliasee val#, linkage]
3543 // ALIAS: [alias type, addrspace, aliasee val#, linkage, visibility, dllstorageclass]
3544 case bitc::MODULE_CODE_ALIAS:
3545 case bitc::MODULE_CODE_ALIAS_OLD: {
3546 bool NewRecord = BitCode == bitc::MODULE_CODE_ALIAS;
3547 if (Record.size() < (3 + (unsigned)NewRecord))
3548 return error("Invalid record");
3550 Type *Ty = getTypeByID(Record[OpNum++]);
3552 return error("Invalid record");
3556 auto *PTy = dyn_cast<PointerType>(Ty);
3558 return error("Invalid type for value");
3559 Ty = PTy->getElementType();
3560 AddrSpace = PTy->getAddressSpace();
3562 AddrSpace = Record[OpNum++];
3565 auto Val = Record[OpNum++];
3566 auto Linkage = Record[OpNum++];
3567 auto *NewGA = GlobalAlias::create(
3568 Ty, AddrSpace, getDecodedLinkage(Linkage), "", TheModule);
3569 // Old bitcode files didn't have visibility field.
3570 // Local linkage must have default visibility.
3571 if (OpNum != Record.size()) {
3572 auto VisInd = OpNum++;
3573 if (!NewGA->hasLocalLinkage())
3574 // FIXME: Change to an error if non-default in 4.0.
3575 NewGA->setVisibility(getDecodedVisibility(Record[VisInd]));
3577 if (OpNum != Record.size())
3578 NewGA->setDLLStorageClass(getDecodedDLLStorageClass(Record[OpNum++]));
3580 upgradeDLLImportExportLinkage(NewGA, Linkage);
3581 if (OpNum != Record.size())
3582 NewGA->setThreadLocalMode(getDecodedThreadLocalMode(Record[OpNum++]));
3583 if (OpNum != Record.size())
3584 NewGA->setUnnamedAddr(Record[OpNum++]);
3585 ValueList.push_back(NewGA);
3586 AliasInits.push_back(std::make_pair(NewGA, Val));
3589 /// MODULE_CODE_PURGEVALS: [numvals]
3590 case bitc::MODULE_CODE_PURGEVALS:
3591 // Trim down the value list to the specified size.
3592 if (Record.size() < 1 || Record[0] > ValueList.size())
3593 return error("Invalid record");
3594 ValueList.shrinkTo(Record[0]);
3596 /// MODULE_CODE_VSTOFFSET: [offset]
3597 case bitc::MODULE_CODE_VSTOFFSET:
3598 if (Record.size() < 1)
3599 return error("Invalid record");
3600 VSTOffset = Record[0];
3607 /// Helper to read the header common to all bitcode files.
3608 static bool hasValidBitcodeHeader(BitstreamCursor &Stream) {
3609 // Sniff for the signature.
3610 if (Stream.Read(8) != 'B' ||
3611 Stream.Read(8) != 'C' ||
3612 Stream.Read(4) != 0x0 ||
3613 Stream.Read(4) != 0xC ||
3614 Stream.Read(4) != 0xE ||
3615 Stream.Read(4) != 0xD)
3621 BitcodeReader::parseBitcodeInto(std::unique_ptr<DataStreamer> Streamer,
3622 Module *M, bool ShouldLazyLoadMetadata) {
3625 if (std::error_code EC = initStream(std::move(Streamer)))
3628 // Sniff for the signature.
3629 if (!hasValidBitcodeHeader(Stream))
3630 return error("Invalid bitcode signature");
3632 // We expect a number of well-defined blocks, though we don't necessarily
3633 // need to understand them all.
3635 if (Stream.AtEndOfStream()) {
3636 // We didn't really read a proper Module.
3637 return error("Malformed IR file");
3640 BitstreamEntry Entry =
3641 Stream.advance(BitstreamCursor::AF_DontAutoprocessAbbrevs);
3643 if (Entry.Kind != BitstreamEntry::SubBlock)
3644 return error("Malformed block");
3646 if (Entry.ID == bitc::IDENTIFICATION_BLOCK_ID) {
3647 parseBitcodeVersion();
3651 if (Entry.ID == bitc::MODULE_BLOCK_ID)
3652 return parseModule(0, ShouldLazyLoadMetadata);
3654 if (Stream.SkipBlock())
3655 return error("Invalid record");
3659 ErrorOr<std::string> BitcodeReader::parseModuleTriple() {
3660 if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
3661 return error("Invalid record");
3663 SmallVector<uint64_t, 64> Record;
3666 // Read all the records for this module.
3668 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
3670 switch (Entry.Kind) {
3671 case BitstreamEntry::SubBlock: // Handled for us already.
3672 case BitstreamEntry::Error:
3673 return error("Malformed block");
3674 case BitstreamEntry::EndBlock:
3676 case BitstreamEntry::Record:
3677 // The interesting case.
3682 switch (Stream.readRecord(Entry.ID, Record)) {
3683 default: break; // Default behavior, ignore unknown content.
3684 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
3686 if (convertToString(Record, 0, S))
3687 return error("Invalid record");
3694 llvm_unreachable("Exit infinite loop");
3697 ErrorOr<std::string> BitcodeReader::parseTriple() {
3698 if (std::error_code EC = initStream(nullptr))
3701 // Sniff for the signature.
3702 if (!hasValidBitcodeHeader(Stream))
3703 return error("Invalid bitcode signature");
3705 // We expect a number of well-defined blocks, though we don't necessarily
3706 // need to understand them all.
3708 BitstreamEntry Entry = Stream.advance();
3710 switch (Entry.Kind) {
3711 case BitstreamEntry::Error:
3712 return error("Malformed block");
3713 case BitstreamEntry::EndBlock:
3714 return std::error_code();
3716 case BitstreamEntry::SubBlock:
3717 if (Entry.ID == bitc::MODULE_BLOCK_ID)
3718 return parseModuleTriple();
3720 // Ignore other sub-blocks.
3721 if (Stream.SkipBlock())
3722 return error("Malformed block");
3725 case BitstreamEntry::Record:
3726 Stream.skipRecord(Entry.ID);
3732 /// Parse metadata attachments.
3733 std::error_code BitcodeReader::parseMetadataAttachment(Function &F) {
3734 if (Stream.EnterSubBlock(bitc::METADATA_ATTACHMENT_ID))
3735 return error("Invalid record");
3737 SmallVector<uint64_t, 64> Record;
3739 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
3741 switch (Entry.Kind) {
3742 case BitstreamEntry::SubBlock: // Handled for us already.
3743 case BitstreamEntry::Error:
3744 return error("Malformed block");
3745 case BitstreamEntry::EndBlock:
3746 return std::error_code();
3747 case BitstreamEntry::Record:
3748 // The interesting case.
3752 // Read a metadata attachment record.
3754 switch (Stream.readRecord(Entry.ID, Record)) {
3755 default: // Default behavior: ignore.
3757 case bitc::METADATA_ATTACHMENT: {
3758 unsigned RecordLength = Record.size();
3760 return error("Invalid record");
3761 if (RecordLength % 2 == 0) {
3762 // A function attachment.
3763 for (unsigned I = 0; I != RecordLength; I += 2) {
3764 auto K = MDKindMap.find(Record[I]);
3765 if (K == MDKindMap.end())
3766 return error("Invalid ID");
3767 Metadata *MD = MDValueList.getValueFwdRef(Record[I + 1]);
3768 F.setMetadata(K->second, cast<MDNode>(MD));
3773 // An instruction attachment.
3774 Instruction *Inst = InstructionList[Record[0]];
3775 for (unsigned i = 1; i != RecordLength; i = i+2) {
3776 unsigned Kind = Record[i];
3777 DenseMap<unsigned, unsigned>::iterator I =
3778 MDKindMap.find(Kind);
3779 if (I == MDKindMap.end())
3780 return error("Invalid ID");
3781 Metadata *Node = MDValueList.getValueFwdRef(Record[i + 1]);
3782 if (isa<LocalAsMetadata>(Node))
3783 // Drop the attachment. This used to be legal, but there's no
3786 Inst->setMetadata(I->second, cast<MDNode>(Node));
3787 if (I->second == LLVMContext::MD_tbaa)
3788 InstsWithTBAATag.push_back(Inst);
3796 static std::error_code typeCheckLoadStoreInst(DiagnosticHandlerFunction DH,
3797 Type *ValType, Type *PtrType) {
3798 if (!isa<PointerType>(PtrType))
3799 return error(DH, "Load/Store operand is not a pointer type");
3800 Type *ElemType = cast<PointerType>(PtrType)->getElementType();
3802 if (ValType && ValType != ElemType)
3803 return error(DH, "Explicit load/store type does not match pointee type of "
3805 if (!PointerType::isLoadableOrStorableType(ElemType))
3806 return error(DH, "Cannot load/store from pointer");
3807 return std::error_code();
3810 /// Lazily parse the specified function body block.
3811 std::error_code BitcodeReader::parseFunctionBody(Function *F) {
3812 if (Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID))
3813 return error("Invalid record");
3815 InstructionList.clear();
3816 unsigned ModuleValueListSize = ValueList.size();
3817 unsigned ModuleMDValueListSize = MDValueList.size();
3819 // Add all the function arguments to the value table.
3820 for (Argument &I : F->args())
3821 ValueList.push_back(&I);
3823 unsigned NextValueNo = ValueList.size();
3824 BasicBlock *CurBB = nullptr;
3825 unsigned CurBBNo = 0;
3828 auto getLastInstruction = [&]() -> Instruction * {
3829 if (CurBB && !CurBB->empty())
3830 return &CurBB->back();
3831 else if (CurBBNo && FunctionBBs[CurBBNo - 1] &&
3832 !FunctionBBs[CurBBNo - 1]->empty())
3833 return &FunctionBBs[CurBBNo - 1]->back();
3837 std::vector<OperandBundleDef> OperandBundles;
3839 // Read all the records.
3840 SmallVector<uint64_t, 64> Record;
3842 BitstreamEntry Entry = Stream.advance();
3844 switch (Entry.Kind) {
3845 case BitstreamEntry::Error:
3846 return error("Malformed block");
3847 case BitstreamEntry::EndBlock:
3848 goto OutOfRecordLoop;
3850 case BitstreamEntry::SubBlock:
3852 default: // Skip unknown content.
3853 if (Stream.SkipBlock())
3854 return error("Invalid record");
3856 case bitc::CONSTANTS_BLOCK_ID:
3857 if (std::error_code EC = parseConstants())
3859 NextValueNo = ValueList.size();
3861 case bitc::VALUE_SYMTAB_BLOCK_ID:
3862 if (std::error_code EC = parseValueSymbolTable())
3865 case bitc::METADATA_ATTACHMENT_ID:
3866 if (std::error_code EC = parseMetadataAttachment(*F))
3869 case bitc::METADATA_BLOCK_ID:
3870 if (std::error_code EC = parseMetadata())
3873 case bitc::USELIST_BLOCK_ID:
3874 if (std::error_code EC = parseUseLists())
3880 case BitstreamEntry::Record:
3881 // The interesting case.
3887 Instruction *I = nullptr;
3888 unsigned BitCode = Stream.readRecord(Entry.ID, Record);
3890 default: // Default behavior: reject
3891 return error("Invalid value");
3892 case bitc::FUNC_CODE_DECLAREBLOCKS: { // DECLAREBLOCKS: [nblocks]
3893 if (Record.size() < 1 || Record[0] == 0)
3894 return error("Invalid record");
3895 // Create all the basic blocks for the function.
3896 FunctionBBs.resize(Record[0]);
3898 // See if anything took the address of blocks in this function.
3899 auto BBFRI = BasicBlockFwdRefs.find(F);
3900 if (BBFRI == BasicBlockFwdRefs.end()) {
3901 for (unsigned i = 0, e = FunctionBBs.size(); i != e; ++i)
3902 FunctionBBs[i] = BasicBlock::Create(Context, "", F);
3904 auto &BBRefs = BBFRI->second;
3905 // Check for invalid basic block references.
3906 if (BBRefs.size() > FunctionBBs.size())
3907 return error("Invalid ID");
3908 assert(!BBRefs.empty() && "Unexpected empty array");
3909 assert(!BBRefs.front() && "Invalid reference to entry block");
3910 for (unsigned I = 0, E = FunctionBBs.size(), RE = BBRefs.size(); I != E;
3912 if (I < RE && BBRefs[I]) {
3913 BBRefs[I]->insertInto(F);
3914 FunctionBBs[I] = BBRefs[I];
3916 FunctionBBs[I] = BasicBlock::Create(Context, "", F);
3919 // Erase from the table.
3920 BasicBlockFwdRefs.erase(BBFRI);
3923 CurBB = FunctionBBs[0];
3927 case bitc::FUNC_CODE_DEBUG_LOC_AGAIN: // DEBUG_LOC_AGAIN
3928 // This record indicates that the last instruction is at the same
3929 // location as the previous instruction with a location.
3930 I = getLastInstruction();
3933 return error("Invalid record");
3934 I->setDebugLoc(LastLoc);
3938 case bitc::FUNC_CODE_DEBUG_LOC: { // DEBUG_LOC: [line, col, scope, ia]
3939 I = getLastInstruction();
3940 if (!I || Record.size() < 4)
3941 return error("Invalid record");
3943 unsigned Line = Record[0], Col = Record[1];
3944 unsigned ScopeID = Record[2], IAID = Record[3];
3946 MDNode *Scope = nullptr, *IA = nullptr;
3947 if (ScopeID) Scope = cast<MDNode>(MDValueList.getValueFwdRef(ScopeID-1));
3948 if (IAID) IA = cast<MDNode>(MDValueList.getValueFwdRef(IAID-1));
3949 LastLoc = DebugLoc::get(Line, Col, Scope, IA);
3950 I->setDebugLoc(LastLoc);
3955 case bitc::FUNC_CODE_INST_BINOP: { // BINOP: [opval, ty, opval, opcode]
3958 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
3959 popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) ||
3960 OpNum+1 > Record.size())
3961 return error("Invalid record");
3963 int Opc = getDecodedBinaryOpcode(Record[OpNum++], LHS->getType());
3965 return error("Invalid record");
3966 I = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3967 InstructionList.push_back(I);
3968 if (OpNum < Record.size()) {
3969 if (Opc == Instruction::Add ||
3970 Opc == Instruction::Sub ||
3971 Opc == Instruction::Mul ||
3972 Opc == Instruction::Shl) {
3973 if (Record[OpNum] & (1 << bitc::OBO_NO_SIGNED_WRAP))
3974 cast<BinaryOperator>(I)->setHasNoSignedWrap(true);
3975 if (Record[OpNum] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
3976 cast<BinaryOperator>(I)->setHasNoUnsignedWrap(true);
3977 } else if (Opc == Instruction::SDiv ||
3978 Opc == Instruction::UDiv ||
3979 Opc == Instruction::LShr ||
3980 Opc == Instruction::AShr) {
3981 if (Record[OpNum] & (1 << bitc::PEO_EXACT))
3982 cast<BinaryOperator>(I)->setIsExact(true);
3983 } else if (isa<FPMathOperator>(I)) {
3984 FastMathFlags FMF = getDecodedFastMathFlags(Record[OpNum]);
3986 I->setFastMathFlags(FMF);
3992 case bitc::FUNC_CODE_INST_CAST: { // CAST: [opval, opty, destty, castopc]
3995 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
3996 OpNum+2 != Record.size())
3997 return error("Invalid record");
3999 Type *ResTy = getTypeByID(Record[OpNum]);
4000 int Opc = getDecodedCastOpcode(Record[OpNum + 1]);
4001 if (Opc == -1 || !ResTy)
4002 return error("Invalid record");
4003 Instruction *Temp = nullptr;
4004 if ((I = UpgradeBitCastInst(Opc, Op, ResTy, Temp))) {
4006 InstructionList.push_back(Temp);
4007 CurBB->getInstList().push_back(Temp);
4010 auto CastOp = (Instruction::CastOps)Opc;
4011 if (!CastInst::castIsValid(CastOp, Op, ResTy))
4012 return error("Invalid cast");
4013 I = CastInst::Create(CastOp, Op, ResTy);
4015 InstructionList.push_back(I);
4018 case bitc::FUNC_CODE_INST_INBOUNDS_GEP_OLD:
4019 case bitc::FUNC_CODE_INST_GEP_OLD:
4020 case bitc::FUNC_CODE_INST_GEP: { // GEP: type, [n x operands]
4026 if (BitCode == bitc::FUNC_CODE_INST_GEP) {
4027 InBounds = Record[OpNum++];
4028 Ty = getTypeByID(Record[OpNum++]);
4030 InBounds = BitCode == bitc::FUNC_CODE_INST_INBOUNDS_GEP_OLD;
4035 if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr))
4036 return error("Invalid record");
4039 Ty = cast<SequentialType>(BasePtr->getType()->getScalarType())
4042 cast<SequentialType>(BasePtr->getType()->getScalarType())
4045 "Explicit gep type does not match pointee type of pointer operand");
4047 SmallVector<Value*, 16> GEPIdx;
4048 while (OpNum != Record.size()) {
4050 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
4051 return error("Invalid record");
4052 GEPIdx.push_back(Op);
4055 I = GetElementPtrInst::Create(Ty, BasePtr, GEPIdx);
4057 InstructionList.push_back(I);
4059 cast<GetElementPtrInst>(I)->setIsInBounds(true);
4063 case bitc::FUNC_CODE_INST_EXTRACTVAL: {
4064 // EXTRACTVAL: [opty, opval, n x indices]
4067 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
4068 return error("Invalid record");
4070 unsigned RecSize = Record.size();
4071 if (OpNum == RecSize)
4072 return error("EXTRACTVAL: Invalid instruction with 0 indices");
4074 SmallVector<unsigned, 4> EXTRACTVALIdx;
4075 Type *CurTy = Agg->getType();
4076 for (; OpNum != RecSize; ++OpNum) {
4077 bool IsArray = CurTy->isArrayTy();
4078 bool IsStruct = CurTy->isStructTy();
4079 uint64_t Index = Record[OpNum];
4081 if (!IsStruct && !IsArray)
4082 return error("EXTRACTVAL: Invalid type");
4083 if ((unsigned)Index != Index)
4084 return error("Invalid value");
4085 if (IsStruct && Index >= CurTy->subtypes().size())
4086 return error("EXTRACTVAL: Invalid struct index");
4087 if (IsArray && Index >= CurTy->getArrayNumElements())
4088 return error("EXTRACTVAL: Invalid array index");
4089 EXTRACTVALIdx.push_back((unsigned)Index);
4092 CurTy = CurTy->subtypes()[Index];
4094 CurTy = CurTy->subtypes()[0];
4097 I = ExtractValueInst::Create(Agg, EXTRACTVALIdx);
4098 InstructionList.push_back(I);
4102 case bitc::FUNC_CODE_INST_INSERTVAL: {
4103 // INSERTVAL: [opty, opval, opty, opval, n x indices]
4106 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
4107 return error("Invalid record");
4109 if (getValueTypePair(Record, OpNum, NextValueNo, Val))
4110 return error("Invalid record");
4112 unsigned RecSize = Record.size();
4113 if (OpNum == RecSize)
4114 return error("INSERTVAL: Invalid instruction with 0 indices");
4116 SmallVector<unsigned, 4> INSERTVALIdx;
4117 Type *CurTy = Agg->getType();
4118 for (; OpNum != RecSize; ++OpNum) {
4119 bool IsArray = CurTy->isArrayTy();
4120 bool IsStruct = CurTy->isStructTy();
4121 uint64_t Index = Record[OpNum];
4123 if (!IsStruct && !IsArray)
4124 return error("INSERTVAL: Invalid type");
4125 if ((unsigned)Index != Index)
4126 return error("Invalid value");
4127 if (IsStruct && Index >= CurTy->subtypes().size())
4128 return error("INSERTVAL: Invalid struct index");
4129 if (IsArray && Index >= CurTy->getArrayNumElements())
4130 return error("INSERTVAL: Invalid array index");
4132 INSERTVALIdx.push_back((unsigned)Index);
4134 CurTy = CurTy->subtypes()[Index];
4136 CurTy = CurTy->subtypes()[0];
4139 if (CurTy != Val->getType())
4140 return error("Inserted value type doesn't match aggregate type");
4142 I = InsertValueInst::Create(Agg, Val, INSERTVALIdx);
4143 InstructionList.push_back(I);
4147 case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval]
4148 // obsolete form of select
4149 // handles select i1 ... in old bitcode
4151 Value *TrueVal, *FalseVal, *Cond;
4152 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
4153 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
4154 popValue(Record, OpNum, NextValueNo, Type::getInt1Ty(Context), Cond))
4155 return error("Invalid record");
4157 I = SelectInst::Create(Cond, TrueVal, FalseVal);
4158 InstructionList.push_back(I);
4162 case bitc::FUNC_CODE_INST_VSELECT: {// VSELECT: [ty,opval,opval,predty,pred]
4163 // new form of select
4164 // handles select i1 or select [N x i1]
4166 Value *TrueVal, *FalseVal, *Cond;
4167 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
4168 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
4169 getValueTypePair(Record, OpNum, NextValueNo, Cond))
4170 return error("Invalid record");
4172 // select condition can be either i1 or [N x i1]
4173 if (VectorType* vector_type =
4174 dyn_cast<VectorType>(Cond->getType())) {
4176 if (vector_type->getElementType() != Type::getInt1Ty(Context))
4177 return error("Invalid type for value");
4180 if (Cond->getType() != Type::getInt1Ty(Context))
4181 return error("Invalid type for value");
4184 I = SelectInst::Create(Cond, TrueVal, FalseVal);
4185 InstructionList.push_back(I);
4189 case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval]
4192 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
4193 getValueTypePair(Record, OpNum, NextValueNo, Idx))
4194 return error("Invalid record");
4195 if (!Vec->getType()->isVectorTy())
4196 return error("Invalid type for value");
4197 I = ExtractElementInst::Create(Vec, Idx);
4198 InstructionList.push_back(I);
4202 case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval]
4204 Value *Vec, *Elt, *Idx;
4205 if (getValueTypePair(Record, OpNum, NextValueNo, Vec))
4206 return error("Invalid record");
4207 if (!Vec->getType()->isVectorTy())
4208 return error("Invalid type for value");
4209 if (popValue(Record, OpNum, NextValueNo,
4210 cast<VectorType>(Vec->getType())->getElementType(), Elt) ||
4211 getValueTypePair(Record, OpNum, NextValueNo, Idx))
4212 return error("Invalid record");
4213 I = InsertElementInst::Create(Vec, Elt, Idx);
4214 InstructionList.push_back(I);
4218 case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval]
4220 Value *Vec1, *Vec2, *Mask;
4221 if (getValueTypePair(Record, OpNum, NextValueNo, Vec1) ||
4222 popValue(Record, OpNum, NextValueNo, Vec1->getType(), Vec2))
4223 return error("Invalid record");
4225 if (getValueTypePair(Record, OpNum, NextValueNo, Mask))
4226 return error("Invalid record");
4227 if (!Vec1->getType()->isVectorTy() || !Vec2->getType()->isVectorTy())
4228 return error("Invalid type for value");
4229 I = new ShuffleVectorInst(Vec1, Vec2, Mask);
4230 InstructionList.push_back(I);
4234 case bitc::FUNC_CODE_INST_CMP: // CMP: [opty, opval, opval, pred]
4235 // Old form of ICmp/FCmp returning bool
4236 // Existed to differentiate between icmp/fcmp and vicmp/vfcmp which were
4237 // both legal on vectors but had different behaviour.
4238 case bitc::FUNC_CODE_INST_CMP2: { // CMP2: [opty, opval, opval, pred]
4239 // FCmp/ICmp returning bool or vector of bool
4243 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
4244 popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS))
4245 return error("Invalid record");
4247 unsigned PredVal = Record[OpNum];
4248 bool IsFP = LHS->getType()->isFPOrFPVectorTy();
4250 if (IsFP && Record.size() > OpNum+1)
4251 FMF = getDecodedFastMathFlags(Record[++OpNum]);
4253 if (OpNum+1 != Record.size())
4254 return error("Invalid record");
4256 if (LHS->getType()->isFPOrFPVectorTy())
4257 I = new FCmpInst((FCmpInst::Predicate)PredVal, LHS, RHS);
4259 I = new ICmpInst((ICmpInst::Predicate)PredVal, LHS, RHS);
4262 I->setFastMathFlags(FMF);
4263 InstructionList.push_back(I);
4267 case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>]
4269 unsigned Size = Record.size();
4271 I = ReturnInst::Create(Context);
4272 InstructionList.push_back(I);
4277 Value *Op = nullptr;
4278 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
4279 return error("Invalid record");
4280 if (OpNum != Record.size())
4281 return error("Invalid record");
4283 I = ReturnInst::Create(Context, Op);
4284 InstructionList.push_back(I);
4287 case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#]
4288 if (Record.size() != 1 && Record.size() != 3)
4289 return error("Invalid record");
4290 BasicBlock *TrueDest = getBasicBlock(Record[0]);
4292 return error("Invalid record");
4294 if (Record.size() == 1) {
4295 I = BranchInst::Create(TrueDest);
4296 InstructionList.push_back(I);
4299 BasicBlock *FalseDest = getBasicBlock(Record[1]);
4300 Value *Cond = getValue(Record, 2, NextValueNo,
4301 Type::getInt1Ty(Context));
4302 if (!FalseDest || !Cond)
4303 return error("Invalid record");
4304 I = BranchInst::Create(TrueDest, FalseDest, Cond);
4305 InstructionList.push_back(I);
4309 case bitc::FUNC_CODE_INST_CLEANUPRET: { // CLEANUPRET: [val] or [val,bb#]
4310 if (Record.size() != 1 && Record.size() != 2)
4311 return error("Invalid record");
4313 Value *CleanupPad = getValue(Record, Idx++, NextValueNo,
4314 Type::getTokenTy(Context), OC_CleanupPad);
4316 return error("Invalid record");
4317 BasicBlock *UnwindDest = nullptr;
4318 if (Record.size() == 2) {
4319 UnwindDest = getBasicBlock(Record[Idx++]);
4321 return error("Invalid record");
4324 I = CleanupReturnInst::Create(cast<CleanupPadInst>(CleanupPad),
4326 InstructionList.push_back(I);
4329 case bitc::FUNC_CODE_INST_CATCHRET: { // CATCHRET: [val,bb#]
4330 if (Record.size() != 2)
4331 return error("Invalid record");
4333 Value *CatchPad = getValue(Record, Idx++, NextValueNo,
4334 Type::getTokenTy(Context), OC_CatchPad);
4336 return error("Invalid record");
4337 BasicBlock *BB = getBasicBlock(Record[Idx++]);
4339 return error("Invalid record");
4341 I = CatchReturnInst::Create(cast<CatchPadInst>(CatchPad), BB);
4342 InstructionList.push_back(I);
4345 case bitc::FUNC_CODE_INST_CATCHPAD: { // CATCHPAD: [bb#,bb#,num,(ty,val)*]
4346 if (Record.size() < 3)
4347 return error("Invalid record");
4349 BasicBlock *NormalBB = getBasicBlock(Record[Idx++]);
4351 return error("Invalid record");
4352 BasicBlock *UnwindBB = getBasicBlock(Record[Idx++]);
4354 return error("Invalid record");
4355 unsigned NumArgOperands = Record[Idx++];
4356 SmallVector<Value *, 2> Args;
4357 for (unsigned Op = 0; Op != NumArgOperands; ++Op) {
4359 if (getValueTypePair(Record, Idx, NextValueNo, Val))
4360 return error("Invalid record");
4361 Args.push_back(Val);
4363 if (Record.size() != Idx)
4364 return error("Invalid record");
4366 I = CatchPadInst::Create(NormalBB, UnwindBB, Args);
4367 InstructionList.push_back(I);
4370 case bitc::FUNC_CODE_INST_TERMINATEPAD: { // TERMINATEPAD: [bb#,num,(ty,val)*]
4371 if (Record.size() < 1)
4372 return error("Invalid record");
4374 bool HasUnwindDest = !!Record[Idx++];
4375 BasicBlock *UnwindDest = nullptr;
4376 if (HasUnwindDest) {
4377 if (Idx == Record.size())
4378 return error("Invalid record");
4379 UnwindDest = getBasicBlock(Record[Idx++]);
4381 return error("Invalid record");
4383 unsigned NumArgOperands = Record[Idx++];
4384 SmallVector<Value *, 2> Args;
4385 for (unsigned Op = 0; Op != NumArgOperands; ++Op) {
4387 if (getValueTypePair(Record, Idx, NextValueNo, Val))
4388 return error("Invalid record");
4389 Args.push_back(Val);
4391 if (Record.size() != Idx)
4392 return error("Invalid record");
4394 I = TerminatePadInst::Create(Context, UnwindDest, Args);
4395 InstructionList.push_back(I);
4398 case bitc::FUNC_CODE_INST_CLEANUPPAD: { // CLEANUPPAD: [num,(ty,val)*]
4399 if (Record.size() < 1)
4400 return error("Invalid record");
4402 unsigned NumArgOperands = Record[Idx++];
4403 SmallVector<Value *, 2> Args;
4404 for (unsigned Op = 0; Op != NumArgOperands; ++Op) {
4406 if (getValueTypePair(Record, Idx, NextValueNo, Val))
4407 return error("Invalid record");
4408 Args.push_back(Val);
4410 if (Record.size() != Idx)
4411 return error("Invalid record");
4413 I = CleanupPadInst::Create(Context, Args);
4414 InstructionList.push_back(I);
4417 case bitc::FUNC_CODE_INST_CATCHENDPAD: { // CATCHENDPADINST: [bb#] or []
4418 if (Record.size() > 1)
4419 return error("Invalid record");
4420 BasicBlock *BB = nullptr;
4421 if (Record.size() == 1) {
4422 BB = getBasicBlock(Record[0]);
4424 return error("Invalid record");
4426 I = CatchEndPadInst::Create(Context, BB);
4427 InstructionList.push_back(I);
4430 case bitc::FUNC_CODE_INST_CLEANUPENDPAD: { // CLEANUPENDPADINST: [val] or [val,bb#]
4431 if (Record.size() != 1 && Record.size() != 2)
4432 return error("Invalid record");
4434 Value *CleanupPad = getValue(Record, Idx++, NextValueNo,
4435 Type::getTokenTy(Context), OC_CleanupPad);
4437 return error("Invalid record");
4439 BasicBlock *BB = nullptr;
4440 if (Record.size() == 2) {
4441 BB = getBasicBlock(Record[Idx++]);
4443 return error("Invalid record");
4445 I = CleanupEndPadInst::Create(cast<CleanupPadInst>(CleanupPad), BB);
4446 InstructionList.push_back(I);
4449 case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, op0, op1, ...]
4451 if ((Record[0] >> 16) == SWITCH_INST_MAGIC) {
4452 // "New" SwitchInst format with case ranges. The changes to write this
4453 // format were reverted but we still recognize bitcode that uses it.
4454 // Hopefully someday we will have support for case ranges and can use
4455 // this format again.
4457 Type *OpTy = getTypeByID(Record[1]);
4458 unsigned ValueBitWidth = cast<IntegerType>(OpTy)->getBitWidth();
4460 Value *Cond = getValue(Record, 2, NextValueNo, OpTy);
4461 BasicBlock *Default = getBasicBlock(Record[3]);
4462 if (!OpTy || !Cond || !Default)
4463 return error("Invalid record");
4465 unsigned NumCases = Record[4];
4467 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
4468 InstructionList.push_back(SI);
4470 unsigned CurIdx = 5;
4471 for (unsigned i = 0; i != NumCases; ++i) {
4472 SmallVector<ConstantInt*, 1> CaseVals;
4473 unsigned NumItems = Record[CurIdx++];
4474 for (unsigned ci = 0; ci != NumItems; ++ci) {
4475 bool isSingleNumber = Record[CurIdx++];
4478 unsigned ActiveWords = 1;
4479 if (ValueBitWidth > 64)
4480 ActiveWords = Record[CurIdx++];
4481 Low = readWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords),
4483 CurIdx += ActiveWords;
4485 if (!isSingleNumber) {
4487 if (ValueBitWidth > 64)
4488 ActiveWords = Record[CurIdx++];
4489 APInt High = readWideAPInt(
4490 makeArrayRef(&Record[CurIdx], ActiveWords), ValueBitWidth);
4491 CurIdx += ActiveWords;
4493 // FIXME: It is not clear whether values in the range should be
4494 // compared as signed or unsigned values. The partially
4495 // implemented changes that used this format in the past used
4496 // unsigned comparisons.
4497 for ( ; Low.ule(High); ++Low)
4498 CaseVals.push_back(ConstantInt::get(Context, Low));
4500 CaseVals.push_back(ConstantInt::get(Context, Low));
4502 BasicBlock *DestBB = getBasicBlock(Record[CurIdx++]);
4503 for (SmallVector<ConstantInt*, 1>::iterator cvi = CaseVals.begin(),
4504 cve = CaseVals.end(); cvi != cve; ++cvi)
4505 SI->addCase(*cvi, DestBB);
4511 // Old SwitchInst format without case ranges.
4513 if (Record.size() < 3 || (Record.size() & 1) == 0)
4514 return error("Invalid record");
4515 Type *OpTy = getTypeByID(Record[0]);
4516 Value *Cond = getValue(Record, 1, NextValueNo, OpTy);
4517 BasicBlock *Default = getBasicBlock(Record[2]);
4518 if (!OpTy || !Cond || !Default)
4519 return error("Invalid record");
4520 unsigned NumCases = (Record.size()-3)/2;
4521 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
4522 InstructionList.push_back(SI);
4523 for (unsigned i = 0, e = NumCases; i != e; ++i) {
4524 ConstantInt *CaseVal =
4525 dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy));
4526 BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]);
4527 if (!CaseVal || !DestBB) {
4529 return error("Invalid record");
4531 SI->addCase(CaseVal, DestBB);
4536 case bitc::FUNC_CODE_INST_INDIRECTBR: { // INDIRECTBR: [opty, op0, op1, ...]
4537 if (Record.size() < 2)
4538 return error("Invalid record");
4539 Type *OpTy = getTypeByID(Record[0]);
4540 Value *Address = getValue(Record, 1, NextValueNo, OpTy);
4541 if (!OpTy || !Address)
4542 return error("Invalid record");
4543 unsigned NumDests = Record.size()-2;
4544 IndirectBrInst *IBI = IndirectBrInst::Create(Address, NumDests);
4545 InstructionList.push_back(IBI);
4546 for (unsigned i = 0, e = NumDests; i != e; ++i) {
4547 if (BasicBlock *DestBB = getBasicBlock(Record[2+i])) {
4548 IBI->addDestination(DestBB);
4551 return error("Invalid record");
4558 case bitc::FUNC_CODE_INST_INVOKE: {
4559 // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...]
4560 if (Record.size() < 4)
4561 return error("Invalid record");
4563 AttributeSet PAL = getAttributes(Record[OpNum++]);
4564 unsigned CCInfo = Record[OpNum++];
4565 BasicBlock *NormalBB = getBasicBlock(Record[OpNum++]);
4566 BasicBlock *UnwindBB = getBasicBlock(Record[OpNum++]);
4568 FunctionType *FTy = nullptr;
4569 if (CCInfo >> 13 & 1 &&
4570 !(FTy = dyn_cast<FunctionType>(getTypeByID(Record[OpNum++]))))
4571 return error("Explicit invoke type is not a function type");
4574 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
4575 return error("Invalid record");
4577 PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType());
4579 return error("Callee is not a pointer");
4581 FTy = dyn_cast<FunctionType>(CalleeTy->getElementType());
4583 return error("Callee is not of pointer to function type");
4584 } else if (CalleeTy->getElementType() != FTy)
4585 return error("Explicit invoke type does not match pointee type of "
4587 if (Record.size() < FTy->getNumParams() + OpNum)
4588 return error("Insufficient operands to call");
4590 SmallVector<Value*, 16> Ops;
4591 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
4592 Ops.push_back(getValue(Record, OpNum, NextValueNo,
4593 FTy->getParamType(i)));
4595 return error("Invalid record");
4598 if (!FTy->isVarArg()) {
4599 if (Record.size() != OpNum)
4600 return error("Invalid record");
4602 // Read type/value pairs for varargs params.
4603 while (OpNum != Record.size()) {
4605 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
4606 return error("Invalid record");
4611 I = InvokeInst::Create(Callee, NormalBB, UnwindBB, Ops, OperandBundles);
4612 OperandBundles.clear();
4613 InstructionList.push_back(I);
4614 cast<InvokeInst>(I)->setCallingConv(
4615 static_cast<CallingConv::ID>(CallingConv::MaxID & CCInfo));
4616 cast<InvokeInst>(I)->setAttributes(PAL);
4619 case bitc::FUNC_CODE_INST_RESUME: { // RESUME: [opval]
4621 Value *Val = nullptr;
4622 if (getValueTypePair(Record, Idx, NextValueNo, Val))
4623 return error("Invalid record");
4624 I = ResumeInst::Create(Val);
4625 InstructionList.push_back(I);
4628 case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE
4629 I = new UnreachableInst(Context);
4630 InstructionList.push_back(I);
4632 case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...]
4633 if (Record.size() < 1 || ((Record.size()-1)&1))
4634 return error("Invalid record");
4635 Type *Ty = getTypeByID(Record[0]);
4637 return error("Invalid record");
4639 PHINode *PN = PHINode::Create(Ty, (Record.size()-1)/2);
4640 InstructionList.push_back(PN);
4642 for (unsigned i = 0, e = Record.size()-1; i != e; i += 2) {
4644 // With the new function encoding, it is possible that operands have
4645 // negative IDs (for forward references). Use a signed VBR
4646 // representation to keep the encoding small.
4648 V = getValueSigned(Record, 1+i, NextValueNo, Ty);
4650 V = getValue(Record, 1+i, NextValueNo, Ty);
4651 BasicBlock *BB = getBasicBlock(Record[2+i]);
4653 return error("Invalid record");
4654 PN->addIncoming(V, BB);
4660 case bitc::FUNC_CODE_INST_LANDINGPAD:
4661 case bitc::FUNC_CODE_INST_LANDINGPAD_OLD: {
4662 // LANDINGPAD: [ty, val, val, num, (id0,val0 ...)?]
4664 if (BitCode == bitc::FUNC_CODE_INST_LANDINGPAD) {
4665 if (Record.size() < 3)
4666 return error("Invalid record");
4668 assert(BitCode == bitc::FUNC_CODE_INST_LANDINGPAD_OLD);
4669 if (Record.size() < 4)
4670 return error("Invalid record");
4672 Type *Ty = getTypeByID(Record[Idx++]);
4674 return error("Invalid record");
4675 if (BitCode == bitc::FUNC_CODE_INST_LANDINGPAD_OLD) {
4676 Value *PersFn = nullptr;
4677 if (getValueTypePair(Record, Idx, NextValueNo, PersFn))
4678 return error("Invalid record");
4680 if (!F->hasPersonalityFn())
4681 F->setPersonalityFn(cast<Constant>(PersFn));
4682 else if (F->getPersonalityFn() != cast<Constant>(PersFn))
4683 return error("Personality function mismatch");
4686 bool IsCleanup = !!Record[Idx++];
4687 unsigned NumClauses = Record[Idx++];
4688 LandingPadInst *LP = LandingPadInst::Create(Ty, NumClauses);
4689 LP->setCleanup(IsCleanup);
4690 for (unsigned J = 0; J != NumClauses; ++J) {
4691 LandingPadInst::ClauseType CT =
4692 LandingPadInst::ClauseType(Record[Idx++]); (void)CT;
4695 if (getValueTypePair(Record, Idx, NextValueNo, Val)) {
4697 return error("Invalid record");
4700 assert((CT != LandingPadInst::Catch ||
4701 !isa<ArrayType>(Val->getType())) &&
4702 "Catch clause has a invalid type!");
4703 assert((CT != LandingPadInst::Filter ||
4704 isa<ArrayType>(Val->getType())) &&
4705 "Filter clause has invalid type!");
4706 LP->addClause(cast<Constant>(Val));
4710 InstructionList.push_back(I);
4714 case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, opty, op, align]
4715 if (Record.size() != 4)
4716 return error("Invalid record");
4717 uint64_t AlignRecord = Record[3];
4718 const uint64_t InAllocaMask = uint64_t(1) << 5;
4719 const uint64_t ExplicitTypeMask = uint64_t(1) << 6;
4720 // Reserve bit 7 for SwiftError flag.
4721 // const uint64_t SwiftErrorMask = uint64_t(1) << 7;
4722 const uint64_t FlagMask = InAllocaMask | ExplicitTypeMask;
4723 bool InAlloca = AlignRecord & InAllocaMask;
4724 Type *Ty = getTypeByID(Record[0]);
4725 if ((AlignRecord & ExplicitTypeMask) == 0) {
4726 auto *PTy = dyn_cast_or_null<PointerType>(Ty);
4728 return error("Old-style alloca with a non-pointer type");
4729 Ty = PTy->getElementType();
4731 Type *OpTy = getTypeByID(Record[1]);
4732 Value *Size = getFnValueByID(Record[2], OpTy);
4734 if (std::error_code EC =
4735 parseAlignmentValue(AlignRecord & ~FlagMask, Align)) {
4739 return error("Invalid record");
4740 AllocaInst *AI = new AllocaInst(Ty, Size, Align);
4741 AI->setUsedWithInAlloca(InAlloca);
4743 InstructionList.push_back(I);
4746 case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol]
4749 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
4750 (OpNum + 2 != Record.size() && OpNum + 3 != Record.size()))
4751 return error("Invalid record");
4754 if (OpNum + 3 == Record.size())
4755 Ty = getTypeByID(Record[OpNum++]);
4756 if (std::error_code EC =
4757 typeCheckLoadStoreInst(DiagnosticHandler, Ty, Op->getType()))
4760 Ty = cast<PointerType>(Op->getType())->getElementType();
4763 if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align))
4765 I = new LoadInst(Ty, Op, "", Record[OpNum + 1], Align);
4767 InstructionList.push_back(I);
4770 case bitc::FUNC_CODE_INST_LOADATOMIC: {
4771 // LOADATOMIC: [opty, op, align, vol, ordering, synchscope]
4774 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
4775 (OpNum + 4 != Record.size() && OpNum + 5 != Record.size()))
4776 return error("Invalid record");
4779 if (OpNum + 5 == Record.size())
4780 Ty = getTypeByID(Record[OpNum++]);
4781 if (std::error_code EC =
4782 typeCheckLoadStoreInst(DiagnosticHandler, Ty, Op->getType()))
4785 Ty = cast<PointerType>(Op->getType())->getElementType();
4787 AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]);
4788 if (Ordering == NotAtomic || Ordering == Release ||
4789 Ordering == AcquireRelease)
4790 return error("Invalid record");
4791 if (Ordering != NotAtomic && Record[OpNum] == 0)
4792 return error("Invalid record");
4793 SynchronizationScope SynchScope = getDecodedSynchScope(Record[OpNum + 3]);
4796 if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align))
4798 I = new LoadInst(Op, "", Record[OpNum+1], Align, Ordering, SynchScope);
4800 InstructionList.push_back(I);
4803 case bitc::FUNC_CODE_INST_STORE:
4804 case bitc::FUNC_CODE_INST_STORE_OLD: { // STORE2:[ptrty, ptr, val, align, vol]
4807 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
4808 (BitCode == bitc::FUNC_CODE_INST_STORE
4809 ? getValueTypePair(Record, OpNum, NextValueNo, Val)
4810 : popValue(Record, OpNum, NextValueNo,
4811 cast<PointerType>(Ptr->getType())->getElementType(),
4813 OpNum + 2 != Record.size())
4814 return error("Invalid record");
4816 if (std::error_code EC = typeCheckLoadStoreInst(
4817 DiagnosticHandler, Val->getType(), Ptr->getType()))
4820 if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align))
4822 I = new StoreInst(Val, Ptr, Record[OpNum+1], Align);
4823 InstructionList.push_back(I);
4826 case bitc::FUNC_CODE_INST_STOREATOMIC:
4827 case bitc::FUNC_CODE_INST_STOREATOMIC_OLD: {
4828 // STOREATOMIC: [ptrty, ptr, val, align, vol, ordering, synchscope]
4831 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
4832 (BitCode == bitc::FUNC_CODE_INST_STOREATOMIC
4833 ? getValueTypePair(Record, OpNum, NextValueNo, Val)
4834 : popValue(Record, OpNum, NextValueNo,
4835 cast<PointerType>(Ptr->getType())->getElementType(),
4837 OpNum + 4 != Record.size())
4838 return error("Invalid record");
4840 if (std::error_code EC = typeCheckLoadStoreInst(
4841 DiagnosticHandler, Val->getType(), Ptr->getType()))
4843 AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]);
4844 if (Ordering == NotAtomic || Ordering == Acquire ||
4845 Ordering == AcquireRelease)
4846 return error("Invalid record");
4847 SynchronizationScope SynchScope = getDecodedSynchScope(Record[OpNum + 3]);
4848 if (Ordering != NotAtomic && Record[OpNum] == 0)
4849 return error("Invalid record");
4852 if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align))
4854 I = new StoreInst(Val, Ptr, Record[OpNum+1], Align, Ordering, SynchScope);
4855 InstructionList.push_back(I);
4858 case bitc::FUNC_CODE_INST_CMPXCHG_OLD:
4859 case bitc::FUNC_CODE_INST_CMPXCHG: {
4860 // CMPXCHG:[ptrty, ptr, cmp, new, vol, successordering, synchscope,
4861 // failureordering?, isweak?]
4863 Value *Ptr, *Cmp, *New;
4864 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
4865 (BitCode == bitc::FUNC_CODE_INST_CMPXCHG
4866 ? getValueTypePair(Record, OpNum, NextValueNo, Cmp)
4867 : popValue(Record, OpNum, NextValueNo,
4868 cast<PointerType>(Ptr->getType())->getElementType(),
4870 popValue(Record, OpNum, NextValueNo, Cmp->getType(), New) ||
4871 Record.size() < OpNum + 3 || Record.size() > OpNum + 5)
4872 return error("Invalid record");
4873 AtomicOrdering SuccessOrdering = getDecodedOrdering(Record[OpNum + 1]);
4874 if (SuccessOrdering == NotAtomic || SuccessOrdering == Unordered)
4875 return error("Invalid record");
4876 SynchronizationScope SynchScope = getDecodedSynchScope(Record[OpNum + 2]);
4878 if (std::error_code EC = typeCheckLoadStoreInst(
4879 DiagnosticHandler, Cmp->getType(), Ptr->getType()))
4881 AtomicOrdering FailureOrdering;
4882 if (Record.size() < 7)
4884 AtomicCmpXchgInst::getStrongestFailureOrdering(SuccessOrdering);
4886 FailureOrdering = getDecodedOrdering(Record[OpNum + 3]);
4888 I = new AtomicCmpXchgInst(Ptr, Cmp, New, SuccessOrdering, FailureOrdering,
4890 cast<AtomicCmpXchgInst>(I)->setVolatile(Record[OpNum]);
4892 if (Record.size() < 8) {
4893 // Before weak cmpxchgs existed, the instruction simply returned the
4894 // value loaded from memory, so bitcode files from that era will be
4895 // expecting the first component of a modern cmpxchg.
4896 CurBB->getInstList().push_back(I);
4897 I = ExtractValueInst::Create(I, 0);
4899 cast<AtomicCmpXchgInst>(I)->setWeak(Record[OpNum+4]);
4902 InstructionList.push_back(I);
4905 case bitc::FUNC_CODE_INST_ATOMICRMW: {
4906 // ATOMICRMW:[ptrty, ptr, val, op, vol, ordering, synchscope]
4909 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
4910 popValue(Record, OpNum, NextValueNo,
4911 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
4912 OpNum+4 != Record.size())
4913 return error("Invalid record");
4914 AtomicRMWInst::BinOp Operation = getDecodedRMWOperation(Record[OpNum]);
4915 if (Operation < AtomicRMWInst::FIRST_BINOP ||
4916 Operation > AtomicRMWInst::LAST_BINOP)
4917 return error("Invalid record");
4918 AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]);
4919 if (Ordering == NotAtomic || Ordering == Unordered)
4920 return error("Invalid record");
4921 SynchronizationScope SynchScope = getDecodedSynchScope(Record[OpNum + 3]);
4922 I = new AtomicRMWInst(Operation, Ptr, Val, Ordering, SynchScope);
4923 cast<AtomicRMWInst>(I)->setVolatile(Record[OpNum+1]);
4924 InstructionList.push_back(I);
4927 case bitc::FUNC_CODE_INST_FENCE: { // FENCE:[ordering, synchscope]
4928 if (2 != Record.size())
4929 return error("Invalid record");
4930 AtomicOrdering Ordering = getDecodedOrdering(Record[0]);
4931 if (Ordering == NotAtomic || Ordering == Unordered ||
4932 Ordering == Monotonic)
4933 return error("Invalid record");
4934 SynchronizationScope SynchScope = getDecodedSynchScope(Record[1]);
4935 I = new FenceInst(Context, Ordering, SynchScope);
4936 InstructionList.push_back(I);
4939 case bitc::FUNC_CODE_INST_CALL: {
4940 // CALL: [paramattrs, cc, fnty, fnid, arg0, arg1...]
4941 if (Record.size() < 3)
4942 return error("Invalid record");
4945 AttributeSet PAL = getAttributes(Record[OpNum++]);
4946 unsigned CCInfo = Record[OpNum++];
4948 FunctionType *FTy = nullptr;
4949 if (CCInfo >> 15 & 1 &&
4950 !(FTy = dyn_cast<FunctionType>(getTypeByID(Record[OpNum++]))))
4951 return error("Explicit call type is not a function type");
4954 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
4955 return error("Invalid record");
4957 PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());
4959 return error("Callee is not a pointer type");
4961 FTy = dyn_cast<FunctionType>(OpTy->getElementType());
4963 return error("Callee is not of pointer to function type");
4964 } else if (OpTy->getElementType() != FTy)
4965 return error("Explicit call type does not match pointee type of "
4967 if (Record.size() < FTy->getNumParams() + OpNum)
4968 return error("Insufficient operands to call");
4970 SmallVector<Value*, 16> Args;
4971 // Read the fixed params.
4972 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
4973 if (FTy->getParamType(i)->isLabelTy())
4974 Args.push_back(getBasicBlock(Record[OpNum]));
4976 Args.push_back(getValue(Record, OpNum, NextValueNo,
4977 FTy->getParamType(i)));
4979 return error("Invalid record");
4982 // Read type/value pairs for varargs params.
4983 if (!FTy->isVarArg()) {
4984 if (OpNum != Record.size())
4985 return error("Invalid record");
4987 while (OpNum != Record.size()) {
4989 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
4990 return error("Invalid record");
4995 I = CallInst::Create(FTy, Callee, Args, OperandBundles);
4996 OperandBundles.clear();
4997 InstructionList.push_back(I);
4998 cast<CallInst>(I)->setCallingConv(
4999 static_cast<CallingConv::ID>((0x7ff & CCInfo) >> 1));
5000 CallInst::TailCallKind TCK = CallInst::TCK_None;
5002 TCK = CallInst::TCK_Tail;
5003 if (CCInfo & (1 << 14))
5004 TCK = CallInst::TCK_MustTail;
5005 cast<CallInst>(I)->setTailCallKind(TCK);
5006 cast<CallInst>(I)->setAttributes(PAL);
5009 case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty]
5010 if (Record.size() < 3)
5011 return error("Invalid record");
5012 Type *OpTy = getTypeByID(Record[0]);
5013 Value *Op = getValue(Record, 1, NextValueNo, OpTy);
5014 Type *ResTy = getTypeByID(Record[2]);
5015 if (!OpTy || !Op || !ResTy)
5016 return error("Invalid record");
5017 I = new VAArgInst(Op, ResTy);
5018 InstructionList.push_back(I);
5022 case bitc::FUNC_CODE_OPERAND_BUNDLE: {
5023 // A call or an invoke can be optionally prefixed with some variable
5024 // number of operand bundle blocks. These blocks are read into
5025 // OperandBundles and consumed at the next call or invoke instruction.
5027 if (Record.size() < 1 || Record[0] >= BundleTags.size())
5028 return error("Invalid record");
5030 OperandBundles.emplace_back();
5031 OperandBundles.back().Tag = BundleTags[Record[0]];
5033 std::vector<Value *> &Inputs = OperandBundles.back().Inputs;
5036 while (OpNum != Record.size()) {
5038 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
5039 return error("Invalid record");
5040 Inputs.push_back(Op);
5047 // Add instruction to end of current BB. If there is no current BB, reject
5051 return error("Invalid instruction with no BB");
5053 if (!OperandBundles.empty()) {
5055 return error("Operand bundles found with no consumer");
5057 CurBB->getInstList().push_back(I);
5059 // If this was a terminator instruction, move to the next block.
5060 if (isa<TerminatorInst>(I)) {
5062 CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : nullptr;
5065 // Non-void values get registered in the value table for future use.
5066 if (I && !I->getType()->isVoidTy())
5067 if (ValueList.assignValue(I, NextValueNo++))
5068 return error("Invalid forward reference");
5073 if (!OperandBundles.empty())
5074 return error("Operand bundles found with no consumer");
5076 // Check the function list for unresolved values.
5077 if (Argument *A = dyn_cast<Argument>(ValueList.back())) {
5078 if (!A->getParent()) {
5079 // We found at least one unresolved value. Nuke them all to avoid leaks.
5080 for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){
5081 if ((A = dyn_cast_or_null<Argument>(ValueList[i])) && !A->getParent()) {
5082 A->replaceAllUsesWith(UndefValue::get(A->getType()));
5086 return error("Never resolved value found in function");
5090 // FIXME: Check for unresolved forward-declared metadata references
5091 // and clean up leaks.
5093 // Trim the value list down to the size it was before we parsed this function.
5094 ValueList.shrinkTo(ModuleValueListSize);
5095 MDValueList.shrinkTo(ModuleMDValueListSize);
5096 std::vector<BasicBlock*>().swap(FunctionBBs);
5097 return std::error_code();
5100 /// Find the function body in the bitcode stream
5101 std::error_code BitcodeReader::findFunctionInStream(
5103 DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator) {
5104 while (DeferredFunctionInfoIterator->second == 0) {
5105 // This is the fallback handling for the old format bitcode that
5106 // didn't contain the function index in the VST, or when we have
5107 // an anonymous function which would not have a VST entry.
5108 // Assert that we have one of those two cases.
5109 assert(VSTOffset == 0 || !F->hasName());
5110 // Parse the next body in the stream and set its position in the
5111 // DeferredFunctionInfo map.
5112 if (std::error_code EC = rememberAndSkipFunctionBodies())
5115 return std::error_code();
5118 //===----------------------------------------------------------------------===//
5119 // GVMaterializer implementation
5120 //===----------------------------------------------------------------------===//
5122 void BitcodeReader::releaseBuffer() { Buffer.release(); }
5124 std::error_code BitcodeReader::materialize(GlobalValue *GV) {
5125 if (std::error_code EC = materializeMetadata())
5128 Function *F = dyn_cast<Function>(GV);
5129 // If it's not a function or is already material, ignore the request.
5130 if (!F || !F->isMaterializable())
5131 return std::error_code();
5133 DenseMap<Function*, uint64_t>::iterator DFII = DeferredFunctionInfo.find(F);
5134 assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!");
5135 // If its position is recorded as 0, its body is somewhere in the stream
5136 // but we haven't seen it yet.
5137 if (DFII->second == 0)
5138 if (std::error_code EC = findFunctionInStream(F, DFII))
5141 // Move the bit stream to the saved position of the deferred function body.
5142 Stream.JumpToBit(DFII->second);
5144 if (std::error_code EC = parseFunctionBody(F))
5146 F->setIsMaterializable(false);
5151 // Upgrade any old intrinsic calls in the function.
5152 for (auto &I : UpgradedIntrinsics) {
5153 for (auto UI = I.first->user_begin(), UE = I.first->user_end(); UI != UE;) {
5156 if (CallInst *CI = dyn_cast<CallInst>(U))
5157 UpgradeIntrinsicCall(CI, I.second);
5161 // Finish fn->subprogram upgrade for materialized functions.
5162 if (DISubprogram *SP = FunctionsWithSPs.lookup(F))
5163 F->setSubprogram(SP);
5165 // Bring in any functions that this function forward-referenced via
5167 return materializeForwardReferencedFunctions();
5170 bool BitcodeReader::isDematerializable(const GlobalValue *GV) const {
5171 const Function *F = dyn_cast<Function>(GV);
5172 if (!F || F->isDeclaration())
5175 // Dematerializing F would leave dangling references that wouldn't be
5176 // reconnected on re-materialization.
5177 if (BlockAddressesTaken.count(F))
5180 return DeferredFunctionInfo.count(const_cast<Function*>(F));
5183 void BitcodeReader::dematerialize(GlobalValue *GV) {
5184 Function *F = dyn_cast<Function>(GV);
5185 // If this function isn't dematerializable, this is a noop.
5186 if (!F || !isDematerializable(F))
5189 assert(DeferredFunctionInfo.count(F) && "No info to read function later?");
5191 // Just forget the function body, we can remat it later.
5192 F->dropAllReferences();
5193 F->setIsMaterializable(true);
5196 std::error_code BitcodeReader::materializeModule(Module *M) {
5197 assert(M == TheModule &&
5198 "Can only Materialize the Module this BitcodeReader is attached to.");
5200 if (std::error_code EC = materializeMetadata())
5203 // Promise to materialize all forward references.
5204 WillMaterializeAllForwardRefs = true;
5206 // Iterate over the module, deserializing any functions that are still on
5208 for (Function &F : *TheModule) {
5209 if (std::error_code EC = materialize(&F))
5212 // At this point, if there are any function bodies, parse the rest of
5213 // the bits in the module past the last function block we have recorded
5214 // through either lazy scanning or the VST.
5215 if (LastFunctionBlockBit || NextUnreadBit)
5216 parseModule(LastFunctionBlockBit > NextUnreadBit ? LastFunctionBlockBit
5219 // Check that all block address forward references got resolved (as we
5221 if (!BasicBlockFwdRefs.empty())
5222 return error("Never resolved function from blockaddress");
5224 // Upgrade any intrinsic calls that slipped through (should not happen!) and
5225 // delete the old functions to clean up. We can't do this unless the entire
5226 // module is materialized because there could always be another function body
5227 // with calls to the old function.
5228 for (auto &I : UpgradedIntrinsics) {
5229 for (auto *U : I.first->users()) {
5230 if (CallInst *CI = dyn_cast<CallInst>(U))
5231 UpgradeIntrinsicCall(CI, I.second);
5233 if (!I.first->use_empty())
5234 I.first->replaceAllUsesWith(I.second);
5235 I.first->eraseFromParent();
5237 UpgradedIntrinsics.clear();
5239 for (unsigned I = 0, E = InstsWithTBAATag.size(); I < E; I++)
5240 UpgradeInstWithTBAATag(InstsWithTBAATag[I]);
5242 UpgradeDebugInfo(*M);
5243 return std::error_code();
5246 std::vector<StructType *> BitcodeReader::getIdentifiedStructTypes() const {
5247 return IdentifiedStructTypes;
5251 BitcodeReader::initStream(std::unique_ptr<DataStreamer> Streamer) {
5253 return initLazyStream(std::move(Streamer));
5254 return initStreamFromBuffer();
5257 std::error_code BitcodeReader::initStreamFromBuffer() {
5258 const unsigned char *BufPtr = (const unsigned char*)Buffer->getBufferStart();
5259 const unsigned char *BufEnd = BufPtr+Buffer->getBufferSize();
5261 if (Buffer->getBufferSize() & 3)
5262 return error("Invalid bitcode signature");
5264 // If we have a wrapper header, parse it and ignore the non-bc file contents.
5265 // The magic number is 0x0B17C0DE stored in little endian.
5266 if (isBitcodeWrapper(BufPtr, BufEnd))
5267 if (SkipBitcodeWrapperHeader(BufPtr, BufEnd, true))
5268 return error("Invalid bitcode wrapper header");
5270 StreamFile.reset(new BitstreamReader(BufPtr, BufEnd));
5271 Stream.init(&*StreamFile);
5273 return std::error_code();
5277 BitcodeReader::initLazyStream(std::unique_ptr<DataStreamer> Streamer) {
5278 // Check and strip off the bitcode wrapper; BitstreamReader expects never to
5281 llvm::make_unique<StreamingMemoryObject>(std::move(Streamer));
5282 StreamingMemoryObject &Bytes = *OwnedBytes;
5283 StreamFile = llvm::make_unique<BitstreamReader>(std::move(OwnedBytes));
5284 Stream.init(&*StreamFile);
5286 unsigned char buf[16];
5287 if (Bytes.readBytes(buf, 16, 0) != 16)
5288 return error("Invalid bitcode signature");
5290 if (!isBitcode(buf, buf + 16))
5291 return error("Invalid bitcode signature");
5293 if (isBitcodeWrapper(buf, buf + 4)) {
5294 const unsigned char *bitcodeStart = buf;
5295 const unsigned char *bitcodeEnd = buf + 16;
5296 SkipBitcodeWrapperHeader(bitcodeStart, bitcodeEnd, false);
5297 Bytes.dropLeadingBytes(bitcodeStart - buf);
5298 Bytes.setKnownObjectSize(bitcodeEnd - bitcodeStart);
5300 return std::error_code();
5303 std::error_code FunctionIndexBitcodeReader::error(BitcodeError E,
5304 const Twine &Message) {
5305 return ::error(DiagnosticHandler, make_error_code(E), Message);
5308 std::error_code FunctionIndexBitcodeReader::error(const Twine &Message) {
5309 return ::error(DiagnosticHandler,
5310 make_error_code(BitcodeError::CorruptedBitcode), Message);
5313 std::error_code FunctionIndexBitcodeReader::error(BitcodeError E) {
5314 return ::error(DiagnosticHandler, make_error_code(E));
5317 FunctionIndexBitcodeReader::FunctionIndexBitcodeReader(
5318 MemoryBuffer *Buffer, LLVMContext &Context,
5319 DiagnosticHandlerFunction DiagnosticHandler, bool IsLazy,
5320 bool CheckFuncSummaryPresenceOnly)
5321 : DiagnosticHandler(getDiagHandler(DiagnosticHandler, Context)),
5322 Buffer(Buffer), IsLazy(IsLazy),
5323 CheckFuncSummaryPresenceOnly(CheckFuncSummaryPresenceOnly) {}
5325 FunctionIndexBitcodeReader::FunctionIndexBitcodeReader(
5326 LLVMContext &Context, DiagnosticHandlerFunction DiagnosticHandler,
5327 bool IsLazy, bool CheckFuncSummaryPresenceOnly)
5328 : DiagnosticHandler(getDiagHandler(DiagnosticHandler, Context)),
5329 Buffer(nullptr), IsLazy(IsLazy),
5330 CheckFuncSummaryPresenceOnly(CheckFuncSummaryPresenceOnly) {}
5332 void FunctionIndexBitcodeReader::freeState() { Buffer = nullptr; }
5334 void FunctionIndexBitcodeReader::releaseBuffer() { Buffer.release(); }
5336 // Specialized value symbol table parser used when reading function index
5337 // blocks where we don't actually create global values.
5338 // At the end of this routine the function index is populated with a map
5339 // from function name to FunctionInfo. The function info contains
5340 // the function block's bitcode offset as well as the offset into the
5341 // function summary section.
5342 std::error_code FunctionIndexBitcodeReader::parseValueSymbolTable() {
5343 if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
5344 return error("Invalid record");
5346 SmallVector<uint64_t, 64> Record;
5348 // Read all the records for this value table.
5349 SmallString<128> ValueName;
5351 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
5353 switch (Entry.Kind) {
5354 case BitstreamEntry::SubBlock: // Handled for us already.
5355 case BitstreamEntry::Error:
5356 return error("Malformed block");
5357 case BitstreamEntry::EndBlock:
5358 return std::error_code();
5359 case BitstreamEntry::Record:
5360 // The interesting case.
5366 switch (Stream.readRecord(Entry.ID, Record)) {
5367 default: // Default behavior: ignore (e.g. VST_CODE_BBENTRY records).
5369 case bitc::VST_CODE_FNENTRY: {
5370 // VST_FNENTRY: [valueid, offset, namechar x N]
5371 if (convertToString(Record, 2, ValueName))
5372 return error("Invalid record");
5373 unsigned ValueID = Record[0];
5374 uint64_t FuncOffset = Record[1];
5375 std::unique_ptr<FunctionInfo> FuncInfo =
5376 llvm::make_unique<FunctionInfo>(FuncOffset);
5377 if (foundFuncSummary() && !IsLazy) {
5378 DenseMap<uint64_t, std::unique_ptr<FunctionSummary>>::iterator SMI =
5379 SummaryMap.find(ValueID);
5380 assert(SMI != SummaryMap.end() && "Summary info not found");
5381 FuncInfo->setFunctionSummary(std::move(SMI->second));
5383 TheIndex->addFunctionInfo(ValueName, std::move(FuncInfo));
5388 case bitc::VST_CODE_COMBINED_FNENTRY: {
5389 // VST_FNENTRY: [offset, namechar x N]
5390 if (convertToString(Record, 1, ValueName))
5391 return error("Invalid record");
5392 uint64_t FuncSummaryOffset = Record[0];
5393 std::unique_ptr<FunctionInfo> FuncInfo =
5394 llvm::make_unique<FunctionInfo>(FuncSummaryOffset);
5395 if (foundFuncSummary() && !IsLazy) {
5396 DenseMap<uint64_t, std::unique_ptr<FunctionSummary>>::iterator SMI =
5397 SummaryMap.find(FuncSummaryOffset);
5398 assert(SMI != SummaryMap.end() && "Summary info not found");
5399 FuncInfo->setFunctionSummary(std::move(SMI->second));
5401 TheIndex->addFunctionInfo(ValueName, std::move(FuncInfo));
5410 // Parse just the blocks needed for function index building out of the module.
5411 // At the end of this routine the function Index is populated with a map
5412 // from function name to FunctionInfo. The function info contains
5413 // either the parsed function summary information (when parsing summaries
5414 // eagerly), or just to the function summary record's offset
5415 // if parsing lazily (IsLazy).
5416 std::error_code FunctionIndexBitcodeReader::parseModule() {
5417 if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
5418 return error("Invalid record");
5420 // Read the function index for this module.
5422 BitstreamEntry Entry = Stream.advance();
5424 switch (Entry.Kind) {
5425 case BitstreamEntry::Error:
5426 return error("Malformed block");
5427 case BitstreamEntry::EndBlock:
5428 return std::error_code();
5430 case BitstreamEntry::SubBlock:
5431 if (CheckFuncSummaryPresenceOnly) {
5432 if (Entry.ID == bitc::FUNCTION_SUMMARY_BLOCK_ID)
5433 SeenFuncSummary = true;
5434 if (Stream.SkipBlock())
5435 return error("Invalid record");
5436 // No need to parse the rest since we found the summary.
5437 return std::error_code();
5440 default: // Skip unknown content.
5441 if (Stream.SkipBlock())
5442 return error("Invalid record");
5444 case bitc::BLOCKINFO_BLOCK_ID:
5445 // Need to parse these to get abbrev ids (e.g. for VST)
5446 if (Stream.ReadBlockInfoBlock())
5447 return error("Malformed block");
5449 case bitc::VALUE_SYMTAB_BLOCK_ID:
5450 if (std::error_code EC = parseValueSymbolTable())
5453 case bitc::FUNCTION_SUMMARY_BLOCK_ID:
5454 SeenFuncSummary = true;
5456 // Lazy parsing of summary info, skip it.
5457 if (Stream.SkipBlock())
5458 return error("Invalid record");
5459 } else if (std::error_code EC = parseEntireSummary())
5462 case bitc::MODULE_STRTAB_BLOCK_ID:
5463 if (std::error_code EC = parseModuleStringTable())
5469 case BitstreamEntry::Record:
5470 Stream.skipRecord(Entry.ID);
5476 // Eagerly parse the entire function summary block (i.e. for all functions
5477 // in the index). This populates the FunctionSummary objects in
5479 std::error_code FunctionIndexBitcodeReader::parseEntireSummary() {
5480 if (Stream.EnterSubBlock(bitc::FUNCTION_SUMMARY_BLOCK_ID))
5481 return error("Invalid record");
5483 SmallVector<uint64_t, 64> Record;
5486 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
5488 switch (Entry.Kind) {
5489 case BitstreamEntry::SubBlock: // Handled for us already.
5490 case BitstreamEntry::Error:
5491 return error("Malformed block");
5492 case BitstreamEntry::EndBlock:
5493 return std::error_code();
5494 case BitstreamEntry::Record:
5495 // The interesting case.
5499 // Read a record. The record format depends on whether this
5500 // is a per-module index or a combined index file. In the per-module
5501 // case the records contain the associated value's ID for correlation
5502 // with VST entries. In the combined index the correlation is done
5503 // via the bitcode offset of the summary records (which were saved
5504 // in the combined index VST entries). The records also contain
5505 // information used for ThinLTO renaming and importing.
5507 uint64_t CurRecordBit = Stream.GetCurrentBitNo();
5508 switch (Stream.readRecord(Entry.ID, Record)) {
5509 default: // Default behavior: ignore.
5511 // FS_PERMODULE_ENTRY: [valueid, islocal, instcount]
5512 case bitc::FS_CODE_PERMODULE_ENTRY: {
5513 unsigned ValueID = Record[0];
5514 bool IsLocal = Record[1];
5515 unsigned InstCount = Record[2];
5516 std::unique_ptr<FunctionSummary> FS =
5517 llvm::make_unique<FunctionSummary>(InstCount);
5518 FS->setLocalFunction(IsLocal);
5519 // The module path string ref set in the summary must be owned by the
5520 // index's module string table. Since we don't have a module path
5521 // string table section in the per-module index, we create a single
5522 // module path string table entry with an empty (0) ID to take
5525 TheIndex->addModulePath(Buffer->getBufferIdentifier(), 0));
5526 SummaryMap[ValueID] = std::move(FS);
5528 // FS_COMBINED_ENTRY: [modid, instcount]
5529 case bitc::FS_CODE_COMBINED_ENTRY: {
5530 uint64_t ModuleId = Record[0];
5531 unsigned InstCount = Record[1];
5532 std::unique_ptr<FunctionSummary> FS =
5533 llvm::make_unique<FunctionSummary>(InstCount);
5534 FS->setModulePath(ModuleIdMap[ModuleId]);
5535 SummaryMap[CurRecordBit] = std::move(FS);
5539 llvm_unreachable("Exit infinite loop");
5542 // Parse the module string table block into the Index.
5543 // This populates the ModulePathStringTable map in the index.
5544 std::error_code FunctionIndexBitcodeReader::parseModuleStringTable() {
5545 if (Stream.EnterSubBlock(bitc::MODULE_STRTAB_BLOCK_ID))
5546 return error("Invalid record");
5548 SmallVector<uint64_t, 64> Record;
5550 SmallString<128> ModulePath;
5552 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
5554 switch (Entry.Kind) {
5555 case BitstreamEntry::SubBlock: // Handled for us already.
5556 case BitstreamEntry::Error:
5557 return error("Malformed block");
5558 case BitstreamEntry::EndBlock:
5559 return std::error_code();
5560 case BitstreamEntry::Record:
5561 // The interesting case.
5566 switch (Stream.readRecord(Entry.ID, Record)) {
5567 default: // Default behavior: ignore.
5569 case bitc::MST_CODE_ENTRY: {
5570 // MST_ENTRY: [modid, namechar x N]
5571 if (convertToString(Record, 1, ModulePath))
5572 return error("Invalid record");
5573 uint64_t ModuleId = Record[0];
5574 StringRef ModulePathInMap = TheIndex->addModulePath(ModulePath, ModuleId);
5575 ModuleIdMap[ModuleId] = ModulePathInMap;
5581 llvm_unreachable("Exit infinite loop");
5584 // Parse the function info index from the bitcode streamer into the given index.
5585 std::error_code FunctionIndexBitcodeReader::parseSummaryIndexInto(
5586 std::unique_ptr<DataStreamer> Streamer, FunctionInfoIndex *I) {
5589 if (std::error_code EC = initStream(std::move(Streamer)))
5592 // Sniff for the signature.
5593 if (!hasValidBitcodeHeader(Stream))
5594 return error("Invalid bitcode signature");
5596 // We expect a number of well-defined blocks, though we don't necessarily
5597 // need to understand them all.
5599 if (Stream.AtEndOfStream()) {
5600 // We didn't really read a proper Module block.
5601 return error("Malformed block");
5604 BitstreamEntry Entry =
5605 Stream.advance(BitstreamCursor::AF_DontAutoprocessAbbrevs);
5607 if (Entry.Kind != BitstreamEntry::SubBlock)
5608 return error("Malformed block");
5610 // If we see a MODULE_BLOCK, parse it to find the blocks needed for
5611 // building the function summary index.
5612 if (Entry.ID == bitc::MODULE_BLOCK_ID)
5613 return parseModule();
5615 if (Stream.SkipBlock())
5616 return error("Invalid record");
5620 // Parse the function information at the given offset in the buffer into
5621 // the index. Used to support lazy parsing of function summaries from the
5622 // combined index during importing.
5623 // TODO: This function is not yet complete as it won't have a consumer
5624 // until ThinLTO function importing is added.
5625 std::error_code FunctionIndexBitcodeReader::parseFunctionSummary(
5626 std::unique_ptr<DataStreamer> Streamer, FunctionInfoIndex *I,
5627 size_t FunctionSummaryOffset) {
5630 if (std::error_code EC = initStream(std::move(Streamer)))
5633 // Sniff for the signature.
5634 if (!hasValidBitcodeHeader(Stream))
5635 return error("Invalid bitcode signature");
5637 Stream.JumpToBit(FunctionSummaryOffset);
5639 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
5641 switch (Entry.Kind) {
5643 return error("Malformed block");
5644 case BitstreamEntry::Record:
5645 // The expected case.
5649 // TODO: Read a record. This interface will be completed when ThinLTO
5650 // importing is added so that it can be tested.
5651 SmallVector<uint64_t, 64> Record;
5652 switch (Stream.readRecord(Entry.ID, Record)) {
5653 case bitc::FS_CODE_COMBINED_ENTRY:
5655 return error("Invalid record");
5658 return std::error_code();
5662 FunctionIndexBitcodeReader::initStream(std::unique_ptr<DataStreamer> Streamer) {
5664 return initLazyStream(std::move(Streamer));
5665 return initStreamFromBuffer();
5668 std::error_code FunctionIndexBitcodeReader::initStreamFromBuffer() {
5669 const unsigned char *BufPtr = (const unsigned char *)Buffer->getBufferStart();
5670 const unsigned char *BufEnd = BufPtr + Buffer->getBufferSize();
5672 if (Buffer->getBufferSize() & 3)
5673 return error("Invalid bitcode signature");
5675 // If we have a wrapper header, parse it and ignore the non-bc file contents.
5676 // The magic number is 0x0B17C0DE stored in little endian.
5677 if (isBitcodeWrapper(BufPtr, BufEnd))
5678 if (SkipBitcodeWrapperHeader(BufPtr, BufEnd, true))
5679 return error("Invalid bitcode wrapper header");
5681 StreamFile.reset(new BitstreamReader(BufPtr, BufEnd));
5682 Stream.init(&*StreamFile);
5684 return std::error_code();
5687 std::error_code FunctionIndexBitcodeReader::initLazyStream(
5688 std::unique_ptr<DataStreamer> Streamer) {
5689 // Check and strip off the bitcode wrapper; BitstreamReader expects never to
5692 llvm::make_unique<StreamingMemoryObject>(std::move(Streamer));
5693 StreamingMemoryObject &Bytes = *OwnedBytes;
5694 StreamFile = llvm::make_unique<BitstreamReader>(std::move(OwnedBytes));
5695 Stream.init(&*StreamFile);
5697 unsigned char buf[16];
5698 if (Bytes.readBytes(buf, 16, 0) != 16)
5699 return error("Invalid bitcode signature");
5701 if (!isBitcode(buf, buf + 16))
5702 return error("Invalid bitcode signature");
5704 if (isBitcodeWrapper(buf, buf + 4)) {
5705 const unsigned char *bitcodeStart = buf;
5706 const unsigned char *bitcodeEnd = buf + 16;
5707 SkipBitcodeWrapperHeader(bitcodeStart, bitcodeEnd, false);
5708 Bytes.dropLeadingBytes(bitcodeStart - buf);
5709 Bytes.setKnownObjectSize(bitcodeEnd - bitcodeStart);
5711 return std::error_code();
5715 class BitcodeErrorCategoryType : public std::error_category {
5716 const char *name() const LLVM_NOEXCEPT override {
5717 return "llvm.bitcode";
5719 std::string message(int IE) const override {
5720 BitcodeError E = static_cast<BitcodeError>(IE);
5722 case BitcodeError::InvalidBitcodeSignature:
5723 return "Invalid bitcode signature";
5724 case BitcodeError::CorruptedBitcode:
5725 return "Corrupted bitcode";
5727 llvm_unreachable("Unknown error type!");
5732 static ManagedStatic<BitcodeErrorCategoryType> ErrorCategory;
5734 const std::error_category &llvm::BitcodeErrorCategory() {
5735 return *ErrorCategory;
5738 //===----------------------------------------------------------------------===//
5739 // External interface
5740 //===----------------------------------------------------------------------===//
5742 static ErrorOr<std::unique_ptr<Module>>
5743 getBitcodeModuleImpl(std::unique_ptr<DataStreamer> Streamer, StringRef Name,
5744 BitcodeReader *R, LLVMContext &Context,
5745 bool MaterializeAll, bool ShouldLazyLoadMetadata) {
5746 std::unique_ptr<Module> M = make_unique<Module>(Name, Context);
5747 M->setMaterializer(R);
5749 auto cleanupOnError = [&](std::error_code EC) {
5750 R->releaseBuffer(); // Never take ownership on error.
5754 // Delay parsing Metadata if ShouldLazyLoadMetadata is true.
5755 if (std::error_code EC = R->parseBitcodeInto(std::move(Streamer), M.get(),
5756 ShouldLazyLoadMetadata))
5757 return cleanupOnError(EC);
5759 if (MaterializeAll) {
5760 // Read in the entire module, and destroy the BitcodeReader.
5761 if (std::error_code EC = M->materializeAllPermanently())
5762 return cleanupOnError(EC);
5764 // Resolve forward references from blockaddresses.
5765 if (std::error_code EC = R->materializeForwardReferencedFunctions())
5766 return cleanupOnError(EC);
5768 return std::move(M);
5771 /// \brief Get a lazy one-at-time loading module from bitcode.
5773 /// This isn't always used in a lazy context. In particular, it's also used by
5774 /// \a parseBitcodeFile(). If this is truly lazy, then we need to eagerly pull
5775 /// in forward-referenced functions from block address references.
5777 /// \param[in] MaterializeAll Set to \c true if we should materialize
5779 static ErrorOr<std::unique_ptr<Module>>
5780 getLazyBitcodeModuleImpl(std::unique_ptr<MemoryBuffer> &&Buffer,
5781 LLVMContext &Context, bool MaterializeAll,
5782 DiagnosticHandlerFunction DiagnosticHandler,
5783 bool ShouldLazyLoadMetadata = false) {
5785 new BitcodeReader(Buffer.get(), Context, DiagnosticHandler);
5787 ErrorOr<std::unique_ptr<Module>> Ret =
5788 getBitcodeModuleImpl(nullptr, Buffer->getBufferIdentifier(), R, Context,
5789 MaterializeAll, ShouldLazyLoadMetadata);
5793 Buffer.release(); // The BitcodeReader owns it now.
5797 ErrorOr<std::unique_ptr<Module>> llvm::getLazyBitcodeModule(
5798 std::unique_ptr<MemoryBuffer> &&Buffer, LLVMContext &Context,
5799 DiagnosticHandlerFunction DiagnosticHandler, bool ShouldLazyLoadMetadata) {
5800 return getLazyBitcodeModuleImpl(std::move(Buffer), Context, false,
5801 DiagnosticHandler, ShouldLazyLoadMetadata);
5804 ErrorOr<std::unique_ptr<Module>> llvm::getStreamedBitcodeModule(
5805 StringRef Name, std::unique_ptr<DataStreamer> Streamer,
5806 LLVMContext &Context, DiagnosticHandlerFunction DiagnosticHandler) {
5807 std::unique_ptr<Module> M = make_unique<Module>(Name, Context);
5808 BitcodeReader *R = new BitcodeReader(Context, DiagnosticHandler);
5810 return getBitcodeModuleImpl(std::move(Streamer), Name, R, Context, false,
5814 ErrorOr<std::unique_ptr<Module>>
5815 llvm::parseBitcodeFile(MemoryBufferRef Buffer, LLVMContext &Context,
5816 DiagnosticHandlerFunction DiagnosticHandler) {
5817 std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
5818 return getLazyBitcodeModuleImpl(std::move(Buf), Context, true,
5820 // TODO: Restore the use-lists to the in-memory state when the bitcode was
5821 // written. We must defer until the Module has been fully materialized.
5825 llvm::getBitcodeTargetTriple(MemoryBufferRef Buffer, LLVMContext &Context,
5826 DiagnosticHandlerFunction DiagnosticHandler) {
5827 std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
5828 auto R = llvm::make_unique<BitcodeReader>(Buf.release(), Context,
5830 ErrorOr<std::string> Triple = R->parseTriple();
5831 if (Triple.getError())
5833 return Triple.get();
5836 // Parse the specified bitcode buffer, returning the function info index.
5837 // If IsLazy is false, parse the entire function summary into
5838 // the index. Otherwise skip the function summary section, and only create
5839 // an index object with a map from function name to function summary offset.
5840 // The index is used to perform lazy function summary reading later.
5841 ErrorOr<std::unique_ptr<FunctionInfoIndex>>
5842 llvm::getFunctionInfoIndex(MemoryBufferRef Buffer, LLVMContext &Context,
5843 DiagnosticHandlerFunction DiagnosticHandler,
5844 const Module *ExportingModule, bool IsLazy) {
5845 std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
5846 FunctionIndexBitcodeReader R(Buf.get(), Context, DiagnosticHandler, IsLazy);
5848 std::unique_ptr<FunctionInfoIndex> Index =
5849 llvm::make_unique<FunctionInfoIndex>(ExportingModule);
5851 auto cleanupOnError = [&](std::error_code EC) {
5852 R.releaseBuffer(); // Never take ownership on error.
5856 if (std::error_code EC = R.parseSummaryIndexInto(nullptr, Index.get()))
5857 return cleanupOnError(EC);
5859 Buf.release(); // The FunctionIndexBitcodeReader owns it now.
5860 return std::move(Index);
5863 // Check if the given bitcode buffer contains a function summary block.
5864 bool llvm::hasFunctionSummary(MemoryBufferRef Buffer, LLVMContext &Context,
5865 DiagnosticHandlerFunction DiagnosticHandler) {
5866 std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
5867 FunctionIndexBitcodeReader R(Buf.get(), Context, DiagnosticHandler, false,
5870 auto cleanupOnError = [&](std::error_code EC) {
5871 R.releaseBuffer(); // Never take ownership on error.
5875 if (std::error_code EC = R.parseSummaryIndexInto(nullptr, nullptr))
5876 return cleanupOnError(EC);
5878 Buf.release(); // The FunctionIndexBitcodeReader owns it now.
5879 return R.foundFuncSummary();
5882 // This method supports lazy reading of function summary data from the combined
5883 // index during ThinLTO function importing. When reading the combined index
5884 // file, getFunctionInfoIndex is first invoked with IsLazy=true.
5885 // Then this method is called for each function considered for importing,
5886 // to parse the summary information for the given function name into
5889 llvm::readFunctionSummary(MemoryBufferRef Buffer, LLVMContext &Context,
5890 DiagnosticHandlerFunction DiagnosticHandler,
5891 StringRef FunctionName,
5892 std::unique_ptr<FunctionInfoIndex> Index) {
5893 std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
5894 FunctionIndexBitcodeReader R(Buf.get(), Context, DiagnosticHandler);
5896 auto cleanupOnError = [&](std::error_code EC) {
5897 R.releaseBuffer(); // Never take ownership on error.
5901 // Lookup the given function name in the FunctionMap, which may
5902 // contain a list of function infos in the case of a COMDAT. Walk through
5903 // and parse each function summary info at the function summary offset
5904 // recorded when parsing the value symbol table.
5905 for (const auto &FI : Index->getFunctionInfoList(FunctionName)) {
5906 size_t FunctionSummaryOffset = FI->bitcodeIndex();
5907 if (std::error_code EC =
5908 R.parseFunctionSummary(nullptr, Index.get(), FunctionSummaryOffset))
5909 return cleanupOnError(EC);
5912 Buf.release(); // The FunctionIndexBitcodeReader owns it now.
5913 return std::error_code();