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 /// Cheap mechanism to just extract the identification block out of bitcode.
275 ErrorOr<std::string> parseIdentificationBlock();
277 static uint64_t decodeSignRotatedValue(uint64_t V);
279 /// Materialize any deferred Metadata block.
280 std::error_code materializeMetadata() override;
282 void setStripDebugInfo() override;
285 /// Parse the "IDENTIFICATION_BLOCK_ID" block, populate the
286 // ProducerIdentification data member, and do some basic enforcement on the
287 // "epoch" encoded in the bitcode.
288 std::error_code parseBitcodeVersion();
290 std::vector<StructType *> IdentifiedStructTypes;
291 StructType *createIdentifiedStructType(LLVMContext &Context, StringRef Name);
292 StructType *createIdentifiedStructType(LLVMContext &Context);
294 Type *getTypeByID(unsigned ID);
295 Value *getFnValueByID(unsigned ID, Type *Ty,
296 OperatorConstraint OC = OC_None) {
297 if (Ty && Ty->isMetadataTy())
298 return MetadataAsValue::get(Ty->getContext(), getFnMetadataByID(ID));
299 return ValueList.getValueFwdRef(ID, Ty, OC);
301 Metadata *getFnMetadataByID(unsigned ID) {
302 return MDValueList.getValueFwdRef(ID);
304 BasicBlock *getBasicBlock(unsigned ID) const {
305 if (ID >= FunctionBBs.size()) return nullptr; // Invalid ID
306 return FunctionBBs[ID];
308 AttributeSet getAttributes(unsigned i) const {
309 if (i-1 < MAttributes.size())
310 return MAttributes[i-1];
311 return AttributeSet();
314 /// Read a value/type pair out of the specified record from slot 'Slot'.
315 /// Increment Slot past the number of slots used in the record. Return true on
317 bool getValueTypePair(SmallVectorImpl<uint64_t> &Record, unsigned &Slot,
318 unsigned InstNum, Value *&ResVal) {
319 if (Slot == Record.size()) return true;
320 unsigned ValNo = (unsigned)Record[Slot++];
321 // Adjust the ValNo, if it was encoded relative to the InstNum.
323 ValNo = InstNum - ValNo;
324 if (ValNo < InstNum) {
325 // If this is not a forward reference, just return the value we already
327 ResVal = getFnValueByID(ValNo, nullptr);
328 return ResVal == nullptr;
330 if (Slot == Record.size())
333 unsigned TypeNo = (unsigned)Record[Slot++];
334 ResVal = getFnValueByID(ValNo, getTypeByID(TypeNo));
335 return ResVal == nullptr;
338 /// Read a value out of the specified record from slot 'Slot'. Increment Slot
339 /// past the number of slots used by the value in the record. Return true if
340 /// there is an error.
341 bool popValue(SmallVectorImpl<uint64_t> &Record, unsigned &Slot,
342 unsigned InstNum, Type *Ty, Value *&ResVal,
343 OperatorConstraint OC = OC_None) {
344 if (getValue(Record, Slot, InstNum, Ty, ResVal, OC))
346 // All values currently take a single record slot.
351 /// Like popValue, but does not increment the Slot number.
352 bool getValue(SmallVectorImpl<uint64_t> &Record, unsigned Slot,
353 unsigned InstNum, Type *Ty, Value *&ResVal,
354 OperatorConstraint OC = OC_None) {
355 ResVal = getValue(Record, Slot, InstNum, Ty, OC);
356 return ResVal == nullptr;
359 /// Version of getValue that returns ResVal directly, or 0 if there is an
361 Value *getValue(SmallVectorImpl<uint64_t> &Record, unsigned Slot,
362 unsigned InstNum, Type *Ty, OperatorConstraint OC = OC_None) {
363 if (Slot == Record.size()) return nullptr;
364 unsigned ValNo = (unsigned)Record[Slot];
365 // Adjust the ValNo, if it was encoded relative to the InstNum.
367 ValNo = InstNum - ValNo;
368 return getFnValueByID(ValNo, Ty, OC);
371 /// Like getValue, but decodes signed VBRs.
372 Value *getValueSigned(SmallVectorImpl<uint64_t> &Record, unsigned Slot,
373 unsigned InstNum, Type *Ty,
374 OperatorConstraint OC = OC_None) {
375 if (Slot == Record.size()) return nullptr;
376 unsigned ValNo = (unsigned)decodeSignRotatedValue(Record[Slot]);
377 // Adjust the ValNo, if it was encoded relative to the InstNum.
379 ValNo = InstNum - ValNo;
380 return getFnValueByID(ValNo, Ty, OC);
383 /// Converts alignment exponent (i.e. power of two (or zero)) to the
384 /// corresponding alignment to use. If alignment is too large, returns
385 /// a corresponding error code.
386 std::error_code parseAlignmentValue(uint64_t Exponent, unsigned &Alignment);
387 std::error_code parseAttrKind(uint64_t Code, Attribute::AttrKind *Kind);
388 std::error_code parseModule(uint64_t ResumeBit,
389 bool ShouldLazyLoadMetadata = false);
390 std::error_code parseAttributeBlock();
391 std::error_code parseAttributeGroupBlock();
392 std::error_code parseTypeTable();
393 std::error_code parseTypeTableBody();
394 std::error_code parseOperandBundleTags();
396 ErrorOr<Value *> recordValue(SmallVectorImpl<uint64_t> &Record,
397 unsigned NameIndex, Triple &TT);
398 std::error_code parseValueSymbolTable(uint64_t Offset = 0);
399 std::error_code parseConstants();
400 std::error_code rememberAndSkipFunctionBodies();
401 std::error_code rememberAndSkipFunctionBody();
402 /// Save the positions of the Metadata blocks and skip parsing the blocks.
403 std::error_code rememberAndSkipMetadata();
404 std::error_code parseFunctionBody(Function *F);
405 std::error_code globalCleanup();
406 std::error_code resolveGlobalAndAliasInits();
407 std::error_code parseMetadata();
408 std::error_code parseMetadataKinds();
409 std::error_code parseMetadataKindRecord(SmallVectorImpl<uint64_t> &Record);
410 std::error_code parseMetadataAttachment(Function &F);
411 ErrorOr<std::string> parseModuleTriple();
412 std::error_code parseUseLists();
413 std::error_code initStream(std::unique_ptr<DataStreamer> Streamer);
414 std::error_code initStreamFromBuffer();
415 std::error_code initLazyStream(std::unique_ptr<DataStreamer> Streamer);
416 std::error_code findFunctionInStream(
418 DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator);
421 /// Class to manage reading and parsing function summary index bitcode
423 class FunctionIndexBitcodeReader {
424 DiagnosticHandlerFunction DiagnosticHandler;
426 /// Eventually points to the function index built during parsing.
427 FunctionInfoIndex *TheIndex = nullptr;
429 std::unique_ptr<MemoryBuffer> Buffer;
430 std::unique_ptr<BitstreamReader> StreamFile;
431 BitstreamCursor Stream;
433 /// \brief Used to indicate whether we are doing lazy parsing of summary data.
435 /// If false, the summary section is fully parsed into the index during
436 /// the initial parse. Otherwise, if true, the caller is expected to
437 /// invoke \a readFunctionSummary for each summary needed, and the summary
438 /// section is thus parsed lazily.
441 /// Used to indicate whether caller only wants to check for the presence
442 /// of the function summary bitcode section. All blocks are skipped,
443 /// but the SeenFuncSummary boolean is set.
444 bool CheckFuncSummaryPresenceOnly = false;
446 /// Indicates whether we have encountered a function summary section
447 /// yet during parsing, used when checking if file contains function
449 bool SeenFuncSummary = false;
451 /// \brief Map populated during function summary section parsing, and
452 /// consumed during ValueSymbolTable parsing.
454 /// Used to correlate summary records with VST entries. For the per-module
455 /// index this maps the ValueID to the parsed function summary, and
456 /// for the combined index this maps the summary record's bitcode
457 /// offset to the function summary (since in the combined index the
458 /// VST records do not hold value IDs but rather hold the function
459 /// summary record offset).
460 DenseMap<uint64_t, std::unique_ptr<FunctionSummary>> SummaryMap;
462 /// Map populated during module path string table parsing, from the
463 /// module ID to a string reference owned by the index's module
464 /// path string table, used to correlate with combined index function
466 DenseMap<uint64_t, StringRef> ModuleIdMap;
469 std::error_code error(BitcodeError E, const Twine &Message);
470 std::error_code error(BitcodeError E);
471 std::error_code error(const Twine &Message);
473 FunctionIndexBitcodeReader(MemoryBuffer *Buffer, LLVMContext &Context,
474 DiagnosticHandlerFunction DiagnosticHandler,
476 bool CheckFuncSummaryPresenceOnly = false);
477 FunctionIndexBitcodeReader(LLVMContext &Context,
478 DiagnosticHandlerFunction DiagnosticHandler,
480 bool CheckFuncSummaryPresenceOnly = false);
481 ~FunctionIndexBitcodeReader() { freeState(); }
485 void releaseBuffer();
487 /// Check if the parser has encountered a function summary section.
488 bool foundFuncSummary() { return SeenFuncSummary; }
490 /// \brief Main interface to parsing a bitcode buffer.
491 /// \returns true if an error occurred.
492 std::error_code parseSummaryIndexInto(std::unique_ptr<DataStreamer> Streamer,
493 FunctionInfoIndex *I);
495 /// \brief Interface for parsing a function summary lazily.
496 std::error_code parseFunctionSummary(std::unique_ptr<DataStreamer> Streamer,
497 FunctionInfoIndex *I,
498 size_t FunctionSummaryOffset);
501 std::error_code parseModule();
502 std::error_code parseValueSymbolTable();
503 std::error_code parseEntireSummary();
504 std::error_code parseModuleStringTable();
505 std::error_code initStream(std::unique_ptr<DataStreamer> Streamer);
506 std::error_code initStreamFromBuffer();
507 std::error_code initLazyStream(std::unique_ptr<DataStreamer> Streamer);
511 BitcodeDiagnosticInfo::BitcodeDiagnosticInfo(std::error_code EC,
512 DiagnosticSeverity Severity,
514 : DiagnosticInfo(DK_Bitcode, Severity), Msg(Msg), EC(EC) {}
516 void BitcodeDiagnosticInfo::print(DiagnosticPrinter &DP) const { DP << Msg; }
518 static std::error_code error(DiagnosticHandlerFunction DiagnosticHandler,
519 std::error_code EC, const Twine &Message) {
520 BitcodeDiagnosticInfo DI(EC, DS_Error, Message);
521 DiagnosticHandler(DI);
525 static std::error_code error(DiagnosticHandlerFunction DiagnosticHandler,
526 std::error_code EC) {
527 return error(DiagnosticHandler, EC, EC.message());
530 static std::error_code error(DiagnosticHandlerFunction DiagnosticHandler,
531 const Twine &Message) {
532 return error(DiagnosticHandler,
533 make_error_code(BitcodeError::CorruptedBitcode), Message);
536 std::error_code BitcodeReader::error(BitcodeError E, const Twine &Message) {
537 if (!ProducerIdentification.empty()) {
538 return ::error(DiagnosticHandler, make_error_code(E),
539 Message + " (Producer: '" + ProducerIdentification +
540 "' Reader: 'LLVM " + LLVM_VERSION_STRING "')");
542 return ::error(DiagnosticHandler, make_error_code(E), Message);
545 std::error_code BitcodeReader::error(const Twine &Message) {
546 if (!ProducerIdentification.empty()) {
547 return ::error(DiagnosticHandler,
548 make_error_code(BitcodeError::CorruptedBitcode),
549 Message + " (Producer: '" + ProducerIdentification +
550 "' Reader: 'LLVM " + LLVM_VERSION_STRING "')");
552 return ::error(DiagnosticHandler,
553 make_error_code(BitcodeError::CorruptedBitcode), Message);
556 std::error_code BitcodeReader::error(BitcodeError E) {
557 return ::error(DiagnosticHandler, make_error_code(E));
560 static DiagnosticHandlerFunction getDiagHandler(DiagnosticHandlerFunction F,
564 return [&C](const DiagnosticInfo &DI) { C.diagnose(DI); };
567 BitcodeReader::BitcodeReader(MemoryBuffer *Buffer, LLVMContext &Context,
568 DiagnosticHandlerFunction DiagnosticHandler)
570 DiagnosticHandler(getDiagHandler(DiagnosticHandler, Context)),
571 Buffer(Buffer), ValueList(Context), MDValueList(Context) {}
573 BitcodeReader::BitcodeReader(LLVMContext &Context,
574 DiagnosticHandlerFunction DiagnosticHandler)
576 DiagnosticHandler(getDiagHandler(DiagnosticHandler, Context)),
577 Buffer(nullptr), ValueList(Context), MDValueList(Context) {}
579 std::error_code BitcodeReader::materializeForwardReferencedFunctions() {
580 if (WillMaterializeAllForwardRefs)
581 return std::error_code();
583 // Prevent recursion.
584 WillMaterializeAllForwardRefs = true;
586 while (!BasicBlockFwdRefQueue.empty()) {
587 Function *F = BasicBlockFwdRefQueue.front();
588 BasicBlockFwdRefQueue.pop_front();
589 assert(F && "Expected valid function");
590 if (!BasicBlockFwdRefs.count(F))
591 // Already materialized.
594 // Check for a function that isn't materializable to prevent an infinite
595 // loop. When parsing a blockaddress stored in a global variable, there
596 // isn't a trivial way to check if a function will have a body without a
597 // linear search through FunctionsWithBodies, so just check it here.
598 if (!F->isMaterializable())
599 return error("Never resolved function from blockaddress");
601 // Try to materialize F.
602 if (std::error_code EC = materialize(F))
605 assert(BasicBlockFwdRefs.empty() && "Function missing from queue");
608 WillMaterializeAllForwardRefs = false;
609 return std::error_code();
612 void BitcodeReader::freeState() {
614 std::vector<Type*>().swap(TypeList);
617 std::vector<Comdat *>().swap(ComdatList);
619 std::vector<AttributeSet>().swap(MAttributes);
620 std::vector<BasicBlock*>().swap(FunctionBBs);
621 std::vector<Function*>().swap(FunctionsWithBodies);
622 DeferredFunctionInfo.clear();
623 DeferredMetadataInfo.clear();
626 assert(BasicBlockFwdRefs.empty() && "Unresolved blockaddress fwd references");
627 BasicBlockFwdRefQueue.clear();
630 //===----------------------------------------------------------------------===//
631 // Helper functions to implement forward reference resolution, etc.
632 //===----------------------------------------------------------------------===//
634 /// Convert a string from a record into an std::string, return true on failure.
635 template <typename StrTy>
636 static bool convertToString(ArrayRef<uint64_t> Record, unsigned Idx,
638 if (Idx > Record.size())
641 for (unsigned i = Idx, e = Record.size(); i != e; ++i)
642 Result += (char)Record[i];
646 static bool hasImplicitComdat(size_t Val) {
650 case 1: // Old WeakAnyLinkage
651 case 4: // Old LinkOnceAnyLinkage
652 case 10: // Old WeakODRLinkage
653 case 11: // Old LinkOnceODRLinkage
658 static GlobalValue::LinkageTypes getDecodedLinkage(unsigned Val) {
660 default: // Map unknown/new linkages to external
662 return GlobalValue::ExternalLinkage;
664 return GlobalValue::AppendingLinkage;
666 return GlobalValue::InternalLinkage;
668 return GlobalValue::ExternalLinkage; // Obsolete DLLImportLinkage
670 return GlobalValue::ExternalLinkage; // Obsolete DLLExportLinkage
672 return GlobalValue::ExternalWeakLinkage;
674 return GlobalValue::CommonLinkage;
676 return GlobalValue::PrivateLinkage;
678 return GlobalValue::AvailableExternallyLinkage;
680 return GlobalValue::PrivateLinkage; // Obsolete LinkerPrivateLinkage
682 return GlobalValue::PrivateLinkage; // Obsolete LinkerPrivateWeakLinkage
684 return GlobalValue::ExternalLinkage; // Obsolete LinkOnceODRAutoHideLinkage
685 case 1: // Old value with implicit comdat.
687 return GlobalValue::WeakAnyLinkage;
688 case 10: // Old value with implicit comdat.
690 return GlobalValue::WeakODRLinkage;
691 case 4: // Old value with implicit comdat.
693 return GlobalValue::LinkOnceAnyLinkage;
694 case 11: // Old value with implicit comdat.
696 return GlobalValue::LinkOnceODRLinkage;
700 static GlobalValue::VisibilityTypes getDecodedVisibility(unsigned Val) {
702 default: // Map unknown visibilities to default.
703 case 0: return GlobalValue::DefaultVisibility;
704 case 1: return GlobalValue::HiddenVisibility;
705 case 2: return GlobalValue::ProtectedVisibility;
709 static GlobalValue::DLLStorageClassTypes
710 getDecodedDLLStorageClass(unsigned Val) {
712 default: // Map unknown values to default.
713 case 0: return GlobalValue::DefaultStorageClass;
714 case 1: return GlobalValue::DLLImportStorageClass;
715 case 2: return GlobalValue::DLLExportStorageClass;
719 static GlobalVariable::ThreadLocalMode getDecodedThreadLocalMode(unsigned Val) {
721 case 0: return GlobalVariable::NotThreadLocal;
722 default: // Map unknown non-zero value to general dynamic.
723 case 1: return GlobalVariable::GeneralDynamicTLSModel;
724 case 2: return GlobalVariable::LocalDynamicTLSModel;
725 case 3: return GlobalVariable::InitialExecTLSModel;
726 case 4: return GlobalVariable::LocalExecTLSModel;
730 static int getDecodedCastOpcode(unsigned Val) {
733 case bitc::CAST_TRUNC : return Instruction::Trunc;
734 case bitc::CAST_ZEXT : return Instruction::ZExt;
735 case bitc::CAST_SEXT : return Instruction::SExt;
736 case bitc::CAST_FPTOUI : return Instruction::FPToUI;
737 case bitc::CAST_FPTOSI : return Instruction::FPToSI;
738 case bitc::CAST_UITOFP : return Instruction::UIToFP;
739 case bitc::CAST_SITOFP : return Instruction::SIToFP;
740 case bitc::CAST_FPTRUNC : return Instruction::FPTrunc;
741 case bitc::CAST_FPEXT : return Instruction::FPExt;
742 case bitc::CAST_PTRTOINT: return Instruction::PtrToInt;
743 case bitc::CAST_INTTOPTR: return Instruction::IntToPtr;
744 case bitc::CAST_BITCAST : return Instruction::BitCast;
745 case bitc::CAST_ADDRSPACECAST: return Instruction::AddrSpaceCast;
749 static int getDecodedBinaryOpcode(unsigned Val, Type *Ty) {
750 bool IsFP = Ty->isFPOrFPVectorTy();
751 // BinOps are only valid for int/fp or vector of int/fp types
752 if (!IsFP && !Ty->isIntOrIntVectorTy())
758 case bitc::BINOP_ADD:
759 return IsFP ? Instruction::FAdd : Instruction::Add;
760 case bitc::BINOP_SUB:
761 return IsFP ? Instruction::FSub : Instruction::Sub;
762 case bitc::BINOP_MUL:
763 return IsFP ? Instruction::FMul : Instruction::Mul;
764 case bitc::BINOP_UDIV:
765 return IsFP ? -1 : Instruction::UDiv;
766 case bitc::BINOP_SDIV:
767 return IsFP ? Instruction::FDiv : Instruction::SDiv;
768 case bitc::BINOP_UREM:
769 return IsFP ? -1 : Instruction::URem;
770 case bitc::BINOP_SREM:
771 return IsFP ? Instruction::FRem : Instruction::SRem;
772 case bitc::BINOP_SHL:
773 return IsFP ? -1 : Instruction::Shl;
774 case bitc::BINOP_LSHR:
775 return IsFP ? -1 : Instruction::LShr;
776 case bitc::BINOP_ASHR:
777 return IsFP ? -1 : Instruction::AShr;
778 case bitc::BINOP_AND:
779 return IsFP ? -1 : Instruction::And;
781 return IsFP ? -1 : Instruction::Or;
782 case bitc::BINOP_XOR:
783 return IsFP ? -1 : Instruction::Xor;
787 static AtomicRMWInst::BinOp getDecodedRMWOperation(unsigned Val) {
789 default: return AtomicRMWInst::BAD_BINOP;
790 case bitc::RMW_XCHG: return AtomicRMWInst::Xchg;
791 case bitc::RMW_ADD: return AtomicRMWInst::Add;
792 case bitc::RMW_SUB: return AtomicRMWInst::Sub;
793 case bitc::RMW_AND: return AtomicRMWInst::And;
794 case bitc::RMW_NAND: return AtomicRMWInst::Nand;
795 case bitc::RMW_OR: return AtomicRMWInst::Or;
796 case bitc::RMW_XOR: return AtomicRMWInst::Xor;
797 case bitc::RMW_MAX: return AtomicRMWInst::Max;
798 case bitc::RMW_MIN: return AtomicRMWInst::Min;
799 case bitc::RMW_UMAX: return AtomicRMWInst::UMax;
800 case bitc::RMW_UMIN: return AtomicRMWInst::UMin;
804 static AtomicOrdering getDecodedOrdering(unsigned Val) {
806 case bitc::ORDERING_NOTATOMIC: return NotAtomic;
807 case bitc::ORDERING_UNORDERED: return Unordered;
808 case bitc::ORDERING_MONOTONIC: return Monotonic;
809 case bitc::ORDERING_ACQUIRE: return Acquire;
810 case bitc::ORDERING_RELEASE: return Release;
811 case bitc::ORDERING_ACQREL: return AcquireRelease;
812 default: // Map unknown orderings to sequentially-consistent.
813 case bitc::ORDERING_SEQCST: return SequentiallyConsistent;
817 static SynchronizationScope getDecodedSynchScope(unsigned Val) {
819 case bitc::SYNCHSCOPE_SINGLETHREAD: return SingleThread;
820 default: // Map unknown scopes to cross-thread.
821 case bitc::SYNCHSCOPE_CROSSTHREAD: return CrossThread;
825 static Comdat::SelectionKind getDecodedComdatSelectionKind(unsigned Val) {
827 default: // Map unknown selection kinds to any.
828 case bitc::COMDAT_SELECTION_KIND_ANY:
830 case bitc::COMDAT_SELECTION_KIND_EXACT_MATCH:
831 return Comdat::ExactMatch;
832 case bitc::COMDAT_SELECTION_KIND_LARGEST:
833 return Comdat::Largest;
834 case bitc::COMDAT_SELECTION_KIND_NO_DUPLICATES:
835 return Comdat::NoDuplicates;
836 case bitc::COMDAT_SELECTION_KIND_SAME_SIZE:
837 return Comdat::SameSize;
841 static FastMathFlags getDecodedFastMathFlags(unsigned Val) {
843 if (0 != (Val & FastMathFlags::UnsafeAlgebra))
844 FMF.setUnsafeAlgebra();
845 if (0 != (Val & FastMathFlags::NoNaNs))
847 if (0 != (Val & FastMathFlags::NoInfs))
849 if (0 != (Val & FastMathFlags::NoSignedZeros))
850 FMF.setNoSignedZeros();
851 if (0 != (Val & FastMathFlags::AllowReciprocal))
852 FMF.setAllowReciprocal();
856 static void upgradeDLLImportExportLinkage(llvm::GlobalValue *GV, unsigned Val) {
858 case 5: GV->setDLLStorageClass(GlobalValue::DLLImportStorageClass); break;
859 case 6: GV->setDLLStorageClass(GlobalValue::DLLExportStorageClass); break;
865 /// \brief A class for maintaining the slot number definition
866 /// as a placeholder for the actual definition for forward constants defs.
867 class ConstantPlaceHolder : public ConstantExpr {
868 void operator=(const ConstantPlaceHolder &) = delete;
871 // allocate space for exactly one operand
872 void *operator new(size_t s) { return User::operator new(s, 1); }
873 explicit ConstantPlaceHolder(Type *Ty, LLVMContext &Context)
874 : ConstantExpr(Ty, Instruction::UserOp1, &Op<0>(), 1) {
875 Op<0>() = UndefValue::get(Type::getInt32Ty(Context));
878 /// \brief Methods to support type inquiry through isa, cast, and dyn_cast.
879 static bool classof(const Value *V) {
880 return isa<ConstantExpr>(V) &&
881 cast<ConstantExpr>(V)->getOpcode() == Instruction::UserOp1;
884 /// Provide fast operand accessors
885 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
889 // FIXME: can we inherit this from ConstantExpr?
891 struct OperandTraits<ConstantPlaceHolder> :
892 public FixedNumOperandTraits<ConstantPlaceHolder, 1> {
894 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ConstantPlaceHolder, Value)
897 bool BitcodeReaderValueList::assignValue(Value *V, unsigned Idx) {
906 WeakVH &OldV = ValuePtrs[Idx];
912 // Handle constants and non-constants (e.g. instrs) differently for
914 if (Constant *PHC = dyn_cast<Constant>(&*OldV)) {
915 ResolveConstants.push_back(std::make_pair(PHC, Idx));
918 // If there was a forward reference to this value, replace it.
919 Value *PrevVal = OldV;
920 // Check operator constraints. We only put cleanuppads or catchpads in
921 // the forward value map if the value is constrained to match.
922 if (CatchPadInst *CatchPad = dyn_cast<CatchPadInst>(PrevVal)) {
923 if (!isa<CatchPadInst>(V))
925 // Delete the dummy basic block that was created with the sentinel
927 BasicBlock *DummyBlock = CatchPad->getUnwindDest();
928 assert(DummyBlock == CatchPad->getNormalDest());
929 CatchPad->dropAllReferences();
931 } else if (isa<CleanupPadInst>(PrevVal)) {
932 if (!isa<CleanupPadInst>(V))
935 OldV->replaceAllUsesWith(V);
943 Constant *BitcodeReaderValueList::getConstantFwdRef(unsigned Idx,
948 if (Value *V = ValuePtrs[Idx]) {
949 if (Ty != V->getType())
950 report_fatal_error("Type mismatch in constant table!");
951 return cast<Constant>(V);
954 // Create and return a placeholder, which will later be RAUW'd.
955 Constant *C = new ConstantPlaceHolder(Ty, Context);
960 Value *BitcodeReaderValueList::getValueFwdRef(unsigned Idx, Type *Ty,
961 OperatorConstraint OC) {
962 // Bail out for a clearly invalid value. This would make us call resize(0)
969 if (Value *V = ValuePtrs[Idx]) {
970 // If the types don't match, it's invalid.
971 if (Ty && Ty != V->getType())
975 // Use dyn_cast to enforce operator constraints
978 return dyn_cast<CatchPadInst>(V);
980 return dyn_cast<CleanupPadInst>(V);
982 llvm_unreachable("Unexpected operator constraint");
986 // No type specified, must be invalid reference.
987 if (!Ty) return nullptr;
989 // Create and return a placeholder, which will later be RAUW'd.
993 V = new Argument(Ty);
996 BasicBlock *BB = BasicBlock::Create(Context);
997 V = CatchPadInst::Create(BB, BB, {});
1001 assert(OC == OC_CleanupPad && "unexpected operator constraint");
1002 V = CleanupPadInst::Create(Context, {});
1010 /// Once all constants are read, this method bulk resolves any forward
1011 /// references. The idea behind this is that we sometimes get constants (such
1012 /// as large arrays) which reference *many* forward ref constants. Replacing
1013 /// each of these causes a lot of thrashing when building/reuniquing the
1014 /// constant. Instead of doing this, we look at all the uses and rewrite all
1015 /// the place holders at once for any constant that uses a placeholder.
1016 void BitcodeReaderValueList::resolveConstantForwardRefs() {
1017 // Sort the values by-pointer so that they are efficient to look up with a
1019 std::sort(ResolveConstants.begin(), ResolveConstants.end());
1021 SmallVector<Constant*, 64> NewOps;
1023 while (!ResolveConstants.empty()) {
1024 Value *RealVal = operator[](ResolveConstants.back().second);
1025 Constant *Placeholder = ResolveConstants.back().first;
1026 ResolveConstants.pop_back();
1028 // Loop over all users of the placeholder, updating them to reference the
1029 // new value. If they reference more than one placeholder, update them all
1031 while (!Placeholder->use_empty()) {
1032 auto UI = Placeholder->user_begin();
1035 // If the using object isn't uniqued, just update the operands. This
1036 // handles instructions and initializers for global variables.
1037 if (!isa<Constant>(U) || isa<GlobalValue>(U)) {
1038 UI.getUse().set(RealVal);
1042 // Otherwise, we have a constant that uses the placeholder. Replace that
1043 // constant with a new constant that has *all* placeholder uses updated.
1044 Constant *UserC = cast<Constant>(U);
1045 for (User::op_iterator I = UserC->op_begin(), E = UserC->op_end();
1048 if (!isa<ConstantPlaceHolder>(*I)) {
1049 // Not a placeholder reference.
1051 } else if (*I == Placeholder) {
1052 // Common case is that it just references this one placeholder.
1055 // Otherwise, look up the placeholder in ResolveConstants.
1056 ResolveConstantsTy::iterator It =
1057 std::lower_bound(ResolveConstants.begin(), ResolveConstants.end(),
1058 std::pair<Constant*, unsigned>(cast<Constant>(*I),
1060 assert(It != ResolveConstants.end() && It->first == *I);
1061 NewOp = operator[](It->second);
1064 NewOps.push_back(cast<Constant>(NewOp));
1067 // Make the new constant.
1069 if (ConstantArray *UserCA = dyn_cast<ConstantArray>(UserC)) {
1070 NewC = ConstantArray::get(UserCA->getType(), NewOps);
1071 } else if (ConstantStruct *UserCS = dyn_cast<ConstantStruct>(UserC)) {
1072 NewC = ConstantStruct::get(UserCS->getType(), NewOps);
1073 } else if (isa<ConstantVector>(UserC)) {
1074 NewC = ConstantVector::get(NewOps);
1076 assert(isa<ConstantExpr>(UserC) && "Must be a ConstantExpr.");
1077 NewC = cast<ConstantExpr>(UserC)->getWithOperands(NewOps);
1080 UserC->replaceAllUsesWith(NewC);
1081 UserC->destroyConstant();
1085 // Update all ValueHandles, they should be the only users at this point.
1086 Placeholder->replaceAllUsesWith(RealVal);
1091 void BitcodeReaderMDValueList::assignValue(Metadata *MD, unsigned Idx) {
1092 if (Idx == size()) {
1100 TrackingMDRef &OldMD = MDValuePtrs[Idx];
1106 // If there was a forward reference to this value, replace it.
1107 TempMDTuple PrevMD(cast<MDTuple>(OldMD.get()));
1108 PrevMD->replaceAllUsesWith(MD);
1112 Metadata *BitcodeReaderMDValueList::getValueFwdRef(unsigned Idx) {
1116 if (Metadata *MD = MDValuePtrs[Idx])
1119 // Track forward refs to be resolved later.
1121 MinFwdRef = std::min(MinFwdRef, Idx);
1122 MaxFwdRef = std::max(MaxFwdRef, Idx);
1125 MinFwdRef = MaxFwdRef = Idx;
1129 // Create and return a placeholder, which will later be RAUW'd.
1130 Metadata *MD = MDNode::getTemporary(Context, None).release();
1131 MDValuePtrs[Idx].reset(MD);
1135 void BitcodeReaderMDValueList::tryToResolveCycles() {
1141 // Still forward references... can't resolve cycles.
1144 // Resolve any cycles.
1145 for (unsigned I = MinFwdRef, E = MaxFwdRef + 1; I != E; ++I) {
1146 auto &MD = MDValuePtrs[I];
1147 auto *N = dyn_cast_or_null<MDNode>(MD);
1151 assert(!N->isTemporary() && "Unexpected forward reference");
1155 // Make sure we return early again until there's another forward ref.
1159 Type *BitcodeReader::getTypeByID(unsigned ID) {
1160 // The type table size is always specified correctly.
1161 if (ID >= TypeList.size())
1164 if (Type *Ty = TypeList[ID])
1167 // If we have a forward reference, the only possible case is when it is to a
1168 // named struct. Just create a placeholder for now.
1169 return TypeList[ID] = createIdentifiedStructType(Context);
1172 StructType *BitcodeReader::createIdentifiedStructType(LLVMContext &Context,
1174 auto *Ret = StructType::create(Context, Name);
1175 IdentifiedStructTypes.push_back(Ret);
1179 StructType *BitcodeReader::createIdentifiedStructType(LLVMContext &Context) {
1180 auto *Ret = StructType::create(Context);
1181 IdentifiedStructTypes.push_back(Ret);
1186 //===----------------------------------------------------------------------===//
1187 // Functions for parsing blocks from the bitcode file
1188 //===----------------------------------------------------------------------===//
1191 /// \brief This fills an AttrBuilder object with the LLVM attributes that have
1192 /// been decoded from the given integer. This function must stay in sync with
1193 /// 'encodeLLVMAttributesForBitcode'.
1194 static void decodeLLVMAttributesForBitcode(AttrBuilder &B,
1195 uint64_t EncodedAttrs) {
1196 // FIXME: Remove in 4.0.
1198 // The alignment is stored as a 16-bit raw value from bits 31--16. We shift
1199 // the bits above 31 down by 11 bits.
1200 unsigned Alignment = (EncodedAttrs & (0xffffULL << 16)) >> 16;
1201 assert((!Alignment || isPowerOf2_32(Alignment)) &&
1202 "Alignment must be a power of two.");
1205 B.addAlignmentAttr(Alignment);
1206 B.addRawValue(((EncodedAttrs & (0xfffffULL << 32)) >> 11) |
1207 (EncodedAttrs & 0xffff));
1210 std::error_code BitcodeReader::parseAttributeBlock() {
1211 if (Stream.EnterSubBlock(bitc::PARAMATTR_BLOCK_ID))
1212 return error("Invalid record");
1214 if (!MAttributes.empty())
1215 return error("Invalid multiple blocks");
1217 SmallVector<uint64_t, 64> Record;
1219 SmallVector<AttributeSet, 8> Attrs;
1221 // Read all the records.
1223 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1225 switch (Entry.Kind) {
1226 case BitstreamEntry::SubBlock: // Handled for us already.
1227 case BitstreamEntry::Error:
1228 return error("Malformed block");
1229 case BitstreamEntry::EndBlock:
1230 return std::error_code();
1231 case BitstreamEntry::Record:
1232 // The interesting case.
1238 switch (Stream.readRecord(Entry.ID, Record)) {
1239 default: // Default behavior: ignore.
1241 case bitc::PARAMATTR_CODE_ENTRY_OLD: { // ENTRY: [paramidx0, attr0, ...]
1242 // FIXME: Remove in 4.0.
1243 if (Record.size() & 1)
1244 return error("Invalid record");
1246 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
1248 decodeLLVMAttributesForBitcode(B, Record[i+1]);
1249 Attrs.push_back(AttributeSet::get(Context, Record[i], B));
1252 MAttributes.push_back(AttributeSet::get(Context, Attrs));
1256 case bitc::PARAMATTR_CODE_ENTRY: { // ENTRY: [attrgrp0, attrgrp1, ...]
1257 for (unsigned i = 0, e = Record.size(); i != e; ++i)
1258 Attrs.push_back(MAttributeGroups[Record[i]]);
1260 MAttributes.push_back(AttributeSet::get(Context, Attrs));
1268 // Returns Attribute::None on unrecognized codes.
1269 static Attribute::AttrKind getAttrFromCode(uint64_t Code) {
1272 return Attribute::None;
1273 case bitc::ATTR_KIND_ALIGNMENT:
1274 return Attribute::Alignment;
1275 case bitc::ATTR_KIND_ALWAYS_INLINE:
1276 return Attribute::AlwaysInline;
1277 case bitc::ATTR_KIND_ARGMEMONLY:
1278 return Attribute::ArgMemOnly;
1279 case bitc::ATTR_KIND_BUILTIN:
1280 return Attribute::Builtin;
1281 case bitc::ATTR_KIND_BY_VAL:
1282 return Attribute::ByVal;
1283 case bitc::ATTR_KIND_IN_ALLOCA:
1284 return Attribute::InAlloca;
1285 case bitc::ATTR_KIND_COLD:
1286 return Attribute::Cold;
1287 case bitc::ATTR_KIND_CONVERGENT:
1288 return Attribute::Convergent;
1289 case bitc::ATTR_KIND_INLINE_HINT:
1290 return Attribute::InlineHint;
1291 case bitc::ATTR_KIND_IN_REG:
1292 return Attribute::InReg;
1293 case bitc::ATTR_KIND_JUMP_TABLE:
1294 return Attribute::JumpTable;
1295 case bitc::ATTR_KIND_MIN_SIZE:
1296 return Attribute::MinSize;
1297 case bitc::ATTR_KIND_NAKED:
1298 return Attribute::Naked;
1299 case bitc::ATTR_KIND_NEST:
1300 return Attribute::Nest;
1301 case bitc::ATTR_KIND_NO_ALIAS:
1302 return Attribute::NoAlias;
1303 case bitc::ATTR_KIND_NO_BUILTIN:
1304 return Attribute::NoBuiltin;
1305 case bitc::ATTR_KIND_NO_CAPTURE:
1306 return Attribute::NoCapture;
1307 case bitc::ATTR_KIND_NO_DUPLICATE:
1308 return Attribute::NoDuplicate;
1309 case bitc::ATTR_KIND_NO_IMPLICIT_FLOAT:
1310 return Attribute::NoImplicitFloat;
1311 case bitc::ATTR_KIND_NO_INLINE:
1312 return Attribute::NoInline;
1313 case bitc::ATTR_KIND_NO_RECURSE:
1314 return Attribute::NoRecurse;
1315 case bitc::ATTR_KIND_NON_LAZY_BIND:
1316 return Attribute::NonLazyBind;
1317 case bitc::ATTR_KIND_NON_NULL:
1318 return Attribute::NonNull;
1319 case bitc::ATTR_KIND_DEREFERENCEABLE:
1320 return Attribute::Dereferenceable;
1321 case bitc::ATTR_KIND_DEREFERENCEABLE_OR_NULL:
1322 return Attribute::DereferenceableOrNull;
1323 case bitc::ATTR_KIND_NO_RED_ZONE:
1324 return Attribute::NoRedZone;
1325 case bitc::ATTR_KIND_NO_RETURN:
1326 return Attribute::NoReturn;
1327 case bitc::ATTR_KIND_NO_UNWIND:
1328 return Attribute::NoUnwind;
1329 case bitc::ATTR_KIND_OPTIMIZE_FOR_SIZE:
1330 return Attribute::OptimizeForSize;
1331 case bitc::ATTR_KIND_OPTIMIZE_NONE:
1332 return Attribute::OptimizeNone;
1333 case bitc::ATTR_KIND_READ_NONE:
1334 return Attribute::ReadNone;
1335 case bitc::ATTR_KIND_READ_ONLY:
1336 return Attribute::ReadOnly;
1337 case bitc::ATTR_KIND_RETURNED:
1338 return Attribute::Returned;
1339 case bitc::ATTR_KIND_RETURNS_TWICE:
1340 return Attribute::ReturnsTwice;
1341 case bitc::ATTR_KIND_S_EXT:
1342 return Attribute::SExt;
1343 case bitc::ATTR_KIND_STACK_ALIGNMENT:
1344 return Attribute::StackAlignment;
1345 case bitc::ATTR_KIND_STACK_PROTECT:
1346 return Attribute::StackProtect;
1347 case bitc::ATTR_KIND_STACK_PROTECT_REQ:
1348 return Attribute::StackProtectReq;
1349 case bitc::ATTR_KIND_STACK_PROTECT_STRONG:
1350 return Attribute::StackProtectStrong;
1351 case bitc::ATTR_KIND_SAFESTACK:
1352 return Attribute::SafeStack;
1353 case bitc::ATTR_KIND_STRUCT_RET:
1354 return Attribute::StructRet;
1355 case bitc::ATTR_KIND_SANITIZE_ADDRESS:
1356 return Attribute::SanitizeAddress;
1357 case bitc::ATTR_KIND_SANITIZE_THREAD:
1358 return Attribute::SanitizeThread;
1359 case bitc::ATTR_KIND_SANITIZE_MEMORY:
1360 return Attribute::SanitizeMemory;
1361 case bitc::ATTR_KIND_UW_TABLE:
1362 return Attribute::UWTable;
1363 case bitc::ATTR_KIND_Z_EXT:
1364 return Attribute::ZExt;
1368 std::error_code BitcodeReader::parseAlignmentValue(uint64_t Exponent,
1369 unsigned &Alignment) {
1370 // Note: Alignment in bitcode files is incremented by 1, so that zero
1371 // can be used for default alignment.
1372 if (Exponent > Value::MaxAlignmentExponent + 1)
1373 return error("Invalid alignment value");
1374 Alignment = (1 << static_cast<unsigned>(Exponent)) >> 1;
1375 return std::error_code();
1378 std::error_code BitcodeReader::parseAttrKind(uint64_t Code,
1379 Attribute::AttrKind *Kind) {
1380 *Kind = getAttrFromCode(Code);
1381 if (*Kind == Attribute::None)
1382 return error(BitcodeError::CorruptedBitcode,
1383 "Unknown attribute kind (" + Twine(Code) + ")");
1384 return std::error_code();
1387 std::error_code BitcodeReader::parseAttributeGroupBlock() {
1388 if (Stream.EnterSubBlock(bitc::PARAMATTR_GROUP_BLOCK_ID))
1389 return error("Invalid record");
1391 if (!MAttributeGroups.empty())
1392 return error("Invalid multiple blocks");
1394 SmallVector<uint64_t, 64> Record;
1396 // Read all the records.
1398 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1400 switch (Entry.Kind) {
1401 case BitstreamEntry::SubBlock: // Handled for us already.
1402 case BitstreamEntry::Error:
1403 return error("Malformed block");
1404 case BitstreamEntry::EndBlock:
1405 return std::error_code();
1406 case BitstreamEntry::Record:
1407 // The interesting case.
1413 switch (Stream.readRecord(Entry.ID, Record)) {
1414 default: // Default behavior: ignore.
1416 case bitc::PARAMATTR_GRP_CODE_ENTRY: { // ENTRY: [grpid, idx, a0, a1, ...]
1417 if (Record.size() < 3)
1418 return error("Invalid record");
1420 uint64_t GrpID = Record[0];
1421 uint64_t Idx = Record[1]; // Index of the object this attribute refers to.
1424 for (unsigned i = 2, e = Record.size(); i != e; ++i) {
1425 if (Record[i] == 0) { // Enum attribute
1426 Attribute::AttrKind Kind;
1427 if (std::error_code EC = parseAttrKind(Record[++i], &Kind))
1430 B.addAttribute(Kind);
1431 } else if (Record[i] == 1) { // Integer attribute
1432 Attribute::AttrKind Kind;
1433 if (std::error_code EC = parseAttrKind(Record[++i], &Kind))
1435 if (Kind == Attribute::Alignment)
1436 B.addAlignmentAttr(Record[++i]);
1437 else if (Kind == Attribute::StackAlignment)
1438 B.addStackAlignmentAttr(Record[++i]);
1439 else if (Kind == Attribute::Dereferenceable)
1440 B.addDereferenceableAttr(Record[++i]);
1441 else if (Kind == Attribute::DereferenceableOrNull)
1442 B.addDereferenceableOrNullAttr(Record[++i]);
1443 } else { // String attribute
1444 assert((Record[i] == 3 || Record[i] == 4) &&
1445 "Invalid attribute group entry");
1446 bool HasValue = (Record[i++] == 4);
1447 SmallString<64> KindStr;
1448 SmallString<64> ValStr;
1450 while (Record[i] != 0 && i != e)
1451 KindStr += Record[i++];
1452 assert(Record[i] == 0 && "Kind string not null terminated");
1455 // Has a value associated with it.
1456 ++i; // Skip the '0' that terminates the "kind" string.
1457 while (Record[i] != 0 && i != e)
1458 ValStr += Record[i++];
1459 assert(Record[i] == 0 && "Value string not null terminated");
1462 B.addAttribute(KindStr.str(), ValStr.str());
1466 MAttributeGroups[GrpID] = AttributeSet::get(Context, Idx, B);
1473 std::error_code BitcodeReader::parseTypeTable() {
1474 if (Stream.EnterSubBlock(bitc::TYPE_BLOCK_ID_NEW))
1475 return error("Invalid record");
1477 return parseTypeTableBody();
1480 std::error_code BitcodeReader::parseTypeTableBody() {
1481 if (!TypeList.empty())
1482 return error("Invalid multiple blocks");
1484 SmallVector<uint64_t, 64> Record;
1485 unsigned NumRecords = 0;
1487 SmallString<64> TypeName;
1489 // Read all the records for this type table.
1491 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1493 switch (Entry.Kind) {
1494 case BitstreamEntry::SubBlock: // Handled for us already.
1495 case BitstreamEntry::Error:
1496 return error("Malformed block");
1497 case BitstreamEntry::EndBlock:
1498 if (NumRecords != TypeList.size())
1499 return error("Malformed block");
1500 return std::error_code();
1501 case BitstreamEntry::Record:
1502 // The interesting case.
1508 Type *ResultTy = nullptr;
1509 switch (Stream.readRecord(Entry.ID, Record)) {
1511 return error("Invalid value");
1512 case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries]
1513 // TYPE_CODE_NUMENTRY contains a count of the number of types in the
1514 // type list. This allows us to reserve space.
1515 if (Record.size() < 1)
1516 return error("Invalid record");
1517 TypeList.resize(Record[0]);
1519 case bitc::TYPE_CODE_VOID: // VOID
1520 ResultTy = Type::getVoidTy(Context);
1522 case bitc::TYPE_CODE_HALF: // HALF
1523 ResultTy = Type::getHalfTy(Context);
1525 case bitc::TYPE_CODE_FLOAT: // FLOAT
1526 ResultTy = Type::getFloatTy(Context);
1528 case bitc::TYPE_CODE_DOUBLE: // DOUBLE
1529 ResultTy = Type::getDoubleTy(Context);
1531 case bitc::TYPE_CODE_X86_FP80: // X86_FP80
1532 ResultTy = Type::getX86_FP80Ty(Context);
1534 case bitc::TYPE_CODE_FP128: // FP128
1535 ResultTy = Type::getFP128Ty(Context);
1537 case bitc::TYPE_CODE_PPC_FP128: // PPC_FP128
1538 ResultTy = Type::getPPC_FP128Ty(Context);
1540 case bitc::TYPE_CODE_LABEL: // LABEL
1541 ResultTy = Type::getLabelTy(Context);
1543 case bitc::TYPE_CODE_METADATA: // METADATA
1544 ResultTy = Type::getMetadataTy(Context);
1546 case bitc::TYPE_CODE_X86_MMX: // X86_MMX
1547 ResultTy = Type::getX86_MMXTy(Context);
1549 case bitc::TYPE_CODE_TOKEN: // TOKEN
1550 ResultTy = Type::getTokenTy(Context);
1552 case bitc::TYPE_CODE_INTEGER: { // INTEGER: [width]
1553 if (Record.size() < 1)
1554 return error("Invalid record");
1556 uint64_t NumBits = Record[0];
1557 if (NumBits < IntegerType::MIN_INT_BITS ||
1558 NumBits > IntegerType::MAX_INT_BITS)
1559 return error("Bitwidth for integer type out of range");
1560 ResultTy = IntegerType::get(Context, NumBits);
1563 case bitc::TYPE_CODE_POINTER: { // POINTER: [pointee type] or
1564 // [pointee type, address space]
1565 if (Record.size() < 1)
1566 return error("Invalid record");
1567 unsigned AddressSpace = 0;
1568 if (Record.size() == 2)
1569 AddressSpace = Record[1];
1570 ResultTy = getTypeByID(Record[0]);
1572 !PointerType::isValidElementType(ResultTy))
1573 return error("Invalid type");
1574 ResultTy = PointerType::get(ResultTy, AddressSpace);
1577 case bitc::TYPE_CODE_FUNCTION_OLD: {
1578 // FIXME: attrid is dead, remove it in LLVM 4.0
1579 // FUNCTION: [vararg, attrid, retty, paramty x N]
1580 if (Record.size() < 3)
1581 return error("Invalid record");
1582 SmallVector<Type*, 8> ArgTys;
1583 for (unsigned i = 3, e = Record.size(); i != e; ++i) {
1584 if (Type *T = getTypeByID(Record[i]))
1585 ArgTys.push_back(T);
1590 ResultTy = getTypeByID(Record[2]);
1591 if (!ResultTy || ArgTys.size() < Record.size()-3)
1592 return error("Invalid type");
1594 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
1597 case bitc::TYPE_CODE_FUNCTION: {
1598 // FUNCTION: [vararg, retty, paramty x N]
1599 if (Record.size() < 2)
1600 return error("Invalid record");
1601 SmallVector<Type*, 8> ArgTys;
1602 for (unsigned i = 2, e = Record.size(); i != e; ++i) {
1603 if (Type *T = getTypeByID(Record[i])) {
1604 if (!FunctionType::isValidArgumentType(T))
1605 return error("Invalid function argument type");
1606 ArgTys.push_back(T);
1612 ResultTy = getTypeByID(Record[1]);
1613 if (!ResultTy || ArgTys.size() < Record.size()-2)
1614 return error("Invalid type");
1616 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
1619 case bitc::TYPE_CODE_STRUCT_ANON: { // STRUCT: [ispacked, eltty x N]
1620 if (Record.size() < 1)
1621 return error("Invalid record");
1622 SmallVector<Type*, 8> EltTys;
1623 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
1624 if (Type *T = getTypeByID(Record[i]))
1625 EltTys.push_back(T);
1629 if (EltTys.size() != Record.size()-1)
1630 return error("Invalid type");
1631 ResultTy = StructType::get(Context, EltTys, Record[0]);
1634 case bitc::TYPE_CODE_STRUCT_NAME: // STRUCT_NAME: [strchr x N]
1635 if (convertToString(Record, 0, TypeName))
1636 return error("Invalid record");
1639 case bitc::TYPE_CODE_STRUCT_NAMED: { // STRUCT: [ispacked, eltty x N]
1640 if (Record.size() < 1)
1641 return error("Invalid record");
1643 if (NumRecords >= TypeList.size())
1644 return error("Invalid TYPE table");
1646 // Check to see if this was forward referenced, if so fill in the temp.
1647 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
1649 Res->setName(TypeName);
1650 TypeList[NumRecords] = nullptr;
1651 } else // Otherwise, create a new struct.
1652 Res = createIdentifiedStructType(Context, TypeName);
1655 SmallVector<Type*, 8> EltTys;
1656 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
1657 if (Type *T = getTypeByID(Record[i]))
1658 EltTys.push_back(T);
1662 if (EltTys.size() != Record.size()-1)
1663 return error("Invalid record");
1664 Res->setBody(EltTys, Record[0]);
1668 case bitc::TYPE_CODE_OPAQUE: { // OPAQUE: []
1669 if (Record.size() != 1)
1670 return error("Invalid record");
1672 if (NumRecords >= TypeList.size())
1673 return error("Invalid TYPE table");
1675 // Check to see if this was forward referenced, if so fill in the temp.
1676 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
1678 Res->setName(TypeName);
1679 TypeList[NumRecords] = nullptr;
1680 } else // Otherwise, create a new struct with no body.
1681 Res = createIdentifiedStructType(Context, TypeName);
1686 case bitc::TYPE_CODE_ARRAY: // ARRAY: [numelts, eltty]
1687 if (Record.size() < 2)
1688 return error("Invalid record");
1689 ResultTy = getTypeByID(Record[1]);
1690 if (!ResultTy || !ArrayType::isValidElementType(ResultTy))
1691 return error("Invalid type");
1692 ResultTy = ArrayType::get(ResultTy, Record[0]);
1694 case bitc::TYPE_CODE_VECTOR: // VECTOR: [numelts, eltty]
1695 if (Record.size() < 2)
1696 return error("Invalid record");
1698 return error("Invalid vector length");
1699 ResultTy = getTypeByID(Record[1]);
1700 if (!ResultTy || !StructType::isValidElementType(ResultTy))
1701 return error("Invalid type");
1702 ResultTy = VectorType::get(ResultTy, Record[0]);
1706 if (NumRecords >= TypeList.size())
1707 return error("Invalid TYPE table");
1708 if (TypeList[NumRecords])
1710 "Invalid TYPE table: Only named structs can be forward referenced");
1711 assert(ResultTy && "Didn't read a type?");
1712 TypeList[NumRecords++] = ResultTy;
1716 std::error_code BitcodeReader::parseOperandBundleTags() {
1717 if (Stream.EnterSubBlock(bitc::OPERAND_BUNDLE_TAGS_BLOCK_ID))
1718 return error("Invalid record");
1720 if (!BundleTags.empty())
1721 return error("Invalid multiple blocks");
1723 SmallVector<uint64_t, 64> Record;
1726 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1728 switch (Entry.Kind) {
1729 case BitstreamEntry::SubBlock: // Handled for us already.
1730 case BitstreamEntry::Error:
1731 return error("Malformed block");
1732 case BitstreamEntry::EndBlock:
1733 return std::error_code();
1734 case BitstreamEntry::Record:
1735 // The interesting case.
1739 // Tags are implicitly mapped to integers by their order.
1741 if (Stream.readRecord(Entry.ID, Record) != bitc::OPERAND_BUNDLE_TAG)
1742 return error("Invalid record");
1744 // OPERAND_BUNDLE_TAG: [strchr x N]
1745 BundleTags.emplace_back();
1746 if (convertToString(Record, 0, BundleTags.back()))
1747 return error("Invalid record");
1752 /// Associate a value with its name from the given index in the provided record.
1753 ErrorOr<Value *> BitcodeReader::recordValue(SmallVectorImpl<uint64_t> &Record,
1754 unsigned NameIndex, Triple &TT) {
1755 SmallString<128> ValueName;
1756 if (convertToString(Record, NameIndex, ValueName))
1757 return error("Invalid record");
1758 unsigned ValueID = Record[0];
1759 if (ValueID >= ValueList.size() || !ValueList[ValueID])
1760 return error("Invalid record");
1761 Value *V = ValueList[ValueID];
1763 StringRef NameStr(ValueName.data(), ValueName.size());
1764 if (NameStr.find_first_of(0) != StringRef::npos)
1765 return error("Invalid value name");
1766 V->setName(NameStr);
1767 auto *GO = dyn_cast<GlobalObject>(V);
1769 if (GO->getComdat() == reinterpret_cast<Comdat *>(1)) {
1770 if (TT.isOSBinFormatMachO())
1771 GO->setComdat(nullptr);
1773 GO->setComdat(TheModule->getOrInsertComdat(V->getName()));
1779 /// Parse the value symbol table at either the current parsing location or
1780 /// at the given bit offset if provided.
1781 std::error_code BitcodeReader::parseValueSymbolTable(uint64_t Offset) {
1782 uint64_t CurrentBit;
1783 // Pass in the Offset to distinguish between calling for the module-level
1784 // VST (where we want to jump to the VST offset) and the function-level
1785 // VST (where we don't).
1787 // Save the current parsing location so we can jump back at the end
1789 CurrentBit = Stream.GetCurrentBitNo();
1790 Stream.JumpToBit(Offset * 32);
1792 // Do some checking if we are in debug mode.
1793 BitstreamEntry Entry = Stream.advance();
1794 assert(Entry.Kind == BitstreamEntry::SubBlock);
1795 assert(Entry.ID == bitc::VALUE_SYMTAB_BLOCK_ID);
1797 // In NDEBUG mode ignore the output so we don't get an unused variable
1803 // Compute the delta between the bitcode indices in the VST (the word offset
1804 // to the word-aligned ENTER_SUBBLOCK for the function block, and that
1805 // expected by the lazy reader. The reader's EnterSubBlock expects to have
1806 // already read the ENTER_SUBBLOCK code (size getAbbrevIDWidth) and BlockID
1807 // (size BlockIDWidth). Note that we access the stream's AbbrevID width here
1808 // just before entering the VST subblock because: 1) the EnterSubBlock
1809 // changes the AbbrevID width; 2) the VST block is nested within the same
1810 // outer MODULE_BLOCK as the FUNCTION_BLOCKs and therefore have the same
1811 // AbbrevID width before calling EnterSubBlock; and 3) when we want to
1812 // jump to the FUNCTION_BLOCK using this offset later, we don't want
1813 // to rely on the stream's AbbrevID width being that of the MODULE_BLOCK.
1814 unsigned FuncBitcodeOffsetDelta =
1815 Stream.getAbbrevIDWidth() + bitc::BlockIDWidth;
1817 if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
1818 return error("Invalid record");
1820 SmallVector<uint64_t, 64> Record;
1822 Triple TT(TheModule->getTargetTriple());
1824 // Read all the records for this value table.
1825 SmallString<128> ValueName;
1827 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1829 switch (Entry.Kind) {
1830 case BitstreamEntry::SubBlock: // Handled for us already.
1831 case BitstreamEntry::Error:
1832 return error("Malformed block");
1833 case BitstreamEntry::EndBlock:
1835 Stream.JumpToBit(CurrentBit);
1836 return std::error_code();
1837 case BitstreamEntry::Record:
1838 // The interesting case.
1844 switch (Stream.readRecord(Entry.ID, Record)) {
1845 default: // Default behavior: unknown type.
1847 case bitc::VST_CODE_ENTRY: { // VST_ENTRY: [valueid, namechar x N]
1848 ErrorOr<Value *> ValOrErr = recordValue(Record, 1, TT);
1849 if (std::error_code EC = ValOrErr.getError())
1854 case bitc::VST_CODE_FNENTRY: {
1855 // VST_FNENTRY: [valueid, offset, namechar x N]
1856 ErrorOr<Value *> ValOrErr = recordValue(Record, 2, TT);
1857 if (std::error_code EC = ValOrErr.getError())
1859 Value *V = ValOrErr.get();
1861 auto *GO = dyn_cast<GlobalObject>(V);
1863 // If this is an alias, need to get the actual Function object
1864 // it aliases, in order to set up the DeferredFunctionInfo entry below.
1865 auto *GA = dyn_cast<GlobalAlias>(V);
1867 GO = GA->getBaseObject();
1871 uint64_t FuncWordOffset = Record[1];
1872 Function *F = dyn_cast<Function>(GO);
1874 uint64_t FuncBitOffset = FuncWordOffset * 32;
1875 DeferredFunctionInfo[F] = FuncBitOffset + FuncBitcodeOffsetDelta;
1876 // Set the LastFunctionBlockBit to point to the last function block.
1877 // Later when parsing is resumed after function materialization,
1878 // we can simply skip that last function block.
1879 if (FuncBitOffset > LastFunctionBlockBit)
1880 LastFunctionBlockBit = FuncBitOffset;
1883 case bitc::VST_CODE_BBENTRY: {
1884 if (convertToString(Record, 1, ValueName))
1885 return error("Invalid record");
1886 BasicBlock *BB = getBasicBlock(Record[0]);
1888 return error("Invalid record");
1890 BB->setName(StringRef(ValueName.data(), ValueName.size()));
1898 /// Parse a single METADATA_KIND record, inserting result in MDKindMap.
1900 BitcodeReader::parseMetadataKindRecord(SmallVectorImpl<uint64_t> &Record) {
1901 if (Record.size() < 2)
1902 return error("Invalid record");
1904 unsigned Kind = Record[0];
1905 SmallString<8> Name(Record.begin() + 1, Record.end());
1907 unsigned NewKind = TheModule->getMDKindID(Name.str());
1908 if (!MDKindMap.insert(std::make_pair(Kind, NewKind)).second)
1909 return error("Conflicting METADATA_KIND records");
1910 return std::error_code();
1913 static int64_t unrotateSign(uint64_t U) { return U & 1 ? ~(U >> 1) : U >> 1; }
1915 std::error_code BitcodeReader::parseMetadata() {
1916 IsMetadataMaterialized = true;
1917 unsigned NextMDValueNo = MDValueList.size();
1919 if (Stream.EnterSubBlock(bitc::METADATA_BLOCK_ID))
1920 return error("Invalid record");
1922 SmallVector<uint64_t, 64> Record;
1925 [&](unsigned ID) -> Metadata *{ return MDValueList.getValueFwdRef(ID); };
1926 auto getMDOrNull = [&](unsigned ID) -> Metadata *{
1928 return getMD(ID - 1);
1931 auto getMDString = [&](unsigned ID) -> MDString *{
1932 // This requires that the ID is not really a forward reference. In
1933 // particular, the MDString must already have been resolved.
1934 return cast_or_null<MDString>(getMDOrNull(ID));
1937 #define GET_OR_DISTINCT(CLASS, DISTINCT, ARGS) \
1938 (DISTINCT ? CLASS::getDistinct ARGS : CLASS::get ARGS)
1940 // Read all the records.
1942 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1944 switch (Entry.Kind) {
1945 case BitstreamEntry::SubBlock: // Handled for us already.
1946 case BitstreamEntry::Error:
1947 return error("Malformed block");
1948 case BitstreamEntry::EndBlock:
1949 MDValueList.tryToResolveCycles();
1950 return std::error_code();
1951 case BitstreamEntry::Record:
1952 // The interesting case.
1958 unsigned Code = Stream.readRecord(Entry.ID, Record);
1959 bool IsDistinct = false;
1961 default: // Default behavior: ignore.
1963 case bitc::METADATA_NAME: {
1964 // Read name of the named metadata.
1965 SmallString<8> Name(Record.begin(), Record.end());
1967 Code = Stream.ReadCode();
1969 unsigned NextBitCode = Stream.readRecord(Code, Record);
1970 if (NextBitCode != bitc::METADATA_NAMED_NODE)
1971 return error("METADATA_NAME not followed by METADATA_NAMED_NODE");
1973 // Read named metadata elements.
1974 unsigned Size = Record.size();
1975 NamedMDNode *NMD = TheModule->getOrInsertNamedMetadata(Name);
1976 for (unsigned i = 0; i != Size; ++i) {
1977 MDNode *MD = dyn_cast_or_null<MDNode>(MDValueList.getValueFwdRef(Record[i]));
1979 return error("Invalid record");
1980 NMD->addOperand(MD);
1984 case bitc::METADATA_OLD_FN_NODE: {
1985 // FIXME: Remove in 4.0.
1986 // This is a LocalAsMetadata record, the only type of function-local
1988 if (Record.size() % 2 == 1)
1989 return error("Invalid record");
1991 // If this isn't a LocalAsMetadata record, we're dropping it. This used
1992 // to be legal, but there's no upgrade path.
1993 auto dropRecord = [&] {
1994 MDValueList.assignValue(MDNode::get(Context, None), NextMDValueNo++);
1996 if (Record.size() != 2) {
2001 Type *Ty = getTypeByID(Record[0]);
2002 if (Ty->isMetadataTy() || Ty->isVoidTy()) {
2007 MDValueList.assignValue(
2008 LocalAsMetadata::get(ValueList.getValueFwdRef(Record[1], Ty)),
2012 case bitc::METADATA_OLD_NODE: {
2013 // FIXME: Remove in 4.0.
2014 if (Record.size() % 2 == 1)
2015 return error("Invalid record");
2017 unsigned Size = Record.size();
2018 SmallVector<Metadata *, 8> Elts;
2019 for (unsigned i = 0; i != Size; i += 2) {
2020 Type *Ty = getTypeByID(Record[i]);
2022 return error("Invalid record");
2023 if (Ty->isMetadataTy())
2024 Elts.push_back(MDValueList.getValueFwdRef(Record[i+1]));
2025 else if (!Ty->isVoidTy()) {
2027 ValueAsMetadata::get(ValueList.getValueFwdRef(Record[i + 1], Ty));
2028 assert(isa<ConstantAsMetadata>(MD) &&
2029 "Expected non-function-local metadata");
2032 Elts.push_back(nullptr);
2034 MDValueList.assignValue(MDNode::get(Context, Elts), NextMDValueNo++);
2037 case bitc::METADATA_VALUE: {
2038 if (Record.size() != 2)
2039 return error("Invalid record");
2041 Type *Ty = getTypeByID(Record[0]);
2042 if (Ty->isMetadataTy() || Ty->isVoidTy())
2043 return error("Invalid record");
2045 MDValueList.assignValue(
2046 ValueAsMetadata::get(ValueList.getValueFwdRef(Record[1], Ty)),
2050 case bitc::METADATA_DISTINCT_NODE:
2053 case bitc::METADATA_NODE: {
2054 SmallVector<Metadata *, 8> Elts;
2055 Elts.reserve(Record.size());
2056 for (unsigned ID : Record)
2057 Elts.push_back(ID ? MDValueList.getValueFwdRef(ID - 1) : nullptr);
2058 MDValueList.assignValue(IsDistinct ? MDNode::getDistinct(Context, Elts)
2059 : MDNode::get(Context, Elts),
2063 case bitc::METADATA_LOCATION: {
2064 if (Record.size() != 5)
2065 return error("Invalid record");
2067 unsigned Line = Record[1];
2068 unsigned Column = Record[2];
2069 MDNode *Scope = cast<MDNode>(MDValueList.getValueFwdRef(Record[3]));
2070 Metadata *InlinedAt =
2071 Record[4] ? MDValueList.getValueFwdRef(Record[4] - 1) : nullptr;
2072 MDValueList.assignValue(
2073 GET_OR_DISTINCT(DILocation, Record[0],
2074 (Context, Line, Column, Scope, InlinedAt)),
2078 case bitc::METADATA_GENERIC_DEBUG: {
2079 if (Record.size() < 4)
2080 return error("Invalid record");
2082 unsigned Tag = Record[1];
2083 unsigned Version = Record[2];
2085 if (Tag >= 1u << 16 || Version != 0)
2086 return error("Invalid record");
2088 auto *Header = getMDString(Record[3]);
2089 SmallVector<Metadata *, 8> DwarfOps;
2090 for (unsigned I = 4, E = Record.size(); I != E; ++I)
2091 DwarfOps.push_back(Record[I] ? MDValueList.getValueFwdRef(Record[I] - 1)
2093 MDValueList.assignValue(GET_OR_DISTINCT(GenericDINode, Record[0],
2094 (Context, Tag, Header, DwarfOps)),
2098 case bitc::METADATA_SUBRANGE: {
2099 if (Record.size() != 3)
2100 return error("Invalid record");
2102 MDValueList.assignValue(
2103 GET_OR_DISTINCT(DISubrange, Record[0],
2104 (Context, Record[1], unrotateSign(Record[2]))),
2108 case bitc::METADATA_ENUMERATOR: {
2109 if (Record.size() != 3)
2110 return error("Invalid record");
2112 MDValueList.assignValue(GET_OR_DISTINCT(DIEnumerator, Record[0],
2113 (Context, unrotateSign(Record[1]),
2114 getMDString(Record[2]))),
2118 case bitc::METADATA_BASIC_TYPE: {
2119 if (Record.size() != 6)
2120 return error("Invalid record");
2122 MDValueList.assignValue(
2123 GET_OR_DISTINCT(DIBasicType, Record[0],
2124 (Context, Record[1], getMDString(Record[2]),
2125 Record[3], Record[4], Record[5])),
2129 case bitc::METADATA_DERIVED_TYPE: {
2130 if (Record.size() != 12)
2131 return error("Invalid record");
2133 MDValueList.assignValue(
2134 GET_OR_DISTINCT(DIDerivedType, Record[0],
2135 (Context, Record[1], getMDString(Record[2]),
2136 getMDOrNull(Record[3]), Record[4],
2137 getMDOrNull(Record[5]), getMDOrNull(Record[6]),
2138 Record[7], Record[8], Record[9], Record[10],
2139 getMDOrNull(Record[11]))),
2143 case bitc::METADATA_COMPOSITE_TYPE: {
2144 if (Record.size() != 16)
2145 return error("Invalid record");
2147 MDValueList.assignValue(
2148 GET_OR_DISTINCT(DICompositeType, Record[0],
2149 (Context, Record[1], getMDString(Record[2]),
2150 getMDOrNull(Record[3]), Record[4],
2151 getMDOrNull(Record[5]), getMDOrNull(Record[6]),
2152 Record[7], Record[8], Record[9], Record[10],
2153 getMDOrNull(Record[11]), Record[12],
2154 getMDOrNull(Record[13]), getMDOrNull(Record[14]),
2155 getMDString(Record[15]))),
2159 case bitc::METADATA_SUBROUTINE_TYPE: {
2160 if (Record.size() != 3)
2161 return error("Invalid record");
2163 MDValueList.assignValue(
2164 GET_OR_DISTINCT(DISubroutineType, Record[0],
2165 (Context, Record[1], getMDOrNull(Record[2]))),
2170 case bitc::METADATA_MODULE: {
2171 if (Record.size() != 6)
2172 return error("Invalid record");
2174 MDValueList.assignValue(
2175 GET_OR_DISTINCT(DIModule, Record[0],
2176 (Context, getMDOrNull(Record[1]),
2177 getMDString(Record[2]), getMDString(Record[3]),
2178 getMDString(Record[4]), getMDString(Record[5]))),
2183 case bitc::METADATA_FILE: {
2184 if (Record.size() != 3)
2185 return error("Invalid record");
2187 MDValueList.assignValue(
2188 GET_OR_DISTINCT(DIFile, Record[0], (Context, getMDString(Record[1]),
2189 getMDString(Record[2]))),
2193 case bitc::METADATA_COMPILE_UNIT: {
2194 if (Record.size() < 14 || Record.size() > 15)
2195 return error("Invalid record");
2197 // Ignore Record[1], which indicates whether this compile unit is
2198 // distinct. It's always distinct.
2199 MDValueList.assignValue(
2200 DICompileUnit::getDistinct(
2201 Context, Record[1], getMDOrNull(Record[2]),
2202 getMDString(Record[3]), Record[4], getMDString(Record[5]),
2203 Record[6], getMDString(Record[7]), Record[8],
2204 getMDOrNull(Record[9]), getMDOrNull(Record[10]),
2205 getMDOrNull(Record[11]), getMDOrNull(Record[12]),
2206 getMDOrNull(Record[13]), Record.size() == 14 ? 0 : Record[14]),
2210 case bitc::METADATA_SUBPROGRAM: {
2211 if (Record.size() != 18 && Record.size() != 19)
2212 return error("Invalid record");
2214 bool HasFn = Record.size() == 19;
2215 DISubprogram *SP = GET_OR_DISTINCT(
2217 Record[0] || Record[8], // All definitions should be distinct.
2218 (Context, getMDOrNull(Record[1]), getMDString(Record[2]),
2219 getMDString(Record[3]), getMDOrNull(Record[4]), Record[5],
2220 getMDOrNull(Record[6]), Record[7], Record[8], Record[9],
2221 getMDOrNull(Record[10]), Record[11], Record[12], Record[13],
2222 Record[14], getMDOrNull(Record[15 + HasFn]),
2223 getMDOrNull(Record[16 + HasFn]), getMDOrNull(Record[17 + HasFn])));
2224 MDValueList.assignValue(SP, NextMDValueNo++);
2226 // Upgrade sp->function mapping to function->sp mapping.
2227 if (HasFn && Record[15]) {
2228 if (auto *CMD = dyn_cast<ConstantAsMetadata>(getMDOrNull(Record[15])))
2229 if (auto *F = dyn_cast<Function>(CMD->getValue())) {
2230 if (F->isMaterializable())
2231 // Defer until materialized; unmaterialized functions may not have
2233 FunctionsWithSPs[F] = SP;
2234 else if (!F->empty())
2235 F->setSubprogram(SP);
2240 case bitc::METADATA_LEXICAL_BLOCK: {
2241 if (Record.size() != 5)
2242 return error("Invalid record");
2244 MDValueList.assignValue(
2245 GET_OR_DISTINCT(DILexicalBlock, Record[0],
2246 (Context, getMDOrNull(Record[1]),
2247 getMDOrNull(Record[2]), Record[3], Record[4])),
2251 case bitc::METADATA_LEXICAL_BLOCK_FILE: {
2252 if (Record.size() != 4)
2253 return error("Invalid record");
2255 MDValueList.assignValue(
2256 GET_OR_DISTINCT(DILexicalBlockFile, Record[0],
2257 (Context, getMDOrNull(Record[1]),
2258 getMDOrNull(Record[2]), Record[3])),
2262 case bitc::METADATA_NAMESPACE: {
2263 if (Record.size() != 5)
2264 return error("Invalid record");
2266 MDValueList.assignValue(
2267 GET_OR_DISTINCT(DINamespace, Record[0],
2268 (Context, getMDOrNull(Record[1]),
2269 getMDOrNull(Record[2]), getMDString(Record[3]),
2274 case bitc::METADATA_TEMPLATE_TYPE: {
2275 if (Record.size() != 3)
2276 return error("Invalid record");
2278 MDValueList.assignValue(GET_OR_DISTINCT(DITemplateTypeParameter,
2280 (Context, getMDString(Record[1]),
2281 getMDOrNull(Record[2]))),
2285 case bitc::METADATA_TEMPLATE_VALUE: {
2286 if (Record.size() != 5)
2287 return error("Invalid record");
2289 MDValueList.assignValue(
2290 GET_OR_DISTINCT(DITemplateValueParameter, Record[0],
2291 (Context, Record[1], getMDString(Record[2]),
2292 getMDOrNull(Record[3]), getMDOrNull(Record[4]))),
2296 case bitc::METADATA_GLOBAL_VAR: {
2297 if (Record.size() != 11)
2298 return error("Invalid record");
2300 MDValueList.assignValue(
2301 GET_OR_DISTINCT(DIGlobalVariable, Record[0],
2302 (Context, getMDOrNull(Record[1]),
2303 getMDString(Record[2]), getMDString(Record[3]),
2304 getMDOrNull(Record[4]), Record[5],
2305 getMDOrNull(Record[6]), Record[7], Record[8],
2306 getMDOrNull(Record[9]), getMDOrNull(Record[10]))),
2310 case bitc::METADATA_LOCAL_VAR: {
2311 // 10th field is for the obseleted 'inlinedAt:' field.
2312 if (Record.size() < 8 || Record.size() > 10)
2313 return error("Invalid record");
2315 // 2nd field used to be an artificial tag, either DW_TAG_auto_variable or
2316 // DW_TAG_arg_variable.
2317 bool HasTag = Record.size() > 8;
2318 MDValueList.assignValue(
2319 GET_OR_DISTINCT(DILocalVariable, Record[0],
2320 (Context, getMDOrNull(Record[1 + HasTag]),
2321 getMDString(Record[2 + HasTag]),
2322 getMDOrNull(Record[3 + HasTag]), Record[4 + HasTag],
2323 getMDOrNull(Record[5 + HasTag]), Record[6 + HasTag],
2324 Record[7 + HasTag])),
2328 case bitc::METADATA_EXPRESSION: {
2329 if (Record.size() < 1)
2330 return error("Invalid record");
2332 MDValueList.assignValue(
2333 GET_OR_DISTINCT(DIExpression, Record[0],
2334 (Context, makeArrayRef(Record).slice(1))),
2338 case bitc::METADATA_OBJC_PROPERTY: {
2339 if (Record.size() != 8)
2340 return error("Invalid record");
2342 MDValueList.assignValue(
2343 GET_OR_DISTINCT(DIObjCProperty, Record[0],
2344 (Context, getMDString(Record[1]),
2345 getMDOrNull(Record[2]), Record[3],
2346 getMDString(Record[4]), getMDString(Record[5]),
2347 Record[6], getMDOrNull(Record[7]))),
2351 case bitc::METADATA_IMPORTED_ENTITY: {
2352 if (Record.size() != 6)
2353 return error("Invalid record");
2355 MDValueList.assignValue(
2356 GET_OR_DISTINCT(DIImportedEntity, Record[0],
2357 (Context, Record[1], getMDOrNull(Record[2]),
2358 getMDOrNull(Record[3]), Record[4],
2359 getMDString(Record[5]))),
2363 case bitc::METADATA_STRING: {
2364 std::string String(Record.begin(), Record.end());
2365 llvm::UpgradeMDStringConstant(String);
2366 Metadata *MD = MDString::get(Context, String);
2367 MDValueList.assignValue(MD, NextMDValueNo++);
2370 case bitc::METADATA_KIND: {
2371 // Support older bitcode files that had METADATA_KIND records in a
2372 // block with METADATA_BLOCK_ID.
2373 if (std::error_code EC = parseMetadataKindRecord(Record))
2379 #undef GET_OR_DISTINCT
2382 /// Parse the metadata kinds out of the METADATA_KIND_BLOCK.
2383 std::error_code BitcodeReader::parseMetadataKinds() {
2384 if (Stream.EnterSubBlock(bitc::METADATA_KIND_BLOCK_ID))
2385 return error("Invalid record");
2387 SmallVector<uint64_t, 64> Record;
2389 // Read all the records.
2391 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
2393 switch (Entry.Kind) {
2394 case BitstreamEntry::SubBlock: // Handled for us already.
2395 case BitstreamEntry::Error:
2396 return error("Malformed block");
2397 case BitstreamEntry::EndBlock:
2398 return std::error_code();
2399 case BitstreamEntry::Record:
2400 // The interesting case.
2406 unsigned Code = Stream.readRecord(Entry.ID, Record);
2408 default: // Default behavior: ignore.
2410 case bitc::METADATA_KIND: {
2411 if (std::error_code EC = parseMetadataKindRecord(Record))
2419 /// Decode a signed value stored with the sign bit in the LSB for dense VBR
2421 uint64_t BitcodeReader::decodeSignRotatedValue(uint64_t V) {
2426 // There is no such thing as -0 with integers. "-0" really means MININT.
2430 /// Resolve all of the initializers for global values and aliases that we can.
2431 std::error_code BitcodeReader::resolveGlobalAndAliasInits() {
2432 std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInitWorklist;
2433 std::vector<std::pair<GlobalAlias*, unsigned> > AliasInitWorklist;
2434 std::vector<std::pair<Function*, unsigned> > FunctionPrefixWorklist;
2435 std::vector<std::pair<Function*, unsigned> > FunctionPrologueWorklist;
2436 std::vector<std::pair<Function*, unsigned> > FunctionPersonalityFnWorklist;
2438 GlobalInitWorklist.swap(GlobalInits);
2439 AliasInitWorklist.swap(AliasInits);
2440 FunctionPrefixWorklist.swap(FunctionPrefixes);
2441 FunctionPrologueWorklist.swap(FunctionPrologues);
2442 FunctionPersonalityFnWorklist.swap(FunctionPersonalityFns);
2444 while (!GlobalInitWorklist.empty()) {
2445 unsigned ValID = GlobalInitWorklist.back().second;
2446 if (ValID >= ValueList.size()) {
2447 // Not ready to resolve this yet, it requires something later in the file.
2448 GlobalInits.push_back(GlobalInitWorklist.back());
2450 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
2451 GlobalInitWorklist.back().first->setInitializer(C);
2453 return error("Expected a constant");
2455 GlobalInitWorklist.pop_back();
2458 while (!AliasInitWorklist.empty()) {
2459 unsigned ValID = AliasInitWorklist.back().second;
2460 if (ValID >= ValueList.size()) {
2461 AliasInits.push_back(AliasInitWorklist.back());
2463 Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]);
2465 return error("Expected a constant");
2466 GlobalAlias *Alias = AliasInitWorklist.back().first;
2467 if (C->getType() != Alias->getType())
2468 return error("Alias and aliasee types don't match");
2469 Alias->setAliasee(C);
2471 AliasInitWorklist.pop_back();
2474 while (!FunctionPrefixWorklist.empty()) {
2475 unsigned ValID = FunctionPrefixWorklist.back().second;
2476 if (ValID >= ValueList.size()) {
2477 FunctionPrefixes.push_back(FunctionPrefixWorklist.back());
2479 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
2480 FunctionPrefixWorklist.back().first->setPrefixData(C);
2482 return error("Expected a constant");
2484 FunctionPrefixWorklist.pop_back();
2487 while (!FunctionPrologueWorklist.empty()) {
2488 unsigned ValID = FunctionPrologueWorklist.back().second;
2489 if (ValID >= ValueList.size()) {
2490 FunctionPrologues.push_back(FunctionPrologueWorklist.back());
2492 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
2493 FunctionPrologueWorklist.back().first->setPrologueData(C);
2495 return error("Expected a constant");
2497 FunctionPrologueWorklist.pop_back();
2500 while (!FunctionPersonalityFnWorklist.empty()) {
2501 unsigned ValID = FunctionPersonalityFnWorklist.back().second;
2502 if (ValID >= ValueList.size()) {
2503 FunctionPersonalityFns.push_back(FunctionPersonalityFnWorklist.back());
2505 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
2506 FunctionPersonalityFnWorklist.back().first->setPersonalityFn(C);
2508 return error("Expected a constant");
2510 FunctionPersonalityFnWorklist.pop_back();
2513 return std::error_code();
2516 static APInt readWideAPInt(ArrayRef<uint64_t> Vals, unsigned TypeBits) {
2517 SmallVector<uint64_t, 8> Words(Vals.size());
2518 std::transform(Vals.begin(), Vals.end(), Words.begin(),
2519 BitcodeReader::decodeSignRotatedValue);
2521 return APInt(TypeBits, Words);
2524 std::error_code BitcodeReader::parseConstants() {
2525 if (Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID))
2526 return error("Invalid record");
2528 SmallVector<uint64_t, 64> Record;
2530 // Read all the records for this value table.
2531 Type *CurTy = Type::getInt32Ty(Context);
2532 unsigned NextCstNo = ValueList.size();
2534 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
2536 switch (Entry.Kind) {
2537 case BitstreamEntry::SubBlock: // Handled for us already.
2538 case BitstreamEntry::Error:
2539 return error("Malformed block");
2540 case BitstreamEntry::EndBlock:
2541 if (NextCstNo != ValueList.size())
2542 return error("Invalid ronstant reference");
2544 // Once all the constants have been read, go through and resolve forward
2546 ValueList.resolveConstantForwardRefs();
2547 return std::error_code();
2548 case BitstreamEntry::Record:
2549 // The interesting case.
2556 unsigned BitCode = Stream.readRecord(Entry.ID, Record);
2558 default: // Default behavior: unknown constant
2559 case bitc::CST_CODE_UNDEF: // UNDEF
2560 V = UndefValue::get(CurTy);
2562 case bitc::CST_CODE_SETTYPE: // SETTYPE: [typeid]
2564 return error("Invalid record");
2565 if (Record[0] >= TypeList.size() || !TypeList[Record[0]])
2566 return error("Invalid record");
2567 CurTy = TypeList[Record[0]];
2568 continue; // Skip the ValueList manipulation.
2569 case bitc::CST_CODE_NULL: // NULL
2570 V = Constant::getNullValue(CurTy);
2572 case bitc::CST_CODE_INTEGER: // INTEGER: [intval]
2573 if (!CurTy->isIntegerTy() || Record.empty())
2574 return error("Invalid record");
2575 V = ConstantInt::get(CurTy, decodeSignRotatedValue(Record[0]));
2577 case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval]
2578 if (!CurTy->isIntegerTy() || Record.empty())
2579 return error("Invalid record");
2582 readWideAPInt(Record, cast<IntegerType>(CurTy)->getBitWidth());
2583 V = ConstantInt::get(Context, VInt);
2587 case bitc::CST_CODE_FLOAT: { // FLOAT: [fpval]
2589 return error("Invalid record");
2590 if (CurTy->isHalfTy())
2591 V = ConstantFP::get(Context, APFloat(APFloat::IEEEhalf,
2592 APInt(16, (uint16_t)Record[0])));
2593 else if (CurTy->isFloatTy())
2594 V = ConstantFP::get(Context, APFloat(APFloat::IEEEsingle,
2595 APInt(32, (uint32_t)Record[0])));
2596 else if (CurTy->isDoubleTy())
2597 V = ConstantFP::get(Context, APFloat(APFloat::IEEEdouble,
2598 APInt(64, Record[0])));
2599 else if (CurTy->isX86_FP80Ty()) {
2600 // Bits are not stored the same way as a normal i80 APInt, compensate.
2601 uint64_t Rearrange[2];
2602 Rearrange[0] = (Record[1] & 0xffffLL) | (Record[0] << 16);
2603 Rearrange[1] = Record[0] >> 48;
2604 V = ConstantFP::get(Context, APFloat(APFloat::x87DoubleExtended,
2605 APInt(80, Rearrange)));
2606 } else if (CurTy->isFP128Ty())
2607 V = ConstantFP::get(Context, APFloat(APFloat::IEEEquad,
2608 APInt(128, Record)));
2609 else if (CurTy->isPPC_FP128Ty())
2610 V = ConstantFP::get(Context, APFloat(APFloat::PPCDoubleDouble,
2611 APInt(128, Record)));
2613 V = UndefValue::get(CurTy);
2617 case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number]
2619 return error("Invalid record");
2621 unsigned Size = Record.size();
2622 SmallVector<Constant*, 16> Elts;
2624 if (StructType *STy = dyn_cast<StructType>(CurTy)) {
2625 for (unsigned i = 0; i != Size; ++i)
2626 Elts.push_back(ValueList.getConstantFwdRef(Record[i],
2627 STy->getElementType(i)));
2628 V = ConstantStruct::get(STy, Elts);
2629 } else if (ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) {
2630 Type *EltTy = ATy->getElementType();
2631 for (unsigned i = 0; i != Size; ++i)
2632 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
2633 V = ConstantArray::get(ATy, Elts);
2634 } else if (VectorType *VTy = dyn_cast<VectorType>(CurTy)) {
2635 Type *EltTy = VTy->getElementType();
2636 for (unsigned i = 0; i != Size; ++i)
2637 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
2638 V = ConstantVector::get(Elts);
2640 V = UndefValue::get(CurTy);
2644 case bitc::CST_CODE_STRING: // STRING: [values]
2645 case bitc::CST_CODE_CSTRING: { // CSTRING: [values]
2647 return error("Invalid record");
2649 SmallString<16> Elts(Record.begin(), Record.end());
2650 V = ConstantDataArray::getString(Context, Elts,
2651 BitCode == bitc::CST_CODE_CSTRING);
2654 case bitc::CST_CODE_DATA: {// DATA: [n x value]
2656 return error("Invalid record");
2658 Type *EltTy = cast<SequentialType>(CurTy)->getElementType();
2659 unsigned Size = Record.size();
2661 if (EltTy->isIntegerTy(8)) {
2662 SmallVector<uint8_t, 16> Elts(Record.begin(), Record.end());
2663 if (isa<VectorType>(CurTy))
2664 V = ConstantDataVector::get(Context, Elts);
2666 V = ConstantDataArray::get(Context, Elts);
2667 } else if (EltTy->isIntegerTy(16)) {
2668 SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end());
2669 if (isa<VectorType>(CurTy))
2670 V = ConstantDataVector::get(Context, Elts);
2672 V = ConstantDataArray::get(Context, Elts);
2673 } else if (EltTy->isIntegerTy(32)) {
2674 SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end());
2675 if (isa<VectorType>(CurTy))
2676 V = ConstantDataVector::get(Context, Elts);
2678 V = ConstantDataArray::get(Context, Elts);
2679 } else if (EltTy->isIntegerTy(64)) {
2680 SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end());
2681 if (isa<VectorType>(CurTy))
2682 V = ConstantDataVector::get(Context, Elts);
2684 V = ConstantDataArray::get(Context, Elts);
2685 } else if (EltTy->isFloatTy()) {
2686 SmallVector<float, 16> Elts(Size);
2687 std::transform(Record.begin(), Record.end(), Elts.begin(), BitsToFloat);
2688 if (isa<VectorType>(CurTy))
2689 V = ConstantDataVector::get(Context, Elts);
2691 V = ConstantDataArray::get(Context, Elts);
2692 } else if (EltTy->isDoubleTy()) {
2693 SmallVector<double, 16> Elts(Size);
2694 std::transform(Record.begin(), Record.end(), Elts.begin(),
2696 if (isa<VectorType>(CurTy))
2697 V = ConstantDataVector::get(Context, Elts);
2699 V = ConstantDataArray::get(Context, Elts);
2701 return error("Invalid type for value");
2706 case bitc::CST_CODE_CE_BINOP: { // CE_BINOP: [opcode, opval, opval]
2707 if (Record.size() < 3)
2708 return error("Invalid record");
2709 int Opc = getDecodedBinaryOpcode(Record[0], CurTy);
2711 V = UndefValue::get(CurTy); // Unknown binop.
2713 Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy);
2714 Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy);
2716 if (Record.size() >= 4) {
2717 if (Opc == Instruction::Add ||
2718 Opc == Instruction::Sub ||
2719 Opc == Instruction::Mul ||
2720 Opc == Instruction::Shl) {
2721 if (Record[3] & (1 << bitc::OBO_NO_SIGNED_WRAP))
2722 Flags |= OverflowingBinaryOperator::NoSignedWrap;
2723 if (Record[3] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
2724 Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
2725 } else if (Opc == Instruction::SDiv ||
2726 Opc == Instruction::UDiv ||
2727 Opc == Instruction::LShr ||
2728 Opc == Instruction::AShr) {
2729 if (Record[3] & (1 << bitc::PEO_EXACT))
2730 Flags |= SDivOperator::IsExact;
2733 V = ConstantExpr::get(Opc, LHS, RHS, Flags);
2737 case bitc::CST_CODE_CE_CAST: { // CE_CAST: [opcode, opty, opval]
2738 if (Record.size() < 3)
2739 return error("Invalid record");
2740 int Opc = getDecodedCastOpcode(Record[0]);
2742 V = UndefValue::get(CurTy); // Unknown cast.
2744 Type *OpTy = getTypeByID(Record[1]);
2746 return error("Invalid record");
2747 Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy);
2748 V = UpgradeBitCastExpr(Opc, Op, CurTy);
2749 if (!V) V = ConstantExpr::getCast(Opc, Op, CurTy);
2753 case bitc::CST_CODE_CE_INBOUNDS_GEP:
2754 case bitc::CST_CODE_CE_GEP: { // CE_GEP: [n x operands]
2756 Type *PointeeType = nullptr;
2757 if (Record.size() % 2)
2758 PointeeType = getTypeByID(Record[OpNum++]);
2759 SmallVector<Constant*, 16> Elts;
2760 while (OpNum != Record.size()) {
2761 Type *ElTy = getTypeByID(Record[OpNum++]);
2763 return error("Invalid record");
2764 Elts.push_back(ValueList.getConstantFwdRef(Record[OpNum++], ElTy));
2769 cast<SequentialType>(Elts[0]->getType()->getScalarType())
2771 return error("Explicit gep operator type does not match pointee type "
2772 "of pointer operand");
2774 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
2775 V = ConstantExpr::getGetElementPtr(PointeeType, Elts[0], Indices,
2777 bitc::CST_CODE_CE_INBOUNDS_GEP);
2780 case bitc::CST_CODE_CE_SELECT: { // CE_SELECT: [opval#, opval#, opval#]
2781 if (Record.size() < 3)
2782 return error("Invalid record");
2784 Type *SelectorTy = Type::getInt1Ty(Context);
2786 // The selector might be an i1 or an <n x i1>
2787 // Get the type from the ValueList before getting a forward ref.
2788 if (VectorType *VTy = dyn_cast<VectorType>(CurTy))
2789 if (Value *V = ValueList[Record[0]])
2790 if (SelectorTy != V->getType())
2791 SelectorTy = VectorType::get(SelectorTy, VTy->getNumElements());
2793 V = ConstantExpr::getSelect(ValueList.getConstantFwdRef(Record[0],
2795 ValueList.getConstantFwdRef(Record[1],CurTy),
2796 ValueList.getConstantFwdRef(Record[2],CurTy));
2799 case bitc::CST_CODE_CE_EXTRACTELT
2800 : { // CE_EXTRACTELT: [opty, opval, opty, opval]
2801 if (Record.size() < 3)
2802 return error("Invalid record");
2804 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
2806 return error("Invalid record");
2807 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
2808 Constant *Op1 = nullptr;
2809 if (Record.size() == 4) {
2810 Type *IdxTy = getTypeByID(Record[2]);
2812 return error("Invalid record");
2813 Op1 = ValueList.getConstantFwdRef(Record[3], IdxTy);
2814 } else // TODO: Remove with llvm 4.0
2815 Op1 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
2817 return error("Invalid record");
2818 V = ConstantExpr::getExtractElement(Op0, Op1);
2821 case bitc::CST_CODE_CE_INSERTELT
2822 : { // CE_INSERTELT: [opval, opval, opty, opval]
2823 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
2824 if (Record.size() < 3 || !OpTy)
2825 return error("Invalid record");
2826 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
2827 Constant *Op1 = ValueList.getConstantFwdRef(Record[1],
2828 OpTy->getElementType());
2829 Constant *Op2 = nullptr;
2830 if (Record.size() == 4) {
2831 Type *IdxTy = getTypeByID(Record[2]);
2833 return error("Invalid record");
2834 Op2 = ValueList.getConstantFwdRef(Record[3], IdxTy);
2835 } else // TODO: Remove with llvm 4.0
2836 Op2 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
2838 return error("Invalid record");
2839 V = ConstantExpr::getInsertElement(Op0, Op1, Op2);
2842 case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval]
2843 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
2844 if (Record.size() < 3 || !OpTy)
2845 return error("Invalid record");
2846 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
2847 Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy);
2848 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
2849 OpTy->getNumElements());
2850 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy);
2851 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
2854 case bitc::CST_CODE_CE_SHUFVEC_EX: { // [opty, opval, opval, opval]
2855 VectorType *RTy = dyn_cast<VectorType>(CurTy);
2857 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
2858 if (Record.size() < 4 || !RTy || !OpTy)
2859 return error("Invalid record");
2860 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
2861 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
2862 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
2863 RTy->getNumElements());
2864 Constant *Op2 = ValueList.getConstantFwdRef(Record[3], ShufTy);
2865 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
2868 case bitc::CST_CODE_CE_CMP: { // CE_CMP: [opty, opval, opval, pred]
2869 if (Record.size() < 4)
2870 return error("Invalid record");
2871 Type *OpTy = getTypeByID(Record[0]);
2873 return error("Invalid record");
2874 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
2875 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
2877 if (OpTy->isFPOrFPVectorTy())
2878 V = ConstantExpr::getFCmp(Record[3], Op0, Op1);
2880 V = ConstantExpr::getICmp(Record[3], Op0, Op1);
2883 // This maintains backward compatibility, pre-asm dialect keywords.
2884 // FIXME: Remove with the 4.0 release.
2885 case bitc::CST_CODE_INLINEASM_OLD: {
2886 if (Record.size() < 2)
2887 return error("Invalid record");
2888 std::string AsmStr, ConstrStr;
2889 bool HasSideEffects = Record[0] & 1;
2890 bool IsAlignStack = Record[0] >> 1;
2891 unsigned AsmStrSize = Record[1];
2892 if (2+AsmStrSize >= Record.size())
2893 return error("Invalid record");
2894 unsigned ConstStrSize = Record[2+AsmStrSize];
2895 if (3+AsmStrSize+ConstStrSize > Record.size())
2896 return error("Invalid record");
2898 for (unsigned i = 0; i != AsmStrSize; ++i)
2899 AsmStr += (char)Record[2+i];
2900 for (unsigned i = 0; i != ConstStrSize; ++i)
2901 ConstrStr += (char)Record[3+AsmStrSize+i];
2902 PointerType *PTy = cast<PointerType>(CurTy);
2903 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
2904 AsmStr, ConstrStr, HasSideEffects, IsAlignStack);
2907 // This version adds support for the asm dialect keywords (e.g.,
2909 case bitc::CST_CODE_INLINEASM: {
2910 if (Record.size() < 2)
2911 return error("Invalid record");
2912 std::string AsmStr, ConstrStr;
2913 bool HasSideEffects = Record[0] & 1;
2914 bool IsAlignStack = (Record[0] >> 1) & 1;
2915 unsigned AsmDialect = Record[0] >> 2;
2916 unsigned AsmStrSize = Record[1];
2917 if (2+AsmStrSize >= Record.size())
2918 return error("Invalid record");
2919 unsigned ConstStrSize = Record[2+AsmStrSize];
2920 if (3+AsmStrSize+ConstStrSize > Record.size())
2921 return error("Invalid record");
2923 for (unsigned i = 0; i != AsmStrSize; ++i)
2924 AsmStr += (char)Record[2+i];
2925 for (unsigned i = 0; i != ConstStrSize; ++i)
2926 ConstrStr += (char)Record[3+AsmStrSize+i];
2927 PointerType *PTy = cast<PointerType>(CurTy);
2928 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
2929 AsmStr, ConstrStr, HasSideEffects, IsAlignStack,
2930 InlineAsm::AsmDialect(AsmDialect));
2933 case bitc::CST_CODE_BLOCKADDRESS:{
2934 if (Record.size() < 3)
2935 return error("Invalid record");
2936 Type *FnTy = getTypeByID(Record[0]);
2938 return error("Invalid record");
2940 dyn_cast_or_null<Function>(ValueList.getConstantFwdRef(Record[1],FnTy));
2942 return error("Invalid record");
2944 // Don't let Fn get dematerialized.
2945 BlockAddressesTaken.insert(Fn);
2947 // If the function is already parsed we can insert the block address right
2950 unsigned BBID = Record[2];
2952 // Invalid reference to entry block.
2953 return error("Invalid ID");
2955 Function::iterator BBI = Fn->begin(), BBE = Fn->end();
2956 for (size_t I = 0, E = BBID; I != E; ++I) {
2958 return error("Invalid ID");
2963 // Otherwise insert a placeholder and remember it so it can be inserted
2964 // when the function is parsed.
2965 auto &FwdBBs = BasicBlockFwdRefs[Fn];
2967 BasicBlockFwdRefQueue.push_back(Fn);
2968 if (FwdBBs.size() < BBID + 1)
2969 FwdBBs.resize(BBID + 1);
2971 FwdBBs[BBID] = BasicBlock::Create(Context);
2974 V = BlockAddress::get(Fn, BB);
2979 if (ValueList.assignValue(V, NextCstNo))
2980 return error("Invalid forward reference");
2985 std::error_code BitcodeReader::parseUseLists() {
2986 if (Stream.EnterSubBlock(bitc::USELIST_BLOCK_ID))
2987 return error("Invalid record");
2989 // Read all the records.
2990 SmallVector<uint64_t, 64> Record;
2992 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
2994 switch (Entry.Kind) {
2995 case BitstreamEntry::SubBlock: // Handled for us already.
2996 case BitstreamEntry::Error:
2997 return error("Malformed block");
2998 case BitstreamEntry::EndBlock:
2999 return std::error_code();
3000 case BitstreamEntry::Record:
3001 // The interesting case.
3005 // Read a use list record.
3008 switch (Stream.readRecord(Entry.ID, Record)) {
3009 default: // Default behavior: unknown type.
3011 case bitc::USELIST_CODE_BB:
3014 case bitc::USELIST_CODE_DEFAULT: {
3015 unsigned RecordLength = Record.size();
3016 if (RecordLength < 3)
3017 // Records should have at least an ID and two indexes.
3018 return error("Invalid record");
3019 unsigned ID = Record.back();
3024 assert(ID < FunctionBBs.size() && "Basic block not found");
3025 V = FunctionBBs[ID];
3028 unsigned NumUses = 0;
3029 SmallDenseMap<const Use *, unsigned, 16> Order;
3030 for (const Use &U : V->uses()) {
3031 if (++NumUses > Record.size())
3033 Order[&U] = Record[NumUses - 1];
3035 if (Order.size() != Record.size() || NumUses > Record.size())
3036 // Mismatches can happen if the functions are being materialized lazily
3037 // (out-of-order), or a value has been upgraded.
3040 V->sortUseList([&](const Use &L, const Use &R) {
3041 return Order.lookup(&L) < Order.lookup(&R);
3049 /// When we see the block for metadata, remember where it is and then skip it.
3050 /// This lets us lazily deserialize the metadata.
3051 std::error_code BitcodeReader::rememberAndSkipMetadata() {
3052 // Save the current stream state.
3053 uint64_t CurBit = Stream.GetCurrentBitNo();
3054 DeferredMetadataInfo.push_back(CurBit);
3056 // Skip over the block for now.
3057 if (Stream.SkipBlock())
3058 return error("Invalid record");
3059 return std::error_code();
3062 std::error_code BitcodeReader::materializeMetadata() {
3063 for (uint64_t BitPos : DeferredMetadataInfo) {
3064 // Move the bit stream to the saved position.
3065 Stream.JumpToBit(BitPos);
3066 if (std::error_code EC = parseMetadata())
3069 DeferredMetadataInfo.clear();
3070 return std::error_code();
3073 void BitcodeReader::setStripDebugInfo() { StripDebugInfo = true; }
3075 /// When we see the block for a function body, remember where it is and then
3076 /// skip it. This lets us lazily deserialize the functions.
3077 std::error_code BitcodeReader::rememberAndSkipFunctionBody() {
3078 // Get the function we are talking about.
3079 if (FunctionsWithBodies.empty())
3080 return error("Insufficient function protos");
3082 Function *Fn = FunctionsWithBodies.back();
3083 FunctionsWithBodies.pop_back();
3085 // Save the current stream state.
3086 uint64_t CurBit = Stream.GetCurrentBitNo();
3088 (DeferredFunctionInfo[Fn] == 0 || DeferredFunctionInfo[Fn] == CurBit) &&
3089 "Mismatch between VST and scanned function offsets");
3090 DeferredFunctionInfo[Fn] = CurBit;
3092 // Skip over the function block for now.
3093 if (Stream.SkipBlock())
3094 return error("Invalid record");
3095 return std::error_code();
3098 std::error_code BitcodeReader::globalCleanup() {
3099 // Patch the initializers for globals and aliases up.
3100 resolveGlobalAndAliasInits();
3101 if (!GlobalInits.empty() || !AliasInits.empty())
3102 return error("Malformed global initializer set");
3104 // Look for intrinsic functions which need to be upgraded at some point
3105 for (Function &F : *TheModule) {
3107 if (UpgradeIntrinsicFunction(&F, NewFn))
3108 UpgradedIntrinsics[&F] = NewFn;
3111 // Look for global variables which need to be renamed.
3112 for (GlobalVariable &GV : TheModule->globals())
3113 UpgradeGlobalVariable(&GV);
3115 // Force deallocation of memory for these vectors to favor the client that
3116 // want lazy deserialization.
3117 std::vector<std::pair<GlobalVariable*, unsigned> >().swap(GlobalInits);
3118 std::vector<std::pair<GlobalAlias*, unsigned> >().swap(AliasInits);
3119 return std::error_code();
3122 /// Support for lazy parsing of function bodies. This is required if we
3123 /// either have an old bitcode file without a VST forward declaration record,
3124 /// or if we have an anonymous function being materialized, since anonymous
3125 /// functions do not have a name and are therefore not in the VST.
3126 std::error_code BitcodeReader::rememberAndSkipFunctionBodies() {
3127 Stream.JumpToBit(NextUnreadBit);
3129 if (Stream.AtEndOfStream())
3130 return error("Could not find function in stream");
3132 if (!SeenFirstFunctionBody)
3133 return error("Trying to materialize functions before seeing function blocks");
3135 // An old bitcode file with the symbol table at the end would have
3136 // finished the parse greedily.
3137 assert(SeenValueSymbolTable);
3139 SmallVector<uint64_t, 64> Record;
3142 BitstreamEntry Entry = Stream.advance();
3143 switch (Entry.Kind) {
3145 return error("Expect SubBlock");
3146 case BitstreamEntry::SubBlock:
3149 return error("Expect function block");
3150 case bitc::FUNCTION_BLOCK_ID:
3151 if (std::error_code EC = rememberAndSkipFunctionBody())
3153 NextUnreadBit = Stream.GetCurrentBitNo();
3154 return std::error_code();
3160 std::error_code BitcodeReader::parseBitcodeVersion() {
3161 if (Stream.EnterSubBlock(bitc::IDENTIFICATION_BLOCK_ID))
3162 return error("Invalid record");
3164 // Read all the records.
3165 SmallVector<uint64_t, 64> Record;
3167 BitstreamEntry Entry = Stream.advance();
3169 switch (Entry.Kind) {
3171 case BitstreamEntry::Error:
3172 return error("Malformed block");
3173 case BitstreamEntry::EndBlock:
3174 return std::error_code();
3175 case BitstreamEntry::Record:
3176 // The interesting case.
3182 unsigned BitCode = Stream.readRecord(Entry.ID, Record);
3184 default: // Default behavior: reject
3185 return error("Invalid value");
3186 case bitc::IDENTIFICATION_CODE_STRING: { // IDENTIFICATION: [strchr x
3188 convertToString(Record, 0, ProducerIdentification);
3191 case bitc::IDENTIFICATION_CODE_EPOCH: { // EPOCH: [epoch#]
3192 unsigned epoch = (unsigned)Record[0];
3193 if (epoch != bitc::BITCODE_CURRENT_EPOCH) {
3195 Twine("Incompatible epoch: Bitcode '") + Twine(epoch) +
3196 "' vs current: '" + Twine(bitc::BITCODE_CURRENT_EPOCH) + "'");
3203 std::error_code BitcodeReader::parseModule(uint64_t ResumeBit,
3204 bool ShouldLazyLoadMetadata) {
3206 Stream.JumpToBit(ResumeBit);
3207 else if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
3208 return error("Invalid record");
3210 SmallVector<uint64_t, 64> Record;
3211 std::vector<std::string> SectionTable;
3212 std::vector<std::string> GCTable;
3214 // Read all the records for this module.
3216 BitstreamEntry Entry = Stream.advance();
3218 switch (Entry.Kind) {
3219 case BitstreamEntry::Error:
3220 return error("Malformed block");
3221 case BitstreamEntry::EndBlock:
3222 return globalCleanup();
3224 case BitstreamEntry::SubBlock:
3226 default: // Skip unknown content.
3227 if (Stream.SkipBlock())
3228 return error("Invalid record");
3230 case bitc::BLOCKINFO_BLOCK_ID:
3231 if (Stream.ReadBlockInfoBlock())
3232 return error("Malformed block");
3234 case bitc::PARAMATTR_BLOCK_ID:
3235 if (std::error_code EC = parseAttributeBlock())
3238 case bitc::PARAMATTR_GROUP_BLOCK_ID:
3239 if (std::error_code EC = parseAttributeGroupBlock())
3242 case bitc::TYPE_BLOCK_ID_NEW:
3243 if (std::error_code EC = parseTypeTable())
3246 case bitc::VALUE_SYMTAB_BLOCK_ID:
3247 if (!SeenValueSymbolTable) {
3248 // Either this is an old form VST without function index and an
3249 // associated VST forward declaration record (which would have caused
3250 // the VST to be jumped to and parsed before it was encountered
3251 // normally in the stream), or there were no function blocks to
3252 // trigger an earlier parsing of the VST.
3253 assert(VSTOffset == 0 || FunctionsWithBodies.empty());
3254 if (std::error_code EC = parseValueSymbolTable())
3256 SeenValueSymbolTable = true;
3258 // We must have had a VST forward declaration record, which caused
3259 // the parser to jump to and parse the VST earlier.
3260 assert(VSTOffset > 0);
3261 if (Stream.SkipBlock())
3262 return error("Invalid record");
3265 case bitc::CONSTANTS_BLOCK_ID:
3266 if (std::error_code EC = parseConstants())
3268 if (std::error_code EC = resolveGlobalAndAliasInits())
3271 case bitc::METADATA_BLOCK_ID:
3272 if (ShouldLazyLoadMetadata && !IsMetadataMaterialized) {
3273 if (std::error_code EC = rememberAndSkipMetadata())
3277 assert(DeferredMetadataInfo.empty() && "Unexpected deferred metadata");
3278 if (std::error_code EC = parseMetadata())
3281 case bitc::METADATA_KIND_BLOCK_ID:
3282 if (std::error_code EC = parseMetadataKinds())
3285 case bitc::FUNCTION_BLOCK_ID:
3286 // If this is the first function body we've seen, reverse the
3287 // FunctionsWithBodies list.
3288 if (!SeenFirstFunctionBody) {
3289 std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
3290 if (std::error_code EC = globalCleanup())
3292 SeenFirstFunctionBody = true;
3295 if (VSTOffset > 0) {
3296 // If we have a VST forward declaration record, make sure we
3297 // parse the VST now if we haven't already. It is needed to
3298 // set up the DeferredFunctionInfo vector for lazy reading.
3299 if (!SeenValueSymbolTable) {
3300 if (std::error_code EC =
3301 BitcodeReader::parseValueSymbolTable(VSTOffset))
3303 SeenValueSymbolTable = true;
3304 // Fall through so that we record the NextUnreadBit below.
3305 // This is necessary in case we have an anonymous function that
3306 // is later materialized. Since it will not have a VST entry we
3307 // need to fall back to the lazy parse to find its offset.
3309 // If we have a VST forward declaration record, but have already
3310 // parsed the VST (just above, when the first function body was
3311 // encountered here), then we are resuming the parse after
3312 // materializing functions. The ResumeBit points to the
3313 // start of the last function block recorded in the
3314 // DeferredFunctionInfo map. Skip it.
3315 if (Stream.SkipBlock())
3316 return error("Invalid record");
3321 // Support older bitcode files that did not have the function
3322 // index in the VST, nor a VST forward declaration record, as
3323 // well as anonymous functions that do not have VST entries.
3324 // Build the DeferredFunctionInfo vector on the fly.
3325 if (std::error_code EC = rememberAndSkipFunctionBody())
3328 // Suspend parsing when we reach the function bodies. Subsequent
3329 // materialization calls will resume it when necessary. If the bitcode
3330 // file is old, the symbol table will be at the end instead and will not
3331 // have been seen yet. In this case, just finish the parse now.
3332 if (SeenValueSymbolTable) {
3333 NextUnreadBit = Stream.GetCurrentBitNo();
3334 return std::error_code();
3337 case bitc::USELIST_BLOCK_ID:
3338 if (std::error_code EC = parseUseLists())
3341 case bitc::OPERAND_BUNDLE_TAGS_BLOCK_ID:
3342 if (std::error_code EC = parseOperandBundleTags())
3348 case BitstreamEntry::Record:
3349 // The interesting case.
3355 auto BitCode = Stream.readRecord(Entry.ID, Record);
3357 default: break; // Default behavior, ignore unknown content.
3358 case bitc::MODULE_CODE_VERSION: { // VERSION: [version#]
3359 if (Record.size() < 1)
3360 return error("Invalid record");
3361 // Only version #0 and #1 are supported so far.
3362 unsigned module_version = Record[0];
3363 switch (module_version) {
3365 return error("Invalid value");
3367 UseRelativeIDs = false;
3370 UseRelativeIDs = true;
3375 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
3377 if (convertToString(Record, 0, S))
3378 return error("Invalid record");
3379 TheModule->setTargetTriple(S);
3382 case bitc::MODULE_CODE_DATALAYOUT: { // DATALAYOUT: [strchr x N]
3384 if (convertToString(Record, 0, S))
3385 return error("Invalid record");
3386 TheModule->setDataLayout(S);
3389 case bitc::MODULE_CODE_ASM: { // ASM: [strchr x N]
3391 if (convertToString(Record, 0, S))
3392 return error("Invalid record");
3393 TheModule->setModuleInlineAsm(S);
3396 case bitc::MODULE_CODE_DEPLIB: { // DEPLIB: [strchr x N]
3397 // FIXME: Remove in 4.0.
3399 if (convertToString(Record, 0, S))
3400 return error("Invalid record");
3404 case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N]
3406 if (convertToString(Record, 0, S))
3407 return error("Invalid record");
3408 SectionTable.push_back(S);
3411 case bitc::MODULE_CODE_GCNAME: { // SECTIONNAME: [strchr x N]
3413 if (convertToString(Record, 0, S))
3414 return error("Invalid record");
3415 GCTable.push_back(S);
3418 case bitc::MODULE_CODE_COMDAT: { // COMDAT: [selection_kind, name]
3419 if (Record.size() < 2)
3420 return error("Invalid record");
3421 Comdat::SelectionKind SK = getDecodedComdatSelectionKind(Record[0]);
3422 unsigned ComdatNameSize = Record[1];
3423 std::string ComdatName;
3424 ComdatName.reserve(ComdatNameSize);
3425 for (unsigned i = 0; i != ComdatNameSize; ++i)
3426 ComdatName += (char)Record[2 + i];
3427 Comdat *C = TheModule->getOrInsertComdat(ComdatName);
3428 C->setSelectionKind(SK);
3429 ComdatList.push_back(C);
3432 // GLOBALVAR: [pointer type, isconst, initid,
3433 // linkage, alignment, section, visibility, threadlocal,
3434 // unnamed_addr, externally_initialized, dllstorageclass,
3436 case bitc::MODULE_CODE_GLOBALVAR: {
3437 if (Record.size() < 6)
3438 return error("Invalid record");
3439 Type *Ty = getTypeByID(Record[0]);
3441 return error("Invalid record");
3442 bool isConstant = Record[1] & 1;
3443 bool explicitType = Record[1] & 2;
3444 unsigned AddressSpace;
3446 AddressSpace = Record[1] >> 2;
3448 if (!Ty->isPointerTy())
3449 return error("Invalid type for value");
3450 AddressSpace = cast<PointerType>(Ty)->getAddressSpace();
3451 Ty = cast<PointerType>(Ty)->getElementType();
3454 uint64_t RawLinkage = Record[3];
3455 GlobalValue::LinkageTypes Linkage = getDecodedLinkage(RawLinkage);
3457 if (std::error_code EC = parseAlignmentValue(Record[4], Alignment))
3459 std::string Section;
3461 if (Record[5]-1 >= SectionTable.size())
3462 return error("Invalid ID");
3463 Section = SectionTable[Record[5]-1];
3465 GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;
3466 // Local linkage must have default visibility.
3467 if (Record.size() > 6 && !GlobalValue::isLocalLinkage(Linkage))
3468 // FIXME: Change to an error if non-default in 4.0.
3469 Visibility = getDecodedVisibility(Record[6]);
3471 GlobalVariable::ThreadLocalMode TLM = GlobalVariable::NotThreadLocal;
3472 if (Record.size() > 7)
3473 TLM = getDecodedThreadLocalMode(Record[7]);
3475 bool UnnamedAddr = false;
3476 if (Record.size() > 8)
3477 UnnamedAddr = Record[8];
3479 bool ExternallyInitialized = false;
3480 if (Record.size() > 9)
3481 ExternallyInitialized = Record[9];
3483 GlobalVariable *NewGV =
3484 new GlobalVariable(*TheModule, Ty, isConstant, Linkage, nullptr, "", nullptr,
3485 TLM, AddressSpace, ExternallyInitialized);
3486 NewGV->setAlignment(Alignment);
3487 if (!Section.empty())
3488 NewGV->setSection(Section);
3489 NewGV->setVisibility(Visibility);
3490 NewGV->setUnnamedAddr(UnnamedAddr);
3492 if (Record.size() > 10)
3493 NewGV->setDLLStorageClass(getDecodedDLLStorageClass(Record[10]));
3495 upgradeDLLImportExportLinkage(NewGV, RawLinkage);
3497 ValueList.push_back(NewGV);
3499 // Remember which value to use for the global initializer.
3500 if (unsigned InitID = Record[2])
3501 GlobalInits.push_back(std::make_pair(NewGV, InitID-1));
3503 if (Record.size() > 11) {
3504 if (unsigned ComdatID = Record[11]) {
3505 if (ComdatID > ComdatList.size())
3506 return error("Invalid global variable comdat ID");
3507 NewGV->setComdat(ComdatList[ComdatID - 1]);
3509 } else if (hasImplicitComdat(RawLinkage)) {
3510 NewGV->setComdat(reinterpret_cast<Comdat *>(1));
3514 // FUNCTION: [type, callingconv, isproto, linkage, paramattr,
3515 // alignment, section, visibility, gc, unnamed_addr,
3516 // prologuedata, dllstorageclass, comdat, prefixdata]
3517 case bitc::MODULE_CODE_FUNCTION: {
3518 if (Record.size() < 8)
3519 return error("Invalid record");
3520 Type *Ty = getTypeByID(Record[0]);
3522 return error("Invalid record");
3523 if (auto *PTy = dyn_cast<PointerType>(Ty))
3524 Ty = PTy->getElementType();
3525 auto *FTy = dyn_cast<FunctionType>(Ty);
3527 return error("Invalid type for value");
3528 auto CC = static_cast<CallingConv::ID>(Record[1]);
3529 if (CC & ~CallingConv::MaxID)
3530 return error("Invalid calling convention ID");
3532 Function *Func = Function::Create(FTy, GlobalValue::ExternalLinkage,
3535 Func->setCallingConv(CC);
3536 bool isProto = Record[2];
3537 uint64_t RawLinkage = Record[3];
3538 Func->setLinkage(getDecodedLinkage(RawLinkage));
3539 Func->setAttributes(getAttributes(Record[4]));
3542 if (std::error_code EC = parseAlignmentValue(Record[5], Alignment))
3544 Func->setAlignment(Alignment);
3546 if (Record[6]-1 >= SectionTable.size())
3547 return error("Invalid ID");
3548 Func->setSection(SectionTable[Record[6]-1]);
3550 // Local linkage must have default visibility.
3551 if (!Func->hasLocalLinkage())
3552 // FIXME: Change to an error if non-default in 4.0.
3553 Func->setVisibility(getDecodedVisibility(Record[7]));
3554 if (Record.size() > 8 && Record[8]) {
3555 if (Record[8]-1 >= GCTable.size())
3556 return error("Invalid ID");
3557 Func->setGC(GCTable[Record[8]-1].c_str());
3559 bool UnnamedAddr = false;
3560 if (Record.size() > 9)
3561 UnnamedAddr = Record[9];
3562 Func->setUnnamedAddr(UnnamedAddr);
3563 if (Record.size() > 10 && Record[10] != 0)
3564 FunctionPrologues.push_back(std::make_pair(Func, Record[10]-1));
3566 if (Record.size() > 11)
3567 Func->setDLLStorageClass(getDecodedDLLStorageClass(Record[11]));
3569 upgradeDLLImportExportLinkage(Func, RawLinkage);
3571 if (Record.size() > 12) {
3572 if (unsigned ComdatID = Record[12]) {
3573 if (ComdatID > ComdatList.size())
3574 return error("Invalid function comdat ID");
3575 Func->setComdat(ComdatList[ComdatID - 1]);
3577 } else if (hasImplicitComdat(RawLinkage)) {
3578 Func->setComdat(reinterpret_cast<Comdat *>(1));
3581 if (Record.size() > 13 && Record[13] != 0)
3582 FunctionPrefixes.push_back(std::make_pair(Func, Record[13]-1));
3584 if (Record.size() > 14 && Record[14] != 0)
3585 FunctionPersonalityFns.push_back(std::make_pair(Func, Record[14] - 1));
3587 ValueList.push_back(Func);
3589 // If this is a function with a body, remember the prototype we are
3590 // creating now, so that we can match up the body with them later.
3592 Func->setIsMaterializable(true);
3593 FunctionsWithBodies.push_back(Func);
3594 DeferredFunctionInfo[Func] = 0;
3598 // ALIAS: [alias type, addrspace, aliasee val#, linkage]
3599 // ALIAS: [alias type, addrspace, aliasee val#, linkage, visibility, dllstorageclass]
3600 case bitc::MODULE_CODE_ALIAS:
3601 case bitc::MODULE_CODE_ALIAS_OLD: {
3602 bool NewRecord = BitCode == bitc::MODULE_CODE_ALIAS;
3603 if (Record.size() < (3 + (unsigned)NewRecord))
3604 return error("Invalid record");
3606 Type *Ty = getTypeByID(Record[OpNum++]);
3608 return error("Invalid record");
3612 auto *PTy = dyn_cast<PointerType>(Ty);
3614 return error("Invalid type for value");
3615 Ty = PTy->getElementType();
3616 AddrSpace = PTy->getAddressSpace();
3618 AddrSpace = Record[OpNum++];
3621 auto Val = Record[OpNum++];
3622 auto Linkage = Record[OpNum++];
3623 auto *NewGA = GlobalAlias::create(
3624 Ty, AddrSpace, getDecodedLinkage(Linkage), "", TheModule);
3625 // Old bitcode files didn't have visibility field.
3626 // Local linkage must have default visibility.
3627 if (OpNum != Record.size()) {
3628 auto VisInd = OpNum++;
3629 if (!NewGA->hasLocalLinkage())
3630 // FIXME: Change to an error if non-default in 4.0.
3631 NewGA->setVisibility(getDecodedVisibility(Record[VisInd]));
3633 if (OpNum != Record.size())
3634 NewGA->setDLLStorageClass(getDecodedDLLStorageClass(Record[OpNum++]));
3636 upgradeDLLImportExportLinkage(NewGA, Linkage);
3637 if (OpNum != Record.size())
3638 NewGA->setThreadLocalMode(getDecodedThreadLocalMode(Record[OpNum++]));
3639 if (OpNum != Record.size())
3640 NewGA->setUnnamedAddr(Record[OpNum++]);
3641 ValueList.push_back(NewGA);
3642 AliasInits.push_back(std::make_pair(NewGA, Val));
3645 /// MODULE_CODE_PURGEVALS: [numvals]
3646 case bitc::MODULE_CODE_PURGEVALS:
3647 // Trim down the value list to the specified size.
3648 if (Record.size() < 1 || Record[0] > ValueList.size())
3649 return error("Invalid record");
3650 ValueList.shrinkTo(Record[0]);
3652 /// MODULE_CODE_VSTOFFSET: [offset]
3653 case bitc::MODULE_CODE_VSTOFFSET:
3654 if (Record.size() < 1)
3655 return error("Invalid record");
3656 VSTOffset = Record[0];
3663 /// Helper to read the header common to all bitcode files.
3664 static bool hasValidBitcodeHeader(BitstreamCursor &Stream) {
3665 // Sniff for the signature.
3666 if (Stream.Read(8) != 'B' ||
3667 Stream.Read(8) != 'C' ||
3668 Stream.Read(4) != 0x0 ||
3669 Stream.Read(4) != 0xC ||
3670 Stream.Read(4) != 0xE ||
3671 Stream.Read(4) != 0xD)
3677 BitcodeReader::parseBitcodeInto(std::unique_ptr<DataStreamer> Streamer,
3678 Module *M, bool ShouldLazyLoadMetadata) {
3681 if (std::error_code EC = initStream(std::move(Streamer)))
3684 // Sniff for the signature.
3685 if (!hasValidBitcodeHeader(Stream))
3686 return error("Invalid bitcode signature");
3688 // We expect a number of well-defined blocks, though we don't necessarily
3689 // need to understand them all.
3691 if (Stream.AtEndOfStream()) {
3692 // We didn't really read a proper Module.
3693 return error("Malformed IR file");
3696 BitstreamEntry Entry =
3697 Stream.advance(BitstreamCursor::AF_DontAutoprocessAbbrevs);
3699 if (Entry.Kind != BitstreamEntry::SubBlock)
3700 return error("Malformed block");
3702 if (Entry.ID == bitc::IDENTIFICATION_BLOCK_ID) {
3703 parseBitcodeVersion();
3707 if (Entry.ID == bitc::MODULE_BLOCK_ID)
3708 return parseModule(0, ShouldLazyLoadMetadata);
3710 if (Stream.SkipBlock())
3711 return error("Invalid record");
3715 ErrorOr<std::string> BitcodeReader::parseModuleTriple() {
3716 if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
3717 return error("Invalid record");
3719 SmallVector<uint64_t, 64> Record;
3722 // Read all the records for this module.
3724 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
3726 switch (Entry.Kind) {
3727 case BitstreamEntry::SubBlock: // Handled for us already.
3728 case BitstreamEntry::Error:
3729 return error("Malformed block");
3730 case BitstreamEntry::EndBlock:
3732 case BitstreamEntry::Record:
3733 // The interesting case.
3738 switch (Stream.readRecord(Entry.ID, Record)) {
3739 default: break; // Default behavior, ignore unknown content.
3740 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
3742 if (convertToString(Record, 0, S))
3743 return error("Invalid record");
3750 llvm_unreachable("Exit infinite loop");
3753 ErrorOr<std::string> BitcodeReader::parseTriple() {
3754 if (std::error_code EC = initStream(nullptr))
3757 // Sniff for the signature.
3758 if (!hasValidBitcodeHeader(Stream))
3759 return error("Invalid bitcode signature");
3761 // We expect a number of well-defined blocks, though we don't necessarily
3762 // need to understand them all.
3764 BitstreamEntry Entry = Stream.advance();
3766 switch (Entry.Kind) {
3767 case BitstreamEntry::Error:
3768 return error("Malformed block");
3769 case BitstreamEntry::EndBlock:
3770 return std::error_code();
3772 case BitstreamEntry::SubBlock:
3773 if (Entry.ID == bitc::MODULE_BLOCK_ID)
3774 return parseModuleTriple();
3776 // Ignore other sub-blocks.
3777 if (Stream.SkipBlock())
3778 return error("Malformed block");
3781 case BitstreamEntry::Record:
3782 Stream.skipRecord(Entry.ID);
3788 ErrorOr<std::string> BitcodeReader::parseIdentificationBlock() {
3789 if (std::error_code EC = initStream(nullptr))
3792 // Sniff for the signature.
3793 if (!hasValidBitcodeHeader(Stream))
3794 return error("Invalid bitcode signature");
3796 // We expect a number of well-defined blocks, though we don't necessarily
3797 // need to understand them all.
3799 BitstreamEntry Entry = Stream.advance();
3800 switch (Entry.Kind) {
3801 case BitstreamEntry::Error:
3802 return error("Malformed block");
3803 case BitstreamEntry::EndBlock:
3804 return std::error_code();
3806 case BitstreamEntry::SubBlock:
3807 if (Entry.ID == bitc::IDENTIFICATION_BLOCK_ID) {
3808 if (std::error_code EC = parseBitcodeVersion())
3810 return ProducerIdentification;
3812 // Ignore other sub-blocks.
3813 if (Stream.SkipBlock())
3814 return error("Malformed block");
3816 case BitstreamEntry::Record:
3817 Stream.skipRecord(Entry.ID);
3823 /// Parse metadata attachments.
3824 std::error_code BitcodeReader::parseMetadataAttachment(Function &F) {
3825 if (Stream.EnterSubBlock(bitc::METADATA_ATTACHMENT_ID))
3826 return error("Invalid record");
3828 SmallVector<uint64_t, 64> Record;
3830 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
3832 switch (Entry.Kind) {
3833 case BitstreamEntry::SubBlock: // Handled for us already.
3834 case BitstreamEntry::Error:
3835 return error("Malformed block");
3836 case BitstreamEntry::EndBlock:
3837 return std::error_code();
3838 case BitstreamEntry::Record:
3839 // The interesting case.
3843 // Read a metadata attachment record.
3845 switch (Stream.readRecord(Entry.ID, Record)) {
3846 default: // Default behavior: ignore.
3848 case bitc::METADATA_ATTACHMENT: {
3849 unsigned RecordLength = Record.size();
3851 return error("Invalid record");
3852 if (RecordLength % 2 == 0) {
3853 // A function attachment.
3854 for (unsigned I = 0; I != RecordLength; I += 2) {
3855 auto K = MDKindMap.find(Record[I]);
3856 if (K == MDKindMap.end())
3857 return error("Invalid ID");
3858 Metadata *MD = MDValueList.getValueFwdRef(Record[I + 1]);
3859 F.setMetadata(K->second, cast<MDNode>(MD));
3864 // An instruction attachment.
3865 Instruction *Inst = InstructionList[Record[0]];
3866 for (unsigned i = 1; i != RecordLength; i = i+2) {
3867 unsigned Kind = Record[i];
3868 DenseMap<unsigned, unsigned>::iterator I =
3869 MDKindMap.find(Kind);
3870 if (I == MDKindMap.end())
3871 return error("Invalid ID");
3872 Metadata *Node = MDValueList.getValueFwdRef(Record[i + 1]);
3873 if (isa<LocalAsMetadata>(Node))
3874 // Drop the attachment. This used to be legal, but there's no
3877 Inst->setMetadata(I->second, cast<MDNode>(Node));
3878 if (I->second == LLVMContext::MD_tbaa)
3879 InstsWithTBAATag.push_back(Inst);
3887 static std::error_code typeCheckLoadStoreInst(DiagnosticHandlerFunction DH,
3888 Type *ValType, Type *PtrType) {
3889 if (!isa<PointerType>(PtrType))
3890 return error(DH, "Load/Store operand is not a pointer type");
3891 Type *ElemType = cast<PointerType>(PtrType)->getElementType();
3893 if (ValType && ValType != ElemType)
3894 return error(DH, "Explicit load/store type does not match pointee type of "
3896 if (!PointerType::isLoadableOrStorableType(ElemType))
3897 return error(DH, "Cannot load/store from pointer");
3898 return std::error_code();
3901 /// Lazily parse the specified function body block.
3902 std::error_code BitcodeReader::parseFunctionBody(Function *F) {
3903 if (Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID))
3904 return error("Invalid record");
3906 InstructionList.clear();
3907 unsigned ModuleValueListSize = ValueList.size();
3908 unsigned ModuleMDValueListSize = MDValueList.size();
3910 // Add all the function arguments to the value table.
3911 for (Argument &I : F->args())
3912 ValueList.push_back(&I);
3914 unsigned NextValueNo = ValueList.size();
3915 BasicBlock *CurBB = nullptr;
3916 unsigned CurBBNo = 0;
3919 auto getLastInstruction = [&]() -> Instruction * {
3920 if (CurBB && !CurBB->empty())
3921 return &CurBB->back();
3922 else if (CurBBNo && FunctionBBs[CurBBNo - 1] &&
3923 !FunctionBBs[CurBBNo - 1]->empty())
3924 return &FunctionBBs[CurBBNo - 1]->back();
3928 std::vector<OperandBundleDef> OperandBundles;
3930 // Read all the records.
3931 SmallVector<uint64_t, 64> Record;
3933 BitstreamEntry Entry = Stream.advance();
3935 switch (Entry.Kind) {
3936 case BitstreamEntry::Error:
3937 return error("Malformed block");
3938 case BitstreamEntry::EndBlock:
3939 goto OutOfRecordLoop;
3941 case BitstreamEntry::SubBlock:
3943 default: // Skip unknown content.
3944 if (Stream.SkipBlock())
3945 return error("Invalid record");
3947 case bitc::CONSTANTS_BLOCK_ID:
3948 if (std::error_code EC = parseConstants())
3950 NextValueNo = ValueList.size();
3952 case bitc::VALUE_SYMTAB_BLOCK_ID:
3953 if (std::error_code EC = parseValueSymbolTable())
3956 case bitc::METADATA_ATTACHMENT_ID:
3957 if (std::error_code EC = parseMetadataAttachment(*F))
3960 case bitc::METADATA_BLOCK_ID:
3961 if (std::error_code EC = parseMetadata())
3964 case bitc::USELIST_BLOCK_ID:
3965 if (std::error_code EC = parseUseLists())
3971 case BitstreamEntry::Record:
3972 // The interesting case.
3978 Instruction *I = nullptr;
3979 unsigned BitCode = Stream.readRecord(Entry.ID, Record);
3981 default: // Default behavior: reject
3982 return error("Invalid value");
3983 case bitc::FUNC_CODE_DECLAREBLOCKS: { // DECLAREBLOCKS: [nblocks]
3984 if (Record.size() < 1 || Record[0] == 0)
3985 return error("Invalid record");
3986 // Create all the basic blocks for the function.
3987 FunctionBBs.resize(Record[0]);
3989 // See if anything took the address of blocks in this function.
3990 auto BBFRI = BasicBlockFwdRefs.find(F);
3991 if (BBFRI == BasicBlockFwdRefs.end()) {
3992 for (unsigned i = 0, e = FunctionBBs.size(); i != e; ++i)
3993 FunctionBBs[i] = BasicBlock::Create(Context, "", F);
3995 auto &BBRefs = BBFRI->second;
3996 // Check for invalid basic block references.
3997 if (BBRefs.size() > FunctionBBs.size())
3998 return error("Invalid ID");
3999 assert(!BBRefs.empty() && "Unexpected empty array");
4000 assert(!BBRefs.front() && "Invalid reference to entry block");
4001 for (unsigned I = 0, E = FunctionBBs.size(), RE = BBRefs.size(); I != E;
4003 if (I < RE && BBRefs[I]) {
4004 BBRefs[I]->insertInto(F);
4005 FunctionBBs[I] = BBRefs[I];
4007 FunctionBBs[I] = BasicBlock::Create(Context, "", F);
4010 // Erase from the table.
4011 BasicBlockFwdRefs.erase(BBFRI);
4014 CurBB = FunctionBBs[0];
4018 case bitc::FUNC_CODE_DEBUG_LOC_AGAIN: // DEBUG_LOC_AGAIN
4019 // This record indicates that the last instruction is at the same
4020 // location as the previous instruction with a location.
4021 I = getLastInstruction();
4024 return error("Invalid record");
4025 I->setDebugLoc(LastLoc);
4029 case bitc::FUNC_CODE_DEBUG_LOC: { // DEBUG_LOC: [line, col, scope, ia]
4030 I = getLastInstruction();
4031 if (!I || Record.size() < 4)
4032 return error("Invalid record");
4034 unsigned Line = Record[0], Col = Record[1];
4035 unsigned ScopeID = Record[2], IAID = Record[3];
4037 MDNode *Scope = nullptr, *IA = nullptr;
4038 if (ScopeID) Scope = cast<MDNode>(MDValueList.getValueFwdRef(ScopeID-1));
4039 if (IAID) IA = cast<MDNode>(MDValueList.getValueFwdRef(IAID-1));
4040 LastLoc = DebugLoc::get(Line, Col, Scope, IA);
4041 I->setDebugLoc(LastLoc);
4046 case bitc::FUNC_CODE_INST_BINOP: { // BINOP: [opval, ty, opval, opcode]
4049 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
4050 popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) ||
4051 OpNum+1 > Record.size())
4052 return error("Invalid record");
4054 int Opc = getDecodedBinaryOpcode(Record[OpNum++], LHS->getType());
4056 return error("Invalid record");
4057 I = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
4058 InstructionList.push_back(I);
4059 if (OpNum < Record.size()) {
4060 if (Opc == Instruction::Add ||
4061 Opc == Instruction::Sub ||
4062 Opc == Instruction::Mul ||
4063 Opc == Instruction::Shl) {
4064 if (Record[OpNum] & (1 << bitc::OBO_NO_SIGNED_WRAP))
4065 cast<BinaryOperator>(I)->setHasNoSignedWrap(true);
4066 if (Record[OpNum] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
4067 cast<BinaryOperator>(I)->setHasNoUnsignedWrap(true);
4068 } else if (Opc == Instruction::SDiv ||
4069 Opc == Instruction::UDiv ||
4070 Opc == Instruction::LShr ||
4071 Opc == Instruction::AShr) {
4072 if (Record[OpNum] & (1 << bitc::PEO_EXACT))
4073 cast<BinaryOperator>(I)->setIsExact(true);
4074 } else if (isa<FPMathOperator>(I)) {
4075 FastMathFlags FMF = getDecodedFastMathFlags(Record[OpNum]);
4077 I->setFastMathFlags(FMF);
4083 case bitc::FUNC_CODE_INST_CAST: { // CAST: [opval, opty, destty, castopc]
4086 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
4087 OpNum+2 != Record.size())
4088 return error("Invalid record");
4090 Type *ResTy = getTypeByID(Record[OpNum]);
4091 int Opc = getDecodedCastOpcode(Record[OpNum + 1]);
4092 if (Opc == -1 || !ResTy)
4093 return error("Invalid record");
4094 Instruction *Temp = nullptr;
4095 if ((I = UpgradeBitCastInst(Opc, Op, ResTy, Temp))) {
4097 InstructionList.push_back(Temp);
4098 CurBB->getInstList().push_back(Temp);
4101 auto CastOp = (Instruction::CastOps)Opc;
4102 if (!CastInst::castIsValid(CastOp, Op, ResTy))
4103 return error("Invalid cast");
4104 I = CastInst::Create(CastOp, Op, ResTy);
4106 InstructionList.push_back(I);
4109 case bitc::FUNC_CODE_INST_INBOUNDS_GEP_OLD:
4110 case bitc::FUNC_CODE_INST_GEP_OLD:
4111 case bitc::FUNC_CODE_INST_GEP: { // GEP: type, [n x operands]
4117 if (BitCode == bitc::FUNC_CODE_INST_GEP) {
4118 InBounds = Record[OpNum++];
4119 Ty = getTypeByID(Record[OpNum++]);
4121 InBounds = BitCode == bitc::FUNC_CODE_INST_INBOUNDS_GEP_OLD;
4126 if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr))
4127 return error("Invalid record");
4130 Ty = cast<SequentialType>(BasePtr->getType()->getScalarType())
4133 cast<SequentialType>(BasePtr->getType()->getScalarType())
4136 "Explicit gep type does not match pointee type of pointer operand");
4138 SmallVector<Value*, 16> GEPIdx;
4139 while (OpNum != Record.size()) {
4141 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
4142 return error("Invalid record");
4143 GEPIdx.push_back(Op);
4146 I = GetElementPtrInst::Create(Ty, BasePtr, GEPIdx);
4148 InstructionList.push_back(I);
4150 cast<GetElementPtrInst>(I)->setIsInBounds(true);
4154 case bitc::FUNC_CODE_INST_EXTRACTVAL: {
4155 // EXTRACTVAL: [opty, opval, n x indices]
4158 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
4159 return error("Invalid record");
4161 unsigned RecSize = Record.size();
4162 if (OpNum == RecSize)
4163 return error("EXTRACTVAL: Invalid instruction with 0 indices");
4165 SmallVector<unsigned, 4> EXTRACTVALIdx;
4166 Type *CurTy = Agg->getType();
4167 for (; OpNum != RecSize; ++OpNum) {
4168 bool IsArray = CurTy->isArrayTy();
4169 bool IsStruct = CurTy->isStructTy();
4170 uint64_t Index = Record[OpNum];
4172 if (!IsStruct && !IsArray)
4173 return error("EXTRACTVAL: Invalid type");
4174 if ((unsigned)Index != Index)
4175 return error("Invalid value");
4176 if (IsStruct && Index >= CurTy->subtypes().size())
4177 return error("EXTRACTVAL: Invalid struct index");
4178 if (IsArray && Index >= CurTy->getArrayNumElements())
4179 return error("EXTRACTVAL: Invalid array index");
4180 EXTRACTVALIdx.push_back((unsigned)Index);
4183 CurTy = CurTy->subtypes()[Index];
4185 CurTy = CurTy->subtypes()[0];
4188 I = ExtractValueInst::Create(Agg, EXTRACTVALIdx);
4189 InstructionList.push_back(I);
4193 case bitc::FUNC_CODE_INST_INSERTVAL: {
4194 // INSERTVAL: [opty, opval, opty, opval, n x indices]
4197 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
4198 return error("Invalid record");
4200 if (getValueTypePair(Record, OpNum, NextValueNo, Val))
4201 return error("Invalid record");
4203 unsigned RecSize = Record.size();
4204 if (OpNum == RecSize)
4205 return error("INSERTVAL: Invalid instruction with 0 indices");
4207 SmallVector<unsigned, 4> INSERTVALIdx;
4208 Type *CurTy = Agg->getType();
4209 for (; OpNum != RecSize; ++OpNum) {
4210 bool IsArray = CurTy->isArrayTy();
4211 bool IsStruct = CurTy->isStructTy();
4212 uint64_t Index = Record[OpNum];
4214 if (!IsStruct && !IsArray)
4215 return error("INSERTVAL: Invalid type");
4216 if ((unsigned)Index != Index)
4217 return error("Invalid value");
4218 if (IsStruct && Index >= CurTy->subtypes().size())
4219 return error("INSERTVAL: Invalid struct index");
4220 if (IsArray && Index >= CurTy->getArrayNumElements())
4221 return error("INSERTVAL: Invalid array index");
4223 INSERTVALIdx.push_back((unsigned)Index);
4225 CurTy = CurTy->subtypes()[Index];
4227 CurTy = CurTy->subtypes()[0];
4230 if (CurTy != Val->getType())
4231 return error("Inserted value type doesn't match aggregate type");
4233 I = InsertValueInst::Create(Agg, Val, INSERTVALIdx);
4234 InstructionList.push_back(I);
4238 case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval]
4239 // obsolete form of select
4240 // handles select i1 ... in old bitcode
4242 Value *TrueVal, *FalseVal, *Cond;
4243 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
4244 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
4245 popValue(Record, OpNum, NextValueNo, Type::getInt1Ty(Context), Cond))
4246 return error("Invalid record");
4248 I = SelectInst::Create(Cond, TrueVal, FalseVal);
4249 InstructionList.push_back(I);
4253 case bitc::FUNC_CODE_INST_VSELECT: {// VSELECT: [ty,opval,opval,predty,pred]
4254 // new form of select
4255 // handles select i1 or select [N x i1]
4257 Value *TrueVal, *FalseVal, *Cond;
4258 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
4259 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
4260 getValueTypePair(Record, OpNum, NextValueNo, Cond))
4261 return error("Invalid record");
4263 // select condition can be either i1 or [N x i1]
4264 if (VectorType* vector_type =
4265 dyn_cast<VectorType>(Cond->getType())) {
4267 if (vector_type->getElementType() != Type::getInt1Ty(Context))
4268 return error("Invalid type for value");
4271 if (Cond->getType() != Type::getInt1Ty(Context))
4272 return error("Invalid type for value");
4275 I = SelectInst::Create(Cond, TrueVal, FalseVal);
4276 InstructionList.push_back(I);
4280 case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval]
4283 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
4284 getValueTypePair(Record, OpNum, NextValueNo, Idx))
4285 return error("Invalid record");
4286 if (!Vec->getType()->isVectorTy())
4287 return error("Invalid type for value");
4288 I = ExtractElementInst::Create(Vec, Idx);
4289 InstructionList.push_back(I);
4293 case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval]
4295 Value *Vec, *Elt, *Idx;
4296 if (getValueTypePair(Record, OpNum, NextValueNo, Vec))
4297 return error("Invalid record");
4298 if (!Vec->getType()->isVectorTy())
4299 return error("Invalid type for value");
4300 if (popValue(Record, OpNum, NextValueNo,
4301 cast<VectorType>(Vec->getType())->getElementType(), Elt) ||
4302 getValueTypePair(Record, OpNum, NextValueNo, Idx))
4303 return error("Invalid record");
4304 I = InsertElementInst::Create(Vec, Elt, Idx);
4305 InstructionList.push_back(I);
4309 case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval]
4311 Value *Vec1, *Vec2, *Mask;
4312 if (getValueTypePair(Record, OpNum, NextValueNo, Vec1) ||
4313 popValue(Record, OpNum, NextValueNo, Vec1->getType(), Vec2))
4314 return error("Invalid record");
4316 if (getValueTypePair(Record, OpNum, NextValueNo, Mask))
4317 return error("Invalid record");
4318 if (!Vec1->getType()->isVectorTy() || !Vec2->getType()->isVectorTy())
4319 return error("Invalid type for value");
4320 I = new ShuffleVectorInst(Vec1, Vec2, Mask);
4321 InstructionList.push_back(I);
4325 case bitc::FUNC_CODE_INST_CMP: // CMP: [opty, opval, opval, pred]
4326 // Old form of ICmp/FCmp returning bool
4327 // Existed to differentiate between icmp/fcmp and vicmp/vfcmp which were
4328 // both legal on vectors but had different behaviour.
4329 case bitc::FUNC_CODE_INST_CMP2: { // CMP2: [opty, opval, opval, pred]
4330 // FCmp/ICmp returning bool or vector of bool
4334 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
4335 popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS))
4336 return error("Invalid record");
4338 unsigned PredVal = Record[OpNum];
4339 bool IsFP = LHS->getType()->isFPOrFPVectorTy();
4341 if (IsFP && Record.size() > OpNum+1)
4342 FMF = getDecodedFastMathFlags(Record[++OpNum]);
4344 if (OpNum+1 != Record.size())
4345 return error("Invalid record");
4347 if (LHS->getType()->isFPOrFPVectorTy())
4348 I = new FCmpInst((FCmpInst::Predicate)PredVal, LHS, RHS);
4350 I = new ICmpInst((ICmpInst::Predicate)PredVal, LHS, RHS);
4353 I->setFastMathFlags(FMF);
4354 InstructionList.push_back(I);
4358 case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>]
4360 unsigned Size = Record.size();
4362 I = ReturnInst::Create(Context);
4363 InstructionList.push_back(I);
4368 Value *Op = nullptr;
4369 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
4370 return error("Invalid record");
4371 if (OpNum != Record.size())
4372 return error("Invalid record");
4374 I = ReturnInst::Create(Context, Op);
4375 InstructionList.push_back(I);
4378 case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#]
4379 if (Record.size() != 1 && Record.size() != 3)
4380 return error("Invalid record");
4381 BasicBlock *TrueDest = getBasicBlock(Record[0]);
4383 return error("Invalid record");
4385 if (Record.size() == 1) {
4386 I = BranchInst::Create(TrueDest);
4387 InstructionList.push_back(I);
4390 BasicBlock *FalseDest = getBasicBlock(Record[1]);
4391 Value *Cond = getValue(Record, 2, NextValueNo,
4392 Type::getInt1Ty(Context));
4393 if (!FalseDest || !Cond)
4394 return error("Invalid record");
4395 I = BranchInst::Create(TrueDest, FalseDest, Cond);
4396 InstructionList.push_back(I);
4400 case bitc::FUNC_CODE_INST_CLEANUPRET: { // CLEANUPRET: [val] or [val,bb#]
4401 if (Record.size() != 1 && Record.size() != 2)
4402 return error("Invalid record");
4404 Value *CleanupPad = getValue(Record, Idx++, NextValueNo,
4405 Type::getTokenTy(Context), OC_CleanupPad);
4407 return error("Invalid record");
4408 BasicBlock *UnwindDest = nullptr;
4409 if (Record.size() == 2) {
4410 UnwindDest = getBasicBlock(Record[Idx++]);
4412 return error("Invalid record");
4415 I = CleanupReturnInst::Create(cast<CleanupPadInst>(CleanupPad),
4417 InstructionList.push_back(I);
4420 case bitc::FUNC_CODE_INST_CATCHRET: { // CATCHRET: [val,bb#]
4421 if (Record.size() != 2)
4422 return error("Invalid record");
4424 Value *CatchPad = getValue(Record, Idx++, NextValueNo,
4425 Type::getTokenTy(Context), OC_CatchPad);
4427 return error("Invalid record");
4428 BasicBlock *BB = getBasicBlock(Record[Idx++]);
4430 return error("Invalid record");
4432 I = CatchReturnInst::Create(cast<CatchPadInst>(CatchPad), BB);
4433 InstructionList.push_back(I);
4436 case bitc::FUNC_CODE_INST_CATCHPAD: { // CATCHPAD: [bb#,bb#,num,(ty,val)*]
4437 if (Record.size() < 3)
4438 return error("Invalid record");
4440 BasicBlock *NormalBB = getBasicBlock(Record[Idx++]);
4442 return error("Invalid record");
4443 BasicBlock *UnwindBB = getBasicBlock(Record[Idx++]);
4445 return error("Invalid record");
4446 unsigned NumArgOperands = Record[Idx++];
4447 SmallVector<Value *, 2> Args;
4448 for (unsigned Op = 0; Op != NumArgOperands; ++Op) {
4450 if (getValueTypePair(Record, Idx, NextValueNo, Val))
4451 return error("Invalid record");
4452 Args.push_back(Val);
4454 if (Record.size() != Idx)
4455 return error("Invalid record");
4457 I = CatchPadInst::Create(NormalBB, UnwindBB, Args);
4458 InstructionList.push_back(I);
4461 case bitc::FUNC_CODE_INST_TERMINATEPAD: { // TERMINATEPAD: [bb#,num,(ty,val)*]
4462 if (Record.size() < 1)
4463 return error("Invalid record");
4465 bool HasUnwindDest = !!Record[Idx++];
4466 BasicBlock *UnwindDest = nullptr;
4467 if (HasUnwindDest) {
4468 if (Idx == Record.size())
4469 return error("Invalid record");
4470 UnwindDest = getBasicBlock(Record[Idx++]);
4472 return error("Invalid record");
4474 unsigned NumArgOperands = Record[Idx++];
4475 SmallVector<Value *, 2> Args;
4476 for (unsigned Op = 0; Op != NumArgOperands; ++Op) {
4478 if (getValueTypePair(Record, Idx, NextValueNo, Val))
4479 return error("Invalid record");
4480 Args.push_back(Val);
4482 if (Record.size() != Idx)
4483 return error("Invalid record");
4485 I = TerminatePadInst::Create(Context, UnwindDest, Args);
4486 InstructionList.push_back(I);
4489 case bitc::FUNC_CODE_INST_CLEANUPPAD: { // CLEANUPPAD: [num,(ty,val)*]
4490 if (Record.size() < 1)
4491 return error("Invalid record");
4493 unsigned NumArgOperands = Record[Idx++];
4494 SmallVector<Value *, 2> Args;
4495 for (unsigned Op = 0; Op != NumArgOperands; ++Op) {
4497 if (getValueTypePair(Record, Idx, NextValueNo, Val))
4498 return error("Invalid record");
4499 Args.push_back(Val);
4501 if (Record.size() != Idx)
4502 return error("Invalid record");
4504 I = CleanupPadInst::Create(Context, Args);
4505 InstructionList.push_back(I);
4508 case bitc::FUNC_CODE_INST_CATCHENDPAD: { // CATCHENDPADINST: [bb#] or []
4509 if (Record.size() > 1)
4510 return error("Invalid record");
4511 BasicBlock *BB = nullptr;
4512 if (Record.size() == 1) {
4513 BB = getBasicBlock(Record[0]);
4515 return error("Invalid record");
4517 I = CatchEndPadInst::Create(Context, BB);
4518 InstructionList.push_back(I);
4521 case bitc::FUNC_CODE_INST_CLEANUPENDPAD: { // CLEANUPENDPADINST: [val] or [val,bb#]
4522 if (Record.size() != 1 && Record.size() != 2)
4523 return error("Invalid record");
4525 Value *CleanupPad = getValue(Record, Idx++, NextValueNo,
4526 Type::getTokenTy(Context), OC_CleanupPad);
4528 return error("Invalid record");
4530 BasicBlock *BB = nullptr;
4531 if (Record.size() == 2) {
4532 BB = getBasicBlock(Record[Idx++]);
4534 return error("Invalid record");
4536 I = CleanupEndPadInst::Create(cast<CleanupPadInst>(CleanupPad), BB);
4537 InstructionList.push_back(I);
4540 case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, op0, op1, ...]
4542 if ((Record[0] >> 16) == SWITCH_INST_MAGIC) {
4543 // "New" SwitchInst format with case ranges. The changes to write this
4544 // format were reverted but we still recognize bitcode that uses it.
4545 // Hopefully someday we will have support for case ranges and can use
4546 // this format again.
4548 Type *OpTy = getTypeByID(Record[1]);
4549 unsigned ValueBitWidth = cast<IntegerType>(OpTy)->getBitWidth();
4551 Value *Cond = getValue(Record, 2, NextValueNo, OpTy);
4552 BasicBlock *Default = getBasicBlock(Record[3]);
4553 if (!OpTy || !Cond || !Default)
4554 return error("Invalid record");
4556 unsigned NumCases = Record[4];
4558 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
4559 InstructionList.push_back(SI);
4561 unsigned CurIdx = 5;
4562 for (unsigned i = 0; i != NumCases; ++i) {
4563 SmallVector<ConstantInt*, 1> CaseVals;
4564 unsigned NumItems = Record[CurIdx++];
4565 for (unsigned ci = 0; ci != NumItems; ++ci) {
4566 bool isSingleNumber = Record[CurIdx++];
4569 unsigned ActiveWords = 1;
4570 if (ValueBitWidth > 64)
4571 ActiveWords = Record[CurIdx++];
4572 Low = readWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords),
4574 CurIdx += ActiveWords;
4576 if (!isSingleNumber) {
4578 if (ValueBitWidth > 64)
4579 ActiveWords = Record[CurIdx++];
4580 APInt High = readWideAPInt(
4581 makeArrayRef(&Record[CurIdx], ActiveWords), ValueBitWidth);
4582 CurIdx += ActiveWords;
4584 // FIXME: It is not clear whether values in the range should be
4585 // compared as signed or unsigned values. The partially
4586 // implemented changes that used this format in the past used
4587 // unsigned comparisons.
4588 for ( ; Low.ule(High); ++Low)
4589 CaseVals.push_back(ConstantInt::get(Context, Low));
4591 CaseVals.push_back(ConstantInt::get(Context, Low));
4593 BasicBlock *DestBB = getBasicBlock(Record[CurIdx++]);
4594 for (SmallVector<ConstantInt*, 1>::iterator cvi = CaseVals.begin(),
4595 cve = CaseVals.end(); cvi != cve; ++cvi)
4596 SI->addCase(*cvi, DestBB);
4602 // Old SwitchInst format without case ranges.
4604 if (Record.size() < 3 || (Record.size() & 1) == 0)
4605 return error("Invalid record");
4606 Type *OpTy = getTypeByID(Record[0]);
4607 Value *Cond = getValue(Record, 1, NextValueNo, OpTy);
4608 BasicBlock *Default = getBasicBlock(Record[2]);
4609 if (!OpTy || !Cond || !Default)
4610 return error("Invalid record");
4611 unsigned NumCases = (Record.size()-3)/2;
4612 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
4613 InstructionList.push_back(SI);
4614 for (unsigned i = 0, e = NumCases; i != e; ++i) {
4615 ConstantInt *CaseVal =
4616 dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy));
4617 BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]);
4618 if (!CaseVal || !DestBB) {
4620 return error("Invalid record");
4622 SI->addCase(CaseVal, DestBB);
4627 case bitc::FUNC_CODE_INST_INDIRECTBR: { // INDIRECTBR: [opty, op0, op1, ...]
4628 if (Record.size() < 2)
4629 return error("Invalid record");
4630 Type *OpTy = getTypeByID(Record[0]);
4631 Value *Address = getValue(Record, 1, NextValueNo, OpTy);
4632 if (!OpTy || !Address)
4633 return error("Invalid record");
4634 unsigned NumDests = Record.size()-2;
4635 IndirectBrInst *IBI = IndirectBrInst::Create(Address, NumDests);
4636 InstructionList.push_back(IBI);
4637 for (unsigned i = 0, e = NumDests; i != e; ++i) {
4638 if (BasicBlock *DestBB = getBasicBlock(Record[2+i])) {
4639 IBI->addDestination(DestBB);
4642 return error("Invalid record");
4649 case bitc::FUNC_CODE_INST_INVOKE: {
4650 // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...]
4651 if (Record.size() < 4)
4652 return error("Invalid record");
4654 AttributeSet PAL = getAttributes(Record[OpNum++]);
4655 unsigned CCInfo = Record[OpNum++];
4656 BasicBlock *NormalBB = getBasicBlock(Record[OpNum++]);
4657 BasicBlock *UnwindBB = getBasicBlock(Record[OpNum++]);
4659 FunctionType *FTy = nullptr;
4660 if (CCInfo >> 13 & 1 &&
4661 !(FTy = dyn_cast<FunctionType>(getTypeByID(Record[OpNum++]))))
4662 return error("Explicit invoke type is not a function type");
4665 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
4666 return error("Invalid record");
4668 PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType());
4670 return error("Callee is not a pointer");
4672 FTy = dyn_cast<FunctionType>(CalleeTy->getElementType());
4674 return error("Callee is not of pointer to function type");
4675 } else if (CalleeTy->getElementType() != FTy)
4676 return error("Explicit invoke type does not match pointee type of "
4678 if (Record.size() < FTy->getNumParams() + OpNum)
4679 return error("Insufficient operands to call");
4681 SmallVector<Value*, 16> Ops;
4682 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
4683 Ops.push_back(getValue(Record, OpNum, NextValueNo,
4684 FTy->getParamType(i)));
4686 return error("Invalid record");
4689 if (!FTy->isVarArg()) {
4690 if (Record.size() != OpNum)
4691 return error("Invalid record");
4693 // Read type/value pairs for varargs params.
4694 while (OpNum != Record.size()) {
4696 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
4697 return error("Invalid record");
4702 I = InvokeInst::Create(Callee, NormalBB, UnwindBB, Ops, OperandBundles);
4703 OperandBundles.clear();
4704 InstructionList.push_back(I);
4705 cast<InvokeInst>(I)->setCallingConv(
4706 static_cast<CallingConv::ID>(CallingConv::MaxID & CCInfo));
4707 cast<InvokeInst>(I)->setAttributes(PAL);
4710 case bitc::FUNC_CODE_INST_RESUME: { // RESUME: [opval]
4712 Value *Val = nullptr;
4713 if (getValueTypePair(Record, Idx, NextValueNo, Val))
4714 return error("Invalid record");
4715 I = ResumeInst::Create(Val);
4716 InstructionList.push_back(I);
4719 case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE
4720 I = new UnreachableInst(Context);
4721 InstructionList.push_back(I);
4723 case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...]
4724 if (Record.size() < 1 || ((Record.size()-1)&1))
4725 return error("Invalid record");
4726 Type *Ty = getTypeByID(Record[0]);
4728 return error("Invalid record");
4730 PHINode *PN = PHINode::Create(Ty, (Record.size()-1)/2);
4731 InstructionList.push_back(PN);
4733 for (unsigned i = 0, e = Record.size()-1; i != e; i += 2) {
4735 // With the new function encoding, it is possible that operands have
4736 // negative IDs (for forward references). Use a signed VBR
4737 // representation to keep the encoding small.
4739 V = getValueSigned(Record, 1+i, NextValueNo, Ty);
4741 V = getValue(Record, 1+i, NextValueNo, Ty);
4742 BasicBlock *BB = getBasicBlock(Record[2+i]);
4744 return error("Invalid record");
4745 PN->addIncoming(V, BB);
4751 case bitc::FUNC_CODE_INST_LANDINGPAD:
4752 case bitc::FUNC_CODE_INST_LANDINGPAD_OLD: {
4753 // LANDINGPAD: [ty, val, val, num, (id0,val0 ...)?]
4755 if (BitCode == bitc::FUNC_CODE_INST_LANDINGPAD) {
4756 if (Record.size() < 3)
4757 return error("Invalid record");
4759 assert(BitCode == bitc::FUNC_CODE_INST_LANDINGPAD_OLD);
4760 if (Record.size() < 4)
4761 return error("Invalid record");
4763 Type *Ty = getTypeByID(Record[Idx++]);
4765 return error("Invalid record");
4766 if (BitCode == bitc::FUNC_CODE_INST_LANDINGPAD_OLD) {
4767 Value *PersFn = nullptr;
4768 if (getValueTypePair(Record, Idx, NextValueNo, PersFn))
4769 return error("Invalid record");
4771 if (!F->hasPersonalityFn())
4772 F->setPersonalityFn(cast<Constant>(PersFn));
4773 else if (F->getPersonalityFn() != cast<Constant>(PersFn))
4774 return error("Personality function mismatch");
4777 bool IsCleanup = !!Record[Idx++];
4778 unsigned NumClauses = Record[Idx++];
4779 LandingPadInst *LP = LandingPadInst::Create(Ty, NumClauses);
4780 LP->setCleanup(IsCleanup);
4781 for (unsigned J = 0; J != NumClauses; ++J) {
4782 LandingPadInst::ClauseType CT =
4783 LandingPadInst::ClauseType(Record[Idx++]); (void)CT;
4786 if (getValueTypePair(Record, Idx, NextValueNo, Val)) {
4788 return error("Invalid record");
4791 assert((CT != LandingPadInst::Catch ||
4792 !isa<ArrayType>(Val->getType())) &&
4793 "Catch clause has a invalid type!");
4794 assert((CT != LandingPadInst::Filter ||
4795 isa<ArrayType>(Val->getType())) &&
4796 "Filter clause has invalid type!");
4797 LP->addClause(cast<Constant>(Val));
4801 InstructionList.push_back(I);
4805 case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, opty, op, align]
4806 if (Record.size() != 4)
4807 return error("Invalid record");
4808 uint64_t AlignRecord = Record[3];
4809 const uint64_t InAllocaMask = uint64_t(1) << 5;
4810 const uint64_t ExplicitTypeMask = uint64_t(1) << 6;
4811 // Reserve bit 7 for SwiftError flag.
4812 // const uint64_t SwiftErrorMask = uint64_t(1) << 7;
4813 const uint64_t FlagMask = InAllocaMask | ExplicitTypeMask;
4814 bool InAlloca = AlignRecord & InAllocaMask;
4815 Type *Ty = getTypeByID(Record[0]);
4816 if ((AlignRecord & ExplicitTypeMask) == 0) {
4817 auto *PTy = dyn_cast_or_null<PointerType>(Ty);
4819 return error("Old-style alloca with a non-pointer type");
4820 Ty = PTy->getElementType();
4822 Type *OpTy = getTypeByID(Record[1]);
4823 Value *Size = getFnValueByID(Record[2], OpTy);
4825 if (std::error_code EC =
4826 parseAlignmentValue(AlignRecord & ~FlagMask, Align)) {
4830 return error("Invalid record");
4831 AllocaInst *AI = new AllocaInst(Ty, Size, Align);
4832 AI->setUsedWithInAlloca(InAlloca);
4834 InstructionList.push_back(I);
4837 case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol]
4840 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
4841 (OpNum + 2 != Record.size() && OpNum + 3 != Record.size()))
4842 return error("Invalid record");
4845 if (OpNum + 3 == Record.size())
4846 Ty = getTypeByID(Record[OpNum++]);
4847 if (std::error_code EC =
4848 typeCheckLoadStoreInst(DiagnosticHandler, Ty, Op->getType()))
4851 Ty = cast<PointerType>(Op->getType())->getElementType();
4854 if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align))
4856 I = new LoadInst(Ty, Op, "", Record[OpNum + 1], Align);
4858 InstructionList.push_back(I);
4861 case bitc::FUNC_CODE_INST_LOADATOMIC: {
4862 // LOADATOMIC: [opty, op, align, vol, ordering, synchscope]
4865 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
4866 (OpNum + 4 != Record.size() && OpNum + 5 != Record.size()))
4867 return error("Invalid record");
4870 if (OpNum + 5 == Record.size())
4871 Ty = getTypeByID(Record[OpNum++]);
4872 if (std::error_code EC =
4873 typeCheckLoadStoreInst(DiagnosticHandler, Ty, Op->getType()))
4876 Ty = cast<PointerType>(Op->getType())->getElementType();
4878 AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]);
4879 if (Ordering == NotAtomic || Ordering == Release ||
4880 Ordering == AcquireRelease)
4881 return error("Invalid record");
4882 if (Ordering != NotAtomic && Record[OpNum] == 0)
4883 return error("Invalid record");
4884 SynchronizationScope SynchScope = getDecodedSynchScope(Record[OpNum + 3]);
4887 if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align))
4889 I = new LoadInst(Op, "", Record[OpNum+1], Align, Ordering, SynchScope);
4891 InstructionList.push_back(I);
4894 case bitc::FUNC_CODE_INST_STORE:
4895 case bitc::FUNC_CODE_INST_STORE_OLD: { // STORE2:[ptrty, ptr, val, align, vol]
4898 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
4899 (BitCode == bitc::FUNC_CODE_INST_STORE
4900 ? getValueTypePair(Record, OpNum, NextValueNo, Val)
4901 : popValue(Record, OpNum, NextValueNo,
4902 cast<PointerType>(Ptr->getType())->getElementType(),
4904 OpNum + 2 != Record.size())
4905 return error("Invalid record");
4907 if (std::error_code EC = typeCheckLoadStoreInst(
4908 DiagnosticHandler, Val->getType(), Ptr->getType()))
4911 if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align))
4913 I = new StoreInst(Val, Ptr, Record[OpNum+1], Align);
4914 InstructionList.push_back(I);
4917 case bitc::FUNC_CODE_INST_STOREATOMIC:
4918 case bitc::FUNC_CODE_INST_STOREATOMIC_OLD: {
4919 // STOREATOMIC: [ptrty, ptr, val, align, vol, ordering, synchscope]
4922 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
4923 (BitCode == bitc::FUNC_CODE_INST_STOREATOMIC
4924 ? getValueTypePair(Record, OpNum, NextValueNo, Val)
4925 : popValue(Record, OpNum, NextValueNo,
4926 cast<PointerType>(Ptr->getType())->getElementType(),
4928 OpNum + 4 != Record.size())
4929 return error("Invalid record");
4931 if (std::error_code EC = typeCheckLoadStoreInst(
4932 DiagnosticHandler, Val->getType(), Ptr->getType()))
4934 AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]);
4935 if (Ordering == NotAtomic || Ordering == Acquire ||
4936 Ordering == AcquireRelease)
4937 return error("Invalid record");
4938 SynchronizationScope SynchScope = getDecodedSynchScope(Record[OpNum + 3]);
4939 if (Ordering != NotAtomic && Record[OpNum] == 0)
4940 return error("Invalid record");
4943 if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align))
4945 I = new StoreInst(Val, Ptr, Record[OpNum+1], Align, Ordering, SynchScope);
4946 InstructionList.push_back(I);
4949 case bitc::FUNC_CODE_INST_CMPXCHG_OLD:
4950 case bitc::FUNC_CODE_INST_CMPXCHG: {
4951 // CMPXCHG:[ptrty, ptr, cmp, new, vol, successordering, synchscope,
4952 // failureordering?, isweak?]
4954 Value *Ptr, *Cmp, *New;
4955 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
4956 (BitCode == bitc::FUNC_CODE_INST_CMPXCHG
4957 ? getValueTypePair(Record, OpNum, NextValueNo, Cmp)
4958 : popValue(Record, OpNum, NextValueNo,
4959 cast<PointerType>(Ptr->getType())->getElementType(),
4961 popValue(Record, OpNum, NextValueNo, Cmp->getType(), New) ||
4962 Record.size() < OpNum + 3 || Record.size() > OpNum + 5)
4963 return error("Invalid record");
4964 AtomicOrdering SuccessOrdering = getDecodedOrdering(Record[OpNum + 1]);
4965 if (SuccessOrdering == NotAtomic || SuccessOrdering == Unordered)
4966 return error("Invalid record");
4967 SynchronizationScope SynchScope = getDecodedSynchScope(Record[OpNum + 2]);
4969 if (std::error_code EC = typeCheckLoadStoreInst(
4970 DiagnosticHandler, Cmp->getType(), Ptr->getType()))
4972 AtomicOrdering FailureOrdering;
4973 if (Record.size() < 7)
4975 AtomicCmpXchgInst::getStrongestFailureOrdering(SuccessOrdering);
4977 FailureOrdering = getDecodedOrdering(Record[OpNum + 3]);
4979 I = new AtomicCmpXchgInst(Ptr, Cmp, New, SuccessOrdering, FailureOrdering,
4981 cast<AtomicCmpXchgInst>(I)->setVolatile(Record[OpNum]);
4983 if (Record.size() < 8) {
4984 // Before weak cmpxchgs existed, the instruction simply returned the
4985 // value loaded from memory, so bitcode files from that era will be
4986 // expecting the first component of a modern cmpxchg.
4987 CurBB->getInstList().push_back(I);
4988 I = ExtractValueInst::Create(I, 0);
4990 cast<AtomicCmpXchgInst>(I)->setWeak(Record[OpNum+4]);
4993 InstructionList.push_back(I);
4996 case bitc::FUNC_CODE_INST_ATOMICRMW: {
4997 // ATOMICRMW:[ptrty, ptr, val, op, vol, ordering, synchscope]
5000 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
5001 popValue(Record, OpNum, NextValueNo,
5002 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
5003 OpNum+4 != Record.size())
5004 return error("Invalid record");
5005 AtomicRMWInst::BinOp Operation = getDecodedRMWOperation(Record[OpNum]);
5006 if (Operation < AtomicRMWInst::FIRST_BINOP ||
5007 Operation > AtomicRMWInst::LAST_BINOP)
5008 return error("Invalid record");
5009 AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]);
5010 if (Ordering == NotAtomic || Ordering == Unordered)
5011 return error("Invalid record");
5012 SynchronizationScope SynchScope = getDecodedSynchScope(Record[OpNum + 3]);
5013 I = new AtomicRMWInst(Operation, Ptr, Val, Ordering, SynchScope);
5014 cast<AtomicRMWInst>(I)->setVolatile(Record[OpNum+1]);
5015 InstructionList.push_back(I);
5018 case bitc::FUNC_CODE_INST_FENCE: { // FENCE:[ordering, synchscope]
5019 if (2 != Record.size())
5020 return error("Invalid record");
5021 AtomicOrdering Ordering = getDecodedOrdering(Record[0]);
5022 if (Ordering == NotAtomic || Ordering == Unordered ||
5023 Ordering == Monotonic)
5024 return error("Invalid record");
5025 SynchronizationScope SynchScope = getDecodedSynchScope(Record[1]);
5026 I = new FenceInst(Context, Ordering, SynchScope);
5027 InstructionList.push_back(I);
5030 case bitc::FUNC_CODE_INST_CALL: {
5031 // CALL: [paramattrs, cc, fnty, fnid, arg0, arg1...]
5032 if (Record.size() < 3)
5033 return error("Invalid record");
5036 AttributeSet PAL = getAttributes(Record[OpNum++]);
5037 unsigned CCInfo = Record[OpNum++];
5039 FunctionType *FTy = nullptr;
5040 if (CCInfo >> bitc::CALL_EXPLICIT_TYPE & 1 &&
5041 !(FTy = dyn_cast<FunctionType>(getTypeByID(Record[OpNum++]))))
5042 return error("Explicit call type is not a function type");
5045 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
5046 return error("Invalid record");
5048 PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());
5050 return error("Callee is not a pointer type");
5052 FTy = dyn_cast<FunctionType>(OpTy->getElementType());
5054 return error("Callee is not of pointer to function type");
5055 } else if (OpTy->getElementType() != FTy)
5056 return error("Explicit call type does not match pointee type of "
5058 if (Record.size() < FTy->getNumParams() + OpNum)
5059 return error("Insufficient operands to call");
5061 SmallVector<Value*, 16> Args;
5062 // Read the fixed params.
5063 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
5064 if (FTy->getParamType(i)->isLabelTy())
5065 Args.push_back(getBasicBlock(Record[OpNum]));
5067 Args.push_back(getValue(Record, OpNum, NextValueNo,
5068 FTy->getParamType(i)));
5070 return error("Invalid record");
5073 // Read type/value pairs for varargs params.
5074 if (!FTy->isVarArg()) {
5075 if (OpNum != Record.size())
5076 return error("Invalid record");
5078 while (OpNum != Record.size()) {
5080 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
5081 return error("Invalid record");
5086 I = CallInst::Create(FTy, Callee, Args, OperandBundles);
5087 OperandBundles.clear();
5088 InstructionList.push_back(I);
5089 cast<CallInst>(I)->setCallingConv(
5090 static_cast<CallingConv::ID>((0x7ff & CCInfo) >> bitc::CALL_CCONV));
5091 CallInst::TailCallKind TCK = CallInst::TCK_None;
5092 if (CCInfo & 1 << bitc::CALL_TAIL)
5093 TCK = CallInst::TCK_Tail;
5094 if (CCInfo & (1 << bitc::CALL_MUSTTAIL))
5095 TCK = CallInst::TCK_MustTail;
5096 if (CCInfo & (1 << bitc::CALL_NOTAIL))
5097 TCK = CallInst::TCK_NoTail;
5098 cast<CallInst>(I)->setTailCallKind(TCK);
5099 cast<CallInst>(I)->setAttributes(PAL);
5102 case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty]
5103 if (Record.size() < 3)
5104 return error("Invalid record");
5105 Type *OpTy = getTypeByID(Record[0]);
5106 Value *Op = getValue(Record, 1, NextValueNo, OpTy);
5107 Type *ResTy = getTypeByID(Record[2]);
5108 if (!OpTy || !Op || !ResTy)
5109 return error("Invalid record");
5110 I = new VAArgInst(Op, ResTy);
5111 InstructionList.push_back(I);
5115 case bitc::FUNC_CODE_OPERAND_BUNDLE: {
5116 // A call or an invoke can be optionally prefixed with some variable
5117 // number of operand bundle blocks. These blocks are read into
5118 // OperandBundles and consumed at the next call or invoke instruction.
5120 if (Record.size() < 1 || Record[0] >= BundleTags.size())
5121 return error("Invalid record");
5123 std::vector<Value *> Inputs;
5126 while (OpNum != Record.size()) {
5128 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
5129 return error("Invalid record");
5130 Inputs.push_back(Op);
5133 OperandBundles.emplace_back(BundleTags[Record[0]], std::move(Inputs));
5138 // Add instruction to end of current BB. If there is no current BB, reject
5142 return error("Invalid instruction with no BB");
5144 if (!OperandBundles.empty()) {
5146 return error("Operand bundles found with no consumer");
5148 CurBB->getInstList().push_back(I);
5150 // If this was a terminator instruction, move to the next block.
5151 if (isa<TerminatorInst>(I)) {
5153 CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : nullptr;
5156 // Non-void values get registered in the value table for future use.
5157 if (I && !I->getType()->isVoidTy())
5158 if (ValueList.assignValue(I, NextValueNo++))
5159 return error("Invalid forward reference");
5164 if (!OperandBundles.empty())
5165 return error("Operand bundles found with no consumer");
5167 // Check the function list for unresolved values.
5168 if (Argument *A = dyn_cast<Argument>(ValueList.back())) {
5169 if (!A->getParent()) {
5170 // We found at least one unresolved value. Nuke them all to avoid leaks.
5171 for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){
5172 if ((A = dyn_cast_or_null<Argument>(ValueList[i])) && !A->getParent()) {
5173 A->replaceAllUsesWith(UndefValue::get(A->getType()));
5177 return error("Never resolved value found in function");
5181 // FIXME: Check for unresolved forward-declared metadata references
5182 // and clean up leaks.
5184 // Trim the value list down to the size it was before we parsed this function.
5185 ValueList.shrinkTo(ModuleValueListSize);
5186 MDValueList.shrinkTo(ModuleMDValueListSize);
5187 std::vector<BasicBlock*>().swap(FunctionBBs);
5188 return std::error_code();
5191 /// Find the function body in the bitcode stream
5192 std::error_code BitcodeReader::findFunctionInStream(
5194 DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator) {
5195 while (DeferredFunctionInfoIterator->second == 0) {
5196 // This is the fallback handling for the old format bitcode that
5197 // didn't contain the function index in the VST, or when we have
5198 // an anonymous function which would not have a VST entry.
5199 // Assert that we have one of those two cases.
5200 assert(VSTOffset == 0 || !F->hasName());
5201 // Parse the next body in the stream and set its position in the
5202 // DeferredFunctionInfo map.
5203 if (std::error_code EC = rememberAndSkipFunctionBodies())
5206 return std::error_code();
5209 //===----------------------------------------------------------------------===//
5210 // GVMaterializer implementation
5211 //===----------------------------------------------------------------------===//
5213 void BitcodeReader::releaseBuffer() { Buffer.release(); }
5215 std::error_code BitcodeReader::materialize(GlobalValue *GV) {
5216 if (std::error_code EC = materializeMetadata())
5219 Function *F = dyn_cast<Function>(GV);
5220 // If it's not a function or is already material, ignore the request.
5221 if (!F || !F->isMaterializable())
5222 return std::error_code();
5224 DenseMap<Function*, uint64_t>::iterator DFII = DeferredFunctionInfo.find(F);
5225 assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!");
5226 // If its position is recorded as 0, its body is somewhere in the stream
5227 // but we haven't seen it yet.
5228 if (DFII->second == 0)
5229 if (std::error_code EC = findFunctionInStream(F, DFII))
5232 // Move the bit stream to the saved position of the deferred function body.
5233 Stream.JumpToBit(DFII->second);
5235 if (std::error_code EC = parseFunctionBody(F))
5237 F->setIsMaterializable(false);
5242 // Upgrade any old intrinsic calls in the function.
5243 for (auto &I : UpgradedIntrinsics) {
5244 for (auto UI = I.first->user_begin(), UE = I.first->user_end(); UI != UE;) {
5247 if (CallInst *CI = dyn_cast<CallInst>(U))
5248 UpgradeIntrinsicCall(CI, I.second);
5252 // Finish fn->subprogram upgrade for materialized functions.
5253 if (DISubprogram *SP = FunctionsWithSPs.lookup(F))
5254 F->setSubprogram(SP);
5256 // Bring in any functions that this function forward-referenced via
5258 return materializeForwardReferencedFunctions();
5261 bool BitcodeReader::isDematerializable(const GlobalValue *GV) const {
5262 const Function *F = dyn_cast<Function>(GV);
5263 if (!F || F->isDeclaration())
5266 // Dematerializing F would leave dangling references that wouldn't be
5267 // reconnected on re-materialization.
5268 if (BlockAddressesTaken.count(F))
5271 return DeferredFunctionInfo.count(const_cast<Function*>(F));
5274 void BitcodeReader::dematerialize(GlobalValue *GV) {
5275 Function *F = dyn_cast<Function>(GV);
5276 // If this function isn't dematerializable, this is a noop.
5277 if (!F || !isDematerializable(F))
5280 assert(DeferredFunctionInfo.count(F) && "No info to read function later?");
5282 // Just forget the function body, we can remat it later.
5283 F->dropAllReferences();
5284 F->setIsMaterializable(true);
5287 std::error_code BitcodeReader::materializeModule(Module *M) {
5288 assert(M == TheModule &&
5289 "Can only Materialize the Module this BitcodeReader is attached to.");
5291 if (std::error_code EC = materializeMetadata())
5294 // Promise to materialize all forward references.
5295 WillMaterializeAllForwardRefs = true;
5297 // Iterate over the module, deserializing any functions that are still on
5299 for (Function &F : *TheModule) {
5300 if (std::error_code EC = materialize(&F))
5303 // At this point, if there are any function bodies, parse the rest of
5304 // the bits in the module past the last function block we have recorded
5305 // through either lazy scanning or the VST.
5306 if (LastFunctionBlockBit || NextUnreadBit)
5307 parseModule(LastFunctionBlockBit > NextUnreadBit ? LastFunctionBlockBit
5310 // Check that all block address forward references got resolved (as we
5312 if (!BasicBlockFwdRefs.empty())
5313 return error("Never resolved function from blockaddress");
5315 // Upgrade any intrinsic calls that slipped through (should not happen!) and
5316 // delete the old functions to clean up. We can't do this unless the entire
5317 // module is materialized because there could always be another function body
5318 // with calls to the old function.
5319 for (auto &I : UpgradedIntrinsics) {
5320 for (auto *U : I.first->users()) {
5321 if (CallInst *CI = dyn_cast<CallInst>(U))
5322 UpgradeIntrinsicCall(CI, I.second);
5324 if (!I.first->use_empty())
5325 I.first->replaceAllUsesWith(I.second);
5326 I.first->eraseFromParent();
5328 UpgradedIntrinsics.clear();
5330 for (unsigned I = 0, E = InstsWithTBAATag.size(); I < E; I++)
5331 UpgradeInstWithTBAATag(InstsWithTBAATag[I]);
5333 UpgradeDebugInfo(*M);
5334 return std::error_code();
5337 std::vector<StructType *> BitcodeReader::getIdentifiedStructTypes() const {
5338 return IdentifiedStructTypes;
5342 BitcodeReader::initStream(std::unique_ptr<DataStreamer> Streamer) {
5344 return initLazyStream(std::move(Streamer));
5345 return initStreamFromBuffer();
5348 std::error_code BitcodeReader::initStreamFromBuffer() {
5349 const unsigned char *BufPtr = (const unsigned char*)Buffer->getBufferStart();
5350 const unsigned char *BufEnd = BufPtr+Buffer->getBufferSize();
5352 if (Buffer->getBufferSize() & 3)
5353 return error("Invalid bitcode signature");
5355 // If we have a wrapper header, parse it and ignore the non-bc file contents.
5356 // The magic number is 0x0B17C0DE stored in little endian.
5357 if (isBitcodeWrapper(BufPtr, BufEnd))
5358 if (SkipBitcodeWrapperHeader(BufPtr, BufEnd, true))
5359 return error("Invalid bitcode wrapper header");
5361 StreamFile.reset(new BitstreamReader(BufPtr, BufEnd));
5362 Stream.init(&*StreamFile);
5364 return std::error_code();
5368 BitcodeReader::initLazyStream(std::unique_ptr<DataStreamer> Streamer) {
5369 // Check and strip off the bitcode wrapper; BitstreamReader expects never to
5372 llvm::make_unique<StreamingMemoryObject>(std::move(Streamer));
5373 StreamingMemoryObject &Bytes = *OwnedBytes;
5374 StreamFile = llvm::make_unique<BitstreamReader>(std::move(OwnedBytes));
5375 Stream.init(&*StreamFile);
5377 unsigned char buf[16];
5378 if (Bytes.readBytes(buf, 16, 0) != 16)
5379 return error("Invalid bitcode signature");
5381 if (!isBitcode(buf, buf + 16))
5382 return error("Invalid bitcode signature");
5384 if (isBitcodeWrapper(buf, buf + 4)) {
5385 const unsigned char *bitcodeStart = buf;
5386 const unsigned char *bitcodeEnd = buf + 16;
5387 SkipBitcodeWrapperHeader(bitcodeStart, bitcodeEnd, false);
5388 Bytes.dropLeadingBytes(bitcodeStart - buf);
5389 Bytes.setKnownObjectSize(bitcodeEnd - bitcodeStart);
5391 return std::error_code();
5394 std::error_code FunctionIndexBitcodeReader::error(BitcodeError E,
5395 const Twine &Message) {
5396 return ::error(DiagnosticHandler, make_error_code(E), Message);
5399 std::error_code FunctionIndexBitcodeReader::error(const Twine &Message) {
5400 return ::error(DiagnosticHandler,
5401 make_error_code(BitcodeError::CorruptedBitcode), Message);
5404 std::error_code FunctionIndexBitcodeReader::error(BitcodeError E) {
5405 return ::error(DiagnosticHandler, make_error_code(E));
5408 FunctionIndexBitcodeReader::FunctionIndexBitcodeReader(
5409 MemoryBuffer *Buffer, LLVMContext &Context,
5410 DiagnosticHandlerFunction DiagnosticHandler, bool IsLazy,
5411 bool CheckFuncSummaryPresenceOnly)
5412 : DiagnosticHandler(getDiagHandler(DiagnosticHandler, Context)),
5413 Buffer(Buffer), IsLazy(IsLazy),
5414 CheckFuncSummaryPresenceOnly(CheckFuncSummaryPresenceOnly) {}
5416 FunctionIndexBitcodeReader::FunctionIndexBitcodeReader(
5417 LLVMContext &Context, DiagnosticHandlerFunction DiagnosticHandler,
5418 bool IsLazy, bool CheckFuncSummaryPresenceOnly)
5419 : DiagnosticHandler(getDiagHandler(DiagnosticHandler, Context)),
5420 Buffer(nullptr), IsLazy(IsLazy),
5421 CheckFuncSummaryPresenceOnly(CheckFuncSummaryPresenceOnly) {}
5423 void FunctionIndexBitcodeReader::freeState() { Buffer = nullptr; }
5425 void FunctionIndexBitcodeReader::releaseBuffer() { Buffer.release(); }
5427 // Specialized value symbol table parser used when reading function index
5428 // blocks where we don't actually create global values.
5429 // At the end of this routine the function index is populated with a map
5430 // from function name to FunctionInfo. The function info contains
5431 // the function block's bitcode offset as well as the offset into the
5432 // function summary section.
5433 std::error_code FunctionIndexBitcodeReader::parseValueSymbolTable() {
5434 if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
5435 return error("Invalid record");
5437 SmallVector<uint64_t, 64> Record;
5439 // Read all the records for this value table.
5440 SmallString<128> ValueName;
5442 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
5444 switch (Entry.Kind) {
5445 case BitstreamEntry::SubBlock: // Handled for us already.
5446 case BitstreamEntry::Error:
5447 return error("Malformed block");
5448 case BitstreamEntry::EndBlock:
5449 return std::error_code();
5450 case BitstreamEntry::Record:
5451 // The interesting case.
5457 switch (Stream.readRecord(Entry.ID, Record)) {
5458 default: // Default behavior: ignore (e.g. VST_CODE_BBENTRY records).
5460 case bitc::VST_CODE_FNENTRY: {
5461 // VST_FNENTRY: [valueid, offset, namechar x N]
5462 if (convertToString(Record, 2, ValueName))
5463 return error("Invalid record");
5464 unsigned ValueID = Record[0];
5465 uint64_t FuncOffset = Record[1];
5466 std::unique_ptr<FunctionInfo> FuncInfo =
5467 llvm::make_unique<FunctionInfo>(FuncOffset);
5468 if (foundFuncSummary() && !IsLazy) {
5469 DenseMap<uint64_t, std::unique_ptr<FunctionSummary>>::iterator SMI =
5470 SummaryMap.find(ValueID);
5471 assert(SMI != SummaryMap.end() && "Summary info not found");
5472 FuncInfo->setFunctionSummary(std::move(SMI->second));
5474 TheIndex->addFunctionInfo(ValueName, std::move(FuncInfo));
5479 case bitc::VST_CODE_COMBINED_FNENTRY: {
5480 // VST_FNENTRY: [offset, namechar x N]
5481 if (convertToString(Record, 1, ValueName))
5482 return error("Invalid record");
5483 uint64_t FuncSummaryOffset = Record[0];
5484 std::unique_ptr<FunctionInfo> FuncInfo =
5485 llvm::make_unique<FunctionInfo>(FuncSummaryOffset);
5486 if (foundFuncSummary() && !IsLazy) {
5487 DenseMap<uint64_t, std::unique_ptr<FunctionSummary>>::iterator SMI =
5488 SummaryMap.find(FuncSummaryOffset);
5489 assert(SMI != SummaryMap.end() && "Summary info not found");
5490 FuncInfo->setFunctionSummary(std::move(SMI->second));
5492 TheIndex->addFunctionInfo(ValueName, std::move(FuncInfo));
5501 // Parse just the blocks needed for function index building out of the module.
5502 // At the end of this routine the function Index is populated with a map
5503 // from function name to FunctionInfo. The function info contains
5504 // either the parsed function summary information (when parsing summaries
5505 // eagerly), or just to the function summary record's offset
5506 // if parsing lazily (IsLazy).
5507 std::error_code FunctionIndexBitcodeReader::parseModule() {
5508 if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
5509 return error("Invalid record");
5511 // Read the function index for this module.
5513 BitstreamEntry Entry = Stream.advance();
5515 switch (Entry.Kind) {
5516 case BitstreamEntry::Error:
5517 return error("Malformed block");
5518 case BitstreamEntry::EndBlock:
5519 return std::error_code();
5521 case BitstreamEntry::SubBlock:
5522 if (CheckFuncSummaryPresenceOnly) {
5523 if (Entry.ID == bitc::FUNCTION_SUMMARY_BLOCK_ID)
5524 SeenFuncSummary = true;
5525 if (Stream.SkipBlock())
5526 return error("Invalid record");
5527 // No need to parse the rest since we found the summary.
5528 return std::error_code();
5531 default: // Skip unknown content.
5532 if (Stream.SkipBlock())
5533 return error("Invalid record");
5535 case bitc::BLOCKINFO_BLOCK_ID:
5536 // Need to parse these to get abbrev ids (e.g. for VST)
5537 if (Stream.ReadBlockInfoBlock())
5538 return error("Malformed block");
5540 case bitc::VALUE_SYMTAB_BLOCK_ID:
5541 if (std::error_code EC = parseValueSymbolTable())
5544 case bitc::FUNCTION_SUMMARY_BLOCK_ID:
5545 SeenFuncSummary = true;
5547 // Lazy parsing of summary info, skip it.
5548 if (Stream.SkipBlock())
5549 return error("Invalid record");
5550 } else if (std::error_code EC = parseEntireSummary())
5553 case bitc::MODULE_STRTAB_BLOCK_ID:
5554 if (std::error_code EC = parseModuleStringTable())
5560 case BitstreamEntry::Record:
5561 Stream.skipRecord(Entry.ID);
5567 // Eagerly parse the entire function summary block (i.e. for all functions
5568 // in the index). This populates the FunctionSummary objects in
5570 std::error_code FunctionIndexBitcodeReader::parseEntireSummary() {
5571 if (Stream.EnterSubBlock(bitc::FUNCTION_SUMMARY_BLOCK_ID))
5572 return error("Invalid record");
5574 SmallVector<uint64_t, 64> Record;
5577 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
5579 switch (Entry.Kind) {
5580 case BitstreamEntry::SubBlock: // Handled for us already.
5581 case BitstreamEntry::Error:
5582 return error("Malformed block");
5583 case BitstreamEntry::EndBlock:
5584 return std::error_code();
5585 case BitstreamEntry::Record:
5586 // The interesting case.
5590 // Read a record. The record format depends on whether this
5591 // is a per-module index or a combined index file. In the per-module
5592 // case the records contain the associated value's ID for correlation
5593 // with VST entries. In the combined index the correlation is done
5594 // via the bitcode offset of the summary records (which were saved
5595 // in the combined index VST entries). The records also contain
5596 // information used for ThinLTO renaming and importing.
5598 uint64_t CurRecordBit = Stream.GetCurrentBitNo();
5599 switch (Stream.readRecord(Entry.ID, Record)) {
5600 default: // Default behavior: ignore.
5602 // FS_PERMODULE_ENTRY: [valueid, islocal, instcount]
5603 case bitc::FS_CODE_PERMODULE_ENTRY: {
5604 unsigned ValueID = Record[0];
5605 bool IsLocal = Record[1];
5606 unsigned InstCount = Record[2];
5607 std::unique_ptr<FunctionSummary> FS =
5608 llvm::make_unique<FunctionSummary>(InstCount);
5609 FS->setLocalFunction(IsLocal);
5610 // The module path string ref set in the summary must be owned by the
5611 // index's module string table. Since we don't have a module path
5612 // string table section in the per-module index, we create a single
5613 // module path string table entry with an empty (0) ID to take
5616 TheIndex->addModulePath(Buffer->getBufferIdentifier(), 0));
5617 SummaryMap[ValueID] = std::move(FS);
5619 // FS_COMBINED_ENTRY: [modid, instcount]
5620 case bitc::FS_CODE_COMBINED_ENTRY: {
5621 uint64_t ModuleId = Record[0];
5622 unsigned InstCount = Record[1];
5623 std::unique_ptr<FunctionSummary> FS =
5624 llvm::make_unique<FunctionSummary>(InstCount);
5625 FS->setModulePath(ModuleIdMap[ModuleId]);
5626 SummaryMap[CurRecordBit] = std::move(FS);
5630 llvm_unreachable("Exit infinite loop");
5633 // Parse the module string table block into the Index.
5634 // This populates the ModulePathStringTable map in the index.
5635 std::error_code FunctionIndexBitcodeReader::parseModuleStringTable() {
5636 if (Stream.EnterSubBlock(bitc::MODULE_STRTAB_BLOCK_ID))
5637 return error("Invalid record");
5639 SmallVector<uint64_t, 64> Record;
5641 SmallString<128> ModulePath;
5643 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
5645 switch (Entry.Kind) {
5646 case BitstreamEntry::SubBlock: // Handled for us already.
5647 case BitstreamEntry::Error:
5648 return error("Malformed block");
5649 case BitstreamEntry::EndBlock:
5650 return std::error_code();
5651 case BitstreamEntry::Record:
5652 // The interesting case.
5657 switch (Stream.readRecord(Entry.ID, Record)) {
5658 default: // Default behavior: ignore.
5660 case bitc::MST_CODE_ENTRY: {
5661 // MST_ENTRY: [modid, namechar x N]
5662 if (convertToString(Record, 1, ModulePath))
5663 return error("Invalid record");
5664 uint64_t ModuleId = Record[0];
5665 StringRef ModulePathInMap = TheIndex->addModulePath(ModulePath, ModuleId);
5666 ModuleIdMap[ModuleId] = ModulePathInMap;
5672 llvm_unreachable("Exit infinite loop");
5675 // Parse the function info index from the bitcode streamer into the given index.
5676 std::error_code FunctionIndexBitcodeReader::parseSummaryIndexInto(
5677 std::unique_ptr<DataStreamer> Streamer, FunctionInfoIndex *I) {
5680 if (std::error_code EC = initStream(std::move(Streamer)))
5683 // Sniff for the signature.
5684 if (!hasValidBitcodeHeader(Stream))
5685 return error("Invalid bitcode signature");
5687 // We expect a number of well-defined blocks, though we don't necessarily
5688 // need to understand them all.
5690 if (Stream.AtEndOfStream()) {
5691 // We didn't really read a proper Module block.
5692 return error("Malformed block");
5695 BitstreamEntry Entry =
5696 Stream.advance(BitstreamCursor::AF_DontAutoprocessAbbrevs);
5698 if (Entry.Kind != BitstreamEntry::SubBlock)
5699 return error("Malformed block");
5701 // If we see a MODULE_BLOCK, parse it to find the blocks needed for
5702 // building the function summary index.
5703 if (Entry.ID == bitc::MODULE_BLOCK_ID)
5704 return parseModule();
5706 if (Stream.SkipBlock())
5707 return error("Invalid record");
5711 // Parse the function information at the given offset in the buffer into
5712 // the index. Used to support lazy parsing of function summaries from the
5713 // combined index during importing.
5714 // TODO: This function is not yet complete as it won't have a consumer
5715 // until ThinLTO function importing is added.
5716 std::error_code FunctionIndexBitcodeReader::parseFunctionSummary(
5717 std::unique_ptr<DataStreamer> Streamer, FunctionInfoIndex *I,
5718 size_t FunctionSummaryOffset) {
5721 if (std::error_code EC = initStream(std::move(Streamer)))
5724 // Sniff for the signature.
5725 if (!hasValidBitcodeHeader(Stream))
5726 return error("Invalid bitcode signature");
5728 Stream.JumpToBit(FunctionSummaryOffset);
5730 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
5732 switch (Entry.Kind) {
5734 return error("Malformed block");
5735 case BitstreamEntry::Record:
5736 // The expected case.
5740 // TODO: Read a record. This interface will be completed when ThinLTO
5741 // importing is added so that it can be tested.
5742 SmallVector<uint64_t, 64> Record;
5743 switch (Stream.readRecord(Entry.ID, Record)) {
5744 case bitc::FS_CODE_COMBINED_ENTRY:
5746 return error("Invalid record");
5749 return std::error_code();
5753 FunctionIndexBitcodeReader::initStream(std::unique_ptr<DataStreamer> Streamer) {
5755 return initLazyStream(std::move(Streamer));
5756 return initStreamFromBuffer();
5759 std::error_code FunctionIndexBitcodeReader::initStreamFromBuffer() {
5760 const unsigned char *BufPtr = (const unsigned char *)Buffer->getBufferStart();
5761 const unsigned char *BufEnd = BufPtr + Buffer->getBufferSize();
5763 if (Buffer->getBufferSize() & 3)
5764 return error("Invalid bitcode signature");
5766 // If we have a wrapper header, parse it and ignore the non-bc file contents.
5767 // The magic number is 0x0B17C0DE stored in little endian.
5768 if (isBitcodeWrapper(BufPtr, BufEnd))
5769 if (SkipBitcodeWrapperHeader(BufPtr, BufEnd, true))
5770 return error("Invalid bitcode wrapper header");
5772 StreamFile.reset(new BitstreamReader(BufPtr, BufEnd));
5773 Stream.init(&*StreamFile);
5775 return std::error_code();
5778 std::error_code FunctionIndexBitcodeReader::initLazyStream(
5779 std::unique_ptr<DataStreamer> Streamer) {
5780 // Check and strip off the bitcode wrapper; BitstreamReader expects never to
5783 llvm::make_unique<StreamingMemoryObject>(std::move(Streamer));
5784 StreamingMemoryObject &Bytes = *OwnedBytes;
5785 StreamFile = llvm::make_unique<BitstreamReader>(std::move(OwnedBytes));
5786 Stream.init(&*StreamFile);
5788 unsigned char buf[16];
5789 if (Bytes.readBytes(buf, 16, 0) != 16)
5790 return error("Invalid bitcode signature");
5792 if (!isBitcode(buf, buf + 16))
5793 return error("Invalid bitcode signature");
5795 if (isBitcodeWrapper(buf, buf + 4)) {
5796 const unsigned char *bitcodeStart = buf;
5797 const unsigned char *bitcodeEnd = buf + 16;
5798 SkipBitcodeWrapperHeader(bitcodeStart, bitcodeEnd, false);
5799 Bytes.dropLeadingBytes(bitcodeStart - buf);
5800 Bytes.setKnownObjectSize(bitcodeEnd - bitcodeStart);
5802 return std::error_code();
5806 class BitcodeErrorCategoryType : public std::error_category {
5807 const char *name() const LLVM_NOEXCEPT override {
5808 return "llvm.bitcode";
5810 std::string message(int IE) const override {
5811 BitcodeError E = static_cast<BitcodeError>(IE);
5813 case BitcodeError::InvalidBitcodeSignature:
5814 return "Invalid bitcode signature";
5815 case BitcodeError::CorruptedBitcode:
5816 return "Corrupted bitcode";
5818 llvm_unreachable("Unknown error type!");
5823 static ManagedStatic<BitcodeErrorCategoryType> ErrorCategory;
5825 const std::error_category &llvm::BitcodeErrorCategory() {
5826 return *ErrorCategory;
5829 //===----------------------------------------------------------------------===//
5830 // External interface
5831 //===----------------------------------------------------------------------===//
5833 static ErrorOr<std::unique_ptr<Module>>
5834 getBitcodeModuleImpl(std::unique_ptr<DataStreamer> Streamer, StringRef Name,
5835 BitcodeReader *R, LLVMContext &Context,
5836 bool MaterializeAll, bool ShouldLazyLoadMetadata) {
5837 std::unique_ptr<Module> M = make_unique<Module>(Name, Context);
5838 M->setMaterializer(R);
5840 auto cleanupOnError = [&](std::error_code EC) {
5841 R->releaseBuffer(); // Never take ownership on error.
5845 // Delay parsing Metadata if ShouldLazyLoadMetadata is true.
5846 if (std::error_code EC = R->parseBitcodeInto(std::move(Streamer), M.get(),
5847 ShouldLazyLoadMetadata))
5848 return cleanupOnError(EC);
5850 if (MaterializeAll) {
5851 // Read in the entire module, and destroy the BitcodeReader.
5852 if (std::error_code EC = M->materializeAllPermanently())
5853 return cleanupOnError(EC);
5855 // Resolve forward references from blockaddresses.
5856 if (std::error_code EC = R->materializeForwardReferencedFunctions())
5857 return cleanupOnError(EC);
5859 return std::move(M);
5862 /// \brief Get a lazy one-at-time loading module from bitcode.
5864 /// This isn't always used in a lazy context. In particular, it's also used by
5865 /// \a parseBitcodeFile(). If this is truly lazy, then we need to eagerly pull
5866 /// in forward-referenced functions from block address references.
5868 /// \param[in] MaterializeAll Set to \c true if we should materialize
5870 static ErrorOr<std::unique_ptr<Module>>
5871 getLazyBitcodeModuleImpl(std::unique_ptr<MemoryBuffer> &&Buffer,
5872 LLVMContext &Context, bool MaterializeAll,
5873 DiagnosticHandlerFunction DiagnosticHandler,
5874 bool ShouldLazyLoadMetadata = false) {
5876 new BitcodeReader(Buffer.get(), Context, DiagnosticHandler);
5878 ErrorOr<std::unique_ptr<Module>> Ret =
5879 getBitcodeModuleImpl(nullptr, Buffer->getBufferIdentifier(), R, Context,
5880 MaterializeAll, ShouldLazyLoadMetadata);
5884 Buffer.release(); // The BitcodeReader owns it now.
5888 ErrorOr<std::unique_ptr<Module>> llvm::getLazyBitcodeModule(
5889 std::unique_ptr<MemoryBuffer> &&Buffer, LLVMContext &Context,
5890 DiagnosticHandlerFunction DiagnosticHandler, bool ShouldLazyLoadMetadata) {
5891 return getLazyBitcodeModuleImpl(std::move(Buffer), Context, false,
5892 DiagnosticHandler, ShouldLazyLoadMetadata);
5895 ErrorOr<std::unique_ptr<Module>> llvm::getStreamedBitcodeModule(
5896 StringRef Name, std::unique_ptr<DataStreamer> Streamer,
5897 LLVMContext &Context, DiagnosticHandlerFunction DiagnosticHandler) {
5898 std::unique_ptr<Module> M = make_unique<Module>(Name, Context);
5899 BitcodeReader *R = new BitcodeReader(Context, DiagnosticHandler);
5901 return getBitcodeModuleImpl(std::move(Streamer), Name, R, Context, false,
5905 ErrorOr<std::unique_ptr<Module>>
5906 llvm::parseBitcodeFile(MemoryBufferRef Buffer, LLVMContext &Context,
5907 DiagnosticHandlerFunction DiagnosticHandler) {
5908 std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
5909 return getLazyBitcodeModuleImpl(std::move(Buf), Context, true,
5911 // TODO: Restore the use-lists to the in-memory state when the bitcode was
5912 // written. We must defer until the Module has been fully materialized.
5916 llvm::getBitcodeTargetTriple(MemoryBufferRef Buffer, LLVMContext &Context,
5917 DiagnosticHandlerFunction DiagnosticHandler) {
5918 std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
5919 auto R = llvm::make_unique<BitcodeReader>(Buf.release(), Context,
5921 ErrorOr<std::string> Triple = R->parseTriple();
5922 if (Triple.getError())
5924 return Triple.get();
5928 llvm::getBitcodeProducerString(MemoryBufferRef Buffer, LLVMContext &Context,
5929 DiagnosticHandlerFunction DiagnosticHandler) {
5930 std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
5931 BitcodeReader R(Buf.release(), Context, DiagnosticHandler);
5932 ErrorOr<std::string> ProducerString = R.parseIdentificationBlock();
5933 if (ProducerString.getError())
5935 return ProducerString.get();
5938 // Parse the specified bitcode buffer, returning the function info index.
5939 // If IsLazy is false, parse the entire function summary into
5940 // the index. Otherwise skip the function summary section, and only create
5941 // an index object with a map from function name to function summary offset.
5942 // The index is used to perform lazy function summary reading later.
5943 ErrorOr<std::unique_ptr<FunctionInfoIndex>>
5944 llvm::getFunctionInfoIndex(MemoryBufferRef Buffer, LLVMContext &Context,
5945 DiagnosticHandlerFunction DiagnosticHandler,
5946 const Module *ExportingModule, bool IsLazy) {
5947 std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
5948 FunctionIndexBitcodeReader R(Buf.get(), Context, DiagnosticHandler, IsLazy);
5950 std::unique_ptr<FunctionInfoIndex> Index =
5951 llvm::make_unique<FunctionInfoIndex>(ExportingModule);
5953 auto cleanupOnError = [&](std::error_code EC) {
5954 R.releaseBuffer(); // Never take ownership on error.
5958 if (std::error_code EC = R.parseSummaryIndexInto(nullptr, Index.get()))
5959 return cleanupOnError(EC);
5961 Buf.release(); // The FunctionIndexBitcodeReader owns it now.
5962 return std::move(Index);
5965 // Check if the given bitcode buffer contains a function summary block.
5966 bool llvm::hasFunctionSummary(MemoryBufferRef Buffer, LLVMContext &Context,
5967 DiagnosticHandlerFunction DiagnosticHandler) {
5968 std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
5969 FunctionIndexBitcodeReader R(Buf.get(), Context, DiagnosticHandler, false,
5972 auto cleanupOnError = [&](std::error_code EC) {
5973 R.releaseBuffer(); // Never take ownership on error.
5977 if (std::error_code EC = R.parseSummaryIndexInto(nullptr, nullptr))
5978 return cleanupOnError(EC);
5980 Buf.release(); // The FunctionIndexBitcodeReader owns it now.
5981 return R.foundFuncSummary();
5984 // This method supports lazy reading of function summary data from the combined
5985 // index during ThinLTO function importing. When reading the combined index
5986 // file, getFunctionInfoIndex is first invoked with IsLazy=true.
5987 // Then this method is called for each function considered for importing,
5988 // to parse the summary information for the given function name into
5991 llvm::readFunctionSummary(MemoryBufferRef Buffer, LLVMContext &Context,
5992 DiagnosticHandlerFunction DiagnosticHandler,
5993 StringRef FunctionName,
5994 std::unique_ptr<FunctionInfoIndex> Index) {
5995 std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
5996 FunctionIndexBitcodeReader R(Buf.get(), Context, DiagnosticHandler);
5998 auto cleanupOnError = [&](std::error_code EC) {
5999 R.releaseBuffer(); // Never take ownership on error.
6003 // Lookup the given function name in the FunctionMap, which may
6004 // contain a list of function infos in the case of a COMDAT. Walk through
6005 // and parse each function summary info at the function summary offset
6006 // recorded when parsing the value symbol table.
6007 for (const auto &FI : Index->getFunctionInfoList(FunctionName)) {
6008 size_t FunctionSummaryOffset = FI->bitcodeIndex();
6009 if (std::error_code EC =
6010 R.parseFunctionSummary(nullptr, Index.get(), FunctionSummaryOffset))
6011 return cleanupOnError(EC);
6014 Buf.release(); // The FunctionIndexBitcodeReader owns it now.
6015 return std::error_code();