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/ADT/APFloat.h"
11 #include "llvm/ADT/APInt.h"
12 #include "llvm/ADT/ArrayRef.h"
13 #include "llvm/ADT/DenseMap.h"
14 #include "llvm/ADT/None.h"
15 #include "llvm/ADT/STLExtras.h"
16 #include "llvm/ADT/SmallString.h"
17 #include "llvm/ADT/SmallVector.h"
18 #include "llvm/ADT/StringRef.h"
19 #include "llvm/ADT/Triple.h"
20 #include "llvm/ADT/Twine.h"
21 #include "llvm/Bitcode/BitstreamReader.h"
22 #include "llvm/Bitcode/LLVMBitCodes.h"
23 #include "llvm/Bitcode/ReaderWriter.h"
24 #include "llvm/IR/Argument.h"
25 #include "llvm/IR/Attributes.h"
26 #include "llvm/IR/AutoUpgrade.h"
27 #include "llvm/IR/BasicBlock.h"
28 #include "llvm/IR/CallingConv.h"
29 #include "llvm/IR/CallSite.h"
30 #include "llvm/IR/Comdat.h"
31 #include "llvm/IR/Constant.h"
32 #include "llvm/IR/Constants.h"
33 #include "llvm/IR/DebugInfo.h"
34 #include "llvm/IR/DebugInfoMetadata.h"
35 #include "llvm/IR/DebugLoc.h"
36 #include "llvm/IR/DerivedTypes.h"
37 #include "llvm/IR/DiagnosticInfo.h"
38 #include "llvm/IR/DiagnosticPrinter.h"
39 #include "llvm/IR/Function.h"
40 #include "llvm/IR/GlobalAlias.h"
41 #include "llvm/IR/GlobalIFunc.h"
42 #include "llvm/IR/GlobalIndirectSymbol.h"
43 #include "llvm/IR/GlobalObject.h"
44 #include "llvm/IR/GlobalValue.h"
45 #include "llvm/IR/GlobalVariable.h"
46 #include "llvm/IR/GVMaterializer.h"
47 #include "llvm/IR/InlineAsm.h"
48 #include "llvm/IR/InstrTypes.h"
49 #include "llvm/IR/Instruction.h"
50 #include "llvm/IR/Instructions.h"
51 #include "llvm/IR/Intrinsics.h"
52 #include "llvm/IR/LLVMContext.h"
53 #include "llvm/IR/Module.h"
54 #include "llvm/IR/ModuleSummaryIndex.h"
55 #include "llvm/IR/OperandTraits.h"
56 #include "llvm/IR/Operator.h"
57 #include "llvm/IR/TrackingMDRef.h"
58 #include "llvm/IR/Type.h"
59 #include "llvm/IR/ValueHandle.h"
60 #include "llvm/Support/AtomicOrdering.h"
61 #include "llvm/Support/Casting.h"
62 #include "llvm/Support/CommandLine.h"
63 #include "llvm/Support/Compiler.h"
64 #include "llvm/Support/DataStream.h"
65 #include "llvm/Support/Debug.h"
66 #include "llvm/Support/ErrorHandling.h"
67 #include "llvm/Support/ErrorOr.h"
68 #include "llvm/Support/ManagedStatic.h"
69 #include "llvm/Support/MemoryBuffer.h"
70 #include "llvm/Support/raw_ostream.h"
71 #include "llvm/Support/StreamingMemoryObject.h"
81 #include <system_error>
88 static cl::opt<bool> PrintSummaryGUIDs(
89 "print-summary-global-ids", cl::init(false), cl::Hidden,
91 "Print the global id for each value when reading the module summary"));
96 SWITCH_INST_MAGIC = 0x4B5 // May 2012 => 1205 => Hex
99 class BitcodeReaderValueList {
100 std::vector<WeakVH> ValuePtrs;
102 /// As we resolve forward-referenced constants, we add information about them
103 /// to this vector. This allows us to resolve them in bulk instead of
104 /// resolving each reference at a time. See the code in
105 /// ResolveConstantForwardRefs for more information about this.
107 /// The key of this vector is the placeholder constant, the value is the slot
108 /// number that holds the resolved value.
109 typedef std::vector<std::pair<Constant*, unsigned> > ResolveConstantsTy;
110 ResolveConstantsTy ResolveConstants;
111 LLVMContext &Context;
114 BitcodeReaderValueList(LLVMContext &C) : Context(C) {}
115 ~BitcodeReaderValueList() {
116 assert(ResolveConstants.empty() && "Constants not resolved?");
119 // vector compatibility methods
120 unsigned size() const { return ValuePtrs.size(); }
121 void resize(unsigned N) { ValuePtrs.resize(N); }
122 void push_back(Value *V) { ValuePtrs.emplace_back(V); }
125 assert(ResolveConstants.empty() && "Constants not resolved?");
129 Value *operator[](unsigned i) const {
130 assert(i < ValuePtrs.size());
134 Value *back() const { return ValuePtrs.back(); }
135 void pop_back() { ValuePtrs.pop_back(); }
136 bool empty() const { return ValuePtrs.empty(); }
138 void shrinkTo(unsigned N) {
139 assert(N <= size() && "Invalid shrinkTo request!");
143 Constant *getConstantFwdRef(unsigned Idx, Type *Ty);
144 Value *getValueFwdRef(unsigned Idx, Type *Ty);
146 void assignValue(Value *V, unsigned Idx);
148 /// Once all constants are read, this method bulk resolves any forward
150 void resolveConstantForwardRefs();
153 class BitcodeReaderMetadataList {
159 /// Array of metadata references.
161 /// Don't use std::vector here. Some versions of libc++ copy (instead of
162 /// move) on resize, and TrackingMDRef is very expensive to copy.
163 SmallVector<TrackingMDRef, 1> MetadataPtrs;
165 /// Structures for resolving old type refs.
167 SmallDenseMap<MDString *, TempMDTuple, 1> Unknown;
168 SmallDenseMap<MDString *, DICompositeType *, 1> Final;
169 SmallDenseMap<MDString *, DICompositeType *, 1> FwdDecls;
170 SmallVector<std::pair<TrackingMDRef, TempMDTuple>, 1> Arrays;
173 LLVMContext &Context;
176 BitcodeReaderMetadataList(LLVMContext &C)
177 : NumFwdRefs(0), AnyFwdRefs(false), Context(C) {}
179 // vector compatibility methods
180 unsigned size() const { return MetadataPtrs.size(); }
181 void resize(unsigned N) { MetadataPtrs.resize(N); }
182 void push_back(Metadata *MD) { MetadataPtrs.emplace_back(MD); }
183 void clear() { MetadataPtrs.clear(); }
184 Metadata *back() const { return MetadataPtrs.back(); }
185 void pop_back() { MetadataPtrs.pop_back(); }
186 bool empty() const { return MetadataPtrs.empty(); }
188 Metadata *operator[](unsigned i) const {
189 assert(i < MetadataPtrs.size());
190 return MetadataPtrs[i];
193 Metadata *lookup(unsigned I) const {
194 if (I < MetadataPtrs.size())
195 return MetadataPtrs[I];
199 void shrinkTo(unsigned N) {
200 assert(N <= size() && "Invalid shrinkTo request!");
201 assert(!AnyFwdRefs && "Unexpected forward refs");
202 MetadataPtrs.resize(N);
205 /// Return the given metadata, creating a replaceable forward reference if
207 Metadata *getMetadataFwdRef(unsigned Idx);
209 /// Return the the given metadata only if it is fully resolved.
211 /// Gives the same result as \a lookup(), unless \a MDNode::isResolved()
212 /// would give \c false.
213 Metadata *getMetadataIfResolved(unsigned Idx);
215 MDNode *getMDNodeFwdRefOrNull(unsigned Idx);
216 void assignValue(Metadata *MD, unsigned Idx);
217 void tryToResolveCycles();
218 bool hasFwdRefs() const { return AnyFwdRefs; }
220 /// Upgrade a type that had an MDString reference.
221 void addTypeRef(MDString &UUID, DICompositeType &CT);
223 /// Upgrade a type that had an MDString reference.
224 Metadata *upgradeTypeRef(Metadata *MaybeUUID);
226 /// Upgrade a type ref array that may have MDString references.
227 Metadata *upgradeTypeRefArray(Metadata *MaybeTuple);
230 Metadata *resolveTypeRefArray(Metadata *MaybeTuple);
233 class BitcodeReaderBase {
235 BitcodeReaderBase() = default;
236 BitcodeReaderBase(MemoryBuffer *Buffer) : Buffer(Buffer) {}
238 std::unique_ptr<MemoryBuffer> Buffer;
239 std::unique_ptr<BitstreamReader> StreamFile;
240 BitstreamCursor Stream;
242 std::error_code initStream(std::unique_ptr<DataStreamer> Streamer);
243 std::error_code initStreamFromBuffer();
244 std::error_code initLazyStream(std::unique_ptr<DataStreamer> Streamer);
246 virtual std::error_code error(const Twine &Message) = 0;
247 virtual ~BitcodeReaderBase() = default;
251 BitcodeReaderBase::initStream(std::unique_ptr<DataStreamer> Streamer) {
253 return initLazyStream(std::move(Streamer));
254 return initStreamFromBuffer();
257 std::error_code BitcodeReaderBase::initStreamFromBuffer() {
258 const unsigned char *BufPtr = (const unsigned char*)Buffer->getBufferStart();
259 const unsigned char *BufEnd = BufPtr+Buffer->getBufferSize();
261 if (Buffer->getBufferSize() & 3)
262 return error("Invalid bitcode signature");
264 // If we have a wrapper header, parse it and ignore the non-bc file contents.
265 // The magic number is 0x0B17C0DE stored in little endian.
266 if (isBitcodeWrapper(BufPtr, BufEnd))
267 if (SkipBitcodeWrapperHeader(BufPtr, BufEnd, true))
268 return error("Invalid bitcode wrapper header");
270 StreamFile.reset(new BitstreamReader(BufPtr, BufEnd));
271 Stream.init(&*StreamFile);
273 return std::error_code();
277 BitcodeReaderBase::initLazyStream(std::unique_ptr<DataStreamer> Streamer) {
278 // Check and strip off the bitcode wrapper; BitstreamReader expects never to
281 llvm::make_unique<StreamingMemoryObject>(std::move(Streamer));
282 StreamingMemoryObject &Bytes = *OwnedBytes;
283 StreamFile = llvm::make_unique<BitstreamReader>(std::move(OwnedBytes));
284 Stream.init(&*StreamFile);
286 unsigned char buf[16];
287 if (Bytes.readBytes(buf, 16, 0) != 16)
288 return error("Invalid bitcode signature");
290 if (!isBitcode(buf, buf + 16))
291 return error("Invalid bitcode signature");
293 if (isBitcodeWrapper(buf, buf + 4)) {
294 const unsigned char *bitcodeStart = buf;
295 const unsigned char *bitcodeEnd = buf + 16;
296 SkipBitcodeWrapperHeader(bitcodeStart, bitcodeEnd, false);
297 Bytes.dropLeadingBytes(bitcodeStart - buf);
298 Bytes.setKnownObjectSize(bitcodeEnd - bitcodeStart);
300 return std::error_code();
303 class BitcodeReader : public BitcodeReaderBase, public GVMaterializer {
304 LLVMContext &Context;
305 Module *TheModule = nullptr;
306 // Next offset to start scanning for lazy parsing of function bodies.
307 uint64_t NextUnreadBit = 0;
308 // Last function offset found in the VST.
309 uint64_t LastFunctionBlockBit = 0;
310 bool SeenValueSymbolTable = false;
311 uint64_t VSTOffset = 0;
312 // Contains an arbitrary and optional string identifying the bitcode producer
313 std::string ProducerIdentification;
315 std::vector<Type*> TypeList;
316 BitcodeReaderValueList ValueList;
317 BitcodeReaderMetadataList MetadataList;
318 std::vector<Comdat *> ComdatList;
319 SmallVector<Instruction *, 64> InstructionList;
321 std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInits;
322 std::vector<std::pair<GlobalIndirectSymbol*, unsigned> > IndirectSymbolInits;
323 std::vector<std::pair<Function*, unsigned> > FunctionPrefixes;
324 std::vector<std::pair<Function*, unsigned> > FunctionPrologues;
325 std::vector<std::pair<Function*, unsigned> > FunctionPersonalityFns;
327 bool HasSeenOldLoopTags = false;
329 /// The set of attributes by index. Index zero in the file is for null, and
330 /// is thus not represented here. As such all indices are off by one.
331 std::vector<AttributeSet> MAttributes;
333 /// The set of attribute groups.
334 std::map<unsigned, AttributeSet> MAttributeGroups;
336 /// While parsing a function body, this is a list of the basic blocks for the
338 std::vector<BasicBlock*> FunctionBBs;
340 // When reading the module header, this list is populated with functions that
341 // have bodies later in the file.
342 std::vector<Function*> FunctionsWithBodies;
344 // When intrinsic functions are encountered which require upgrading they are
345 // stored here with their replacement function.
346 typedef DenseMap<Function*, Function*> UpdatedIntrinsicMap;
347 UpdatedIntrinsicMap UpgradedIntrinsics;
348 // Intrinsics which were remangled because of types rename
349 UpdatedIntrinsicMap RemangledIntrinsics;
351 // Map the bitcode's custom MDKind ID to the Module's MDKind ID.
352 DenseMap<unsigned, unsigned> MDKindMap;
354 // Several operations happen after the module header has been read, but
355 // before function bodies are processed. This keeps track of whether
356 // we've done this yet.
357 bool SeenFirstFunctionBody = false;
359 /// When function bodies are initially scanned, this map contains info about
360 /// where to find deferred function body in the stream.
361 DenseMap<Function*, uint64_t> DeferredFunctionInfo;
363 /// When Metadata block is initially scanned when parsing the module, we may
364 /// choose to defer parsing of the metadata. This vector contains info about
365 /// which Metadata blocks are deferred.
366 std::vector<uint64_t> DeferredMetadataInfo;
368 /// These are basic blocks forward-referenced by block addresses. They are
369 /// inserted lazily into functions when they're loaded. The basic block ID is
370 /// its index into the vector.
371 DenseMap<Function *, std::vector<BasicBlock *>> BasicBlockFwdRefs;
372 std::deque<Function *> BasicBlockFwdRefQueue;
374 /// Indicates that we are using a new encoding for instruction operands where
375 /// most operands in the current FUNCTION_BLOCK are encoded relative to the
376 /// instruction number, for a more compact encoding. Some instruction
377 /// operands are not relative to the instruction ID: basic block numbers, and
378 /// types. Once the old style function blocks have been phased out, we would
379 /// not need this flag.
380 bool UseRelativeIDs = false;
382 /// True if all functions will be materialized, negating the need to process
383 /// (e.g.) blockaddress forward references.
384 bool WillMaterializeAllForwardRefs = false;
386 /// True if any Metadata block has been materialized.
387 bool IsMetadataMaterialized = false;
389 bool StripDebugInfo = false;
391 /// Functions that need to be matched with subprograms when upgrading old
393 SmallDenseMap<Function *, DISubprogram *, 16> FunctionsWithSPs;
395 std::vector<std::string> BundleTags;
398 std::error_code error(BitcodeError E, const Twine &Message);
399 std::error_code error(const Twine &Message) override;
401 BitcodeReader(MemoryBuffer *Buffer, LLVMContext &Context);
402 BitcodeReader(LLVMContext &Context);
403 ~BitcodeReader() override { freeState(); }
405 std::error_code materializeForwardReferencedFunctions();
409 void releaseBuffer();
411 std::error_code materialize(GlobalValue *GV) override;
412 std::error_code materializeModule() override;
413 std::vector<StructType *> getIdentifiedStructTypes() const override;
415 /// \brief Main interface to parsing a bitcode buffer.
416 /// \returns true if an error occurred.
417 std::error_code parseBitcodeInto(std::unique_ptr<DataStreamer> Streamer,
419 bool ShouldLazyLoadMetadata = false);
421 /// \brief Cheap mechanism to just extract module triple
422 /// \returns true if an error occurred.
423 ErrorOr<std::string> parseTriple();
425 /// Cheap mechanism to just extract the identification block out of bitcode.
426 ErrorOr<std::string> parseIdentificationBlock();
428 /// Peak at the module content and return true if any ObjC category or class
430 ErrorOr<bool> hasObjCCategory();
432 static uint64_t decodeSignRotatedValue(uint64_t V);
434 /// Materialize any deferred Metadata block.
435 std::error_code materializeMetadata() override;
437 void setStripDebugInfo() override;
440 /// Parse the "IDENTIFICATION_BLOCK_ID" block, populate the
441 // ProducerIdentification data member, and do some basic enforcement on the
442 // "epoch" encoded in the bitcode.
443 std::error_code parseBitcodeVersion();
445 std::vector<StructType *> IdentifiedStructTypes;
446 StructType *createIdentifiedStructType(LLVMContext &Context, StringRef Name);
447 StructType *createIdentifiedStructType(LLVMContext &Context);
449 Type *getTypeByID(unsigned ID);
451 Value *getFnValueByID(unsigned ID, Type *Ty) {
452 if (Ty && Ty->isMetadataTy())
453 return MetadataAsValue::get(Ty->getContext(), getFnMetadataByID(ID));
454 return ValueList.getValueFwdRef(ID, Ty);
457 Metadata *getFnMetadataByID(unsigned ID) {
458 return MetadataList.getMetadataFwdRef(ID);
461 BasicBlock *getBasicBlock(unsigned ID) const {
462 if (ID >= FunctionBBs.size()) return nullptr; // Invalid ID
463 return FunctionBBs[ID];
466 AttributeSet getAttributes(unsigned i) const {
467 if (i-1 < MAttributes.size())
468 return MAttributes[i-1];
469 return AttributeSet();
472 /// Read a value/type pair out of the specified record from slot 'Slot'.
473 /// Increment Slot past the number of slots used in the record. Return true on
475 bool getValueTypePair(SmallVectorImpl<uint64_t> &Record, unsigned &Slot,
476 unsigned InstNum, Value *&ResVal) {
477 if (Slot == Record.size()) return true;
478 unsigned ValNo = (unsigned)Record[Slot++];
479 // Adjust the ValNo, if it was encoded relative to the InstNum.
481 ValNo = InstNum - ValNo;
482 if (ValNo < InstNum) {
483 // If this is not a forward reference, just return the value we already
485 ResVal = getFnValueByID(ValNo, nullptr);
486 return ResVal == nullptr;
488 if (Slot == Record.size())
491 unsigned TypeNo = (unsigned)Record[Slot++];
492 ResVal = getFnValueByID(ValNo, getTypeByID(TypeNo));
493 return ResVal == nullptr;
496 /// Read a value out of the specified record from slot 'Slot'. Increment Slot
497 /// past the number of slots used by the value in the record. Return true if
498 /// there is an error.
499 bool popValue(SmallVectorImpl<uint64_t> &Record, unsigned &Slot,
500 unsigned InstNum, Type *Ty, Value *&ResVal) {
501 if (getValue(Record, Slot, InstNum, Ty, ResVal))
503 // All values currently take a single record slot.
508 /// Like popValue, but does not increment the Slot number.
509 bool getValue(SmallVectorImpl<uint64_t> &Record, unsigned Slot,
510 unsigned InstNum, Type *Ty, Value *&ResVal) {
511 ResVal = getValue(Record, Slot, InstNum, Ty);
512 return ResVal == nullptr;
515 /// Version of getValue that returns ResVal directly, or 0 if there is an
517 Value *getValue(SmallVectorImpl<uint64_t> &Record, unsigned Slot,
518 unsigned InstNum, Type *Ty) {
519 if (Slot == Record.size()) return nullptr;
520 unsigned ValNo = (unsigned)Record[Slot];
521 // Adjust the ValNo, if it was encoded relative to the InstNum.
523 ValNo = InstNum - ValNo;
524 return getFnValueByID(ValNo, Ty);
527 /// Like getValue, but decodes signed VBRs.
528 Value *getValueSigned(SmallVectorImpl<uint64_t> &Record, unsigned Slot,
529 unsigned InstNum, Type *Ty) {
530 if (Slot == Record.size()) return nullptr;
531 unsigned ValNo = (unsigned)decodeSignRotatedValue(Record[Slot]);
532 // Adjust the ValNo, if it was encoded relative to the InstNum.
534 ValNo = InstNum - ValNo;
535 return getFnValueByID(ValNo, Ty);
538 /// Converts alignment exponent (i.e. power of two (or zero)) to the
539 /// corresponding alignment to use. If alignment is too large, returns
540 /// a corresponding error code.
541 std::error_code parseAlignmentValue(uint64_t Exponent, unsigned &Alignment);
542 std::error_code parseAttrKind(uint64_t Code, Attribute::AttrKind *Kind);
543 std::error_code parseModule(uint64_t ResumeBit,
544 bool ShouldLazyLoadMetadata = false);
545 std::error_code parseAttributeBlock();
546 std::error_code parseAttributeGroupBlock();
547 std::error_code parseTypeTable();
548 std::error_code parseTypeTableBody();
549 std::error_code parseOperandBundleTags();
551 ErrorOr<Value *> recordValue(SmallVectorImpl<uint64_t> &Record,
552 unsigned NameIndex, Triple &TT);
553 std::error_code parseValueSymbolTable(uint64_t Offset = 0);
554 std::error_code parseConstants();
555 std::error_code rememberAndSkipFunctionBodies();
556 std::error_code rememberAndSkipFunctionBody();
557 /// Save the positions of the Metadata blocks and skip parsing the blocks.
558 std::error_code rememberAndSkipMetadata();
559 std::error_code parseFunctionBody(Function *F);
560 std::error_code globalCleanup();
561 std::error_code resolveGlobalAndIndirectSymbolInits();
562 std::error_code parseMetadata(bool ModuleLevel = false);
563 std::error_code parseMetadataStrings(ArrayRef<uint64_t> Record,
565 unsigned &NextMetadataNo);
566 std::error_code parseMetadataKinds();
567 std::error_code parseMetadataKindRecord(SmallVectorImpl<uint64_t> &Record);
569 parseGlobalObjectAttachment(GlobalObject &GO,
570 ArrayRef<uint64_t> Record);
571 std::error_code parseMetadataAttachment(Function &F);
572 ErrorOr<std::string> parseModuleTriple();
573 ErrorOr<bool> hasObjCCategoryInModule();
574 std::error_code parseUseLists();
575 std::error_code findFunctionInStream(
577 DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator);
580 /// Class to manage reading and parsing function summary index bitcode
582 class ModuleSummaryIndexBitcodeReader : public BitcodeReaderBase {
583 DiagnosticHandlerFunction DiagnosticHandler;
585 /// Eventually points to the module index built during parsing.
586 ModuleSummaryIndex *TheIndex = nullptr;
588 /// Used to indicate whether caller only wants to check for the presence
589 /// of the global value summary bitcode section. All blocks are skipped,
590 /// but the SeenGlobalValSummary boolean is set.
591 bool CheckGlobalValSummaryPresenceOnly = false;
593 /// Indicates whether we have encountered a global value summary section
594 /// yet during parsing, used when checking if file contains global value
596 bool SeenGlobalValSummary = false;
598 /// Indicates whether we have already parsed the VST, used for error checking.
599 bool SeenValueSymbolTable = false;
601 /// Set to the offset of the VST recorded in the MODULE_CODE_VSTOFFSET record.
602 /// Used to enable on-demand parsing of the VST.
603 uint64_t VSTOffset = 0;
605 // Map to save ValueId to GUID association that was recorded in the
606 // ValueSymbolTable. It is used after the VST is parsed to convert
607 // call graph edges read from the function summary from referencing
608 // callees by their ValueId to using the GUID instead, which is how
609 // they are recorded in the summary index being built.
610 // We save a second GUID which is the same as the first one, but ignoring the
611 // linkage, i.e. for value other than local linkage they are identical.
612 DenseMap<unsigned, std::pair<GlobalValue::GUID, GlobalValue::GUID>>
613 ValueIdToCallGraphGUIDMap;
615 /// Map populated during module path string table parsing, from the
616 /// module ID to a string reference owned by the index's module
617 /// path string table, used to correlate with combined index
619 DenseMap<uint64_t, StringRef> ModuleIdMap;
621 /// Original source file name recorded in a bitcode record.
622 std::string SourceFileName;
625 std::error_code error(const Twine &Message);
627 ModuleSummaryIndexBitcodeReader(
628 MemoryBuffer *Buffer, DiagnosticHandlerFunction DiagnosticHandler,
629 bool CheckGlobalValSummaryPresenceOnly = false);
630 ~ModuleSummaryIndexBitcodeReader() { freeState(); }
634 void releaseBuffer();
636 /// Check if the parser has encountered a summary section.
637 bool foundGlobalValSummary() { return SeenGlobalValSummary; }
639 /// \brief Main interface to parsing a bitcode buffer.
640 /// \returns true if an error occurred.
641 std::error_code parseSummaryIndexInto(std::unique_ptr<DataStreamer> Streamer,
642 ModuleSummaryIndex *I);
645 std::error_code parseModule();
646 std::error_code parseValueSymbolTable(
648 DenseMap<unsigned, GlobalValue::LinkageTypes> &ValueIdToLinkageMap);
649 std::error_code parseEntireSummary();
650 std::error_code parseModuleStringTable();
651 std::pair<GlobalValue::GUID, GlobalValue::GUID>
653 getGUIDFromValueId(unsigned ValueId);
654 std::pair<GlobalValue::GUID, CalleeInfo::HotnessType>
655 readCallGraphEdge(const SmallVector<uint64_t, 64> &Record, unsigned int &I,
656 bool IsOldProfileFormat, bool HasProfile);
659 } // end anonymous namespace
661 BitcodeDiagnosticInfo::BitcodeDiagnosticInfo(std::error_code EC,
662 DiagnosticSeverity Severity,
664 : DiagnosticInfo(DK_Bitcode, Severity), Msg(Msg), EC(EC) {}
666 void BitcodeDiagnosticInfo::print(DiagnosticPrinter &DP) const { DP << Msg; }
668 static std::error_code error(const DiagnosticHandlerFunction &DiagnosticHandler,
669 std::error_code EC, const Twine &Message) {
670 BitcodeDiagnosticInfo DI(EC, DS_Error, Message);
671 DiagnosticHandler(DI);
675 static std::error_code error(LLVMContext &Context, std::error_code EC,
676 const Twine &Message) {
677 return error([&](const DiagnosticInfo &DI) { Context.diagnose(DI); }, EC,
681 static std::error_code error(LLVMContext &Context, const Twine &Message) {
682 return error(Context, make_error_code(BitcodeError::CorruptedBitcode),
686 std::error_code BitcodeReader::error(BitcodeError E, const Twine &Message) {
687 if (!ProducerIdentification.empty()) {
688 return ::error(Context, make_error_code(E),
689 Message + " (Producer: '" + ProducerIdentification +
690 "' Reader: 'LLVM " + LLVM_VERSION_STRING "')");
692 return ::error(Context, make_error_code(E), Message);
695 std::error_code BitcodeReader::error(const Twine &Message) {
696 if (!ProducerIdentification.empty()) {
697 return ::error(Context, make_error_code(BitcodeError::CorruptedBitcode),
698 Message + " (Producer: '" + ProducerIdentification +
699 "' Reader: 'LLVM " + LLVM_VERSION_STRING "')");
701 return ::error(Context, make_error_code(BitcodeError::CorruptedBitcode),
705 BitcodeReader::BitcodeReader(MemoryBuffer *Buffer, LLVMContext &Context)
706 : BitcodeReaderBase(Buffer), Context(Context), ValueList(Context),
707 MetadataList(Context) {}
709 BitcodeReader::BitcodeReader(LLVMContext &Context)
710 : Context(Context), ValueList(Context), MetadataList(Context) {}
712 std::error_code BitcodeReader::materializeForwardReferencedFunctions() {
713 if (WillMaterializeAllForwardRefs)
714 return std::error_code();
716 // Prevent recursion.
717 WillMaterializeAllForwardRefs = true;
719 while (!BasicBlockFwdRefQueue.empty()) {
720 Function *F = BasicBlockFwdRefQueue.front();
721 BasicBlockFwdRefQueue.pop_front();
722 assert(F && "Expected valid function");
723 if (!BasicBlockFwdRefs.count(F))
724 // Already materialized.
727 // Check for a function that isn't materializable to prevent an infinite
728 // loop. When parsing a blockaddress stored in a global variable, there
729 // isn't a trivial way to check if a function will have a body without a
730 // linear search through FunctionsWithBodies, so just check it here.
731 if (!F->isMaterializable())
732 return error("Never resolved function from blockaddress");
734 // Try to materialize F.
735 if (std::error_code EC = materialize(F))
738 assert(BasicBlockFwdRefs.empty() && "Function missing from queue");
741 WillMaterializeAllForwardRefs = false;
742 return std::error_code();
745 void BitcodeReader::freeState() {
747 std::vector<Type*>().swap(TypeList);
749 MetadataList.clear();
750 std::vector<Comdat *>().swap(ComdatList);
752 std::vector<AttributeSet>().swap(MAttributes);
753 std::vector<BasicBlock*>().swap(FunctionBBs);
754 std::vector<Function*>().swap(FunctionsWithBodies);
755 DeferredFunctionInfo.clear();
756 DeferredMetadataInfo.clear();
759 assert(BasicBlockFwdRefs.empty() && "Unresolved blockaddress fwd references");
760 BasicBlockFwdRefQueue.clear();
763 //===----------------------------------------------------------------------===//
764 // Helper functions to implement forward reference resolution, etc.
765 //===----------------------------------------------------------------------===//
767 /// Convert a string from a record into an std::string, return true on failure.
768 template <typename StrTy>
769 static bool convertToString(ArrayRef<uint64_t> Record, unsigned Idx,
771 if (Idx > Record.size())
774 for (unsigned i = Idx, e = Record.size(); i != e; ++i)
775 Result += (char)Record[i];
779 static bool hasImplicitComdat(size_t Val) {
783 case 1: // Old WeakAnyLinkage
784 case 4: // Old LinkOnceAnyLinkage
785 case 10: // Old WeakODRLinkage
786 case 11: // Old LinkOnceODRLinkage
791 static GlobalValue::LinkageTypes getDecodedLinkage(unsigned Val) {
793 default: // Map unknown/new linkages to external
795 return GlobalValue::ExternalLinkage;
797 return GlobalValue::AppendingLinkage;
799 return GlobalValue::InternalLinkage;
801 return GlobalValue::ExternalLinkage; // Obsolete DLLImportLinkage
803 return GlobalValue::ExternalLinkage; // Obsolete DLLExportLinkage
805 return GlobalValue::ExternalWeakLinkage;
807 return GlobalValue::CommonLinkage;
809 return GlobalValue::PrivateLinkage;
811 return GlobalValue::AvailableExternallyLinkage;
813 return GlobalValue::PrivateLinkage; // Obsolete LinkerPrivateLinkage
815 return GlobalValue::PrivateLinkage; // Obsolete LinkerPrivateWeakLinkage
817 return GlobalValue::ExternalLinkage; // Obsolete LinkOnceODRAutoHideLinkage
818 case 1: // Old value with implicit comdat.
820 return GlobalValue::WeakAnyLinkage;
821 case 10: // Old value with implicit comdat.
823 return GlobalValue::WeakODRLinkage;
824 case 4: // Old value with implicit comdat.
826 return GlobalValue::LinkOnceAnyLinkage;
827 case 11: // Old value with implicit comdat.
829 return GlobalValue::LinkOnceODRLinkage;
833 /// Decode the flags for GlobalValue in the summary.
834 static GlobalValueSummary::GVFlags getDecodedGVSummaryFlags(uint64_t RawFlags,
836 // Summary were not emitted before LLVM 3.9, we don't need to upgrade Linkage
837 // like getDecodedLinkage() above. Any future change to the linkage enum and
838 // to getDecodedLinkage() will need to be taken into account here as above.
839 auto Linkage = GlobalValue::LinkageTypes(RawFlags & 0xF); // 4 bits
840 RawFlags = RawFlags >> 4;
841 bool HasSection = RawFlags & 0x1;
842 bool IsNotViableToInline = RawFlags & 0x2;
843 return GlobalValueSummary::GVFlags(Linkage, HasSection, IsNotViableToInline);
846 static GlobalValue::VisibilityTypes getDecodedVisibility(unsigned Val) {
848 default: // Map unknown visibilities to default.
849 case 0: return GlobalValue::DefaultVisibility;
850 case 1: return GlobalValue::HiddenVisibility;
851 case 2: return GlobalValue::ProtectedVisibility;
855 static GlobalValue::DLLStorageClassTypes
856 getDecodedDLLStorageClass(unsigned Val) {
858 default: // Map unknown values to default.
859 case 0: return GlobalValue::DefaultStorageClass;
860 case 1: return GlobalValue::DLLImportStorageClass;
861 case 2: return GlobalValue::DLLExportStorageClass;
865 static GlobalVariable::ThreadLocalMode getDecodedThreadLocalMode(unsigned Val) {
867 case 0: return GlobalVariable::NotThreadLocal;
868 default: // Map unknown non-zero value to general dynamic.
869 case 1: return GlobalVariable::GeneralDynamicTLSModel;
870 case 2: return GlobalVariable::LocalDynamicTLSModel;
871 case 3: return GlobalVariable::InitialExecTLSModel;
872 case 4: return GlobalVariable::LocalExecTLSModel;
876 static GlobalVariable::UnnamedAddr getDecodedUnnamedAddrType(unsigned Val) {
878 default: // Map unknown to UnnamedAddr::None.
879 case 0: return GlobalVariable::UnnamedAddr::None;
880 case 1: return GlobalVariable::UnnamedAddr::Global;
881 case 2: return GlobalVariable::UnnamedAddr::Local;
885 static int getDecodedCastOpcode(unsigned Val) {
888 case bitc::CAST_TRUNC : return Instruction::Trunc;
889 case bitc::CAST_ZEXT : return Instruction::ZExt;
890 case bitc::CAST_SEXT : return Instruction::SExt;
891 case bitc::CAST_FPTOUI : return Instruction::FPToUI;
892 case bitc::CAST_FPTOSI : return Instruction::FPToSI;
893 case bitc::CAST_UITOFP : return Instruction::UIToFP;
894 case bitc::CAST_SITOFP : return Instruction::SIToFP;
895 case bitc::CAST_FPTRUNC : return Instruction::FPTrunc;
896 case bitc::CAST_FPEXT : return Instruction::FPExt;
897 case bitc::CAST_PTRTOINT: return Instruction::PtrToInt;
898 case bitc::CAST_INTTOPTR: return Instruction::IntToPtr;
899 case bitc::CAST_BITCAST : return Instruction::BitCast;
900 case bitc::CAST_ADDRSPACECAST: return Instruction::AddrSpaceCast;
904 static int getDecodedBinaryOpcode(unsigned Val, Type *Ty) {
905 bool IsFP = Ty->isFPOrFPVectorTy();
906 // BinOps are only valid for int/fp or vector of int/fp types
907 if (!IsFP && !Ty->isIntOrIntVectorTy())
913 case bitc::BINOP_ADD:
914 return IsFP ? Instruction::FAdd : Instruction::Add;
915 case bitc::BINOP_SUB:
916 return IsFP ? Instruction::FSub : Instruction::Sub;
917 case bitc::BINOP_MUL:
918 return IsFP ? Instruction::FMul : Instruction::Mul;
919 case bitc::BINOP_UDIV:
920 return IsFP ? -1 : Instruction::UDiv;
921 case bitc::BINOP_SDIV:
922 return IsFP ? Instruction::FDiv : Instruction::SDiv;
923 case bitc::BINOP_UREM:
924 return IsFP ? -1 : Instruction::URem;
925 case bitc::BINOP_SREM:
926 return IsFP ? Instruction::FRem : Instruction::SRem;
927 case bitc::BINOP_SHL:
928 return IsFP ? -1 : Instruction::Shl;
929 case bitc::BINOP_LSHR:
930 return IsFP ? -1 : Instruction::LShr;
931 case bitc::BINOP_ASHR:
932 return IsFP ? -1 : Instruction::AShr;
933 case bitc::BINOP_AND:
934 return IsFP ? -1 : Instruction::And;
936 return IsFP ? -1 : Instruction::Or;
937 case bitc::BINOP_XOR:
938 return IsFP ? -1 : Instruction::Xor;
942 static AtomicRMWInst::BinOp getDecodedRMWOperation(unsigned Val) {
944 default: return AtomicRMWInst::BAD_BINOP;
945 case bitc::RMW_XCHG: return AtomicRMWInst::Xchg;
946 case bitc::RMW_ADD: return AtomicRMWInst::Add;
947 case bitc::RMW_SUB: return AtomicRMWInst::Sub;
948 case bitc::RMW_AND: return AtomicRMWInst::And;
949 case bitc::RMW_NAND: return AtomicRMWInst::Nand;
950 case bitc::RMW_OR: return AtomicRMWInst::Or;
951 case bitc::RMW_XOR: return AtomicRMWInst::Xor;
952 case bitc::RMW_MAX: return AtomicRMWInst::Max;
953 case bitc::RMW_MIN: return AtomicRMWInst::Min;
954 case bitc::RMW_UMAX: return AtomicRMWInst::UMax;
955 case bitc::RMW_UMIN: return AtomicRMWInst::UMin;
959 static AtomicOrdering getDecodedOrdering(unsigned Val) {
961 case bitc::ORDERING_NOTATOMIC: return AtomicOrdering::NotAtomic;
962 case bitc::ORDERING_UNORDERED: return AtomicOrdering::Unordered;
963 case bitc::ORDERING_MONOTONIC: return AtomicOrdering::Monotonic;
964 case bitc::ORDERING_ACQUIRE: return AtomicOrdering::Acquire;
965 case bitc::ORDERING_RELEASE: return AtomicOrdering::Release;
966 case bitc::ORDERING_ACQREL: return AtomicOrdering::AcquireRelease;
967 default: // Map unknown orderings to sequentially-consistent.
968 case bitc::ORDERING_SEQCST: return AtomicOrdering::SequentiallyConsistent;
972 static SynchronizationScope getDecodedSynchScope(unsigned Val) {
974 case bitc::SYNCHSCOPE_SINGLETHREAD: return SingleThread;
975 default: // Map unknown scopes to cross-thread.
976 case bitc::SYNCHSCOPE_CROSSTHREAD: return CrossThread;
980 static Comdat::SelectionKind getDecodedComdatSelectionKind(unsigned Val) {
982 default: // Map unknown selection kinds to any.
983 case bitc::COMDAT_SELECTION_KIND_ANY:
985 case bitc::COMDAT_SELECTION_KIND_EXACT_MATCH:
986 return Comdat::ExactMatch;
987 case bitc::COMDAT_SELECTION_KIND_LARGEST:
988 return Comdat::Largest;
989 case bitc::COMDAT_SELECTION_KIND_NO_DUPLICATES:
990 return Comdat::NoDuplicates;
991 case bitc::COMDAT_SELECTION_KIND_SAME_SIZE:
992 return Comdat::SameSize;
996 static FastMathFlags getDecodedFastMathFlags(unsigned Val) {
998 if (0 != (Val & FastMathFlags::UnsafeAlgebra))
999 FMF.setUnsafeAlgebra();
1000 if (0 != (Val & FastMathFlags::NoNaNs))
1002 if (0 != (Val & FastMathFlags::NoInfs))
1004 if (0 != (Val & FastMathFlags::NoSignedZeros))
1005 FMF.setNoSignedZeros();
1006 if (0 != (Val & FastMathFlags::AllowReciprocal))
1007 FMF.setAllowReciprocal();
1011 static void upgradeDLLImportExportLinkage(GlobalValue *GV, unsigned Val) {
1013 case 5: GV->setDLLStorageClass(GlobalValue::DLLImportStorageClass); break;
1014 case 6: GV->setDLLStorageClass(GlobalValue::DLLExportStorageClass); break;
1021 /// \brief A class for maintaining the slot number definition
1022 /// as a placeholder for the actual definition for forward constants defs.
1023 class ConstantPlaceHolder : public ConstantExpr {
1024 void operator=(const ConstantPlaceHolder &) = delete;
1027 // allocate space for exactly one operand
1028 void *operator new(size_t s) { return User::operator new(s, 1); }
1029 explicit ConstantPlaceHolder(Type *Ty, LLVMContext &Context)
1030 : ConstantExpr(Ty, Instruction::UserOp1, &Op<0>(), 1) {
1031 Op<0>() = UndefValue::get(Type::getInt32Ty(Context));
1034 /// \brief Methods to support type inquiry through isa, cast, and dyn_cast.
1035 static bool classof(const Value *V) {
1036 return isa<ConstantExpr>(V) &&
1037 cast<ConstantExpr>(V)->getOpcode() == Instruction::UserOp1;
1040 /// Provide fast operand accessors
1041 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
1044 } // end anonymous namespace
1046 // FIXME: can we inherit this from ConstantExpr?
1048 struct OperandTraits<ConstantPlaceHolder> :
1049 public FixedNumOperandTraits<ConstantPlaceHolder, 1> {
1051 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ConstantPlaceHolder, Value)
1053 } // end namespace llvm
1055 void BitcodeReaderValueList::assignValue(Value *V, unsigned Idx) {
1056 if (Idx == size()) {
1064 WeakVH &OldV = ValuePtrs[Idx];
1070 // Handle constants and non-constants (e.g. instrs) differently for
1072 if (Constant *PHC = dyn_cast<Constant>(&*OldV)) {
1073 ResolveConstants.push_back(std::make_pair(PHC, Idx));
1076 // If there was a forward reference to this value, replace it.
1077 Value *PrevVal = OldV;
1078 OldV->replaceAllUsesWith(V);
1083 Constant *BitcodeReaderValueList::getConstantFwdRef(unsigned Idx,
1088 if (Value *V = ValuePtrs[Idx]) {
1089 if (Ty != V->getType())
1090 report_fatal_error("Type mismatch in constant table!");
1091 return cast<Constant>(V);
1094 // Create and return a placeholder, which will later be RAUW'd.
1095 Constant *C = new ConstantPlaceHolder(Ty, Context);
1100 Value *BitcodeReaderValueList::getValueFwdRef(unsigned Idx, Type *Ty) {
1101 // Bail out for a clearly invalid value. This would make us call resize(0)
1102 if (Idx == std::numeric_limits<unsigned>::max())
1108 if (Value *V = ValuePtrs[Idx]) {
1109 // If the types don't match, it's invalid.
1110 if (Ty && Ty != V->getType())
1115 // No type specified, must be invalid reference.
1116 if (!Ty) return nullptr;
1118 // Create and return a placeholder, which will later be RAUW'd.
1119 Value *V = new Argument(Ty);
1124 /// Once all constants are read, this method bulk resolves any forward
1125 /// references. The idea behind this is that we sometimes get constants (such
1126 /// as large arrays) which reference *many* forward ref constants. Replacing
1127 /// each of these causes a lot of thrashing when building/reuniquing the
1128 /// constant. Instead of doing this, we look at all the uses and rewrite all
1129 /// the place holders at once for any constant that uses a placeholder.
1130 void BitcodeReaderValueList::resolveConstantForwardRefs() {
1131 // Sort the values by-pointer so that they are efficient to look up with a
1133 std::sort(ResolveConstants.begin(), ResolveConstants.end());
1135 SmallVector<Constant*, 64> NewOps;
1137 while (!ResolveConstants.empty()) {
1138 Value *RealVal = operator[](ResolveConstants.back().second);
1139 Constant *Placeholder = ResolveConstants.back().first;
1140 ResolveConstants.pop_back();
1142 // Loop over all users of the placeholder, updating them to reference the
1143 // new value. If they reference more than one placeholder, update them all
1145 while (!Placeholder->use_empty()) {
1146 auto UI = Placeholder->user_begin();
1149 // If the using object isn't uniqued, just update the operands. This
1150 // handles instructions and initializers for global variables.
1151 if (!isa<Constant>(U) || isa<GlobalValue>(U)) {
1152 UI.getUse().set(RealVal);
1156 // Otherwise, we have a constant that uses the placeholder. Replace that
1157 // constant with a new constant that has *all* placeholder uses updated.
1158 Constant *UserC = cast<Constant>(U);
1159 for (User::op_iterator I = UserC->op_begin(), E = UserC->op_end();
1162 if (!isa<ConstantPlaceHolder>(*I)) {
1163 // Not a placeholder reference.
1165 } else if (*I == Placeholder) {
1166 // Common case is that it just references this one placeholder.
1169 // Otherwise, look up the placeholder in ResolveConstants.
1170 ResolveConstantsTy::iterator It =
1171 std::lower_bound(ResolveConstants.begin(), ResolveConstants.end(),
1172 std::pair<Constant*, unsigned>(cast<Constant>(*I),
1174 assert(It != ResolveConstants.end() && It->first == *I);
1175 NewOp = operator[](It->second);
1178 NewOps.push_back(cast<Constant>(NewOp));
1181 // Make the new constant.
1183 if (ConstantArray *UserCA = dyn_cast<ConstantArray>(UserC)) {
1184 NewC = ConstantArray::get(UserCA->getType(), NewOps);
1185 } else if (ConstantStruct *UserCS = dyn_cast<ConstantStruct>(UserC)) {
1186 NewC = ConstantStruct::get(UserCS->getType(), NewOps);
1187 } else if (isa<ConstantVector>(UserC)) {
1188 NewC = ConstantVector::get(NewOps);
1190 assert(isa<ConstantExpr>(UserC) && "Must be a ConstantExpr.");
1191 NewC = cast<ConstantExpr>(UserC)->getWithOperands(NewOps);
1194 UserC->replaceAllUsesWith(NewC);
1195 UserC->destroyConstant();
1199 // Update all ValueHandles, they should be the only users at this point.
1200 Placeholder->replaceAllUsesWith(RealVal);
1205 void BitcodeReaderMetadataList::assignValue(Metadata *MD, unsigned Idx) {
1206 if (Idx == size()) {
1214 TrackingMDRef &OldMD = MetadataPtrs[Idx];
1220 // If there was a forward reference to this value, replace it.
1221 TempMDTuple PrevMD(cast<MDTuple>(OldMD.get()));
1222 PrevMD->replaceAllUsesWith(MD);
1226 Metadata *BitcodeReaderMetadataList::getMetadataFwdRef(unsigned Idx) {
1230 if (Metadata *MD = MetadataPtrs[Idx])
1233 // Track forward refs to be resolved later.
1235 MinFwdRef = std::min(MinFwdRef, Idx);
1236 MaxFwdRef = std::max(MaxFwdRef, Idx);
1239 MinFwdRef = MaxFwdRef = Idx;
1243 // Create and return a placeholder, which will later be RAUW'd.
1244 Metadata *MD = MDNode::getTemporary(Context, None).release();
1245 MetadataPtrs[Idx].reset(MD);
1249 Metadata *BitcodeReaderMetadataList::getMetadataIfResolved(unsigned Idx) {
1250 Metadata *MD = lookup(Idx);
1251 if (auto *N = dyn_cast_or_null<MDNode>(MD))
1252 if (!N->isResolved())
1257 MDNode *BitcodeReaderMetadataList::getMDNodeFwdRefOrNull(unsigned Idx) {
1258 return dyn_cast_or_null<MDNode>(getMetadataFwdRef(Idx));
1261 void BitcodeReaderMetadataList::tryToResolveCycles() {
1263 // Still forward references... can't resolve cycles.
1266 bool DidReplaceTypeRefs = false;
1268 // Give up on finding a full definition for any forward decls that remain.
1269 for (const auto &Ref : OldTypeRefs.FwdDecls)
1270 OldTypeRefs.Final.insert(Ref);
1271 OldTypeRefs.FwdDecls.clear();
1273 // Upgrade from old type ref arrays. In strange cases, this could add to
1274 // OldTypeRefs.Unknown.
1275 for (const auto &Array : OldTypeRefs.Arrays) {
1276 DidReplaceTypeRefs = true;
1277 Array.second->replaceAllUsesWith(resolveTypeRefArray(Array.first.get()));
1279 OldTypeRefs.Arrays.clear();
1281 // Replace old string-based type refs with the resolved node, if possible.
1282 // If we haven't seen the node, leave it to the verifier to complain about
1283 // the invalid string reference.
1284 for (const auto &Ref : OldTypeRefs.Unknown) {
1285 DidReplaceTypeRefs = true;
1286 if (DICompositeType *CT = OldTypeRefs.Final.lookup(Ref.first))
1287 Ref.second->replaceAllUsesWith(CT);
1289 Ref.second->replaceAllUsesWith(Ref.first);
1291 OldTypeRefs.Unknown.clear();
1293 // Make sure all the upgraded types are resolved.
1294 if (DidReplaceTypeRefs) {
1297 MaxFwdRef = MetadataPtrs.size() - 1;
1304 // Resolve any cycles.
1305 for (unsigned I = MinFwdRef, E = MaxFwdRef + 1; I != E; ++I) {
1306 auto &MD = MetadataPtrs[I];
1307 auto *N = dyn_cast_or_null<MDNode>(MD);
1311 assert(!N->isTemporary() && "Unexpected forward reference");
1315 // Make sure we return early again until there's another forward ref.
1319 void BitcodeReaderMetadataList::addTypeRef(MDString &UUID,
1320 DICompositeType &CT) {
1321 assert(CT.getRawIdentifier() == &UUID && "Mismatched UUID");
1322 if (CT.isForwardDecl())
1323 OldTypeRefs.FwdDecls.insert(std::make_pair(&UUID, &CT));
1325 OldTypeRefs.Final.insert(std::make_pair(&UUID, &CT));
1328 Metadata *BitcodeReaderMetadataList::upgradeTypeRef(Metadata *MaybeUUID) {
1329 auto *UUID = dyn_cast_or_null<MDString>(MaybeUUID);
1330 if (LLVM_LIKELY(!UUID))
1333 if (auto *CT = OldTypeRefs.Final.lookup(UUID))
1336 auto &Ref = OldTypeRefs.Unknown[UUID];
1338 Ref = MDNode::getTemporary(Context, None);
1342 Metadata *BitcodeReaderMetadataList::upgradeTypeRefArray(Metadata *MaybeTuple) {
1343 auto *Tuple = dyn_cast_or_null<MDTuple>(MaybeTuple);
1344 if (!Tuple || Tuple->isDistinct())
1347 // Look through the array immediately if possible.
1348 if (!Tuple->isTemporary())
1349 return resolveTypeRefArray(Tuple);
1351 // Create and return a placeholder to use for now. Eventually
1352 // resolveTypeRefArrays() will be resolve this forward reference.
1353 OldTypeRefs.Arrays.emplace_back(
1354 std::piecewise_construct, std::forward_as_tuple(Tuple),
1355 std::forward_as_tuple(MDTuple::getTemporary(Context, None)));
1356 return OldTypeRefs.Arrays.back().second.get();
1359 Metadata *BitcodeReaderMetadataList::resolveTypeRefArray(Metadata *MaybeTuple) {
1360 auto *Tuple = dyn_cast_or_null<MDTuple>(MaybeTuple);
1361 if (!Tuple || Tuple->isDistinct())
1364 // Look through the DITypeRefArray, upgrading each DITypeRef.
1365 SmallVector<Metadata *, 32> Ops;
1366 Ops.reserve(Tuple->getNumOperands());
1367 for (Metadata *MD : Tuple->operands())
1368 Ops.push_back(upgradeTypeRef(MD));
1370 return MDTuple::get(Context, Ops);
1373 Type *BitcodeReader::getTypeByID(unsigned ID) {
1374 // The type table size is always specified correctly.
1375 if (ID >= TypeList.size())
1378 if (Type *Ty = TypeList[ID])
1381 // If we have a forward reference, the only possible case is when it is to a
1382 // named struct. Just create a placeholder for now.
1383 return TypeList[ID] = createIdentifiedStructType(Context);
1386 StructType *BitcodeReader::createIdentifiedStructType(LLVMContext &Context,
1388 auto *Ret = StructType::create(Context, Name);
1389 IdentifiedStructTypes.push_back(Ret);
1393 StructType *BitcodeReader::createIdentifiedStructType(LLVMContext &Context) {
1394 auto *Ret = StructType::create(Context);
1395 IdentifiedStructTypes.push_back(Ret);
1399 //===----------------------------------------------------------------------===//
1400 // Functions for parsing blocks from the bitcode file
1401 //===----------------------------------------------------------------------===//
1403 /// \brief This fills an AttrBuilder object with the LLVM attributes that have
1404 /// been decoded from the given integer. This function must stay in sync with
1405 /// 'encodeLLVMAttributesForBitcode'.
1406 static void decodeLLVMAttributesForBitcode(AttrBuilder &B,
1407 uint64_t EncodedAttrs) {
1408 // FIXME: Remove in 4.0.
1410 // The alignment is stored as a 16-bit raw value from bits 31--16. We shift
1411 // the bits above 31 down by 11 bits.
1412 unsigned Alignment = (EncodedAttrs & (0xffffULL << 16)) >> 16;
1413 assert((!Alignment || isPowerOf2_32(Alignment)) &&
1414 "Alignment must be a power of two.");
1417 B.addAlignmentAttr(Alignment);
1418 B.addRawValue(((EncodedAttrs & (0xfffffULL << 32)) >> 11) |
1419 (EncodedAttrs & 0xffff));
1422 std::error_code BitcodeReader::parseAttributeBlock() {
1423 if (Stream.EnterSubBlock(bitc::PARAMATTR_BLOCK_ID))
1424 return error("Invalid record");
1426 if (!MAttributes.empty())
1427 return error("Invalid multiple blocks");
1429 SmallVector<uint64_t, 64> Record;
1431 SmallVector<AttributeSet, 8> Attrs;
1433 // Read all the records.
1435 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1437 switch (Entry.Kind) {
1438 case BitstreamEntry::SubBlock: // Handled for us already.
1439 case BitstreamEntry::Error:
1440 return error("Malformed block");
1441 case BitstreamEntry::EndBlock:
1442 return std::error_code();
1443 case BitstreamEntry::Record:
1444 // The interesting case.
1450 switch (Stream.readRecord(Entry.ID, Record)) {
1451 default: // Default behavior: ignore.
1453 case bitc::PARAMATTR_CODE_ENTRY_OLD: { // ENTRY: [paramidx0, attr0, ...]
1454 // FIXME: Remove in 4.0.
1455 if (Record.size() & 1)
1456 return error("Invalid record");
1458 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
1460 decodeLLVMAttributesForBitcode(B, Record[i+1]);
1461 Attrs.push_back(AttributeSet::get(Context, Record[i], B));
1464 MAttributes.push_back(AttributeSet::get(Context, Attrs));
1468 case bitc::PARAMATTR_CODE_ENTRY: { // ENTRY: [attrgrp0, attrgrp1, ...]
1469 for (unsigned i = 0, e = Record.size(); i != e; ++i)
1470 Attrs.push_back(MAttributeGroups[Record[i]]);
1472 MAttributes.push_back(AttributeSet::get(Context, Attrs));
1480 // Returns Attribute::None on unrecognized codes.
1481 static Attribute::AttrKind getAttrFromCode(uint64_t Code) {
1484 return Attribute::None;
1485 case bitc::ATTR_KIND_ALIGNMENT:
1486 return Attribute::Alignment;
1487 case bitc::ATTR_KIND_ALWAYS_INLINE:
1488 return Attribute::AlwaysInline;
1489 case bitc::ATTR_KIND_ARGMEMONLY:
1490 return Attribute::ArgMemOnly;
1491 case bitc::ATTR_KIND_BUILTIN:
1492 return Attribute::Builtin;
1493 case bitc::ATTR_KIND_BY_VAL:
1494 return Attribute::ByVal;
1495 case bitc::ATTR_KIND_IN_ALLOCA:
1496 return Attribute::InAlloca;
1497 case bitc::ATTR_KIND_COLD:
1498 return Attribute::Cold;
1499 case bitc::ATTR_KIND_CONVERGENT:
1500 return Attribute::Convergent;
1501 case bitc::ATTR_KIND_INACCESSIBLEMEM_ONLY:
1502 return Attribute::InaccessibleMemOnly;
1503 case bitc::ATTR_KIND_INACCESSIBLEMEM_OR_ARGMEMONLY:
1504 return Attribute::InaccessibleMemOrArgMemOnly;
1505 case bitc::ATTR_KIND_INLINE_HINT:
1506 return Attribute::InlineHint;
1507 case bitc::ATTR_KIND_IN_REG:
1508 return Attribute::InReg;
1509 case bitc::ATTR_KIND_JUMP_TABLE:
1510 return Attribute::JumpTable;
1511 case bitc::ATTR_KIND_MIN_SIZE:
1512 return Attribute::MinSize;
1513 case bitc::ATTR_KIND_NAKED:
1514 return Attribute::Naked;
1515 case bitc::ATTR_KIND_NEST:
1516 return Attribute::Nest;
1517 case bitc::ATTR_KIND_NO_ALIAS:
1518 return Attribute::NoAlias;
1519 case bitc::ATTR_KIND_NO_BUILTIN:
1520 return Attribute::NoBuiltin;
1521 case bitc::ATTR_KIND_NO_CAPTURE:
1522 return Attribute::NoCapture;
1523 case bitc::ATTR_KIND_NO_DUPLICATE:
1524 return Attribute::NoDuplicate;
1525 case bitc::ATTR_KIND_NO_IMPLICIT_FLOAT:
1526 return Attribute::NoImplicitFloat;
1527 case bitc::ATTR_KIND_NO_INLINE:
1528 return Attribute::NoInline;
1529 case bitc::ATTR_KIND_NO_RECURSE:
1530 return Attribute::NoRecurse;
1531 case bitc::ATTR_KIND_NON_LAZY_BIND:
1532 return Attribute::NonLazyBind;
1533 case bitc::ATTR_KIND_NON_NULL:
1534 return Attribute::NonNull;
1535 case bitc::ATTR_KIND_DEREFERENCEABLE:
1536 return Attribute::Dereferenceable;
1537 case bitc::ATTR_KIND_DEREFERENCEABLE_OR_NULL:
1538 return Attribute::DereferenceableOrNull;
1539 case bitc::ATTR_KIND_ALLOC_SIZE:
1540 return Attribute::AllocSize;
1541 case bitc::ATTR_KIND_NO_RED_ZONE:
1542 return Attribute::NoRedZone;
1543 case bitc::ATTR_KIND_NO_RETURN:
1544 return Attribute::NoReturn;
1545 case bitc::ATTR_KIND_NO_UNWIND:
1546 return Attribute::NoUnwind;
1547 case bitc::ATTR_KIND_OPTIMIZE_FOR_SIZE:
1548 return Attribute::OptimizeForSize;
1549 case bitc::ATTR_KIND_OPTIMIZE_NONE:
1550 return Attribute::OptimizeNone;
1551 case bitc::ATTR_KIND_READ_NONE:
1552 return Attribute::ReadNone;
1553 case bitc::ATTR_KIND_READ_ONLY:
1554 return Attribute::ReadOnly;
1555 case bitc::ATTR_KIND_RETURNED:
1556 return Attribute::Returned;
1557 case bitc::ATTR_KIND_RETURNS_TWICE:
1558 return Attribute::ReturnsTwice;
1559 case bitc::ATTR_KIND_S_EXT:
1560 return Attribute::SExt;
1561 case bitc::ATTR_KIND_STACK_ALIGNMENT:
1562 return Attribute::StackAlignment;
1563 case bitc::ATTR_KIND_STACK_PROTECT:
1564 return Attribute::StackProtect;
1565 case bitc::ATTR_KIND_STACK_PROTECT_REQ:
1566 return Attribute::StackProtectReq;
1567 case bitc::ATTR_KIND_STACK_PROTECT_STRONG:
1568 return Attribute::StackProtectStrong;
1569 case bitc::ATTR_KIND_SAFESTACK:
1570 return Attribute::SafeStack;
1571 case bitc::ATTR_KIND_STRUCT_RET:
1572 return Attribute::StructRet;
1573 case bitc::ATTR_KIND_SANITIZE_ADDRESS:
1574 return Attribute::SanitizeAddress;
1575 case bitc::ATTR_KIND_SANITIZE_THREAD:
1576 return Attribute::SanitizeThread;
1577 case bitc::ATTR_KIND_SANITIZE_MEMORY:
1578 return Attribute::SanitizeMemory;
1579 case bitc::ATTR_KIND_SWIFT_ERROR:
1580 return Attribute::SwiftError;
1581 case bitc::ATTR_KIND_SWIFT_SELF:
1582 return Attribute::SwiftSelf;
1583 case bitc::ATTR_KIND_UW_TABLE:
1584 return Attribute::UWTable;
1585 case bitc::ATTR_KIND_WRITEONLY:
1586 return Attribute::WriteOnly;
1587 case bitc::ATTR_KIND_Z_EXT:
1588 return Attribute::ZExt;
1592 std::error_code BitcodeReader::parseAlignmentValue(uint64_t Exponent,
1593 unsigned &Alignment) {
1594 // Note: Alignment in bitcode files is incremented by 1, so that zero
1595 // can be used for default alignment.
1596 if (Exponent > Value::MaxAlignmentExponent + 1)
1597 return error("Invalid alignment value");
1598 Alignment = (1 << static_cast<unsigned>(Exponent)) >> 1;
1599 return std::error_code();
1602 std::error_code BitcodeReader::parseAttrKind(uint64_t Code,
1603 Attribute::AttrKind *Kind) {
1604 *Kind = getAttrFromCode(Code);
1605 if (*Kind == Attribute::None)
1606 return error(BitcodeError::CorruptedBitcode,
1607 "Unknown attribute kind (" + Twine(Code) + ")");
1608 return std::error_code();
1611 std::error_code BitcodeReader::parseAttributeGroupBlock() {
1612 if (Stream.EnterSubBlock(bitc::PARAMATTR_GROUP_BLOCK_ID))
1613 return error("Invalid record");
1615 if (!MAttributeGroups.empty())
1616 return error("Invalid multiple blocks");
1618 SmallVector<uint64_t, 64> Record;
1620 // Read all the records.
1622 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1624 switch (Entry.Kind) {
1625 case BitstreamEntry::SubBlock: // Handled for us already.
1626 case BitstreamEntry::Error:
1627 return error("Malformed block");
1628 case BitstreamEntry::EndBlock:
1629 return std::error_code();
1630 case BitstreamEntry::Record:
1631 // The interesting case.
1637 switch (Stream.readRecord(Entry.ID, Record)) {
1638 default: // Default behavior: ignore.
1640 case bitc::PARAMATTR_GRP_CODE_ENTRY: { // ENTRY: [grpid, idx, a0, a1, ...]
1641 if (Record.size() < 3)
1642 return error("Invalid record");
1644 uint64_t GrpID = Record[0];
1645 uint64_t Idx = Record[1]; // Index of the object this attribute refers to.
1648 for (unsigned i = 2, e = Record.size(); i != e; ++i) {
1649 if (Record[i] == 0) { // Enum attribute
1650 Attribute::AttrKind Kind;
1651 if (std::error_code EC = parseAttrKind(Record[++i], &Kind))
1654 B.addAttribute(Kind);
1655 } else if (Record[i] == 1) { // Integer attribute
1656 Attribute::AttrKind Kind;
1657 if (std::error_code EC = parseAttrKind(Record[++i], &Kind))
1659 if (Kind == Attribute::Alignment)
1660 B.addAlignmentAttr(Record[++i]);
1661 else if (Kind == Attribute::StackAlignment)
1662 B.addStackAlignmentAttr(Record[++i]);
1663 else if (Kind == Attribute::Dereferenceable)
1664 B.addDereferenceableAttr(Record[++i]);
1665 else if (Kind == Attribute::DereferenceableOrNull)
1666 B.addDereferenceableOrNullAttr(Record[++i]);
1667 else if (Kind == Attribute::AllocSize)
1668 B.addAllocSizeAttrFromRawRepr(Record[++i]);
1669 } else { // String attribute
1670 assert((Record[i] == 3 || Record[i] == 4) &&
1671 "Invalid attribute group entry");
1672 bool HasValue = (Record[i++] == 4);
1673 SmallString<64> KindStr;
1674 SmallString<64> ValStr;
1676 while (Record[i] != 0 && i != e)
1677 KindStr += Record[i++];
1678 assert(Record[i] == 0 && "Kind string not null terminated");
1681 // Has a value associated with it.
1682 ++i; // Skip the '0' that terminates the "kind" string.
1683 while (Record[i] != 0 && i != e)
1684 ValStr += Record[i++];
1685 assert(Record[i] == 0 && "Value string not null terminated");
1688 B.addAttribute(KindStr.str(), ValStr.str());
1692 MAttributeGroups[GrpID] = AttributeSet::get(Context, Idx, B);
1699 std::error_code BitcodeReader::parseTypeTable() {
1700 if (Stream.EnterSubBlock(bitc::TYPE_BLOCK_ID_NEW))
1701 return error("Invalid record");
1703 return parseTypeTableBody();
1706 std::error_code BitcodeReader::parseTypeTableBody() {
1707 if (!TypeList.empty())
1708 return error("Invalid multiple blocks");
1710 SmallVector<uint64_t, 64> Record;
1711 unsigned NumRecords = 0;
1713 SmallString<64> TypeName;
1715 // Read all the records for this type table.
1717 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1719 switch (Entry.Kind) {
1720 case BitstreamEntry::SubBlock: // Handled for us already.
1721 case BitstreamEntry::Error:
1722 return error("Malformed block");
1723 case BitstreamEntry::EndBlock:
1724 if (NumRecords != TypeList.size())
1725 return error("Malformed block");
1726 return std::error_code();
1727 case BitstreamEntry::Record:
1728 // The interesting case.
1734 Type *ResultTy = nullptr;
1735 switch (Stream.readRecord(Entry.ID, Record)) {
1737 return error("Invalid value");
1738 case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries]
1739 // TYPE_CODE_NUMENTRY contains a count of the number of types in the
1740 // type list. This allows us to reserve space.
1741 if (Record.size() < 1)
1742 return error("Invalid record");
1743 TypeList.resize(Record[0]);
1745 case bitc::TYPE_CODE_VOID: // VOID
1746 ResultTy = Type::getVoidTy(Context);
1748 case bitc::TYPE_CODE_HALF: // HALF
1749 ResultTy = Type::getHalfTy(Context);
1751 case bitc::TYPE_CODE_FLOAT: // FLOAT
1752 ResultTy = Type::getFloatTy(Context);
1754 case bitc::TYPE_CODE_DOUBLE: // DOUBLE
1755 ResultTy = Type::getDoubleTy(Context);
1757 case bitc::TYPE_CODE_X86_FP80: // X86_FP80
1758 ResultTy = Type::getX86_FP80Ty(Context);
1760 case bitc::TYPE_CODE_FP128: // FP128
1761 ResultTy = Type::getFP128Ty(Context);
1763 case bitc::TYPE_CODE_PPC_FP128: // PPC_FP128
1764 ResultTy = Type::getPPC_FP128Ty(Context);
1766 case bitc::TYPE_CODE_LABEL: // LABEL
1767 ResultTy = Type::getLabelTy(Context);
1769 case bitc::TYPE_CODE_METADATA: // METADATA
1770 ResultTy = Type::getMetadataTy(Context);
1772 case bitc::TYPE_CODE_X86_MMX: // X86_MMX
1773 ResultTy = Type::getX86_MMXTy(Context);
1775 case bitc::TYPE_CODE_TOKEN: // TOKEN
1776 ResultTy = Type::getTokenTy(Context);
1778 case bitc::TYPE_CODE_INTEGER: { // INTEGER: [width]
1779 if (Record.size() < 1)
1780 return error("Invalid record");
1782 uint64_t NumBits = Record[0];
1783 if (NumBits < IntegerType::MIN_INT_BITS ||
1784 NumBits > IntegerType::MAX_INT_BITS)
1785 return error("Bitwidth for integer type out of range");
1786 ResultTy = IntegerType::get(Context, NumBits);
1789 case bitc::TYPE_CODE_POINTER: { // POINTER: [pointee type] or
1790 // [pointee type, address space]
1791 if (Record.size() < 1)
1792 return error("Invalid record");
1793 unsigned AddressSpace = 0;
1794 if (Record.size() == 2)
1795 AddressSpace = Record[1];
1796 ResultTy = getTypeByID(Record[0]);
1798 !PointerType::isValidElementType(ResultTy))
1799 return error("Invalid type");
1800 ResultTy = PointerType::get(ResultTy, AddressSpace);
1803 case bitc::TYPE_CODE_FUNCTION_OLD: {
1804 // FIXME: attrid is dead, remove it in LLVM 4.0
1805 // FUNCTION: [vararg, attrid, retty, paramty x N]
1806 if (Record.size() < 3)
1807 return error("Invalid record");
1808 SmallVector<Type*, 8> ArgTys;
1809 for (unsigned i = 3, e = Record.size(); i != e; ++i) {
1810 if (Type *T = getTypeByID(Record[i]))
1811 ArgTys.push_back(T);
1816 ResultTy = getTypeByID(Record[2]);
1817 if (!ResultTy || ArgTys.size() < Record.size()-3)
1818 return error("Invalid type");
1820 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
1823 case bitc::TYPE_CODE_FUNCTION: {
1824 // FUNCTION: [vararg, retty, paramty x N]
1825 if (Record.size() < 2)
1826 return error("Invalid record");
1827 SmallVector<Type*, 8> ArgTys;
1828 for (unsigned i = 2, e = Record.size(); i != e; ++i) {
1829 if (Type *T = getTypeByID(Record[i])) {
1830 if (!FunctionType::isValidArgumentType(T))
1831 return error("Invalid function argument type");
1832 ArgTys.push_back(T);
1838 ResultTy = getTypeByID(Record[1]);
1839 if (!ResultTy || ArgTys.size() < Record.size()-2)
1840 return error("Invalid type");
1842 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
1845 case bitc::TYPE_CODE_STRUCT_ANON: { // STRUCT: [ispacked, eltty x N]
1846 if (Record.size() < 1)
1847 return error("Invalid record");
1848 SmallVector<Type*, 8> EltTys;
1849 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
1850 if (Type *T = getTypeByID(Record[i]))
1851 EltTys.push_back(T);
1855 if (EltTys.size() != Record.size()-1)
1856 return error("Invalid type");
1857 ResultTy = StructType::get(Context, EltTys, Record[0]);
1860 case bitc::TYPE_CODE_STRUCT_NAME: // STRUCT_NAME: [strchr x N]
1861 if (convertToString(Record, 0, TypeName))
1862 return error("Invalid record");
1865 case bitc::TYPE_CODE_STRUCT_NAMED: { // STRUCT: [ispacked, eltty x N]
1866 if (Record.size() < 1)
1867 return error("Invalid record");
1869 if (NumRecords >= TypeList.size())
1870 return error("Invalid TYPE table");
1872 // Check to see if this was forward referenced, if so fill in the temp.
1873 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
1875 Res->setName(TypeName);
1876 TypeList[NumRecords] = nullptr;
1877 } else // Otherwise, create a new struct.
1878 Res = createIdentifiedStructType(Context, TypeName);
1881 SmallVector<Type*, 8> EltTys;
1882 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
1883 if (Type *T = getTypeByID(Record[i]))
1884 EltTys.push_back(T);
1888 if (EltTys.size() != Record.size()-1)
1889 return error("Invalid record");
1890 Res->setBody(EltTys, Record[0]);
1894 case bitc::TYPE_CODE_OPAQUE: { // OPAQUE: []
1895 if (Record.size() != 1)
1896 return error("Invalid record");
1898 if (NumRecords >= TypeList.size())
1899 return error("Invalid TYPE table");
1901 // Check to see if this was forward referenced, if so fill in the temp.
1902 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
1904 Res->setName(TypeName);
1905 TypeList[NumRecords] = nullptr;
1906 } else // Otherwise, create a new struct with no body.
1907 Res = createIdentifiedStructType(Context, TypeName);
1912 case bitc::TYPE_CODE_ARRAY: // ARRAY: [numelts, eltty]
1913 if (Record.size() < 2)
1914 return error("Invalid record");
1915 ResultTy = getTypeByID(Record[1]);
1916 if (!ResultTy || !ArrayType::isValidElementType(ResultTy))
1917 return error("Invalid type");
1918 ResultTy = ArrayType::get(ResultTy, Record[0]);
1920 case bitc::TYPE_CODE_VECTOR: // VECTOR: [numelts, eltty]
1921 if (Record.size() < 2)
1922 return error("Invalid record");
1924 return error("Invalid vector length");
1925 ResultTy = getTypeByID(Record[1]);
1926 if (!ResultTy || !StructType::isValidElementType(ResultTy))
1927 return error("Invalid type");
1928 ResultTy = VectorType::get(ResultTy, Record[0]);
1932 if (NumRecords >= TypeList.size())
1933 return error("Invalid TYPE table");
1934 if (TypeList[NumRecords])
1936 "Invalid TYPE table: Only named structs can be forward referenced");
1937 assert(ResultTy && "Didn't read a type?");
1938 TypeList[NumRecords++] = ResultTy;
1942 std::error_code BitcodeReader::parseOperandBundleTags() {
1943 if (Stream.EnterSubBlock(bitc::OPERAND_BUNDLE_TAGS_BLOCK_ID))
1944 return error("Invalid record");
1946 if (!BundleTags.empty())
1947 return error("Invalid multiple blocks");
1949 SmallVector<uint64_t, 64> Record;
1952 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1954 switch (Entry.Kind) {
1955 case BitstreamEntry::SubBlock: // Handled for us already.
1956 case BitstreamEntry::Error:
1957 return error("Malformed block");
1958 case BitstreamEntry::EndBlock:
1959 return std::error_code();
1960 case BitstreamEntry::Record:
1961 // The interesting case.
1965 // Tags are implicitly mapped to integers by their order.
1967 if (Stream.readRecord(Entry.ID, Record) != bitc::OPERAND_BUNDLE_TAG)
1968 return error("Invalid record");
1970 // OPERAND_BUNDLE_TAG: [strchr x N]
1971 BundleTags.emplace_back();
1972 if (convertToString(Record, 0, BundleTags.back()))
1973 return error("Invalid record");
1978 /// Associate a value with its name from the given index in the provided record.
1979 ErrorOr<Value *> BitcodeReader::recordValue(SmallVectorImpl<uint64_t> &Record,
1980 unsigned NameIndex, Triple &TT) {
1981 SmallString<128> ValueName;
1982 if (convertToString(Record, NameIndex, ValueName))
1983 return error("Invalid record");
1984 unsigned ValueID = Record[0];
1985 if (ValueID >= ValueList.size() || !ValueList[ValueID])
1986 return error("Invalid record");
1987 Value *V = ValueList[ValueID];
1989 StringRef NameStr(ValueName.data(), ValueName.size());
1990 if (NameStr.find_first_of(0) != StringRef::npos)
1991 return error("Invalid value name");
1992 V->setName(NameStr);
1993 auto *GO = dyn_cast<GlobalObject>(V);
1995 if (GO->getComdat() == reinterpret_cast<Comdat *>(1)) {
1996 if (TT.isOSBinFormatMachO())
1997 GO->setComdat(nullptr);
1999 GO->setComdat(TheModule->getOrInsertComdat(V->getName()));
2005 /// Helper to note and return the current location, and jump to the given
2007 static uint64_t jumpToValueSymbolTable(uint64_t Offset,
2008 BitstreamCursor &Stream) {
2009 // Save the current parsing location so we can jump back at the end
2011 uint64_t CurrentBit = Stream.GetCurrentBitNo();
2012 Stream.JumpToBit(Offset * 32);
2014 // Do some checking if we are in debug mode.
2015 BitstreamEntry Entry = Stream.advance();
2016 assert(Entry.Kind == BitstreamEntry::SubBlock);
2017 assert(Entry.ID == bitc::VALUE_SYMTAB_BLOCK_ID);
2019 // In NDEBUG mode ignore the output so we don't get an unused variable
2026 /// Parse the value symbol table at either the current parsing location or
2027 /// at the given bit offset if provided.
2028 std::error_code BitcodeReader::parseValueSymbolTable(uint64_t Offset) {
2029 uint64_t CurrentBit;
2030 // Pass in the Offset to distinguish between calling for the module-level
2031 // VST (where we want to jump to the VST offset) and the function-level
2032 // VST (where we don't).
2034 CurrentBit = jumpToValueSymbolTable(Offset, Stream);
2036 // Compute the delta between the bitcode indices in the VST (the word offset
2037 // to the word-aligned ENTER_SUBBLOCK for the function block, and that
2038 // expected by the lazy reader. The reader's EnterSubBlock expects to have
2039 // already read the ENTER_SUBBLOCK code (size getAbbrevIDWidth) and BlockID
2040 // (size BlockIDWidth). Note that we access the stream's AbbrevID width here
2041 // just before entering the VST subblock because: 1) the EnterSubBlock
2042 // changes the AbbrevID width; 2) the VST block is nested within the same
2043 // outer MODULE_BLOCK as the FUNCTION_BLOCKs and therefore have the same
2044 // AbbrevID width before calling EnterSubBlock; and 3) when we want to
2045 // jump to the FUNCTION_BLOCK using this offset later, we don't want
2046 // to rely on the stream's AbbrevID width being that of the MODULE_BLOCK.
2047 unsigned FuncBitcodeOffsetDelta =
2048 Stream.getAbbrevIDWidth() + bitc::BlockIDWidth;
2050 if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
2051 return error("Invalid record");
2053 SmallVector<uint64_t, 64> Record;
2055 Triple TT(TheModule->getTargetTriple());
2057 // Read all the records for this value table.
2058 SmallString<128> ValueName;
2061 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
2063 switch (Entry.Kind) {
2064 case BitstreamEntry::SubBlock: // Handled for us already.
2065 case BitstreamEntry::Error:
2066 return error("Malformed block");
2067 case BitstreamEntry::EndBlock:
2069 Stream.JumpToBit(CurrentBit);
2070 return std::error_code();
2071 case BitstreamEntry::Record:
2072 // The interesting case.
2078 switch (Stream.readRecord(Entry.ID, Record)) {
2079 default: // Default behavior: unknown type.
2081 case bitc::VST_CODE_ENTRY: { // VST_CODE_ENTRY: [valueid, namechar x N]
2082 ErrorOr<Value *> ValOrErr = recordValue(Record, 1, TT);
2083 if (std::error_code EC = ValOrErr.getError())
2088 case bitc::VST_CODE_FNENTRY: {
2089 // VST_CODE_FNENTRY: [valueid, offset, namechar x N]
2090 ErrorOr<Value *> ValOrErr = recordValue(Record, 2, TT);
2091 if (std::error_code EC = ValOrErr.getError())
2093 Value *V = ValOrErr.get();
2095 auto *GO = dyn_cast<GlobalObject>(V);
2097 // If this is an alias, need to get the actual Function object
2098 // it aliases, in order to set up the DeferredFunctionInfo entry below.
2099 auto *GA = dyn_cast<GlobalAlias>(V);
2101 GO = GA->getBaseObject();
2105 uint64_t FuncWordOffset = Record[1];
2106 Function *F = dyn_cast<Function>(GO);
2108 uint64_t FuncBitOffset = FuncWordOffset * 32;
2109 DeferredFunctionInfo[F] = FuncBitOffset + FuncBitcodeOffsetDelta;
2110 // Set the LastFunctionBlockBit to point to the last function block.
2111 // Later when parsing is resumed after function materialization,
2112 // we can simply skip that last function block.
2113 if (FuncBitOffset > LastFunctionBlockBit)
2114 LastFunctionBlockBit = FuncBitOffset;
2117 case bitc::VST_CODE_BBENTRY: {
2118 if (convertToString(Record, 1, ValueName))
2119 return error("Invalid record");
2120 BasicBlock *BB = getBasicBlock(Record[0]);
2122 return error("Invalid record");
2124 BB->setName(StringRef(ValueName.data(), ValueName.size()));
2132 /// Parse a single METADATA_KIND record, inserting result in MDKindMap.
2134 BitcodeReader::parseMetadataKindRecord(SmallVectorImpl<uint64_t> &Record) {
2135 if (Record.size() < 2)
2136 return error("Invalid record");
2138 unsigned Kind = Record[0];
2139 SmallString<8> Name(Record.begin() + 1, Record.end());
2141 unsigned NewKind = TheModule->getMDKindID(Name.str());
2142 if (!MDKindMap.insert(std::make_pair(Kind, NewKind)).second)
2143 return error("Conflicting METADATA_KIND records");
2144 return std::error_code();
2147 static int64_t unrotateSign(uint64_t U) { return U & 1 ? ~(U >> 1) : U >> 1; }
2149 std::error_code BitcodeReader::parseMetadataStrings(ArrayRef<uint64_t> Record,
2151 unsigned &NextMetadataNo) {
2152 // All the MDStrings in the block are emitted together in a single
2153 // record. The strings are concatenated and stored in a blob along with
2155 if (Record.size() != 2)
2156 return error("Invalid record: metadata strings layout");
2158 unsigned NumStrings = Record[0];
2159 unsigned StringsOffset = Record[1];
2161 return error("Invalid record: metadata strings with no strings");
2162 if (StringsOffset > Blob.size())
2163 return error("Invalid record: metadata strings corrupt offset");
2165 StringRef Lengths = Blob.slice(0, StringsOffset);
2166 SimpleBitstreamCursor R(*StreamFile);
2167 R.jumpToPointer(Lengths.begin());
2169 // Ensure that Blob doesn't get invalidated, even if this is reading from
2170 // a StreamingMemoryObject with corrupt data.
2171 R.setArtificialByteLimit(R.getCurrentByteNo() + StringsOffset);
2173 StringRef Strings = Blob.drop_front(StringsOffset);
2175 if (R.AtEndOfStream())
2176 return error("Invalid record: metadata strings bad length");
2178 unsigned Size = R.ReadVBR(6);
2179 if (Strings.size() < Size)
2180 return error("Invalid record: metadata strings truncated chars");
2182 MetadataList.assignValue(MDString::get(Context, Strings.slice(0, Size)),
2184 Strings = Strings.drop_front(Size);
2185 } while (--NumStrings);
2187 return std::error_code();
2192 class PlaceholderQueue {
2193 // Placeholders would thrash around when moved, so store in a std::deque
2194 // instead of some sort of vector.
2195 std::deque<DistinctMDOperandPlaceholder> PHs;
2198 DistinctMDOperandPlaceholder &getPlaceholderOp(unsigned ID);
2199 void flush(BitcodeReaderMetadataList &MetadataList);
2202 } // end anonymous namespace
2204 DistinctMDOperandPlaceholder &PlaceholderQueue::getPlaceholderOp(unsigned ID) {
2205 PHs.emplace_back(ID);
2209 void PlaceholderQueue::flush(BitcodeReaderMetadataList &MetadataList) {
2210 while (!PHs.empty()) {
2211 PHs.front().replaceUseWith(
2212 MetadataList.getMetadataFwdRef(PHs.front().getID()));
2217 /// Parse a METADATA_BLOCK. If ModuleLevel is true then we are parsing
2218 /// module level metadata.
2219 std::error_code BitcodeReader::parseMetadata(bool ModuleLevel) {
2220 assert((ModuleLevel || DeferredMetadataInfo.empty()) &&
2221 "Must read all module-level metadata before function-level");
2223 IsMetadataMaterialized = true;
2224 unsigned NextMetadataNo = MetadataList.size();
2226 if (!ModuleLevel && MetadataList.hasFwdRefs())
2227 return error("Invalid metadata: fwd refs into function blocks");
2229 if (Stream.EnterSubBlock(bitc::METADATA_BLOCK_ID))
2230 return error("Invalid record");
2232 std::vector<std::pair<DICompileUnit *, Metadata *>> CUSubprograms;
2233 SmallVector<uint64_t, 64> Record;
2235 PlaceholderQueue Placeholders;
2237 auto getMD = [&](unsigned ID) -> Metadata * {
2239 return MetadataList.getMetadataFwdRef(ID);
2240 if (auto *MD = MetadataList.getMetadataIfResolved(ID))
2242 return &Placeholders.getPlaceholderOp(ID);
2244 auto getMDOrNull = [&](unsigned ID) -> Metadata * {
2246 return getMD(ID - 1);
2249 auto getMDOrNullWithoutPlaceholders = [&](unsigned ID) -> Metadata * {
2251 return MetadataList.getMetadataFwdRef(ID - 1);
2254 auto getMDString = [&](unsigned ID) -> MDString *{
2255 // This requires that the ID is not really a forward reference. In
2256 // particular, the MDString must already have been resolved.
2257 return cast_or_null<MDString>(getMDOrNull(ID));
2260 // Support for old type refs.
2261 auto getDITypeRefOrNull = [&](unsigned ID) {
2262 return MetadataList.upgradeTypeRef(getMDOrNull(ID));
2265 #define GET_OR_DISTINCT(CLASS, ARGS) \
2266 (IsDistinct ? CLASS::getDistinct ARGS : CLASS::get ARGS)
2268 // Read all the records.
2270 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
2272 switch (Entry.Kind) {
2273 case BitstreamEntry::SubBlock: // Handled for us already.
2274 case BitstreamEntry::Error:
2275 return error("Malformed block");
2276 case BitstreamEntry::EndBlock:
2277 // Upgrade old-style CU <-> SP pointers to point from SP to CU.
2278 for (auto CU_SP : CUSubprograms)
2279 if (auto *SPs = dyn_cast_or_null<MDTuple>(CU_SP.second))
2280 for (auto &Op : SPs->operands())
2281 if (auto *SP = dyn_cast_or_null<MDNode>(Op))
2282 SP->replaceOperandWith(7, CU_SP.first);
2284 MetadataList.tryToResolveCycles();
2285 Placeholders.flush(MetadataList);
2286 return std::error_code();
2287 case BitstreamEntry::Record:
2288 // The interesting case.
2295 unsigned Code = Stream.readRecord(Entry.ID, Record, &Blob);
2298 default: // Default behavior: ignore.
2300 case bitc::METADATA_NAME: {
2301 // Read name of the named metadata.
2302 SmallString<8> Name(Record.begin(), Record.end());
2304 Code = Stream.ReadCode();
2306 unsigned NextBitCode = Stream.readRecord(Code, Record);
2307 if (NextBitCode != bitc::METADATA_NAMED_NODE)
2308 return error("METADATA_NAME not followed by METADATA_NAMED_NODE");
2310 // Read named metadata elements.
2311 unsigned Size = Record.size();
2312 NamedMDNode *NMD = TheModule->getOrInsertNamedMetadata(Name);
2313 for (unsigned i = 0; i != Size; ++i) {
2314 MDNode *MD = MetadataList.getMDNodeFwdRefOrNull(Record[i]);
2316 return error("Invalid record");
2317 NMD->addOperand(MD);
2321 case bitc::METADATA_OLD_FN_NODE: {
2322 // FIXME: Remove in 4.0.
2323 // This is a LocalAsMetadata record, the only type of function-local
2325 if (Record.size() % 2 == 1)
2326 return error("Invalid record");
2328 // If this isn't a LocalAsMetadata record, we're dropping it. This used
2329 // to be legal, but there's no upgrade path.
2330 auto dropRecord = [&] {
2331 MetadataList.assignValue(MDNode::get(Context, None), NextMetadataNo++);
2333 if (Record.size() != 2) {
2338 Type *Ty = getTypeByID(Record[0]);
2339 if (Ty->isMetadataTy() || Ty->isVoidTy()) {
2344 MetadataList.assignValue(
2345 LocalAsMetadata::get(ValueList.getValueFwdRef(Record[1], Ty)),
2349 case bitc::METADATA_OLD_NODE: {
2350 // FIXME: Remove in 4.0.
2351 if (Record.size() % 2 == 1)
2352 return error("Invalid record");
2354 unsigned Size = Record.size();
2355 SmallVector<Metadata *, 8> Elts;
2356 for (unsigned i = 0; i != Size; i += 2) {
2357 Type *Ty = getTypeByID(Record[i]);
2359 return error("Invalid record");
2360 if (Ty->isMetadataTy())
2361 Elts.push_back(getMD(Record[i + 1]));
2362 else if (!Ty->isVoidTy()) {
2364 ValueAsMetadata::get(ValueList.getValueFwdRef(Record[i + 1], Ty));
2365 assert(isa<ConstantAsMetadata>(MD) &&
2366 "Expected non-function-local metadata");
2369 Elts.push_back(nullptr);
2371 MetadataList.assignValue(MDNode::get(Context, Elts), NextMetadataNo++);
2374 case bitc::METADATA_VALUE: {
2375 if (Record.size() != 2)
2376 return error("Invalid record");
2378 Type *Ty = getTypeByID(Record[0]);
2379 if (Ty->isMetadataTy() || Ty->isVoidTy())
2380 return error("Invalid record");
2382 MetadataList.assignValue(
2383 ValueAsMetadata::get(ValueList.getValueFwdRef(Record[1], Ty)),
2387 case bitc::METADATA_DISTINCT_NODE:
2390 case bitc::METADATA_NODE: {
2391 SmallVector<Metadata *, 8> Elts;
2392 Elts.reserve(Record.size());
2393 for (unsigned ID : Record)
2394 Elts.push_back(getMDOrNull(ID));
2395 MetadataList.assignValue(IsDistinct ? MDNode::getDistinct(Context, Elts)
2396 : MDNode::get(Context, Elts),
2400 case bitc::METADATA_LOCATION: {
2401 if (Record.size() != 5)
2402 return error("Invalid record");
2404 IsDistinct = Record[0];
2405 unsigned Line = Record[1];
2406 unsigned Column = Record[2];
2407 Metadata *Scope = getMD(Record[3]);
2408 Metadata *InlinedAt = getMDOrNull(Record[4]);
2409 MetadataList.assignValue(
2410 GET_OR_DISTINCT(DILocation,
2411 (Context, Line, Column, Scope, InlinedAt)),
2415 case bitc::METADATA_GENERIC_DEBUG: {
2416 if (Record.size() < 4)
2417 return error("Invalid record");
2419 IsDistinct = Record[0];
2420 unsigned Tag = Record[1];
2421 unsigned Version = Record[2];
2423 if (Tag >= 1u << 16 || Version != 0)
2424 return error("Invalid record");
2426 auto *Header = getMDString(Record[3]);
2427 SmallVector<Metadata *, 8> DwarfOps;
2428 for (unsigned I = 4, E = Record.size(); I != E; ++I)
2429 DwarfOps.push_back(getMDOrNull(Record[I]));
2430 MetadataList.assignValue(
2431 GET_OR_DISTINCT(GenericDINode, (Context, Tag, Header, DwarfOps)),
2435 case bitc::METADATA_SUBRANGE: {
2436 if (Record.size() != 3)
2437 return error("Invalid record");
2439 IsDistinct = Record[0];
2440 MetadataList.assignValue(
2441 GET_OR_DISTINCT(DISubrange,
2442 (Context, Record[1], unrotateSign(Record[2]))),
2446 case bitc::METADATA_ENUMERATOR: {
2447 if (Record.size() != 3)
2448 return error("Invalid record");
2450 IsDistinct = Record[0];
2451 MetadataList.assignValue(
2452 GET_OR_DISTINCT(DIEnumerator, (Context, unrotateSign(Record[1]),
2453 getMDString(Record[2]))),
2457 case bitc::METADATA_BASIC_TYPE: {
2458 if (Record.size() != 6)
2459 return error("Invalid record");
2461 IsDistinct = Record[0];
2462 MetadataList.assignValue(
2463 GET_OR_DISTINCT(DIBasicType,
2464 (Context, Record[1], getMDString(Record[2]),
2465 Record[3], Record[4], Record[5])),
2469 case bitc::METADATA_DERIVED_TYPE: {
2470 if (Record.size() != 12)
2471 return error("Invalid record");
2473 IsDistinct = Record[0];
2474 DINode::DIFlags Flags = static_cast<DINode::DIFlags>(Record[10]);
2475 MetadataList.assignValue(
2476 GET_OR_DISTINCT(DIDerivedType,
2477 (Context, Record[1], getMDString(Record[2]),
2478 getMDOrNull(Record[3]), Record[4],
2479 getDITypeRefOrNull(Record[5]),
2480 getDITypeRefOrNull(Record[6]), Record[7], Record[8],
2481 Record[9], Flags, getDITypeRefOrNull(Record[11]))),
2485 case bitc::METADATA_COMPOSITE_TYPE: {
2486 if (Record.size() != 16)
2487 return error("Invalid record");
2489 // If we have a UUID and this is not a forward declaration, lookup the
2491 IsDistinct = Record[0] & 0x1;
2492 bool IsNotUsedInTypeRef = Record[0] >= 2;
2493 unsigned Tag = Record[1];
2494 MDString *Name = getMDString(Record[2]);
2495 Metadata *File = getMDOrNull(Record[3]);
2496 unsigned Line = Record[4];
2497 Metadata *Scope = getDITypeRefOrNull(Record[5]);
2498 Metadata *BaseType = getDITypeRefOrNull(Record[6]);
2499 uint64_t SizeInBits = Record[7];
2500 uint64_t AlignInBits = Record[8];
2501 uint64_t OffsetInBits = Record[9];
2502 DINode::DIFlags Flags = static_cast<DINode::DIFlags>(Record[10]);
2503 Metadata *Elements = getMDOrNull(Record[11]);
2504 unsigned RuntimeLang = Record[12];
2505 Metadata *VTableHolder = getDITypeRefOrNull(Record[13]);
2506 Metadata *TemplateParams = getMDOrNull(Record[14]);
2507 auto *Identifier = getMDString(Record[15]);
2508 DICompositeType *CT = nullptr;
2510 CT = DICompositeType::buildODRType(
2511 Context, *Identifier, Tag, Name, File, Line, Scope, BaseType,
2512 SizeInBits, AlignInBits, OffsetInBits, Flags, Elements, RuntimeLang,
2513 VTableHolder, TemplateParams);
2515 // Create a node if we didn't get a lazy ODR type.
2517 CT = GET_OR_DISTINCT(DICompositeType,
2518 (Context, Tag, Name, File, Line, Scope, BaseType,
2519 SizeInBits, AlignInBits, OffsetInBits, Flags,
2520 Elements, RuntimeLang, VTableHolder,
2521 TemplateParams, Identifier));
2522 if (!IsNotUsedInTypeRef && Identifier)
2523 MetadataList.addTypeRef(*Identifier, *cast<DICompositeType>(CT));
2525 MetadataList.assignValue(CT, NextMetadataNo++);
2528 case bitc::METADATA_SUBROUTINE_TYPE: {
2529 if (Record.size() < 3 || Record.size() > 4)
2530 return error("Invalid record");
2531 bool IsOldTypeRefArray = Record[0] < 2;
2532 unsigned CC = (Record.size() > 3) ? Record[3] : 0;
2534 IsDistinct = Record[0] & 0x1;
2535 DINode::DIFlags Flags = static_cast<DINode::DIFlags>(Record[1]);
2536 Metadata *Types = getMDOrNull(Record[2]);
2537 if (LLVM_UNLIKELY(IsOldTypeRefArray))
2538 Types = MetadataList.upgradeTypeRefArray(Types);
2540 MetadataList.assignValue(
2541 GET_OR_DISTINCT(DISubroutineType, (Context, Flags, CC, Types)),
2546 case bitc::METADATA_MODULE: {
2547 if (Record.size() != 6)
2548 return error("Invalid record");
2550 IsDistinct = Record[0];
2551 MetadataList.assignValue(
2552 GET_OR_DISTINCT(DIModule,
2553 (Context, getMDOrNull(Record[1]),
2554 getMDString(Record[2]), getMDString(Record[3]),
2555 getMDString(Record[4]), getMDString(Record[5]))),
2560 case bitc::METADATA_FILE: {
2561 if (Record.size() != 3)
2562 return error("Invalid record");
2564 IsDistinct = Record[0];
2565 MetadataList.assignValue(
2566 GET_OR_DISTINCT(DIFile, (Context, getMDString(Record[1]),
2567 getMDString(Record[2]))),
2571 case bitc::METADATA_COMPILE_UNIT: {
2572 if (Record.size() < 14 || Record.size() > 17)
2573 return error("Invalid record");
2575 // Ignore Record[0], which indicates whether this compile unit is
2576 // distinct. It's always distinct.
2578 auto *CU = DICompileUnit::getDistinct(
2579 Context, Record[1], getMDOrNull(Record[2]), getMDString(Record[3]),
2580 Record[4], getMDString(Record[5]), Record[6], getMDString(Record[7]),
2581 Record[8], getMDOrNull(Record[9]), getMDOrNull(Record[10]),
2582 getMDOrNull(Record[12]), getMDOrNull(Record[13]),
2583 Record.size() <= 15 ? nullptr : getMDOrNull(Record[15]),
2584 Record.size() <= 14 ? 0 : Record[14],
2585 Record.size() <= 16 ? true : Record[16]);
2587 MetadataList.assignValue(CU, NextMetadataNo++);
2589 // Move the Upgrade the list of subprograms.
2590 if (Metadata *SPs = getMDOrNullWithoutPlaceholders(Record[11]))
2591 CUSubprograms.push_back({CU, SPs});
2594 case bitc::METADATA_SUBPROGRAM: {
2595 if (Record.size() < 18 || Record.size() > 20)
2596 return error("Invalid record");
2599 (Record[0] & 1) || Record[8]; // All definitions should be distinct.
2600 // Version 1 has a Function as Record[15].
2601 // Version 2 has removed Record[15].
2602 // Version 3 has the Unit as Record[15].
2603 // Version 4 added thisAdjustment.
2604 bool HasUnit = Record[0] >= 2;
2605 if (HasUnit && Record.size() < 19)
2606 return error("Invalid record");
2607 Metadata *CUorFn = getMDOrNull(Record[15]);
2608 unsigned Offset = Record.size() >= 19 ? 1 : 0;
2609 bool HasFn = Offset && !HasUnit;
2610 bool HasThisAdj = Record.size() >= 20;
2611 DISubprogram *SP = GET_OR_DISTINCT(
2612 DISubprogram, (Context,
2613 getDITypeRefOrNull(Record[1]), // scope
2614 getMDString(Record[2]), // name
2615 getMDString(Record[3]), // linkageName
2616 getMDOrNull(Record[4]), // file
2618 getMDOrNull(Record[6]), // type
2619 Record[7], // isLocal
2620 Record[8], // isDefinition
2621 Record[9], // scopeLine
2622 getDITypeRefOrNull(Record[10]), // containingType
2623 Record[11], // virtuality
2624 Record[12], // virtualIndex
2625 HasThisAdj ? Record[19] : 0, // thisAdjustment
2626 static_cast<DINode::DIFlags>(Record[13] // flags
2628 Record[14], // isOptimized
2629 HasUnit ? CUorFn : nullptr, // unit
2630 getMDOrNull(Record[15 + Offset]), // templateParams
2631 getMDOrNull(Record[16 + Offset]), // declaration
2632 getMDOrNull(Record[17 + Offset]) // variables
2634 MetadataList.assignValue(SP, NextMetadataNo++);
2636 // Upgrade sp->function mapping to function->sp mapping.
2638 if (auto *CMD = dyn_cast_or_null<ConstantAsMetadata>(CUorFn))
2639 if (auto *F = dyn_cast<Function>(CMD->getValue())) {
2640 if (F->isMaterializable())
2641 // Defer until materialized; unmaterialized functions may not have
2643 FunctionsWithSPs[F] = SP;
2644 else if (!F->empty())
2645 F->setSubprogram(SP);
2650 case bitc::METADATA_LEXICAL_BLOCK: {
2651 if (Record.size() != 5)
2652 return error("Invalid record");
2654 IsDistinct = Record[0];
2655 MetadataList.assignValue(
2656 GET_OR_DISTINCT(DILexicalBlock,
2657 (Context, getMDOrNull(Record[1]),
2658 getMDOrNull(Record[2]), Record[3], Record[4])),
2662 case bitc::METADATA_LEXICAL_BLOCK_FILE: {
2663 if (Record.size() != 4)
2664 return error("Invalid record");
2666 IsDistinct = Record[0];
2667 MetadataList.assignValue(
2668 GET_OR_DISTINCT(DILexicalBlockFile,
2669 (Context, getMDOrNull(Record[1]),
2670 getMDOrNull(Record[2]), Record[3])),
2674 case bitc::METADATA_NAMESPACE: {
2675 if (Record.size() != 5)
2676 return error("Invalid record");
2678 IsDistinct = Record[0];
2679 MetadataList.assignValue(
2680 GET_OR_DISTINCT(DINamespace, (Context, getMDOrNull(Record[1]),
2681 getMDOrNull(Record[2]),
2682 getMDString(Record[3]), Record[4])),
2686 case bitc::METADATA_MACRO: {
2687 if (Record.size() != 5)
2688 return error("Invalid record");
2690 IsDistinct = Record[0];
2691 MetadataList.assignValue(
2692 GET_OR_DISTINCT(DIMacro,
2693 (Context, Record[1], Record[2],
2694 getMDString(Record[3]), getMDString(Record[4]))),
2698 case bitc::METADATA_MACRO_FILE: {
2699 if (Record.size() != 5)
2700 return error("Invalid record");
2702 IsDistinct = Record[0];
2703 MetadataList.assignValue(
2704 GET_OR_DISTINCT(DIMacroFile,
2705 (Context, Record[1], Record[2],
2706 getMDOrNull(Record[3]), getMDOrNull(Record[4]))),
2710 case bitc::METADATA_TEMPLATE_TYPE: {
2711 if (Record.size() != 3)
2712 return error("Invalid record");
2714 IsDistinct = Record[0];
2715 MetadataList.assignValue(GET_OR_DISTINCT(DITemplateTypeParameter,
2716 (Context, getMDString(Record[1]),
2717 getDITypeRefOrNull(Record[2]))),
2721 case bitc::METADATA_TEMPLATE_VALUE: {
2722 if (Record.size() != 5)
2723 return error("Invalid record");
2725 IsDistinct = Record[0];
2726 MetadataList.assignValue(
2727 GET_OR_DISTINCT(DITemplateValueParameter,
2728 (Context, Record[1], getMDString(Record[2]),
2729 getDITypeRefOrNull(Record[3]),
2730 getMDOrNull(Record[4]))),
2734 case bitc::METADATA_GLOBAL_VAR: {
2735 if (Record.size() != 11)
2736 return error("Invalid record");
2738 IsDistinct = Record[0];
2740 // Upgrade old metadata, which stored a global variable reference or a
2741 // ConstantInt here.
2742 Metadata *Expr = getMDOrNull(Record[9]);
2743 GlobalVariable *Attach = nullptr;
2744 if (auto *CMD = dyn_cast_or_null<ConstantAsMetadata>(Expr)) {
2745 if (auto *GV = dyn_cast<GlobalVariable>(CMD->getValue())) {
2748 } else if (auto *CI = dyn_cast<ConstantInt>(CMD->getValue())) {
2749 Expr = DIExpression::get(Context,
2750 {dwarf::DW_OP_constu, CI->getZExtValue(),
2751 dwarf::DW_OP_stack_value});
2757 DIGlobalVariable *DGV = GET_OR_DISTINCT(
2759 (Context, getMDOrNull(Record[1]), getMDString(Record[2]),
2760 getMDString(Record[3]), getMDOrNull(Record[4]), Record[5],
2761 getDITypeRefOrNull(Record[6]), Record[7], Record[8], Expr,
2762 getMDOrNull(Record[10])));
2763 MetadataList.assignValue(DGV, NextMetadataNo++);
2766 Attach->addDebugInfo(DGV);
2770 case bitc::METADATA_LOCAL_VAR: {
2771 // 10th field is for the obseleted 'inlinedAt:' field.
2772 if (Record.size() < 8 || Record.size() > 10)
2773 return error("Invalid record");
2775 // 2nd field used to be an artificial tag, either DW_TAG_auto_variable or
2776 // DW_TAG_arg_variable.
2777 IsDistinct = Record[0];
2778 bool HasTag = Record.size() > 8;
2779 DINode::DIFlags Flags = static_cast<DINode::DIFlags>(Record[7 + HasTag]);
2780 MetadataList.assignValue(
2781 GET_OR_DISTINCT(DILocalVariable,
2782 (Context, getMDOrNull(Record[1 + HasTag]),
2783 getMDString(Record[2 + HasTag]),
2784 getMDOrNull(Record[3 + HasTag]), Record[4 + HasTag],
2785 getDITypeRefOrNull(Record[5 + HasTag]),
2786 Record[6 + HasTag], Flags)),
2790 case bitc::METADATA_EXPRESSION: {
2791 if (Record.size() < 1)
2792 return error("Invalid record");
2794 IsDistinct = Record[0];
2795 MetadataList.assignValue(
2796 GET_OR_DISTINCT(DIExpression,
2797 (Context, makeArrayRef(Record).slice(1))),
2801 case bitc::METADATA_OBJC_PROPERTY: {
2802 if (Record.size() != 8)
2803 return error("Invalid record");
2805 IsDistinct = Record[0];
2806 MetadataList.assignValue(
2807 GET_OR_DISTINCT(DIObjCProperty,
2808 (Context, getMDString(Record[1]),
2809 getMDOrNull(Record[2]), Record[3],
2810 getMDString(Record[4]), getMDString(Record[5]),
2811 Record[6], getDITypeRefOrNull(Record[7]))),
2815 case bitc::METADATA_IMPORTED_ENTITY: {
2816 if (Record.size() != 6)
2817 return error("Invalid record");
2819 IsDistinct = Record[0];
2820 MetadataList.assignValue(
2821 GET_OR_DISTINCT(DIImportedEntity,
2822 (Context, Record[1], getMDOrNull(Record[2]),
2823 getDITypeRefOrNull(Record[3]), Record[4],
2824 getMDString(Record[5]))),
2828 case bitc::METADATA_STRING_OLD: {
2829 std::string String(Record.begin(), Record.end());
2831 // Test for upgrading !llvm.loop.
2832 HasSeenOldLoopTags |= mayBeOldLoopAttachmentTag(String);
2834 Metadata *MD = MDString::get(Context, String);
2835 MetadataList.assignValue(MD, NextMetadataNo++);
2838 case bitc::METADATA_STRINGS:
2839 if (std::error_code EC =
2840 parseMetadataStrings(Record, Blob, NextMetadataNo))
2843 case bitc::METADATA_GLOBAL_DECL_ATTACHMENT: {
2844 if (Record.size() % 2 == 0)
2845 return error("Invalid record");
2846 unsigned ValueID = Record[0];
2847 if (ValueID >= ValueList.size())
2848 return error("Invalid record");
2849 if (auto *GO = dyn_cast<GlobalObject>(ValueList[ValueID]))
2850 parseGlobalObjectAttachment(*GO, ArrayRef<uint64_t>(Record).slice(1));
2853 case bitc::METADATA_KIND: {
2854 // Support older bitcode files that had METADATA_KIND records in a
2855 // block with METADATA_BLOCK_ID.
2856 if (std::error_code EC = parseMetadataKindRecord(Record))
2863 #undef GET_OR_DISTINCT
2866 /// Parse the metadata kinds out of the METADATA_KIND_BLOCK.
2867 std::error_code BitcodeReader::parseMetadataKinds() {
2868 if (Stream.EnterSubBlock(bitc::METADATA_KIND_BLOCK_ID))
2869 return error("Invalid record");
2871 SmallVector<uint64_t, 64> Record;
2873 // Read all the records.
2875 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
2877 switch (Entry.Kind) {
2878 case BitstreamEntry::SubBlock: // Handled for us already.
2879 case BitstreamEntry::Error:
2880 return error("Malformed block");
2881 case BitstreamEntry::EndBlock:
2882 return std::error_code();
2883 case BitstreamEntry::Record:
2884 // The interesting case.
2890 unsigned Code = Stream.readRecord(Entry.ID, Record);
2892 default: // Default behavior: ignore.
2894 case bitc::METADATA_KIND: {
2895 if (std::error_code EC = parseMetadataKindRecord(Record))
2903 /// Decode a signed value stored with the sign bit in the LSB for dense VBR
2905 uint64_t BitcodeReader::decodeSignRotatedValue(uint64_t V) {
2910 // There is no such thing as -0 with integers. "-0" really means MININT.
2914 /// Resolve all of the initializers for global values and aliases that we can.
2915 std::error_code BitcodeReader::resolveGlobalAndIndirectSymbolInits() {
2916 std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInitWorklist;
2917 std::vector<std::pair<GlobalIndirectSymbol*, unsigned> >
2918 IndirectSymbolInitWorklist;
2919 std::vector<std::pair<Function*, unsigned> > FunctionPrefixWorklist;
2920 std::vector<std::pair<Function*, unsigned> > FunctionPrologueWorklist;
2921 std::vector<std::pair<Function*, unsigned> > FunctionPersonalityFnWorklist;
2923 GlobalInitWorklist.swap(GlobalInits);
2924 IndirectSymbolInitWorklist.swap(IndirectSymbolInits);
2925 FunctionPrefixWorklist.swap(FunctionPrefixes);
2926 FunctionPrologueWorklist.swap(FunctionPrologues);
2927 FunctionPersonalityFnWorklist.swap(FunctionPersonalityFns);
2929 while (!GlobalInitWorklist.empty()) {
2930 unsigned ValID = GlobalInitWorklist.back().second;
2931 if (ValID >= ValueList.size()) {
2932 // Not ready to resolve this yet, it requires something later in the file.
2933 GlobalInits.push_back(GlobalInitWorklist.back());
2935 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
2936 GlobalInitWorklist.back().first->setInitializer(C);
2938 return error("Expected a constant");
2940 GlobalInitWorklist.pop_back();
2943 while (!IndirectSymbolInitWorklist.empty()) {
2944 unsigned ValID = IndirectSymbolInitWorklist.back().second;
2945 if (ValID >= ValueList.size()) {
2946 IndirectSymbolInits.push_back(IndirectSymbolInitWorklist.back());
2948 Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]);
2950 return error("Expected a constant");
2951 GlobalIndirectSymbol *GIS = IndirectSymbolInitWorklist.back().first;
2952 if (isa<GlobalAlias>(GIS) && C->getType() != GIS->getType())
2953 return error("Alias and aliasee types don't match");
2954 GIS->setIndirectSymbol(C);
2956 IndirectSymbolInitWorklist.pop_back();
2959 while (!FunctionPrefixWorklist.empty()) {
2960 unsigned ValID = FunctionPrefixWorklist.back().second;
2961 if (ValID >= ValueList.size()) {
2962 FunctionPrefixes.push_back(FunctionPrefixWorklist.back());
2964 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
2965 FunctionPrefixWorklist.back().first->setPrefixData(C);
2967 return error("Expected a constant");
2969 FunctionPrefixWorklist.pop_back();
2972 while (!FunctionPrologueWorklist.empty()) {
2973 unsigned ValID = FunctionPrologueWorklist.back().second;
2974 if (ValID >= ValueList.size()) {
2975 FunctionPrologues.push_back(FunctionPrologueWorklist.back());
2977 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
2978 FunctionPrologueWorklist.back().first->setPrologueData(C);
2980 return error("Expected a constant");
2982 FunctionPrologueWorklist.pop_back();
2985 while (!FunctionPersonalityFnWorklist.empty()) {
2986 unsigned ValID = FunctionPersonalityFnWorklist.back().second;
2987 if (ValID >= ValueList.size()) {
2988 FunctionPersonalityFns.push_back(FunctionPersonalityFnWorklist.back());
2990 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
2991 FunctionPersonalityFnWorklist.back().first->setPersonalityFn(C);
2993 return error("Expected a constant");
2995 FunctionPersonalityFnWorklist.pop_back();
2998 return std::error_code();
3001 static APInt readWideAPInt(ArrayRef<uint64_t> Vals, unsigned TypeBits) {
3002 SmallVector<uint64_t, 8> Words(Vals.size());
3003 transform(Vals, Words.begin(),
3004 BitcodeReader::decodeSignRotatedValue);
3006 return APInt(TypeBits, Words);
3009 std::error_code BitcodeReader::parseConstants() {
3010 if (Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID))
3011 return error("Invalid record");
3013 SmallVector<uint64_t, 64> Record;
3015 // Read all the records for this value table.
3016 Type *CurTy = Type::getInt32Ty(Context);
3017 unsigned NextCstNo = ValueList.size();
3020 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
3022 switch (Entry.Kind) {
3023 case BitstreamEntry::SubBlock: // Handled for us already.
3024 case BitstreamEntry::Error:
3025 return error("Malformed block");
3026 case BitstreamEntry::EndBlock:
3027 if (NextCstNo != ValueList.size())
3028 return error("Invalid constant reference");
3030 // Once all the constants have been read, go through and resolve forward
3032 ValueList.resolveConstantForwardRefs();
3033 return std::error_code();
3034 case BitstreamEntry::Record:
3035 // The interesting case.
3041 Type *VoidType = Type::getVoidTy(Context);
3043 unsigned BitCode = Stream.readRecord(Entry.ID, Record);
3045 default: // Default behavior: unknown constant
3046 case bitc::CST_CODE_UNDEF: // UNDEF
3047 V = UndefValue::get(CurTy);
3049 case bitc::CST_CODE_SETTYPE: // SETTYPE: [typeid]
3051 return error("Invalid record");
3052 if (Record[0] >= TypeList.size() || !TypeList[Record[0]])
3053 return error("Invalid record");
3054 if (TypeList[Record[0]] == VoidType)
3055 return error("Invalid constant type");
3056 CurTy = TypeList[Record[0]];
3057 continue; // Skip the ValueList manipulation.
3058 case bitc::CST_CODE_NULL: // NULL
3059 V = Constant::getNullValue(CurTy);
3061 case bitc::CST_CODE_INTEGER: // INTEGER: [intval]
3062 if (!CurTy->isIntegerTy() || Record.empty())
3063 return error("Invalid record");
3064 V = ConstantInt::get(CurTy, decodeSignRotatedValue(Record[0]));
3066 case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval]
3067 if (!CurTy->isIntegerTy() || Record.empty())
3068 return error("Invalid record");
3071 readWideAPInt(Record, cast<IntegerType>(CurTy)->getBitWidth());
3072 V = ConstantInt::get(Context, VInt);
3076 case bitc::CST_CODE_FLOAT: { // FLOAT: [fpval]
3078 return error("Invalid record");
3079 if (CurTy->isHalfTy())
3080 V = ConstantFP::get(Context, APFloat(APFloat::IEEEhalf,
3081 APInt(16, (uint16_t)Record[0])));
3082 else if (CurTy->isFloatTy())
3083 V = ConstantFP::get(Context, APFloat(APFloat::IEEEsingle,
3084 APInt(32, (uint32_t)Record[0])));
3085 else if (CurTy->isDoubleTy())
3086 V = ConstantFP::get(Context, APFloat(APFloat::IEEEdouble,
3087 APInt(64, Record[0])));
3088 else if (CurTy->isX86_FP80Ty()) {
3089 // Bits are not stored the same way as a normal i80 APInt, compensate.
3090 uint64_t Rearrange[2];
3091 Rearrange[0] = (Record[1] & 0xffffLL) | (Record[0] << 16);
3092 Rearrange[1] = Record[0] >> 48;
3093 V = ConstantFP::get(Context, APFloat(APFloat::x87DoubleExtended,
3094 APInt(80, Rearrange)));
3095 } else if (CurTy->isFP128Ty())
3096 V = ConstantFP::get(Context, APFloat(APFloat::IEEEquad,
3097 APInt(128, Record)));
3098 else if (CurTy->isPPC_FP128Ty())
3099 V = ConstantFP::get(Context, APFloat(APFloat::PPCDoubleDouble,
3100 APInt(128, Record)));
3102 V = UndefValue::get(CurTy);
3106 case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number]
3108 return error("Invalid record");
3110 unsigned Size = Record.size();
3111 SmallVector<Constant*, 16> Elts;
3113 if (StructType *STy = dyn_cast<StructType>(CurTy)) {
3114 for (unsigned i = 0; i != Size; ++i)
3115 Elts.push_back(ValueList.getConstantFwdRef(Record[i],
3116 STy->getElementType(i)));
3117 V = ConstantStruct::get(STy, Elts);
3118 } else if (ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) {
3119 Type *EltTy = ATy->getElementType();
3120 for (unsigned i = 0; i != Size; ++i)
3121 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
3122 V = ConstantArray::get(ATy, Elts);
3123 } else if (VectorType *VTy = dyn_cast<VectorType>(CurTy)) {
3124 Type *EltTy = VTy->getElementType();
3125 for (unsigned i = 0; i != Size; ++i)
3126 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
3127 V = ConstantVector::get(Elts);
3129 V = UndefValue::get(CurTy);
3133 case bitc::CST_CODE_STRING: // STRING: [values]
3134 case bitc::CST_CODE_CSTRING: { // CSTRING: [values]
3136 return error("Invalid record");
3138 SmallString<16> Elts(Record.begin(), Record.end());
3139 V = ConstantDataArray::getString(Context, Elts,
3140 BitCode == bitc::CST_CODE_CSTRING);
3143 case bitc::CST_CODE_DATA: {// DATA: [n x value]
3145 return error("Invalid record");
3147 Type *EltTy = cast<SequentialType>(CurTy)->getElementType();
3148 if (EltTy->isIntegerTy(8)) {
3149 SmallVector<uint8_t, 16> Elts(Record.begin(), Record.end());
3150 if (isa<VectorType>(CurTy))
3151 V = ConstantDataVector::get(Context, Elts);
3153 V = ConstantDataArray::get(Context, Elts);
3154 } else if (EltTy->isIntegerTy(16)) {
3155 SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end());
3156 if (isa<VectorType>(CurTy))
3157 V = ConstantDataVector::get(Context, Elts);
3159 V = ConstantDataArray::get(Context, Elts);
3160 } else if (EltTy->isIntegerTy(32)) {
3161 SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end());
3162 if (isa<VectorType>(CurTy))
3163 V = ConstantDataVector::get(Context, Elts);
3165 V = ConstantDataArray::get(Context, Elts);
3166 } else if (EltTy->isIntegerTy(64)) {
3167 SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end());
3168 if (isa<VectorType>(CurTy))
3169 V = ConstantDataVector::get(Context, Elts);
3171 V = ConstantDataArray::get(Context, Elts);
3172 } else if (EltTy->isHalfTy()) {
3173 SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end());
3174 if (isa<VectorType>(CurTy))
3175 V = ConstantDataVector::getFP(Context, Elts);
3177 V = ConstantDataArray::getFP(Context, Elts);
3178 } else if (EltTy->isFloatTy()) {
3179 SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end());
3180 if (isa<VectorType>(CurTy))
3181 V = ConstantDataVector::getFP(Context, Elts);
3183 V = ConstantDataArray::getFP(Context, Elts);
3184 } else if (EltTy->isDoubleTy()) {
3185 SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end());
3186 if (isa<VectorType>(CurTy))
3187 V = ConstantDataVector::getFP(Context, Elts);
3189 V = ConstantDataArray::getFP(Context, Elts);
3191 return error("Invalid type for value");
3195 case bitc::CST_CODE_CE_BINOP: { // CE_BINOP: [opcode, opval, opval]
3196 if (Record.size() < 3)
3197 return error("Invalid record");
3198 int Opc = getDecodedBinaryOpcode(Record[0], CurTy);
3200 V = UndefValue::get(CurTy); // Unknown binop.
3202 Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy);
3203 Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy);
3205 if (Record.size() >= 4) {
3206 if (Opc == Instruction::Add ||
3207 Opc == Instruction::Sub ||
3208 Opc == Instruction::Mul ||
3209 Opc == Instruction::Shl) {
3210 if (Record[3] & (1 << bitc::OBO_NO_SIGNED_WRAP))
3211 Flags |= OverflowingBinaryOperator::NoSignedWrap;
3212 if (Record[3] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
3213 Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
3214 } else if (Opc == Instruction::SDiv ||
3215 Opc == Instruction::UDiv ||
3216 Opc == Instruction::LShr ||
3217 Opc == Instruction::AShr) {
3218 if (Record[3] & (1 << bitc::PEO_EXACT))
3219 Flags |= SDivOperator::IsExact;
3222 V = ConstantExpr::get(Opc, LHS, RHS, Flags);
3226 case bitc::CST_CODE_CE_CAST: { // CE_CAST: [opcode, opty, opval]
3227 if (Record.size() < 3)
3228 return error("Invalid record");
3229 int Opc = getDecodedCastOpcode(Record[0]);
3231 V = UndefValue::get(CurTy); // Unknown cast.
3233 Type *OpTy = getTypeByID(Record[1]);
3235 return error("Invalid record");
3236 Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy);
3237 V = UpgradeBitCastExpr(Opc, Op, CurTy);
3238 if (!V) V = ConstantExpr::getCast(Opc, Op, CurTy);
3242 case bitc::CST_CODE_CE_INBOUNDS_GEP:
3243 case bitc::CST_CODE_CE_GEP: { // CE_GEP: [n x operands]
3245 Type *PointeeType = nullptr;
3246 if (Record.size() % 2)
3247 PointeeType = getTypeByID(Record[OpNum++]);
3248 SmallVector<Constant*, 16> Elts;
3249 while (OpNum != Record.size()) {
3250 Type *ElTy = getTypeByID(Record[OpNum++]);
3252 return error("Invalid record");
3253 Elts.push_back(ValueList.getConstantFwdRef(Record[OpNum++], ElTy));
3258 cast<SequentialType>(Elts[0]->getType()->getScalarType())
3260 return error("Explicit gep operator type does not match pointee type "
3261 "of pointer operand");
3263 if (Elts.size() < 1)
3264 return error("Invalid gep with no operands");
3266 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
3267 V = ConstantExpr::getGetElementPtr(PointeeType, Elts[0], Indices,
3269 bitc::CST_CODE_CE_INBOUNDS_GEP);
3272 case bitc::CST_CODE_CE_SELECT: { // CE_SELECT: [opval#, opval#, opval#]
3273 if (Record.size() < 3)
3274 return error("Invalid record");
3276 Type *SelectorTy = Type::getInt1Ty(Context);
3278 // The selector might be an i1 or an <n x i1>
3279 // Get the type from the ValueList before getting a forward ref.
3280 if (VectorType *VTy = dyn_cast<VectorType>(CurTy))
3281 if (Value *V = ValueList[Record[0]])
3282 if (SelectorTy != V->getType())
3283 SelectorTy = VectorType::get(SelectorTy, VTy->getNumElements());
3285 V = ConstantExpr::getSelect(ValueList.getConstantFwdRef(Record[0],
3287 ValueList.getConstantFwdRef(Record[1],CurTy),
3288 ValueList.getConstantFwdRef(Record[2],CurTy));
3291 case bitc::CST_CODE_CE_EXTRACTELT
3292 : { // CE_EXTRACTELT: [opty, opval, opty, opval]
3293 if (Record.size() < 3)
3294 return error("Invalid record");
3296 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
3298 return error("Invalid record");
3299 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
3300 Constant *Op1 = nullptr;
3301 if (Record.size() == 4) {
3302 Type *IdxTy = getTypeByID(Record[2]);
3304 return error("Invalid record");
3305 Op1 = ValueList.getConstantFwdRef(Record[3], IdxTy);
3306 } else // TODO: Remove with llvm 4.0
3307 Op1 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
3309 return error("Invalid record");
3310 V = ConstantExpr::getExtractElement(Op0, Op1);
3313 case bitc::CST_CODE_CE_INSERTELT
3314 : { // CE_INSERTELT: [opval, opval, opty, opval]
3315 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
3316 if (Record.size() < 3 || !OpTy)
3317 return error("Invalid record");
3318 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
3319 Constant *Op1 = ValueList.getConstantFwdRef(Record[1],
3320 OpTy->getElementType());
3321 Constant *Op2 = nullptr;
3322 if (Record.size() == 4) {
3323 Type *IdxTy = getTypeByID(Record[2]);
3325 return error("Invalid record");
3326 Op2 = ValueList.getConstantFwdRef(Record[3], IdxTy);
3327 } else // TODO: Remove with llvm 4.0
3328 Op2 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
3330 return error("Invalid record");
3331 V = ConstantExpr::getInsertElement(Op0, Op1, Op2);
3334 case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval]
3335 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
3336 if (Record.size() < 3 || !OpTy)
3337 return error("Invalid record");
3338 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
3339 Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy);
3340 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
3341 OpTy->getNumElements());
3342 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy);
3343 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
3346 case bitc::CST_CODE_CE_SHUFVEC_EX: { // [opty, opval, opval, opval]
3347 VectorType *RTy = dyn_cast<VectorType>(CurTy);
3349 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
3350 if (Record.size() < 4 || !RTy || !OpTy)
3351 return error("Invalid record");
3352 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
3353 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
3354 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
3355 RTy->getNumElements());
3356 Constant *Op2 = ValueList.getConstantFwdRef(Record[3], ShufTy);
3357 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
3360 case bitc::CST_CODE_CE_CMP: { // CE_CMP: [opty, opval, opval, pred]
3361 if (Record.size() < 4)
3362 return error("Invalid record");
3363 Type *OpTy = getTypeByID(Record[0]);
3365 return error("Invalid record");
3366 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
3367 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
3369 if (OpTy->isFPOrFPVectorTy())
3370 V = ConstantExpr::getFCmp(Record[3], Op0, Op1);
3372 V = ConstantExpr::getICmp(Record[3], Op0, Op1);
3375 // This maintains backward compatibility, pre-asm dialect keywords.
3376 // FIXME: Remove with the 4.0 release.
3377 case bitc::CST_CODE_INLINEASM_OLD: {
3378 if (Record.size() < 2)
3379 return error("Invalid record");
3380 std::string AsmStr, ConstrStr;
3381 bool HasSideEffects = Record[0] & 1;
3382 bool IsAlignStack = Record[0] >> 1;
3383 unsigned AsmStrSize = Record[1];
3384 if (2+AsmStrSize >= Record.size())
3385 return error("Invalid record");
3386 unsigned ConstStrSize = Record[2+AsmStrSize];
3387 if (3+AsmStrSize+ConstStrSize > Record.size())
3388 return error("Invalid record");
3390 for (unsigned i = 0; i != AsmStrSize; ++i)
3391 AsmStr += (char)Record[2+i];
3392 for (unsigned i = 0; i != ConstStrSize; ++i)
3393 ConstrStr += (char)Record[3+AsmStrSize+i];
3394 PointerType *PTy = cast<PointerType>(CurTy);
3395 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
3396 AsmStr, ConstrStr, HasSideEffects, IsAlignStack);
3399 // This version adds support for the asm dialect keywords (e.g.,
3401 case bitc::CST_CODE_INLINEASM: {
3402 if (Record.size() < 2)
3403 return error("Invalid record");
3404 std::string AsmStr, ConstrStr;
3405 bool HasSideEffects = Record[0] & 1;
3406 bool IsAlignStack = (Record[0] >> 1) & 1;
3407 unsigned AsmDialect = Record[0] >> 2;
3408 unsigned AsmStrSize = Record[1];
3409 if (2+AsmStrSize >= Record.size())
3410 return error("Invalid record");
3411 unsigned ConstStrSize = Record[2+AsmStrSize];
3412 if (3+AsmStrSize+ConstStrSize > Record.size())
3413 return error("Invalid record");
3415 for (unsigned i = 0; i != AsmStrSize; ++i)
3416 AsmStr += (char)Record[2+i];
3417 for (unsigned i = 0; i != ConstStrSize; ++i)
3418 ConstrStr += (char)Record[3+AsmStrSize+i];
3419 PointerType *PTy = cast<PointerType>(CurTy);
3420 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
3421 AsmStr, ConstrStr, HasSideEffects, IsAlignStack,
3422 InlineAsm::AsmDialect(AsmDialect));
3425 case bitc::CST_CODE_BLOCKADDRESS:{
3426 if (Record.size() < 3)
3427 return error("Invalid record");
3428 Type *FnTy = getTypeByID(Record[0]);
3430 return error("Invalid record");
3432 dyn_cast_or_null<Function>(ValueList.getConstantFwdRef(Record[1],FnTy));
3434 return error("Invalid record");
3436 // If the function is already parsed we can insert the block address right
3439 unsigned BBID = Record[2];
3441 // Invalid reference to entry block.
3442 return error("Invalid ID");
3444 Function::iterator BBI = Fn->begin(), BBE = Fn->end();
3445 for (size_t I = 0, E = BBID; I != E; ++I) {
3447 return error("Invalid ID");
3452 // Otherwise insert a placeholder and remember it so it can be inserted
3453 // when the function is parsed.
3454 auto &FwdBBs = BasicBlockFwdRefs[Fn];
3456 BasicBlockFwdRefQueue.push_back(Fn);
3457 if (FwdBBs.size() < BBID + 1)
3458 FwdBBs.resize(BBID + 1);
3460 FwdBBs[BBID] = BasicBlock::Create(Context);
3463 V = BlockAddress::get(Fn, BB);
3468 ValueList.assignValue(V, NextCstNo);
3473 std::error_code BitcodeReader::parseUseLists() {
3474 if (Stream.EnterSubBlock(bitc::USELIST_BLOCK_ID))
3475 return error("Invalid record");
3477 // Read all the records.
3478 SmallVector<uint64_t, 64> Record;
3481 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
3483 switch (Entry.Kind) {
3484 case BitstreamEntry::SubBlock: // Handled for us already.
3485 case BitstreamEntry::Error:
3486 return error("Malformed block");
3487 case BitstreamEntry::EndBlock:
3488 return std::error_code();
3489 case BitstreamEntry::Record:
3490 // The interesting case.
3494 // Read a use list record.
3497 switch (Stream.readRecord(Entry.ID, Record)) {
3498 default: // Default behavior: unknown type.
3500 case bitc::USELIST_CODE_BB:
3503 case bitc::USELIST_CODE_DEFAULT: {
3504 unsigned RecordLength = Record.size();
3505 if (RecordLength < 3)
3506 // Records should have at least an ID and two indexes.
3507 return error("Invalid record");
3508 unsigned ID = Record.back();
3513 assert(ID < FunctionBBs.size() && "Basic block not found");
3514 V = FunctionBBs[ID];
3517 unsigned NumUses = 0;
3518 SmallDenseMap<const Use *, unsigned, 16> Order;
3519 for (const Use &U : V->materialized_uses()) {
3520 if (++NumUses > Record.size())
3522 Order[&U] = Record[NumUses - 1];
3524 if (Order.size() != Record.size() || NumUses > Record.size())
3525 // Mismatches can happen if the functions are being materialized lazily
3526 // (out-of-order), or a value has been upgraded.
3529 V->sortUseList([&](const Use &L, const Use &R) {
3530 return Order.lookup(&L) < Order.lookup(&R);
3538 /// When we see the block for metadata, remember where it is and then skip it.
3539 /// This lets us lazily deserialize the metadata.
3540 std::error_code BitcodeReader::rememberAndSkipMetadata() {
3541 // Save the current stream state.
3542 uint64_t CurBit = Stream.GetCurrentBitNo();
3543 DeferredMetadataInfo.push_back(CurBit);
3545 // Skip over the block for now.
3546 if (Stream.SkipBlock())
3547 return error("Invalid record");
3548 return std::error_code();
3551 std::error_code BitcodeReader::materializeMetadata() {
3552 for (uint64_t BitPos : DeferredMetadataInfo) {
3553 // Move the bit stream to the saved position.
3554 Stream.JumpToBit(BitPos);
3555 if (std::error_code EC = parseMetadata(true))
3558 DeferredMetadataInfo.clear();
3559 return std::error_code();
3562 void BitcodeReader::setStripDebugInfo() { StripDebugInfo = true; }
3564 /// When we see the block for a function body, remember where it is and then
3565 /// skip it. This lets us lazily deserialize the functions.
3566 std::error_code BitcodeReader::rememberAndSkipFunctionBody() {
3567 // Get the function we are talking about.
3568 if (FunctionsWithBodies.empty())
3569 return error("Insufficient function protos");
3571 Function *Fn = FunctionsWithBodies.back();
3572 FunctionsWithBodies.pop_back();
3574 // Save the current stream state.
3575 uint64_t CurBit = Stream.GetCurrentBitNo();
3577 (DeferredFunctionInfo[Fn] == 0 || DeferredFunctionInfo[Fn] == CurBit) &&
3578 "Mismatch between VST and scanned function offsets");
3579 DeferredFunctionInfo[Fn] = CurBit;
3581 // Skip over the function block for now.
3582 if (Stream.SkipBlock())
3583 return error("Invalid record");
3584 return std::error_code();
3587 std::error_code BitcodeReader::globalCleanup() {
3588 // Patch the initializers for globals and aliases up.
3589 resolveGlobalAndIndirectSymbolInits();
3590 if (!GlobalInits.empty() || !IndirectSymbolInits.empty())
3591 return error("Malformed global initializer set");
3593 // Look for intrinsic functions which need to be upgraded at some point
3594 for (Function &F : *TheModule) {
3596 if (UpgradeIntrinsicFunction(&F, NewFn))
3597 UpgradedIntrinsics[&F] = NewFn;
3598 else if (auto Remangled = Intrinsic::remangleIntrinsicFunction(&F))
3599 // Some types could be renamed during loading if several modules are
3600 // loaded in the same LLVMContext (LTO scenario). In this case we should
3601 // remangle intrinsics names as well.
3602 RemangledIntrinsics[&F] = Remangled.getValue();
3605 // Look for global variables which need to be renamed.
3606 for (GlobalVariable &GV : TheModule->globals())
3607 UpgradeGlobalVariable(&GV);
3609 // Force deallocation of memory for these vectors to favor the client that
3610 // want lazy deserialization.
3611 std::vector<std::pair<GlobalVariable*, unsigned> >().swap(GlobalInits);
3612 std::vector<std::pair<GlobalIndirectSymbol*, unsigned> >().swap(
3613 IndirectSymbolInits);
3614 return std::error_code();
3617 /// Support for lazy parsing of function bodies. This is required if we
3618 /// either have an old bitcode file without a VST forward declaration record,
3619 /// or if we have an anonymous function being materialized, since anonymous
3620 /// functions do not have a name and are therefore not in the VST.
3621 std::error_code BitcodeReader::rememberAndSkipFunctionBodies() {
3622 Stream.JumpToBit(NextUnreadBit);
3624 if (Stream.AtEndOfStream())
3625 return error("Could not find function in stream");
3627 if (!SeenFirstFunctionBody)
3628 return error("Trying to materialize functions before seeing function blocks");
3630 // An old bitcode file with the symbol table at the end would have
3631 // finished the parse greedily.
3632 assert(SeenValueSymbolTable);
3634 SmallVector<uint64_t, 64> Record;
3637 BitstreamEntry Entry = Stream.advance();
3638 switch (Entry.Kind) {
3640 return error("Expect SubBlock");
3641 case BitstreamEntry::SubBlock:
3644 return error("Expect function block");
3645 case bitc::FUNCTION_BLOCK_ID:
3646 if (std::error_code EC = rememberAndSkipFunctionBody())
3648 NextUnreadBit = Stream.GetCurrentBitNo();
3649 return std::error_code();
3655 std::error_code BitcodeReader::parseBitcodeVersion() {
3656 if (Stream.EnterSubBlock(bitc::IDENTIFICATION_BLOCK_ID))
3657 return error("Invalid record");
3659 // Read all the records.
3660 SmallVector<uint64_t, 64> Record;
3663 BitstreamEntry Entry = Stream.advance();
3665 switch (Entry.Kind) {
3667 case BitstreamEntry::Error:
3668 return error("Malformed block");
3669 case BitstreamEntry::EndBlock:
3670 return std::error_code();
3671 case BitstreamEntry::Record:
3672 // The interesting case.
3678 unsigned BitCode = Stream.readRecord(Entry.ID, Record);
3680 default: // Default behavior: reject
3681 return error("Invalid value");
3682 case bitc::IDENTIFICATION_CODE_STRING: { // IDENTIFICATION: [strchr x
3684 convertToString(Record, 0, ProducerIdentification);
3687 case bitc::IDENTIFICATION_CODE_EPOCH: { // EPOCH: [epoch#]
3688 unsigned epoch = (unsigned)Record[0];
3689 if (epoch != bitc::BITCODE_CURRENT_EPOCH) {
3691 Twine("Incompatible epoch: Bitcode '") + Twine(epoch) +
3692 "' vs current: '" + Twine(bitc::BITCODE_CURRENT_EPOCH) + "'");
3699 std::error_code BitcodeReader::parseModule(uint64_t ResumeBit,
3700 bool ShouldLazyLoadMetadata) {
3702 Stream.JumpToBit(ResumeBit);
3703 else if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
3704 return error("Invalid record");
3706 SmallVector<uint64_t, 64> Record;
3707 std::vector<std::string> SectionTable;
3708 std::vector<std::string> GCTable;
3710 // Read all the records for this module.
3712 BitstreamEntry Entry = Stream.advance();
3714 switch (Entry.Kind) {
3715 case BitstreamEntry::Error:
3716 return error("Malformed block");
3717 case BitstreamEntry::EndBlock:
3718 return globalCleanup();
3720 case BitstreamEntry::SubBlock:
3722 default: // Skip unknown content.
3723 if (Stream.SkipBlock())
3724 return error("Invalid record");
3726 case bitc::BLOCKINFO_BLOCK_ID:
3727 if (Stream.ReadBlockInfoBlock())
3728 return error("Malformed block");
3730 case bitc::PARAMATTR_BLOCK_ID:
3731 if (std::error_code EC = parseAttributeBlock())
3734 case bitc::PARAMATTR_GROUP_BLOCK_ID:
3735 if (std::error_code EC = parseAttributeGroupBlock())
3738 case bitc::TYPE_BLOCK_ID_NEW:
3739 if (std::error_code EC = parseTypeTable())
3742 case bitc::VALUE_SYMTAB_BLOCK_ID:
3743 if (!SeenValueSymbolTable) {
3744 // Either this is an old form VST without function index and an
3745 // associated VST forward declaration record (which would have caused
3746 // the VST to be jumped to and parsed before it was encountered
3747 // normally in the stream), or there were no function blocks to
3748 // trigger an earlier parsing of the VST.
3749 assert(VSTOffset == 0 || FunctionsWithBodies.empty());
3750 if (std::error_code EC = parseValueSymbolTable())
3752 SeenValueSymbolTable = true;
3754 // We must have had a VST forward declaration record, which caused
3755 // the parser to jump to and parse the VST earlier.
3756 assert(VSTOffset > 0);
3757 if (Stream.SkipBlock())
3758 return error("Invalid record");
3761 case bitc::CONSTANTS_BLOCK_ID:
3762 if (std::error_code EC = parseConstants())
3764 if (std::error_code EC = resolveGlobalAndIndirectSymbolInits())
3767 case bitc::METADATA_BLOCK_ID:
3768 if (ShouldLazyLoadMetadata && !IsMetadataMaterialized) {
3769 if (std::error_code EC = rememberAndSkipMetadata())
3773 assert(DeferredMetadataInfo.empty() && "Unexpected deferred metadata");
3774 if (std::error_code EC = parseMetadata(true))
3777 case bitc::METADATA_KIND_BLOCK_ID:
3778 if (std::error_code EC = parseMetadataKinds())
3781 case bitc::FUNCTION_BLOCK_ID:
3782 // If this is the first function body we've seen, reverse the
3783 // FunctionsWithBodies list.
3784 if (!SeenFirstFunctionBody) {
3785 std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
3786 if (std::error_code EC = globalCleanup())
3788 SeenFirstFunctionBody = true;
3791 if (VSTOffset > 0) {
3792 // If we have a VST forward declaration record, make sure we
3793 // parse the VST now if we haven't already. It is needed to
3794 // set up the DeferredFunctionInfo vector for lazy reading.
3795 if (!SeenValueSymbolTable) {
3796 if (std::error_code EC =
3797 BitcodeReader::parseValueSymbolTable(VSTOffset))
3799 SeenValueSymbolTable = true;
3800 // Fall through so that we record the NextUnreadBit below.
3801 // This is necessary in case we have an anonymous function that
3802 // is later materialized. Since it will not have a VST entry we
3803 // need to fall back to the lazy parse to find its offset.
3805 // If we have a VST forward declaration record, but have already
3806 // parsed the VST (just above, when the first function body was
3807 // encountered here), then we are resuming the parse after
3808 // materializing functions. The ResumeBit points to the
3809 // start of the last function block recorded in the
3810 // DeferredFunctionInfo map. Skip it.
3811 if (Stream.SkipBlock())
3812 return error("Invalid record");
3817 // Support older bitcode files that did not have the function
3818 // index in the VST, nor a VST forward declaration record, as
3819 // well as anonymous functions that do not have VST entries.
3820 // Build the DeferredFunctionInfo vector on the fly.
3821 if (std::error_code EC = rememberAndSkipFunctionBody())
3824 // Suspend parsing when we reach the function bodies. Subsequent
3825 // materialization calls will resume it when necessary. If the bitcode
3826 // file is old, the symbol table will be at the end instead and will not
3827 // have been seen yet. In this case, just finish the parse now.
3828 if (SeenValueSymbolTable) {
3829 NextUnreadBit = Stream.GetCurrentBitNo();
3830 // After the VST has been parsed, we need to make sure intrinsic name
3831 // are auto-upgraded.
3832 return globalCleanup();
3835 case bitc::USELIST_BLOCK_ID:
3836 if (std::error_code EC = parseUseLists())
3839 case bitc::OPERAND_BUNDLE_TAGS_BLOCK_ID:
3840 if (std::error_code EC = parseOperandBundleTags())
3846 case BitstreamEntry::Record:
3847 // The interesting case.
3852 auto BitCode = Stream.readRecord(Entry.ID, Record);
3854 default: break; // Default behavior, ignore unknown content.
3855 case bitc::MODULE_CODE_VERSION: { // VERSION: [version#]
3856 if (Record.size() < 1)
3857 return error("Invalid record");
3858 // Only version #0 and #1 are supported so far.
3859 unsigned module_version = Record[0];
3860 switch (module_version) {
3862 return error("Invalid value");
3864 UseRelativeIDs = false;
3867 UseRelativeIDs = true;
3872 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
3874 if (convertToString(Record, 0, S))
3875 return error("Invalid record");
3876 TheModule->setTargetTriple(S);
3879 case bitc::MODULE_CODE_DATALAYOUT: { // DATALAYOUT: [strchr x N]
3881 if (convertToString(Record, 0, S))
3882 return error("Invalid record");
3883 TheModule->setDataLayout(S);
3886 case bitc::MODULE_CODE_ASM: { // ASM: [strchr x N]
3888 if (convertToString(Record, 0, S))
3889 return error("Invalid record");
3890 TheModule->setModuleInlineAsm(S);
3893 case bitc::MODULE_CODE_DEPLIB: { // DEPLIB: [strchr x N]
3894 // FIXME: Remove in 4.0.
3896 if (convertToString(Record, 0, S))
3897 return error("Invalid record");
3901 case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N]
3903 if (convertToString(Record, 0, S))
3904 return error("Invalid record");
3905 SectionTable.push_back(S);
3908 case bitc::MODULE_CODE_GCNAME: { // SECTIONNAME: [strchr x N]
3910 if (convertToString(Record, 0, S))
3911 return error("Invalid record");
3912 GCTable.push_back(S);
3915 case bitc::MODULE_CODE_COMDAT: { // COMDAT: [selection_kind, name]
3916 if (Record.size() < 2)
3917 return error("Invalid record");
3918 Comdat::SelectionKind SK = getDecodedComdatSelectionKind(Record[0]);
3919 unsigned ComdatNameSize = Record[1];
3920 std::string ComdatName;
3921 ComdatName.reserve(ComdatNameSize);
3922 for (unsigned i = 0; i != ComdatNameSize; ++i)
3923 ComdatName += (char)Record[2 + i];
3924 Comdat *C = TheModule->getOrInsertComdat(ComdatName);
3925 C->setSelectionKind(SK);
3926 ComdatList.push_back(C);
3929 // GLOBALVAR: [pointer type, isconst, initid,
3930 // linkage, alignment, section, visibility, threadlocal,
3931 // unnamed_addr, externally_initialized, dllstorageclass,
3933 case bitc::MODULE_CODE_GLOBALVAR: {
3934 if (Record.size() < 6)
3935 return error("Invalid record");
3936 Type *Ty = getTypeByID(Record[0]);
3938 return error("Invalid record");
3939 bool isConstant = Record[1] & 1;
3940 bool explicitType = Record[1] & 2;
3941 unsigned AddressSpace;
3943 AddressSpace = Record[1] >> 2;
3945 if (!Ty->isPointerTy())
3946 return error("Invalid type for value");
3947 AddressSpace = cast<PointerType>(Ty)->getAddressSpace();
3948 Ty = cast<PointerType>(Ty)->getElementType();
3951 uint64_t RawLinkage = Record[3];
3952 GlobalValue::LinkageTypes Linkage = getDecodedLinkage(RawLinkage);
3954 if (std::error_code EC = parseAlignmentValue(Record[4], Alignment))
3956 std::string Section;
3958 if (Record[5]-1 >= SectionTable.size())
3959 return error("Invalid ID");
3960 Section = SectionTable[Record[5]-1];
3962 GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;
3963 // Local linkage must have default visibility.
3964 if (Record.size() > 6 && !GlobalValue::isLocalLinkage(Linkage))
3965 // FIXME: Change to an error if non-default in 4.0.
3966 Visibility = getDecodedVisibility(Record[6]);
3968 GlobalVariable::ThreadLocalMode TLM = GlobalVariable::NotThreadLocal;
3969 if (Record.size() > 7)
3970 TLM = getDecodedThreadLocalMode(Record[7]);
3972 GlobalValue::UnnamedAddr UnnamedAddr = GlobalValue::UnnamedAddr::None;
3973 if (Record.size() > 8)
3974 UnnamedAddr = getDecodedUnnamedAddrType(Record[8]);
3976 bool ExternallyInitialized = false;
3977 if (Record.size() > 9)
3978 ExternallyInitialized = Record[9];
3980 GlobalVariable *NewGV =
3981 new GlobalVariable(*TheModule, Ty, isConstant, Linkage, nullptr, "", nullptr,
3982 TLM, AddressSpace, ExternallyInitialized);
3983 NewGV->setAlignment(Alignment);
3984 if (!Section.empty())
3985 NewGV->setSection(Section);
3986 NewGV->setVisibility(Visibility);
3987 NewGV->setUnnamedAddr(UnnamedAddr);
3989 if (Record.size() > 10)
3990 NewGV->setDLLStorageClass(getDecodedDLLStorageClass(Record[10]));
3992 upgradeDLLImportExportLinkage(NewGV, RawLinkage);
3994 ValueList.push_back(NewGV);
3996 // Remember which value to use for the global initializer.
3997 if (unsigned InitID = Record[2])
3998 GlobalInits.push_back(std::make_pair(NewGV, InitID-1));
4000 if (Record.size() > 11) {
4001 if (unsigned ComdatID = Record[11]) {
4002 if (ComdatID > ComdatList.size())
4003 return error("Invalid global variable comdat ID");
4004 NewGV->setComdat(ComdatList[ComdatID - 1]);
4006 } else if (hasImplicitComdat(RawLinkage)) {
4007 NewGV->setComdat(reinterpret_cast<Comdat *>(1));
4012 // FUNCTION: [type, callingconv, isproto, linkage, paramattr,
4013 // alignment, section, visibility, gc, unnamed_addr,
4014 // prologuedata, dllstorageclass, comdat, prefixdata]
4015 case bitc::MODULE_CODE_FUNCTION: {
4016 if (Record.size() < 8)
4017 return error("Invalid record");
4018 Type *Ty = getTypeByID(Record[0]);
4020 return error("Invalid record");
4021 if (auto *PTy = dyn_cast<PointerType>(Ty))
4022 Ty = PTy->getElementType();
4023 auto *FTy = dyn_cast<FunctionType>(Ty);
4025 return error("Invalid type for value");
4026 auto CC = static_cast<CallingConv::ID>(Record[1]);
4027 if (CC & ~CallingConv::MaxID)
4028 return error("Invalid calling convention ID");
4030 Function *Func = Function::Create(FTy, GlobalValue::ExternalLinkage,
4033 Func->setCallingConv(CC);
4034 bool isProto = Record[2];
4035 uint64_t RawLinkage = Record[3];
4036 Func->setLinkage(getDecodedLinkage(RawLinkage));
4037 Func->setAttributes(getAttributes(Record[4]));
4040 if (std::error_code EC = parseAlignmentValue(Record[5], Alignment))
4042 Func->setAlignment(Alignment);
4044 if (Record[6]-1 >= SectionTable.size())
4045 return error("Invalid ID");
4046 Func->setSection(SectionTable[Record[6]-1]);
4048 // Local linkage must have default visibility.
4049 if (!Func->hasLocalLinkage())
4050 // FIXME: Change to an error if non-default in 4.0.
4051 Func->setVisibility(getDecodedVisibility(Record[7]));
4052 if (Record.size() > 8 && Record[8]) {
4053 if (Record[8]-1 >= GCTable.size())
4054 return error("Invalid ID");
4055 Func->setGC(GCTable[Record[8] - 1]);
4057 GlobalValue::UnnamedAddr UnnamedAddr = GlobalValue::UnnamedAddr::None;
4058 if (Record.size() > 9)
4059 UnnamedAddr = getDecodedUnnamedAddrType(Record[9]);
4060 Func->setUnnamedAddr(UnnamedAddr);
4061 if (Record.size() > 10 && Record[10] != 0)
4062 FunctionPrologues.push_back(std::make_pair(Func, Record[10]-1));
4064 if (Record.size() > 11)
4065 Func->setDLLStorageClass(getDecodedDLLStorageClass(Record[11]));
4067 upgradeDLLImportExportLinkage(Func, RawLinkage);
4069 if (Record.size() > 12) {
4070 if (unsigned ComdatID = Record[12]) {
4071 if (ComdatID > ComdatList.size())
4072 return error("Invalid function comdat ID");
4073 Func->setComdat(ComdatList[ComdatID - 1]);
4075 } else if (hasImplicitComdat(RawLinkage)) {
4076 Func->setComdat(reinterpret_cast<Comdat *>(1));
4079 if (Record.size() > 13 && Record[13] != 0)
4080 FunctionPrefixes.push_back(std::make_pair(Func, Record[13]-1));
4082 if (Record.size() > 14 && Record[14] != 0)
4083 FunctionPersonalityFns.push_back(std::make_pair(Func, Record[14] - 1));
4085 ValueList.push_back(Func);
4087 // If this is a function with a body, remember the prototype we are
4088 // creating now, so that we can match up the body with them later.
4090 Func->setIsMaterializable(true);
4091 FunctionsWithBodies.push_back(Func);
4092 DeferredFunctionInfo[Func] = 0;
4096 // ALIAS: [alias type, addrspace, aliasee val#, linkage]
4097 // ALIAS: [alias type, addrspace, aliasee val#, linkage, visibility, dllstorageclass]
4098 // IFUNC: [alias type, addrspace, aliasee val#, linkage, visibility, dllstorageclass]
4099 case bitc::MODULE_CODE_IFUNC:
4100 case bitc::MODULE_CODE_ALIAS:
4101 case bitc::MODULE_CODE_ALIAS_OLD: {
4102 bool NewRecord = BitCode != bitc::MODULE_CODE_ALIAS_OLD;
4103 if (Record.size() < (3 + (unsigned)NewRecord))
4104 return error("Invalid record");
4106 Type *Ty = getTypeByID(Record[OpNum++]);
4108 return error("Invalid record");
4112 auto *PTy = dyn_cast<PointerType>(Ty);
4114 return error("Invalid type for value");
4115 Ty = PTy->getElementType();
4116 AddrSpace = PTy->getAddressSpace();
4118 AddrSpace = Record[OpNum++];
4121 auto Val = Record[OpNum++];
4122 auto Linkage = Record[OpNum++];
4123 GlobalIndirectSymbol *NewGA;
4124 if (BitCode == bitc::MODULE_CODE_ALIAS ||
4125 BitCode == bitc::MODULE_CODE_ALIAS_OLD)
4126 NewGA = GlobalAlias::create(Ty, AddrSpace, getDecodedLinkage(Linkage),
4129 NewGA = GlobalIFunc::create(Ty, AddrSpace, getDecodedLinkage(Linkage),
4130 "", nullptr, TheModule);
4131 // Old bitcode files didn't have visibility field.
4132 // Local linkage must have default visibility.
4133 if (OpNum != Record.size()) {
4134 auto VisInd = OpNum++;
4135 if (!NewGA->hasLocalLinkage())
4136 // FIXME: Change to an error if non-default in 4.0.
4137 NewGA->setVisibility(getDecodedVisibility(Record[VisInd]));
4139 if (OpNum != Record.size())
4140 NewGA->setDLLStorageClass(getDecodedDLLStorageClass(Record[OpNum++]));
4142 upgradeDLLImportExportLinkage(NewGA, Linkage);
4143 if (OpNum != Record.size())
4144 NewGA->setThreadLocalMode(getDecodedThreadLocalMode(Record[OpNum++]));
4145 if (OpNum != Record.size())
4146 NewGA->setUnnamedAddr(getDecodedUnnamedAddrType(Record[OpNum++]));
4147 ValueList.push_back(NewGA);
4148 IndirectSymbolInits.push_back(std::make_pair(NewGA, Val));
4151 /// MODULE_CODE_PURGEVALS: [numvals]
4152 case bitc::MODULE_CODE_PURGEVALS:
4153 // Trim down the value list to the specified size.
4154 if (Record.size() < 1 || Record[0] > ValueList.size())
4155 return error("Invalid record");
4156 ValueList.shrinkTo(Record[0]);
4158 /// MODULE_CODE_VSTOFFSET: [offset]
4159 case bitc::MODULE_CODE_VSTOFFSET:
4160 if (Record.size() < 1)
4161 return error("Invalid record");
4162 VSTOffset = Record[0];
4164 /// MODULE_CODE_SOURCE_FILENAME: [namechar x N]
4165 case bitc::MODULE_CODE_SOURCE_FILENAME:
4166 SmallString<128> ValueName;
4167 if (convertToString(Record, 0, ValueName))
4168 return error("Invalid record");
4169 TheModule->setSourceFileName(ValueName);
4176 /// Helper to read the header common to all bitcode files.
4177 static bool hasValidBitcodeHeader(BitstreamCursor &Stream) {
4178 // Sniff for the signature.
4179 if (Stream.Read(8) != 'B' ||
4180 Stream.Read(8) != 'C' ||
4181 Stream.Read(4) != 0x0 ||
4182 Stream.Read(4) != 0xC ||
4183 Stream.Read(4) != 0xE ||
4184 Stream.Read(4) != 0xD)
4190 BitcodeReader::parseBitcodeInto(std::unique_ptr<DataStreamer> Streamer,
4191 Module *M, bool ShouldLazyLoadMetadata) {
4194 if (std::error_code EC = initStream(std::move(Streamer)))
4197 // Sniff for the signature.
4198 if (!hasValidBitcodeHeader(Stream))
4199 return error("Invalid bitcode signature");
4201 // We expect a number of well-defined blocks, though we don't necessarily
4202 // need to understand them all.
4204 if (Stream.AtEndOfStream()) {
4205 // We didn't really read a proper Module.
4206 return error("Malformed IR file");
4209 BitstreamEntry Entry =
4210 Stream.advance(BitstreamCursor::AF_DontAutoprocessAbbrevs);
4212 if (Entry.Kind != BitstreamEntry::SubBlock)
4213 return error("Malformed block");
4215 if (Entry.ID == bitc::IDENTIFICATION_BLOCK_ID) {
4216 parseBitcodeVersion();
4220 if (Entry.ID == bitc::MODULE_BLOCK_ID)
4221 return parseModule(0, ShouldLazyLoadMetadata);
4223 if (Stream.SkipBlock())
4224 return error("Invalid record");
4228 ErrorOr<std::string> BitcodeReader::parseModuleTriple() {
4229 if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
4230 return error("Invalid record");
4232 SmallVector<uint64_t, 64> Record;
4236 // Read all the records for this module.
4238 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
4240 switch (Entry.Kind) {
4241 case BitstreamEntry::SubBlock: // Handled for us already.
4242 case BitstreamEntry::Error:
4243 return error("Malformed block");
4244 case BitstreamEntry::EndBlock:
4246 case BitstreamEntry::Record:
4247 // The interesting case.
4252 switch (Stream.readRecord(Entry.ID, Record)) {
4253 default: break; // Default behavior, ignore unknown content.
4254 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
4256 if (convertToString(Record, 0, S))
4257 return error("Invalid record");
4264 llvm_unreachable("Exit infinite loop");
4267 ErrorOr<std::string> BitcodeReader::parseTriple() {
4268 if (std::error_code EC = initStream(nullptr))
4271 // Sniff for the signature.
4272 if (!hasValidBitcodeHeader(Stream))
4273 return error("Invalid bitcode signature");
4275 // We expect a number of well-defined blocks, though we don't necessarily
4276 // need to understand them all.
4278 BitstreamEntry Entry = Stream.advance();
4280 switch (Entry.Kind) {
4281 case BitstreamEntry::Error:
4282 return error("Malformed block");
4283 case BitstreamEntry::EndBlock:
4284 return std::error_code();
4286 case BitstreamEntry::SubBlock:
4287 if (Entry.ID == bitc::MODULE_BLOCK_ID)
4288 return parseModuleTriple();
4290 // Ignore other sub-blocks.
4291 if (Stream.SkipBlock())
4292 return error("Malformed block");
4295 case BitstreamEntry::Record:
4296 Stream.skipRecord(Entry.ID);
4302 ErrorOr<std::string> BitcodeReader::parseIdentificationBlock() {
4303 if (std::error_code EC = initStream(nullptr))
4306 // Sniff for the signature.
4307 if (!hasValidBitcodeHeader(Stream))
4308 return error("Invalid bitcode signature");
4310 // We expect a number of well-defined blocks, though we don't necessarily
4311 // need to understand them all.
4313 BitstreamEntry Entry = Stream.advance();
4314 switch (Entry.Kind) {
4315 case BitstreamEntry::Error:
4316 return error("Malformed block");
4317 case BitstreamEntry::EndBlock:
4318 return std::error_code();
4320 case BitstreamEntry::SubBlock:
4321 if (Entry.ID == bitc::IDENTIFICATION_BLOCK_ID) {
4322 if (std::error_code EC = parseBitcodeVersion())
4324 return ProducerIdentification;
4326 // Ignore other sub-blocks.
4327 if (Stream.SkipBlock())
4328 return error("Malformed block");
4330 case BitstreamEntry::Record:
4331 Stream.skipRecord(Entry.ID);
4337 std::error_code BitcodeReader::parseGlobalObjectAttachment(
4338 GlobalObject &GO, ArrayRef<uint64_t> Record) {
4339 assert(Record.size() % 2 == 0);
4340 for (unsigned I = 0, E = Record.size(); I != E; I += 2) {
4341 auto K = MDKindMap.find(Record[I]);
4342 if (K == MDKindMap.end())
4343 return error("Invalid ID");
4344 MDNode *MD = MetadataList.getMDNodeFwdRefOrNull(Record[I + 1]);
4346 return error("Invalid metadata attachment");
4347 GO.addMetadata(K->second, *MD);
4349 return std::error_code();
4352 ErrorOr<bool> BitcodeReader::hasObjCCategory() {
4353 if (std::error_code EC = initStream(nullptr))
4356 // Sniff for the signature.
4357 if (!hasValidBitcodeHeader(Stream))
4358 return error("Invalid bitcode signature");
4360 // We expect a number of well-defined blocks, though we don't necessarily
4361 // need to understand them all.
4363 BitstreamEntry Entry = Stream.advance();
4365 switch (Entry.Kind) {
4366 case BitstreamEntry::Error:
4367 return error("Malformed block");
4368 case BitstreamEntry::EndBlock:
4369 return std::error_code();
4371 case BitstreamEntry::SubBlock:
4372 if (Entry.ID == bitc::MODULE_BLOCK_ID)
4373 return hasObjCCategoryInModule();
4375 // Ignore other sub-blocks.
4376 if (Stream.SkipBlock())
4377 return error("Malformed block");
4380 case BitstreamEntry::Record:
4381 Stream.skipRecord(Entry.ID);
4387 ErrorOr<bool> BitcodeReader::hasObjCCategoryInModule() {
4388 if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
4389 return error("Invalid record");
4391 SmallVector<uint64_t, 64> Record;
4392 // Read all the records for this module.
4395 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
4397 switch (Entry.Kind) {
4398 case BitstreamEntry::SubBlock: // Handled for us already.
4399 case BitstreamEntry::Error:
4400 return error("Malformed block");
4401 case BitstreamEntry::EndBlock:
4403 case BitstreamEntry::Record:
4404 // The interesting case.
4409 switch (Stream.readRecord(Entry.ID, Record)) {
4411 break; // Default behavior, ignore unknown content.
4412 case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N]
4414 if (convertToString(Record, 0, S))
4415 return error("Invalid record");
4416 // Check for the i386 and other (x86_64, ARM) conventions
4417 if (S.find("__DATA, __objc_catlist") != std::string::npos ||
4418 S.find("__OBJC,__category") != std::string::npos)
4425 llvm_unreachable("Exit infinite loop");
4428 /// Parse metadata attachments.
4429 std::error_code BitcodeReader::parseMetadataAttachment(Function &F) {
4430 if (Stream.EnterSubBlock(bitc::METADATA_ATTACHMENT_ID))
4431 return error("Invalid record");
4433 SmallVector<uint64_t, 64> Record;
4436 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
4438 switch (Entry.Kind) {
4439 case BitstreamEntry::SubBlock: // Handled for us already.
4440 case BitstreamEntry::Error:
4441 return error("Malformed block");
4442 case BitstreamEntry::EndBlock:
4443 return std::error_code();
4444 case BitstreamEntry::Record:
4445 // The interesting case.
4449 // Read a metadata attachment record.
4451 switch (Stream.readRecord(Entry.ID, Record)) {
4452 default: // Default behavior: ignore.
4454 case bitc::METADATA_ATTACHMENT: {
4455 unsigned RecordLength = Record.size();
4457 return error("Invalid record");
4458 if (RecordLength % 2 == 0) {
4459 // A function attachment.
4460 if (std::error_code EC = parseGlobalObjectAttachment(F, Record))
4465 // An instruction attachment.
4466 Instruction *Inst = InstructionList[Record[0]];
4467 for (unsigned i = 1; i != RecordLength; i = i+2) {
4468 unsigned Kind = Record[i];
4469 DenseMap<unsigned, unsigned>::iterator I =
4470 MDKindMap.find(Kind);
4471 if (I == MDKindMap.end())
4472 return error("Invalid ID");
4473 Metadata *Node = MetadataList.getMetadataFwdRef(Record[i + 1]);
4474 if (isa<LocalAsMetadata>(Node))
4475 // Drop the attachment. This used to be legal, but there's no
4478 MDNode *MD = dyn_cast_or_null<MDNode>(Node);
4480 return error("Invalid metadata attachment");
4482 if (HasSeenOldLoopTags && I->second == LLVMContext::MD_loop)
4483 MD = upgradeInstructionLoopAttachment(*MD);
4485 if (I->second == LLVMContext::MD_tbaa) {
4486 assert(!MD->isTemporary() && "should load MDs before attachments");
4487 MD = UpgradeTBAANode(*MD);
4489 Inst->setMetadata(I->second, MD);
4497 static std::error_code typeCheckLoadStoreInst(Type *ValType, Type *PtrType) {
4498 LLVMContext &Context = PtrType->getContext();
4499 if (!isa<PointerType>(PtrType))
4500 return error(Context, "Load/Store operand is not a pointer type");
4501 Type *ElemType = cast<PointerType>(PtrType)->getElementType();
4503 if (ValType && ValType != ElemType)
4504 return error(Context, "Explicit load/store type does not match pointee "
4505 "type of pointer operand");
4506 if (!PointerType::isLoadableOrStorableType(ElemType))
4507 return error(Context, "Cannot load/store from pointer");
4508 return std::error_code();
4511 /// Lazily parse the specified function body block.
4512 std::error_code BitcodeReader::parseFunctionBody(Function *F) {
4513 if (Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID))
4514 return error("Invalid record");
4516 // Unexpected unresolved metadata when parsing function.
4517 if (MetadataList.hasFwdRefs())
4518 return error("Invalid function metadata: incoming forward references");
4520 InstructionList.clear();
4521 unsigned ModuleValueListSize = ValueList.size();
4522 unsigned ModuleMetadataListSize = MetadataList.size();
4524 // Add all the function arguments to the value table.
4525 for (Argument &I : F->args())
4526 ValueList.push_back(&I);
4528 unsigned NextValueNo = ValueList.size();
4529 BasicBlock *CurBB = nullptr;
4530 unsigned CurBBNo = 0;
4533 auto getLastInstruction = [&]() -> Instruction * {
4534 if (CurBB && !CurBB->empty())
4535 return &CurBB->back();
4536 else if (CurBBNo && FunctionBBs[CurBBNo - 1] &&
4537 !FunctionBBs[CurBBNo - 1]->empty())
4538 return &FunctionBBs[CurBBNo - 1]->back();
4542 std::vector<OperandBundleDef> OperandBundles;
4544 // Read all the records.
4545 SmallVector<uint64_t, 64> Record;
4548 BitstreamEntry Entry = Stream.advance();
4550 switch (Entry.Kind) {
4551 case BitstreamEntry::Error:
4552 return error("Malformed block");
4553 case BitstreamEntry::EndBlock:
4554 goto OutOfRecordLoop;
4556 case BitstreamEntry::SubBlock:
4558 default: // Skip unknown content.
4559 if (Stream.SkipBlock())
4560 return error("Invalid record");
4562 case bitc::CONSTANTS_BLOCK_ID:
4563 if (std::error_code EC = parseConstants())
4565 NextValueNo = ValueList.size();
4567 case bitc::VALUE_SYMTAB_BLOCK_ID:
4568 if (std::error_code EC = parseValueSymbolTable())
4571 case bitc::METADATA_ATTACHMENT_ID:
4572 if (std::error_code EC = parseMetadataAttachment(*F))
4575 case bitc::METADATA_BLOCK_ID:
4576 if (std::error_code EC = parseMetadata())
4579 case bitc::USELIST_BLOCK_ID:
4580 if (std::error_code EC = parseUseLists())
4586 case BitstreamEntry::Record:
4587 // The interesting case.
4593 Instruction *I = nullptr;
4594 unsigned BitCode = Stream.readRecord(Entry.ID, Record);
4596 default: // Default behavior: reject
4597 return error("Invalid value");
4598 case bitc::FUNC_CODE_DECLAREBLOCKS: { // DECLAREBLOCKS: [nblocks]
4599 if (Record.size() < 1 || Record[0] == 0)
4600 return error("Invalid record");
4601 // Create all the basic blocks for the function.
4602 FunctionBBs.resize(Record[0]);
4604 // See if anything took the address of blocks in this function.
4605 auto BBFRI = BasicBlockFwdRefs.find(F);
4606 if (BBFRI == BasicBlockFwdRefs.end()) {
4607 for (unsigned i = 0, e = FunctionBBs.size(); i != e; ++i)
4608 FunctionBBs[i] = BasicBlock::Create(Context, "", F);
4610 auto &BBRefs = BBFRI->second;
4611 // Check for invalid basic block references.
4612 if (BBRefs.size() > FunctionBBs.size())
4613 return error("Invalid ID");
4614 assert(!BBRefs.empty() && "Unexpected empty array");
4615 assert(!BBRefs.front() && "Invalid reference to entry block");
4616 for (unsigned I = 0, E = FunctionBBs.size(), RE = BBRefs.size(); I != E;
4618 if (I < RE && BBRefs[I]) {
4619 BBRefs[I]->insertInto(F);
4620 FunctionBBs[I] = BBRefs[I];
4622 FunctionBBs[I] = BasicBlock::Create(Context, "", F);
4625 // Erase from the table.
4626 BasicBlockFwdRefs.erase(BBFRI);
4629 CurBB = FunctionBBs[0];
4633 case bitc::FUNC_CODE_DEBUG_LOC_AGAIN: // DEBUG_LOC_AGAIN
4634 // This record indicates that the last instruction is at the same
4635 // location as the previous instruction with a location.
4636 I = getLastInstruction();
4639 return error("Invalid record");
4640 I->setDebugLoc(LastLoc);
4644 case bitc::FUNC_CODE_DEBUG_LOC: { // DEBUG_LOC: [line, col, scope, ia]
4645 I = getLastInstruction();
4646 if (!I || Record.size() < 4)
4647 return error("Invalid record");
4649 unsigned Line = Record[0], Col = Record[1];
4650 unsigned ScopeID = Record[2], IAID = Record[3];
4652 MDNode *Scope = nullptr, *IA = nullptr;
4654 Scope = MetadataList.getMDNodeFwdRefOrNull(ScopeID - 1);
4656 return error("Invalid record");
4659 IA = MetadataList.getMDNodeFwdRefOrNull(IAID - 1);
4661 return error("Invalid record");
4663 LastLoc = DebugLoc::get(Line, Col, Scope, IA);
4664 I->setDebugLoc(LastLoc);
4669 case bitc::FUNC_CODE_INST_BINOP: { // BINOP: [opval, ty, opval, opcode]
4672 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
4673 popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) ||
4674 OpNum+1 > Record.size())
4675 return error("Invalid record");
4677 int Opc = getDecodedBinaryOpcode(Record[OpNum++], LHS->getType());
4679 return error("Invalid record");
4680 I = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
4681 InstructionList.push_back(I);
4682 if (OpNum < Record.size()) {
4683 if (Opc == Instruction::Add ||
4684 Opc == Instruction::Sub ||
4685 Opc == Instruction::Mul ||
4686 Opc == Instruction::Shl) {
4687 if (Record[OpNum] & (1 << bitc::OBO_NO_SIGNED_WRAP))
4688 cast<BinaryOperator>(I)->setHasNoSignedWrap(true);
4689 if (Record[OpNum] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
4690 cast<BinaryOperator>(I)->setHasNoUnsignedWrap(true);
4691 } else if (Opc == Instruction::SDiv ||
4692 Opc == Instruction::UDiv ||
4693 Opc == Instruction::LShr ||
4694 Opc == Instruction::AShr) {
4695 if (Record[OpNum] & (1 << bitc::PEO_EXACT))
4696 cast<BinaryOperator>(I)->setIsExact(true);
4697 } else if (isa<FPMathOperator>(I)) {
4698 FastMathFlags FMF = getDecodedFastMathFlags(Record[OpNum]);
4700 I->setFastMathFlags(FMF);
4706 case bitc::FUNC_CODE_INST_CAST: { // CAST: [opval, opty, destty, castopc]
4709 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
4710 OpNum+2 != Record.size())
4711 return error("Invalid record");
4713 Type *ResTy = getTypeByID(Record[OpNum]);
4714 int Opc = getDecodedCastOpcode(Record[OpNum + 1]);
4715 if (Opc == -1 || !ResTy)
4716 return error("Invalid record");
4717 Instruction *Temp = nullptr;
4718 if ((I = UpgradeBitCastInst(Opc, Op, ResTy, Temp))) {
4720 InstructionList.push_back(Temp);
4721 CurBB->getInstList().push_back(Temp);
4724 auto CastOp = (Instruction::CastOps)Opc;
4725 if (!CastInst::castIsValid(CastOp, Op, ResTy))
4726 return error("Invalid cast");
4727 I = CastInst::Create(CastOp, Op, ResTy);
4729 InstructionList.push_back(I);
4732 case bitc::FUNC_CODE_INST_INBOUNDS_GEP_OLD:
4733 case bitc::FUNC_CODE_INST_GEP_OLD:
4734 case bitc::FUNC_CODE_INST_GEP: { // GEP: type, [n x operands]
4740 if (BitCode == bitc::FUNC_CODE_INST_GEP) {
4741 InBounds = Record[OpNum++];
4742 Ty = getTypeByID(Record[OpNum++]);
4744 InBounds = BitCode == bitc::FUNC_CODE_INST_INBOUNDS_GEP_OLD;
4749 if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr))
4750 return error("Invalid record");
4753 Ty = cast<SequentialType>(BasePtr->getType()->getScalarType())
4756 cast<SequentialType>(BasePtr->getType()->getScalarType())
4759 "Explicit gep type does not match pointee type of pointer operand");
4761 SmallVector<Value*, 16> GEPIdx;
4762 while (OpNum != Record.size()) {
4764 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
4765 return error("Invalid record");
4766 GEPIdx.push_back(Op);
4769 I = GetElementPtrInst::Create(Ty, BasePtr, GEPIdx);
4771 InstructionList.push_back(I);
4773 cast<GetElementPtrInst>(I)->setIsInBounds(true);
4777 case bitc::FUNC_CODE_INST_EXTRACTVAL: {
4778 // EXTRACTVAL: [opty, opval, n x indices]
4781 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
4782 return error("Invalid record");
4784 unsigned RecSize = Record.size();
4785 if (OpNum == RecSize)
4786 return error("EXTRACTVAL: Invalid instruction with 0 indices");
4788 SmallVector<unsigned, 4> EXTRACTVALIdx;
4789 Type *CurTy = Agg->getType();
4790 for (; OpNum != RecSize; ++OpNum) {
4791 bool IsArray = CurTy->isArrayTy();
4792 bool IsStruct = CurTy->isStructTy();
4793 uint64_t Index = Record[OpNum];
4795 if (!IsStruct && !IsArray)
4796 return error("EXTRACTVAL: Invalid type");
4797 if ((unsigned)Index != Index)
4798 return error("Invalid value");
4799 if (IsStruct && Index >= CurTy->subtypes().size())
4800 return error("EXTRACTVAL: Invalid struct index");
4801 if (IsArray && Index >= CurTy->getArrayNumElements())
4802 return error("EXTRACTVAL: Invalid array index");
4803 EXTRACTVALIdx.push_back((unsigned)Index);
4806 CurTy = CurTy->subtypes()[Index];
4808 CurTy = CurTy->subtypes()[0];
4811 I = ExtractValueInst::Create(Agg, EXTRACTVALIdx);
4812 InstructionList.push_back(I);
4816 case bitc::FUNC_CODE_INST_INSERTVAL: {
4817 // INSERTVAL: [opty, opval, opty, opval, n x indices]
4820 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
4821 return error("Invalid record");
4823 if (getValueTypePair(Record, OpNum, NextValueNo, Val))
4824 return error("Invalid record");
4826 unsigned RecSize = Record.size();
4827 if (OpNum == RecSize)
4828 return error("INSERTVAL: Invalid instruction with 0 indices");
4830 SmallVector<unsigned, 4> INSERTVALIdx;
4831 Type *CurTy = Agg->getType();
4832 for (; OpNum != RecSize; ++OpNum) {
4833 bool IsArray = CurTy->isArrayTy();
4834 bool IsStruct = CurTy->isStructTy();
4835 uint64_t Index = Record[OpNum];
4837 if (!IsStruct && !IsArray)
4838 return error("INSERTVAL: Invalid type");
4839 if ((unsigned)Index != Index)
4840 return error("Invalid value");
4841 if (IsStruct && Index >= CurTy->subtypes().size())
4842 return error("INSERTVAL: Invalid struct index");
4843 if (IsArray && Index >= CurTy->getArrayNumElements())
4844 return error("INSERTVAL: Invalid array index");
4846 INSERTVALIdx.push_back((unsigned)Index);
4848 CurTy = CurTy->subtypes()[Index];
4850 CurTy = CurTy->subtypes()[0];
4853 if (CurTy != Val->getType())
4854 return error("Inserted value type doesn't match aggregate type");
4856 I = InsertValueInst::Create(Agg, Val, INSERTVALIdx);
4857 InstructionList.push_back(I);
4861 case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval]
4862 // obsolete form of select
4863 // handles select i1 ... in old bitcode
4865 Value *TrueVal, *FalseVal, *Cond;
4866 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
4867 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
4868 popValue(Record, OpNum, NextValueNo, Type::getInt1Ty(Context), Cond))
4869 return error("Invalid record");
4871 I = SelectInst::Create(Cond, TrueVal, FalseVal);
4872 InstructionList.push_back(I);
4876 case bitc::FUNC_CODE_INST_VSELECT: {// VSELECT: [ty,opval,opval,predty,pred]
4877 // new form of select
4878 // handles select i1 or select [N x i1]
4880 Value *TrueVal, *FalseVal, *Cond;
4881 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
4882 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
4883 getValueTypePair(Record, OpNum, NextValueNo, Cond))
4884 return error("Invalid record");
4886 // select condition can be either i1 or [N x i1]
4887 if (VectorType* vector_type =
4888 dyn_cast<VectorType>(Cond->getType())) {
4890 if (vector_type->getElementType() != Type::getInt1Ty(Context))
4891 return error("Invalid type for value");
4894 if (Cond->getType() != Type::getInt1Ty(Context))
4895 return error("Invalid type for value");
4898 I = SelectInst::Create(Cond, TrueVal, FalseVal);
4899 InstructionList.push_back(I);
4903 case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval]
4906 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
4907 getValueTypePair(Record, OpNum, NextValueNo, Idx))
4908 return error("Invalid record");
4909 if (!Vec->getType()->isVectorTy())
4910 return error("Invalid type for value");
4911 I = ExtractElementInst::Create(Vec, Idx);
4912 InstructionList.push_back(I);
4916 case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval]
4918 Value *Vec, *Elt, *Idx;
4919 if (getValueTypePair(Record, OpNum, NextValueNo, Vec))
4920 return error("Invalid record");
4921 if (!Vec->getType()->isVectorTy())
4922 return error("Invalid type for value");
4923 if (popValue(Record, OpNum, NextValueNo,
4924 cast<VectorType>(Vec->getType())->getElementType(), Elt) ||
4925 getValueTypePair(Record, OpNum, NextValueNo, Idx))
4926 return error("Invalid record");
4927 I = InsertElementInst::Create(Vec, Elt, Idx);
4928 InstructionList.push_back(I);
4932 case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval]
4934 Value *Vec1, *Vec2, *Mask;
4935 if (getValueTypePair(Record, OpNum, NextValueNo, Vec1) ||
4936 popValue(Record, OpNum, NextValueNo, Vec1->getType(), Vec2))
4937 return error("Invalid record");
4939 if (getValueTypePair(Record, OpNum, NextValueNo, Mask))
4940 return error("Invalid record");
4941 if (!Vec1->getType()->isVectorTy() || !Vec2->getType()->isVectorTy())
4942 return error("Invalid type for value");
4943 I = new ShuffleVectorInst(Vec1, Vec2, Mask);
4944 InstructionList.push_back(I);
4948 case bitc::FUNC_CODE_INST_CMP: // CMP: [opty, opval, opval, pred]
4949 // Old form of ICmp/FCmp returning bool
4950 // Existed to differentiate between icmp/fcmp and vicmp/vfcmp which were
4951 // both legal on vectors but had different behaviour.
4952 case bitc::FUNC_CODE_INST_CMP2: { // CMP2: [opty, opval, opval, pred]
4953 // FCmp/ICmp returning bool or vector of bool
4957 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
4958 popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS))
4959 return error("Invalid record");
4961 unsigned PredVal = Record[OpNum];
4962 bool IsFP = LHS->getType()->isFPOrFPVectorTy();
4964 if (IsFP && Record.size() > OpNum+1)
4965 FMF = getDecodedFastMathFlags(Record[++OpNum]);
4967 if (OpNum+1 != Record.size())
4968 return error("Invalid record");
4970 if (LHS->getType()->isFPOrFPVectorTy())
4971 I = new FCmpInst((FCmpInst::Predicate)PredVal, LHS, RHS);
4973 I = new ICmpInst((ICmpInst::Predicate)PredVal, LHS, RHS);
4976 I->setFastMathFlags(FMF);
4977 InstructionList.push_back(I);
4981 case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>]
4983 unsigned Size = Record.size();
4985 I = ReturnInst::Create(Context);
4986 InstructionList.push_back(I);
4991 Value *Op = nullptr;
4992 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
4993 return error("Invalid record");
4994 if (OpNum != Record.size())
4995 return error("Invalid record");
4997 I = ReturnInst::Create(Context, Op);
4998 InstructionList.push_back(I);
5001 case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#]
5002 if (Record.size() != 1 && Record.size() != 3)
5003 return error("Invalid record");
5004 BasicBlock *TrueDest = getBasicBlock(Record[0]);
5006 return error("Invalid record");
5008 if (Record.size() == 1) {
5009 I = BranchInst::Create(TrueDest);
5010 InstructionList.push_back(I);
5013 BasicBlock *FalseDest = getBasicBlock(Record[1]);
5014 Value *Cond = getValue(Record, 2, NextValueNo,
5015 Type::getInt1Ty(Context));
5016 if (!FalseDest || !Cond)
5017 return error("Invalid record");
5018 I = BranchInst::Create(TrueDest, FalseDest, Cond);
5019 InstructionList.push_back(I);
5023 case bitc::FUNC_CODE_INST_CLEANUPRET: { // CLEANUPRET: [val] or [val,bb#]
5024 if (Record.size() != 1 && Record.size() != 2)
5025 return error("Invalid record");
5028 getValue(Record, Idx++, NextValueNo, Type::getTokenTy(Context));
5030 return error("Invalid record");
5031 BasicBlock *UnwindDest = nullptr;
5032 if (Record.size() == 2) {
5033 UnwindDest = getBasicBlock(Record[Idx++]);
5035 return error("Invalid record");
5038 I = CleanupReturnInst::Create(CleanupPad, UnwindDest);
5039 InstructionList.push_back(I);
5042 case bitc::FUNC_CODE_INST_CATCHRET: { // CATCHRET: [val,bb#]
5043 if (Record.size() != 2)
5044 return error("Invalid record");
5047 getValue(Record, Idx++, NextValueNo, Type::getTokenTy(Context));
5049 return error("Invalid record");
5050 BasicBlock *BB = getBasicBlock(Record[Idx++]);
5052 return error("Invalid record");
5054 I = CatchReturnInst::Create(CatchPad, BB);
5055 InstructionList.push_back(I);
5058 case bitc::FUNC_CODE_INST_CATCHSWITCH: { // CATCHSWITCH: [tok,num,(bb)*,bb?]
5059 // We must have, at minimum, the outer scope and the number of arguments.
5060 if (Record.size() < 2)
5061 return error("Invalid record");
5066 getValue(Record, Idx++, NextValueNo, Type::getTokenTy(Context));
5068 unsigned NumHandlers = Record[Idx++];
5070 SmallVector<BasicBlock *, 2> Handlers;
5071 for (unsigned Op = 0; Op != NumHandlers; ++Op) {
5072 BasicBlock *BB = getBasicBlock(Record[Idx++]);
5074 return error("Invalid record");
5075 Handlers.push_back(BB);
5078 BasicBlock *UnwindDest = nullptr;
5079 if (Idx + 1 == Record.size()) {
5080 UnwindDest = getBasicBlock(Record[Idx++]);
5082 return error("Invalid record");
5085 if (Record.size() != Idx)
5086 return error("Invalid record");
5089 CatchSwitchInst::Create(ParentPad, UnwindDest, NumHandlers);
5090 for (BasicBlock *Handler : Handlers)
5091 CatchSwitch->addHandler(Handler);
5093 InstructionList.push_back(I);
5096 case bitc::FUNC_CODE_INST_CATCHPAD:
5097 case bitc::FUNC_CODE_INST_CLEANUPPAD: { // [tok,num,(ty,val)*]
5098 // We must have, at minimum, the outer scope and the number of arguments.
5099 if (Record.size() < 2)
5100 return error("Invalid record");
5105 getValue(Record, Idx++, NextValueNo, Type::getTokenTy(Context));
5107 unsigned NumArgOperands = Record[Idx++];
5109 SmallVector<Value *, 2> Args;
5110 for (unsigned Op = 0; Op != NumArgOperands; ++Op) {
5112 if (getValueTypePair(Record, Idx, NextValueNo, Val))
5113 return error("Invalid record");
5114 Args.push_back(Val);
5117 if (Record.size() != Idx)
5118 return error("Invalid record");
5120 if (BitCode == bitc::FUNC_CODE_INST_CLEANUPPAD)
5121 I = CleanupPadInst::Create(ParentPad, Args);
5123 I = CatchPadInst::Create(ParentPad, Args);
5124 InstructionList.push_back(I);
5127 case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, op0, op1, ...]
5129 if ((Record[0] >> 16) == SWITCH_INST_MAGIC) {
5130 // "New" SwitchInst format with case ranges. The changes to write this
5131 // format were reverted but we still recognize bitcode that uses it.
5132 // Hopefully someday we will have support for case ranges and can use
5133 // this format again.
5135 Type *OpTy = getTypeByID(Record[1]);
5136 unsigned ValueBitWidth = cast<IntegerType>(OpTy)->getBitWidth();
5138 Value *Cond = getValue(Record, 2, NextValueNo, OpTy);
5139 BasicBlock *Default = getBasicBlock(Record[3]);
5140 if (!OpTy || !Cond || !Default)
5141 return error("Invalid record");
5143 unsigned NumCases = Record[4];
5145 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
5146 InstructionList.push_back(SI);
5148 unsigned CurIdx = 5;
5149 for (unsigned i = 0; i != NumCases; ++i) {
5150 SmallVector<ConstantInt*, 1> CaseVals;
5151 unsigned NumItems = Record[CurIdx++];
5152 for (unsigned ci = 0; ci != NumItems; ++ci) {
5153 bool isSingleNumber = Record[CurIdx++];
5156 unsigned ActiveWords = 1;
5157 if (ValueBitWidth > 64)
5158 ActiveWords = Record[CurIdx++];
5159 Low = readWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords),
5161 CurIdx += ActiveWords;
5163 if (!isSingleNumber) {
5165 if (ValueBitWidth > 64)
5166 ActiveWords = Record[CurIdx++];
5167 APInt High = readWideAPInt(
5168 makeArrayRef(&Record[CurIdx], ActiveWords), ValueBitWidth);
5169 CurIdx += ActiveWords;
5171 // FIXME: It is not clear whether values in the range should be
5172 // compared as signed or unsigned values. The partially
5173 // implemented changes that used this format in the past used
5174 // unsigned comparisons.
5175 for ( ; Low.ule(High); ++Low)
5176 CaseVals.push_back(ConstantInt::get(Context, Low));
5178 CaseVals.push_back(ConstantInt::get(Context, Low));
5180 BasicBlock *DestBB = getBasicBlock(Record[CurIdx++]);
5181 for (SmallVector<ConstantInt*, 1>::iterator cvi = CaseVals.begin(),
5182 cve = CaseVals.end(); cvi != cve; ++cvi)
5183 SI->addCase(*cvi, DestBB);
5189 // Old SwitchInst format without case ranges.
5191 if (Record.size() < 3 || (Record.size() & 1) == 0)
5192 return error("Invalid record");
5193 Type *OpTy = getTypeByID(Record[0]);
5194 Value *Cond = getValue(Record, 1, NextValueNo, OpTy);
5195 BasicBlock *Default = getBasicBlock(Record[2]);
5196 if (!OpTy || !Cond || !Default)
5197 return error("Invalid record");
5198 unsigned NumCases = (Record.size()-3)/2;
5199 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
5200 InstructionList.push_back(SI);
5201 for (unsigned i = 0, e = NumCases; i != e; ++i) {
5202 ConstantInt *CaseVal =
5203 dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy));
5204 BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]);
5205 if (!CaseVal || !DestBB) {
5207 return error("Invalid record");
5209 SI->addCase(CaseVal, DestBB);
5214 case bitc::FUNC_CODE_INST_INDIRECTBR: { // INDIRECTBR: [opty, op0, op1, ...]
5215 if (Record.size() < 2)
5216 return error("Invalid record");
5217 Type *OpTy = getTypeByID(Record[0]);
5218 Value *Address = getValue(Record, 1, NextValueNo, OpTy);
5219 if (!OpTy || !Address)
5220 return error("Invalid record");
5221 unsigned NumDests = Record.size()-2;
5222 IndirectBrInst *IBI = IndirectBrInst::Create(Address, NumDests);
5223 InstructionList.push_back(IBI);
5224 for (unsigned i = 0, e = NumDests; i != e; ++i) {
5225 if (BasicBlock *DestBB = getBasicBlock(Record[2+i])) {
5226 IBI->addDestination(DestBB);
5229 return error("Invalid record");
5236 case bitc::FUNC_CODE_INST_INVOKE: {
5237 // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...]
5238 if (Record.size() < 4)
5239 return error("Invalid record");
5241 AttributeSet PAL = getAttributes(Record[OpNum++]);
5242 unsigned CCInfo = Record[OpNum++];
5243 BasicBlock *NormalBB = getBasicBlock(Record[OpNum++]);
5244 BasicBlock *UnwindBB = getBasicBlock(Record[OpNum++]);
5246 FunctionType *FTy = nullptr;
5247 if (CCInfo >> 13 & 1 &&
5248 !(FTy = dyn_cast<FunctionType>(getTypeByID(Record[OpNum++]))))
5249 return error("Explicit invoke type is not a function type");
5252 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
5253 return error("Invalid record");
5255 PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType());
5257 return error("Callee is not a pointer");
5259 FTy = dyn_cast<FunctionType>(CalleeTy->getElementType());
5261 return error("Callee is not of pointer to function type");
5262 } else if (CalleeTy->getElementType() != FTy)
5263 return error("Explicit invoke type does not match pointee type of "
5265 if (Record.size() < FTy->getNumParams() + OpNum)
5266 return error("Insufficient operands to call");
5268 SmallVector<Value*, 16> Ops;
5269 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
5270 Ops.push_back(getValue(Record, OpNum, NextValueNo,
5271 FTy->getParamType(i)));
5273 return error("Invalid record");
5276 if (!FTy->isVarArg()) {
5277 if (Record.size() != OpNum)
5278 return error("Invalid record");
5280 // Read type/value pairs for varargs params.
5281 while (OpNum != Record.size()) {
5283 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
5284 return error("Invalid record");
5289 I = InvokeInst::Create(Callee, NormalBB, UnwindBB, Ops, OperandBundles);
5290 OperandBundles.clear();
5291 InstructionList.push_back(I);
5292 cast<InvokeInst>(I)->setCallingConv(
5293 static_cast<CallingConv::ID>(CallingConv::MaxID & CCInfo));
5294 cast<InvokeInst>(I)->setAttributes(PAL);
5297 case bitc::FUNC_CODE_INST_RESUME: { // RESUME: [opval]
5299 Value *Val = nullptr;
5300 if (getValueTypePair(Record, Idx, NextValueNo, Val))
5301 return error("Invalid record");
5302 I = ResumeInst::Create(Val);
5303 InstructionList.push_back(I);
5306 case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE
5307 I = new UnreachableInst(Context);
5308 InstructionList.push_back(I);
5310 case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...]
5311 if (Record.size() < 1 || ((Record.size()-1)&1))
5312 return error("Invalid record");
5313 Type *Ty = getTypeByID(Record[0]);
5315 return error("Invalid record");
5317 PHINode *PN = PHINode::Create(Ty, (Record.size()-1)/2);
5318 InstructionList.push_back(PN);
5320 for (unsigned i = 0, e = Record.size()-1; i != e; i += 2) {
5322 // With the new function encoding, it is possible that operands have
5323 // negative IDs (for forward references). Use a signed VBR
5324 // representation to keep the encoding small.
5326 V = getValueSigned(Record, 1+i, NextValueNo, Ty);
5328 V = getValue(Record, 1+i, NextValueNo, Ty);
5329 BasicBlock *BB = getBasicBlock(Record[2+i]);
5331 return error("Invalid record");
5332 PN->addIncoming(V, BB);
5338 case bitc::FUNC_CODE_INST_LANDINGPAD:
5339 case bitc::FUNC_CODE_INST_LANDINGPAD_OLD: {
5340 // LANDINGPAD: [ty, val, val, num, (id0,val0 ...)?]
5342 if (BitCode == bitc::FUNC_CODE_INST_LANDINGPAD) {
5343 if (Record.size() < 3)
5344 return error("Invalid record");
5346 assert(BitCode == bitc::FUNC_CODE_INST_LANDINGPAD_OLD);
5347 if (Record.size() < 4)
5348 return error("Invalid record");
5350 Type *Ty = getTypeByID(Record[Idx++]);
5352 return error("Invalid record");
5353 if (BitCode == bitc::FUNC_CODE_INST_LANDINGPAD_OLD) {
5354 Value *PersFn = nullptr;
5355 if (getValueTypePair(Record, Idx, NextValueNo, PersFn))
5356 return error("Invalid record");
5358 if (!F->hasPersonalityFn())
5359 F->setPersonalityFn(cast<Constant>(PersFn));
5360 else if (F->getPersonalityFn() != cast<Constant>(PersFn))
5361 return error("Personality function mismatch");
5364 bool IsCleanup = !!Record[Idx++];
5365 unsigned NumClauses = Record[Idx++];
5366 LandingPadInst *LP = LandingPadInst::Create(Ty, NumClauses);
5367 LP->setCleanup(IsCleanup);
5368 for (unsigned J = 0; J != NumClauses; ++J) {
5369 LandingPadInst::ClauseType CT =
5370 LandingPadInst::ClauseType(Record[Idx++]); (void)CT;
5373 if (getValueTypePair(Record, Idx, NextValueNo, Val)) {
5375 return error("Invalid record");
5378 assert((CT != LandingPadInst::Catch ||
5379 !isa<ArrayType>(Val->getType())) &&
5380 "Catch clause has a invalid type!");
5381 assert((CT != LandingPadInst::Filter ||
5382 isa<ArrayType>(Val->getType())) &&
5383 "Filter clause has invalid type!");
5384 LP->addClause(cast<Constant>(Val));
5388 InstructionList.push_back(I);
5392 case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, opty, op, align]
5393 if (Record.size() != 4)
5394 return error("Invalid record");
5395 uint64_t AlignRecord = Record[3];
5396 const uint64_t InAllocaMask = uint64_t(1) << 5;
5397 const uint64_t ExplicitTypeMask = uint64_t(1) << 6;
5398 const uint64_t SwiftErrorMask = uint64_t(1) << 7;
5399 const uint64_t FlagMask = InAllocaMask | ExplicitTypeMask |
5401 bool InAlloca = AlignRecord & InAllocaMask;
5402 bool SwiftError = AlignRecord & SwiftErrorMask;
5403 Type *Ty = getTypeByID(Record[0]);
5404 if ((AlignRecord & ExplicitTypeMask) == 0) {
5405 auto *PTy = dyn_cast_or_null<PointerType>(Ty);
5407 return error("Old-style alloca with a non-pointer type");
5408 Ty = PTy->getElementType();
5410 Type *OpTy = getTypeByID(Record[1]);
5411 Value *Size = getFnValueByID(Record[2], OpTy);
5413 if (std::error_code EC =
5414 parseAlignmentValue(AlignRecord & ~FlagMask, Align)) {
5418 return error("Invalid record");
5419 AllocaInst *AI = new AllocaInst(Ty, Size, Align);
5420 AI->setUsedWithInAlloca(InAlloca);
5421 AI->setSwiftError(SwiftError);
5423 InstructionList.push_back(I);
5426 case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol]
5429 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
5430 (OpNum + 2 != Record.size() && OpNum + 3 != Record.size()))
5431 return error("Invalid record");
5434 if (OpNum + 3 == Record.size())
5435 Ty = getTypeByID(Record[OpNum++]);
5436 if (std::error_code EC = typeCheckLoadStoreInst(Ty, Op->getType()))
5439 Ty = cast<PointerType>(Op->getType())->getElementType();
5442 if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align))
5444 I = new LoadInst(Ty, Op, "", Record[OpNum + 1], Align);
5446 InstructionList.push_back(I);
5449 case bitc::FUNC_CODE_INST_LOADATOMIC: {
5450 // LOADATOMIC: [opty, op, align, vol, ordering, synchscope]
5453 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
5454 (OpNum + 4 != Record.size() && OpNum + 5 != Record.size()))
5455 return error("Invalid record");
5458 if (OpNum + 5 == Record.size())
5459 Ty = getTypeByID(Record[OpNum++]);
5460 if (std::error_code EC = typeCheckLoadStoreInst(Ty, Op->getType()))
5463 Ty = cast<PointerType>(Op->getType())->getElementType();
5465 AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]);
5466 if (Ordering == AtomicOrdering::NotAtomic ||
5467 Ordering == AtomicOrdering::Release ||
5468 Ordering == AtomicOrdering::AcquireRelease)
5469 return error("Invalid record");
5470 if (Ordering != AtomicOrdering::NotAtomic && Record[OpNum] == 0)
5471 return error("Invalid record");
5472 SynchronizationScope SynchScope = getDecodedSynchScope(Record[OpNum + 3]);
5475 if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align))
5477 I = new LoadInst(Op, "", Record[OpNum+1], Align, Ordering, SynchScope);
5479 InstructionList.push_back(I);
5482 case bitc::FUNC_CODE_INST_STORE:
5483 case bitc::FUNC_CODE_INST_STORE_OLD: { // STORE2:[ptrty, ptr, val, align, vol]
5486 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
5487 (BitCode == bitc::FUNC_CODE_INST_STORE
5488 ? getValueTypePair(Record, OpNum, NextValueNo, Val)
5489 : popValue(Record, OpNum, NextValueNo,
5490 cast<PointerType>(Ptr->getType())->getElementType(),
5492 OpNum + 2 != Record.size())
5493 return error("Invalid record");
5495 if (std::error_code EC =
5496 typeCheckLoadStoreInst(Val->getType(), Ptr->getType()))
5499 if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align))
5501 I = new StoreInst(Val, Ptr, Record[OpNum+1], Align);
5502 InstructionList.push_back(I);
5505 case bitc::FUNC_CODE_INST_STOREATOMIC:
5506 case bitc::FUNC_CODE_INST_STOREATOMIC_OLD: {
5507 // STOREATOMIC: [ptrty, ptr, val, align, vol, ordering, synchscope]
5510 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
5511 !isa<PointerType>(Ptr->getType()) ||
5512 (BitCode == bitc::FUNC_CODE_INST_STOREATOMIC
5513 ? getValueTypePair(Record, OpNum, NextValueNo, Val)
5514 : popValue(Record, OpNum, NextValueNo,
5515 cast<PointerType>(Ptr->getType())->getElementType(),
5517 OpNum + 4 != Record.size())
5518 return error("Invalid record");
5520 if (std::error_code EC =
5521 typeCheckLoadStoreInst(Val->getType(), Ptr->getType()))
5523 AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]);
5524 if (Ordering == AtomicOrdering::NotAtomic ||
5525 Ordering == AtomicOrdering::Acquire ||
5526 Ordering == AtomicOrdering::AcquireRelease)
5527 return error("Invalid record");
5528 SynchronizationScope SynchScope = getDecodedSynchScope(Record[OpNum + 3]);
5529 if (Ordering != AtomicOrdering::NotAtomic && Record[OpNum] == 0)
5530 return error("Invalid record");
5533 if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align))
5535 I = new StoreInst(Val, Ptr, Record[OpNum+1], Align, Ordering, SynchScope);
5536 InstructionList.push_back(I);
5539 case bitc::FUNC_CODE_INST_CMPXCHG_OLD:
5540 case bitc::FUNC_CODE_INST_CMPXCHG: {
5541 // CMPXCHG:[ptrty, ptr, cmp, new, vol, successordering, synchscope,
5542 // failureordering?, isweak?]
5544 Value *Ptr, *Cmp, *New;
5545 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
5546 (BitCode == bitc::FUNC_CODE_INST_CMPXCHG
5547 ? getValueTypePair(Record, OpNum, NextValueNo, Cmp)
5548 : popValue(Record, OpNum, NextValueNo,
5549 cast<PointerType>(Ptr->getType())->getElementType(),
5551 popValue(Record, OpNum, NextValueNo, Cmp->getType(), New) ||
5552 Record.size() < OpNum + 3 || Record.size() > OpNum + 5)
5553 return error("Invalid record");
5554 AtomicOrdering SuccessOrdering = getDecodedOrdering(Record[OpNum + 1]);
5555 if (SuccessOrdering == AtomicOrdering::NotAtomic ||
5556 SuccessOrdering == AtomicOrdering::Unordered)
5557 return error("Invalid record");
5558 SynchronizationScope SynchScope = getDecodedSynchScope(Record[OpNum + 2]);
5560 if (std::error_code EC =
5561 typeCheckLoadStoreInst(Cmp->getType(), Ptr->getType()))
5563 AtomicOrdering FailureOrdering;
5564 if (Record.size() < 7)
5566 AtomicCmpXchgInst::getStrongestFailureOrdering(SuccessOrdering);
5568 FailureOrdering = getDecodedOrdering(Record[OpNum + 3]);
5570 I = new AtomicCmpXchgInst(Ptr, Cmp, New, SuccessOrdering, FailureOrdering,
5572 cast<AtomicCmpXchgInst>(I)->setVolatile(Record[OpNum]);
5574 if (Record.size() < 8) {
5575 // Before weak cmpxchgs existed, the instruction simply returned the
5576 // value loaded from memory, so bitcode files from that era will be
5577 // expecting the first component of a modern cmpxchg.
5578 CurBB->getInstList().push_back(I);
5579 I = ExtractValueInst::Create(I, 0);
5581 cast<AtomicCmpXchgInst>(I)->setWeak(Record[OpNum+4]);
5584 InstructionList.push_back(I);
5587 case bitc::FUNC_CODE_INST_ATOMICRMW: {
5588 // ATOMICRMW:[ptrty, ptr, val, op, vol, ordering, synchscope]
5591 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
5592 !isa<PointerType>(Ptr->getType()) ||
5593 popValue(Record, OpNum, NextValueNo,
5594 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
5595 OpNum+4 != Record.size())
5596 return error("Invalid record");
5597 AtomicRMWInst::BinOp Operation = getDecodedRMWOperation(Record[OpNum]);
5598 if (Operation < AtomicRMWInst::FIRST_BINOP ||
5599 Operation > AtomicRMWInst::LAST_BINOP)
5600 return error("Invalid record");
5601 AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]);
5602 if (Ordering == AtomicOrdering::NotAtomic ||
5603 Ordering == AtomicOrdering::Unordered)
5604 return error("Invalid record");
5605 SynchronizationScope SynchScope = getDecodedSynchScope(Record[OpNum + 3]);
5606 I = new AtomicRMWInst(Operation, Ptr, Val, Ordering, SynchScope);
5607 cast<AtomicRMWInst>(I)->setVolatile(Record[OpNum+1]);
5608 InstructionList.push_back(I);
5611 case bitc::FUNC_CODE_INST_FENCE: { // FENCE:[ordering, synchscope]
5612 if (2 != Record.size())
5613 return error("Invalid record");
5614 AtomicOrdering Ordering = getDecodedOrdering(Record[0]);
5615 if (Ordering == AtomicOrdering::NotAtomic ||
5616 Ordering == AtomicOrdering::Unordered ||
5617 Ordering == AtomicOrdering::Monotonic)
5618 return error("Invalid record");
5619 SynchronizationScope SynchScope = getDecodedSynchScope(Record[1]);
5620 I = new FenceInst(Context, Ordering, SynchScope);
5621 InstructionList.push_back(I);
5624 case bitc::FUNC_CODE_INST_CALL: {
5625 // CALL: [paramattrs, cc, fmf, fnty, fnid, arg0, arg1...]
5626 if (Record.size() < 3)
5627 return error("Invalid record");
5630 AttributeSet PAL = getAttributes(Record[OpNum++]);
5631 unsigned CCInfo = Record[OpNum++];
5634 if ((CCInfo >> bitc::CALL_FMF) & 1) {
5635 FMF = getDecodedFastMathFlags(Record[OpNum++]);
5637 return error("Fast math flags indicator set for call with no FMF");
5640 FunctionType *FTy = nullptr;
5641 if (CCInfo >> bitc::CALL_EXPLICIT_TYPE & 1 &&
5642 !(FTy = dyn_cast<FunctionType>(getTypeByID(Record[OpNum++]))))
5643 return error("Explicit call type is not a function type");
5646 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
5647 return error("Invalid record");
5649 PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());
5651 return error("Callee is not a pointer type");
5653 FTy = dyn_cast<FunctionType>(OpTy->getElementType());
5655 return error("Callee is not of pointer to function type");
5656 } else if (OpTy->getElementType() != FTy)
5657 return error("Explicit call type does not match pointee type of "
5659 if (Record.size() < FTy->getNumParams() + OpNum)
5660 return error("Insufficient operands to call");
5662 SmallVector<Value*, 16> Args;
5663 // Read the fixed params.
5664 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
5665 if (FTy->getParamType(i)->isLabelTy())
5666 Args.push_back(getBasicBlock(Record[OpNum]));
5668 Args.push_back(getValue(Record, OpNum, NextValueNo,
5669 FTy->getParamType(i)));
5671 return error("Invalid record");
5674 // Read type/value pairs for varargs params.
5675 if (!FTy->isVarArg()) {
5676 if (OpNum != Record.size())
5677 return error("Invalid record");
5679 while (OpNum != Record.size()) {
5681 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
5682 return error("Invalid record");
5687 I = CallInst::Create(FTy, Callee, Args, OperandBundles);
5688 OperandBundles.clear();
5689 InstructionList.push_back(I);
5690 cast<CallInst>(I)->setCallingConv(
5691 static_cast<CallingConv::ID>((0x7ff & CCInfo) >> bitc::CALL_CCONV));
5692 CallInst::TailCallKind TCK = CallInst::TCK_None;
5693 if (CCInfo & 1 << bitc::CALL_TAIL)
5694 TCK = CallInst::TCK_Tail;
5695 if (CCInfo & (1 << bitc::CALL_MUSTTAIL))
5696 TCK = CallInst::TCK_MustTail;
5697 if (CCInfo & (1 << bitc::CALL_NOTAIL))
5698 TCK = CallInst::TCK_NoTail;
5699 cast<CallInst>(I)->setTailCallKind(TCK);
5700 cast<CallInst>(I)->setAttributes(PAL);
5702 if (!isa<FPMathOperator>(I))
5703 return error("Fast-math-flags specified for call without "
5704 "floating-point scalar or vector return type");
5705 I->setFastMathFlags(FMF);
5709 case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty]
5710 if (Record.size() < 3)
5711 return error("Invalid record");
5712 Type *OpTy = getTypeByID(Record[0]);
5713 Value *Op = getValue(Record, 1, NextValueNo, OpTy);
5714 Type *ResTy = getTypeByID(Record[2]);
5715 if (!OpTy || !Op || !ResTy)
5716 return error("Invalid record");
5717 I = new VAArgInst(Op, ResTy);
5718 InstructionList.push_back(I);
5722 case bitc::FUNC_CODE_OPERAND_BUNDLE: {
5723 // A call or an invoke can be optionally prefixed with some variable
5724 // number of operand bundle blocks. These blocks are read into
5725 // OperandBundles and consumed at the next call or invoke instruction.
5727 if (Record.size() < 1 || Record[0] >= BundleTags.size())
5728 return error("Invalid record");
5730 std::vector<Value *> Inputs;
5733 while (OpNum != Record.size()) {
5735 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
5736 return error("Invalid record");
5737 Inputs.push_back(Op);
5740 OperandBundles.emplace_back(BundleTags[Record[0]], std::move(Inputs));
5745 // Add instruction to end of current BB. If there is no current BB, reject
5749 return error("Invalid instruction with no BB");
5751 if (!OperandBundles.empty()) {
5753 return error("Operand bundles found with no consumer");
5755 CurBB->getInstList().push_back(I);
5757 // If this was a terminator instruction, move to the next block.
5758 if (isa<TerminatorInst>(I)) {
5760 CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : nullptr;
5763 // Non-void values get registered in the value table for future use.
5764 if (I && !I->getType()->isVoidTy())
5765 ValueList.assignValue(I, NextValueNo++);
5770 if (!OperandBundles.empty())
5771 return error("Operand bundles found with no consumer");
5773 // Check the function list for unresolved values.
5774 if (Argument *A = dyn_cast<Argument>(ValueList.back())) {
5775 if (!A->getParent()) {
5776 // We found at least one unresolved value. Nuke them all to avoid leaks.
5777 for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){
5778 if ((A = dyn_cast_or_null<Argument>(ValueList[i])) && !A->getParent()) {
5779 A->replaceAllUsesWith(UndefValue::get(A->getType()));
5783 return error("Never resolved value found in function");
5787 // Unexpected unresolved metadata about to be dropped.
5788 if (MetadataList.hasFwdRefs())
5789 return error("Invalid function metadata: outgoing forward refs");
5791 // Trim the value list down to the size it was before we parsed this function.
5792 ValueList.shrinkTo(ModuleValueListSize);
5793 MetadataList.shrinkTo(ModuleMetadataListSize);
5794 std::vector<BasicBlock*>().swap(FunctionBBs);
5795 return std::error_code();
5798 /// Find the function body in the bitcode stream
5799 std::error_code BitcodeReader::findFunctionInStream(
5801 DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator) {
5802 while (DeferredFunctionInfoIterator->second == 0) {
5803 // This is the fallback handling for the old format bitcode that
5804 // didn't contain the function index in the VST, or when we have
5805 // an anonymous function which would not have a VST entry.
5806 // Assert that we have one of those two cases.
5807 assert(VSTOffset == 0 || !F->hasName());
5808 // Parse the next body in the stream and set its position in the
5809 // DeferredFunctionInfo map.
5810 if (std::error_code EC = rememberAndSkipFunctionBodies())
5813 return std::error_code();
5816 //===----------------------------------------------------------------------===//
5817 // GVMaterializer implementation
5818 //===----------------------------------------------------------------------===//
5820 void BitcodeReader::releaseBuffer() { Buffer.release(); }
5822 std::error_code BitcodeReader::materialize(GlobalValue *GV) {
5823 Function *F = dyn_cast<Function>(GV);
5824 // If it's not a function or is already material, ignore the request.
5825 if (!F || !F->isMaterializable())
5826 return std::error_code();
5828 DenseMap<Function*, uint64_t>::iterator DFII = DeferredFunctionInfo.find(F);
5829 assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!");
5830 // If its position is recorded as 0, its body is somewhere in the stream
5831 // but we haven't seen it yet.
5832 if (DFII->second == 0)
5833 if (std::error_code EC = findFunctionInStream(F, DFII))
5836 // Materialize metadata before parsing any function bodies.
5837 if (std::error_code EC = materializeMetadata())
5840 // Move the bit stream to the saved position of the deferred function body.
5841 Stream.JumpToBit(DFII->second);
5843 if (std::error_code EC = parseFunctionBody(F))
5845 F->setIsMaterializable(false);
5850 // Upgrade any old intrinsic calls in the function.
5851 for (auto &I : UpgradedIntrinsics) {
5852 for (auto UI = I.first->materialized_user_begin(), UE = I.first->user_end();
5856 if (CallInst *CI = dyn_cast<CallInst>(U))
5857 UpgradeIntrinsicCall(CI, I.second);
5861 // Update calls to the remangled intrinsics
5862 for (auto &I : RemangledIntrinsics)
5863 for (auto UI = I.first->materialized_user_begin(), UE = I.first->user_end();
5865 // Don't expect any other users than call sites
5866 CallSite(*UI++).setCalledFunction(I.second);
5868 // Finish fn->subprogram upgrade for materialized functions.
5869 if (DISubprogram *SP = FunctionsWithSPs.lookup(F))
5870 F->setSubprogram(SP);
5872 // Bring in any functions that this function forward-referenced via
5874 return materializeForwardReferencedFunctions();
5877 std::error_code BitcodeReader::materializeModule() {
5878 if (std::error_code EC = materializeMetadata())
5881 // Promise to materialize all forward references.
5882 WillMaterializeAllForwardRefs = true;
5884 // Iterate over the module, deserializing any functions that are still on
5886 for (Function &F : *TheModule) {
5887 if (std::error_code EC = materialize(&F))
5890 // At this point, if there are any function bodies, parse the rest of
5891 // the bits in the module past the last function block we have recorded
5892 // through either lazy scanning or the VST.
5893 if (LastFunctionBlockBit || NextUnreadBit)
5894 parseModule(LastFunctionBlockBit > NextUnreadBit ? LastFunctionBlockBit
5897 // Check that all block address forward references got resolved (as we
5899 if (!BasicBlockFwdRefs.empty())
5900 return error("Never resolved function from blockaddress");
5902 // Upgrade any intrinsic calls that slipped through (should not happen!) and
5903 // delete the old functions to clean up. We can't do this unless the entire
5904 // module is materialized because there could always be another function body
5905 // with calls to the old function.
5906 for (auto &I : UpgradedIntrinsics) {
5907 for (auto *U : I.first->users()) {
5908 if (CallInst *CI = dyn_cast<CallInst>(U))
5909 UpgradeIntrinsicCall(CI, I.second);
5911 if (!I.first->use_empty())
5912 I.first->replaceAllUsesWith(I.second);
5913 I.first->eraseFromParent();
5915 UpgradedIntrinsics.clear();
5916 // Do the same for remangled intrinsics
5917 for (auto &I : RemangledIntrinsics) {
5918 I.first->replaceAllUsesWith(I.second);
5919 I.first->eraseFromParent();
5921 RemangledIntrinsics.clear();
5923 UpgradeDebugInfo(*TheModule);
5925 UpgradeModuleFlags(*TheModule);
5926 return std::error_code();
5929 std::vector<StructType *> BitcodeReader::getIdentifiedStructTypes() const {
5930 return IdentifiedStructTypes;
5933 std::error_code ModuleSummaryIndexBitcodeReader::error(const Twine &Message) {
5934 return ::error(DiagnosticHandler,
5935 make_error_code(BitcodeError::CorruptedBitcode), Message);
5938 ModuleSummaryIndexBitcodeReader::ModuleSummaryIndexBitcodeReader(
5939 MemoryBuffer *Buffer, DiagnosticHandlerFunction DiagnosticHandler,
5940 bool CheckGlobalValSummaryPresenceOnly)
5941 : BitcodeReaderBase(Buffer), DiagnosticHandler(std::move(DiagnosticHandler)),
5942 CheckGlobalValSummaryPresenceOnly(CheckGlobalValSummaryPresenceOnly) {}
5944 void ModuleSummaryIndexBitcodeReader::freeState() { Buffer = nullptr; }
5946 void ModuleSummaryIndexBitcodeReader::releaseBuffer() { Buffer.release(); }
5948 std::pair<GlobalValue::GUID, GlobalValue::GUID>
5949 ModuleSummaryIndexBitcodeReader::getGUIDFromValueId(unsigned ValueId) {
5950 auto VGI = ValueIdToCallGraphGUIDMap.find(ValueId);
5951 assert(VGI != ValueIdToCallGraphGUIDMap.end());
5955 // Specialized value symbol table parser used when reading module index
5956 // blocks where we don't actually create global values. The parsed information
5957 // is saved in the bitcode reader for use when later parsing summaries.
5958 std::error_code ModuleSummaryIndexBitcodeReader::parseValueSymbolTable(
5960 DenseMap<unsigned, GlobalValue::LinkageTypes> &ValueIdToLinkageMap) {
5961 assert(Offset > 0 && "Expected non-zero VST offset");
5962 uint64_t CurrentBit = jumpToValueSymbolTable(Offset, Stream);
5964 if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
5965 return error("Invalid record");
5967 SmallVector<uint64_t, 64> Record;
5969 // Read all the records for this value table.
5970 SmallString<128> ValueName;
5973 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
5975 switch (Entry.Kind) {
5976 case BitstreamEntry::SubBlock: // Handled for us already.
5977 case BitstreamEntry::Error:
5978 return error("Malformed block");
5979 case BitstreamEntry::EndBlock:
5980 // Done parsing VST, jump back to wherever we came from.
5981 Stream.JumpToBit(CurrentBit);
5982 return std::error_code();
5983 case BitstreamEntry::Record:
5984 // The interesting case.
5990 switch (Stream.readRecord(Entry.ID, Record)) {
5991 default: // Default behavior: ignore (e.g. VST_CODE_BBENTRY records).
5993 case bitc::VST_CODE_ENTRY: { // VST_CODE_ENTRY: [valueid, namechar x N]
5994 if (convertToString(Record, 1, ValueName))
5995 return error("Invalid record");
5996 unsigned ValueID = Record[0];
5997 assert(!SourceFileName.empty());
5998 auto VLI = ValueIdToLinkageMap.find(ValueID);
5999 assert(VLI != ValueIdToLinkageMap.end() &&
6000 "No linkage found for VST entry?");
6001 auto Linkage = VLI->second;
6002 std::string GlobalId =
6003 GlobalValue::getGlobalIdentifier(ValueName, Linkage, SourceFileName);
6004 auto ValueGUID = GlobalValue::getGUID(GlobalId);
6005 auto OriginalNameID = ValueGUID;
6006 if (GlobalValue::isLocalLinkage(Linkage))
6007 OriginalNameID = GlobalValue::getGUID(ValueName);
6008 if (PrintSummaryGUIDs)
6009 dbgs() << "GUID " << ValueGUID << "(" << OriginalNameID << ") is "
6010 << ValueName << "\n";
6011 ValueIdToCallGraphGUIDMap[ValueID] =
6012 std::make_pair(ValueGUID, OriginalNameID);
6016 case bitc::VST_CODE_FNENTRY: {
6017 // VST_CODE_FNENTRY: [valueid, offset, namechar x N]
6018 if (convertToString(Record, 2, ValueName))
6019 return error("Invalid record");
6020 unsigned ValueID = Record[0];
6021 assert(!SourceFileName.empty());
6022 auto VLI = ValueIdToLinkageMap.find(ValueID);
6023 assert(VLI != ValueIdToLinkageMap.end() &&
6024 "No linkage found for VST entry?");
6025 auto Linkage = VLI->second;
6026 std::string FunctionGlobalId = GlobalValue::getGlobalIdentifier(
6027 ValueName, VLI->second, SourceFileName);
6028 auto FunctionGUID = GlobalValue::getGUID(FunctionGlobalId);
6029 auto OriginalNameID = FunctionGUID;
6030 if (GlobalValue::isLocalLinkage(Linkage))
6031 OriginalNameID = GlobalValue::getGUID(ValueName);
6032 if (PrintSummaryGUIDs)
6033 dbgs() << "GUID " << FunctionGUID << "(" << OriginalNameID << ") is "
6034 << ValueName << "\n";
6035 ValueIdToCallGraphGUIDMap[ValueID] =
6036 std::make_pair(FunctionGUID, OriginalNameID);
6041 case bitc::VST_CODE_COMBINED_ENTRY: {
6042 // VST_CODE_COMBINED_ENTRY: [valueid, refguid]
6043 unsigned ValueID = Record[0];
6044 GlobalValue::GUID RefGUID = Record[1];
6045 // The "original name", which is the second value of the pair will be
6046 // overriden later by a FS_COMBINED_ORIGINAL_NAME in the combined index.
6047 ValueIdToCallGraphGUIDMap[ValueID] = std::make_pair(RefGUID, RefGUID);
6054 // Parse just the blocks needed for building the index out of the module.
6055 // At the end of this routine the module Index is populated with a map
6056 // from global value id to GlobalValueSummary objects.
6057 std::error_code ModuleSummaryIndexBitcodeReader::parseModule() {
6058 if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
6059 return error("Invalid record");
6061 SmallVector<uint64_t, 64> Record;
6062 DenseMap<unsigned, GlobalValue::LinkageTypes> ValueIdToLinkageMap;
6063 unsigned ValueId = 0;
6065 // Read the index for this module.
6067 BitstreamEntry Entry = Stream.advance();
6069 switch (Entry.Kind) {
6070 case BitstreamEntry::Error:
6071 return error("Malformed block");
6072 case BitstreamEntry::EndBlock:
6073 return std::error_code();
6075 case BitstreamEntry::SubBlock:
6076 if (CheckGlobalValSummaryPresenceOnly) {
6077 if (Entry.ID == bitc::GLOBALVAL_SUMMARY_BLOCK_ID) {
6078 SeenGlobalValSummary = true;
6079 // No need to parse the rest since we found the summary.
6080 return std::error_code();
6082 if (Stream.SkipBlock())
6083 return error("Invalid record");
6087 default: // Skip unknown content.
6088 if (Stream.SkipBlock())
6089 return error("Invalid record");
6091 case bitc::BLOCKINFO_BLOCK_ID:
6092 // Need to parse these to get abbrev ids (e.g. for VST)
6093 if (Stream.ReadBlockInfoBlock())
6094 return error("Malformed block");
6096 case bitc::VALUE_SYMTAB_BLOCK_ID:
6097 // Should have been parsed earlier via VSTOffset, unless there
6098 // is no summary section.
6099 assert(((SeenValueSymbolTable && VSTOffset > 0) ||
6100 !SeenGlobalValSummary) &&
6101 "Expected early VST parse via VSTOffset record");
6102 if (Stream.SkipBlock())
6103 return error("Invalid record");
6105 case bitc::GLOBALVAL_SUMMARY_BLOCK_ID:
6106 assert(!SeenValueSymbolTable &&
6107 "Already read VST when parsing summary block?");
6108 // We might not have a VST if there were no values in the
6109 // summary. An empty summary block generated when we are
6110 // performing ThinLTO compiles so we don't later invoke
6111 // the regular LTO process on them.
6112 if (VSTOffset > 0) {
6113 if (std::error_code EC =
6114 parseValueSymbolTable(VSTOffset, ValueIdToLinkageMap))
6116 SeenValueSymbolTable = true;
6118 SeenGlobalValSummary = true;
6119 if (std::error_code EC = parseEntireSummary())
6122 case bitc::MODULE_STRTAB_BLOCK_ID:
6123 if (std::error_code EC = parseModuleStringTable())
6129 case BitstreamEntry::Record: {
6131 auto BitCode = Stream.readRecord(Entry.ID, Record);
6134 break; // Default behavior, ignore unknown content.
6135 /// MODULE_CODE_SOURCE_FILENAME: [namechar x N]
6136 case bitc::MODULE_CODE_SOURCE_FILENAME: {
6137 SmallString<128> ValueName;
6138 if (convertToString(Record, 0, ValueName))
6139 return error("Invalid record");
6140 SourceFileName = ValueName.c_str();
6143 /// MODULE_CODE_HASH: [5*i32]
6144 case bitc::MODULE_CODE_HASH: {
6145 if (Record.size() != 5)
6146 return error("Invalid hash length " + Twine(Record.size()).str());
6149 if (TheIndex->modulePaths().empty())
6150 // We always seed the index with the module.
6151 TheIndex->addModulePath(Buffer->getBufferIdentifier(), 0);
6152 if (TheIndex->modulePaths().size() != 1)
6153 return error("Don't expect multiple modules defined?");
6154 auto &Hash = TheIndex->modulePaths().begin()->second.second;
6156 for (auto &Val : Record) {
6157 assert(!(Val >> 32) && "Unexpected high bits set");
6162 /// MODULE_CODE_VSTOFFSET: [offset]
6163 case bitc::MODULE_CODE_VSTOFFSET:
6164 if (Record.size() < 1)
6165 return error("Invalid record");
6166 VSTOffset = Record[0];
6168 // GLOBALVAR: [pointer type, isconst, initid,
6169 // linkage, alignment, section, visibility, threadlocal,
6170 // unnamed_addr, externally_initialized, dllstorageclass,
6172 case bitc::MODULE_CODE_GLOBALVAR: {
6173 if (Record.size() < 6)
6174 return error("Invalid record");
6175 uint64_t RawLinkage = Record[3];
6176 GlobalValue::LinkageTypes Linkage = getDecodedLinkage(RawLinkage);
6177 ValueIdToLinkageMap[ValueId++] = Linkage;
6180 // FUNCTION: [type, callingconv, isproto, linkage, paramattr,
6181 // alignment, section, visibility, gc, unnamed_addr,
6182 // prologuedata, dllstorageclass, comdat, prefixdata]
6183 case bitc::MODULE_CODE_FUNCTION: {
6184 if (Record.size() < 8)
6185 return error("Invalid record");
6186 uint64_t RawLinkage = Record[3];
6187 GlobalValue::LinkageTypes Linkage = getDecodedLinkage(RawLinkage);
6188 ValueIdToLinkageMap[ValueId++] = Linkage;
6191 // ALIAS: [alias type, addrspace, aliasee val#, linkage, visibility,
6193 case bitc::MODULE_CODE_ALIAS: {
6194 if (Record.size() < 6)
6195 return error("Invalid record");
6196 uint64_t RawLinkage = Record[3];
6197 GlobalValue::LinkageTypes Linkage = getDecodedLinkage(RawLinkage);
6198 ValueIdToLinkageMap[ValueId++] = Linkage;
6208 // Eagerly parse the entire summary block. This populates the GlobalValueSummary
6209 // objects in the index.
6210 std::error_code ModuleSummaryIndexBitcodeReader::parseEntireSummary() {
6211 if (Stream.EnterSubBlock(bitc::GLOBALVAL_SUMMARY_BLOCK_ID))
6212 return error("Invalid record");
6213 SmallVector<uint64_t, 64> Record;
6217 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
6218 if (Entry.Kind != BitstreamEntry::Record)
6219 return error("Invalid Summary Block: record for version expected");
6220 if (Stream.readRecord(Entry.ID, Record) != bitc::FS_VERSION)
6221 return error("Invalid Summary Block: version expected");
6223 const uint64_t Version = Record[0];
6224 const bool IsOldProfileFormat = Version == 1;
6225 if (!IsOldProfileFormat && Version != 2)
6226 return error("Invalid summary version " + Twine(Version) +
6227 ", 1 or 2 expected");
6230 // Keep around the last seen summary to be used when we see an optional
6231 // "OriginalName" attachement.
6232 GlobalValueSummary *LastSeenSummary = nullptr;
6233 bool Combined = false;
6236 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
6238 switch (Entry.Kind) {
6239 case BitstreamEntry::SubBlock: // Handled for us already.
6240 case BitstreamEntry::Error:
6241 return error("Malformed block");
6242 case BitstreamEntry::EndBlock:
6243 // For a per-module index, remove any entries that still have empty
6244 // summaries. The VST parsing creates entries eagerly for all symbols,
6245 // but not all have associated summaries (e.g. it doesn't know how to
6246 // distinguish between VST_CODE_ENTRY for function declarations vs global
6247 // variables with initializers that end up with a summary). Remove those
6248 // entries now so that we don't need to rely on the combined index merger
6249 // to clean them up (especially since that may not run for the first
6250 // module's index if we merge into that).
6252 TheIndex->removeEmptySummaryEntries();
6253 return std::error_code();
6254 case BitstreamEntry::Record:
6255 // The interesting case.
6259 // Read a record. The record format depends on whether this
6260 // is a per-module index or a combined index file. In the per-module
6261 // case the records contain the associated value's ID for correlation
6262 // with VST entries. In the combined index the correlation is done
6263 // via the bitcode offset of the summary records (which were saved
6264 // in the combined index VST entries). The records also contain
6265 // information used for ThinLTO renaming and importing.
6267 auto BitCode = Stream.readRecord(Entry.ID, Record);
6269 default: // Default behavior: ignore.
6271 // FS_PERMODULE: [valueid, flags, instcount, numrefs, numrefs x valueid,
6273 // FS_PERMODULE_PROFILE: [valueid, flags, instcount, numrefs,
6274 // numrefs x valueid,
6275 // n x (valueid, hotness)]
6276 case bitc::FS_PERMODULE:
6277 case bitc::FS_PERMODULE_PROFILE: {
6278 unsigned ValueID = Record[0];
6279 uint64_t RawFlags = Record[1];
6280 unsigned InstCount = Record[2];
6281 unsigned NumRefs = Record[3];
6282 auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
6283 std::unique_ptr<FunctionSummary> FS =
6284 llvm::make_unique<FunctionSummary>(Flags, InstCount);
6285 // The module path string ref set in the summary must be owned by the
6286 // index's module string table. Since we don't have a module path
6287 // string table section in the per-module index, we create a single
6288 // module path string table entry with an empty (0) ID to take
6291 TheIndex->addModulePath(Buffer->getBufferIdentifier(), 0)->first());
6292 static int RefListStartIndex = 4;
6293 int CallGraphEdgeStartIndex = RefListStartIndex + NumRefs;
6294 assert(Record.size() >= RefListStartIndex + NumRefs &&
6295 "Record size inconsistent with number of references");
6296 for (unsigned I = 4, E = CallGraphEdgeStartIndex; I != E; ++I) {
6297 unsigned RefValueId = Record[I];
6298 GlobalValue::GUID RefGUID = getGUIDFromValueId(RefValueId).first;
6299 FS->addRefEdge(RefGUID);
6301 bool HasProfile = (BitCode == bitc::FS_PERMODULE_PROFILE);
6302 for (unsigned I = CallGraphEdgeStartIndex, E = Record.size(); I != E;
6304 CalleeInfo::HotnessType Hotness;
6305 GlobalValue::GUID CalleeGUID;
6306 std::tie(CalleeGUID, Hotness) =
6307 readCallGraphEdge(Record, I, IsOldProfileFormat, HasProfile);
6308 FS->addCallGraphEdge(CalleeGUID, CalleeInfo(Hotness));
6310 auto GUID = getGUIDFromValueId(ValueID);
6311 FS->setOriginalName(GUID.second);
6312 TheIndex->addGlobalValueSummary(GUID.first, std::move(FS));
6315 // FS_ALIAS: [valueid, flags, valueid]
6316 // Aliases must be emitted (and parsed) after all FS_PERMODULE entries, as
6317 // they expect all aliasee summaries to be available.
6318 case bitc::FS_ALIAS: {
6319 unsigned ValueID = Record[0];
6320 uint64_t RawFlags = Record[1];
6321 unsigned AliaseeID = Record[2];
6322 auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
6323 std::unique_ptr<AliasSummary> AS = llvm::make_unique<AliasSummary>(Flags);
6324 // The module path string ref set in the summary must be owned by the
6325 // index's module string table. Since we don't have a module path
6326 // string table section in the per-module index, we create a single
6327 // module path string table entry with an empty (0) ID to take
6330 TheIndex->addModulePath(Buffer->getBufferIdentifier(), 0)->first());
6332 GlobalValue::GUID AliaseeGUID = getGUIDFromValueId(AliaseeID).first;
6333 auto *AliaseeSummary = TheIndex->getGlobalValueSummary(AliaseeGUID);
6334 if (!AliaseeSummary)
6335 return error("Alias expects aliasee summary to be parsed");
6336 AS->setAliasee(AliaseeSummary);
6338 auto GUID = getGUIDFromValueId(ValueID);
6339 AS->setOriginalName(GUID.second);
6340 TheIndex->addGlobalValueSummary(GUID.first, std::move(AS));
6343 // FS_PERMODULE_GLOBALVAR_INIT_REFS: [valueid, flags, n x valueid]
6344 case bitc::FS_PERMODULE_GLOBALVAR_INIT_REFS: {
6345 unsigned ValueID = Record[0];
6346 uint64_t RawFlags = Record[1];
6347 auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
6348 std::unique_ptr<GlobalVarSummary> FS =
6349 llvm::make_unique<GlobalVarSummary>(Flags);
6351 TheIndex->addModulePath(Buffer->getBufferIdentifier(), 0)->first());
6352 for (unsigned I = 2, E = Record.size(); I != E; ++I) {
6353 unsigned RefValueId = Record[I];
6354 GlobalValue::GUID RefGUID = getGUIDFromValueId(RefValueId).first;
6355 FS->addRefEdge(RefGUID);
6357 auto GUID = getGUIDFromValueId(ValueID);
6358 FS->setOriginalName(GUID.second);
6359 TheIndex->addGlobalValueSummary(GUID.first, std::move(FS));
6362 // FS_COMBINED: [valueid, modid, flags, instcount, numrefs,
6363 // numrefs x valueid, n x (valueid)]
6364 // FS_COMBINED_PROFILE: [valueid, modid, flags, instcount, numrefs,
6365 // numrefs x valueid, n x (valueid, hotness)]
6366 case bitc::FS_COMBINED:
6367 case bitc::FS_COMBINED_PROFILE: {
6368 unsigned ValueID = Record[0];
6369 uint64_t ModuleId = Record[1];
6370 uint64_t RawFlags = Record[2];
6371 unsigned InstCount = Record[3];
6372 unsigned NumRefs = Record[4];
6373 auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
6374 std::unique_ptr<FunctionSummary> FS =
6375 llvm::make_unique<FunctionSummary>(Flags, InstCount);
6376 LastSeenSummary = FS.get();
6377 FS->setModulePath(ModuleIdMap[ModuleId]);
6378 static int RefListStartIndex = 5;
6379 int CallGraphEdgeStartIndex = RefListStartIndex + NumRefs;
6380 assert(Record.size() >= RefListStartIndex + NumRefs &&
6381 "Record size inconsistent with number of references");
6382 for (unsigned I = RefListStartIndex, E = CallGraphEdgeStartIndex; I != E;
6384 unsigned RefValueId = Record[I];
6385 GlobalValue::GUID RefGUID = getGUIDFromValueId(RefValueId).first;
6386 FS->addRefEdge(RefGUID);
6388 bool HasProfile = (BitCode == bitc::FS_COMBINED_PROFILE);
6389 for (unsigned I = CallGraphEdgeStartIndex, E = Record.size(); I != E;
6391 CalleeInfo::HotnessType Hotness;
6392 GlobalValue::GUID CalleeGUID;
6393 std::tie(CalleeGUID, Hotness) =
6394 readCallGraphEdge(Record, I, IsOldProfileFormat, HasProfile);
6395 FS->addCallGraphEdge(CalleeGUID, CalleeInfo(Hotness));
6397 GlobalValue::GUID GUID = getGUIDFromValueId(ValueID).first;
6398 TheIndex->addGlobalValueSummary(GUID, std::move(FS));
6402 // FS_COMBINED_ALIAS: [valueid, modid, flags, valueid]
6403 // Aliases must be emitted (and parsed) after all FS_COMBINED entries, as
6404 // they expect all aliasee summaries to be available.
6405 case bitc::FS_COMBINED_ALIAS: {
6406 unsigned ValueID = Record[0];
6407 uint64_t ModuleId = Record[1];
6408 uint64_t RawFlags = Record[2];
6409 unsigned AliaseeValueId = Record[3];
6410 auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
6411 std::unique_ptr<AliasSummary> AS = llvm::make_unique<AliasSummary>(Flags);
6412 LastSeenSummary = AS.get();
6413 AS->setModulePath(ModuleIdMap[ModuleId]);
6415 auto AliaseeGUID = getGUIDFromValueId(AliaseeValueId).first;
6416 auto AliaseeInModule =
6417 TheIndex->findSummaryInModule(AliaseeGUID, AS->modulePath());
6418 if (!AliaseeInModule)
6419 return error("Alias expects aliasee summary to be parsed");
6420 AS->setAliasee(AliaseeInModule);
6422 GlobalValue::GUID GUID = getGUIDFromValueId(ValueID).first;
6423 TheIndex->addGlobalValueSummary(GUID, std::move(AS));
6427 // FS_COMBINED_GLOBALVAR_INIT_REFS: [valueid, modid, flags, n x valueid]
6428 case bitc::FS_COMBINED_GLOBALVAR_INIT_REFS: {
6429 unsigned ValueID = Record[0];
6430 uint64_t ModuleId = Record[1];
6431 uint64_t RawFlags = Record[2];
6432 auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
6433 std::unique_ptr<GlobalVarSummary> FS =
6434 llvm::make_unique<GlobalVarSummary>(Flags);
6435 LastSeenSummary = FS.get();
6436 FS->setModulePath(ModuleIdMap[ModuleId]);
6437 for (unsigned I = 3, E = Record.size(); I != E; ++I) {
6438 unsigned RefValueId = Record[I];
6439 GlobalValue::GUID RefGUID = getGUIDFromValueId(RefValueId).first;
6440 FS->addRefEdge(RefGUID);
6442 GlobalValue::GUID GUID = getGUIDFromValueId(ValueID).first;
6443 TheIndex->addGlobalValueSummary(GUID, std::move(FS));
6447 // FS_COMBINED_ORIGINAL_NAME: [original_name]
6448 case bitc::FS_COMBINED_ORIGINAL_NAME: {
6449 uint64_t OriginalName = Record[0];
6450 if (!LastSeenSummary)
6451 return error("Name attachment that does not follow a combined record");
6452 LastSeenSummary->setOriginalName(OriginalName);
6453 // Reset the LastSeenSummary
6454 LastSeenSummary = nullptr;
6458 llvm_unreachable("Exit infinite loop");
6461 std::pair<GlobalValue::GUID, CalleeInfo::HotnessType>
6462 ModuleSummaryIndexBitcodeReader::readCallGraphEdge(
6463 const SmallVector<uint64_t, 64> &Record, unsigned int &I,
6464 const bool IsOldProfileFormat, const bool HasProfile) {
6466 auto Hotness = CalleeInfo::HotnessType::Unknown;
6467 unsigned CalleeValueId = Record[I];
6468 GlobalValue::GUID CalleeGUID = getGUIDFromValueId(CalleeValueId).first;
6469 if (IsOldProfileFormat) {
6470 I += 1; // Skip old callsitecount field
6472 I += 1; // Skip old profilecount field
6473 } else if (HasProfile)
6474 Hotness = static_cast<CalleeInfo::HotnessType>(Record[++I]);
6475 return {CalleeGUID, Hotness};
6478 // Parse the module string table block into the Index.
6479 // This populates the ModulePathStringTable map in the index.
6480 std::error_code ModuleSummaryIndexBitcodeReader::parseModuleStringTable() {
6481 if (Stream.EnterSubBlock(bitc::MODULE_STRTAB_BLOCK_ID))
6482 return error("Invalid record");
6484 SmallVector<uint64_t, 64> Record;
6486 SmallString<128> ModulePath;
6487 ModulePathStringTableTy::iterator LastSeenModulePath;
6490 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
6492 switch (Entry.Kind) {
6493 case BitstreamEntry::SubBlock: // Handled for us already.
6494 case BitstreamEntry::Error:
6495 return error("Malformed block");
6496 case BitstreamEntry::EndBlock:
6497 return std::error_code();
6498 case BitstreamEntry::Record:
6499 // The interesting case.
6504 switch (Stream.readRecord(Entry.ID, Record)) {
6505 default: // Default behavior: ignore.
6507 case bitc::MST_CODE_ENTRY: {
6508 // MST_ENTRY: [modid, namechar x N]
6509 uint64_t ModuleId = Record[0];
6511 if (convertToString(Record, 1, ModulePath))
6512 return error("Invalid record");
6514 LastSeenModulePath = TheIndex->addModulePath(ModulePath, ModuleId);
6515 ModuleIdMap[ModuleId] = LastSeenModulePath->first();
6520 /// MST_CODE_HASH: [5*i32]
6521 case bitc::MST_CODE_HASH: {
6522 if (Record.size() != 5)
6523 return error("Invalid hash length " + Twine(Record.size()).str());
6524 if (LastSeenModulePath == TheIndex->modulePaths().end())
6525 return error("Invalid hash that does not follow a module path");
6527 for (auto &Val : Record) {
6528 assert(!(Val >> 32) && "Unexpected high bits set");
6529 LastSeenModulePath->second.second[Pos++] = Val;
6531 // Reset LastSeenModulePath to avoid overriding the hash unexpectedly.
6532 LastSeenModulePath = TheIndex->modulePaths().end();
6537 llvm_unreachable("Exit infinite loop");
6540 // Parse the function info index from the bitcode streamer into the given index.
6541 std::error_code ModuleSummaryIndexBitcodeReader::parseSummaryIndexInto(
6542 std::unique_ptr<DataStreamer> Streamer, ModuleSummaryIndex *I) {
6545 if (std::error_code EC = initStream(std::move(Streamer)))
6548 // Sniff for the signature.
6549 if (!hasValidBitcodeHeader(Stream))
6550 return error("Invalid bitcode signature");
6552 // We expect a number of well-defined blocks, though we don't necessarily
6553 // need to understand them all.
6555 if (Stream.AtEndOfStream()) {
6556 // We didn't really read a proper Module block.
6557 return error("Malformed block");
6560 BitstreamEntry Entry =
6561 Stream.advance(BitstreamCursor::AF_DontAutoprocessAbbrevs);
6563 if (Entry.Kind != BitstreamEntry::SubBlock)
6564 return error("Malformed block");
6566 // If we see a MODULE_BLOCK, parse it to find the blocks needed for
6567 // building the function summary index.
6568 if (Entry.ID == bitc::MODULE_BLOCK_ID)
6569 return parseModule();
6571 if (Stream.SkipBlock())
6572 return error("Invalid record");
6578 // FIXME: This class is only here to support the transition to llvm::Error. It
6579 // will be removed once this transition is complete. Clients should prefer to
6580 // deal with the Error value directly, rather than converting to error_code.
6581 class BitcodeErrorCategoryType : public std::error_category {
6582 const char *name() const LLVM_NOEXCEPT override {
6583 return "llvm.bitcode";
6585 std::string message(int IE) const override {
6586 BitcodeError E = static_cast<BitcodeError>(IE);
6588 case BitcodeError::InvalidBitcodeSignature:
6589 return "Invalid bitcode signature";
6590 case BitcodeError::CorruptedBitcode:
6591 return "Corrupted bitcode";
6593 llvm_unreachable("Unknown error type!");
6597 } // end anonymous namespace
6599 static ManagedStatic<BitcodeErrorCategoryType> ErrorCategory;
6601 const std::error_category &llvm::BitcodeErrorCategory() {
6602 return *ErrorCategory;
6605 //===----------------------------------------------------------------------===//
6606 // External interface
6607 //===----------------------------------------------------------------------===//
6609 static ErrorOr<std::unique_ptr<Module>>
6610 getBitcodeModuleImpl(std::unique_ptr<DataStreamer> Streamer, StringRef Name,
6611 BitcodeReader *R, LLVMContext &Context,
6612 bool MaterializeAll, bool ShouldLazyLoadMetadata) {
6613 std::unique_ptr<Module> M = llvm::make_unique<Module>(Name, Context);
6614 M->setMaterializer(R);
6616 auto cleanupOnError = [&](std::error_code EC) {
6617 R->releaseBuffer(); // Never take ownership on error.
6621 // Delay parsing Metadata if ShouldLazyLoadMetadata is true.
6622 if (std::error_code EC = R->parseBitcodeInto(std::move(Streamer), M.get(),
6623 ShouldLazyLoadMetadata))
6624 return cleanupOnError(EC);
6626 if (MaterializeAll) {
6627 // Read in the entire module, and destroy the BitcodeReader.
6628 if (std::error_code EC = M->materializeAll())
6629 return cleanupOnError(EC);
6631 // Resolve forward references from blockaddresses.
6632 if (std::error_code EC = R->materializeForwardReferencedFunctions())
6633 return cleanupOnError(EC);
6635 return std::move(M);
6638 /// \brief Get a lazy one-at-time loading module from bitcode.
6640 /// This isn't always used in a lazy context. In particular, it's also used by
6641 /// \a parseBitcodeFile(). If this is truly lazy, then we need to eagerly pull
6642 /// in forward-referenced functions from block address references.
6644 /// \param[in] MaterializeAll Set to \c true if we should materialize
6646 static ErrorOr<std::unique_ptr<Module>>
6647 getLazyBitcodeModuleImpl(std::unique_ptr<MemoryBuffer> &&Buffer,
6648 LLVMContext &Context, bool MaterializeAll,
6649 bool ShouldLazyLoadMetadata = false) {
6650 BitcodeReader *R = new BitcodeReader(Buffer.get(), Context);
6652 ErrorOr<std::unique_ptr<Module>> Ret =
6653 getBitcodeModuleImpl(nullptr, Buffer->getBufferIdentifier(), R, Context,
6654 MaterializeAll, ShouldLazyLoadMetadata);
6658 Buffer.release(); // The BitcodeReader owns it now.
6662 ErrorOr<std::unique_ptr<Module>>
6663 llvm::getLazyBitcodeModule(std::unique_ptr<MemoryBuffer> &&Buffer,
6664 LLVMContext &Context, bool ShouldLazyLoadMetadata) {
6665 return getLazyBitcodeModuleImpl(std::move(Buffer), Context, false,
6666 ShouldLazyLoadMetadata);
6669 ErrorOr<std::unique_ptr<Module>>
6670 llvm::getStreamedBitcodeModule(StringRef Name,
6671 std::unique_ptr<DataStreamer> Streamer,
6672 LLVMContext &Context) {
6673 std::unique_ptr<Module> M = llvm::make_unique<Module>(Name, Context);
6674 BitcodeReader *R = new BitcodeReader(Context);
6676 return getBitcodeModuleImpl(std::move(Streamer), Name, R, Context, false,
6680 ErrorOr<std::unique_ptr<Module>> llvm::parseBitcodeFile(MemoryBufferRef Buffer,
6681 LLVMContext &Context) {
6682 std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
6683 return getLazyBitcodeModuleImpl(std::move(Buf), Context, true);
6684 // TODO: Restore the use-lists to the in-memory state when the bitcode was
6685 // written. We must defer until the Module has been fully materialized.
6688 std::string llvm::getBitcodeTargetTriple(MemoryBufferRef Buffer,
6689 LLVMContext &Context) {
6690 std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
6691 auto R = llvm::make_unique<BitcodeReader>(Buf.release(), Context);
6692 ErrorOr<std::string> Triple = R->parseTriple();
6693 if (Triple.getError())
6695 return Triple.get();
6698 bool llvm::isBitcodeContainingObjCCategory(MemoryBufferRef Buffer,
6699 LLVMContext &Context) {
6700 std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
6701 auto R = llvm::make_unique<BitcodeReader>(Buf.release(), Context);
6702 ErrorOr<bool> hasObjCCategory = R->hasObjCCategory();
6703 if (hasObjCCategory.getError())
6705 return hasObjCCategory.get();
6708 std::string llvm::getBitcodeProducerString(MemoryBufferRef Buffer,
6709 LLVMContext &Context) {
6710 std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
6711 BitcodeReader R(Buf.release(), Context);
6712 ErrorOr<std::string> ProducerString = R.parseIdentificationBlock();
6713 if (ProducerString.getError())
6715 return ProducerString.get();
6718 // Parse the specified bitcode buffer, returning the function info index.
6719 ErrorOr<std::unique_ptr<ModuleSummaryIndex>> llvm::getModuleSummaryIndex(
6720 MemoryBufferRef Buffer,
6721 const DiagnosticHandlerFunction &DiagnosticHandler) {
6722 std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
6723 ModuleSummaryIndexBitcodeReader R(Buf.get(), DiagnosticHandler);
6725 auto Index = llvm::make_unique<ModuleSummaryIndex>();
6727 auto cleanupOnError = [&](std::error_code EC) {
6728 R.releaseBuffer(); // Never take ownership on error.
6732 if (std::error_code EC = R.parseSummaryIndexInto(nullptr, Index.get()))
6733 return cleanupOnError(EC);
6735 Buf.release(); // The ModuleSummaryIndexBitcodeReader owns it now.
6736 return std::move(Index);
6739 // Check if the given bitcode buffer contains a global value summary block.
6740 bool llvm::hasGlobalValueSummary(
6741 MemoryBufferRef Buffer,
6742 const DiagnosticHandlerFunction &DiagnosticHandler) {
6743 std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
6744 ModuleSummaryIndexBitcodeReader R(Buf.get(), DiagnosticHandler, true);
6746 auto cleanupOnError = [&](std::error_code EC) {
6747 R.releaseBuffer(); // Never take ownership on error.
6751 if (std::error_code EC = R.parseSummaryIndexInto(nullptr, nullptr))
6752 return cleanupOnError(EC);
6754 Buf.release(); // The ModuleSummaryIndexBitcodeReader owns it now.
6755 return R.foundGlobalValSummary();