1 //===- BitcodeReader.cpp - Internal BitcodeReader implementation ----------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 #include "llvm/Bitcode/ReaderWriter.h"
11 #include "llvm/ADT/STLExtras.h"
12 #include "llvm/ADT/SmallString.h"
13 #include "llvm/ADT/SmallVector.h"
14 #include "llvm/ADT/Triple.h"
15 #include "llvm/Bitcode/BitstreamReader.h"
16 #include "llvm/Bitcode/LLVMBitCodes.h"
17 #include "llvm/IR/AutoUpgrade.h"
18 #include "llvm/IR/Constants.h"
19 #include "llvm/IR/DebugInfo.h"
20 #include "llvm/IR/DebugInfoMetadata.h"
21 #include "llvm/IR/DerivedTypes.h"
22 #include "llvm/IR/DiagnosticPrinter.h"
23 #include "llvm/IR/GVMaterializer.h"
24 #include "llvm/IR/InlineAsm.h"
25 #include "llvm/IR/IntrinsicInst.h"
26 #include "llvm/IR/LLVMContext.h"
27 #include "llvm/IR/Module.h"
28 #include "llvm/IR/OperandTraits.h"
29 #include "llvm/IR/Operator.h"
30 #include "llvm/IR/FunctionInfo.h"
31 #include "llvm/IR/ValueHandle.h"
32 #include "llvm/Support/DataStream.h"
33 #include "llvm/Support/ManagedStatic.h"
34 #include "llvm/Support/MathExtras.h"
35 #include "llvm/Support/MemoryBuffer.h"
36 #include "llvm/Support/raw_ostream.h"
42 SWITCH_INST_MAGIC = 0x4B5 // May 2012 => 1205 => Hex
45 /// Indicates which operator an operand allows (for the few operands that may
46 /// only reference a certain operator).
47 enum OperatorConstraint {
48 OC_None = 0, // No constraint
49 OC_CatchPad, // Must be CatchPadInst
50 OC_CleanupPad // Must be CleanupPadInst
53 class BitcodeReaderValueList {
54 std::vector<WeakVH> ValuePtrs;
56 /// As we resolve forward-referenced constants, we add information about them
57 /// to this vector. This allows us to resolve them in bulk instead of
58 /// resolving each reference at a time. See the code in
59 /// ResolveConstantForwardRefs for more information about this.
61 /// The key of this vector is the placeholder constant, the value is the slot
62 /// number that holds the resolved value.
63 typedef std::vector<std::pair<Constant*, unsigned> > ResolveConstantsTy;
64 ResolveConstantsTy ResolveConstants;
67 BitcodeReaderValueList(LLVMContext &C) : Context(C) {}
68 ~BitcodeReaderValueList() {
69 assert(ResolveConstants.empty() && "Constants not resolved?");
72 // vector compatibility methods
73 unsigned size() const { return ValuePtrs.size(); }
74 void resize(unsigned N) { ValuePtrs.resize(N); }
75 void push_back(Value *V) { ValuePtrs.emplace_back(V); }
78 assert(ResolveConstants.empty() && "Constants not resolved?");
82 Value *operator[](unsigned i) const {
83 assert(i < ValuePtrs.size());
87 Value *back() const { return ValuePtrs.back(); }
88 void pop_back() { ValuePtrs.pop_back(); }
89 bool empty() const { return ValuePtrs.empty(); }
90 void shrinkTo(unsigned N) {
91 assert(N <= size() && "Invalid shrinkTo request!");
95 Constant *getConstantFwdRef(unsigned Idx, Type *Ty);
96 Value *getValueFwdRef(unsigned Idx, Type *Ty,
97 OperatorConstraint OC = OC_None);
99 bool assignValue(Value *V, unsigned Idx);
101 /// Once all constants are read, this method bulk resolves any forward
103 void resolveConstantForwardRefs();
106 class BitcodeReaderMDValueList {
111 std::vector<TrackingMDRef> MDValuePtrs;
113 LLVMContext &Context;
115 BitcodeReaderMDValueList(LLVMContext &C)
116 : NumFwdRefs(0), AnyFwdRefs(false), Context(C) {}
118 // vector compatibility methods
119 unsigned size() const { return MDValuePtrs.size(); }
120 void resize(unsigned N) { MDValuePtrs.resize(N); }
121 void push_back(Metadata *MD) { MDValuePtrs.emplace_back(MD); }
122 void clear() { MDValuePtrs.clear(); }
123 Metadata *back() const { return MDValuePtrs.back(); }
124 void pop_back() { MDValuePtrs.pop_back(); }
125 bool empty() const { return MDValuePtrs.empty(); }
127 Metadata *operator[](unsigned i) const {
128 assert(i < MDValuePtrs.size());
129 return MDValuePtrs[i];
132 void shrinkTo(unsigned N) {
133 assert(N <= size() && "Invalid shrinkTo request!");
134 MDValuePtrs.resize(N);
137 Metadata *getValueFwdRef(unsigned Idx);
138 void assignValue(Metadata *MD, unsigned Idx);
139 void tryToResolveCycles();
142 class BitcodeReader : public GVMaterializer {
143 LLVMContext &Context;
144 DiagnosticHandlerFunction DiagnosticHandler;
145 Module *TheModule = nullptr;
146 std::unique_ptr<MemoryBuffer> Buffer;
147 std::unique_ptr<BitstreamReader> StreamFile;
148 BitstreamCursor Stream;
149 // Next offset to start scanning for lazy parsing of function bodies.
150 uint64_t NextUnreadBit = 0;
151 // Last function offset found in the VST.
152 uint64_t LastFunctionBlockBit = 0;
153 bool SeenValueSymbolTable = false;
154 uint64_t VSTOffset = 0;
155 // Contains an arbitrary and optional string identifying the bitcode producer
156 std::string ProducerIdentification;
158 std::vector<Type*> TypeList;
159 BitcodeReaderValueList ValueList;
160 BitcodeReaderMDValueList MDValueList;
161 std::vector<Comdat *> ComdatList;
162 SmallVector<Instruction *, 64> InstructionList;
164 std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInits;
165 std::vector<std::pair<GlobalAlias*, unsigned> > AliasInits;
166 std::vector<std::pair<Function*, unsigned> > FunctionPrefixes;
167 std::vector<std::pair<Function*, unsigned> > FunctionPrologues;
168 std::vector<std::pair<Function*, unsigned> > FunctionPersonalityFns;
170 SmallVector<Instruction*, 64> InstsWithTBAATag;
172 /// The set of attributes by index. Index zero in the file is for null, and
173 /// is thus not represented here. As such all indices are off by one.
174 std::vector<AttributeSet> MAttributes;
176 /// The set of attribute groups.
177 std::map<unsigned, AttributeSet> MAttributeGroups;
179 /// While parsing a function body, this is a list of the basic blocks for the
181 std::vector<BasicBlock*> FunctionBBs;
183 // When reading the module header, this list is populated with functions that
184 // have bodies later in the file.
185 std::vector<Function*> FunctionsWithBodies;
187 // When intrinsic functions are encountered which require upgrading they are
188 // stored here with their replacement function.
189 typedef DenseMap<Function*, Function*> UpgradedIntrinsicMap;
190 UpgradedIntrinsicMap UpgradedIntrinsics;
192 // Map the bitcode's custom MDKind ID to the Module's MDKind ID.
193 DenseMap<unsigned, unsigned> MDKindMap;
195 // Several operations happen after the module header has been read, but
196 // before function bodies are processed. This keeps track of whether
197 // we've done this yet.
198 bool SeenFirstFunctionBody = false;
200 /// When function bodies are initially scanned, this map contains info about
201 /// where to find deferred function body in the stream.
202 DenseMap<Function*, uint64_t> DeferredFunctionInfo;
204 /// When Metadata block is initially scanned when parsing the module, we may
205 /// choose to defer parsing of the metadata. This vector contains info about
206 /// which Metadata blocks are deferred.
207 std::vector<uint64_t> DeferredMetadataInfo;
209 /// These are basic blocks forward-referenced by block addresses. They are
210 /// inserted lazily into functions when they're loaded. The basic block ID is
211 /// its index into the vector.
212 DenseMap<Function *, std::vector<BasicBlock *>> BasicBlockFwdRefs;
213 std::deque<Function *> BasicBlockFwdRefQueue;
215 /// Indicates that we are using a new encoding for instruction operands where
216 /// most operands in the current FUNCTION_BLOCK are encoded relative to the
217 /// instruction number, for a more compact encoding. Some instruction
218 /// operands are not relative to the instruction ID: basic block numbers, and
219 /// types. Once the old style function blocks have been phased out, we would
220 /// not need this flag.
221 bool UseRelativeIDs = false;
223 /// True if all functions will be materialized, negating the need to process
224 /// (e.g.) blockaddress forward references.
225 bool WillMaterializeAllForwardRefs = false;
227 /// Functions that have block addresses taken. This is usually empty.
228 SmallPtrSet<const Function *, 4> BlockAddressesTaken;
230 /// True if any Metadata block has been materialized.
231 bool IsMetadataMaterialized = false;
233 bool StripDebugInfo = false;
235 std::vector<std::string> BundleTags;
238 std::error_code error(BitcodeError E, const Twine &Message);
239 std::error_code error(BitcodeError E);
240 std::error_code error(const Twine &Message);
242 BitcodeReader(MemoryBuffer *Buffer, LLVMContext &Context,
243 DiagnosticHandlerFunction DiagnosticHandler);
244 BitcodeReader(LLVMContext &Context,
245 DiagnosticHandlerFunction DiagnosticHandler);
246 ~BitcodeReader() override { freeState(); }
248 std::error_code materializeForwardReferencedFunctions();
252 void releaseBuffer();
254 bool isDematerializable(const GlobalValue *GV) const override;
255 std::error_code materialize(GlobalValue *GV) override;
256 std::error_code materializeModule(Module *M) override;
257 std::vector<StructType *> getIdentifiedStructTypes() const override;
258 void dematerialize(GlobalValue *GV) override;
260 /// \brief Main interface to parsing a bitcode buffer.
261 /// \returns true if an error occurred.
262 std::error_code parseBitcodeInto(std::unique_ptr<DataStreamer> Streamer,
264 bool ShouldLazyLoadMetadata = false);
266 /// \brief Cheap mechanism to just extract module triple
267 /// \returns true if an error occurred.
268 ErrorOr<std::string> parseTriple();
270 static uint64_t decodeSignRotatedValue(uint64_t V);
272 /// Materialize any deferred Metadata block.
273 std::error_code materializeMetadata() override;
275 void setStripDebugInfo() override;
278 /// Parse the "IDENTIFICATION_BLOCK_ID" block, populate the
279 // ProducerIdentification data member, and do some basic enforcement on the
280 // "epoch" encoded in the bitcode.
281 std::error_code parseBitcodeVersion();
283 std::vector<StructType *> IdentifiedStructTypes;
284 StructType *createIdentifiedStructType(LLVMContext &Context, StringRef Name);
285 StructType *createIdentifiedStructType(LLVMContext &Context);
287 Type *getTypeByID(unsigned ID);
288 Value *getFnValueByID(unsigned ID, Type *Ty,
289 OperatorConstraint OC = OC_None) {
290 if (Ty && Ty->isMetadataTy())
291 return MetadataAsValue::get(Ty->getContext(), getFnMetadataByID(ID));
292 return ValueList.getValueFwdRef(ID, Ty, OC);
294 Metadata *getFnMetadataByID(unsigned ID) {
295 return MDValueList.getValueFwdRef(ID);
297 BasicBlock *getBasicBlock(unsigned ID) const {
298 if (ID >= FunctionBBs.size()) return nullptr; // Invalid ID
299 return FunctionBBs[ID];
301 AttributeSet getAttributes(unsigned i) const {
302 if (i-1 < MAttributes.size())
303 return MAttributes[i-1];
304 return AttributeSet();
307 /// Read a value/type pair out of the specified record from slot 'Slot'.
308 /// Increment Slot past the number of slots used in the record. Return true on
310 bool getValueTypePair(SmallVectorImpl<uint64_t> &Record, unsigned &Slot,
311 unsigned InstNum, Value *&ResVal) {
312 if (Slot == Record.size()) return true;
313 unsigned ValNo = (unsigned)Record[Slot++];
314 // Adjust the ValNo, if it was encoded relative to the InstNum.
316 ValNo = InstNum - ValNo;
317 if (ValNo < InstNum) {
318 // If this is not a forward reference, just return the value we already
320 ResVal = getFnValueByID(ValNo, nullptr);
321 return ResVal == nullptr;
323 if (Slot == Record.size())
326 unsigned TypeNo = (unsigned)Record[Slot++];
327 ResVal = getFnValueByID(ValNo, getTypeByID(TypeNo));
328 return ResVal == nullptr;
331 /// Read a value out of the specified record from slot 'Slot'. Increment Slot
332 /// past the number of slots used by the value in the record. Return true if
333 /// there is an error.
334 bool popValue(SmallVectorImpl<uint64_t> &Record, unsigned &Slot,
335 unsigned InstNum, Type *Ty, Value *&ResVal,
336 OperatorConstraint OC = OC_None) {
337 if (getValue(Record, Slot, InstNum, Ty, ResVal, OC))
339 // All values currently take a single record slot.
344 /// Like popValue, but does not increment the Slot number.
345 bool getValue(SmallVectorImpl<uint64_t> &Record, unsigned Slot,
346 unsigned InstNum, Type *Ty, Value *&ResVal,
347 OperatorConstraint OC = OC_None) {
348 ResVal = getValue(Record, Slot, InstNum, Ty, OC);
349 return ResVal == nullptr;
352 /// Version of getValue that returns ResVal directly, or 0 if there is an
354 Value *getValue(SmallVectorImpl<uint64_t> &Record, unsigned Slot,
355 unsigned InstNum, Type *Ty, OperatorConstraint OC = OC_None) {
356 if (Slot == Record.size()) return nullptr;
357 unsigned ValNo = (unsigned)Record[Slot];
358 // Adjust the ValNo, if it was encoded relative to the InstNum.
360 ValNo = InstNum - ValNo;
361 return getFnValueByID(ValNo, Ty, OC);
364 /// Like getValue, but decodes signed VBRs.
365 Value *getValueSigned(SmallVectorImpl<uint64_t> &Record, unsigned Slot,
366 unsigned InstNum, Type *Ty,
367 OperatorConstraint OC = OC_None) {
368 if (Slot == Record.size()) return nullptr;
369 unsigned ValNo = (unsigned)decodeSignRotatedValue(Record[Slot]);
370 // Adjust the ValNo, if it was encoded relative to the InstNum.
372 ValNo = InstNum - ValNo;
373 return getFnValueByID(ValNo, Ty, OC);
376 /// Converts alignment exponent (i.e. power of two (or zero)) to the
377 /// corresponding alignment to use. If alignment is too large, returns
378 /// a corresponding error code.
379 std::error_code parseAlignmentValue(uint64_t Exponent, unsigned &Alignment);
380 std::error_code parseAttrKind(uint64_t Code, Attribute::AttrKind *Kind);
381 std::error_code parseModule(uint64_t ResumeBit,
382 bool ShouldLazyLoadMetadata = false);
383 std::error_code parseAttributeBlock();
384 std::error_code parseAttributeGroupBlock();
385 std::error_code parseTypeTable();
386 std::error_code parseTypeTableBody();
387 std::error_code parseOperandBundleTags();
389 ErrorOr<Value *> recordValue(SmallVectorImpl<uint64_t> &Record,
390 unsigned NameIndex, Triple &TT);
391 std::error_code parseValueSymbolTable(uint64_t Offset = 0);
392 std::error_code parseConstants();
393 std::error_code rememberAndSkipFunctionBodies();
394 std::error_code rememberAndSkipFunctionBody();
395 /// Save the positions of the Metadata blocks and skip parsing the blocks.
396 std::error_code rememberAndSkipMetadata();
397 std::error_code parseFunctionBody(Function *F);
398 std::error_code globalCleanup();
399 std::error_code resolveGlobalAndAliasInits();
400 std::error_code parseMetadata();
401 std::error_code parseMetadataAttachment(Function &F);
402 ErrorOr<std::string> parseModuleTriple();
403 std::error_code parseUseLists();
404 std::error_code initStream(std::unique_ptr<DataStreamer> Streamer);
405 std::error_code initStreamFromBuffer();
406 std::error_code initLazyStream(std::unique_ptr<DataStreamer> Streamer);
407 std::error_code findFunctionInStream(
409 DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator);
412 /// Class to manage reading and parsing function summary index bitcode
414 class FunctionIndexBitcodeReader {
415 DiagnosticHandlerFunction DiagnosticHandler;
417 /// Eventually points to the function index built during parsing.
418 FunctionInfoIndex *TheIndex = nullptr;
420 std::unique_ptr<MemoryBuffer> Buffer;
421 std::unique_ptr<BitstreamReader> StreamFile;
422 BitstreamCursor Stream;
424 /// \brief Used to indicate whether we are doing lazy parsing of summary data.
426 /// If false, the summary section is fully parsed into the index during
427 /// the initial parse. Otherwise, if true, the caller is expected to
428 /// invoke \a readFunctionSummary for each summary needed, and the summary
429 /// section is thus parsed lazily.
432 /// Used to indicate whether caller only wants to check for the presence
433 /// of the function summary bitcode section. All blocks are skipped,
434 /// but the SeenFuncSummary boolean is set.
435 bool CheckFuncSummaryPresenceOnly = false;
437 /// Indicates whether we have encountered a function summary section
438 /// yet during parsing, used when checking if file contains function
440 bool SeenFuncSummary = false;
442 /// \brief Map populated during function summary section parsing, and
443 /// consumed during ValueSymbolTable parsing.
445 /// Used to correlate summary records with VST entries. For the per-module
446 /// index this maps the ValueID to the parsed function summary, and
447 /// for the combined index this maps the summary record's bitcode
448 /// offset to the function summary (since in the combined index the
449 /// VST records do not hold value IDs but rather hold the function
450 /// summary record offset).
451 DenseMap<uint64_t, std::unique_ptr<FunctionSummary>> SummaryMap;
453 /// Map populated during module path string table parsing, from the
454 /// module ID to a string reference owned by the index's module
455 /// path string table, used to correlate with combined index function
457 DenseMap<uint64_t, StringRef> ModuleIdMap;
460 std::error_code error(BitcodeError E, const Twine &Message);
461 std::error_code error(BitcodeError E);
462 std::error_code error(const Twine &Message);
464 FunctionIndexBitcodeReader(MemoryBuffer *Buffer, LLVMContext &Context,
465 DiagnosticHandlerFunction DiagnosticHandler,
467 bool CheckFuncSummaryPresenceOnly = false);
468 FunctionIndexBitcodeReader(LLVMContext &Context,
469 DiagnosticHandlerFunction DiagnosticHandler,
471 bool CheckFuncSummaryPresenceOnly = false);
472 ~FunctionIndexBitcodeReader() { freeState(); }
476 void releaseBuffer();
478 /// Check if the parser has encountered a function summary section.
479 bool foundFuncSummary() { return SeenFuncSummary; }
481 /// \brief Main interface to parsing a bitcode buffer.
482 /// \returns true if an error occurred.
483 std::error_code parseSummaryIndexInto(std::unique_ptr<DataStreamer> Streamer,
484 FunctionInfoIndex *I);
486 /// \brief Interface for parsing a function summary lazily.
487 std::error_code parseFunctionSummary(std::unique_ptr<DataStreamer> Streamer,
488 FunctionInfoIndex *I,
489 size_t FunctionSummaryOffset);
492 std::error_code parseModule();
493 std::error_code parseValueSymbolTable();
494 std::error_code parseEntireSummary();
495 std::error_code parseModuleStringTable();
496 std::error_code initStream(std::unique_ptr<DataStreamer> Streamer);
497 std::error_code initStreamFromBuffer();
498 std::error_code initLazyStream(std::unique_ptr<DataStreamer> Streamer);
502 BitcodeDiagnosticInfo::BitcodeDiagnosticInfo(std::error_code EC,
503 DiagnosticSeverity Severity,
505 : DiagnosticInfo(DK_Bitcode, Severity), Msg(Msg), EC(EC) {}
507 void BitcodeDiagnosticInfo::print(DiagnosticPrinter &DP) const { DP << Msg; }
509 static std::error_code error(DiagnosticHandlerFunction DiagnosticHandler,
510 std::error_code EC, const Twine &Message) {
511 BitcodeDiagnosticInfo DI(EC, DS_Error, Message);
512 DiagnosticHandler(DI);
516 static std::error_code error(DiagnosticHandlerFunction DiagnosticHandler,
517 std::error_code EC) {
518 return error(DiagnosticHandler, EC, EC.message());
521 static std::error_code error(DiagnosticHandlerFunction DiagnosticHandler,
522 const Twine &Message) {
523 return error(DiagnosticHandler,
524 make_error_code(BitcodeError::CorruptedBitcode), Message);
527 std::error_code BitcodeReader::error(BitcodeError E, const Twine &Message) {
528 if (!ProducerIdentification.empty()) {
529 Twine MsgWithID = Message + " (Producer: '" + ProducerIdentification +
530 "' Reader: 'LLVM " + LLVM_VERSION_STRING "')";
531 return ::error(DiagnosticHandler, make_error_code(E), MsgWithID);
533 return ::error(DiagnosticHandler, make_error_code(E), Message);
536 std::error_code BitcodeReader::error(const Twine &Message) {
537 if (!ProducerIdentification.empty()) {
538 Twine MsgWithID = Message + " (Producer: '" + ProducerIdentification +
539 "' Reader: 'LLVM " + LLVM_VERSION_STRING "')";
540 return ::error(DiagnosticHandler,
541 make_error_code(BitcodeError::CorruptedBitcode), MsgWithID);
543 return ::error(DiagnosticHandler,
544 make_error_code(BitcodeError::CorruptedBitcode), Message);
547 std::error_code BitcodeReader::error(BitcodeError E) {
548 return ::error(DiagnosticHandler, make_error_code(E));
551 static DiagnosticHandlerFunction getDiagHandler(DiagnosticHandlerFunction F,
555 return [&C](const DiagnosticInfo &DI) { C.diagnose(DI); };
558 BitcodeReader::BitcodeReader(MemoryBuffer *Buffer, LLVMContext &Context,
559 DiagnosticHandlerFunction DiagnosticHandler)
561 DiagnosticHandler(getDiagHandler(DiagnosticHandler, Context)),
562 Buffer(Buffer), ValueList(Context), MDValueList(Context) {}
564 BitcodeReader::BitcodeReader(LLVMContext &Context,
565 DiagnosticHandlerFunction DiagnosticHandler)
567 DiagnosticHandler(getDiagHandler(DiagnosticHandler, Context)),
568 Buffer(nullptr), ValueList(Context), MDValueList(Context) {}
570 std::error_code BitcodeReader::materializeForwardReferencedFunctions() {
571 if (WillMaterializeAllForwardRefs)
572 return std::error_code();
574 // Prevent recursion.
575 WillMaterializeAllForwardRefs = true;
577 while (!BasicBlockFwdRefQueue.empty()) {
578 Function *F = BasicBlockFwdRefQueue.front();
579 BasicBlockFwdRefQueue.pop_front();
580 assert(F && "Expected valid function");
581 if (!BasicBlockFwdRefs.count(F))
582 // Already materialized.
585 // Check for a function that isn't materializable to prevent an infinite
586 // loop. When parsing a blockaddress stored in a global variable, there
587 // isn't a trivial way to check if a function will have a body without a
588 // linear search through FunctionsWithBodies, so just check it here.
589 if (!F->isMaterializable())
590 return error("Never resolved function from blockaddress");
592 // Try to materialize F.
593 if (std::error_code EC = materialize(F))
596 assert(BasicBlockFwdRefs.empty() && "Function missing from queue");
599 WillMaterializeAllForwardRefs = false;
600 return std::error_code();
603 void BitcodeReader::freeState() {
605 std::vector<Type*>().swap(TypeList);
608 std::vector<Comdat *>().swap(ComdatList);
610 std::vector<AttributeSet>().swap(MAttributes);
611 std::vector<BasicBlock*>().swap(FunctionBBs);
612 std::vector<Function*>().swap(FunctionsWithBodies);
613 DeferredFunctionInfo.clear();
614 DeferredMetadataInfo.clear();
617 assert(BasicBlockFwdRefs.empty() && "Unresolved blockaddress fwd references");
618 BasicBlockFwdRefQueue.clear();
621 //===----------------------------------------------------------------------===//
622 // Helper functions to implement forward reference resolution, etc.
623 //===----------------------------------------------------------------------===//
625 /// Convert a string from a record into an std::string, return true on failure.
626 template <typename StrTy>
627 static bool convertToString(ArrayRef<uint64_t> Record, unsigned Idx,
629 if (Idx > Record.size())
632 for (unsigned i = Idx, e = Record.size(); i != e; ++i)
633 Result += (char)Record[i];
637 static bool hasImplicitComdat(size_t Val) {
641 case 1: // Old WeakAnyLinkage
642 case 4: // Old LinkOnceAnyLinkage
643 case 10: // Old WeakODRLinkage
644 case 11: // Old LinkOnceODRLinkage
649 static GlobalValue::LinkageTypes getDecodedLinkage(unsigned Val) {
651 default: // Map unknown/new linkages to external
653 return GlobalValue::ExternalLinkage;
655 return GlobalValue::AppendingLinkage;
657 return GlobalValue::InternalLinkage;
659 return GlobalValue::ExternalLinkage; // Obsolete DLLImportLinkage
661 return GlobalValue::ExternalLinkage; // Obsolete DLLExportLinkage
663 return GlobalValue::ExternalWeakLinkage;
665 return GlobalValue::CommonLinkage;
667 return GlobalValue::PrivateLinkage;
669 return GlobalValue::AvailableExternallyLinkage;
671 return GlobalValue::PrivateLinkage; // Obsolete LinkerPrivateLinkage
673 return GlobalValue::PrivateLinkage; // Obsolete LinkerPrivateWeakLinkage
675 return GlobalValue::ExternalLinkage; // Obsolete LinkOnceODRAutoHideLinkage
676 case 1: // Old value with implicit comdat.
678 return GlobalValue::WeakAnyLinkage;
679 case 10: // Old value with implicit comdat.
681 return GlobalValue::WeakODRLinkage;
682 case 4: // Old value with implicit comdat.
684 return GlobalValue::LinkOnceAnyLinkage;
685 case 11: // Old value with implicit comdat.
687 return GlobalValue::LinkOnceODRLinkage;
691 static GlobalValue::VisibilityTypes getDecodedVisibility(unsigned Val) {
693 default: // Map unknown visibilities to default.
694 case 0: return GlobalValue::DefaultVisibility;
695 case 1: return GlobalValue::HiddenVisibility;
696 case 2: return GlobalValue::ProtectedVisibility;
700 static GlobalValue::DLLStorageClassTypes
701 getDecodedDLLStorageClass(unsigned Val) {
703 default: // Map unknown values to default.
704 case 0: return GlobalValue::DefaultStorageClass;
705 case 1: return GlobalValue::DLLImportStorageClass;
706 case 2: return GlobalValue::DLLExportStorageClass;
710 static GlobalVariable::ThreadLocalMode getDecodedThreadLocalMode(unsigned Val) {
712 case 0: return GlobalVariable::NotThreadLocal;
713 default: // Map unknown non-zero value to general dynamic.
714 case 1: return GlobalVariable::GeneralDynamicTLSModel;
715 case 2: return GlobalVariable::LocalDynamicTLSModel;
716 case 3: return GlobalVariable::InitialExecTLSModel;
717 case 4: return GlobalVariable::LocalExecTLSModel;
721 static int getDecodedCastOpcode(unsigned Val) {
724 case bitc::CAST_TRUNC : return Instruction::Trunc;
725 case bitc::CAST_ZEXT : return Instruction::ZExt;
726 case bitc::CAST_SEXT : return Instruction::SExt;
727 case bitc::CAST_FPTOUI : return Instruction::FPToUI;
728 case bitc::CAST_FPTOSI : return Instruction::FPToSI;
729 case bitc::CAST_UITOFP : return Instruction::UIToFP;
730 case bitc::CAST_SITOFP : return Instruction::SIToFP;
731 case bitc::CAST_FPTRUNC : return Instruction::FPTrunc;
732 case bitc::CAST_FPEXT : return Instruction::FPExt;
733 case bitc::CAST_PTRTOINT: return Instruction::PtrToInt;
734 case bitc::CAST_INTTOPTR: return Instruction::IntToPtr;
735 case bitc::CAST_BITCAST : return Instruction::BitCast;
736 case bitc::CAST_ADDRSPACECAST: return Instruction::AddrSpaceCast;
740 static int getDecodedBinaryOpcode(unsigned Val, Type *Ty) {
741 bool IsFP = Ty->isFPOrFPVectorTy();
742 // BinOps are only valid for int/fp or vector of int/fp types
743 if (!IsFP && !Ty->isIntOrIntVectorTy())
749 case bitc::BINOP_ADD:
750 return IsFP ? Instruction::FAdd : Instruction::Add;
751 case bitc::BINOP_SUB:
752 return IsFP ? Instruction::FSub : Instruction::Sub;
753 case bitc::BINOP_MUL:
754 return IsFP ? Instruction::FMul : Instruction::Mul;
755 case bitc::BINOP_UDIV:
756 return IsFP ? -1 : Instruction::UDiv;
757 case bitc::BINOP_SDIV:
758 return IsFP ? Instruction::FDiv : Instruction::SDiv;
759 case bitc::BINOP_UREM:
760 return IsFP ? -1 : Instruction::URem;
761 case bitc::BINOP_SREM:
762 return IsFP ? Instruction::FRem : Instruction::SRem;
763 case bitc::BINOP_SHL:
764 return IsFP ? -1 : Instruction::Shl;
765 case bitc::BINOP_LSHR:
766 return IsFP ? -1 : Instruction::LShr;
767 case bitc::BINOP_ASHR:
768 return IsFP ? -1 : Instruction::AShr;
769 case bitc::BINOP_AND:
770 return IsFP ? -1 : Instruction::And;
772 return IsFP ? -1 : Instruction::Or;
773 case bitc::BINOP_XOR:
774 return IsFP ? -1 : Instruction::Xor;
778 static AtomicRMWInst::BinOp getDecodedRMWOperation(unsigned Val) {
780 default: return AtomicRMWInst::BAD_BINOP;
781 case bitc::RMW_XCHG: return AtomicRMWInst::Xchg;
782 case bitc::RMW_ADD: return AtomicRMWInst::Add;
783 case bitc::RMW_SUB: return AtomicRMWInst::Sub;
784 case bitc::RMW_AND: return AtomicRMWInst::And;
785 case bitc::RMW_NAND: return AtomicRMWInst::Nand;
786 case bitc::RMW_OR: return AtomicRMWInst::Or;
787 case bitc::RMW_XOR: return AtomicRMWInst::Xor;
788 case bitc::RMW_MAX: return AtomicRMWInst::Max;
789 case bitc::RMW_MIN: return AtomicRMWInst::Min;
790 case bitc::RMW_UMAX: return AtomicRMWInst::UMax;
791 case bitc::RMW_UMIN: return AtomicRMWInst::UMin;
795 static AtomicOrdering getDecodedOrdering(unsigned Val) {
797 case bitc::ORDERING_NOTATOMIC: return NotAtomic;
798 case bitc::ORDERING_UNORDERED: return Unordered;
799 case bitc::ORDERING_MONOTONIC: return Monotonic;
800 case bitc::ORDERING_ACQUIRE: return Acquire;
801 case bitc::ORDERING_RELEASE: return Release;
802 case bitc::ORDERING_ACQREL: return AcquireRelease;
803 default: // Map unknown orderings to sequentially-consistent.
804 case bitc::ORDERING_SEQCST: return SequentiallyConsistent;
808 static SynchronizationScope getDecodedSynchScope(unsigned Val) {
810 case bitc::SYNCHSCOPE_SINGLETHREAD: return SingleThread;
811 default: // Map unknown scopes to cross-thread.
812 case bitc::SYNCHSCOPE_CROSSTHREAD: return CrossThread;
816 static Comdat::SelectionKind getDecodedComdatSelectionKind(unsigned Val) {
818 default: // Map unknown selection kinds to any.
819 case bitc::COMDAT_SELECTION_KIND_ANY:
821 case bitc::COMDAT_SELECTION_KIND_EXACT_MATCH:
822 return Comdat::ExactMatch;
823 case bitc::COMDAT_SELECTION_KIND_LARGEST:
824 return Comdat::Largest;
825 case bitc::COMDAT_SELECTION_KIND_NO_DUPLICATES:
826 return Comdat::NoDuplicates;
827 case bitc::COMDAT_SELECTION_KIND_SAME_SIZE:
828 return Comdat::SameSize;
832 static FastMathFlags getDecodedFastMathFlags(unsigned Val) {
834 if (0 != (Val & FastMathFlags::UnsafeAlgebra))
835 FMF.setUnsafeAlgebra();
836 if (0 != (Val & FastMathFlags::NoNaNs))
838 if (0 != (Val & FastMathFlags::NoInfs))
840 if (0 != (Val & FastMathFlags::NoSignedZeros))
841 FMF.setNoSignedZeros();
842 if (0 != (Val & FastMathFlags::AllowReciprocal))
843 FMF.setAllowReciprocal();
847 static void upgradeDLLImportExportLinkage(llvm::GlobalValue *GV, unsigned Val) {
849 case 5: GV->setDLLStorageClass(GlobalValue::DLLImportStorageClass); break;
850 case 6: GV->setDLLStorageClass(GlobalValue::DLLExportStorageClass); break;
856 /// \brief A class for maintaining the slot number definition
857 /// as a placeholder for the actual definition for forward constants defs.
858 class ConstantPlaceHolder : public ConstantExpr {
859 void operator=(const ConstantPlaceHolder &) = delete;
862 // allocate space for exactly one operand
863 void *operator new(size_t s) { return User::operator new(s, 1); }
864 explicit ConstantPlaceHolder(Type *Ty, LLVMContext &Context)
865 : ConstantExpr(Ty, Instruction::UserOp1, &Op<0>(), 1) {
866 Op<0>() = UndefValue::get(Type::getInt32Ty(Context));
869 /// \brief Methods to support type inquiry through isa, cast, and dyn_cast.
870 static bool classof(const Value *V) {
871 return isa<ConstantExpr>(V) &&
872 cast<ConstantExpr>(V)->getOpcode() == Instruction::UserOp1;
875 /// Provide fast operand accessors
876 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
880 // FIXME: can we inherit this from ConstantExpr?
882 struct OperandTraits<ConstantPlaceHolder> :
883 public FixedNumOperandTraits<ConstantPlaceHolder, 1> {
885 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ConstantPlaceHolder, Value)
888 bool BitcodeReaderValueList::assignValue(Value *V, unsigned Idx) {
897 WeakVH &OldV = ValuePtrs[Idx];
903 // Handle constants and non-constants (e.g. instrs) differently for
905 if (Constant *PHC = dyn_cast<Constant>(&*OldV)) {
906 ResolveConstants.push_back(std::make_pair(PHC, Idx));
909 // If there was a forward reference to this value, replace it.
910 Value *PrevVal = OldV;
911 // Check operator constraints. We only put cleanuppads or catchpads in
912 // the forward value map if the value is constrained to match.
913 if (CatchPadInst *CatchPad = dyn_cast<CatchPadInst>(PrevVal)) {
914 if (!isa<CatchPadInst>(V))
916 // Delete the dummy basic block that was created with the sentinel
918 BasicBlock *DummyBlock = CatchPad->getUnwindDest();
919 assert(DummyBlock == CatchPad->getNormalDest());
920 CatchPad->dropAllReferences();
922 } else if (isa<CleanupPadInst>(PrevVal)) {
923 if (!isa<CleanupPadInst>(V))
926 OldV->replaceAllUsesWith(V);
934 Constant *BitcodeReaderValueList::getConstantFwdRef(unsigned Idx,
939 if (Value *V = ValuePtrs[Idx]) {
940 if (Ty != V->getType())
941 report_fatal_error("Type mismatch in constant table!");
942 return cast<Constant>(V);
945 // Create and return a placeholder, which will later be RAUW'd.
946 Constant *C = new ConstantPlaceHolder(Ty, Context);
951 Value *BitcodeReaderValueList::getValueFwdRef(unsigned Idx, Type *Ty,
952 OperatorConstraint OC) {
953 // Bail out for a clearly invalid value. This would make us call resize(0)
960 if (Value *V = ValuePtrs[Idx]) {
961 // If the types don't match, it's invalid.
962 if (Ty && Ty != V->getType())
966 // Use dyn_cast to enforce operator constraints
969 return dyn_cast<CatchPadInst>(V);
971 return dyn_cast<CleanupPadInst>(V);
973 llvm_unreachable("Unexpected operator constraint");
977 // No type specified, must be invalid reference.
978 if (!Ty) return nullptr;
980 // Create and return a placeholder, which will later be RAUW'd.
984 V = new Argument(Ty);
987 BasicBlock *BB = BasicBlock::Create(Context);
988 V = CatchPadInst::Create(BB, BB, {});
992 assert(OC == OC_CleanupPad && "unexpected operator constraint");
993 V = CleanupPadInst::Create(Context, {});
1001 /// Once all constants are read, this method bulk resolves any forward
1002 /// references. The idea behind this is that we sometimes get constants (such
1003 /// as large arrays) which reference *many* forward ref constants. Replacing
1004 /// each of these causes a lot of thrashing when building/reuniquing the
1005 /// constant. Instead of doing this, we look at all the uses and rewrite all
1006 /// the place holders at once for any constant that uses a placeholder.
1007 void BitcodeReaderValueList::resolveConstantForwardRefs() {
1008 // Sort the values by-pointer so that they are efficient to look up with a
1010 std::sort(ResolveConstants.begin(), ResolveConstants.end());
1012 SmallVector<Constant*, 64> NewOps;
1014 while (!ResolveConstants.empty()) {
1015 Value *RealVal = operator[](ResolveConstants.back().second);
1016 Constant *Placeholder = ResolveConstants.back().first;
1017 ResolveConstants.pop_back();
1019 // Loop over all users of the placeholder, updating them to reference the
1020 // new value. If they reference more than one placeholder, update them all
1022 while (!Placeholder->use_empty()) {
1023 auto UI = Placeholder->user_begin();
1026 // If the using object isn't uniqued, just update the operands. This
1027 // handles instructions and initializers for global variables.
1028 if (!isa<Constant>(U) || isa<GlobalValue>(U)) {
1029 UI.getUse().set(RealVal);
1033 // Otherwise, we have a constant that uses the placeholder. Replace that
1034 // constant with a new constant that has *all* placeholder uses updated.
1035 Constant *UserC = cast<Constant>(U);
1036 for (User::op_iterator I = UserC->op_begin(), E = UserC->op_end();
1039 if (!isa<ConstantPlaceHolder>(*I)) {
1040 // Not a placeholder reference.
1042 } else if (*I == Placeholder) {
1043 // Common case is that it just references this one placeholder.
1046 // Otherwise, look up the placeholder in ResolveConstants.
1047 ResolveConstantsTy::iterator It =
1048 std::lower_bound(ResolveConstants.begin(), ResolveConstants.end(),
1049 std::pair<Constant*, unsigned>(cast<Constant>(*I),
1051 assert(It != ResolveConstants.end() && It->first == *I);
1052 NewOp = operator[](It->second);
1055 NewOps.push_back(cast<Constant>(NewOp));
1058 // Make the new constant.
1060 if (ConstantArray *UserCA = dyn_cast<ConstantArray>(UserC)) {
1061 NewC = ConstantArray::get(UserCA->getType(), NewOps);
1062 } else if (ConstantStruct *UserCS = dyn_cast<ConstantStruct>(UserC)) {
1063 NewC = ConstantStruct::get(UserCS->getType(), NewOps);
1064 } else if (isa<ConstantVector>(UserC)) {
1065 NewC = ConstantVector::get(NewOps);
1067 assert(isa<ConstantExpr>(UserC) && "Must be a ConstantExpr.");
1068 NewC = cast<ConstantExpr>(UserC)->getWithOperands(NewOps);
1071 UserC->replaceAllUsesWith(NewC);
1072 UserC->destroyConstant();
1076 // Update all ValueHandles, they should be the only users at this point.
1077 Placeholder->replaceAllUsesWith(RealVal);
1082 void BitcodeReaderMDValueList::assignValue(Metadata *MD, unsigned Idx) {
1083 if (Idx == size()) {
1091 TrackingMDRef &OldMD = MDValuePtrs[Idx];
1097 // If there was a forward reference to this value, replace it.
1098 TempMDTuple PrevMD(cast<MDTuple>(OldMD.get()));
1099 PrevMD->replaceAllUsesWith(MD);
1103 Metadata *BitcodeReaderMDValueList::getValueFwdRef(unsigned Idx) {
1107 if (Metadata *MD = MDValuePtrs[Idx])
1110 // Track forward refs to be resolved later.
1112 MinFwdRef = std::min(MinFwdRef, Idx);
1113 MaxFwdRef = std::max(MaxFwdRef, Idx);
1116 MinFwdRef = MaxFwdRef = Idx;
1120 // Create and return a placeholder, which will later be RAUW'd.
1121 Metadata *MD = MDNode::getTemporary(Context, None).release();
1122 MDValuePtrs[Idx].reset(MD);
1126 void BitcodeReaderMDValueList::tryToResolveCycles() {
1132 // Still forward references... can't resolve cycles.
1135 // Resolve any cycles.
1136 for (unsigned I = MinFwdRef, E = MaxFwdRef + 1; I != E; ++I) {
1137 auto &MD = MDValuePtrs[I];
1138 auto *N = dyn_cast_or_null<MDNode>(MD);
1142 assert(!N->isTemporary() && "Unexpected forward reference");
1146 // Make sure we return early again until there's another forward ref.
1150 Type *BitcodeReader::getTypeByID(unsigned ID) {
1151 // The type table size is always specified correctly.
1152 if (ID >= TypeList.size())
1155 if (Type *Ty = TypeList[ID])
1158 // If we have a forward reference, the only possible case is when it is to a
1159 // named struct. Just create a placeholder for now.
1160 return TypeList[ID] = createIdentifiedStructType(Context);
1163 StructType *BitcodeReader::createIdentifiedStructType(LLVMContext &Context,
1165 auto *Ret = StructType::create(Context, Name);
1166 IdentifiedStructTypes.push_back(Ret);
1170 StructType *BitcodeReader::createIdentifiedStructType(LLVMContext &Context) {
1171 auto *Ret = StructType::create(Context);
1172 IdentifiedStructTypes.push_back(Ret);
1177 //===----------------------------------------------------------------------===//
1178 // Functions for parsing blocks from the bitcode file
1179 //===----------------------------------------------------------------------===//
1182 /// \brief This fills an AttrBuilder object with the LLVM attributes that have
1183 /// been decoded from the given integer. This function must stay in sync with
1184 /// 'encodeLLVMAttributesForBitcode'.
1185 static void decodeLLVMAttributesForBitcode(AttrBuilder &B,
1186 uint64_t EncodedAttrs) {
1187 // FIXME: Remove in 4.0.
1189 // The alignment is stored as a 16-bit raw value from bits 31--16. We shift
1190 // the bits above 31 down by 11 bits.
1191 unsigned Alignment = (EncodedAttrs & (0xffffULL << 16)) >> 16;
1192 assert((!Alignment || isPowerOf2_32(Alignment)) &&
1193 "Alignment must be a power of two.");
1196 B.addAlignmentAttr(Alignment);
1197 B.addRawValue(((EncodedAttrs & (0xfffffULL << 32)) >> 11) |
1198 (EncodedAttrs & 0xffff));
1201 std::error_code BitcodeReader::parseAttributeBlock() {
1202 if (Stream.EnterSubBlock(bitc::PARAMATTR_BLOCK_ID))
1203 return error("Invalid record");
1205 if (!MAttributes.empty())
1206 return error("Invalid multiple blocks");
1208 SmallVector<uint64_t, 64> Record;
1210 SmallVector<AttributeSet, 8> Attrs;
1212 // Read all the records.
1214 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1216 switch (Entry.Kind) {
1217 case BitstreamEntry::SubBlock: // Handled for us already.
1218 case BitstreamEntry::Error:
1219 return error("Malformed block");
1220 case BitstreamEntry::EndBlock:
1221 return std::error_code();
1222 case BitstreamEntry::Record:
1223 // The interesting case.
1229 switch (Stream.readRecord(Entry.ID, Record)) {
1230 default: // Default behavior: ignore.
1232 case bitc::PARAMATTR_CODE_ENTRY_OLD: { // ENTRY: [paramidx0, attr0, ...]
1233 // FIXME: Remove in 4.0.
1234 if (Record.size() & 1)
1235 return error("Invalid record");
1237 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
1239 decodeLLVMAttributesForBitcode(B, Record[i+1]);
1240 Attrs.push_back(AttributeSet::get(Context, Record[i], B));
1243 MAttributes.push_back(AttributeSet::get(Context, Attrs));
1247 case bitc::PARAMATTR_CODE_ENTRY: { // ENTRY: [attrgrp0, attrgrp1, ...]
1248 for (unsigned i = 0, e = Record.size(); i != e; ++i)
1249 Attrs.push_back(MAttributeGroups[Record[i]]);
1251 MAttributes.push_back(AttributeSet::get(Context, Attrs));
1259 // Returns Attribute::None on unrecognized codes.
1260 static Attribute::AttrKind getAttrFromCode(uint64_t Code) {
1263 return Attribute::None;
1264 case bitc::ATTR_KIND_ALIGNMENT:
1265 return Attribute::Alignment;
1266 case bitc::ATTR_KIND_ALWAYS_INLINE:
1267 return Attribute::AlwaysInline;
1268 case bitc::ATTR_KIND_ARGMEMONLY:
1269 return Attribute::ArgMemOnly;
1270 case bitc::ATTR_KIND_BUILTIN:
1271 return Attribute::Builtin;
1272 case bitc::ATTR_KIND_BY_VAL:
1273 return Attribute::ByVal;
1274 case bitc::ATTR_KIND_IN_ALLOCA:
1275 return Attribute::InAlloca;
1276 case bitc::ATTR_KIND_COLD:
1277 return Attribute::Cold;
1278 case bitc::ATTR_KIND_CONVERGENT:
1279 return Attribute::Convergent;
1280 case bitc::ATTR_KIND_INLINE_HINT:
1281 return Attribute::InlineHint;
1282 case bitc::ATTR_KIND_IN_REG:
1283 return Attribute::InReg;
1284 case bitc::ATTR_KIND_JUMP_TABLE:
1285 return Attribute::JumpTable;
1286 case bitc::ATTR_KIND_MIN_SIZE:
1287 return Attribute::MinSize;
1288 case bitc::ATTR_KIND_NAKED:
1289 return Attribute::Naked;
1290 case bitc::ATTR_KIND_NEST:
1291 return Attribute::Nest;
1292 case bitc::ATTR_KIND_NO_ALIAS:
1293 return Attribute::NoAlias;
1294 case bitc::ATTR_KIND_NO_BUILTIN:
1295 return Attribute::NoBuiltin;
1296 case bitc::ATTR_KIND_NO_CAPTURE:
1297 return Attribute::NoCapture;
1298 case bitc::ATTR_KIND_NO_DUPLICATE:
1299 return Attribute::NoDuplicate;
1300 case bitc::ATTR_KIND_NO_IMPLICIT_FLOAT:
1301 return Attribute::NoImplicitFloat;
1302 case bitc::ATTR_KIND_NO_INLINE:
1303 return Attribute::NoInline;
1304 case bitc::ATTR_KIND_NON_LAZY_BIND:
1305 return Attribute::NonLazyBind;
1306 case bitc::ATTR_KIND_NON_NULL:
1307 return Attribute::NonNull;
1308 case bitc::ATTR_KIND_DEREFERENCEABLE:
1309 return Attribute::Dereferenceable;
1310 case bitc::ATTR_KIND_DEREFERENCEABLE_OR_NULL:
1311 return Attribute::DereferenceableOrNull;
1312 case bitc::ATTR_KIND_NO_RED_ZONE:
1313 return Attribute::NoRedZone;
1314 case bitc::ATTR_KIND_NO_RETURN:
1315 return Attribute::NoReturn;
1316 case bitc::ATTR_KIND_NO_UNWIND:
1317 return Attribute::NoUnwind;
1318 case bitc::ATTR_KIND_OPTIMIZE_FOR_SIZE:
1319 return Attribute::OptimizeForSize;
1320 case bitc::ATTR_KIND_OPTIMIZE_NONE:
1321 return Attribute::OptimizeNone;
1322 case bitc::ATTR_KIND_READ_NONE:
1323 return Attribute::ReadNone;
1324 case bitc::ATTR_KIND_READ_ONLY:
1325 return Attribute::ReadOnly;
1326 case bitc::ATTR_KIND_RETURNED:
1327 return Attribute::Returned;
1328 case bitc::ATTR_KIND_RETURNS_TWICE:
1329 return Attribute::ReturnsTwice;
1330 case bitc::ATTR_KIND_S_EXT:
1331 return Attribute::SExt;
1332 case bitc::ATTR_KIND_STACK_ALIGNMENT:
1333 return Attribute::StackAlignment;
1334 case bitc::ATTR_KIND_STACK_PROTECT:
1335 return Attribute::StackProtect;
1336 case bitc::ATTR_KIND_STACK_PROTECT_REQ:
1337 return Attribute::StackProtectReq;
1338 case bitc::ATTR_KIND_STACK_PROTECT_STRONG:
1339 return Attribute::StackProtectStrong;
1340 case bitc::ATTR_KIND_SAFESTACK:
1341 return Attribute::SafeStack;
1342 case bitc::ATTR_KIND_STRUCT_RET:
1343 return Attribute::StructRet;
1344 case bitc::ATTR_KIND_SANITIZE_ADDRESS:
1345 return Attribute::SanitizeAddress;
1346 case bitc::ATTR_KIND_SANITIZE_THREAD:
1347 return Attribute::SanitizeThread;
1348 case bitc::ATTR_KIND_SANITIZE_MEMORY:
1349 return Attribute::SanitizeMemory;
1350 case bitc::ATTR_KIND_UW_TABLE:
1351 return Attribute::UWTable;
1352 case bitc::ATTR_KIND_Z_EXT:
1353 return Attribute::ZExt;
1357 std::error_code BitcodeReader::parseAlignmentValue(uint64_t Exponent,
1358 unsigned &Alignment) {
1359 // Note: Alignment in bitcode files is incremented by 1, so that zero
1360 // can be used for default alignment.
1361 if (Exponent > Value::MaxAlignmentExponent + 1)
1362 return error("Invalid alignment value");
1363 Alignment = (1 << static_cast<unsigned>(Exponent)) >> 1;
1364 return std::error_code();
1367 std::error_code BitcodeReader::parseAttrKind(uint64_t Code,
1368 Attribute::AttrKind *Kind) {
1369 *Kind = getAttrFromCode(Code);
1370 if (*Kind == Attribute::None)
1371 return error(BitcodeError::CorruptedBitcode,
1372 "Unknown attribute kind (" + Twine(Code) + ")");
1373 return std::error_code();
1376 std::error_code BitcodeReader::parseAttributeGroupBlock() {
1377 if (Stream.EnterSubBlock(bitc::PARAMATTR_GROUP_BLOCK_ID))
1378 return error("Invalid record");
1380 if (!MAttributeGroups.empty())
1381 return error("Invalid multiple blocks");
1383 SmallVector<uint64_t, 64> Record;
1385 // Read all the records.
1387 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1389 switch (Entry.Kind) {
1390 case BitstreamEntry::SubBlock: // Handled for us already.
1391 case BitstreamEntry::Error:
1392 return error("Malformed block");
1393 case BitstreamEntry::EndBlock:
1394 return std::error_code();
1395 case BitstreamEntry::Record:
1396 // The interesting case.
1402 switch (Stream.readRecord(Entry.ID, Record)) {
1403 default: // Default behavior: ignore.
1405 case bitc::PARAMATTR_GRP_CODE_ENTRY: { // ENTRY: [grpid, idx, a0, a1, ...]
1406 if (Record.size() < 3)
1407 return error("Invalid record");
1409 uint64_t GrpID = Record[0];
1410 uint64_t Idx = Record[1]; // Index of the object this attribute refers to.
1413 for (unsigned i = 2, e = Record.size(); i != e; ++i) {
1414 if (Record[i] == 0) { // Enum attribute
1415 Attribute::AttrKind Kind;
1416 if (std::error_code EC = parseAttrKind(Record[++i], &Kind))
1419 B.addAttribute(Kind);
1420 } else if (Record[i] == 1) { // Integer attribute
1421 Attribute::AttrKind Kind;
1422 if (std::error_code EC = parseAttrKind(Record[++i], &Kind))
1424 if (Kind == Attribute::Alignment)
1425 B.addAlignmentAttr(Record[++i]);
1426 else if (Kind == Attribute::StackAlignment)
1427 B.addStackAlignmentAttr(Record[++i]);
1428 else if (Kind == Attribute::Dereferenceable)
1429 B.addDereferenceableAttr(Record[++i]);
1430 else if (Kind == Attribute::DereferenceableOrNull)
1431 B.addDereferenceableOrNullAttr(Record[++i]);
1432 } else { // String attribute
1433 assert((Record[i] == 3 || Record[i] == 4) &&
1434 "Invalid attribute group entry");
1435 bool HasValue = (Record[i++] == 4);
1436 SmallString<64> KindStr;
1437 SmallString<64> ValStr;
1439 while (Record[i] != 0 && i != e)
1440 KindStr += Record[i++];
1441 assert(Record[i] == 0 && "Kind string not null terminated");
1444 // Has a value associated with it.
1445 ++i; // Skip the '0' that terminates the "kind" string.
1446 while (Record[i] != 0 && i != e)
1447 ValStr += Record[i++];
1448 assert(Record[i] == 0 && "Value string not null terminated");
1451 B.addAttribute(KindStr.str(), ValStr.str());
1455 MAttributeGroups[GrpID] = AttributeSet::get(Context, Idx, B);
1462 std::error_code BitcodeReader::parseTypeTable() {
1463 if (Stream.EnterSubBlock(bitc::TYPE_BLOCK_ID_NEW))
1464 return error("Invalid record");
1466 return parseTypeTableBody();
1469 std::error_code BitcodeReader::parseTypeTableBody() {
1470 if (!TypeList.empty())
1471 return error("Invalid multiple blocks");
1473 SmallVector<uint64_t, 64> Record;
1474 unsigned NumRecords = 0;
1476 SmallString<64> TypeName;
1478 // Read all the records for this type table.
1480 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1482 switch (Entry.Kind) {
1483 case BitstreamEntry::SubBlock: // Handled for us already.
1484 case BitstreamEntry::Error:
1485 return error("Malformed block");
1486 case BitstreamEntry::EndBlock:
1487 if (NumRecords != TypeList.size())
1488 return error("Malformed block");
1489 return std::error_code();
1490 case BitstreamEntry::Record:
1491 // The interesting case.
1497 Type *ResultTy = nullptr;
1498 switch (Stream.readRecord(Entry.ID, Record)) {
1500 return error("Invalid value");
1501 case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries]
1502 // TYPE_CODE_NUMENTRY contains a count of the number of types in the
1503 // type list. This allows us to reserve space.
1504 if (Record.size() < 1)
1505 return error("Invalid record");
1506 TypeList.resize(Record[0]);
1508 case bitc::TYPE_CODE_VOID: // VOID
1509 ResultTy = Type::getVoidTy(Context);
1511 case bitc::TYPE_CODE_HALF: // HALF
1512 ResultTy = Type::getHalfTy(Context);
1514 case bitc::TYPE_CODE_FLOAT: // FLOAT
1515 ResultTy = Type::getFloatTy(Context);
1517 case bitc::TYPE_CODE_DOUBLE: // DOUBLE
1518 ResultTy = Type::getDoubleTy(Context);
1520 case bitc::TYPE_CODE_X86_FP80: // X86_FP80
1521 ResultTy = Type::getX86_FP80Ty(Context);
1523 case bitc::TYPE_CODE_FP128: // FP128
1524 ResultTy = Type::getFP128Ty(Context);
1526 case bitc::TYPE_CODE_PPC_FP128: // PPC_FP128
1527 ResultTy = Type::getPPC_FP128Ty(Context);
1529 case bitc::TYPE_CODE_LABEL: // LABEL
1530 ResultTy = Type::getLabelTy(Context);
1532 case bitc::TYPE_CODE_METADATA: // METADATA
1533 ResultTy = Type::getMetadataTy(Context);
1535 case bitc::TYPE_CODE_X86_MMX: // X86_MMX
1536 ResultTy = Type::getX86_MMXTy(Context);
1538 case bitc::TYPE_CODE_TOKEN: // TOKEN
1539 ResultTy = Type::getTokenTy(Context);
1541 case bitc::TYPE_CODE_INTEGER: { // INTEGER: [width]
1542 if (Record.size() < 1)
1543 return error("Invalid record");
1545 uint64_t NumBits = Record[0];
1546 if (NumBits < IntegerType::MIN_INT_BITS ||
1547 NumBits > IntegerType::MAX_INT_BITS)
1548 return error("Bitwidth for integer type out of range");
1549 ResultTy = IntegerType::get(Context, NumBits);
1552 case bitc::TYPE_CODE_POINTER: { // POINTER: [pointee type] or
1553 // [pointee type, address space]
1554 if (Record.size() < 1)
1555 return error("Invalid record");
1556 unsigned AddressSpace = 0;
1557 if (Record.size() == 2)
1558 AddressSpace = Record[1];
1559 ResultTy = getTypeByID(Record[0]);
1561 !PointerType::isValidElementType(ResultTy))
1562 return error("Invalid type");
1563 ResultTy = PointerType::get(ResultTy, AddressSpace);
1566 case bitc::TYPE_CODE_FUNCTION_OLD: {
1567 // FIXME: attrid is dead, remove it in LLVM 4.0
1568 // FUNCTION: [vararg, attrid, retty, paramty x N]
1569 if (Record.size() < 3)
1570 return error("Invalid record");
1571 SmallVector<Type*, 8> ArgTys;
1572 for (unsigned i = 3, e = Record.size(); i != e; ++i) {
1573 if (Type *T = getTypeByID(Record[i]))
1574 ArgTys.push_back(T);
1579 ResultTy = getTypeByID(Record[2]);
1580 if (!ResultTy || ArgTys.size() < Record.size()-3)
1581 return error("Invalid type");
1583 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
1586 case bitc::TYPE_CODE_FUNCTION: {
1587 // FUNCTION: [vararg, retty, paramty x N]
1588 if (Record.size() < 2)
1589 return error("Invalid record");
1590 SmallVector<Type*, 8> ArgTys;
1591 for (unsigned i = 2, e = Record.size(); i != e; ++i) {
1592 if (Type *T = getTypeByID(Record[i])) {
1593 if (!FunctionType::isValidArgumentType(T))
1594 return error("Invalid function argument type");
1595 ArgTys.push_back(T);
1601 ResultTy = getTypeByID(Record[1]);
1602 if (!ResultTy || ArgTys.size() < Record.size()-2)
1603 return error("Invalid type");
1605 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
1608 case bitc::TYPE_CODE_STRUCT_ANON: { // STRUCT: [ispacked, eltty x N]
1609 if (Record.size() < 1)
1610 return error("Invalid record");
1611 SmallVector<Type*, 8> EltTys;
1612 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
1613 if (Type *T = getTypeByID(Record[i]))
1614 EltTys.push_back(T);
1618 if (EltTys.size() != Record.size()-1)
1619 return error("Invalid type");
1620 ResultTy = StructType::get(Context, EltTys, Record[0]);
1623 case bitc::TYPE_CODE_STRUCT_NAME: // STRUCT_NAME: [strchr x N]
1624 if (convertToString(Record, 0, TypeName))
1625 return error("Invalid record");
1628 case bitc::TYPE_CODE_STRUCT_NAMED: { // STRUCT: [ispacked, eltty x N]
1629 if (Record.size() < 1)
1630 return error("Invalid record");
1632 if (NumRecords >= TypeList.size())
1633 return error("Invalid TYPE table");
1635 // Check to see if this was forward referenced, if so fill in the temp.
1636 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
1638 Res->setName(TypeName);
1639 TypeList[NumRecords] = nullptr;
1640 } else // Otherwise, create a new struct.
1641 Res = createIdentifiedStructType(Context, TypeName);
1644 SmallVector<Type*, 8> EltTys;
1645 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
1646 if (Type *T = getTypeByID(Record[i]))
1647 EltTys.push_back(T);
1651 if (EltTys.size() != Record.size()-1)
1652 return error("Invalid record");
1653 Res->setBody(EltTys, Record[0]);
1657 case bitc::TYPE_CODE_OPAQUE: { // OPAQUE: []
1658 if (Record.size() != 1)
1659 return error("Invalid record");
1661 if (NumRecords >= TypeList.size())
1662 return error("Invalid TYPE table");
1664 // Check to see if this was forward referenced, if so fill in the temp.
1665 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
1667 Res->setName(TypeName);
1668 TypeList[NumRecords] = nullptr;
1669 } else // Otherwise, create a new struct with no body.
1670 Res = createIdentifiedStructType(Context, TypeName);
1675 case bitc::TYPE_CODE_ARRAY: // ARRAY: [numelts, eltty]
1676 if (Record.size() < 2)
1677 return error("Invalid record");
1678 ResultTy = getTypeByID(Record[1]);
1679 if (!ResultTy || !ArrayType::isValidElementType(ResultTy))
1680 return error("Invalid type");
1681 ResultTy = ArrayType::get(ResultTy, Record[0]);
1683 case bitc::TYPE_CODE_VECTOR: // VECTOR: [numelts, eltty]
1684 if (Record.size() < 2)
1685 return error("Invalid record");
1687 return error("Invalid vector length");
1688 ResultTy = getTypeByID(Record[1]);
1689 if (!ResultTy || !StructType::isValidElementType(ResultTy))
1690 return error("Invalid type");
1691 ResultTy = VectorType::get(ResultTy, Record[0]);
1695 if (NumRecords >= TypeList.size())
1696 return error("Invalid TYPE table");
1697 if (TypeList[NumRecords])
1699 "Invalid TYPE table: Only named structs can be forward referenced");
1700 assert(ResultTy && "Didn't read a type?");
1701 TypeList[NumRecords++] = ResultTy;
1705 std::error_code BitcodeReader::parseOperandBundleTags() {
1706 if (Stream.EnterSubBlock(bitc::OPERAND_BUNDLE_TAGS_BLOCK_ID))
1707 return error("Invalid record");
1709 if (!BundleTags.empty())
1710 return error("Invalid multiple blocks");
1712 SmallVector<uint64_t, 64> Record;
1715 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1717 switch (Entry.Kind) {
1718 case BitstreamEntry::SubBlock: // Handled for us already.
1719 case BitstreamEntry::Error:
1720 return error("Malformed block");
1721 case BitstreamEntry::EndBlock:
1722 return std::error_code();
1723 case BitstreamEntry::Record:
1724 // The interesting case.
1728 // Tags are implicitly mapped to integers by their order.
1730 if (Stream.readRecord(Entry.ID, Record) != bitc::OPERAND_BUNDLE_TAG)
1731 return error("Invalid record");
1733 // OPERAND_BUNDLE_TAG: [strchr x N]
1734 BundleTags.emplace_back();
1735 if (convertToString(Record, 0, BundleTags.back()))
1736 return error("Invalid record");
1741 /// Associate a value with its name from the given index in the provided record.
1742 ErrorOr<Value *> BitcodeReader::recordValue(SmallVectorImpl<uint64_t> &Record,
1743 unsigned NameIndex, Triple &TT) {
1744 SmallString<128> ValueName;
1745 if (convertToString(Record, NameIndex, ValueName))
1746 return error("Invalid record");
1747 unsigned ValueID = Record[0];
1748 if (ValueID >= ValueList.size() || !ValueList[ValueID])
1749 return error("Invalid record");
1750 Value *V = ValueList[ValueID];
1752 V->setName(StringRef(ValueName.data(), ValueName.size()));
1753 auto *GO = dyn_cast<GlobalObject>(V);
1755 if (GO->getComdat() == reinterpret_cast<Comdat *>(1)) {
1756 if (TT.isOSBinFormatMachO())
1757 GO->setComdat(nullptr);
1759 GO->setComdat(TheModule->getOrInsertComdat(V->getName()));
1765 /// Parse the value symbol table at either the current parsing location or
1766 /// at the given bit offset if provided.
1767 std::error_code BitcodeReader::parseValueSymbolTable(uint64_t Offset) {
1768 uint64_t CurrentBit;
1769 // Pass in the Offset to distinguish between calling for the module-level
1770 // VST (where we want to jump to the VST offset) and the function-level
1771 // VST (where we don't).
1773 // Save the current parsing location so we can jump back at the end
1775 CurrentBit = Stream.GetCurrentBitNo();
1776 Stream.JumpToBit(Offset * 32);
1778 // Do some checking if we are in debug mode.
1779 BitstreamEntry Entry = Stream.advance();
1780 assert(Entry.Kind == BitstreamEntry::SubBlock);
1781 assert(Entry.ID == bitc::VALUE_SYMTAB_BLOCK_ID);
1783 // In NDEBUG mode ignore the output so we don't get an unused variable
1789 // Compute the delta between the bitcode indices in the VST (the word offset
1790 // to the word-aligned ENTER_SUBBLOCK for the function block, and that
1791 // expected by the lazy reader. The reader's EnterSubBlock expects to have
1792 // already read the ENTER_SUBBLOCK code (size getAbbrevIDWidth) and BlockID
1793 // (size BlockIDWidth). Note that we access the stream's AbbrevID width here
1794 // just before entering the VST subblock because: 1) the EnterSubBlock
1795 // changes the AbbrevID width; 2) the VST block is nested within the same
1796 // outer MODULE_BLOCK as the FUNCTION_BLOCKs and therefore have the same
1797 // AbbrevID width before calling EnterSubBlock; and 3) when we want to
1798 // jump to the FUNCTION_BLOCK using this offset later, we don't want
1799 // to rely on the stream's AbbrevID width being that of the MODULE_BLOCK.
1800 unsigned FuncBitcodeOffsetDelta =
1801 Stream.getAbbrevIDWidth() + bitc::BlockIDWidth;
1803 if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
1804 return error("Invalid record");
1806 SmallVector<uint64_t, 64> Record;
1808 Triple TT(TheModule->getTargetTriple());
1810 // Read all the records for this value table.
1811 SmallString<128> ValueName;
1813 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1815 switch (Entry.Kind) {
1816 case BitstreamEntry::SubBlock: // Handled for us already.
1817 case BitstreamEntry::Error:
1818 return error("Malformed block");
1819 case BitstreamEntry::EndBlock:
1821 Stream.JumpToBit(CurrentBit);
1822 return std::error_code();
1823 case BitstreamEntry::Record:
1824 // The interesting case.
1830 switch (Stream.readRecord(Entry.ID, Record)) {
1831 default: // Default behavior: unknown type.
1833 case bitc::VST_CODE_ENTRY: { // VST_ENTRY: [valueid, namechar x N]
1834 ErrorOr<Value *> ValOrErr = recordValue(Record, 1, TT);
1835 if (std::error_code EC = ValOrErr.getError())
1840 case bitc::VST_CODE_FNENTRY: {
1841 // VST_FNENTRY: [valueid, offset, namechar x N]
1842 ErrorOr<Value *> ValOrErr = recordValue(Record, 2, TT);
1843 if (std::error_code EC = ValOrErr.getError())
1845 Value *V = ValOrErr.get();
1847 auto *GO = dyn_cast<GlobalObject>(V);
1849 // If this is an alias, need to get the actual Function object
1850 // it aliases, in order to set up the DeferredFunctionInfo entry below.
1851 auto *GA = dyn_cast<GlobalAlias>(V);
1853 GO = GA->getBaseObject();
1857 uint64_t FuncWordOffset = Record[1];
1858 Function *F = dyn_cast<Function>(GO);
1860 uint64_t FuncBitOffset = FuncWordOffset * 32;
1861 DeferredFunctionInfo[F] = FuncBitOffset + FuncBitcodeOffsetDelta;
1862 // Set the LastFunctionBlockBit to point to the last function block.
1863 // Later when parsing is resumed after function materialization,
1864 // we can simply skip that last function block.
1865 if (FuncBitOffset > LastFunctionBlockBit)
1866 LastFunctionBlockBit = FuncBitOffset;
1869 case bitc::VST_CODE_BBENTRY: {
1870 if (convertToString(Record, 1, ValueName))
1871 return error("Invalid record");
1872 BasicBlock *BB = getBasicBlock(Record[0]);
1874 return error("Invalid record");
1876 BB->setName(StringRef(ValueName.data(), ValueName.size()));
1884 static int64_t unrotateSign(uint64_t U) { return U & 1 ? ~(U >> 1) : U >> 1; }
1886 std::error_code BitcodeReader::parseMetadata() {
1887 IsMetadataMaterialized = true;
1888 unsigned NextMDValueNo = MDValueList.size();
1890 if (Stream.EnterSubBlock(bitc::METADATA_BLOCK_ID))
1891 return error("Invalid record");
1893 SmallVector<uint64_t, 64> Record;
1896 [&](unsigned ID) -> Metadata *{ return MDValueList.getValueFwdRef(ID); };
1897 auto getMDOrNull = [&](unsigned ID) -> Metadata *{
1899 return getMD(ID - 1);
1902 auto getMDString = [&](unsigned ID) -> MDString *{
1903 // This requires that the ID is not really a forward reference. In
1904 // particular, the MDString must already have been resolved.
1905 return cast_or_null<MDString>(getMDOrNull(ID));
1908 #define GET_OR_DISTINCT(CLASS, DISTINCT, ARGS) \
1909 (DISTINCT ? CLASS::getDistinct ARGS : CLASS::get ARGS)
1911 // Read all the records.
1913 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1915 switch (Entry.Kind) {
1916 case BitstreamEntry::SubBlock: // Handled for us already.
1917 case BitstreamEntry::Error:
1918 return error("Malformed block");
1919 case BitstreamEntry::EndBlock:
1920 MDValueList.tryToResolveCycles();
1921 return std::error_code();
1922 case BitstreamEntry::Record:
1923 // The interesting case.
1929 unsigned Code = Stream.readRecord(Entry.ID, Record);
1930 bool IsDistinct = false;
1932 default: // Default behavior: ignore.
1934 case bitc::METADATA_NAME: {
1935 // Read name of the named metadata.
1936 SmallString<8> Name(Record.begin(), Record.end());
1938 Code = Stream.ReadCode();
1940 unsigned NextBitCode = Stream.readRecord(Code, Record);
1941 if (NextBitCode != bitc::METADATA_NAMED_NODE)
1942 return error("METADATA_NAME not followed by METADATA_NAMED_NODE");
1944 // Read named metadata elements.
1945 unsigned Size = Record.size();
1946 NamedMDNode *NMD = TheModule->getOrInsertNamedMetadata(Name);
1947 for (unsigned i = 0; i != Size; ++i) {
1948 MDNode *MD = dyn_cast_or_null<MDNode>(MDValueList.getValueFwdRef(Record[i]));
1950 return error("Invalid record");
1951 NMD->addOperand(MD);
1955 case bitc::METADATA_OLD_FN_NODE: {
1956 // FIXME: Remove in 4.0.
1957 // This is a LocalAsMetadata record, the only type of function-local
1959 if (Record.size() % 2 == 1)
1960 return error("Invalid record");
1962 // If this isn't a LocalAsMetadata record, we're dropping it. This used
1963 // to be legal, but there's no upgrade path.
1964 auto dropRecord = [&] {
1965 MDValueList.assignValue(MDNode::get(Context, None), NextMDValueNo++);
1967 if (Record.size() != 2) {
1972 Type *Ty = getTypeByID(Record[0]);
1973 if (Ty->isMetadataTy() || Ty->isVoidTy()) {
1978 MDValueList.assignValue(
1979 LocalAsMetadata::get(ValueList.getValueFwdRef(Record[1], Ty)),
1983 case bitc::METADATA_OLD_NODE: {
1984 // FIXME: Remove in 4.0.
1985 if (Record.size() % 2 == 1)
1986 return error("Invalid record");
1988 unsigned Size = Record.size();
1989 SmallVector<Metadata *, 8> Elts;
1990 for (unsigned i = 0; i != Size; i += 2) {
1991 Type *Ty = getTypeByID(Record[i]);
1993 return error("Invalid record");
1994 if (Ty->isMetadataTy())
1995 Elts.push_back(MDValueList.getValueFwdRef(Record[i+1]));
1996 else if (!Ty->isVoidTy()) {
1998 ValueAsMetadata::get(ValueList.getValueFwdRef(Record[i + 1], Ty));
1999 assert(isa<ConstantAsMetadata>(MD) &&
2000 "Expected non-function-local metadata");
2003 Elts.push_back(nullptr);
2005 MDValueList.assignValue(MDNode::get(Context, Elts), NextMDValueNo++);
2008 case bitc::METADATA_VALUE: {
2009 if (Record.size() != 2)
2010 return error("Invalid record");
2012 Type *Ty = getTypeByID(Record[0]);
2013 if (Ty->isMetadataTy() || Ty->isVoidTy())
2014 return error("Invalid record");
2016 MDValueList.assignValue(
2017 ValueAsMetadata::get(ValueList.getValueFwdRef(Record[1], Ty)),
2021 case bitc::METADATA_DISTINCT_NODE:
2024 case bitc::METADATA_NODE: {
2025 SmallVector<Metadata *, 8> Elts;
2026 Elts.reserve(Record.size());
2027 for (unsigned ID : Record)
2028 Elts.push_back(ID ? MDValueList.getValueFwdRef(ID - 1) : nullptr);
2029 MDValueList.assignValue(IsDistinct ? MDNode::getDistinct(Context, Elts)
2030 : MDNode::get(Context, Elts),
2034 case bitc::METADATA_LOCATION: {
2035 if (Record.size() != 5)
2036 return error("Invalid record");
2038 unsigned Line = Record[1];
2039 unsigned Column = Record[2];
2040 MDNode *Scope = cast<MDNode>(MDValueList.getValueFwdRef(Record[3]));
2041 Metadata *InlinedAt =
2042 Record[4] ? MDValueList.getValueFwdRef(Record[4] - 1) : nullptr;
2043 MDValueList.assignValue(
2044 GET_OR_DISTINCT(DILocation, Record[0],
2045 (Context, Line, Column, Scope, InlinedAt)),
2049 case bitc::METADATA_GENERIC_DEBUG: {
2050 if (Record.size() < 4)
2051 return error("Invalid record");
2053 unsigned Tag = Record[1];
2054 unsigned Version = Record[2];
2056 if (Tag >= 1u << 16 || Version != 0)
2057 return error("Invalid record");
2059 auto *Header = getMDString(Record[3]);
2060 SmallVector<Metadata *, 8> DwarfOps;
2061 for (unsigned I = 4, E = Record.size(); I != E; ++I)
2062 DwarfOps.push_back(Record[I] ? MDValueList.getValueFwdRef(Record[I] - 1)
2064 MDValueList.assignValue(GET_OR_DISTINCT(GenericDINode, Record[0],
2065 (Context, Tag, Header, DwarfOps)),
2069 case bitc::METADATA_SUBRANGE: {
2070 if (Record.size() != 3)
2071 return error("Invalid record");
2073 MDValueList.assignValue(
2074 GET_OR_DISTINCT(DISubrange, Record[0],
2075 (Context, Record[1], unrotateSign(Record[2]))),
2079 case bitc::METADATA_ENUMERATOR: {
2080 if (Record.size() != 3)
2081 return error("Invalid record");
2083 MDValueList.assignValue(GET_OR_DISTINCT(DIEnumerator, Record[0],
2084 (Context, unrotateSign(Record[1]),
2085 getMDString(Record[2]))),
2089 case bitc::METADATA_BASIC_TYPE: {
2090 if (Record.size() != 6)
2091 return error("Invalid record");
2093 MDValueList.assignValue(
2094 GET_OR_DISTINCT(DIBasicType, Record[0],
2095 (Context, Record[1], getMDString(Record[2]),
2096 Record[3], Record[4], Record[5])),
2100 case bitc::METADATA_DERIVED_TYPE: {
2101 if (Record.size() != 12)
2102 return error("Invalid record");
2104 MDValueList.assignValue(
2105 GET_OR_DISTINCT(DIDerivedType, Record[0],
2106 (Context, Record[1], getMDString(Record[2]),
2107 getMDOrNull(Record[3]), Record[4],
2108 getMDOrNull(Record[5]), getMDOrNull(Record[6]),
2109 Record[7], Record[8], Record[9], Record[10],
2110 getMDOrNull(Record[11]))),
2114 case bitc::METADATA_COMPOSITE_TYPE: {
2115 if (Record.size() != 16)
2116 return error("Invalid record");
2118 MDValueList.assignValue(
2119 GET_OR_DISTINCT(DICompositeType, Record[0],
2120 (Context, Record[1], getMDString(Record[2]),
2121 getMDOrNull(Record[3]), Record[4],
2122 getMDOrNull(Record[5]), getMDOrNull(Record[6]),
2123 Record[7], Record[8], Record[9], Record[10],
2124 getMDOrNull(Record[11]), Record[12],
2125 getMDOrNull(Record[13]), getMDOrNull(Record[14]),
2126 getMDString(Record[15]))),
2130 case bitc::METADATA_SUBROUTINE_TYPE: {
2131 if (Record.size() != 3)
2132 return error("Invalid record");
2134 MDValueList.assignValue(
2135 GET_OR_DISTINCT(DISubroutineType, Record[0],
2136 (Context, Record[1], getMDOrNull(Record[2]))),
2141 case bitc::METADATA_MODULE: {
2142 if (Record.size() != 6)
2143 return error("Invalid record");
2145 MDValueList.assignValue(
2146 GET_OR_DISTINCT(DIModule, Record[0],
2147 (Context, getMDOrNull(Record[1]),
2148 getMDString(Record[2]), getMDString(Record[3]),
2149 getMDString(Record[4]), getMDString(Record[5]))),
2154 case bitc::METADATA_FILE: {
2155 if (Record.size() != 3)
2156 return error("Invalid record");
2158 MDValueList.assignValue(
2159 GET_OR_DISTINCT(DIFile, Record[0], (Context, getMDString(Record[1]),
2160 getMDString(Record[2]))),
2164 case bitc::METADATA_COMPILE_UNIT: {
2165 if (Record.size() < 14 || Record.size() > 15)
2166 return error("Invalid record");
2168 // Ignore Record[1], which indicates whether this compile unit is
2169 // distinct. It's always distinct.
2170 MDValueList.assignValue(
2171 DICompileUnit::getDistinct(
2172 Context, Record[1], getMDOrNull(Record[2]),
2173 getMDString(Record[3]), Record[4], getMDString(Record[5]),
2174 Record[6], getMDString(Record[7]), Record[8],
2175 getMDOrNull(Record[9]), getMDOrNull(Record[10]),
2176 getMDOrNull(Record[11]), getMDOrNull(Record[12]),
2177 getMDOrNull(Record[13]), Record.size() == 14 ? 0 : Record[14]),
2181 case bitc::METADATA_SUBPROGRAM: {
2182 if (Record.size() != 19)
2183 return error("Invalid record");
2185 MDValueList.assignValue(
2188 Record[0] || Record[8], // All definitions should be distinct.
2189 (Context, getMDOrNull(Record[1]), getMDString(Record[2]),
2190 getMDString(Record[3]), getMDOrNull(Record[4]), Record[5],
2191 getMDOrNull(Record[6]), Record[7], Record[8], Record[9],
2192 getMDOrNull(Record[10]), Record[11], Record[12], Record[13],
2193 Record[14], getMDOrNull(Record[15]), getMDOrNull(Record[16]),
2194 getMDOrNull(Record[17]), getMDOrNull(Record[18]))),
2198 case bitc::METADATA_LEXICAL_BLOCK: {
2199 if (Record.size() != 5)
2200 return error("Invalid record");
2202 MDValueList.assignValue(
2203 GET_OR_DISTINCT(DILexicalBlock, Record[0],
2204 (Context, getMDOrNull(Record[1]),
2205 getMDOrNull(Record[2]), Record[3], Record[4])),
2209 case bitc::METADATA_LEXICAL_BLOCK_FILE: {
2210 if (Record.size() != 4)
2211 return error("Invalid record");
2213 MDValueList.assignValue(
2214 GET_OR_DISTINCT(DILexicalBlockFile, Record[0],
2215 (Context, getMDOrNull(Record[1]),
2216 getMDOrNull(Record[2]), Record[3])),
2220 case bitc::METADATA_NAMESPACE: {
2221 if (Record.size() != 5)
2222 return error("Invalid record");
2224 MDValueList.assignValue(
2225 GET_OR_DISTINCT(DINamespace, Record[0],
2226 (Context, getMDOrNull(Record[1]),
2227 getMDOrNull(Record[2]), getMDString(Record[3]),
2232 case bitc::METADATA_TEMPLATE_TYPE: {
2233 if (Record.size() != 3)
2234 return error("Invalid record");
2236 MDValueList.assignValue(GET_OR_DISTINCT(DITemplateTypeParameter,
2238 (Context, getMDString(Record[1]),
2239 getMDOrNull(Record[2]))),
2243 case bitc::METADATA_TEMPLATE_VALUE: {
2244 if (Record.size() != 5)
2245 return error("Invalid record");
2247 MDValueList.assignValue(
2248 GET_OR_DISTINCT(DITemplateValueParameter, Record[0],
2249 (Context, Record[1], getMDString(Record[2]),
2250 getMDOrNull(Record[3]), getMDOrNull(Record[4]))),
2254 case bitc::METADATA_GLOBAL_VAR: {
2255 if (Record.size() != 11)
2256 return error("Invalid record");
2258 MDValueList.assignValue(
2259 GET_OR_DISTINCT(DIGlobalVariable, Record[0],
2260 (Context, getMDOrNull(Record[1]),
2261 getMDString(Record[2]), getMDString(Record[3]),
2262 getMDOrNull(Record[4]), Record[5],
2263 getMDOrNull(Record[6]), Record[7], Record[8],
2264 getMDOrNull(Record[9]), getMDOrNull(Record[10]))),
2268 case bitc::METADATA_LOCAL_VAR: {
2269 // 10th field is for the obseleted 'inlinedAt:' field.
2270 if (Record.size() < 8 || Record.size() > 10)
2271 return error("Invalid record");
2273 // 2nd field used to be an artificial tag, either DW_TAG_auto_variable or
2274 // DW_TAG_arg_variable.
2275 bool HasTag = Record.size() > 8;
2276 MDValueList.assignValue(
2277 GET_OR_DISTINCT(DILocalVariable, Record[0],
2278 (Context, getMDOrNull(Record[1 + HasTag]),
2279 getMDString(Record[2 + HasTag]),
2280 getMDOrNull(Record[3 + HasTag]), Record[4 + HasTag],
2281 getMDOrNull(Record[5 + HasTag]), Record[6 + HasTag],
2282 Record[7 + HasTag])),
2286 case bitc::METADATA_EXPRESSION: {
2287 if (Record.size() < 1)
2288 return error("Invalid record");
2290 MDValueList.assignValue(
2291 GET_OR_DISTINCT(DIExpression, Record[0],
2292 (Context, makeArrayRef(Record).slice(1))),
2296 case bitc::METADATA_OBJC_PROPERTY: {
2297 if (Record.size() != 8)
2298 return error("Invalid record");
2300 MDValueList.assignValue(
2301 GET_OR_DISTINCT(DIObjCProperty, Record[0],
2302 (Context, getMDString(Record[1]),
2303 getMDOrNull(Record[2]), Record[3],
2304 getMDString(Record[4]), getMDString(Record[5]),
2305 Record[6], getMDOrNull(Record[7]))),
2309 case bitc::METADATA_IMPORTED_ENTITY: {
2310 if (Record.size() != 6)
2311 return error("Invalid record");
2313 MDValueList.assignValue(
2314 GET_OR_DISTINCT(DIImportedEntity, Record[0],
2315 (Context, Record[1], getMDOrNull(Record[2]),
2316 getMDOrNull(Record[3]), Record[4],
2317 getMDString(Record[5]))),
2321 case bitc::METADATA_STRING: {
2322 std::string String(Record.begin(), Record.end());
2323 llvm::UpgradeMDStringConstant(String);
2324 Metadata *MD = MDString::get(Context, String);
2325 MDValueList.assignValue(MD, NextMDValueNo++);
2328 case bitc::METADATA_KIND: {
2329 if (Record.size() < 2)
2330 return error("Invalid record");
2332 unsigned Kind = Record[0];
2333 SmallString<8> Name(Record.begin()+1, Record.end());
2335 unsigned NewKind = TheModule->getMDKindID(Name.str());
2336 if (!MDKindMap.insert(std::make_pair(Kind, NewKind)).second)
2337 return error("Conflicting METADATA_KIND records");
2342 #undef GET_OR_DISTINCT
2345 /// Decode a signed value stored with the sign bit in the LSB for dense VBR
2347 uint64_t BitcodeReader::decodeSignRotatedValue(uint64_t V) {
2352 // There is no such thing as -0 with integers. "-0" really means MININT.
2356 /// Resolve all of the initializers for global values and aliases that we can.
2357 std::error_code BitcodeReader::resolveGlobalAndAliasInits() {
2358 std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInitWorklist;
2359 std::vector<std::pair<GlobalAlias*, unsigned> > AliasInitWorklist;
2360 std::vector<std::pair<Function*, unsigned> > FunctionPrefixWorklist;
2361 std::vector<std::pair<Function*, unsigned> > FunctionPrologueWorklist;
2362 std::vector<std::pair<Function*, unsigned> > FunctionPersonalityFnWorklist;
2364 GlobalInitWorklist.swap(GlobalInits);
2365 AliasInitWorklist.swap(AliasInits);
2366 FunctionPrefixWorklist.swap(FunctionPrefixes);
2367 FunctionPrologueWorklist.swap(FunctionPrologues);
2368 FunctionPersonalityFnWorklist.swap(FunctionPersonalityFns);
2370 while (!GlobalInitWorklist.empty()) {
2371 unsigned ValID = GlobalInitWorklist.back().second;
2372 if (ValID >= ValueList.size()) {
2373 // Not ready to resolve this yet, it requires something later in the file.
2374 GlobalInits.push_back(GlobalInitWorklist.back());
2376 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
2377 GlobalInitWorklist.back().first->setInitializer(C);
2379 return error("Expected a constant");
2381 GlobalInitWorklist.pop_back();
2384 while (!AliasInitWorklist.empty()) {
2385 unsigned ValID = AliasInitWorklist.back().second;
2386 if (ValID >= ValueList.size()) {
2387 AliasInits.push_back(AliasInitWorklist.back());
2389 Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]);
2391 return error("Expected a constant");
2392 GlobalAlias *Alias = AliasInitWorklist.back().first;
2393 if (C->getType() != Alias->getType())
2394 return error("Alias and aliasee types don't match");
2395 Alias->setAliasee(C);
2397 AliasInitWorklist.pop_back();
2400 while (!FunctionPrefixWorklist.empty()) {
2401 unsigned ValID = FunctionPrefixWorklist.back().second;
2402 if (ValID >= ValueList.size()) {
2403 FunctionPrefixes.push_back(FunctionPrefixWorklist.back());
2405 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
2406 FunctionPrefixWorklist.back().first->setPrefixData(C);
2408 return error("Expected a constant");
2410 FunctionPrefixWorklist.pop_back();
2413 while (!FunctionPrologueWorklist.empty()) {
2414 unsigned ValID = FunctionPrologueWorklist.back().second;
2415 if (ValID >= ValueList.size()) {
2416 FunctionPrologues.push_back(FunctionPrologueWorklist.back());
2418 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
2419 FunctionPrologueWorklist.back().first->setPrologueData(C);
2421 return error("Expected a constant");
2423 FunctionPrologueWorklist.pop_back();
2426 while (!FunctionPersonalityFnWorklist.empty()) {
2427 unsigned ValID = FunctionPersonalityFnWorklist.back().second;
2428 if (ValID >= ValueList.size()) {
2429 FunctionPersonalityFns.push_back(FunctionPersonalityFnWorklist.back());
2431 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
2432 FunctionPersonalityFnWorklist.back().first->setPersonalityFn(C);
2434 return error("Expected a constant");
2436 FunctionPersonalityFnWorklist.pop_back();
2439 return std::error_code();
2442 static APInt readWideAPInt(ArrayRef<uint64_t> Vals, unsigned TypeBits) {
2443 SmallVector<uint64_t, 8> Words(Vals.size());
2444 std::transform(Vals.begin(), Vals.end(), Words.begin(),
2445 BitcodeReader::decodeSignRotatedValue);
2447 return APInt(TypeBits, Words);
2450 std::error_code BitcodeReader::parseConstants() {
2451 if (Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID))
2452 return error("Invalid record");
2454 SmallVector<uint64_t, 64> Record;
2456 // Read all the records for this value table.
2457 Type *CurTy = Type::getInt32Ty(Context);
2458 unsigned NextCstNo = ValueList.size();
2460 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
2462 switch (Entry.Kind) {
2463 case BitstreamEntry::SubBlock: // Handled for us already.
2464 case BitstreamEntry::Error:
2465 return error("Malformed block");
2466 case BitstreamEntry::EndBlock:
2467 if (NextCstNo != ValueList.size())
2468 return error("Invalid ronstant reference");
2470 // Once all the constants have been read, go through and resolve forward
2472 ValueList.resolveConstantForwardRefs();
2473 return std::error_code();
2474 case BitstreamEntry::Record:
2475 // The interesting case.
2482 unsigned BitCode = Stream.readRecord(Entry.ID, Record);
2484 default: // Default behavior: unknown constant
2485 case bitc::CST_CODE_UNDEF: // UNDEF
2486 V = UndefValue::get(CurTy);
2488 case bitc::CST_CODE_SETTYPE: // SETTYPE: [typeid]
2490 return error("Invalid record");
2491 if (Record[0] >= TypeList.size() || !TypeList[Record[0]])
2492 return error("Invalid record");
2493 CurTy = TypeList[Record[0]];
2494 continue; // Skip the ValueList manipulation.
2495 case bitc::CST_CODE_NULL: // NULL
2496 V = Constant::getNullValue(CurTy);
2498 case bitc::CST_CODE_INTEGER: // INTEGER: [intval]
2499 if (!CurTy->isIntegerTy() || Record.empty())
2500 return error("Invalid record");
2501 V = ConstantInt::get(CurTy, decodeSignRotatedValue(Record[0]));
2503 case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval]
2504 if (!CurTy->isIntegerTy() || Record.empty())
2505 return error("Invalid record");
2508 readWideAPInt(Record, cast<IntegerType>(CurTy)->getBitWidth());
2509 V = ConstantInt::get(Context, VInt);
2513 case bitc::CST_CODE_FLOAT: { // FLOAT: [fpval]
2515 return error("Invalid record");
2516 if (CurTy->isHalfTy())
2517 V = ConstantFP::get(Context, APFloat(APFloat::IEEEhalf,
2518 APInt(16, (uint16_t)Record[0])));
2519 else if (CurTy->isFloatTy())
2520 V = ConstantFP::get(Context, APFloat(APFloat::IEEEsingle,
2521 APInt(32, (uint32_t)Record[0])));
2522 else if (CurTy->isDoubleTy())
2523 V = ConstantFP::get(Context, APFloat(APFloat::IEEEdouble,
2524 APInt(64, Record[0])));
2525 else if (CurTy->isX86_FP80Ty()) {
2526 // Bits are not stored the same way as a normal i80 APInt, compensate.
2527 uint64_t Rearrange[2];
2528 Rearrange[0] = (Record[1] & 0xffffLL) | (Record[0] << 16);
2529 Rearrange[1] = Record[0] >> 48;
2530 V = ConstantFP::get(Context, APFloat(APFloat::x87DoubleExtended,
2531 APInt(80, Rearrange)));
2532 } else if (CurTy->isFP128Ty())
2533 V = ConstantFP::get(Context, APFloat(APFloat::IEEEquad,
2534 APInt(128, Record)));
2535 else if (CurTy->isPPC_FP128Ty())
2536 V = ConstantFP::get(Context, APFloat(APFloat::PPCDoubleDouble,
2537 APInt(128, Record)));
2539 V = UndefValue::get(CurTy);
2543 case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number]
2545 return error("Invalid record");
2547 unsigned Size = Record.size();
2548 SmallVector<Constant*, 16> Elts;
2550 if (StructType *STy = dyn_cast<StructType>(CurTy)) {
2551 for (unsigned i = 0; i != Size; ++i)
2552 Elts.push_back(ValueList.getConstantFwdRef(Record[i],
2553 STy->getElementType(i)));
2554 V = ConstantStruct::get(STy, Elts);
2555 } else if (ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) {
2556 Type *EltTy = ATy->getElementType();
2557 for (unsigned i = 0; i != Size; ++i)
2558 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
2559 V = ConstantArray::get(ATy, Elts);
2560 } else if (VectorType *VTy = dyn_cast<VectorType>(CurTy)) {
2561 Type *EltTy = VTy->getElementType();
2562 for (unsigned i = 0; i != Size; ++i)
2563 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
2564 V = ConstantVector::get(Elts);
2566 V = UndefValue::get(CurTy);
2570 case bitc::CST_CODE_STRING: // STRING: [values]
2571 case bitc::CST_CODE_CSTRING: { // CSTRING: [values]
2573 return error("Invalid record");
2575 SmallString<16> Elts(Record.begin(), Record.end());
2576 V = ConstantDataArray::getString(Context, Elts,
2577 BitCode == bitc::CST_CODE_CSTRING);
2580 case bitc::CST_CODE_DATA: {// DATA: [n x value]
2582 return error("Invalid record");
2584 Type *EltTy = cast<SequentialType>(CurTy)->getElementType();
2585 unsigned Size = Record.size();
2587 if (EltTy->isIntegerTy(8)) {
2588 SmallVector<uint8_t, 16> Elts(Record.begin(), Record.end());
2589 if (isa<VectorType>(CurTy))
2590 V = ConstantDataVector::get(Context, Elts);
2592 V = ConstantDataArray::get(Context, Elts);
2593 } else if (EltTy->isIntegerTy(16)) {
2594 SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end());
2595 if (isa<VectorType>(CurTy))
2596 V = ConstantDataVector::get(Context, Elts);
2598 V = ConstantDataArray::get(Context, Elts);
2599 } else if (EltTy->isIntegerTy(32)) {
2600 SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end());
2601 if (isa<VectorType>(CurTy))
2602 V = ConstantDataVector::get(Context, Elts);
2604 V = ConstantDataArray::get(Context, Elts);
2605 } else if (EltTy->isIntegerTy(64)) {
2606 SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end());
2607 if (isa<VectorType>(CurTy))
2608 V = ConstantDataVector::get(Context, Elts);
2610 V = ConstantDataArray::get(Context, Elts);
2611 } else if (EltTy->isFloatTy()) {
2612 SmallVector<float, 16> Elts(Size);
2613 std::transform(Record.begin(), Record.end(), Elts.begin(), BitsToFloat);
2614 if (isa<VectorType>(CurTy))
2615 V = ConstantDataVector::get(Context, Elts);
2617 V = ConstantDataArray::get(Context, Elts);
2618 } else if (EltTy->isDoubleTy()) {
2619 SmallVector<double, 16> Elts(Size);
2620 std::transform(Record.begin(), Record.end(), Elts.begin(),
2622 if (isa<VectorType>(CurTy))
2623 V = ConstantDataVector::get(Context, Elts);
2625 V = ConstantDataArray::get(Context, Elts);
2627 return error("Invalid type for value");
2632 case bitc::CST_CODE_CE_BINOP: { // CE_BINOP: [opcode, opval, opval]
2633 if (Record.size() < 3)
2634 return error("Invalid record");
2635 int Opc = getDecodedBinaryOpcode(Record[0], CurTy);
2637 V = UndefValue::get(CurTy); // Unknown binop.
2639 Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy);
2640 Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy);
2642 if (Record.size() >= 4) {
2643 if (Opc == Instruction::Add ||
2644 Opc == Instruction::Sub ||
2645 Opc == Instruction::Mul ||
2646 Opc == Instruction::Shl) {
2647 if (Record[3] & (1 << bitc::OBO_NO_SIGNED_WRAP))
2648 Flags |= OverflowingBinaryOperator::NoSignedWrap;
2649 if (Record[3] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
2650 Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
2651 } else if (Opc == Instruction::SDiv ||
2652 Opc == Instruction::UDiv ||
2653 Opc == Instruction::LShr ||
2654 Opc == Instruction::AShr) {
2655 if (Record[3] & (1 << bitc::PEO_EXACT))
2656 Flags |= SDivOperator::IsExact;
2659 V = ConstantExpr::get(Opc, LHS, RHS, Flags);
2663 case bitc::CST_CODE_CE_CAST: { // CE_CAST: [opcode, opty, opval]
2664 if (Record.size() < 3)
2665 return error("Invalid record");
2666 int Opc = getDecodedCastOpcode(Record[0]);
2668 V = UndefValue::get(CurTy); // Unknown cast.
2670 Type *OpTy = getTypeByID(Record[1]);
2672 return error("Invalid record");
2673 Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy);
2674 V = UpgradeBitCastExpr(Opc, Op, CurTy);
2675 if (!V) V = ConstantExpr::getCast(Opc, Op, CurTy);
2679 case bitc::CST_CODE_CE_INBOUNDS_GEP:
2680 case bitc::CST_CODE_CE_GEP: { // CE_GEP: [n x operands]
2682 Type *PointeeType = nullptr;
2683 if (Record.size() % 2)
2684 PointeeType = getTypeByID(Record[OpNum++]);
2685 SmallVector<Constant*, 16> Elts;
2686 while (OpNum != Record.size()) {
2687 Type *ElTy = getTypeByID(Record[OpNum++]);
2689 return error("Invalid record");
2690 Elts.push_back(ValueList.getConstantFwdRef(Record[OpNum++], ElTy));
2695 cast<SequentialType>(Elts[0]->getType()->getScalarType())
2697 return error("Explicit gep operator type does not match pointee type "
2698 "of pointer operand");
2700 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
2701 V = ConstantExpr::getGetElementPtr(PointeeType, Elts[0], Indices,
2703 bitc::CST_CODE_CE_INBOUNDS_GEP);
2706 case bitc::CST_CODE_CE_SELECT: { // CE_SELECT: [opval#, opval#, opval#]
2707 if (Record.size() < 3)
2708 return error("Invalid record");
2710 Type *SelectorTy = Type::getInt1Ty(Context);
2712 // The selector might be an i1 or an <n x i1>
2713 // Get the type from the ValueList before getting a forward ref.
2714 if (VectorType *VTy = dyn_cast<VectorType>(CurTy))
2715 if (Value *V = ValueList[Record[0]])
2716 if (SelectorTy != V->getType())
2717 SelectorTy = VectorType::get(SelectorTy, VTy->getNumElements());
2719 V = ConstantExpr::getSelect(ValueList.getConstantFwdRef(Record[0],
2721 ValueList.getConstantFwdRef(Record[1],CurTy),
2722 ValueList.getConstantFwdRef(Record[2],CurTy));
2725 case bitc::CST_CODE_CE_EXTRACTELT
2726 : { // CE_EXTRACTELT: [opty, opval, opty, opval]
2727 if (Record.size() < 3)
2728 return error("Invalid record");
2730 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
2732 return error("Invalid record");
2733 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
2734 Constant *Op1 = nullptr;
2735 if (Record.size() == 4) {
2736 Type *IdxTy = getTypeByID(Record[2]);
2738 return error("Invalid record");
2739 Op1 = ValueList.getConstantFwdRef(Record[3], IdxTy);
2740 } else // TODO: Remove with llvm 4.0
2741 Op1 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
2743 return error("Invalid record");
2744 V = ConstantExpr::getExtractElement(Op0, Op1);
2747 case bitc::CST_CODE_CE_INSERTELT
2748 : { // CE_INSERTELT: [opval, opval, opty, opval]
2749 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
2750 if (Record.size() < 3 || !OpTy)
2751 return error("Invalid record");
2752 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
2753 Constant *Op1 = ValueList.getConstantFwdRef(Record[1],
2754 OpTy->getElementType());
2755 Constant *Op2 = nullptr;
2756 if (Record.size() == 4) {
2757 Type *IdxTy = getTypeByID(Record[2]);
2759 return error("Invalid record");
2760 Op2 = ValueList.getConstantFwdRef(Record[3], IdxTy);
2761 } else // TODO: Remove with llvm 4.0
2762 Op2 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
2764 return error("Invalid record");
2765 V = ConstantExpr::getInsertElement(Op0, Op1, Op2);
2768 case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval]
2769 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
2770 if (Record.size() < 3 || !OpTy)
2771 return error("Invalid record");
2772 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
2773 Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy);
2774 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
2775 OpTy->getNumElements());
2776 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy);
2777 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
2780 case bitc::CST_CODE_CE_SHUFVEC_EX: { // [opty, opval, opval, opval]
2781 VectorType *RTy = dyn_cast<VectorType>(CurTy);
2783 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
2784 if (Record.size() < 4 || !RTy || !OpTy)
2785 return error("Invalid record");
2786 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
2787 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
2788 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
2789 RTy->getNumElements());
2790 Constant *Op2 = ValueList.getConstantFwdRef(Record[3], ShufTy);
2791 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
2794 case bitc::CST_CODE_CE_CMP: { // CE_CMP: [opty, opval, opval, pred]
2795 if (Record.size() < 4)
2796 return error("Invalid record");
2797 Type *OpTy = getTypeByID(Record[0]);
2799 return error("Invalid record");
2800 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
2801 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
2803 if (OpTy->isFPOrFPVectorTy())
2804 V = ConstantExpr::getFCmp(Record[3], Op0, Op1);
2806 V = ConstantExpr::getICmp(Record[3], Op0, Op1);
2809 // This maintains backward compatibility, pre-asm dialect keywords.
2810 // FIXME: Remove with the 4.0 release.
2811 case bitc::CST_CODE_INLINEASM_OLD: {
2812 if (Record.size() < 2)
2813 return error("Invalid record");
2814 std::string AsmStr, ConstrStr;
2815 bool HasSideEffects = Record[0] & 1;
2816 bool IsAlignStack = Record[0] >> 1;
2817 unsigned AsmStrSize = Record[1];
2818 if (2+AsmStrSize >= Record.size())
2819 return error("Invalid record");
2820 unsigned ConstStrSize = Record[2+AsmStrSize];
2821 if (3+AsmStrSize+ConstStrSize > Record.size())
2822 return error("Invalid record");
2824 for (unsigned i = 0; i != AsmStrSize; ++i)
2825 AsmStr += (char)Record[2+i];
2826 for (unsigned i = 0; i != ConstStrSize; ++i)
2827 ConstrStr += (char)Record[3+AsmStrSize+i];
2828 PointerType *PTy = cast<PointerType>(CurTy);
2829 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
2830 AsmStr, ConstrStr, HasSideEffects, IsAlignStack);
2833 // This version adds support for the asm dialect keywords (e.g.,
2835 case bitc::CST_CODE_INLINEASM: {
2836 if (Record.size() < 2)
2837 return error("Invalid record");
2838 std::string AsmStr, ConstrStr;
2839 bool HasSideEffects = Record[0] & 1;
2840 bool IsAlignStack = (Record[0] >> 1) & 1;
2841 unsigned AsmDialect = Record[0] >> 2;
2842 unsigned AsmStrSize = Record[1];
2843 if (2+AsmStrSize >= Record.size())
2844 return error("Invalid record");
2845 unsigned ConstStrSize = Record[2+AsmStrSize];
2846 if (3+AsmStrSize+ConstStrSize > Record.size())
2847 return error("Invalid record");
2849 for (unsigned i = 0; i != AsmStrSize; ++i)
2850 AsmStr += (char)Record[2+i];
2851 for (unsigned i = 0; i != ConstStrSize; ++i)
2852 ConstrStr += (char)Record[3+AsmStrSize+i];
2853 PointerType *PTy = cast<PointerType>(CurTy);
2854 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
2855 AsmStr, ConstrStr, HasSideEffects, IsAlignStack,
2856 InlineAsm::AsmDialect(AsmDialect));
2859 case bitc::CST_CODE_BLOCKADDRESS:{
2860 if (Record.size() < 3)
2861 return error("Invalid record");
2862 Type *FnTy = getTypeByID(Record[0]);
2864 return error("Invalid record");
2866 dyn_cast_or_null<Function>(ValueList.getConstantFwdRef(Record[1],FnTy));
2868 return error("Invalid record");
2870 // Don't let Fn get dematerialized.
2871 BlockAddressesTaken.insert(Fn);
2873 // If the function is already parsed we can insert the block address right
2876 unsigned BBID = Record[2];
2878 // Invalid reference to entry block.
2879 return error("Invalid ID");
2881 Function::iterator BBI = Fn->begin(), BBE = Fn->end();
2882 for (size_t I = 0, E = BBID; I != E; ++I) {
2884 return error("Invalid ID");
2889 // Otherwise insert a placeholder and remember it so it can be inserted
2890 // when the function is parsed.
2891 auto &FwdBBs = BasicBlockFwdRefs[Fn];
2893 BasicBlockFwdRefQueue.push_back(Fn);
2894 if (FwdBBs.size() < BBID + 1)
2895 FwdBBs.resize(BBID + 1);
2897 FwdBBs[BBID] = BasicBlock::Create(Context);
2900 V = BlockAddress::get(Fn, BB);
2905 if (ValueList.assignValue(V, NextCstNo))
2906 return error("Invalid forward reference");
2911 std::error_code BitcodeReader::parseUseLists() {
2912 if (Stream.EnterSubBlock(bitc::USELIST_BLOCK_ID))
2913 return error("Invalid record");
2915 // Read all the records.
2916 SmallVector<uint64_t, 64> Record;
2918 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
2920 switch (Entry.Kind) {
2921 case BitstreamEntry::SubBlock: // Handled for us already.
2922 case BitstreamEntry::Error:
2923 return error("Malformed block");
2924 case BitstreamEntry::EndBlock:
2925 return std::error_code();
2926 case BitstreamEntry::Record:
2927 // The interesting case.
2931 // Read a use list record.
2934 switch (Stream.readRecord(Entry.ID, Record)) {
2935 default: // Default behavior: unknown type.
2937 case bitc::USELIST_CODE_BB:
2940 case bitc::USELIST_CODE_DEFAULT: {
2941 unsigned RecordLength = Record.size();
2942 if (RecordLength < 3)
2943 // Records should have at least an ID and two indexes.
2944 return error("Invalid record");
2945 unsigned ID = Record.back();
2950 assert(ID < FunctionBBs.size() && "Basic block not found");
2951 V = FunctionBBs[ID];
2954 unsigned NumUses = 0;
2955 SmallDenseMap<const Use *, unsigned, 16> Order;
2956 for (const Use &U : V->uses()) {
2957 if (++NumUses > Record.size())
2959 Order[&U] = Record[NumUses - 1];
2961 if (Order.size() != Record.size() || NumUses > Record.size())
2962 // Mismatches can happen if the functions are being materialized lazily
2963 // (out-of-order), or a value has been upgraded.
2966 V->sortUseList([&](const Use &L, const Use &R) {
2967 return Order.lookup(&L) < Order.lookup(&R);
2975 /// When we see the block for metadata, remember where it is and then skip it.
2976 /// This lets us lazily deserialize the metadata.
2977 std::error_code BitcodeReader::rememberAndSkipMetadata() {
2978 // Save the current stream state.
2979 uint64_t CurBit = Stream.GetCurrentBitNo();
2980 DeferredMetadataInfo.push_back(CurBit);
2982 // Skip over the block for now.
2983 if (Stream.SkipBlock())
2984 return error("Invalid record");
2985 return std::error_code();
2988 std::error_code BitcodeReader::materializeMetadata() {
2989 for (uint64_t BitPos : DeferredMetadataInfo) {
2990 // Move the bit stream to the saved position.
2991 Stream.JumpToBit(BitPos);
2992 if (std::error_code EC = parseMetadata())
2995 DeferredMetadataInfo.clear();
2996 return std::error_code();
2999 void BitcodeReader::setStripDebugInfo() { StripDebugInfo = true; }
3001 /// When we see the block for a function body, remember where it is and then
3002 /// skip it. This lets us lazily deserialize the functions.
3003 std::error_code BitcodeReader::rememberAndSkipFunctionBody() {
3004 // Get the function we are talking about.
3005 if (FunctionsWithBodies.empty())
3006 return error("Insufficient function protos");
3008 Function *Fn = FunctionsWithBodies.back();
3009 FunctionsWithBodies.pop_back();
3011 // Save the current stream state.
3012 uint64_t CurBit = Stream.GetCurrentBitNo();
3014 (DeferredFunctionInfo[Fn] == 0 || DeferredFunctionInfo[Fn] == CurBit) &&
3015 "Mismatch between VST and scanned function offsets");
3016 DeferredFunctionInfo[Fn] = CurBit;
3018 // Skip over the function block for now.
3019 if (Stream.SkipBlock())
3020 return error("Invalid record");
3021 return std::error_code();
3024 std::error_code BitcodeReader::globalCleanup() {
3025 // Patch the initializers for globals and aliases up.
3026 resolveGlobalAndAliasInits();
3027 if (!GlobalInits.empty() || !AliasInits.empty())
3028 return error("Malformed global initializer set");
3030 // Look for intrinsic functions which need to be upgraded at some point
3031 for (Function &F : *TheModule) {
3033 if (UpgradeIntrinsicFunction(&F, NewFn))
3034 UpgradedIntrinsics[&F] = NewFn;
3037 // Look for global variables which need to be renamed.
3038 for (GlobalVariable &GV : TheModule->globals())
3039 UpgradeGlobalVariable(&GV);
3041 // Force deallocation of memory for these vectors to favor the client that
3042 // want lazy deserialization.
3043 std::vector<std::pair<GlobalVariable*, unsigned> >().swap(GlobalInits);
3044 std::vector<std::pair<GlobalAlias*, unsigned> >().swap(AliasInits);
3045 return std::error_code();
3048 /// Support for lazy parsing of function bodies. This is required if we
3049 /// either have an old bitcode file without a VST forward declaration record,
3050 /// or if we have an anonymous function being materialized, since anonymous
3051 /// functions do not have a name and are therefore not in the VST.
3052 std::error_code BitcodeReader::rememberAndSkipFunctionBodies() {
3053 Stream.JumpToBit(NextUnreadBit);
3055 if (Stream.AtEndOfStream()) return error("Could not find function in stream");
3057 if (!SeenFirstFunctionBody)
3058 return error("Trying to materialize functions before seeing function blocks");
3060 // An old bitcode file with the symbol table at the end would have
3061 // finished the parse greedily.
3062 assert(SeenValueSymbolTable);
3064 SmallVector<uint64_t, 64> Record;
3067 BitstreamEntry Entry = Stream.advance();
3068 switch (Entry.Kind) {
3070 return error("Expect SubBlock");
3071 case BitstreamEntry::SubBlock:
3074 return error("Expect function block");
3075 case bitc::FUNCTION_BLOCK_ID:
3076 if (std::error_code EC = rememberAndSkipFunctionBody()) return EC;
3077 NextUnreadBit = Stream.GetCurrentBitNo();
3078 return std::error_code();
3084 std::error_code BitcodeReader::parseBitcodeVersion() {
3085 if (Stream.EnterSubBlock(bitc::IDENTIFICATION_BLOCK_ID))
3086 return error("Invalid record");
3088 // Read all the records.
3089 SmallVector<uint64_t, 64> Record;
3091 BitstreamEntry Entry = Stream.advance();
3093 switch (Entry.Kind) {
3095 case BitstreamEntry::Error:
3096 return error("Malformed block");
3097 case BitstreamEntry::EndBlock:
3098 return std::error_code();
3099 case BitstreamEntry::Record:
3100 // The interesting case.
3106 unsigned BitCode = Stream.readRecord(Entry.ID, Record);
3108 default: // Default behavior: reject
3109 return error("Invalid value");
3110 case bitc::IDENTIFICATION_CODE_STRING: { // IDENTIFICATION: [strchr x
3112 convertToString(Record, 0, ProducerIdentification);
3115 case bitc::IDENTIFICATION_CODE_EPOCH: { // EPOCH: [epoch#]
3116 unsigned epoch = (unsigned)Record[0];
3117 if (epoch != bitc::BITCODE_CURRENT_EPOCH) {
3119 Twine("Incompatible epoch: Bitcode '") + Twine(epoch) +
3120 "' vs current: '" + Twine(bitc::BITCODE_CURRENT_EPOCH) + "'");
3127 std::error_code BitcodeReader::parseModule(uint64_t ResumeBit,
3128 bool ShouldLazyLoadMetadata) {
3130 Stream.JumpToBit(ResumeBit);
3131 else if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
3132 return error("Invalid record");
3134 SmallVector<uint64_t, 64> Record;
3135 std::vector<std::string> SectionTable;
3136 std::vector<std::string> GCTable;
3138 // Read all the records for this module.
3140 BitstreamEntry Entry = Stream.advance();
3142 switch (Entry.Kind) {
3143 case BitstreamEntry::Error:
3144 return error("Malformed block");
3145 case BitstreamEntry::EndBlock:
3146 return globalCleanup();
3148 case BitstreamEntry::SubBlock:
3150 default: // Skip unknown content.
3151 if (Stream.SkipBlock())
3152 return error("Invalid record");
3154 case bitc::BLOCKINFO_BLOCK_ID:
3155 if (Stream.ReadBlockInfoBlock())
3156 return error("Malformed block");
3158 case bitc::PARAMATTR_BLOCK_ID:
3159 if (std::error_code EC = parseAttributeBlock())
3162 case bitc::PARAMATTR_GROUP_BLOCK_ID:
3163 if (std::error_code EC = parseAttributeGroupBlock())
3166 case bitc::TYPE_BLOCK_ID_NEW:
3167 if (std::error_code EC = parseTypeTable())
3170 case bitc::VALUE_SYMTAB_BLOCK_ID:
3171 if (!SeenValueSymbolTable) {
3172 // Either this is an old form VST without function index and an
3173 // associated VST forward declaration record (which would have caused
3174 // the VST to be jumped to and parsed before it was encountered
3175 // normally in the stream), or there were no function blocks to
3176 // trigger an earlier parsing of the VST.
3177 assert(VSTOffset == 0 || FunctionsWithBodies.empty());
3178 if (std::error_code EC = parseValueSymbolTable())
3180 SeenValueSymbolTable = true;
3182 // We must have had a VST forward declaration record, which caused
3183 // the parser to jump to and parse the VST earlier.
3184 assert(VSTOffset > 0);
3185 if (Stream.SkipBlock())
3186 return error("Invalid record");
3189 case bitc::CONSTANTS_BLOCK_ID:
3190 if (std::error_code EC = parseConstants())
3192 if (std::error_code EC = resolveGlobalAndAliasInits())
3195 case bitc::METADATA_BLOCK_ID:
3196 if (ShouldLazyLoadMetadata && !IsMetadataMaterialized) {
3197 if (std::error_code EC = rememberAndSkipMetadata())
3201 assert(DeferredMetadataInfo.empty() && "Unexpected deferred metadata");
3202 if (std::error_code EC = parseMetadata())
3205 case bitc::FUNCTION_BLOCK_ID:
3206 // If this is the first function body we've seen, reverse the
3207 // FunctionsWithBodies list.
3208 if (!SeenFirstFunctionBody) {
3209 std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
3210 if (std::error_code EC = globalCleanup())
3212 SeenFirstFunctionBody = true;
3215 if (VSTOffset > 0) {
3216 // If we have a VST forward declaration record, make sure we
3217 // parse the VST now if we haven't already. It is needed to
3218 // set up the DeferredFunctionInfo vector for lazy reading.
3219 if (!SeenValueSymbolTable) {
3220 if (std::error_code EC =
3221 BitcodeReader::parseValueSymbolTable(VSTOffset))
3223 SeenValueSymbolTable = true;
3224 // Fall through so that we record the NextUnreadBit below.
3225 // This is necessary in case we have an anonymous function that
3226 // is later materialized. Since it will not have a VST entry we
3227 // need to fall back to the lazy parse to find its offset.
3229 // If we have a VST forward declaration record, but have already
3230 // parsed the VST (just above, when the first function body was
3231 // encountered here), then we are resuming the parse after
3232 // materializing functions. The ResumeBit points to the
3233 // start of the last function block recorded in the
3234 // DeferredFunctionInfo map. Skip it.
3235 if (Stream.SkipBlock())
3236 return error("Invalid record");
3241 // Support older bitcode files that did not have the function
3242 // index in the VST, nor a VST forward declaration record, as
3243 // well as anonymous functions that do not have VST entries.
3244 // Build the DeferredFunctionInfo vector on the fly.
3245 if (std::error_code EC = rememberAndSkipFunctionBody())
3248 // Suspend parsing when we reach the function bodies. Subsequent
3249 // materialization calls will resume it when necessary. If the bitcode
3250 // file is old, the symbol table will be at the end instead and will not
3251 // have been seen yet. In this case, just finish the parse now.
3252 if (SeenValueSymbolTable) {
3253 NextUnreadBit = Stream.GetCurrentBitNo();
3254 return std::error_code();
3257 case bitc::USELIST_BLOCK_ID:
3258 if (std::error_code EC = parseUseLists())
3261 case bitc::OPERAND_BUNDLE_TAGS_BLOCK_ID:
3262 if (std::error_code EC = parseOperandBundleTags())
3268 case BitstreamEntry::Record:
3269 // The interesting case.
3275 auto BitCode = Stream.readRecord(Entry.ID, Record);
3277 default: break; // Default behavior, ignore unknown content.
3278 case bitc::MODULE_CODE_VERSION: { // VERSION: [version#]
3279 if (Record.size() < 1)
3280 return error("Invalid record");
3281 // Only version #0 and #1 are supported so far.
3282 unsigned module_version = Record[0];
3283 switch (module_version) {
3285 return error("Invalid value");
3287 UseRelativeIDs = false;
3290 UseRelativeIDs = true;
3295 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
3297 if (convertToString(Record, 0, S))
3298 return error("Invalid record");
3299 TheModule->setTargetTriple(S);
3302 case bitc::MODULE_CODE_DATALAYOUT: { // DATALAYOUT: [strchr x N]
3304 if (convertToString(Record, 0, S))
3305 return error("Invalid record");
3306 TheModule->setDataLayout(S);
3309 case bitc::MODULE_CODE_ASM: { // ASM: [strchr x N]
3311 if (convertToString(Record, 0, S))
3312 return error("Invalid record");
3313 TheModule->setModuleInlineAsm(S);
3316 case bitc::MODULE_CODE_DEPLIB: { // DEPLIB: [strchr x N]
3317 // FIXME: Remove in 4.0.
3319 if (convertToString(Record, 0, S))
3320 return error("Invalid record");
3324 case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N]
3326 if (convertToString(Record, 0, S))
3327 return error("Invalid record");
3328 SectionTable.push_back(S);
3331 case bitc::MODULE_CODE_GCNAME: { // SECTIONNAME: [strchr x N]
3333 if (convertToString(Record, 0, S))
3334 return error("Invalid record");
3335 GCTable.push_back(S);
3338 case bitc::MODULE_CODE_COMDAT: { // COMDAT: [selection_kind, name]
3339 if (Record.size() < 2)
3340 return error("Invalid record");
3341 Comdat::SelectionKind SK = getDecodedComdatSelectionKind(Record[0]);
3342 unsigned ComdatNameSize = Record[1];
3343 std::string ComdatName;
3344 ComdatName.reserve(ComdatNameSize);
3345 for (unsigned i = 0; i != ComdatNameSize; ++i)
3346 ComdatName += (char)Record[2 + i];
3347 Comdat *C = TheModule->getOrInsertComdat(ComdatName);
3348 C->setSelectionKind(SK);
3349 ComdatList.push_back(C);
3352 // GLOBALVAR: [pointer type, isconst, initid,
3353 // linkage, alignment, section, visibility, threadlocal,
3354 // unnamed_addr, externally_initialized, dllstorageclass,
3356 case bitc::MODULE_CODE_GLOBALVAR: {
3357 if (Record.size() < 6)
3358 return error("Invalid record");
3359 Type *Ty = getTypeByID(Record[0]);
3361 return error("Invalid record");
3362 bool isConstant = Record[1] & 1;
3363 bool explicitType = Record[1] & 2;
3364 unsigned AddressSpace;
3366 AddressSpace = Record[1] >> 2;
3368 if (!Ty->isPointerTy())
3369 return error("Invalid type for value");
3370 AddressSpace = cast<PointerType>(Ty)->getAddressSpace();
3371 Ty = cast<PointerType>(Ty)->getElementType();
3374 uint64_t RawLinkage = Record[3];
3375 GlobalValue::LinkageTypes Linkage = getDecodedLinkage(RawLinkage);
3377 if (std::error_code EC = parseAlignmentValue(Record[4], Alignment))
3379 std::string Section;
3381 if (Record[5]-1 >= SectionTable.size())
3382 return error("Invalid ID");
3383 Section = SectionTable[Record[5]-1];
3385 GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;
3386 // Local linkage must have default visibility.
3387 if (Record.size() > 6 && !GlobalValue::isLocalLinkage(Linkage))
3388 // FIXME: Change to an error if non-default in 4.0.
3389 Visibility = getDecodedVisibility(Record[6]);
3391 GlobalVariable::ThreadLocalMode TLM = GlobalVariable::NotThreadLocal;
3392 if (Record.size() > 7)
3393 TLM = getDecodedThreadLocalMode(Record[7]);
3395 bool UnnamedAddr = false;
3396 if (Record.size() > 8)
3397 UnnamedAddr = Record[8];
3399 bool ExternallyInitialized = false;
3400 if (Record.size() > 9)
3401 ExternallyInitialized = Record[9];
3403 GlobalVariable *NewGV =
3404 new GlobalVariable(*TheModule, Ty, isConstant, Linkage, nullptr, "", nullptr,
3405 TLM, AddressSpace, ExternallyInitialized);
3406 NewGV->setAlignment(Alignment);
3407 if (!Section.empty())
3408 NewGV->setSection(Section);
3409 NewGV->setVisibility(Visibility);
3410 NewGV->setUnnamedAddr(UnnamedAddr);
3412 if (Record.size() > 10)
3413 NewGV->setDLLStorageClass(getDecodedDLLStorageClass(Record[10]));
3415 upgradeDLLImportExportLinkage(NewGV, RawLinkage);
3417 ValueList.push_back(NewGV);
3419 // Remember which value to use for the global initializer.
3420 if (unsigned InitID = Record[2])
3421 GlobalInits.push_back(std::make_pair(NewGV, InitID-1));
3423 if (Record.size() > 11) {
3424 if (unsigned ComdatID = Record[11]) {
3425 if (ComdatID > ComdatList.size())
3426 return error("Invalid global variable comdat ID");
3427 NewGV->setComdat(ComdatList[ComdatID - 1]);
3429 } else if (hasImplicitComdat(RawLinkage)) {
3430 NewGV->setComdat(reinterpret_cast<Comdat *>(1));
3434 // FUNCTION: [type, callingconv, isproto, linkage, paramattr,
3435 // alignment, section, visibility, gc, unnamed_addr,
3436 // prologuedata, dllstorageclass, comdat, prefixdata]
3437 case bitc::MODULE_CODE_FUNCTION: {
3438 if (Record.size() < 8)
3439 return error("Invalid record");
3440 Type *Ty = getTypeByID(Record[0]);
3442 return error("Invalid record");
3443 if (auto *PTy = dyn_cast<PointerType>(Ty))
3444 Ty = PTy->getElementType();
3445 auto *FTy = dyn_cast<FunctionType>(Ty);
3447 return error("Invalid type for value");
3448 auto CC = static_cast<CallingConv::ID>(Record[1]);
3449 if (CC & ~CallingConv::MaxID)
3450 return error("Invalid calling convention ID");
3452 Function *Func = Function::Create(FTy, GlobalValue::ExternalLinkage,
3455 Func->setCallingConv(CC);
3456 bool isProto = Record[2];
3457 uint64_t RawLinkage = Record[3];
3458 Func->setLinkage(getDecodedLinkage(RawLinkage));
3459 Func->setAttributes(getAttributes(Record[4]));
3462 if (std::error_code EC = parseAlignmentValue(Record[5], Alignment))
3464 Func->setAlignment(Alignment);
3466 if (Record[6]-1 >= SectionTable.size())
3467 return error("Invalid ID");
3468 Func->setSection(SectionTable[Record[6]-1]);
3470 // Local linkage must have default visibility.
3471 if (!Func->hasLocalLinkage())
3472 // FIXME: Change to an error if non-default in 4.0.
3473 Func->setVisibility(getDecodedVisibility(Record[7]));
3474 if (Record.size() > 8 && Record[8]) {
3475 if (Record[8]-1 >= GCTable.size())
3476 return error("Invalid ID");
3477 Func->setGC(GCTable[Record[8]-1].c_str());
3479 bool UnnamedAddr = false;
3480 if (Record.size() > 9)
3481 UnnamedAddr = Record[9];
3482 Func->setUnnamedAddr(UnnamedAddr);
3483 if (Record.size() > 10 && Record[10] != 0)
3484 FunctionPrologues.push_back(std::make_pair(Func, Record[10]-1));
3486 if (Record.size() > 11)
3487 Func->setDLLStorageClass(getDecodedDLLStorageClass(Record[11]));
3489 upgradeDLLImportExportLinkage(Func, RawLinkage);
3491 if (Record.size() > 12) {
3492 if (unsigned ComdatID = Record[12]) {
3493 if (ComdatID > ComdatList.size())
3494 return error("Invalid function comdat ID");
3495 Func->setComdat(ComdatList[ComdatID - 1]);
3497 } else if (hasImplicitComdat(RawLinkage)) {
3498 Func->setComdat(reinterpret_cast<Comdat *>(1));
3501 if (Record.size() > 13 && Record[13] != 0)
3502 FunctionPrefixes.push_back(std::make_pair(Func, Record[13]-1));
3504 if (Record.size() > 14 && Record[14] != 0)
3505 FunctionPersonalityFns.push_back(std::make_pair(Func, Record[14] - 1));
3507 ValueList.push_back(Func);
3509 // If this is a function with a body, remember the prototype we are
3510 // creating now, so that we can match up the body with them later.
3512 Func->setIsMaterializable(true);
3513 FunctionsWithBodies.push_back(Func);
3514 DeferredFunctionInfo[Func] = 0;
3518 // ALIAS: [alias type, addrspace, aliasee val#, linkage]
3519 // ALIAS: [alias type, addrspace, aliasee val#, linkage, visibility, dllstorageclass]
3520 case bitc::MODULE_CODE_ALIAS:
3521 case bitc::MODULE_CODE_ALIAS_OLD: {
3522 bool NewRecord = BitCode == bitc::MODULE_CODE_ALIAS;
3523 if (Record.size() < (3 + (unsigned)NewRecord))
3524 return error("Invalid record");
3526 Type *Ty = getTypeByID(Record[OpNum++]);
3528 return error("Invalid record");
3532 auto *PTy = dyn_cast<PointerType>(Ty);
3534 return error("Invalid type for value");
3535 Ty = PTy->getElementType();
3536 AddrSpace = PTy->getAddressSpace();
3538 AddrSpace = Record[OpNum++];
3541 auto Val = Record[OpNum++];
3542 auto Linkage = Record[OpNum++];
3543 auto *NewGA = GlobalAlias::create(
3544 Ty, AddrSpace, getDecodedLinkage(Linkage), "", TheModule);
3545 // Old bitcode files didn't have visibility field.
3546 // Local linkage must have default visibility.
3547 if (OpNum != Record.size()) {
3548 auto VisInd = OpNum++;
3549 if (!NewGA->hasLocalLinkage())
3550 // FIXME: Change to an error if non-default in 4.0.
3551 NewGA->setVisibility(getDecodedVisibility(Record[VisInd]));
3553 if (OpNum != Record.size())
3554 NewGA->setDLLStorageClass(getDecodedDLLStorageClass(Record[OpNum++]));
3556 upgradeDLLImportExportLinkage(NewGA, Linkage);
3557 if (OpNum != Record.size())
3558 NewGA->setThreadLocalMode(getDecodedThreadLocalMode(Record[OpNum++]));
3559 if (OpNum != Record.size())
3560 NewGA->setUnnamedAddr(Record[OpNum++]);
3561 ValueList.push_back(NewGA);
3562 AliasInits.push_back(std::make_pair(NewGA, Val));
3565 /// MODULE_CODE_PURGEVALS: [numvals]
3566 case bitc::MODULE_CODE_PURGEVALS:
3567 // Trim down the value list to the specified size.
3568 if (Record.size() < 1 || Record[0] > ValueList.size())
3569 return error("Invalid record");
3570 ValueList.shrinkTo(Record[0]);
3572 /// MODULE_CODE_VSTOFFSET: [offset]
3573 case bitc::MODULE_CODE_VSTOFFSET:
3574 if (Record.size() < 1)
3575 return error("Invalid record");
3576 VSTOffset = Record[0];
3583 /// Helper to read the header common to all bitcode files.
3584 static bool hasValidBitcodeHeader(BitstreamCursor &Stream) {
3585 // Sniff for the signature.
3586 if (Stream.Read(8) != 'B' ||
3587 Stream.Read(8) != 'C' ||
3588 Stream.Read(4) != 0x0 ||
3589 Stream.Read(4) != 0xC ||
3590 Stream.Read(4) != 0xE ||
3591 Stream.Read(4) != 0xD)
3597 BitcodeReader::parseBitcodeInto(std::unique_ptr<DataStreamer> Streamer,
3598 Module *M, bool ShouldLazyLoadMetadata) {
3601 if (std::error_code EC = initStream(std::move(Streamer)))
3604 // Sniff for the signature.
3605 if (!hasValidBitcodeHeader(Stream)) return error("Invalid bitcode signature");
3607 // We expect a number of well-defined blocks, though we don't necessarily
3608 // need to understand them all.
3610 if (Stream.AtEndOfStream()) {
3611 // We didn't really read a proper Module.
3612 return error("Malformed IR file");
3615 BitstreamEntry Entry =
3616 Stream.advance(BitstreamCursor::AF_DontAutoprocessAbbrevs);
3618 if (Entry.Kind != BitstreamEntry::SubBlock)
3619 return error("Malformed block");
3621 if (Entry.ID == bitc::IDENTIFICATION_BLOCK_ID) {
3622 parseBitcodeVersion();
3626 if (Entry.ID == bitc::MODULE_BLOCK_ID)
3627 return parseModule(0, ShouldLazyLoadMetadata);
3629 if (Stream.SkipBlock())
3630 return error("Invalid record");
3634 ErrorOr<std::string> BitcodeReader::parseModuleTriple() {
3635 if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
3636 return error("Invalid record");
3638 SmallVector<uint64_t, 64> Record;
3641 // Read all the records for this module.
3643 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
3645 switch (Entry.Kind) {
3646 case BitstreamEntry::SubBlock: // Handled for us already.
3647 case BitstreamEntry::Error:
3648 return error("Malformed block");
3649 case BitstreamEntry::EndBlock:
3651 case BitstreamEntry::Record:
3652 // The interesting case.
3657 switch (Stream.readRecord(Entry.ID, Record)) {
3658 default: break; // Default behavior, ignore unknown content.
3659 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
3661 if (convertToString(Record, 0, S))
3662 return error("Invalid record");
3669 llvm_unreachable("Exit infinite loop");
3672 ErrorOr<std::string> BitcodeReader::parseTriple() {
3673 if (std::error_code EC = initStream(nullptr))
3676 // Sniff for the signature.
3677 if (!hasValidBitcodeHeader(Stream)) return error("Invalid bitcode signature");
3679 // We expect a number of well-defined blocks, though we don't necessarily
3680 // need to understand them all.
3682 BitstreamEntry Entry = Stream.advance();
3684 switch (Entry.Kind) {
3685 case BitstreamEntry::Error:
3686 return error("Malformed block");
3687 case BitstreamEntry::EndBlock:
3688 return std::error_code();
3690 case BitstreamEntry::SubBlock:
3691 if (Entry.ID == bitc::MODULE_BLOCK_ID)
3692 return parseModuleTriple();
3694 // Ignore other sub-blocks.
3695 if (Stream.SkipBlock())
3696 return error("Malformed block");
3699 case BitstreamEntry::Record:
3700 Stream.skipRecord(Entry.ID);
3706 /// Parse metadata attachments.
3707 std::error_code BitcodeReader::parseMetadataAttachment(Function &F) {
3708 if (Stream.EnterSubBlock(bitc::METADATA_ATTACHMENT_ID))
3709 return error("Invalid record");
3711 SmallVector<uint64_t, 64> Record;
3713 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
3715 switch (Entry.Kind) {
3716 case BitstreamEntry::SubBlock: // Handled for us already.
3717 case BitstreamEntry::Error:
3718 return error("Malformed block");
3719 case BitstreamEntry::EndBlock:
3720 return std::error_code();
3721 case BitstreamEntry::Record:
3722 // The interesting case.
3726 // Read a metadata attachment record.
3728 switch (Stream.readRecord(Entry.ID, Record)) {
3729 default: // Default behavior: ignore.
3731 case bitc::METADATA_ATTACHMENT: {
3732 unsigned RecordLength = Record.size();
3734 return error("Invalid record");
3735 if (RecordLength % 2 == 0) {
3736 // A function attachment.
3737 for (unsigned I = 0; I != RecordLength; I += 2) {
3738 auto K = MDKindMap.find(Record[I]);
3739 if (K == MDKindMap.end())
3740 return error("Invalid ID");
3741 Metadata *MD = MDValueList.getValueFwdRef(Record[I + 1]);
3742 F.setMetadata(K->second, cast<MDNode>(MD));
3747 // An instruction attachment.
3748 Instruction *Inst = InstructionList[Record[0]];
3749 for (unsigned i = 1; i != RecordLength; i = i+2) {
3750 unsigned Kind = Record[i];
3751 DenseMap<unsigned, unsigned>::iterator I =
3752 MDKindMap.find(Kind);
3753 if (I == MDKindMap.end())
3754 return error("Invalid ID");
3755 Metadata *Node = MDValueList.getValueFwdRef(Record[i + 1]);
3756 if (isa<LocalAsMetadata>(Node))
3757 // Drop the attachment. This used to be legal, but there's no
3760 Inst->setMetadata(I->second, cast<MDNode>(Node));
3761 if (I->second == LLVMContext::MD_tbaa)
3762 InstsWithTBAATag.push_back(Inst);
3770 static std::error_code typeCheckLoadStoreInst(DiagnosticHandlerFunction DH,
3771 Type *ValType, Type *PtrType) {
3772 if (!isa<PointerType>(PtrType))
3773 return error(DH, "Load/Store operand is not a pointer type");
3774 Type *ElemType = cast<PointerType>(PtrType)->getElementType();
3776 if (ValType && ValType != ElemType)
3777 return error(DH, "Explicit load/store type does not match pointee type of "
3779 if (!PointerType::isLoadableOrStorableType(ElemType))
3780 return error(DH, "Cannot load/store from pointer");
3781 return std::error_code();
3784 /// Lazily parse the specified function body block.
3785 std::error_code BitcodeReader::parseFunctionBody(Function *F) {
3786 if (Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID))
3787 return error("Invalid record");
3789 InstructionList.clear();
3790 unsigned ModuleValueListSize = ValueList.size();
3791 unsigned ModuleMDValueListSize = MDValueList.size();
3793 // Add all the function arguments to the value table.
3794 for (Argument &I : F->args())
3795 ValueList.push_back(&I);
3797 unsigned NextValueNo = ValueList.size();
3798 BasicBlock *CurBB = nullptr;
3799 unsigned CurBBNo = 0;
3802 auto getLastInstruction = [&]() -> Instruction * {
3803 if (CurBB && !CurBB->empty())
3804 return &CurBB->back();
3805 else if (CurBBNo && FunctionBBs[CurBBNo - 1] &&
3806 !FunctionBBs[CurBBNo - 1]->empty())
3807 return &FunctionBBs[CurBBNo - 1]->back();
3811 std::vector<OperandBundleDef> OperandBundles;
3813 // Read all the records.
3814 SmallVector<uint64_t, 64> Record;
3816 BitstreamEntry Entry = Stream.advance();
3818 switch (Entry.Kind) {
3819 case BitstreamEntry::Error:
3820 return error("Malformed block");
3821 case BitstreamEntry::EndBlock:
3822 goto OutOfRecordLoop;
3824 case BitstreamEntry::SubBlock:
3826 default: // Skip unknown content.
3827 if (Stream.SkipBlock())
3828 return error("Invalid record");
3830 case bitc::CONSTANTS_BLOCK_ID:
3831 if (std::error_code EC = parseConstants())
3833 NextValueNo = ValueList.size();
3835 case bitc::VALUE_SYMTAB_BLOCK_ID:
3836 if (std::error_code EC = parseValueSymbolTable())
3839 case bitc::METADATA_ATTACHMENT_ID:
3840 if (std::error_code EC = parseMetadataAttachment(*F))
3843 case bitc::METADATA_BLOCK_ID:
3844 if (std::error_code EC = parseMetadata())
3847 case bitc::USELIST_BLOCK_ID:
3848 if (std::error_code EC = parseUseLists())
3854 case BitstreamEntry::Record:
3855 // The interesting case.
3861 Instruction *I = nullptr;
3862 unsigned BitCode = Stream.readRecord(Entry.ID, Record);
3864 default: // Default behavior: reject
3865 return error("Invalid value");
3866 case bitc::FUNC_CODE_DECLAREBLOCKS: { // DECLAREBLOCKS: [nblocks]
3867 if (Record.size() < 1 || Record[0] == 0)
3868 return error("Invalid record");
3869 // Create all the basic blocks for the function.
3870 FunctionBBs.resize(Record[0]);
3872 // See if anything took the address of blocks in this function.
3873 auto BBFRI = BasicBlockFwdRefs.find(F);
3874 if (BBFRI == BasicBlockFwdRefs.end()) {
3875 for (unsigned i = 0, e = FunctionBBs.size(); i != e; ++i)
3876 FunctionBBs[i] = BasicBlock::Create(Context, "", F);
3878 auto &BBRefs = BBFRI->second;
3879 // Check for invalid basic block references.
3880 if (BBRefs.size() > FunctionBBs.size())
3881 return error("Invalid ID");
3882 assert(!BBRefs.empty() && "Unexpected empty array");
3883 assert(!BBRefs.front() && "Invalid reference to entry block");
3884 for (unsigned I = 0, E = FunctionBBs.size(), RE = BBRefs.size(); I != E;
3886 if (I < RE && BBRefs[I]) {
3887 BBRefs[I]->insertInto(F);
3888 FunctionBBs[I] = BBRefs[I];
3890 FunctionBBs[I] = BasicBlock::Create(Context, "", F);
3893 // Erase from the table.
3894 BasicBlockFwdRefs.erase(BBFRI);
3897 CurBB = FunctionBBs[0];
3901 case bitc::FUNC_CODE_DEBUG_LOC_AGAIN: // DEBUG_LOC_AGAIN
3902 // This record indicates that the last instruction is at the same
3903 // location as the previous instruction with a location.
3904 I = getLastInstruction();
3907 return error("Invalid record");
3908 I->setDebugLoc(LastLoc);
3912 case bitc::FUNC_CODE_DEBUG_LOC: { // DEBUG_LOC: [line, col, scope, ia]
3913 I = getLastInstruction();
3914 if (!I || Record.size() < 4)
3915 return error("Invalid record");
3917 unsigned Line = Record[0], Col = Record[1];
3918 unsigned ScopeID = Record[2], IAID = Record[3];
3920 MDNode *Scope = nullptr, *IA = nullptr;
3921 if (ScopeID) Scope = cast<MDNode>(MDValueList.getValueFwdRef(ScopeID-1));
3922 if (IAID) IA = cast<MDNode>(MDValueList.getValueFwdRef(IAID-1));
3923 LastLoc = DebugLoc::get(Line, Col, Scope, IA);
3924 I->setDebugLoc(LastLoc);
3929 case bitc::FUNC_CODE_INST_BINOP: { // BINOP: [opval, ty, opval, opcode]
3932 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
3933 popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) ||
3934 OpNum+1 > Record.size())
3935 return error("Invalid record");
3937 int Opc = getDecodedBinaryOpcode(Record[OpNum++], LHS->getType());
3939 return error("Invalid record");
3940 I = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3941 InstructionList.push_back(I);
3942 if (OpNum < Record.size()) {
3943 if (Opc == Instruction::Add ||
3944 Opc == Instruction::Sub ||
3945 Opc == Instruction::Mul ||
3946 Opc == Instruction::Shl) {
3947 if (Record[OpNum] & (1 << bitc::OBO_NO_SIGNED_WRAP))
3948 cast<BinaryOperator>(I)->setHasNoSignedWrap(true);
3949 if (Record[OpNum] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
3950 cast<BinaryOperator>(I)->setHasNoUnsignedWrap(true);
3951 } else if (Opc == Instruction::SDiv ||
3952 Opc == Instruction::UDiv ||
3953 Opc == Instruction::LShr ||
3954 Opc == Instruction::AShr) {
3955 if (Record[OpNum] & (1 << bitc::PEO_EXACT))
3956 cast<BinaryOperator>(I)->setIsExact(true);
3957 } else if (isa<FPMathOperator>(I)) {
3958 FastMathFlags FMF = getDecodedFastMathFlags(Record[OpNum]);
3960 I->setFastMathFlags(FMF);
3966 case bitc::FUNC_CODE_INST_CAST: { // CAST: [opval, opty, destty, castopc]
3969 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
3970 OpNum+2 != Record.size())
3971 return error("Invalid record");
3973 Type *ResTy = getTypeByID(Record[OpNum]);
3974 int Opc = getDecodedCastOpcode(Record[OpNum + 1]);
3975 if (Opc == -1 || !ResTy)
3976 return error("Invalid record");
3977 Instruction *Temp = nullptr;
3978 if ((I = UpgradeBitCastInst(Opc, Op, ResTy, Temp))) {
3980 InstructionList.push_back(Temp);
3981 CurBB->getInstList().push_back(Temp);
3984 auto CastOp = (Instruction::CastOps)Opc;
3985 if (!CastInst::castIsValid(CastOp, Op, ResTy))
3986 return error("Invalid cast");
3987 I = CastInst::Create(CastOp, Op, ResTy);
3989 InstructionList.push_back(I);
3992 case bitc::FUNC_CODE_INST_INBOUNDS_GEP_OLD:
3993 case bitc::FUNC_CODE_INST_GEP_OLD:
3994 case bitc::FUNC_CODE_INST_GEP: { // GEP: type, [n x operands]
4000 if (BitCode == bitc::FUNC_CODE_INST_GEP) {
4001 InBounds = Record[OpNum++];
4002 Ty = getTypeByID(Record[OpNum++]);
4004 InBounds = BitCode == bitc::FUNC_CODE_INST_INBOUNDS_GEP_OLD;
4009 if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr))
4010 return error("Invalid record");
4013 Ty = cast<SequentialType>(BasePtr->getType()->getScalarType())
4016 cast<SequentialType>(BasePtr->getType()->getScalarType())
4019 "Explicit gep type does not match pointee type of pointer operand");
4021 SmallVector<Value*, 16> GEPIdx;
4022 while (OpNum != Record.size()) {
4024 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
4025 return error("Invalid record");
4026 GEPIdx.push_back(Op);
4029 I = GetElementPtrInst::Create(Ty, BasePtr, GEPIdx);
4031 InstructionList.push_back(I);
4033 cast<GetElementPtrInst>(I)->setIsInBounds(true);
4037 case bitc::FUNC_CODE_INST_EXTRACTVAL: {
4038 // EXTRACTVAL: [opty, opval, n x indices]
4041 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
4042 return error("Invalid record");
4044 unsigned RecSize = Record.size();
4045 if (OpNum == RecSize)
4046 return error("EXTRACTVAL: Invalid instruction with 0 indices");
4048 SmallVector<unsigned, 4> EXTRACTVALIdx;
4049 Type *CurTy = Agg->getType();
4050 for (; OpNum != RecSize; ++OpNum) {
4051 bool IsArray = CurTy->isArrayTy();
4052 bool IsStruct = CurTy->isStructTy();
4053 uint64_t Index = Record[OpNum];
4055 if (!IsStruct && !IsArray)
4056 return error("EXTRACTVAL: Invalid type");
4057 if ((unsigned)Index != Index)
4058 return error("Invalid value");
4059 if (IsStruct && Index >= CurTy->subtypes().size())
4060 return error("EXTRACTVAL: Invalid struct index");
4061 if (IsArray && Index >= CurTy->getArrayNumElements())
4062 return error("EXTRACTVAL: Invalid array index");
4063 EXTRACTVALIdx.push_back((unsigned)Index);
4066 CurTy = CurTy->subtypes()[Index];
4068 CurTy = CurTy->subtypes()[0];
4071 I = ExtractValueInst::Create(Agg, EXTRACTVALIdx);
4072 InstructionList.push_back(I);
4076 case bitc::FUNC_CODE_INST_INSERTVAL: {
4077 // INSERTVAL: [opty, opval, opty, opval, n x indices]
4080 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
4081 return error("Invalid record");
4083 if (getValueTypePair(Record, OpNum, NextValueNo, Val))
4084 return error("Invalid record");
4086 unsigned RecSize = Record.size();
4087 if (OpNum == RecSize)
4088 return error("INSERTVAL: Invalid instruction with 0 indices");
4090 SmallVector<unsigned, 4> INSERTVALIdx;
4091 Type *CurTy = Agg->getType();
4092 for (; OpNum != RecSize; ++OpNum) {
4093 bool IsArray = CurTy->isArrayTy();
4094 bool IsStruct = CurTy->isStructTy();
4095 uint64_t Index = Record[OpNum];
4097 if (!IsStruct && !IsArray)
4098 return error("INSERTVAL: Invalid type");
4099 if ((unsigned)Index != Index)
4100 return error("Invalid value");
4101 if (IsStruct && Index >= CurTy->subtypes().size())
4102 return error("INSERTVAL: Invalid struct index");
4103 if (IsArray && Index >= CurTy->getArrayNumElements())
4104 return error("INSERTVAL: Invalid array index");
4106 INSERTVALIdx.push_back((unsigned)Index);
4108 CurTy = CurTy->subtypes()[Index];
4110 CurTy = CurTy->subtypes()[0];
4113 if (CurTy != Val->getType())
4114 return error("Inserted value type doesn't match aggregate type");
4116 I = InsertValueInst::Create(Agg, Val, INSERTVALIdx);
4117 InstructionList.push_back(I);
4121 case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval]
4122 // obsolete form of select
4123 // handles select i1 ... in old bitcode
4125 Value *TrueVal, *FalseVal, *Cond;
4126 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
4127 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
4128 popValue(Record, OpNum, NextValueNo, Type::getInt1Ty(Context), Cond))
4129 return error("Invalid record");
4131 I = SelectInst::Create(Cond, TrueVal, FalseVal);
4132 InstructionList.push_back(I);
4136 case bitc::FUNC_CODE_INST_VSELECT: {// VSELECT: [ty,opval,opval,predty,pred]
4137 // new form of select
4138 // handles select i1 or select [N x i1]
4140 Value *TrueVal, *FalseVal, *Cond;
4141 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
4142 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
4143 getValueTypePair(Record, OpNum, NextValueNo, Cond))
4144 return error("Invalid record");
4146 // select condition can be either i1 or [N x i1]
4147 if (VectorType* vector_type =
4148 dyn_cast<VectorType>(Cond->getType())) {
4150 if (vector_type->getElementType() != Type::getInt1Ty(Context))
4151 return error("Invalid type for value");
4154 if (Cond->getType() != Type::getInt1Ty(Context))
4155 return error("Invalid type for value");
4158 I = SelectInst::Create(Cond, TrueVal, FalseVal);
4159 InstructionList.push_back(I);
4163 case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval]
4166 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
4167 getValueTypePair(Record, OpNum, NextValueNo, Idx))
4168 return error("Invalid record");
4169 if (!Vec->getType()->isVectorTy())
4170 return error("Invalid type for value");
4171 I = ExtractElementInst::Create(Vec, Idx);
4172 InstructionList.push_back(I);
4176 case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval]
4178 Value *Vec, *Elt, *Idx;
4179 if (getValueTypePair(Record, OpNum, NextValueNo, Vec))
4180 return error("Invalid record");
4181 if (!Vec->getType()->isVectorTy())
4182 return error("Invalid type for value");
4183 if (popValue(Record, OpNum, NextValueNo,
4184 cast<VectorType>(Vec->getType())->getElementType(), Elt) ||
4185 getValueTypePair(Record, OpNum, NextValueNo, Idx))
4186 return error("Invalid record");
4187 I = InsertElementInst::Create(Vec, Elt, Idx);
4188 InstructionList.push_back(I);
4192 case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval]
4194 Value *Vec1, *Vec2, *Mask;
4195 if (getValueTypePair(Record, OpNum, NextValueNo, Vec1) ||
4196 popValue(Record, OpNum, NextValueNo, Vec1->getType(), Vec2))
4197 return error("Invalid record");
4199 if (getValueTypePair(Record, OpNum, NextValueNo, Mask))
4200 return error("Invalid record");
4201 if (!Vec1->getType()->isVectorTy() || !Vec2->getType()->isVectorTy())
4202 return error("Invalid type for value");
4203 I = new ShuffleVectorInst(Vec1, Vec2, Mask);
4204 InstructionList.push_back(I);
4208 case bitc::FUNC_CODE_INST_CMP: // CMP: [opty, opval, opval, pred]
4209 // Old form of ICmp/FCmp returning bool
4210 // Existed to differentiate between icmp/fcmp and vicmp/vfcmp which were
4211 // both legal on vectors but had different behaviour.
4212 case bitc::FUNC_CODE_INST_CMP2: { // CMP2: [opty, opval, opval, pred]
4213 // FCmp/ICmp returning bool or vector of bool
4217 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
4218 popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS))
4219 return error("Invalid record");
4221 unsigned PredVal = Record[OpNum];
4222 bool IsFP = LHS->getType()->isFPOrFPVectorTy();
4224 if (IsFP && Record.size() > OpNum+1)
4225 FMF = getDecodedFastMathFlags(Record[++OpNum]);
4227 if (OpNum+1 != Record.size())
4228 return error("Invalid record");
4230 if (LHS->getType()->isFPOrFPVectorTy())
4231 I = new FCmpInst((FCmpInst::Predicate)PredVal, LHS, RHS);
4233 I = new ICmpInst((ICmpInst::Predicate)PredVal, LHS, RHS);
4236 I->setFastMathFlags(FMF);
4237 InstructionList.push_back(I);
4241 case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>]
4243 unsigned Size = Record.size();
4245 I = ReturnInst::Create(Context);
4246 InstructionList.push_back(I);
4251 Value *Op = nullptr;
4252 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
4253 return error("Invalid record");
4254 if (OpNum != Record.size())
4255 return error("Invalid record");
4257 I = ReturnInst::Create(Context, Op);
4258 InstructionList.push_back(I);
4261 case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#]
4262 if (Record.size() != 1 && Record.size() != 3)
4263 return error("Invalid record");
4264 BasicBlock *TrueDest = getBasicBlock(Record[0]);
4266 return error("Invalid record");
4268 if (Record.size() == 1) {
4269 I = BranchInst::Create(TrueDest);
4270 InstructionList.push_back(I);
4273 BasicBlock *FalseDest = getBasicBlock(Record[1]);
4274 Value *Cond = getValue(Record, 2, NextValueNo,
4275 Type::getInt1Ty(Context));
4276 if (!FalseDest || !Cond)
4277 return error("Invalid record");
4278 I = BranchInst::Create(TrueDest, FalseDest, Cond);
4279 InstructionList.push_back(I);
4283 case bitc::FUNC_CODE_INST_CLEANUPRET: { // CLEANUPRET: [val] or [val,bb#]
4284 if (Record.size() != 1 && Record.size() != 2)
4285 return error("Invalid record");
4287 Value *CleanupPad = getValue(Record, Idx++, NextValueNo,
4288 Type::getTokenTy(Context), OC_CleanupPad);
4290 return error("Invalid record");
4291 BasicBlock *UnwindDest = nullptr;
4292 if (Record.size() == 2) {
4293 UnwindDest = getBasicBlock(Record[Idx++]);
4295 return error("Invalid record");
4298 I = CleanupReturnInst::Create(cast<CleanupPadInst>(CleanupPad),
4300 InstructionList.push_back(I);
4303 case bitc::FUNC_CODE_INST_CATCHRET: { // CATCHRET: [val,bb#]
4304 if (Record.size() != 2)
4305 return error("Invalid record");
4307 Value *CatchPad = getValue(Record, Idx++, NextValueNo,
4308 Type::getTokenTy(Context), OC_CatchPad);
4310 return error("Invalid record");
4311 BasicBlock *BB = getBasicBlock(Record[Idx++]);
4313 return error("Invalid record");
4315 I = CatchReturnInst::Create(cast<CatchPadInst>(CatchPad), BB);
4316 InstructionList.push_back(I);
4319 case bitc::FUNC_CODE_INST_CATCHPAD: { // CATCHPAD: [bb#,bb#,num,(ty,val)*]
4320 if (Record.size() < 3)
4321 return error("Invalid record");
4323 BasicBlock *NormalBB = getBasicBlock(Record[Idx++]);
4325 return error("Invalid record");
4326 BasicBlock *UnwindBB = getBasicBlock(Record[Idx++]);
4328 return error("Invalid record");
4329 unsigned NumArgOperands = Record[Idx++];
4330 SmallVector<Value *, 2> Args;
4331 for (unsigned Op = 0; Op != NumArgOperands; ++Op) {
4333 if (getValueTypePair(Record, Idx, NextValueNo, Val))
4334 return error("Invalid record");
4335 Args.push_back(Val);
4337 if (Record.size() != Idx)
4338 return error("Invalid record");
4340 I = CatchPadInst::Create(NormalBB, UnwindBB, Args);
4341 InstructionList.push_back(I);
4344 case bitc::FUNC_CODE_INST_TERMINATEPAD: { // TERMINATEPAD: [bb#,num,(ty,val)*]
4345 if (Record.size() < 1)
4346 return error("Invalid record");
4348 bool HasUnwindDest = !!Record[Idx++];
4349 BasicBlock *UnwindDest = nullptr;
4350 if (HasUnwindDest) {
4351 if (Idx == Record.size())
4352 return error("Invalid record");
4353 UnwindDest = getBasicBlock(Record[Idx++]);
4355 return error("Invalid record");
4357 unsigned NumArgOperands = Record[Idx++];
4358 SmallVector<Value *, 2> Args;
4359 for (unsigned Op = 0; Op != NumArgOperands; ++Op) {
4361 if (getValueTypePair(Record, Idx, NextValueNo, Val))
4362 return error("Invalid record");
4363 Args.push_back(Val);
4365 if (Record.size() != Idx)
4366 return error("Invalid record");
4368 I = TerminatePadInst::Create(Context, UnwindDest, Args);
4369 InstructionList.push_back(I);
4372 case bitc::FUNC_CODE_INST_CLEANUPPAD: { // CLEANUPPAD: [num,(ty,val)*]
4373 if (Record.size() < 1)
4374 return error("Invalid record");
4376 unsigned NumArgOperands = Record[Idx++];
4377 SmallVector<Value *, 2> Args;
4378 for (unsigned Op = 0; Op != NumArgOperands; ++Op) {
4380 if (getValueTypePair(Record, Idx, NextValueNo, Val))
4381 return error("Invalid record");
4382 Args.push_back(Val);
4384 if (Record.size() != Idx)
4385 return error("Invalid record");
4387 I = CleanupPadInst::Create(Context, Args);
4388 InstructionList.push_back(I);
4391 case bitc::FUNC_CODE_INST_CATCHENDPAD: { // CATCHENDPADINST: [bb#] or []
4392 if (Record.size() > 1)
4393 return error("Invalid record");
4394 BasicBlock *BB = nullptr;
4395 if (Record.size() == 1) {
4396 BB = getBasicBlock(Record[0]);
4398 return error("Invalid record");
4400 I = CatchEndPadInst::Create(Context, BB);
4401 InstructionList.push_back(I);
4404 case bitc::FUNC_CODE_INST_CLEANUPENDPAD: { // CLEANUPENDPADINST: [val] or [val,bb#]
4405 if (Record.size() != 1 && Record.size() != 2)
4406 return error("Invalid record");
4408 Value *CleanupPad = getValue(Record, Idx++, NextValueNo,
4409 Type::getTokenTy(Context), OC_CleanupPad);
4411 return error("Invalid record");
4413 BasicBlock *BB = nullptr;
4414 if (Record.size() == 2) {
4415 BB = getBasicBlock(Record[Idx++]);
4417 return error("Invalid record");
4419 I = CleanupEndPadInst::Create(cast<CleanupPadInst>(CleanupPad), BB);
4420 InstructionList.push_back(I);
4423 case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, op0, op1, ...]
4425 if ((Record[0] >> 16) == SWITCH_INST_MAGIC) {
4426 // "New" SwitchInst format with case ranges. The changes to write this
4427 // format were reverted but we still recognize bitcode that uses it.
4428 // Hopefully someday we will have support for case ranges and can use
4429 // this format again.
4431 Type *OpTy = getTypeByID(Record[1]);
4432 unsigned ValueBitWidth = cast<IntegerType>(OpTy)->getBitWidth();
4434 Value *Cond = getValue(Record, 2, NextValueNo, OpTy);
4435 BasicBlock *Default = getBasicBlock(Record[3]);
4436 if (!OpTy || !Cond || !Default)
4437 return error("Invalid record");
4439 unsigned NumCases = Record[4];
4441 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
4442 InstructionList.push_back(SI);
4444 unsigned CurIdx = 5;
4445 for (unsigned i = 0; i != NumCases; ++i) {
4446 SmallVector<ConstantInt*, 1> CaseVals;
4447 unsigned NumItems = Record[CurIdx++];
4448 for (unsigned ci = 0; ci != NumItems; ++ci) {
4449 bool isSingleNumber = Record[CurIdx++];
4452 unsigned ActiveWords = 1;
4453 if (ValueBitWidth > 64)
4454 ActiveWords = Record[CurIdx++];
4455 Low = readWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords),
4457 CurIdx += ActiveWords;
4459 if (!isSingleNumber) {
4461 if (ValueBitWidth > 64)
4462 ActiveWords = Record[CurIdx++];
4463 APInt High = readWideAPInt(
4464 makeArrayRef(&Record[CurIdx], ActiveWords), ValueBitWidth);
4465 CurIdx += ActiveWords;
4467 // FIXME: It is not clear whether values in the range should be
4468 // compared as signed or unsigned values. The partially
4469 // implemented changes that used this format in the past used
4470 // unsigned comparisons.
4471 for ( ; Low.ule(High); ++Low)
4472 CaseVals.push_back(ConstantInt::get(Context, Low));
4474 CaseVals.push_back(ConstantInt::get(Context, Low));
4476 BasicBlock *DestBB = getBasicBlock(Record[CurIdx++]);
4477 for (SmallVector<ConstantInt*, 1>::iterator cvi = CaseVals.begin(),
4478 cve = CaseVals.end(); cvi != cve; ++cvi)
4479 SI->addCase(*cvi, DestBB);
4485 // Old SwitchInst format without case ranges.
4487 if (Record.size() < 3 || (Record.size() & 1) == 0)
4488 return error("Invalid record");
4489 Type *OpTy = getTypeByID(Record[0]);
4490 Value *Cond = getValue(Record, 1, NextValueNo, OpTy);
4491 BasicBlock *Default = getBasicBlock(Record[2]);
4492 if (!OpTy || !Cond || !Default)
4493 return error("Invalid record");
4494 unsigned NumCases = (Record.size()-3)/2;
4495 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
4496 InstructionList.push_back(SI);
4497 for (unsigned i = 0, e = NumCases; i != e; ++i) {
4498 ConstantInt *CaseVal =
4499 dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy));
4500 BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]);
4501 if (!CaseVal || !DestBB) {
4503 return error("Invalid record");
4505 SI->addCase(CaseVal, DestBB);
4510 case bitc::FUNC_CODE_INST_INDIRECTBR: { // INDIRECTBR: [opty, op0, op1, ...]
4511 if (Record.size() < 2)
4512 return error("Invalid record");
4513 Type *OpTy = getTypeByID(Record[0]);
4514 Value *Address = getValue(Record, 1, NextValueNo, OpTy);
4515 if (!OpTy || !Address)
4516 return error("Invalid record");
4517 unsigned NumDests = Record.size()-2;
4518 IndirectBrInst *IBI = IndirectBrInst::Create(Address, NumDests);
4519 InstructionList.push_back(IBI);
4520 for (unsigned i = 0, e = NumDests; i != e; ++i) {
4521 if (BasicBlock *DestBB = getBasicBlock(Record[2+i])) {
4522 IBI->addDestination(DestBB);
4525 return error("Invalid record");
4532 case bitc::FUNC_CODE_INST_INVOKE: {
4533 // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...]
4534 if (Record.size() < 4)
4535 return error("Invalid record");
4537 AttributeSet PAL = getAttributes(Record[OpNum++]);
4538 unsigned CCInfo = Record[OpNum++];
4539 BasicBlock *NormalBB = getBasicBlock(Record[OpNum++]);
4540 BasicBlock *UnwindBB = getBasicBlock(Record[OpNum++]);
4542 FunctionType *FTy = nullptr;
4543 if (CCInfo >> 13 & 1 &&
4544 !(FTy = dyn_cast<FunctionType>(getTypeByID(Record[OpNum++]))))
4545 return error("Explicit invoke type is not a function type");
4548 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
4549 return error("Invalid record");
4551 PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType());
4553 return error("Callee is not a pointer");
4555 FTy = dyn_cast<FunctionType>(CalleeTy->getElementType());
4557 return error("Callee is not of pointer to function type");
4558 } else if (CalleeTy->getElementType() != FTy)
4559 return error("Explicit invoke type does not match pointee type of "
4561 if (Record.size() < FTy->getNumParams() + OpNum)
4562 return error("Insufficient operands to call");
4564 SmallVector<Value*, 16> Ops;
4565 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
4566 Ops.push_back(getValue(Record, OpNum, NextValueNo,
4567 FTy->getParamType(i)));
4569 return error("Invalid record");
4572 if (!FTy->isVarArg()) {
4573 if (Record.size() != OpNum)
4574 return error("Invalid record");
4576 // Read type/value pairs for varargs params.
4577 while (OpNum != Record.size()) {
4579 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
4580 return error("Invalid record");
4585 I = InvokeInst::Create(Callee, NormalBB, UnwindBB, Ops, OperandBundles);
4586 OperandBundles.clear();
4587 InstructionList.push_back(I);
4588 cast<InvokeInst>(I)->setCallingConv(
4589 static_cast<CallingConv::ID>(CallingConv::MaxID & CCInfo));
4590 cast<InvokeInst>(I)->setAttributes(PAL);
4593 case bitc::FUNC_CODE_INST_RESUME: { // RESUME: [opval]
4595 Value *Val = nullptr;
4596 if (getValueTypePair(Record, Idx, NextValueNo, Val))
4597 return error("Invalid record");
4598 I = ResumeInst::Create(Val);
4599 InstructionList.push_back(I);
4602 case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE
4603 I = new UnreachableInst(Context);
4604 InstructionList.push_back(I);
4606 case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...]
4607 if (Record.size() < 1 || ((Record.size()-1)&1))
4608 return error("Invalid record");
4609 Type *Ty = getTypeByID(Record[0]);
4611 return error("Invalid record");
4613 PHINode *PN = PHINode::Create(Ty, (Record.size()-1)/2);
4614 InstructionList.push_back(PN);
4616 for (unsigned i = 0, e = Record.size()-1; i != e; i += 2) {
4618 // With the new function encoding, it is possible that operands have
4619 // negative IDs (for forward references). Use a signed VBR
4620 // representation to keep the encoding small.
4622 V = getValueSigned(Record, 1+i, NextValueNo, Ty);
4624 V = getValue(Record, 1+i, NextValueNo, Ty);
4625 BasicBlock *BB = getBasicBlock(Record[2+i]);
4627 return error("Invalid record");
4628 PN->addIncoming(V, BB);
4634 case bitc::FUNC_CODE_INST_LANDINGPAD:
4635 case bitc::FUNC_CODE_INST_LANDINGPAD_OLD: {
4636 // LANDINGPAD: [ty, val, val, num, (id0,val0 ...)?]
4638 if (BitCode == bitc::FUNC_CODE_INST_LANDINGPAD) {
4639 if (Record.size() < 3)
4640 return error("Invalid record");
4642 assert(BitCode == bitc::FUNC_CODE_INST_LANDINGPAD_OLD);
4643 if (Record.size() < 4)
4644 return error("Invalid record");
4646 Type *Ty = getTypeByID(Record[Idx++]);
4648 return error("Invalid record");
4649 if (BitCode == bitc::FUNC_CODE_INST_LANDINGPAD_OLD) {
4650 Value *PersFn = nullptr;
4651 if (getValueTypePair(Record, Idx, NextValueNo, PersFn))
4652 return error("Invalid record");
4654 if (!F->hasPersonalityFn())
4655 F->setPersonalityFn(cast<Constant>(PersFn));
4656 else if (F->getPersonalityFn() != cast<Constant>(PersFn))
4657 return error("Personality function mismatch");
4660 bool IsCleanup = !!Record[Idx++];
4661 unsigned NumClauses = Record[Idx++];
4662 LandingPadInst *LP = LandingPadInst::Create(Ty, NumClauses);
4663 LP->setCleanup(IsCleanup);
4664 for (unsigned J = 0; J != NumClauses; ++J) {
4665 LandingPadInst::ClauseType CT =
4666 LandingPadInst::ClauseType(Record[Idx++]); (void)CT;
4669 if (getValueTypePair(Record, Idx, NextValueNo, Val)) {
4671 return error("Invalid record");
4674 assert((CT != LandingPadInst::Catch ||
4675 !isa<ArrayType>(Val->getType())) &&
4676 "Catch clause has a invalid type!");
4677 assert((CT != LandingPadInst::Filter ||
4678 isa<ArrayType>(Val->getType())) &&
4679 "Filter clause has invalid type!");
4680 LP->addClause(cast<Constant>(Val));
4684 InstructionList.push_back(I);
4688 case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, opty, op, align]
4689 if (Record.size() != 4)
4690 return error("Invalid record");
4691 uint64_t AlignRecord = Record[3];
4692 const uint64_t InAllocaMask = uint64_t(1) << 5;
4693 const uint64_t ExplicitTypeMask = uint64_t(1) << 6;
4694 // Reserve bit 7 for SwiftError flag.
4695 // const uint64_t SwiftErrorMask = uint64_t(1) << 7;
4696 const uint64_t FlagMask = InAllocaMask | ExplicitTypeMask;
4697 bool InAlloca = AlignRecord & InAllocaMask;
4698 Type *Ty = getTypeByID(Record[0]);
4699 if ((AlignRecord & ExplicitTypeMask) == 0) {
4700 auto *PTy = dyn_cast_or_null<PointerType>(Ty);
4702 return error("Old-style alloca with a non-pointer type");
4703 Ty = PTy->getElementType();
4705 Type *OpTy = getTypeByID(Record[1]);
4706 Value *Size = getFnValueByID(Record[2], OpTy);
4708 if (std::error_code EC =
4709 parseAlignmentValue(AlignRecord & ~FlagMask, Align)) {
4713 return error("Invalid record");
4714 AllocaInst *AI = new AllocaInst(Ty, Size, Align);
4715 AI->setUsedWithInAlloca(InAlloca);
4717 InstructionList.push_back(I);
4720 case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol]
4723 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
4724 (OpNum + 2 != Record.size() && OpNum + 3 != Record.size()))
4725 return error("Invalid record");
4728 if (OpNum + 3 == Record.size())
4729 Ty = getTypeByID(Record[OpNum++]);
4730 if (std::error_code EC =
4731 typeCheckLoadStoreInst(DiagnosticHandler, Ty, Op->getType()))
4734 Ty = cast<PointerType>(Op->getType())->getElementType();
4737 if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align))
4739 I = new LoadInst(Ty, Op, "", Record[OpNum + 1], Align);
4741 InstructionList.push_back(I);
4744 case bitc::FUNC_CODE_INST_LOADATOMIC: {
4745 // LOADATOMIC: [opty, op, align, vol, ordering, synchscope]
4748 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
4749 (OpNum + 4 != Record.size() && OpNum + 5 != Record.size()))
4750 return error("Invalid record");
4753 if (OpNum + 5 == Record.size())
4754 Ty = getTypeByID(Record[OpNum++]);
4755 if (std::error_code EC =
4756 typeCheckLoadStoreInst(DiagnosticHandler, Ty, Op->getType()))
4759 Ty = cast<PointerType>(Op->getType())->getElementType();
4761 AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]);
4762 if (Ordering == NotAtomic || Ordering == Release ||
4763 Ordering == AcquireRelease)
4764 return error("Invalid record");
4765 if (Ordering != NotAtomic && Record[OpNum] == 0)
4766 return error("Invalid record");
4767 SynchronizationScope SynchScope = getDecodedSynchScope(Record[OpNum + 3]);
4770 if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align))
4772 I = new LoadInst(Op, "", Record[OpNum+1], Align, Ordering, SynchScope);
4774 InstructionList.push_back(I);
4777 case bitc::FUNC_CODE_INST_STORE:
4778 case bitc::FUNC_CODE_INST_STORE_OLD: { // STORE2:[ptrty, ptr, val, align, vol]
4781 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
4782 (BitCode == bitc::FUNC_CODE_INST_STORE
4783 ? getValueTypePair(Record, OpNum, NextValueNo, Val)
4784 : popValue(Record, OpNum, NextValueNo,
4785 cast<PointerType>(Ptr->getType())->getElementType(),
4787 OpNum + 2 != Record.size())
4788 return error("Invalid record");
4790 if (std::error_code EC = typeCheckLoadStoreInst(
4791 DiagnosticHandler, Val->getType(), Ptr->getType()))
4794 if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align))
4796 I = new StoreInst(Val, Ptr, Record[OpNum+1], Align);
4797 InstructionList.push_back(I);
4800 case bitc::FUNC_CODE_INST_STOREATOMIC:
4801 case bitc::FUNC_CODE_INST_STOREATOMIC_OLD: {
4802 // STOREATOMIC: [ptrty, ptr, val, align, vol, ordering, synchscope]
4805 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
4806 (BitCode == bitc::FUNC_CODE_INST_STOREATOMIC
4807 ? getValueTypePair(Record, OpNum, NextValueNo, Val)
4808 : popValue(Record, OpNum, NextValueNo,
4809 cast<PointerType>(Ptr->getType())->getElementType(),
4811 OpNum + 4 != Record.size())
4812 return error("Invalid record");
4814 if (std::error_code EC = typeCheckLoadStoreInst(
4815 DiagnosticHandler, Val->getType(), Ptr->getType()))
4817 AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]);
4818 if (Ordering == NotAtomic || Ordering == Acquire ||
4819 Ordering == AcquireRelease)
4820 return error("Invalid record");
4821 SynchronizationScope SynchScope = getDecodedSynchScope(Record[OpNum + 3]);
4822 if (Ordering != NotAtomic && Record[OpNum] == 0)
4823 return error("Invalid record");
4826 if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align))
4828 I = new StoreInst(Val, Ptr, Record[OpNum+1], Align, Ordering, SynchScope);
4829 InstructionList.push_back(I);
4832 case bitc::FUNC_CODE_INST_CMPXCHG_OLD:
4833 case bitc::FUNC_CODE_INST_CMPXCHG: {
4834 // CMPXCHG:[ptrty, ptr, cmp, new, vol, successordering, synchscope,
4835 // failureordering?, isweak?]
4837 Value *Ptr, *Cmp, *New;
4838 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
4839 (BitCode == bitc::FUNC_CODE_INST_CMPXCHG
4840 ? getValueTypePair(Record, OpNum, NextValueNo, Cmp)
4841 : popValue(Record, OpNum, NextValueNo,
4842 cast<PointerType>(Ptr->getType())->getElementType(),
4844 popValue(Record, OpNum, NextValueNo, Cmp->getType(), New) ||
4845 Record.size() < OpNum + 3 || Record.size() > OpNum + 5)
4846 return error("Invalid record");
4847 AtomicOrdering SuccessOrdering = getDecodedOrdering(Record[OpNum + 1]);
4848 if (SuccessOrdering == NotAtomic || SuccessOrdering == Unordered)
4849 return error("Invalid record");
4850 SynchronizationScope SynchScope = getDecodedSynchScope(Record[OpNum + 2]);
4852 if (std::error_code EC = typeCheckLoadStoreInst(
4853 DiagnosticHandler, Cmp->getType(), Ptr->getType()))
4855 AtomicOrdering FailureOrdering;
4856 if (Record.size() < 7)
4858 AtomicCmpXchgInst::getStrongestFailureOrdering(SuccessOrdering);
4860 FailureOrdering = getDecodedOrdering(Record[OpNum + 3]);
4862 I = new AtomicCmpXchgInst(Ptr, Cmp, New, SuccessOrdering, FailureOrdering,
4864 cast<AtomicCmpXchgInst>(I)->setVolatile(Record[OpNum]);
4866 if (Record.size() < 8) {
4867 // Before weak cmpxchgs existed, the instruction simply returned the
4868 // value loaded from memory, so bitcode files from that era will be
4869 // expecting the first component of a modern cmpxchg.
4870 CurBB->getInstList().push_back(I);
4871 I = ExtractValueInst::Create(I, 0);
4873 cast<AtomicCmpXchgInst>(I)->setWeak(Record[OpNum+4]);
4876 InstructionList.push_back(I);
4879 case bitc::FUNC_CODE_INST_ATOMICRMW: {
4880 // ATOMICRMW:[ptrty, ptr, val, op, vol, ordering, synchscope]
4883 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
4884 popValue(Record, OpNum, NextValueNo,
4885 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
4886 OpNum+4 != Record.size())
4887 return error("Invalid record");
4888 AtomicRMWInst::BinOp Operation = getDecodedRMWOperation(Record[OpNum]);
4889 if (Operation < AtomicRMWInst::FIRST_BINOP ||
4890 Operation > AtomicRMWInst::LAST_BINOP)
4891 return error("Invalid record");
4892 AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]);
4893 if (Ordering == NotAtomic || Ordering == Unordered)
4894 return error("Invalid record");
4895 SynchronizationScope SynchScope = getDecodedSynchScope(Record[OpNum + 3]);
4896 I = new AtomicRMWInst(Operation, Ptr, Val, Ordering, SynchScope);
4897 cast<AtomicRMWInst>(I)->setVolatile(Record[OpNum+1]);
4898 InstructionList.push_back(I);
4901 case bitc::FUNC_CODE_INST_FENCE: { // FENCE:[ordering, synchscope]
4902 if (2 != Record.size())
4903 return error("Invalid record");
4904 AtomicOrdering Ordering = getDecodedOrdering(Record[0]);
4905 if (Ordering == NotAtomic || Ordering == Unordered ||
4906 Ordering == Monotonic)
4907 return error("Invalid record");
4908 SynchronizationScope SynchScope = getDecodedSynchScope(Record[1]);
4909 I = new FenceInst(Context, Ordering, SynchScope);
4910 InstructionList.push_back(I);
4913 case bitc::FUNC_CODE_INST_CALL: {
4914 // CALL: [paramattrs, cc, fnty, fnid, arg0, arg1...]
4915 if (Record.size() < 3)
4916 return error("Invalid record");
4919 AttributeSet PAL = getAttributes(Record[OpNum++]);
4920 unsigned CCInfo = Record[OpNum++];
4922 FunctionType *FTy = nullptr;
4923 if (CCInfo >> 15 & 1 &&
4924 !(FTy = dyn_cast<FunctionType>(getTypeByID(Record[OpNum++]))))
4925 return error("Explicit call type is not a function type");
4928 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
4929 return error("Invalid record");
4931 PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());
4933 return error("Callee is not a pointer type");
4935 FTy = dyn_cast<FunctionType>(OpTy->getElementType());
4937 return error("Callee is not of pointer to function type");
4938 } else if (OpTy->getElementType() != FTy)
4939 return error("Explicit call type does not match pointee type of "
4941 if (Record.size() < FTy->getNumParams() + OpNum)
4942 return error("Insufficient operands to call");
4944 SmallVector<Value*, 16> Args;
4945 // Read the fixed params.
4946 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
4947 if (FTy->getParamType(i)->isLabelTy())
4948 Args.push_back(getBasicBlock(Record[OpNum]));
4950 Args.push_back(getValue(Record, OpNum, NextValueNo,
4951 FTy->getParamType(i)));
4953 return error("Invalid record");
4956 // Read type/value pairs for varargs params.
4957 if (!FTy->isVarArg()) {
4958 if (OpNum != Record.size())
4959 return error("Invalid record");
4961 while (OpNum != Record.size()) {
4963 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
4964 return error("Invalid record");
4969 I = CallInst::Create(FTy, Callee, Args, OperandBundles);
4970 OperandBundles.clear();
4971 InstructionList.push_back(I);
4972 cast<CallInst>(I)->setCallingConv(
4973 static_cast<CallingConv::ID>((0x7ff & CCInfo) >> 1));
4974 CallInst::TailCallKind TCK = CallInst::TCK_None;
4976 TCK = CallInst::TCK_Tail;
4977 if (CCInfo & (1 << 14))
4978 TCK = CallInst::TCK_MustTail;
4979 cast<CallInst>(I)->setTailCallKind(TCK);
4980 cast<CallInst>(I)->setAttributes(PAL);
4983 case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty]
4984 if (Record.size() < 3)
4985 return error("Invalid record");
4986 Type *OpTy = getTypeByID(Record[0]);
4987 Value *Op = getValue(Record, 1, NextValueNo, OpTy);
4988 Type *ResTy = getTypeByID(Record[2]);
4989 if (!OpTy || !Op || !ResTy)
4990 return error("Invalid record");
4991 I = new VAArgInst(Op, ResTy);
4992 InstructionList.push_back(I);
4996 case bitc::FUNC_CODE_OPERAND_BUNDLE: {
4997 // A call or an invoke can be optionally prefixed with some variable
4998 // number of operand bundle blocks. These blocks are read into
4999 // OperandBundles and consumed at the next call or invoke instruction.
5001 if (Record.size() < 1 || Record[0] >= BundleTags.size())
5002 return error("Invalid record");
5004 OperandBundles.emplace_back();
5005 OperandBundles.back().Tag = BundleTags[Record[0]];
5007 std::vector<Value *> &Inputs = OperandBundles.back().Inputs;
5010 while (OpNum != Record.size()) {
5012 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
5013 return error("Invalid record");
5014 Inputs.push_back(Op);
5021 // Add instruction to end of current BB. If there is no current BB, reject
5025 return error("Invalid instruction with no BB");
5027 if (!OperandBundles.empty()) {
5029 return error("Operand bundles found with no consumer");
5031 CurBB->getInstList().push_back(I);
5033 // If this was a terminator instruction, move to the next block.
5034 if (isa<TerminatorInst>(I)) {
5036 CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : nullptr;
5039 // Non-void values get registered in the value table for future use.
5040 if (I && !I->getType()->isVoidTy())
5041 if (ValueList.assignValue(I, NextValueNo++))
5042 return error("Invalid forward reference");
5047 if (!OperandBundles.empty())
5048 return error("Operand bundles found with no consumer");
5050 // Check the function list for unresolved values.
5051 if (Argument *A = dyn_cast<Argument>(ValueList.back())) {
5052 if (!A->getParent()) {
5053 // We found at least one unresolved value. Nuke them all to avoid leaks.
5054 for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){
5055 if ((A = dyn_cast_or_null<Argument>(ValueList[i])) && !A->getParent()) {
5056 A->replaceAllUsesWith(UndefValue::get(A->getType()));
5060 return error("Never resolved value found in function");
5064 // FIXME: Check for unresolved forward-declared metadata references
5065 // and clean up leaks.
5067 // Trim the value list down to the size it was before we parsed this function.
5068 ValueList.shrinkTo(ModuleValueListSize);
5069 MDValueList.shrinkTo(ModuleMDValueListSize);
5070 std::vector<BasicBlock*>().swap(FunctionBBs);
5071 return std::error_code();
5074 /// Find the function body in the bitcode stream
5075 std::error_code BitcodeReader::findFunctionInStream(
5077 DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator) {
5078 while (DeferredFunctionInfoIterator->second == 0) {
5079 // This is the fallback handling for the old format bitcode that
5080 // didn't contain the function index in the VST, or when we have
5081 // an anonymous function which would not have a VST entry.
5082 // Assert that we have one of those two cases.
5083 assert(VSTOffset == 0 || !F->hasName());
5084 // Parse the next body in the stream and set its position in the
5085 // DeferredFunctionInfo map.
5086 if (std::error_code EC = rememberAndSkipFunctionBodies()) return EC;
5088 return std::error_code();
5091 //===----------------------------------------------------------------------===//
5092 // GVMaterializer implementation
5093 //===----------------------------------------------------------------------===//
5095 void BitcodeReader::releaseBuffer() { Buffer.release(); }
5097 std::error_code BitcodeReader::materialize(GlobalValue *GV) {
5098 if (std::error_code EC = materializeMetadata())
5101 Function *F = dyn_cast<Function>(GV);
5102 // If it's not a function or is already material, ignore the request.
5103 if (!F || !F->isMaterializable())
5104 return std::error_code();
5106 DenseMap<Function*, uint64_t>::iterator DFII = DeferredFunctionInfo.find(F);
5107 assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!");
5108 // If its position is recorded as 0, its body is somewhere in the stream
5109 // but we haven't seen it yet.
5110 if (DFII->second == 0)
5111 if (std::error_code EC = findFunctionInStream(F, DFII))
5114 // Move the bit stream to the saved position of the deferred function body.
5115 Stream.JumpToBit(DFII->second);
5117 if (std::error_code EC = parseFunctionBody(F))
5119 F->setIsMaterializable(false);
5124 // Upgrade any old intrinsic calls in the function.
5125 for (auto &I : UpgradedIntrinsics) {
5126 for (auto UI = I.first->user_begin(), UE = I.first->user_end(); UI != UE;) {
5129 if (CallInst *CI = dyn_cast<CallInst>(U))
5130 UpgradeIntrinsicCall(CI, I.second);
5134 // Bring in any functions that this function forward-referenced via
5136 return materializeForwardReferencedFunctions();
5139 bool BitcodeReader::isDematerializable(const GlobalValue *GV) const {
5140 const Function *F = dyn_cast<Function>(GV);
5141 if (!F || F->isDeclaration())
5144 // Dematerializing F would leave dangling references that wouldn't be
5145 // reconnected on re-materialization.
5146 if (BlockAddressesTaken.count(F))
5149 return DeferredFunctionInfo.count(const_cast<Function*>(F));
5152 void BitcodeReader::dematerialize(GlobalValue *GV) {
5153 Function *F = dyn_cast<Function>(GV);
5154 // If this function isn't dematerializable, this is a noop.
5155 if (!F || !isDematerializable(F))
5158 assert(DeferredFunctionInfo.count(F) && "No info to read function later?");
5160 // Just forget the function body, we can remat it later.
5161 F->dropAllReferences();
5162 F->setIsMaterializable(true);
5165 std::error_code BitcodeReader::materializeModule(Module *M) {
5166 assert(M == TheModule &&
5167 "Can only Materialize the Module this BitcodeReader is attached to.");
5169 if (std::error_code EC = materializeMetadata())
5172 // Promise to materialize all forward references.
5173 WillMaterializeAllForwardRefs = true;
5175 // Iterate over the module, deserializing any functions that are still on
5177 for (Function &F : *TheModule) {
5178 if (std::error_code EC = materialize(&F))
5181 // At this point, if there are any function bodies, parse the rest of
5182 // the bits in the module past the last function block we have recorded
5183 // through either lazy scanning or the VST.
5184 if (LastFunctionBlockBit || NextUnreadBit)
5185 parseModule(LastFunctionBlockBit > NextUnreadBit ? LastFunctionBlockBit
5188 // Check that all block address forward references got resolved (as we
5190 if (!BasicBlockFwdRefs.empty())
5191 return error("Never resolved function from blockaddress");
5193 // Upgrade any intrinsic calls that slipped through (should not happen!) and
5194 // delete the old functions to clean up. We can't do this unless the entire
5195 // module is materialized because there could always be another function body
5196 // with calls to the old function.
5197 for (auto &I : UpgradedIntrinsics) {
5198 for (auto *U : I.first->users()) {
5199 if (CallInst *CI = dyn_cast<CallInst>(U))
5200 UpgradeIntrinsicCall(CI, I.second);
5202 if (!I.first->use_empty())
5203 I.first->replaceAllUsesWith(I.second);
5204 I.first->eraseFromParent();
5206 UpgradedIntrinsics.clear();
5208 for (unsigned I = 0, E = InstsWithTBAATag.size(); I < E; I++)
5209 UpgradeInstWithTBAATag(InstsWithTBAATag[I]);
5211 UpgradeDebugInfo(*M);
5212 return std::error_code();
5215 std::vector<StructType *> BitcodeReader::getIdentifiedStructTypes() const {
5216 return IdentifiedStructTypes;
5220 BitcodeReader::initStream(std::unique_ptr<DataStreamer> Streamer) {
5222 return initLazyStream(std::move(Streamer));
5223 return initStreamFromBuffer();
5226 std::error_code BitcodeReader::initStreamFromBuffer() {
5227 const unsigned char *BufPtr = (const unsigned char*)Buffer->getBufferStart();
5228 const unsigned char *BufEnd = BufPtr+Buffer->getBufferSize();
5230 if (Buffer->getBufferSize() & 3)
5231 return error("Invalid bitcode signature");
5233 // If we have a wrapper header, parse it and ignore the non-bc file contents.
5234 // The magic number is 0x0B17C0DE stored in little endian.
5235 if (isBitcodeWrapper(BufPtr, BufEnd))
5236 if (SkipBitcodeWrapperHeader(BufPtr, BufEnd, true))
5237 return error("Invalid bitcode wrapper header");
5239 StreamFile.reset(new BitstreamReader(BufPtr, BufEnd));
5240 Stream.init(&*StreamFile);
5242 return std::error_code();
5246 BitcodeReader::initLazyStream(std::unique_ptr<DataStreamer> Streamer) {
5247 // Check and strip off the bitcode wrapper; BitstreamReader expects never to
5250 llvm::make_unique<StreamingMemoryObject>(std::move(Streamer));
5251 StreamingMemoryObject &Bytes = *OwnedBytes;
5252 StreamFile = llvm::make_unique<BitstreamReader>(std::move(OwnedBytes));
5253 Stream.init(&*StreamFile);
5255 unsigned char buf[16];
5256 if (Bytes.readBytes(buf, 16, 0) != 16)
5257 return error("Invalid bitcode signature");
5259 if (!isBitcode(buf, buf + 16))
5260 return error("Invalid bitcode signature");
5262 if (isBitcodeWrapper(buf, buf + 4)) {
5263 const unsigned char *bitcodeStart = buf;
5264 const unsigned char *bitcodeEnd = buf + 16;
5265 SkipBitcodeWrapperHeader(bitcodeStart, bitcodeEnd, false);
5266 Bytes.dropLeadingBytes(bitcodeStart - buf);
5267 Bytes.setKnownObjectSize(bitcodeEnd - bitcodeStart);
5269 return std::error_code();
5272 std::error_code FunctionIndexBitcodeReader::error(BitcodeError E,
5273 const Twine &Message) {
5274 return ::error(DiagnosticHandler, make_error_code(E), Message);
5277 std::error_code FunctionIndexBitcodeReader::error(const Twine &Message) {
5278 return ::error(DiagnosticHandler,
5279 make_error_code(BitcodeError::CorruptedBitcode), Message);
5282 std::error_code FunctionIndexBitcodeReader::error(BitcodeError E) {
5283 return ::error(DiagnosticHandler, make_error_code(E));
5286 FunctionIndexBitcodeReader::FunctionIndexBitcodeReader(
5287 MemoryBuffer *Buffer, LLVMContext &Context,
5288 DiagnosticHandlerFunction DiagnosticHandler, bool IsLazy,
5289 bool CheckFuncSummaryPresenceOnly)
5290 : DiagnosticHandler(getDiagHandler(DiagnosticHandler, Context)),
5293 CheckFuncSummaryPresenceOnly(CheckFuncSummaryPresenceOnly) {}
5295 FunctionIndexBitcodeReader::FunctionIndexBitcodeReader(
5296 LLVMContext &Context, DiagnosticHandlerFunction DiagnosticHandler,
5297 bool IsLazy, bool CheckFuncSummaryPresenceOnly)
5298 : DiagnosticHandler(getDiagHandler(DiagnosticHandler, Context)),
5301 CheckFuncSummaryPresenceOnly(CheckFuncSummaryPresenceOnly) {}
5303 void FunctionIndexBitcodeReader::freeState() { Buffer = nullptr; }
5305 void FunctionIndexBitcodeReader::releaseBuffer() { Buffer.release(); }
5307 // Specialized value symbol table parser used when reading function index
5308 // blocks where we don't actually create global values.
5309 // At the end of this routine the function index is populated with a map
5310 // from function name to FunctionInfo. The function info contains
5311 // the function block's bitcode offset as well as the offset into the
5312 // function summary section.
5313 std::error_code FunctionIndexBitcodeReader::parseValueSymbolTable() {
5314 if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
5315 return error("Invalid record");
5317 SmallVector<uint64_t, 64> Record;
5319 // Read all the records for this value table.
5320 SmallString<128> ValueName;
5322 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
5324 switch (Entry.Kind) {
5325 case BitstreamEntry::SubBlock: // Handled for us already.
5326 case BitstreamEntry::Error:
5327 return error("Malformed block");
5328 case BitstreamEntry::EndBlock:
5329 return std::error_code();
5330 case BitstreamEntry::Record:
5331 // The interesting case.
5337 switch (Stream.readRecord(Entry.ID, Record)) {
5338 default: // Default behavior: ignore (e.g. VST_CODE_BBENTRY records).
5340 case bitc::VST_CODE_FNENTRY: {
5341 // VST_FNENTRY: [valueid, offset, namechar x N]
5342 if (convertToString(Record, 2, ValueName))
5343 return error("Invalid record");
5344 unsigned ValueID = Record[0];
5345 uint64_t FuncOffset = Record[1];
5346 std::unique_ptr<FunctionInfo> FuncInfo =
5347 llvm::make_unique<FunctionInfo>(FuncOffset);
5348 if (foundFuncSummary() && !IsLazy) {
5349 DenseMap<uint64_t, std::unique_ptr<FunctionSummary>>::iterator SMI =
5350 SummaryMap.find(ValueID);
5351 assert(SMI != SummaryMap.end() && "Summary info not found");
5352 FuncInfo->setFunctionSummary(std::move(SMI->second));
5354 TheIndex->addFunctionInfo(ValueName, std::move(FuncInfo));
5359 case bitc::VST_CODE_COMBINED_FNENTRY: {
5360 // VST_FNENTRY: [offset, namechar x N]
5361 if (convertToString(Record, 1, ValueName))
5362 return error("Invalid record");
5363 uint64_t FuncSummaryOffset = Record[0];
5364 std::unique_ptr<FunctionInfo> FuncInfo =
5365 llvm::make_unique<FunctionInfo>(FuncSummaryOffset);
5366 if (foundFuncSummary() && !IsLazy) {
5367 DenseMap<uint64_t, std::unique_ptr<FunctionSummary>>::iterator SMI =
5368 SummaryMap.find(FuncSummaryOffset);
5369 assert(SMI != SummaryMap.end() && "Summary info not found");
5370 FuncInfo->setFunctionSummary(std::move(SMI->second));
5372 TheIndex->addFunctionInfo(ValueName, std::move(FuncInfo));
5381 // Parse just the blocks needed for function index building out of the module.
5382 // At the end of this routine the function Index is populated with a map
5383 // from function name to FunctionInfo. The function info contains
5384 // either the parsed function summary information (when parsing summaries
5385 // eagerly), or just to the function summary record's offset
5386 // if parsing lazily (IsLazy).
5387 std::error_code FunctionIndexBitcodeReader::parseModule() {
5388 if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
5389 return error("Invalid record");
5391 // Read the function index for this module.
5393 BitstreamEntry Entry = Stream.advance();
5395 switch (Entry.Kind) {
5396 case BitstreamEntry::Error:
5397 return error("Malformed block");
5398 case BitstreamEntry::EndBlock:
5399 return std::error_code();
5401 case BitstreamEntry::SubBlock:
5402 if (CheckFuncSummaryPresenceOnly) {
5403 if (Entry.ID == bitc::FUNCTION_SUMMARY_BLOCK_ID)
5404 SeenFuncSummary = true;
5405 if (Stream.SkipBlock()) return error("Invalid record");
5406 // No need to parse the rest since we found the summary.
5407 return std::error_code();
5410 default: // Skip unknown content.
5411 if (Stream.SkipBlock()) return error("Invalid record");
5413 case bitc::BLOCKINFO_BLOCK_ID:
5414 // Need to parse these to get abbrev ids (e.g. for VST)
5415 if (Stream.ReadBlockInfoBlock()) return error("Malformed block");
5417 case bitc::VALUE_SYMTAB_BLOCK_ID:
5418 if (std::error_code EC = parseValueSymbolTable()) return EC;
5420 case bitc::FUNCTION_SUMMARY_BLOCK_ID:
5421 SeenFuncSummary = true;
5423 // Lazy parsing of summary info, skip it.
5424 if (Stream.SkipBlock()) return error("Invalid record");
5425 } else if (std::error_code EC = parseEntireSummary())
5428 case bitc::MODULE_STRTAB_BLOCK_ID:
5429 if (std::error_code EC = parseModuleStringTable()) return EC;
5434 case BitstreamEntry::Record:
5435 Stream.skipRecord(Entry.ID);
5441 // Eagerly parse the entire function summary block (i.e. for all functions
5442 // in the index). This populates the FunctionSummary objects in
5444 std::error_code FunctionIndexBitcodeReader::parseEntireSummary() {
5445 if (Stream.EnterSubBlock(bitc::FUNCTION_SUMMARY_BLOCK_ID))
5446 return error("Invalid record");
5448 SmallVector<uint64_t, 64> Record;
5451 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
5453 switch (Entry.Kind) {
5454 case BitstreamEntry::SubBlock: // Handled for us already.
5455 case BitstreamEntry::Error:
5456 return error("Malformed block");
5457 case BitstreamEntry::EndBlock:
5458 return std::error_code();
5459 case BitstreamEntry::Record:
5460 // The interesting case.
5464 // Read a record. The record format depends on whether this
5465 // is a per-module index or a combined index file. In the per-module
5466 // case the records contain the associated value's ID for correlation
5467 // with VST entries. In the combined index the correlation is done
5468 // via the bitcode offset of the summary records (which were saved
5469 // in the combined index VST entries). The records also contain
5470 // information used for ThinLTO renaming and importing.
5472 uint64_t CurRecordBit = Stream.GetCurrentBitNo();
5473 switch (Stream.readRecord(Entry.ID, Record)) {
5474 default: // Default behavior: ignore.
5476 // FS_PERMODULE_ENTRY: [valueid, islocal, instcount]
5477 case bitc::FS_CODE_PERMODULE_ENTRY: {
5478 unsigned ValueID = Record[0];
5479 bool IsLocal = Record[1];
5480 unsigned InstCount = Record[2];
5481 std::unique_ptr<FunctionSummary> FS =
5482 llvm::make_unique<FunctionSummary>(InstCount);
5483 FS->setLocalFunction(IsLocal);
5484 // The module path string ref set in the summary must be owned by the
5485 // index's module string table. Since we don't have a module path
5486 // string table section in the per-module index, we create a single
5487 // module path string table entry with an empty (0) ID to take
5490 TheIndex->addModulePath(Buffer->getBufferIdentifier(), 0));
5491 SummaryMap[ValueID] = std::move(FS);
5493 // FS_COMBINED_ENTRY: [modid, instcount]
5494 case bitc::FS_CODE_COMBINED_ENTRY: {
5495 uint64_t ModuleId = Record[0];
5496 unsigned InstCount = Record[1];
5497 std::unique_ptr<FunctionSummary> FS =
5498 llvm::make_unique<FunctionSummary>(InstCount);
5499 FS->setModulePath(ModuleIdMap[ModuleId]);
5500 SummaryMap[CurRecordBit] = std::move(FS);
5504 llvm_unreachable("Exit infinite loop");
5507 // Parse the module string table block into the Index.
5508 // This populates the ModulePathStringTable map in the index.
5509 std::error_code FunctionIndexBitcodeReader::parseModuleStringTable() {
5510 if (Stream.EnterSubBlock(bitc::MODULE_STRTAB_BLOCK_ID))
5511 return error("Invalid record");
5513 SmallVector<uint64_t, 64> Record;
5515 SmallString<128> ModulePath;
5517 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
5519 switch (Entry.Kind) {
5520 case BitstreamEntry::SubBlock: // Handled for us already.
5521 case BitstreamEntry::Error:
5522 return error("Malformed block");
5523 case BitstreamEntry::EndBlock:
5524 return std::error_code();
5525 case BitstreamEntry::Record:
5526 // The interesting case.
5531 switch (Stream.readRecord(Entry.ID, Record)) {
5532 default: // Default behavior: ignore.
5534 case bitc::MST_CODE_ENTRY: {
5535 // MST_ENTRY: [modid, namechar x N]
5536 if (convertToString(Record, 1, ModulePath))
5537 return error("Invalid record");
5538 uint64_t ModuleId = Record[0];
5539 StringRef ModulePathInMap =
5540 TheIndex->addModulePath(ModulePath, ModuleId);
5541 ModuleIdMap[ModuleId] = ModulePathInMap;
5547 llvm_unreachable("Exit infinite loop");
5550 // Parse the function info index from the bitcode streamer into the given index.
5551 std::error_code FunctionIndexBitcodeReader::parseSummaryIndexInto(
5552 std::unique_ptr<DataStreamer> Streamer, FunctionInfoIndex *I) {
5555 if (std::error_code EC = initStream(std::move(Streamer))) return EC;
5557 // Sniff for the signature.
5558 if (!hasValidBitcodeHeader(Stream)) return error("Invalid bitcode signature");
5560 // We expect a number of well-defined blocks, though we don't necessarily
5561 // need to understand them all.
5563 if (Stream.AtEndOfStream()) {
5564 // We didn't really read a proper Module block.
5565 return error("Malformed block");
5568 BitstreamEntry Entry =
5569 Stream.advance(BitstreamCursor::AF_DontAutoprocessAbbrevs);
5571 if (Entry.Kind != BitstreamEntry::SubBlock) return error("Malformed block");
5573 // If we see a MODULE_BLOCK, parse it to find the blocks needed for
5574 // building the function summary index.
5575 if (Entry.ID == bitc::MODULE_BLOCK_ID) return parseModule();
5577 if (Stream.SkipBlock()) return error("Invalid record");
5581 // Parse the function information at the given offset in the buffer into
5582 // the index. Used to support lazy parsing of function summaries from the
5583 // combined index during importing.
5584 // TODO: This function is not yet complete as it won't have a consumer
5585 // until ThinLTO function importing is added.
5586 std::error_code FunctionIndexBitcodeReader::parseFunctionSummary(
5587 std::unique_ptr<DataStreamer> Streamer, FunctionInfoIndex *I,
5588 size_t FunctionSummaryOffset) {
5591 if (std::error_code EC = initStream(std::move(Streamer))) return EC;
5593 // Sniff for the signature.
5594 if (!hasValidBitcodeHeader(Stream)) return error("Invalid bitcode signature");
5596 Stream.JumpToBit(FunctionSummaryOffset);
5598 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
5600 switch (Entry.Kind) {
5602 return error("Malformed block");
5603 case BitstreamEntry::Record:
5604 // The expected case.
5608 // TODO: Read a record. This interface will be completed when ThinLTO
5609 // importing is added so that it can be tested.
5610 SmallVector<uint64_t, 64> Record;
5611 switch (Stream.readRecord(Entry.ID, Record)) {
5612 case bitc::FS_CODE_COMBINED_ENTRY:
5614 return error("Invalid record");
5617 return std::error_code();
5620 std::error_code FunctionIndexBitcodeReader::initStream(
5621 std::unique_ptr<DataStreamer> Streamer) {
5622 if (Streamer) return initLazyStream(std::move(Streamer));
5623 return initStreamFromBuffer();
5626 std::error_code FunctionIndexBitcodeReader::initStreamFromBuffer() {
5627 const unsigned char *BufPtr = (const unsigned char *)Buffer->getBufferStart();
5628 const unsigned char *BufEnd = BufPtr + Buffer->getBufferSize();
5630 if (Buffer->getBufferSize() & 3) return error("Invalid bitcode signature");
5632 // If we have a wrapper header, parse it and ignore the non-bc file contents.
5633 // The magic number is 0x0B17C0DE stored in little endian.
5634 if (isBitcodeWrapper(BufPtr, BufEnd))
5635 if (SkipBitcodeWrapperHeader(BufPtr, BufEnd, true))
5636 return error("Invalid bitcode wrapper header");
5638 StreamFile.reset(new BitstreamReader(BufPtr, BufEnd));
5639 Stream.init(&*StreamFile);
5641 return std::error_code();
5644 std::error_code FunctionIndexBitcodeReader::initLazyStream(
5645 std::unique_ptr<DataStreamer> Streamer) {
5646 // Check and strip off the bitcode wrapper; BitstreamReader expects never to
5649 llvm::make_unique<StreamingMemoryObject>(std::move(Streamer));
5650 StreamingMemoryObject &Bytes = *OwnedBytes;
5651 StreamFile = llvm::make_unique<BitstreamReader>(std::move(OwnedBytes));
5652 Stream.init(&*StreamFile);
5654 unsigned char buf[16];
5655 if (Bytes.readBytes(buf, 16, 0) != 16)
5656 return error("Invalid bitcode signature");
5658 if (!isBitcode(buf, buf + 16)) return error("Invalid bitcode signature");
5660 if (isBitcodeWrapper(buf, buf + 4)) {
5661 const unsigned char *bitcodeStart = buf;
5662 const unsigned char *bitcodeEnd = buf + 16;
5663 SkipBitcodeWrapperHeader(bitcodeStart, bitcodeEnd, false);
5664 Bytes.dropLeadingBytes(bitcodeStart - buf);
5665 Bytes.setKnownObjectSize(bitcodeEnd - bitcodeStart);
5667 return std::error_code();
5671 class BitcodeErrorCategoryType : public std::error_category {
5672 const char *name() const LLVM_NOEXCEPT override {
5673 return "llvm.bitcode";
5675 std::string message(int IE) const override {
5676 BitcodeError E = static_cast<BitcodeError>(IE);
5678 case BitcodeError::InvalidBitcodeSignature:
5679 return "Invalid bitcode signature";
5680 case BitcodeError::CorruptedBitcode:
5681 return "Corrupted bitcode";
5683 llvm_unreachable("Unknown error type!");
5688 static ManagedStatic<BitcodeErrorCategoryType> ErrorCategory;
5690 const std::error_category &llvm::BitcodeErrorCategory() {
5691 return *ErrorCategory;
5694 //===----------------------------------------------------------------------===//
5695 // External interface
5696 //===----------------------------------------------------------------------===//
5698 static ErrorOr<std::unique_ptr<Module>>
5699 getBitcodeModuleImpl(std::unique_ptr<DataStreamer> Streamer, StringRef Name,
5700 BitcodeReader *R, LLVMContext &Context,
5701 bool MaterializeAll, bool ShouldLazyLoadMetadata) {
5702 std::unique_ptr<Module> M = make_unique<Module>(Name, Context);
5703 M->setMaterializer(R);
5705 auto cleanupOnError = [&](std::error_code EC) {
5706 R->releaseBuffer(); // Never take ownership on error.
5710 // Delay parsing Metadata if ShouldLazyLoadMetadata is true.
5711 if (std::error_code EC = R->parseBitcodeInto(std::move(Streamer), M.get(),
5712 ShouldLazyLoadMetadata))
5713 return cleanupOnError(EC);
5715 if (MaterializeAll) {
5716 // Read in the entire module, and destroy the BitcodeReader.
5717 if (std::error_code EC = M->materializeAllPermanently())
5718 return cleanupOnError(EC);
5720 // Resolve forward references from blockaddresses.
5721 if (std::error_code EC = R->materializeForwardReferencedFunctions())
5722 return cleanupOnError(EC);
5724 return std::move(M);
5727 /// \brief Get a lazy one-at-time loading module from bitcode.
5729 /// This isn't always used in a lazy context. In particular, it's also used by
5730 /// \a parseBitcodeFile(). If this is truly lazy, then we need to eagerly pull
5731 /// in forward-referenced functions from block address references.
5733 /// \param[in] MaterializeAll Set to \c true if we should materialize
5735 static ErrorOr<std::unique_ptr<Module>>
5736 getLazyBitcodeModuleImpl(std::unique_ptr<MemoryBuffer> &&Buffer,
5737 LLVMContext &Context, bool MaterializeAll,
5738 DiagnosticHandlerFunction DiagnosticHandler,
5739 bool ShouldLazyLoadMetadata = false) {
5741 new BitcodeReader(Buffer.get(), Context, DiagnosticHandler);
5743 ErrorOr<std::unique_ptr<Module>> Ret =
5744 getBitcodeModuleImpl(nullptr, Buffer->getBufferIdentifier(), R, Context,
5745 MaterializeAll, ShouldLazyLoadMetadata);
5749 Buffer.release(); // The BitcodeReader owns it now.
5753 ErrorOr<std::unique_ptr<Module>> llvm::getLazyBitcodeModule(
5754 std::unique_ptr<MemoryBuffer> &&Buffer, LLVMContext &Context,
5755 DiagnosticHandlerFunction DiagnosticHandler, bool ShouldLazyLoadMetadata) {
5756 return getLazyBitcodeModuleImpl(std::move(Buffer), Context, false,
5757 DiagnosticHandler, ShouldLazyLoadMetadata);
5760 ErrorOr<std::unique_ptr<Module>> llvm::getStreamedBitcodeModule(
5761 StringRef Name, std::unique_ptr<DataStreamer> Streamer,
5762 LLVMContext &Context, DiagnosticHandlerFunction DiagnosticHandler) {
5763 std::unique_ptr<Module> M = make_unique<Module>(Name, Context);
5764 BitcodeReader *R = new BitcodeReader(Context, DiagnosticHandler);
5766 return getBitcodeModuleImpl(std::move(Streamer), Name, R, Context, false,
5770 ErrorOr<std::unique_ptr<Module>>
5771 llvm::parseBitcodeFile(MemoryBufferRef Buffer, LLVMContext &Context,
5772 DiagnosticHandlerFunction DiagnosticHandler) {
5773 std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
5774 return getLazyBitcodeModuleImpl(std::move(Buf), Context, true,
5776 // TODO: Restore the use-lists to the in-memory state when the bitcode was
5777 // written. We must defer until the Module has been fully materialized.
5781 llvm::getBitcodeTargetTriple(MemoryBufferRef Buffer, LLVMContext &Context,
5782 DiagnosticHandlerFunction DiagnosticHandler) {
5783 std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
5784 auto R = llvm::make_unique<BitcodeReader>(Buf.release(), Context,
5786 ErrorOr<std::string> Triple = R->parseTriple();
5787 if (Triple.getError())
5789 return Triple.get();
5792 // Parse the specified bitcode buffer, returning the function info index.
5793 // If IsLazy is false, parse the entire function summary into
5794 // the index. Otherwise skip the function summary section, and only create
5795 // an index object with a map from function name to function summary offset.
5796 // The index is used to perform lazy function summary reading later.
5797 ErrorOr<std::unique_ptr<FunctionInfoIndex>> llvm::getFunctionInfoIndex(
5798 MemoryBufferRef Buffer, LLVMContext &Context,
5799 DiagnosticHandlerFunction DiagnosticHandler, bool IsLazy) {
5800 std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
5801 FunctionIndexBitcodeReader R(Buf.get(), Context, DiagnosticHandler, IsLazy);
5803 std::unique_ptr<FunctionInfoIndex> Index =
5804 llvm::make_unique<FunctionInfoIndex>();
5806 auto cleanupOnError = [&](std::error_code EC) {
5807 R.releaseBuffer(); // Never take ownership on error.
5811 if (std::error_code EC = R.parseSummaryIndexInto(nullptr, Index.get()))
5812 return cleanupOnError(EC);
5814 Buf.release(); // The FunctionIndexBitcodeReader owns it now.
5815 return std::move(Index);
5818 // Check if the given bitcode buffer contains a function summary block.
5819 bool llvm::hasFunctionSummary(MemoryBufferRef Buffer, LLVMContext &Context,
5820 DiagnosticHandlerFunction DiagnosticHandler) {
5821 std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
5822 FunctionIndexBitcodeReader R(Buf.get(), Context, DiagnosticHandler, false,
5825 auto cleanupOnError = [&](std::error_code EC) {
5826 R.releaseBuffer(); // Never take ownership on error.
5830 if (std::error_code EC = R.parseSummaryIndexInto(nullptr, nullptr))
5831 return cleanupOnError(EC);
5833 Buf.release(); // The FunctionIndexBitcodeReader owns it now.
5834 return R.foundFuncSummary();
5837 // This method supports lazy reading of function summary data from the combined
5838 // index during ThinLTO function importing. When reading the combined index
5839 // file, getFunctionInfoIndex is first invoked with IsLazy=true.
5840 // Then this method is called for each function considered for importing,
5841 // to parse the summary information for the given function name into
5843 std::error_code llvm::readFunctionSummary(
5844 MemoryBufferRef Buffer, LLVMContext &Context,
5845 DiagnosticHandlerFunction DiagnosticHandler, StringRef FunctionName,
5846 std::unique_ptr<FunctionInfoIndex> Index) {
5847 std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
5848 FunctionIndexBitcodeReader R(Buf.get(), Context, DiagnosticHandler);
5850 auto cleanupOnError = [&](std::error_code EC) {
5851 R.releaseBuffer(); // Never take ownership on error.
5855 // Lookup the given function name in the FunctionMap, which may
5856 // contain a list of function infos in the case of a COMDAT. Walk through
5857 // and parse each function summary info at the function summary offset
5858 // recorded when parsing the value symbol table.
5859 for (const auto &FI : Index->getFunctionInfoList(FunctionName)) {
5860 size_t FunctionSummaryOffset = FI->bitcodeIndex();
5861 if (std::error_code EC =
5862 R.parseFunctionSummary(nullptr, Index.get(), FunctionSummaryOffset))
5863 return cleanupOnError(EC);
5866 Buf.release(); // The FunctionIndexBitcodeReader owns it now.
5867 return std::error_code();