1 //===- BitcodeReader.cpp - Internal BitcodeReader implementation ----------===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
9 #include "llvm/Bitcode/BitcodeReader.h"
10 #include "MetadataLoader.h"
11 #include "ValueList.h"
12 #include "llvm/ADT/APFloat.h"
13 #include "llvm/ADT/APInt.h"
14 #include "llvm/ADT/ArrayRef.h"
15 #include "llvm/ADT/DenseMap.h"
16 #include "llvm/ADT/Optional.h"
17 #include "llvm/ADT/STLExtras.h"
18 #include "llvm/ADT/SmallString.h"
19 #include "llvm/ADT/SmallVector.h"
20 #include "llvm/ADT/StringRef.h"
21 #include "llvm/ADT/Triple.h"
22 #include "llvm/ADT/Twine.h"
23 #include "llvm/Bitcode/BitstreamReader.h"
24 #include "llvm/Bitcode/LLVMBitCodes.h"
25 #include "llvm/Config/llvm-config.h"
26 #include "llvm/IR/Argument.h"
27 #include "llvm/IR/Attributes.h"
28 #include "llvm/IR/AutoUpgrade.h"
29 #include "llvm/IR/BasicBlock.h"
30 #include "llvm/IR/CallSite.h"
31 #include "llvm/IR/CallingConv.h"
32 #include "llvm/IR/Comdat.h"
33 #include "llvm/IR/Constant.h"
34 #include "llvm/IR/Constants.h"
35 #include "llvm/IR/DataLayout.h"
36 #include "llvm/IR/DebugInfo.h"
37 #include "llvm/IR/DebugInfoMetadata.h"
38 #include "llvm/IR/DebugLoc.h"
39 #include "llvm/IR/DerivedTypes.h"
40 #include "llvm/IR/Function.h"
41 #include "llvm/IR/GVMaterializer.h"
42 #include "llvm/IR/GlobalAlias.h"
43 #include "llvm/IR/GlobalIFunc.h"
44 #include "llvm/IR/GlobalIndirectSymbol.h"
45 #include "llvm/IR/GlobalObject.h"
46 #include "llvm/IR/GlobalValue.h"
47 #include "llvm/IR/GlobalVariable.h"
48 #include "llvm/IR/InlineAsm.h"
49 #include "llvm/IR/InstIterator.h"
50 #include "llvm/IR/InstrTypes.h"
51 #include "llvm/IR/Instruction.h"
52 #include "llvm/IR/Instructions.h"
53 #include "llvm/IR/Intrinsics.h"
54 #include "llvm/IR/LLVMContext.h"
55 #include "llvm/IR/Metadata.h"
56 #include "llvm/IR/Module.h"
57 #include "llvm/IR/ModuleSummaryIndex.h"
58 #include "llvm/IR/Operator.h"
59 #include "llvm/IR/Type.h"
60 #include "llvm/IR/Value.h"
61 #include "llvm/IR/Verifier.h"
62 #include "llvm/Support/AtomicOrdering.h"
63 #include "llvm/Support/Casting.h"
64 #include "llvm/Support/CommandLine.h"
65 #include "llvm/Support/Compiler.h"
66 #include "llvm/Support/Debug.h"
67 #include "llvm/Support/Error.h"
68 #include "llvm/Support/ErrorHandling.h"
69 #include "llvm/Support/ErrorOr.h"
70 #include "llvm/Support/ManagedStatic.h"
71 #include "llvm/Support/MathExtras.h"
72 #include "llvm/Support/MemoryBuffer.h"
73 #include "llvm/Support/raw_ostream.h"
83 #include <system_error>
90 static cl::opt
<bool> PrintSummaryGUIDs(
91 "print-summary-global-ids", cl::init(false), cl::Hidden
,
93 "Print the global id for each value when reading the module summary"));
98 SWITCH_INST_MAGIC
= 0x4B5 // May 2012 => 1205 => Hex
101 } // end anonymous namespace
103 static Error
error(const Twine
&Message
) {
104 return make_error
<StringError
>(
105 Message
, make_error_code(BitcodeError::CorruptedBitcode
));
108 /// Helper to read the header common to all bitcode files.
109 static bool hasValidBitcodeHeader(BitstreamCursor
&Stream
) {
110 // Sniff for the signature.
111 if (!Stream
.canSkipToPos(4) ||
112 Stream
.Read(8) != 'B' ||
113 Stream
.Read(8) != 'C' ||
114 Stream
.Read(4) != 0x0 ||
115 Stream
.Read(4) != 0xC ||
116 Stream
.Read(4) != 0xE ||
117 Stream
.Read(4) != 0xD)
122 static Expected
<BitstreamCursor
> initStream(MemoryBufferRef Buffer
) {
123 const unsigned char *BufPtr
= (const unsigned char *)Buffer
.getBufferStart();
124 const unsigned char *BufEnd
= BufPtr
+ Buffer
.getBufferSize();
126 if (Buffer
.getBufferSize() & 3)
127 return error("Invalid bitcode signature");
129 // If we have a wrapper header, parse it and ignore the non-bc file contents.
130 // The magic number is 0x0B17C0DE stored in little endian.
131 if (isBitcodeWrapper(BufPtr
, BufEnd
))
132 if (SkipBitcodeWrapperHeader(BufPtr
, BufEnd
, true))
133 return error("Invalid bitcode wrapper header");
135 BitstreamCursor
Stream(ArrayRef
<uint8_t>(BufPtr
, BufEnd
));
136 if (!hasValidBitcodeHeader(Stream
))
137 return error("Invalid bitcode signature");
139 return std::move(Stream
);
142 /// Convert a string from a record into an std::string, return true on failure.
143 template <typename StrTy
>
144 static bool convertToString(ArrayRef
<uint64_t> Record
, unsigned Idx
,
146 if (Idx
> Record
.size())
149 for (unsigned i
= Idx
, e
= Record
.size(); i
!= e
; ++i
)
150 Result
+= (char)Record
[i
];
154 // Strip all the TBAA attachment for the module.
155 static void stripTBAA(Module
*M
) {
157 if (F
.isMaterializable())
159 for (auto &I
: instructions(F
))
160 I
.setMetadata(LLVMContext::MD_tbaa
, nullptr);
164 /// Read the "IDENTIFICATION_BLOCK_ID" block, do some basic enforcement on the
165 /// "epoch" encoded in the bitcode, and return the producer name if any.
166 static Expected
<std::string
> readIdentificationBlock(BitstreamCursor
&Stream
) {
167 if (Stream
.EnterSubBlock(bitc::IDENTIFICATION_BLOCK_ID
))
168 return error("Invalid record");
170 // Read all the records.
171 SmallVector
<uint64_t, 64> Record
;
173 std::string ProducerIdentification
;
176 BitstreamEntry Entry
= Stream
.advance();
178 switch (Entry
.Kind
) {
180 case BitstreamEntry::Error
:
181 return error("Malformed block");
182 case BitstreamEntry::EndBlock
:
183 return ProducerIdentification
;
184 case BitstreamEntry::Record
:
185 // The interesting case.
191 unsigned BitCode
= Stream
.readRecord(Entry
.ID
, Record
);
193 default: // Default behavior: reject
194 return error("Invalid value");
195 case bitc::IDENTIFICATION_CODE_STRING
: // IDENTIFICATION: [strchr x N]
196 convertToString(Record
, 0, ProducerIdentification
);
198 case bitc::IDENTIFICATION_CODE_EPOCH
: { // EPOCH: [epoch#]
199 unsigned epoch
= (unsigned)Record
[0];
200 if (epoch
!= bitc::BITCODE_CURRENT_EPOCH
) {
202 Twine("Incompatible epoch: Bitcode '") + Twine(epoch
) +
203 "' vs current: '" + Twine(bitc::BITCODE_CURRENT_EPOCH
) + "'");
210 static Expected
<std::string
> readIdentificationCode(BitstreamCursor
&Stream
) {
211 // We expect a number of well-defined blocks, though we don't necessarily
212 // need to understand them all.
214 if (Stream
.AtEndOfStream())
217 BitstreamEntry Entry
= Stream
.advance();
218 switch (Entry
.Kind
) {
219 case BitstreamEntry::EndBlock
:
220 case BitstreamEntry::Error
:
221 return error("Malformed block");
223 case BitstreamEntry::SubBlock
:
224 if (Entry
.ID
== bitc::IDENTIFICATION_BLOCK_ID
)
225 return readIdentificationBlock(Stream
);
227 // Ignore other sub-blocks.
228 if (Stream
.SkipBlock())
229 return error("Malformed block");
231 case BitstreamEntry::Record
:
232 Stream
.skipRecord(Entry
.ID
);
238 static Expected
<bool> hasObjCCategoryInModule(BitstreamCursor
&Stream
) {
239 if (Stream
.EnterSubBlock(bitc::MODULE_BLOCK_ID
))
240 return error("Invalid record");
242 SmallVector
<uint64_t, 64> Record
;
243 // Read all the records for this module.
246 BitstreamEntry Entry
= Stream
.advanceSkippingSubblocks();
248 switch (Entry
.Kind
) {
249 case BitstreamEntry::SubBlock
: // Handled for us already.
250 case BitstreamEntry::Error
:
251 return error("Malformed block");
252 case BitstreamEntry::EndBlock
:
254 case BitstreamEntry::Record
:
255 // The interesting case.
260 switch (Stream
.readRecord(Entry
.ID
, Record
)) {
262 break; // Default behavior, ignore unknown content.
263 case bitc::MODULE_CODE_SECTIONNAME
: { // SECTIONNAME: [strchr x N]
265 if (convertToString(Record
, 0, S
))
266 return error("Invalid record");
267 // Check for the i386 and other (x86_64, ARM) conventions
268 if (S
.find("__DATA,__objc_catlist") != std::string::npos
||
269 S
.find("__OBJC,__category") != std::string::npos
)
276 llvm_unreachable("Exit infinite loop");
279 static Expected
<bool> hasObjCCategory(BitstreamCursor
&Stream
) {
280 // We expect a number of well-defined blocks, though we don't necessarily
281 // need to understand them all.
283 BitstreamEntry Entry
= Stream
.advance();
285 switch (Entry
.Kind
) {
286 case BitstreamEntry::Error
:
287 return error("Malformed block");
288 case BitstreamEntry::EndBlock
:
291 case BitstreamEntry::SubBlock
:
292 if (Entry
.ID
== bitc::MODULE_BLOCK_ID
)
293 return hasObjCCategoryInModule(Stream
);
295 // Ignore other sub-blocks.
296 if (Stream
.SkipBlock())
297 return error("Malformed block");
300 case BitstreamEntry::Record
:
301 Stream
.skipRecord(Entry
.ID
);
307 static Expected
<std::string
> readModuleTriple(BitstreamCursor
&Stream
) {
308 if (Stream
.EnterSubBlock(bitc::MODULE_BLOCK_ID
))
309 return error("Invalid record");
311 SmallVector
<uint64_t, 64> Record
;
315 // Read all the records for this module.
317 BitstreamEntry Entry
= Stream
.advanceSkippingSubblocks();
319 switch (Entry
.Kind
) {
320 case BitstreamEntry::SubBlock
: // Handled for us already.
321 case BitstreamEntry::Error
:
322 return error("Malformed block");
323 case BitstreamEntry::EndBlock
:
325 case BitstreamEntry::Record
:
326 // The interesting case.
331 switch (Stream
.readRecord(Entry
.ID
, Record
)) {
332 default: break; // Default behavior, ignore unknown content.
333 case bitc::MODULE_CODE_TRIPLE
: { // TRIPLE: [strchr x N]
335 if (convertToString(Record
, 0, S
))
336 return error("Invalid record");
343 llvm_unreachable("Exit infinite loop");
346 static Expected
<std::string
> readTriple(BitstreamCursor
&Stream
) {
347 // We expect a number of well-defined blocks, though we don't necessarily
348 // need to understand them all.
350 BitstreamEntry Entry
= Stream
.advance();
352 switch (Entry
.Kind
) {
353 case BitstreamEntry::Error
:
354 return error("Malformed block");
355 case BitstreamEntry::EndBlock
:
358 case BitstreamEntry::SubBlock
:
359 if (Entry
.ID
== bitc::MODULE_BLOCK_ID
)
360 return readModuleTriple(Stream
);
362 // Ignore other sub-blocks.
363 if (Stream
.SkipBlock())
364 return error("Malformed block");
367 case BitstreamEntry::Record
:
368 Stream
.skipRecord(Entry
.ID
);
376 class BitcodeReaderBase
{
378 BitcodeReaderBase(BitstreamCursor Stream
, StringRef Strtab
)
379 : Stream(std::move(Stream
)), Strtab(Strtab
) {
380 this->Stream
.setBlockInfo(&BlockInfo
);
383 BitstreamBlockInfo BlockInfo
;
384 BitstreamCursor Stream
;
387 /// In version 2 of the bitcode we store names of global values and comdats in
388 /// a string table rather than in the VST.
389 bool UseStrtab
= false;
391 Expected
<unsigned> parseVersionRecord(ArrayRef
<uint64_t> Record
);
393 /// If this module uses a string table, pop the reference to the string table
394 /// and return the referenced string and the rest of the record. Otherwise
395 /// just return the record itself.
396 std::pair
<StringRef
, ArrayRef
<uint64_t>>
397 readNameFromStrtab(ArrayRef
<uint64_t> Record
);
399 bool readBlockInfo();
401 // Contains an arbitrary and optional string identifying the bitcode producer
402 std::string ProducerIdentification
;
404 Error
error(const Twine
&Message
);
407 } // end anonymous namespace
409 Error
BitcodeReaderBase::error(const Twine
&Message
) {
410 std::string FullMsg
= Message
.str();
411 if (!ProducerIdentification
.empty())
412 FullMsg
+= " (Producer: '" + ProducerIdentification
+ "' Reader: 'LLVM " +
413 LLVM_VERSION_STRING
"')";
414 return ::error(FullMsg
);
418 BitcodeReaderBase::parseVersionRecord(ArrayRef
<uint64_t> Record
) {
420 return error("Invalid record");
421 unsigned ModuleVersion
= Record
[0];
422 if (ModuleVersion
> 2)
423 return error("Invalid value");
424 UseStrtab
= ModuleVersion
>= 2;
425 return ModuleVersion
;
428 std::pair
<StringRef
, ArrayRef
<uint64_t>>
429 BitcodeReaderBase::readNameFromStrtab(ArrayRef
<uint64_t> Record
) {
432 // Invalid reference. Let the caller complain about the record being empty.
433 if (Record
[0] + Record
[1] > Strtab
.size())
435 return {StringRef(Strtab
.data() + Record
[0], Record
[1]), Record
.slice(2)};
440 class BitcodeReader
: public BitcodeReaderBase
, public GVMaterializer
{
441 LLVMContext
&Context
;
442 Module
*TheModule
= nullptr;
443 // Next offset to start scanning for lazy parsing of function bodies.
444 uint64_t NextUnreadBit
= 0;
445 // Last function offset found in the VST.
446 uint64_t LastFunctionBlockBit
= 0;
447 bool SeenValueSymbolTable
= false;
448 uint64_t VSTOffset
= 0;
450 std::vector
<std::string
> SectionTable
;
451 std::vector
<std::string
> GCTable
;
453 std::vector
<Type
*> TypeList
;
454 BitcodeReaderValueList ValueList
;
455 Optional
<MetadataLoader
> MDLoader
;
456 std::vector
<Comdat
*> ComdatList
;
457 SmallVector
<Instruction
*, 64> InstructionList
;
459 std::vector
<std::pair
<GlobalVariable
*, unsigned>> GlobalInits
;
460 std::vector
<std::pair
<GlobalIndirectSymbol
*, unsigned>> IndirectSymbolInits
;
461 std::vector
<std::pair
<Function
*, unsigned>> FunctionPrefixes
;
462 std::vector
<std::pair
<Function
*, unsigned>> FunctionPrologues
;
463 std::vector
<std::pair
<Function
*, unsigned>> FunctionPersonalityFns
;
465 /// The set of attributes by index. Index zero in the file is for null, and
466 /// is thus not represented here. As such all indices are off by one.
467 std::vector
<AttributeList
> MAttributes
;
469 /// The set of attribute groups.
470 std::map
<unsigned, AttributeList
> MAttributeGroups
;
472 /// While parsing a function body, this is a list of the basic blocks for the
474 std::vector
<BasicBlock
*> FunctionBBs
;
476 // When reading the module header, this list is populated with functions that
477 // have bodies later in the file.
478 std::vector
<Function
*> FunctionsWithBodies
;
480 // When intrinsic functions are encountered which require upgrading they are
481 // stored here with their replacement function.
482 using UpdatedIntrinsicMap
= DenseMap
<Function
*, Function
*>;
483 UpdatedIntrinsicMap UpgradedIntrinsics
;
484 // Intrinsics which were remangled because of types rename
485 UpdatedIntrinsicMap RemangledIntrinsics
;
487 // Several operations happen after the module header has been read, but
488 // before function bodies are processed. This keeps track of whether
489 // we've done this yet.
490 bool SeenFirstFunctionBody
= false;
492 /// When function bodies are initially scanned, this map contains info about
493 /// where to find deferred function body in the stream.
494 DenseMap
<Function
*, uint64_t> DeferredFunctionInfo
;
496 /// When Metadata block is initially scanned when parsing the module, we may
497 /// choose to defer parsing of the metadata. This vector contains info about
498 /// which Metadata blocks are deferred.
499 std::vector
<uint64_t> DeferredMetadataInfo
;
501 /// These are basic blocks forward-referenced by block addresses. They are
502 /// inserted lazily into functions when they're loaded. The basic block ID is
503 /// its index into the vector.
504 DenseMap
<Function
*, std::vector
<BasicBlock
*>> BasicBlockFwdRefs
;
505 std::deque
<Function
*> BasicBlockFwdRefQueue
;
507 /// Indicates that we are using a new encoding for instruction operands where
508 /// most operands in the current FUNCTION_BLOCK are encoded relative to the
509 /// instruction number, for a more compact encoding. Some instruction
510 /// operands are not relative to the instruction ID: basic block numbers, and
511 /// types. Once the old style function blocks have been phased out, we would
512 /// not need this flag.
513 bool UseRelativeIDs
= false;
515 /// True if all functions will be materialized, negating the need to process
516 /// (e.g.) blockaddress forward references.
517 bool WillMaterializeAllForwardRefs
= false;
519 bool StripDebugInfo
= false;
520 TBAAVerifier TBAAVerifyHelper
;
522 std::vector
<std::string
> BundleTags
;
523 SmallVector
<SyncScope::ID
, 8> SSIDs
;
526 BitcodeReader(BitstreamCursor Stream
, StringRef Strtab
,
527 StringRef ProducerIdentification
, LLVMContext
&Context
);
529 Error
materializeForwardReferencedFunctions();
531 Error
materialize(GlobalValue
*GV
) override
;
532 Error
materializeModule() override
;
533 std::vector
<StructType
*> getIdentifiedStructTypes() const override
;
535 /// Main interface to parsing a bitcode buffer.
536 /// \returns true if an error occurred.
537 Error
parseBitcodeInto(Module
*M
, bool ShouldLazyLoadMetadata
= false,
538 bool IsImporting
= false);
540 static uint64_t decodeSignRotatedValue(uint64_t V
);
542 /// Materialize any deferred Metadata block.
543 Error
materializeMetadata() override
;
545 void setStripDebugInfo() override
;
548 std::vector
<StructType
*> IdentifiedStructTypes
;
549 StructType
*createIdentifiedStructType(LLVMContext
&Context
, StringRef Name
);
550 StructType
*createIdentifiedStructType(LLVMContext
&Context
);
552 Type
*getTypeByID(unsigned ID
);
554 Value
*getFnValueByID(unsigned ID
, Type
*Ty
) {
555 if (Ty
&& Ty
->isMetadataTy())
556 return MetadataAsValue::get(Ty
->getContext(), getFnMetadataByID(ID
));
557 return ValueList
.getValueFwdRef(ID
, Ty
);
560 Metadata
*getFnMetadataByID(unsigned ID
) {
561 return MDLoader
->getMetadataFwdRefOrLoad(ID
);
564 BasicBlock
*getBasicBlock(unsigned ID
) const {
565 if (ID
>= FunctionBBs
.size()) return nullptr; // Invalid ID
566 return FunctionBBs
[ID
];
569 AttributeList
getAttributes(unsigned i
) const {
570 if (i
-1 < MAttributes
.size())
571 return MAttributes
[i
-1];
572 return AttributeList();
575 /// Read a value/type pair out of the specified record from slot 'Slot'.
576 /// Increment Slot past the number of slots used in the record. Return true on
578 bool getValueTypePair(SmallVectorImpl
<uint64_t> &Record
, unsigned &Slot
,
579 unsigned InstNum
, Value
*&ResVal
) {
580 if (Slot
== Record
.size()) return true;
581 unsigned ValNo
= (unsigned)Record
[Slot
++];
582 // Adjust the ValNo, if it was encoded relative to the InstNum.
584 ValNo
= InstNum
- ValNo
;
585 if (ValNo
< InstNum
) {
586 // If this is not a forward reference, just return the value we already
588 ResVal
= getFnValueByID(ValNo
, nullptr);
589 return ResVal
== nullptr;
591 if (Slot
== Record
.size())
594 unsigned TypeNo
= (unsigned)Record
[Slot
++];
595 ResVal
= getFnValueByID(ValNo
, getTypeByID(TypeNo
));
596 return ResVal
== nullptr;
599 /// Read a value out of the specified record from slot 'Slot'. Increment Slot
600 /// past the number of slots used by the value in the record. Return true if
601 /// there is an error.
602 bool popValue(SmallVectorImpl
<uint64_t> &Record
, unsigned &Slot
,
603 unsigned InstNum
, Type
*Ty
, Value
*&ResVal
) {
604 if (getValue(Record
, Slot
, InstNum
, Ty
, ResVal
))
606 // All values currently take a single record slot.
611 /// Like popValue, but does not increment the Slot number.
612 bool getValue(SmallVectorImpl
<uint64_t> &Record
, unsigned Slot
,
613 unsigned InstNum
, Type
*Ty
, Value
*&ResVal
) {
614 ResVal
= getValue(Record
, Slot
, InstNum
, Ty
);
615 return ResVal
== nullptr;
618 /// Version of getValue that returns ResVal directly, or 0 if there is an
620 Value
*getValue(SmallVectorImpl
<uint64_t> &Record
, unsigned Slot
,
621 unsigned InstNum
, Type
*Ty
) {
622 if (Slot
== Record
.size()) return nullptr;
623 unsigned ValNo
= (unsigned)Record
[Slot
];
624 // Adjust the ValNo, if it was encoded relative to the InstNum.
626 ValNo
= InstNum
- ValNo
;
627 return getFnValueByID(ValNo
, Ty
);
630 /// Like getValue, but decodes signed VBRs.
631 Value
*getValueSigned(SmallVectorImpl
<uint64_t> &Record
, unsigned Slot
,
632 unsigned InstNum
, Type
*Ty
) {
633 if (Slot
== Record
.size()) return nullptr;
634 unsigned ValNo
= (unsigned)decodeSignRotatedValue(Record
[Slot
]);
635 // Adjust the ValNo, if it was encoded relative to the InstNum.
637 ValNo
= InstNum
- ValNo
;
638 return getFnValueByID(ValNo
, Ty
);
641 /// Converts alignment exponent (i.e. power of two (or zero)) to the
642 /// corresponding alignment to use. If alignment is too large, returns
643 /// a corresponding error code.
644 Error
parseAlignmentValue(uint64_t Exponent
, unsigned &Alignment
);
645 Error
parseAttrKind(uint64_t Code
, Attribute::AttrKind
*Kind
);
646 Error
parseModule(uint64_t ResumeBit
, bool ShouldLazyLoadMetadata
= false);
648 Error
parseComdatRecord(ArrayRef
<uint64_t> Record
);
649 Error
parseGlobalVarRecord(ArrayRef
<uint64_t> Record
);
650 Error
parseFunctionRecord(ArrayRef
<uint64_t> Record
);
651 Error
parseGlobalIndirectSymbolRecord(unsigned BitCode
,
652 ArrayRef
<uint64_t> Record
);
654 Error
parseAttributeBlock();
655 Error
parseAttributeGroupBlock();
656 Error
parseTypeTable();
657 Error
parseTypeTableBody();
658 Error
parseOperandBundleTags();
659 Error
parseSyncScopeNames();
661 Expected
<Value
*> recordValue(SmallVectorImpl
<uint64_t> &Record
,
662 unsigned NameIndex
, Triple
&TT
);
663 void setDeferredFunctionInfo(unsigned FuncBitcodeOffsetDelta
, Function
*F
,
664 ArrayRef
<uint64_t> Record
);
665 Error
parseValueSymbolTable(uint64_t Offset
= 0);
666 Error
parseGlobalValueSymbolTable();
667 Error
parseConstants();
668 Error
rememberAndSkipFunctionBodies();
669 Error
rememberAndSkipFunctionBody();
670 /// Save the positions of the Metadata blocks and skip parsing the blocks.
671 Error
rememberAndSkipMetadata();
672 Error
typeCheckLoadStoreInst(Type
*ValType
, Type
*PtrType
);
673 Error
parseFunctionBody(Function
*F
);
674 Error
globalCleanup();
675 Error
resolveGlobalAndIndirectSymbolInits();
676 Error
parseUseLists();
677 Error
findFunctionInStream(
679 DenseMap
<Function
*, uint64_t>::iterator DeferredFunctionInfoIterator
);
681 SyncScope::ID
getDecodedSyncScopeID(unsigned Val
);
684 /// Class to manage reading and parsing function summary index bitcode
686 class ModuleSummaryIndexBitcodeReader
: public BitcodeReaderBase
{
687 /// The module index built during parsing.
688 ModuleSummaryIndex
&TheIndex
;
690 /// Indicates whether we have encountered a global value summary section
691 /// yet during parsing.
692 bool SeenGlobalValSummary
= false;
694 /// Indicates whether we have already parsed the VST, used for error checking.
695 bool SeenValueSymbolTable
= false;
697 /// Set to the offset of the VST recorded in the MODULE_CODE_VSTOFFSET record.
698 /// Used to enable on-demand parsing of the VST.
699 uint64_t VSTOffset
= 0;
701 // Map to save ValueId to ValueInfo association that was recorded in the
702 // ValueSymbolTable. It is used after the VST is parsed to convert
703 // call graph edges read from the function summary from referencing
704 // callees by their ValueId to using the ValueInfo instead, which is how
705 // they are recorded in the summary index being built.
706 // We save a GUID which refers to the same global as the ValueInfo, but
707 // ignoring the linkage, i.e. for values other than local linkage they are
709 DenseMap
<unsigned, std::pair
<ValueInfo
, GlobalValue::GUID
>>
710 ValueIdToValueInfoMap
;
712 /// Map populated during module path string table parsing, from the
713 /// module ID to a string reference owned by the index's module
714 /// path string table, used to correlate with combined index
716 DenseMap
<uint64_t, StringRef
> ModuleIdMap
;
718 /// Original source file name recorded in a bitcode record.
719 std::string SourceFileName
;
721 /// The string identifier given to this module by the client, normally the
722 /// path to the bitcode file.
723 StringRef ModulePath
;
725 /// For per-module summary indexes, the unique numerical identifier given to
726 /// this module by the client.
730 ModuleSummaryIndexBitcodeReader(BitstreamCursor Stream
, StringRef Strtab
,
731 ModuleSummaryIndex
&TheIndex
,
732 StringRef ModulePath
, unsigned ModuleId
);
737 void setValueGUID(uint64_t ValueID
, StringRef ValueName
,
738 GlobalValue::LinkageTypes Linkage
,
739 StringRef SourceFileName
);
740 Error
parseValueSymbolTable(
742 DenseMap
<unsigned, GlobalValue::LinkageTypes
> &ValueIdToLinkageMap
);
743 std::vector
<ValueInfo
> makeRefList(ArrayRef
<uint64_t> Record
);
744 std::vector
<FunctionSummary::EdgeTy
> makeCallList(ArrayRef
<uint64_t> Record
,
745 bool IsOldProfileFormat
,
748 Error
parseEntireSummary(unsigned ID
);
749 Error
parseModuleStringTable();
751 std::pair
<ValueInfo
, GlobalValue::GUID
>
752 getValueInfoFromValueId(unsigned ValueId
);
754 void addThisModule();
755 ModuleSummaryIndex::ModuleInfo
*getThisModule();
758 } // end anonymous namespace
760 std::error_code
llvm::errorToErrorCodeAndEmitErrors(LLVMContext
&Ctx
,
764 handleAllErrors(std::move(Err
), [&](ErrorInfoBase
&EIB
) {
765 EC
= EIB
.convertToErrorCode();
766 Ctx
.emitError(EIB
.message());
770 return std::error_code();
773 BitcodeReader::BitcodeReader(BitstreamCursor Stream
, StringRef Strtab
,
774 StringRef ProducerIdentification
,
775 LLVMContext
&Context
)
776 : BitcodeReaderBase(std::move(Stream
), Strtab
), Context(Context
),
778 this->ProducerIdentification
= ProducerIdentification
;
781 Error
BitcodeReader::materializeForwardReferencedFunctions() {
782 if (WillMaterializeAllForwardRefs
)
783 return Error::success();
785 // Prevent recursion.
786 WillMaterializeAllForwardRefs
= true;
788 while (!BasicBlockFwdRefQueue
.empty()) {
789 Function
*F
= BasicBlockFwdRefQueue
.front();
790 BasicBlockFwdRefQueue
.pop_front();
791 assert(F
&& "Expected valid function");
792 if (!BasicBlockFwdRefs
.count(F
))
793 // Already materialized.
796 // Check for a function that isn't materializable to prevent an infinite
797 // loop. When parsing a blockaddress stored in a global variable, there
798 // isn't a trivial way to check if a function will have a body without a
799 // linear search through FunctionsWithBodies, so just check it here.
800 if (!F
->isMaterializable())
801 return error("Never resolved function from blockaddress");
803 // Try to materialize F.
804 if (Error Err
= materialize(F
))
807 assert(BasicBlockFwdRefs
.empty() && "Function missing from queue");
810 WillMaterializeAllForwardRefs
= false;
811 return Error::success();
814 //===----------------------------------------------------------------------===//
815 // Helper functions to implement forward reference resolution, etc.
816 //===----------------------------------------------------------------------===//
818 static bool hasImplicitComdat(size_t Val
) {
822 case 1: // Old WeakAnyLinkage
823 case 4: // Old LinkOnceAnyLinkage
824 case 10: // Old WeakODRLinkage
825 case 11: // Old LinkOnceODRLinkage
830 static GlobalValue::LinkageTypes
getDecodedLinkage(unsigned Val
) {
832 default: // Map unknown/new linkages to external
834 return GlobalValue::ExternalLinkage
;
836 return GlobalValue::AppendingLinkage
;
838 return GlobalValue::InternalLinkage
;
840 return GlobalValue::ExternalLinkage
; // Obsolete DLLImportLinkage
842 return GlobalValue::ExternalLinkage
; // Obsolete DLLExportLinkage
844 return GlobalValue::ExternalWeakLinkage
;
846 return GlobalValue::CommonLinkage
;
848 return GlobalValue::PrivateLinkage
;
850 return GlobalValue::AvailableExternallyLinkage
;
852 return GlobalValue::PrivateLinkage
; // Obsolete LinkerPrivateLinkage
854 return GlobalValue::PrivateLinkage
; // Obsolete LinkerPrivateWeakLinkage
856 return GlobalValue::ExternalLinkage
; // Obsolete LinkOnceODRAutoHideLinkage
857 case 1: // Old value with implicit comdat.
859 return GlobalValue::WeakAnyLinkage
;
860 case 10: // Old value with implicit comdat.
862 return GlobalValue::WeakODRLinkage
;
863 case 4: // Old value with implicit comdat.
865 return GlobalValue::LinkOnceAnyLinkage
;
866 case 11: // Old value with implicit comdat.
868 return GlobalValue::LinkOnceODRLinkage
;
872 static FunctionSummary::FFlags
getDecodedFFlags(uint64_t RawFlags
) {
873 FunctionSummary::FFlags Flags
;
874 Flags
.ReadNone
= RawFlags
& 0x1;
875 Flags
.ReadOnly
= (RawFlags
>> 1) & 0x1;
876 Flags
.NoRecurse
= (RawFlags
>> 2) & 0x1;
877 Flags
.ReturnDoesNotAlias
= (RawFlags
>> 3) & 0x1;
878 Flags
.NoInline
= (RawFlags
>> 4) & 0x1;
882 /// Decode the flags for GlobalValue in the summary.
883 static GlobalValueSummary::GVFlags
getDecodedGVSummaryFlags(uint64_t RawFlags
,
885 // Summary were not emitted before LLVM 3.9, we don't need to upgrade Linkage
886 // like getDecodedLinkage() above. Any future change to the linkage enum and
887 // to getDecodedLinkage() will need to be taken into account here as above.
888 auto Linkage
= GlobalValue::LinkageTypes(RawFlags
& 0xF); // 4 bits
889 RawFlags
= RawFlags
>> 4;
890 bool NotEligibleToImport
= (RawFlags
& 0x1) || Version
< 3;
891 // The Live flag wasn't introduced until version 3. For dead stripping
892 // to work correctly on earlier versions, we must conservatively treat all
894 bool Live
= (RawFlags
& 0x2) || Version
< 3;
895 bool Local
= (RawFlags
& 0x4);
897 return GlobalValueSummary::GVFlags(Linkage
, NotEligibleToImport
, Live
, Local
);
900 // Decode the flags for GlobalVariable in the summary
901 static GlobalVarSummary::GVarFlags
getDecodedGVarFlags(uint64_t RawFlags
) {
902 return GlobalVarSummary::GVarFlags((RawFlags
& 0x1) ? true : false);
905 static GlobalValue::VisibilityTypes
getDecodedVisibility(unsigned Val
) {
907 default: // Map unknown visibilities to default.
908 case 0: return GlobalValue::DefaultVisibility
;
909 case 1: return GlobalValue::HiddenVisibility
;
910 case 2: return GlobalValue::ProtectedVisibility
;
914 static GlobalValue::DLLStorageClassTypes
915 getDecodedDLLStorageClass(unsigned Val
) {
917 default: // Map unknown values to default.
918 case 0: return GlobalValue::DefaultStorageClass
;
919 case 1: return GlobalValue::DLLImportStorageClass
;
920 case 2: return GlobalValue::DLLExportStorageClass
;
924 static bool getDecodedDSOLocal(unsigned Val
) {
926 default: // Map unknown values to preemptable.
927 case 0: return false;
932 static GlobalVariable::ThreadLocalMode
getDecodedThreadLocalMode(unsigned Val
) {
934 case 0: return GlobalVariable::NotThreadLocal
;
935 default: // Map unknown non-zero value to general dynamic.
936 case 1: return GlobalVariable::GeneralDynamicTLSModel
;
937 case 2: return GlobalVariable::LocalDynamicTLSModel
;
938 case 3: return GlobalVariable::InitialExecTLSModel
;
939 case 4: return GlobalVariable::LocalExecTLSModel
;
943 static GlobalVariable::UnnamedAddr
getDecodedUnnamedAddrType(unsigned Val
) {
945 default: // Map unknown to UnnamedAddr::None.
946 case 0: return GlobalVariable::UnnamedAddr::None
;
947 case 1: return GlobalVariable::UnnamedAddr::Global
;
948 case 2: return GlobalVariable::UnnamedAddr::Local
;
952 static int getDecodedCastOpcode(unsigned Val
) {
955 case bitc::CAST_TRUNC
: return Instruction::Trunc
;
956 case bitc::CAST_ZEXT
: return Instruction::ZExt
;
957 case bitc::CAST_SEXT
: return Instruction::SExt
;
958 case bitc::CAST_FPTOUI
: return Instruction::FPToUI
;
959 case bitc::CAST_FPTOSI
: return Instruction::FPToSI
;
960 case bitc::CAST_UITOFP
: return Instruction::UIToFP
;
961 case bitc::CAST_SITOFP
: return Instruction::SIToFP
;
962 case bitc::CAST_FPTRUNC
: return Instruction::FPTrunc
;
963 case bitc::CAST_FPEXT
: return Instruction::FPExt
;
964 case bitc::CAST_PTRTOINT
: return Instruction::PtrToInt
;
965 case bitc::CAST_INTTOPTR
: return Instruction::IntToPtr
;
966 case bitc::CAST_BITCAST
: return Instruction::BitCast
;
967 case bitc::CAST_ADDRSPACECAST
: return Instruction::AddrSpaceCast
;
971 static int getDecodedUnaryOpcode(unsigned Val
, Type
*Ty
) {
972 bool IsFP
= Ty
->isFPOrFPVectorTy();
973 // UnOps are only valid for int/fp or vector of int/fp types
974 if (!IsFP
&& !Ty
->isIntOrIntVectorTy())
981 return IsFP
? Instruction::FNeg
: -1;
985 static int getDecodedBinaryOpcode(unsigned Val
, Type
*Ty
) {
986 bool IsFP
= Ty
->isFPOrFPVectorTy();
987 // BinOps are only valid for int/fp or vector of int/fp types
988 if (!IsFP
&& !Ty
->isIntOrIntVectorTy())
994 case bitc::BINOP_ADD
:
995 return IsFP
? Instruction::FAdd
: Instruction::Add
;
996 case bitc::BINOP_SUB
:
997 return IsFP
? Instruction::FSub
: Instruction::Sub
;
998 case bitc::BINOP_MUL
:
999 return IsFP
? Instruction::FMul
: Instruction::Mul
;
1000 case bitc::BINOP_UDIV
:
1001 return IsFP
? -1 : Instruction::UDiv
;
1002 case bitc::BINOP_SDIV
:
1003 return IsFP
? Instruction::FDiv
: Instruction::SDiv
;
1004 case bitc::BINOP_UREM
:
1005 return IsFP
? -1 : Instruction::URem
;
1006 case bitc::BINOP_SREM
:
1007 return IsFP
? Instruction::FRem
: Instruction::SRem
;
1008 case bitc::BINOP_SHL
:
1009 return IsFP
? -1 : Instruction::Shl
;
1010 case bitc::BINOP_LSHR
:
1011 return IsFP
? -1 : Instruction::LShr
;
1012 case bitc::BINOP_ASHR
:
1013 return IsFP
? -1 : Instruction::AShr
;
1014 case bitc::BINOP_AND
:
1015 return IsFP
? -1 : Instruction::And
;
1016 case bitc::BINOP_OR
:
1017 return IsFP
? -1 : Instruction::Or
;
1018 case bitc::BINOP_XOR
:
1019 return IsFP
? -1 : Instruction::Xor
;
1023 static AtomicRMWInst::BinOp
getDecodedRMWOperation(unsigned Val
) {
1025 default: return AtomicRMWInst::BAD_BINOP
;
1026 case bitc::RMW_XCHG
: return AtomicRMWInst::Xchg
;
1027 case bitc::RMW_ADD
: return AtomicRMWInst::Add
;
1028 case bitc::RMW_SUB
: return AtomicRMWInst::Sub
;
1029 case bitc::RMW_AND
: return AtomicRMWInst::And
;
1030 case bitc::RMW_NAND
: return AtomicRMWInst::Nand
;
1031 case bitc::RMW_OR
: return AtomicRMWInst::Or
;
1032 case bitc::RMW_XOR
: return AtomicRMWInst::Xor
;
1033 case bitc::RMW_MAX
: return AtomicRMWInst::Max
;
1034 case bitc::RMW_MIN
: return AtomicRMWInst::Min
;
1035 case bitc::RMW_UMAX
: return AtomicRMWInst::UMax
;
1036 case bitc::RMW_UMIN
: return AtomicRMWInst::UMin
;
1037 case bitc::RMW_FADD
: return AtomicRMWInst::FAdd
;
1038 case bitc::RMW_FSUB
: return AtomicRMWInst::FSub
;
1042 static AtomicOrdering
getDecodedOrdering(unsigned Val
) {
1044 case bitc::ORDERING_NOTATOMIC
: return AtomicOrdering::NotAtomic
;
1045 case bitc::ORDERING_UNORDERED
: return AtomicOrdering::Unordered
;
1046 case bitc::ORDERING_MONOTONIC
: return AtomicOrdering::Monotonic
;
1047 case bitc::ORDERING_ACQUIRE
: return AtomicOrdering::Acquire
;
1048 case bitc::ORDERING_RELEASE
: return AtomicOrdering::Release
;
1049 case bitc::ORDERING_ACQREL
: return AtomicOrdering::AcquireRelease
;
1050 default: // Map unknown orderings to sequentially-consistent.
1051 case bitc::ORDERING_SEQCST
: return AtomicOrdering::SequentiallyConsistent
;
1055 static Comdat::SelectionKind
getDecodedComdatSelectionKind(unsigned Val
) {
1057 default: // Map unknown selection kinds to any.
1058 case bitc::COMDAT_SELECTION_KIND_ANY
:
1060 case bitc::COMDAT_SELECTION_KIND_EXACT_MATCH
:
1061 return Comdat::ExactMatch
;
1062 case bitc::COMDAT_SELECTION_KIND_LARGEST
:
1063 return Comdat::Largest
;
1064 case bitc::COMDAT_SELECTION_KIND_NO_DUPLICATES
:
1065 return Comdat::NoDuplicates
;
1066 case bitc::COMDAT_SELECTION_KIND_SAME_SIZE
:
1067 return Comdat::SameSize
;
1071 static FastMathFlags
getDecodedFastMathFlags(unsigned Val
) {
1073 if (0 != (Val
& bitc::UnsafeAlgebra
))
1075 if (0 != (Val
& bitc::AllowReassoc
))
1076 FMF
.setAllowReassoc();
1077 if (0 != (Val
& bitc::NoNaNs
))
1079 if (0 != (Val
& bitc::NoInfs
))
1081 if (0 != (Val
& bitc::NoSignedZeros
))
1082 FMF
.setNoSignedZeros();
1083 if (0 != (Val
& bitc::AllowReciprocal
))
1084 FMF
.setAllowReciprocal();
1085 if (0 != (Val
& bitc::AllowContract
))
1086 FMF
.setAllowContract(true);
1087 if (0 != (Val
& bitc::ApproxFunc
))
1088 FMF
.setApproxFunc();
1092 static void upgradeDLLImportExportLinkage(GlobalValue
*GV
, unsigned Val
) {
1094 case 5: GV
->setDLLStorageClass(GlobalValue::DLLImportStorageClass
); break;
1095 case 6: GV
->setDLLStorageClass(GlobalValue::DLLExportStorageClass
); break;
1099 Type
*BitcodeReader::getTypeByID(unsigned ID
) {
1100 // The type table size is always specified correctly.
1101 if (ID
>= TypeList
.size())
1104 if (Type
*Ty
= TypeList
[ID
])
1107 // If we have a forward reference, the only possible case is when it is to a
1108 // named struct. Just create a placeholder for now.
1109 return TypeList
[ID
] = createIdentifiedStructType(Context
);
1112 StructType
*BitcodeReader::createIdentifiedStructType(LLVMContext
&Context
,
1114 auto *Ret
= StructType::create(Context
, Name
);
1115 IdentifiedStructTypes
.push_back(Ret
);
1119 StructType
*BitcodeReader::createIdentifiedStructType(LLVMContext
&Context
) {
1120 auto *Ret
= StructType::create(Context
);
1121 IdentifiedStructTypes
.push_back(Ret
);
1125 //===----------------------------------------------------------------------===//
1126 // Functions for parsing blocks from the bitcode file
1127 //===----------------------------------------------------------------------===//
1129 static uint64_t getRawAttributeMask(Attribute::AttrKind Val
) {
1131 case Attribute::EndAttrKinds
:
1132 llvm_unreachable("Synthetic enumerators which should never get here");
1134 case Attribute::None
: return 0;
1135 case Attribute::ZExt
: return 1 << 0;
1136 case Attribute::SExt
: return 1 << 1;
1137 case Attribute::NoReturn
: return 1 << 2;
1138 case Attribute::InReg
: return 1 << 3;
1139 case Attribute::StructRet
: return 1 << 4;
1140 case Attribute::NoUnwind
: return 1 << 5;
1141 case Attribute::NoAlias
: return 1 << 6;
1142 case Attribute::ByVal
: return 1 << 7;
1143 case Attribute::Nest
: return 1 << 8;
1144 case Attribute::ReadNone
: return 1 << 9;
1145 case Attribute::ReadOnly
: return 1 << 10;
1146 case Attribute::NoInline
: return 1 << 11;
1147 case Attribute::AlwaysInline
: return 1 << 12;
1148 case Attribute::OptimizeForSize
: return 1 << 13;
1149 case Attribute::StackProtect
: return 1 << 14;
1150 case Attribute::StackProtectReq
: return 1 << 15;
1151 case Attribute::Alignment
: return 31 << 16;
1152 case Attribute::NoCapture
: return 1 << 21;
1153 case Attribute::NoRedZone
: return 1 << 22;
1154 case Attribute::NoImplicitFloat
: return 1 << 23;
1155 case Attribute::Naked
: return 1 << 24;
1156 case Attribute::InlineHint
: return 1 << 25;
1157 case Attribute::StackAlignment
: return 7 << 26;
1158 case Attribute::ReturnsTwice
: return 1 << 29;
1159 case Attribute::UWTable
: return 1 << 30;
1160 case Attribute::NonLazyBind
: return 1U << 31;
1161 case Attribute::SanitizeAddress
: return 1ULL << 32;
1162 case Attribute::MinSize
: return 1ULL << 33;
1163 case Attribute::NoDuplicate
: return 1ULL << 34;
1164 case Attribute::StackProtectStrong
: return 1ULL << 35;
1165 case Attribute::SanitizeThread
: return 1ULL << 36;
1166 case Attribute::SanitizeMemory
: return 1ULL << 37;
1167 case Attribute::NoBuiltin
: return 1ULL << 38;
1168 case Attribute::Returned
: return 1ULL << 39;
1169 case Attribute::Cold
: return 1ULL << 40;
1170 case Attribute::Builtin
: return 1ULL << 41;
1171 case Attribute::OptimizeNone
: return 1ULL << 42;
1172 case Attribute::InAlloca
: return 1ULL << 43;
1173 case Attribute::NonNull
: return 1ULL << 44;
1174 case Attribute::JumpTable
: return 1ULL << 45;
1175 case Attribute::Convergent
: return 1ULL << 46;
1176 case Attribute::SafeStack
: return 1ULL << 47;
1177 case Attribute::NoRecurse
: return 1ULL << 48;
1178 case Attribute::InaccessibleMemOnly
: return 1ULL << 49;
1179 case Attribute::InaccessibleMemOrArgMemOnly
: return 1ULL << 50;
1180 case Attribute::SwiftSelf
: return 1ULL << 51;
1181 case Attribute::SwiftError
: return 1ULL << 52;
1182 case Attribute::WriteOnly
: return 1ULL << 53;
1183 case Attribute::Speculatable
: return 1ULL << 54;
1184 case Attribute::StrictFP
: return 1ULL << 55;
1185 case Attribute::SanitizeHWAddress
: return 1ULL << 56;
1186 case Attribute::NoCfCheck
: return 1ULL << 57;
1187 case Attribute::OptForFuzzing
: return 1ULL << 58;
1188 case Attribute::ShadowCallStack
: return 1ULL << 59;
1189 case Attribute::SpeculativeLoadHardening
:
1191 case Attribute::Dereferenceable
:
1192 llvm_unreachable("dereferenceable attribute not supported in raw format");
1194 case Attribute::DereferenceableOrNull
:
1195 llvm_unreachable("dereferenceable_or_null attribute not supported in raw "
1198 case Attribute::ArgMemOnly
:
1199 llvm_unreachable("argmemonly attribute not supported in raw format");
1201 case Attribute::AllocSize
:
1202 llvm_unreachable("allocsize not supported in raw format");
1205 llvm_unreachable("Unsupported attribute type");
1208 static void addRawAttributeValue(AttrBuilder
&B
, uint64_t Val
) {
1211 for (Attribute::AttrKind I
= Attribute::None
; I
!= Attribute::EndAttrKinds
;
1212 I
= Attribute::AttrKind(I
+ 1)) {
1213 if (I
== Attribute::Dereferenceable
||
1214 I
== Attribute::DereferenceableOrNull
||
1215 I
== Attribute::ArgMemOnly
||
1216 I
== Attribute::AllocSize
)
1218 if (uint64_t A
= (Val
& getRawAttributeMask(I
))) {
1219 if (I
== Attribute::Alignment
)
1220 B
.addAlignmentAttr(1ULL << ((A
>> 16) - 1));
1221 else if (I
== Attribute::StackAlignment
)
1222 B
.addStackAlignmentAttr(1ULL << ((A
>> 26)-1));
1229 /// This fills an AttrBuilder object with the LLVM attributes that have
1230 /// been decoded from the given integer. This function must stay in sync with
1231 /// 'encodeLLVMAttributesForBitcode'.
1232 static void decodeLLVMAttributesForBitcode(AttrBuilder
&B
,
1233 uint64_t EncodedAttrs
) {
1234 // FIXME: Remove in 4.0.
1236 // The alignment is stored as a 16-bit raw value from bits 31--16. We shift
1237 // the bits above 31 down by 11 bits.
1238 unsigned Alignment
= (EncodedAttrs
& (0xffffULL
<< 16)) >> 16;
1239 assert((!Alignment
|| isPowerOf2_32(Alignment
)) &&
1240 "Alignment must be a power of two.");
1243 B
.addAlignmentAttr(Alignment
);
1244 addRawAttributeValue(B
, ((EncodedAttrs
& (0xfffffULL
<< 32)) >> 11) |
1245 (EncodedAttrs
& 0xffff));
1248 Error
BitcodeReader::parseAttributeBlock() {
1249 if (Stream
.EnterSubBlock(bitc::PARAMATTR_BLOCK_ID
))
1250 return error("Invalid record");
1252 if (!MAttributes
.empty())
1253 return error("Invalid multiple blocks");
1255 SmallVector
<uint64_t, 64> Record
;
1257 SmallVector
<AttributeList
, 8> Attrs
;
1259 // Read all the records.
1261 BitstreamEntry Entry
= Stream
.advanceSkippingSubblocks();
1263 switch (Entry
.Kind
) {
1264 case BitstreamEntry::SubBlock
: // Handled for us already.
1265 case BitstreamEntry::Error
:
1266 return error("Malformed block");
1267 case BitstreamEntry::EndBlock
:
1268 return Error::success();
1269 case BitstreamEntry::Record
:
1270 // The interesting case.
1276 switch (Stream
.readRecord(Entry
.ID
, Record
)) {
1277 default: // Default behavior: ignore.
1279 case bitc::PARAMATTR_CODE_ENTRY_OLD
: // ENTRY: [paramidx0, attr0, ...]
1280 // FIXME: Remove in 4.0.
1281 if (Record
.size() & 1)
1282 return error("Invalid record");
1284 for (unsigned i
= 0, e
= Record
.size(); i
!= e
; i
+= 2) {
1286 decodeLLVMAttributesForBitcode(B
, Record
[i
+1]);
1287 Attrs
.push_back(AttributeList::get(Context
, Record
[i
], B
));
1290 MAttributes
.push_back(AttributeList::get(Context
, Attrs
));
1293 case bitc::PARAMATTR_CODE_ENTRY
: // ENTRY: [attrgrp0, attrgrp1, ...]
1294 for (unsigned i
= 0, e
= Record
.size(); i
!= e
; ++i
)
1295 Attrs
.push_back(MAttributeGroups
[Record
[i
]]);
1297 MAttributes
.push_back(AttributeList::get(Context
, Attrs
));
1304 // Returns Attribute::None on unrecognized codes.
1305 static Attribute::AttrKind
getAttrFromCode(uint64_t Code
) {
1308 return Attribute::None
;
1309 case bitc::ATTR_KIND_ALIGNMENT
:
1310 return Attribute::Alignment
;
1311 case bitc::ATTR_KIND_ALWAYS_INLINE
:
1312 return Attribute::AlwaysInline
;
1313 case bitc::ATTR_KIND_ARGMEMONLY
:
1314 return Attribute::ArgMemOnly
;
1315 case bitc::ATTR_KIND_BUILTIN
:
1316 return Attribute::Builtin
;
1317 case bitc::ATTR_KIND_BY_VAL
:
1318 return Attribute::ByVal
;
1319 case bitc::ATTR_KIND_IN_ALLOCA
:
1320 return Attribute::InAlloca
;
1321 case bitc::ATTR_KIND_COLD
:
1322 return Attribute::Cold
;
1323 case bitc::ATTR_KIND_CONVERGENT
:
1324 return Attribute::Convergent
;
1325 case bitc::ATTR_KIND_INACCESSIBLEMEM_ONLY
:
1326 return Attribute::InaccessibleMemOnly
;
1327 case bitc::ATTR_KIND_INACCESSIBLEMEM_OR_ARGMEMONLY
:
1328 return Attribute::InaccessibleMemOrArgMemOnly
;
1329 case bitc::ATTR_KIND_INLINE_HINT
:
1330 return Attribute::InlineHint
;
1331 case bitc::ATTR_KIND_IN_REG
:
1332 return Attribute::InReg
;
1333 case bitc::ATTR_KIND_JUMP_TABLE
:
1334 return Attribute::JumpTable
;
1335 case bitc::ATTR_KIND_MIN_SIZE
:
1336 return Attribute::MinSize
;
1337 case bitc::ATTR_KIND_NAKED
:
1338 return Attribute::Naked
;
1339 case bitc::ATTR_KIND_NEST
:
1340 return Attribute::Nest
;
1341 case bitc::ATTR_KIND_NO_ALIAS
:
1342 return Attribute::NoAlias
;
1343 case bitc::ATTR_KIND_NO_BUILTIN
:
1344 return Attribute::NoBuiltin
;
1345 case bitc::ATTR_KIND_NO_CAPTURE
:
1346 return Attribute::NoCapture
;
1347 case bitc::ATTR_KIND_NO_DUPLICATE
:
1348 return Attribute::NoDuplicate
;
1349 case bitc::ATTR_KIND_NO_IMPLICIT_FLOAT
:
1350 return Attribute::NoImplicitFloat
;
1351 case bitc::ATTR_KIND_NO_INLINE
:
1352 return Attribute::NoInline
;
1353 case bitc::ATTR_KIND_NO_RECURSE
:
1354 return Attribute::NoRecurse
;
1355 case bitc::ATTR_KIND_NON_LAZY_BIND
:
1356 return Attribute::NonLazyBind
;
1357 case bitc::ATTR_KIND_NON_NULL
:
1358 return Attribute::NonNull
;
1359 case bitc::ATTR_KIND_DEREFERENCEABLE
:
1360 return Attribute::Dereferenceable
;
1361 case bitc::ATTR_KIND_DEREFERENCEABLE_OR_NULL
:
1362 return Attribute::DereferenceableOrNull
;
1363 case bitc::ATTR_KIND_ALLOC_SIZE
:
1364 return Attribute::AllocSize
;
1365 case bitc::ATTR_KIND_NO_RED_ZONE
:
1366 return Attribute::NoRedZone
;
1367 case bitc::ATTR_KIND_NO_RETURN
:
1368 return Attribute::NoReturn
;
1369 case bitc::ATTR_KIND_NOCF_CHECK
:
1370 return Attribute::NoCfCheck
;
1371 case bitc::ATTR_KIND_NO_UNWIND
:
1372 return Attribute::NoUnwind
;
1373 case bitc::ATTR_KIND_OPT_FOR_FUZZING
:
1374 return Attribute::OptForFuzzing
;
1375 case bitc::ATTR_KIND_OPTIMIZE_FOR_SIZE
:
1376 return Attribute::OptimizeForSize
;
1377 case bitc::ATTR_KIND_OPTIMIZE_NONE
:
1378 return Attribute::OptimizeNone
;
1379 case bitc::ATTR_KIND_READ_NONE
:
1380 return Attribute::ReadNone
;
1381 case bitc::ATTR_KIND_READ_ONLY
:
1382 return Attribute::ReadOnly
;
1383 case bitc::ATTR_KIND_RETURNED
:
1384 return Attribute::Returned
;
1385 case bitc::ATTR_KIND_RETURNS_TWICE
:
1386 return Attribute::ReturnsTwice
;
1387 case bitc::ATTR_KIND_S_EXT
:
1388 return Attribute::SExt
;
1389 case bitc::ATTR_KIND_SPECULATABLE
:
1390 return Attribute::Speculatable
;
1391 case bitc::ATTR_KIND_STACK_ALIGNMENT
:
1392 return Attribute::StackAlignment
;
1393 case bitc::ATTR_KIND_STACK_PROTECT
:
1394 return Attribute::StackProtect
;
1395 case bitc::ATTR_KIND_STACK_PROTECT_REQ
:
1396 return Attribute::StackProtectReq
;
1397 case bitc::ATTR_KIND_STACK_PROTECT_STRONG
:
1398 return Attribute::StackProtectStrong
;
1399 case bitc::ATTR_KIND_SAFESTACK
:
1400 return Attribute::SafeStack
;
1401 case bitc::ATTR_KIND_SHADOWCALLSTACK
:
1402 return Attribute::ShadowCallStack
;
1403 case bitc::ATTR_KIND_STRICT_FP
:
1404 return Attribute::StrictFP
;
1405 case bitc::ATTR_KIND_STRUCT_RET
:
1406 return Attribute::StructRet
;
1407 case bitc::ATTR_KIND_SANITIZE_ADDRESS
:
1408 return Attribute::SanitizeAddress
;
1409 case bitc::ATTR_KIND_SANITIZE_HWADDRESS
:
1410 return Attribute::SanitizeHWAddress
;
1411 case bitc::ATTR_KIND_SANITIZE_THREAD
:
1412 return Attribute::SanitizeThread
;
1413 case bitc::ATTR_KIND_SANITIZE_MEMORY
:
1414 return Attribute::SanitizeMemory
;
1415 case bitc::ATTR_KIND_SPECULATIVE_LOAD_HARDENING
:
1416 return Attribute::SpeculativeLoadHardening
;
1417 case bitc::ATTR_KIND_SWIFT_ERROR
:
1418 return Attribute::SwiftError
;
1419 case bitc::ATTR_KIND_SWIFT_SELF
:
1420 return Attribute::SwiftSelf
;
1421 case bitc::ATTR_KIND_UW_TABLE
:
1422 return Attribute::UWTable
;
1423 case bitc::ATTR_KIND_WRITEONLY
:
1424 return Attribute::WriteOnly
;
1425 case bitc::ATTR_KIND_Z_EXT
:
1426 return Attribute::ZExt
;
1430 Error
BitcodeReader::parseAlignmentValue(uint64_t Exponent
,
1431 unsigned &Alignment
) {
1432 // Note: Alignment in bitcode files is incremented by 1, so that zero
1433 // can be used for default alignment.
1434 if (Exponent
> Value::MaxAlignmentExponent
+ 1)
1435 return error("Invalid alignment value");
1436 Alignment
= (1 << static_cast<unsigned>(Exponent
)) >> 1;
1437 return Error::success();
1440 Error
BitcodeReader::parseAttrKind(uint64_t Code
, Attribute::AttrKind
*Kind
) {
1441 *Kind
= getAttrFromCode(Code
);
1442 if (*Kind
== Attribute::None
)
1443 return error("Unknown attribute kind (" + Twine(Code
) + ")");
1444 return Error::success();
1447 Error
BitcodeReader::parseAttributeGroupBlock() {
1448 if (Stream
.EnterSubBlock(bitc::PARAMATTR_GROUP_BLOCK_ID
))
1449 return error("Invalid record");
1451 if (!MAttributeGroups
.empty())
1452 return error("Invalid multiple blocks");
1454 SmallVector
<uint64_t, 64> Record
;
1456 // Read all the records.
1458 BitstreamEntry Entry
= Stream
.advanceSkippingSubblocks();
1460 switch (Entry
.Kind
) {
1461 case BitstreamEntry::SubBlock
: // Handled for us already.
1462 case BitstreamEntry::Error
:
1463 return error("Malformed block");
1464 case BitstreamEntry::EndBlock
:
1465 return Error::success();
1466 case BitstreamEntry::Record
:
1467 // The interesting case.
1473 switch (Stream
.readRecord(Entry
.ID
, Record
)) {
1474 default: // Default behavior: ignore.
1476 case bitc::PARAMATTR_GRP_CODE_ENTRY
: { // ENTRY: [grpid, idx, a0, a1, ...]
1477 if (Record
.size() < 3)
1478 return error("Invalid record");
1480 uint64_t GrpID
= Record
[0];
1481 uint64_t Idx
= Record
[1]; // Index of the object this attribute refers to.
1484 for (unsigned i
= 2, e
= Record
.size(); i
!= e
; ++i
) {
1485 if (Record
[i
] == 0) { // Enum attribute
1486 Attribute::AttrKind Kind
;
1487 if (Error Err
= parseAttrKind(Record
[++i
], &Kind
))
1490 B
.addAttribute(Kind
);
1491 } else if (Record
[i
] == 1) { // Integer attribute
1492 Attribute::AttrKind Kind
;
1493 if (Error Err
= parseAttrKind(Record
[++i
], &Kind
))
1495 if (Kind
== Attribute::Alignment
)
1496 B
.addAlignmentAttr(Record
[++i
]);
1497 else if (Kind
== Attribute::StackAlignment
)
1498 B
.addStackAlignmentAttr(Record
[++i
]);
1499 else if (Kind
== Attribute::Dereferenceable
)
1500 B
.addDereferenceableAttr(Record
[++i
]);
1501 else if (Kind
== Attribute::DereferenceableOrNull
)
1502 B
.addDereferenceableOrNullAttr(Record
[++i
]);
1503 else if (Kind
== Attribute::AllocSize
)
1504 B
.addAllocSizeAttrFromRawRepr(Record
[++i
]);
1505 } else { // String attribute
1506 assert((Record
[i
] == 3 || Record
[i
] == 4) &&
1507 "Invalid attribute group entry");
1508 bool HasValue
= (Record
[i
++] == 4);
1509 SmallString
<64> KindStr
;
1510 SmallString
<64> ValStr
;
1512 while (Record
[i
] != 0 && i
!= e
)
1513 KindStr
+= Record
[i
++];
1514 assert(Record
[i
] == 0 && "Kind string not null terminated");
1517 // Has a value associated with it.
1518 ++i
; // Skip the '0' that terminates the "kind" string.
1519 while (Record
[i
] != 0 && i
!= e
)
1520 ValStr
+= Record
[i
++];
1521 assert(Record
[i
] == 0 && "Value string not null terminated");
1524 B
.addAttribute(KindStr
.str(), ValStr
.str());
1528 MAttributeGroups
[GrpID
] = AttributeList::get(Context
, Idx
, B
);
1535 Error
BitcodeReader::parseTypeTable() {
1536 if (Stream
.EnterSubBlock(bitc::TYPE_BLOCK_ID_NEW
))
1537 return error("Invalid record");
1539 return parseTypeTableBody();
1542 Error
BitcodeReader::parseTypeTableBody() {
1543 if (!TypeList
.empty())
1544 return error("Invalid multiple blocks");
1546 SmallVector
<uint64_t, 64> Record
;
1547 unsigned NumRecords
= 0;
1549 SmallString
<64> TypeName
;
1551 // Read all the records for this type table.
1553 BitstreamEntry Entry
= Stream
.advanceSkippingSubblocks();
1555 switch (Entry
.Kind
) {
1556 case BitstreamEntry::SubBlock
: // Handled for us already.
1557 case BitstreamEntry::Error
:
1558 return error("Malformed block");
1559 case BitstreamEntry::EndBlock
:
1560 if (NumRecords
!= TypeList
.size())
1561 return error("Malformed block");
1562 return Error::success();
1563 case BitstreamEntry::Record
:
1564 // The interesting case.
1570 Type
*ResultTy
= nullptr;
1571 switch (Stream
.readRecord(Entry
.ID
, Record
)) {
1573 return error("Invalid value");
1574 case bitc::TYPE_CODE_NUMENTRY
: // TYPE_CODE_NUMENTRY: [numentries]
1575 // TYPE_CODE_NUMENTRY contains a count of the number of types in the
1576 // type list. This allows us to reserve space.
1577 if (Record
.size() < 1)
1578 return error("Invalid record");
1579 TypeList
.resize(Record
[0]);
1581 case bitc::TYPE_CODE_VOID
: // VOID
1582 ResultTy
= Type::getVoidTy(Context
);
1584 case bitc::TYPE_CODE_HALF
: // HALF
1585 ResultTy
= Type::getHalfTy(Context
);
1587 case bitc::TYPE_CODE_FLOAT
: // FLOAT
1588 ResultTy
= Type::getFloatTy(Context
);
1590 case bitc::TYPE_CODE_DOUBLE
: // DOUBLE
1591 ResultTy
= Type::getDoubleTy(Context
);
1593 case bitc::TYPE_CODE_X86_FP80
: // X86_FP80
1594 ResultTy
= Type::getX86_FP80Ty(Context
);
1596 case bitc::TYPE_CODE_FP128
: // FP128
1597 ResultTy
= Type::getFP128Ty(Context
);
1599 case bitc::TYPE_CODE_PPC_FP128
: // PPC_FP128
1600 ResultTy
= Type::getPPC_FP128Ty(Context
);
1602 case bitc::TYPE_CODE_LABEL
: // LABEL
1603 ResultTy
= Type::getLabelTy(Context
);
1605 case bitc::TYPE_CODE_METADATA
: // METADATA
1606 ResultTy
= Type::getMetadataTy(Context
);
1608 case bitc::TYPE_CODE_X86_MMX
: // X86_MMX
1609 ResultTy
= Type::getX86_MMXTy(Context
);
1611 case bitc::TYPE_CODE_TOKEN
: // TOKEN
1612 ResultTy
= Type::getTokenTy(Context
);
1614 case bitc::TYPE_CODE_INTEGER
: { // INTEGER: [width]
1615 if (Record
.size() < 1)
1616 return error("Invalid record");
1618 uint64_t NumBits
= Record
[0];
1619 if (NumBits
< IntegerType::MIN_INT_BITS
||
1620 NumBits
> IntegerType::MAX_INT_BITS
)
1621 return error("Bitwidth for integer type out of range");
1622 ResultTy
= IntegerType::get(Context
, NumBits
);
1625 case bitc::TYPE_CODE_POINTER
: { // POINTER: [pointee type] or
1626 // [pointee type, address space]
1627 if (Record
.size() < 1)
1628 return error("Invalid record");
1629 unsigned AddressSpace
= 0;
1630 if (Record
.size() == 2)
1631 AddressSpace
= Record
[1];
1632 ResultTy
= getTypeByID(Record
[0]);
1634 !PointerType::isValidElementType(ResultTy
))
1635 return error("Invalid type");
1636 ResultTy
= PointerType::get(ResultTy
, AddressSpace
);
1639 case bitc::TYPE_CODE_FUNCTION_OLD
: {
1640 // FIXME: attrid is dead, remove it in LLVM 4.0
1641 // FUNCTION: [vararg, attrid, retty, paramty x N]
1642 if (Record
.size() < 3)
1643 return error("Invalid record");
1644 SmallVector
<Type
*, 8> ArgTys
;
1645 for (unsigned i
= 3, e
= Record
.size(); i
!= e
; ++i
) {
1646 if (Type
*T
= getTypeByID(Record
[i
]))
1647 ArgTys
.push_back(T
);
1652 ResultTy
= getTypeByID(Record
[2]);
1653 if (!ResultTy
|| ArgTys
.size() < Record
.size()-3)
1654 return error("Invalid type");
1656 ResultTy
= FunctionType::get(ResultTy
, ArgTys
, Record
[0]);
1659 case bitc::TYPE_CODE_FUNCTION
: {
1660 // FUNCTION: [vararg, retty, paramty x N]
1661 if (Record
.size() < 2)
1662 return error("Invalid record");
1663 SmallVector
<Type
*, 8> ArgTys
;
1664 for (unsigned i
= 2, e
= Record
.size(); i
!= e
; ++i
) {
1665 if (Type
*T
= getTypeByID(Record
[i
])) {
1666 if (!FunctionType::isValidArgumentType(T
))
1667 return error("Invalid function argument type");
1668 ArgTys
.push_back(T
);
1674 ResultTy
= getTypeByID(Record
[1]);
1675 if (!ResultTy
|| ArgTys
.size() < Record
.size()-2)
1676 return error("Invalid type");
1678 ResultTy
= FunctionType::get(ResultTy
, ArgTys
, Record
[0]);
1681 case bitc::TYPE_CODE_STRUCT_ANON
: { // STRUCT: [ispacked, eltty x N]
1682 if (Record
.size() < 1)
1683 return error("Invalid record");
1684 SmallVector
<Type
*, 8> EltTys
;
1685 for (unsigned i
= 1, e
= Record
.size(); i
!= e
; ++i
) {
1686 if (Type
*T
= getTypeByID(Record
[i
]))
1687 EltTys
.push_back(T
);
1691 if (EltTys
.size() != Record
.size()-1)
1692 return error("Invalid type");
1693 ResultTy
= StructType::get(Context
, EltTys
, Record
[0]);
1696 case bitc::TYPE_CODE_STRUCT_NAME
: // STRUCT_NAME: [strchr x N]
1697 if (convertToString(Record
, 0, TypeName
))
1698 return error("Invalid record");
1701 case bitc::TYPE_CODE_STRUCT_NAMED
: { // STRUCT: [ispacked, eltty x N]
1702 if (Record
.size() < 1)
1703 return error("Invalid record");
1705 if (NumRecords
>= TypeList
.size())
1706 return error("Invalid TYPE table");
1708 // Check to see if this was forward referenced, if so fill in the temp.
1709 StructType
*Res
= cast_or_null
<StructType
>(TypeList
[NumRecords
]);
1711 Res
->setName(TypeName
);
1712 TypeList
[NumRecords
] = nullptr;
1713 } else // Otherwise, create a new struct.
1714 Res
= createIdentifiedStructType(Context
, TypeName
);
1717 SmallVector
<Type
*, 8> EltTys
;
1718 for (unsigned i
= 1, e
= Record
.size(); i
!= e
; ++i
) {
1719 if (Type
*T
= getTypeByID(Record
[i
]))
1720 EltTys
.push_back(T
);
1724 if (EltTys
.size() != Record
.size()-1)
1725 return error("Invalid record");
1726 Res
->setBody(EltTys
, Record
[0]);
1730 case bitc::TYPE_CODE_OPAQUE
: { // OPAQUE: []
1731 if (Record
.size() != 1)
1732 return error("Invalid record");
1734 if (NumRecords
>= TypeList
.size())
1735 return error("Invalid TYPE table");
1737 // Check to see if this was forward referenced, if so fill in the temp.
1738 StructType
*Res
= cast_or_null
<StructType
>(TypeList
[NumRecords
]);
1740 Res
->setName(TypeName
);
1741 TypeList
[NumRecords
] = nullptr;
1742 } else // Otherwise, create a new struct with no body.
1743 Res
= createIdentifiedStructType(Context
, TypeName
);
1748 case bitc::TYPE_CODE_ARRAY
: // ARRAY: [numelts, eltty]
1749 if (Record
.size() < 2)
1750 return error("Invalid record");
1751 ResultTy
= getTypeByID(Record
[1]);
1752 if (!ResultTy
|| !ArrayType::isValidElementType(ResultTy
))
1753 return error("Invalid type");
1754 ResultTy
= ArrayType::get(ResultTy
, Record
[0]);
1756 case bitc::TYPE_CODE_VECTOR
: // VECTOR: [numelts, eltty]
1757 if (Record
.size() < 2)
1758 return error("Invalid record");
1760 return error("Invalid vector length");
1761 ResultTy
= getTypeByID(Record
[1]);
1762 if (!ResultTy
|| !StructType::isValidElementType(ResultTy
))
1763 return error("Invalid type");
1764 ResultTy
= VectorType::get(ResultTy
, Record
[0]);
1768 if (NumRecords
>= TypeList
.size())
1769 return error("Invalid TYPE table");
1770 if (TypeList
[NumRecords
])
1772 "Invalid TYPE table: Only named structs can be forward referenced");
1773 assert(ResultTy
&& "Didn't read a type?");
1774 TypeList
[NumRecords
++] = ResultTy
;
1778 Error
BitcodeReader::parseOperandBundleTags() {
1779 if (Stream
.EnterSubBlock(bitc::OPERAND_BUNDLE_TAGS_BLOCK_ID
))
1780 return error("Invalid record");
1782 if (!BundleTags
.empty())
1783 return error("Invalid multiple blocks");
1785 SmallVector
<uint64_t, 64> Record
;
1788 BitstreamEntry Entry
= Stream
.advanceSkippingSubblocks();
1790 switch (Entry
.Kind
) {
1791 case BitstreamEntry::SubBlock
: // Handled for us already.
1792 case BitstreamEntry::Error
:
1793 return error("Malformed block");
1794 case BitstreamEntry::EndBlock
:
1795 return Error::success();
1796 case BitstreamEntry::Record
:
1797 // The interesting case.
1801 // Tags are implicitly mapped to integers by their order.
1803 if (Stream
.readRecord(Entry
.ID
, Record
) != bitc::OPERAND_BUNDLE_TAG
)
1804 return error("Invalid record");
1806 // OPERAND_BUNDLE_TAG: [strchr x N]
1807 BundleTags
.emplace_back();
1808 if (convertToString(Record
, 0, BundleTags
.back()))
1809 return error("Invalid record");
1814 Error
BitcodeReader::parseSyncScopeNames() {
1815 if (Stream
.EnterSubBlock(bitc::SYNC_SCOPE_NAMES_BLOCK_ID
))
1816 return error("Invalid record");
1819 return error("Invalid multiple synchronization scope names blocks");
1821 SmallVector
<uint64_t, 64> Record
;
1823 BitstreamEntry Entry
= Stream
.advanceSkippingSubblocks();
1824 switch (Entry
.Kind
) {
1825 case BitstreamEntry::SubBlock
: // Handled for us already.
1826 case BitstreamEntry::Error
:
1827 return error("Malformed block");
1828 case BitstreamEntry::EndBlock
:
1830 return error("Invalid empty synchronization scope names block");
1831 return Error::success();
1832 case BitstreamEntry::Record
:
1833 // The interesting case.
1837 // Synchronization scope names are implicitly mapped to synchronization
1838 // scope IDs by their order.
1840 if (Stream
.readRecord(Entry
.ID
, Record
) != bitc::SYNC_SCOPE_NAME
)
1841 return error("Invalid record");
1843 SmallString
<16> SSN
;
1844 if (convertToString(Record
, 0, SSN
))
1845 return error("Invalid record");
1847 SSIDs
.push_back(Context
.getOrInsertSyncScopeID(SSN
));
1852 /// Associate a value with its name from the given index in the provided record.
1853 Expected
<Value
*> BitcodeReader::recordValue(SmallVectorImpl
<uint64_t> &Record
,
1854 unsigned NameIndex
, Triple
&TT
) {
1855 SmallString
<128> ValueName
;
1856 if (convertToString(Record
, NameIndex
, ValueName
))
1857 return error("Invalid record");
1858 unsigned ValueID
= Record
[0];
1859 if (ValueID
>= ValueList
.size() || !ValueList
[ValueID
])
1860 return error("Invalid record");
1861 Value
*V
= ValueList
[ValueID
];
1863 StringRef
NameStr(ValueName
.data(), ValueName
.size());
1864 if (NameStr
.find_first_of(0) != StringRef::npos
)
1865 return error("Invalid value name");
1866 V
->setName(NameStr
);
1867 auto *GO
= dyn_cast
<GlobalObject
>(V
);
1869 if (GO
->getComdat() == reinterpret_cast<Comdat
*>(1)) {
1870 if (TT
.supportsCOMDAT())
1871 GO
->setComdat(TheModule
->getOrInsertComdat(V
->getName()));
1873 GO
->setComdat(nullptr);
1879 /// Helper to note and return the current location, and jump to the given
1881 static uint64_t jumpToValueSymbolTable(uint64_t Offset
,
1882 BitstreamCursor
&Stream
) {
1883 // Save the current parsing location so we can jump back at the end
1885 uint64_t CurrentBit
= Stream
.GetCurrentBitNo();
1886 Stream
.JumpToBit(Offset
* 32);
1888 // Do some checking if we are in debug mode.
1889 BitstreamEntry Entry
= Stream
.advance();
1890 assert(Entry
.Kind
== BitstreamEntry::SubBlock
);
1891 assert(Entry
.ID
== bitc::VALUE_SYMTAB_BLOCK_ID
);
1893 // In NDEBUG mode ignore the output so we don't get an unused variable
1900 void BitcodeReader::setDeferredFunctionInfo(unsigned FuncBitcodeOffsetDelta
,
1902 ArrayRef
<uint64_t> Record
) {
1903 // Note that we subtract 1 here because the offset is relative to one word
1904 // before the start of the identification or module block, which was
1905 // historically always the start of the regular bitcode header.
1906 uint64_t FuncWordOffset
= Record
[1] - 1;
1907 uint64_t FuncBitOffset
= FuncWordOffset
* 32;
1908 DeferredFunctionInfo
[F
] = FuncBitOffset
+ FuncBitcodeOffsetDelta
;
1909 // Set the LastFunctionBlockBit to point to the last function block.
1910 // Later when parsing is resumed after function materialization,
1911 // we can simply skip that last function block.
1912 if (FuncBitOffset
> LastFunctionBlockBit
)
1913 LastFunctionBlockBit
= FuncBitOffset
;
1916 /// Read a new-style GlobalValue symbol table.
1917 Error
BitcodeReader::parseGlobalValueSymbolTable() {
1918 unsigned FuncBitcodeOffsetDelta
=
1919 Stream
.getAbbrevIDWidth() + bitc::BlockIDWidth
;
1921 if (Stream
.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID
))
1922 return error("Invalid record");
1924 SmallVector
<uint64_t, 64> Record
;
1926 BitstreamEntry Entry
= Stream
.advanceSkippingSubblocks();
1928 switch (Entry
.Kind
) {
1929 case BitstreamEntry::SubBlock
:
1930 case BitstreamEntry::Error
:
1931 return error("Malformed block");
1932 case BitstreamEntry::EndBlock
:
1933 return Error::success();
1934 case BitstreamEntry::Record
:
1939 switch (Stream
.readRecord(Entry
.ID
, Record
)) {
1940 case bitc::VST_CODE_FNENTRY
: // [valueid, offset]
1941 setDeferredFunctionInfo(FuncBitcodeOffsetDelta
,
1942 cast
<Function
>(ValueList
[Record
[0]]), Record
);
1948 /// Parse the value symbol table at either the current parsing location or
1949 /// at the given bit offset if provided.
1950 Error
BitcodeReader::parseValueSymbolTable(uint64_t Offset
) {
1951 uint64_t CurrentBit
;
1952 // Pass in the Offset to distinguish between calling for the module-level
1953 // VST (where we want to jump to the VST offset) and the function-level
1954 // VST (where we don't).
1956 CurrentBit
= jumpToValueSymbolTable(Offset
, Stream
);
1957 // If this module uses a string table, read this as a module-level VST.
1959 if (Error Err
= parseGlobalValueSymbolTable())
1961 Stream
.JumpToBit(CurrentBit
);
1962 return Error::success();
1964 // Otherwise, the VST will be in a similar format to a function-level VST,
1965 // and will contain symbol names.
1968 // Compute the delta between the bitcode indices in the VST (the word offset
1969 // to the word-aligned ENTER_SUBBLOCK for the function block, and that
1970 // expected by the lazy reader. The reader's EnterSubBlock expects to have
1971 // already read the ENTER_SUBBLOCK code (size getAbbrevIDWidth) and BlockID
1972 // (size BlockIDWidth). Note that we access the stream's AbbrevID width here
1973 // just before entering the VST subblock because: 1) the EnterSubBlock
1974 // changes the AbbrevID width; 2) the VST block is nested within the same
1975 // outer MODULE_BLOCK as the FUNCTION_BLOCKs and therefore have the same
1976 // AbbrevID width before calling EnterSubBlock; and 3) when we want to
1977 // jump to the FUNCTION_BLOCK using this offset later, we don't want
1978 // to rely on the stream's AbbrevID width being that of the MODULE_BLOCK.
1979 unsigned FuncBitcodeOffsetDelta
=
1980 Stream
.getAbbrevIDWidth() + bitc::BlockIDWidth
;
1982 if (Stream
.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID
))
1983 return error("Invalid record");
1985 SmallVector
<uint64_t, 64> Record
;
1987 Triple
TT(TheModule
->getTargetTriple());
1989 // Read all the records for this value table.
1990 SmallString
<128> ValueName
;
1993 BitstreamEntry Entry
= Stream
.advanceSkippingSubblocks();
1995 switch (Entry
.Kind
) {
1996 case BitstreamEntry::SubBlock
: // Handled for us already.
1997 case BitstreamEntry::Error
:
1998 return error("Malformed block");
1999 case BitstreamEntry::EndBlock
:
2001 Stream
.JumpToBit(CurrentBit
);
2002 return Error::success();
2003 case BitstreamEntry::Record
:
2004 // The interesting case.
2010 switch (Stream
.readRecord(Entry
.ID
, Record
)) {
2011 default: // Default behavior: unknown type.
2013 case bitc::VST_CODE_ENTRY
: { // VST_CODE_ENTRY: [valueid, namechar x N]
2014 Expected
<Value
*> ValOrErr
= recordValue(Record
, 1, TT
);
2015 if (Error Err
= ValOrErr
.takeError())
2020 case bitc::VST_CODE_FNENTRY
: {
2021 // VST_CODE_FNENTRY: [valueid, offset, namechar x N]
2022 Expected
<Value
*> ValOrErr
= recordValue(Record
, 2, TT
);
2023 if (Error Err
= ValOrErr
.takeError())
2025 Value
*V
= ValOrErr
.get();
2027 // Ignore function offsets emitted for aliases of functions in older
2028 // versions of LLVM.
2029 if (auto *F
= dyn_cast
<Function
>(V
))
2030 setDeferredFunctionInfo(FuncBitcodeOffsetDelta
, F
, Record
);
2033 case bitc::VST_CODE_BBENTRY
: {
2034 if (convertToString(Record
, 1, ValueName
))
2035 return error("Invalid record");
2036 BasicBlock
*BB
= getBasicBlock(Record
[0]);
2038 return error("Invalid record");
2040 BB
->setName(StringRef(ValueName
.data(), ValueName
.size()));
2048 /// Decode a signed value stored with the sign bit in the LSB for dense VBR
2050 uint64_t BitcodeReader::decodeSignRotatedValue(uint64_t V
) {
2055 // There is no such thing as -0 with integers. "-0" really means MININT.
2059 /// Resolve all of the initializers for global values and aliases that we can.
2060 Error
BitcodeReader::resolveGlobalAndIndirectSymbolInits() {
2061 std::vector
<std::pair
<GlobalVariable
*, unsigned>> GlobalInitWorklist
;
2062 std::vector
<std::pair
<GlobalIndirectSymbol
*, unsigned>>
2063 IndirectSymbolInitWorklist
;
2064 std::vector
<std::pair
<Function
*, unsigned>> FunctionPrefixWorklist
;
2065 std::vector
<std::pair
<Function
*, unsigned>> FunctionPrologueWorklist
;
2066 std::vector
<std::pair
<Function
*, unsigned>> FunctionPersonalityFnWorklist
;
2068 GlobalInitWorklist
.swap(GlobalInits
);
2069 IndirectSymbolInitWorklist
.swap(IndirectSymbolInits
);
2070 FunctionPrefixWorklist
.swap(FunctionPrefixes
);
2071 FunctionPrologueWorklist
.swap(FunctionPrologues
);
2072 FunctionPersonalityFnWorklist
.swap(FunctionPersonalityFns
);
2074 while (!GlobalInitWorklist
.empty()) {
2075 unsigned ValID
= GlobalInitWorklist
.back().second
;
2076 if (ValID
>= ValueList
.size()) {
2077 // Not ready to resolve this yet, it requires something later in the file.
2078 GlobalInits
.push_back(GlobalInitWorklist
.back());
2080 if (Constant
*C
= dyn_cast_or_null
<Constant
>(ValueList
[ValID
]))
2081 GlobalInitWorklist
.back().first
->setInitializer(C
);
2083 return error("Expected a constant");
2085 GlobalInitWorklist
.pop_back();
2088 while (!IndirectSymbolInitWorklist
.empty()) {
2089 unsigned ValID
= IndirectSymbolInitWorklist
.back().second
;
2090 if (ValID
>= ValueList
.size()) {
2091 IndirectSymbolInits
.push_back(IndirectSymbolInitWorklist
.back());
2093 Constant
*C
= dyn_cast_or_null
<Constant
>(ValueList
[ValID
]);
2095 return error("Expected a constant");
2096 GlobalIndirectSymbol
*GIS
= IndirectSymbolInitWorklist
.back().first
;
2097 if (isa
<GlobalAlias
>(GIS
) && C
->getType() != GIS
->getType())
2098 return error("Alias and aliasee types don't match");
2099 GIS
->setIndirectSymbol(C
);
2101 IndirectSymbolInitWorklist
.pop_back();
2104 while (!FunctionPrefixWorklist
.empty()) {
2105 unsigned ValID
= FunctionPrefixWorklist
.back().second
;
2106 if (ValID
>= ValueList
.size()) {
2107 FunctionPrefixes
.push_back(FunctionPrefixWorklist
.back());
2109 if (Constant
*C
= dyn_cast_or_null
<Constant
>(ValueList
[ValID
]))
2110 FunctionPrefixWorklist
.back().first
->setPrefixData(C
);
2112 return error("Expected a constant");
2114 FunctionPrefixWorklist
.pop_back();
2117 while (!FunctionPrologueWorklist
.empty()) {
2118 unsigned ValID
= FunctionPrologueWorklist
.back().second
;
2119 if (ValID
>= ValueList
.size()) {
2120 FunctionPrologues
.push_back(FunctionPrologueWorklist
.back());
2122 if (Constant
*C
= dyn_cast_or_null
<Constant
>(ValueList
[ValID
]))
2123 FunctionPrologueWorklist
.back().first
->setPrologueData(C
);
2125 return error("Expected a constant");
2127 FunctionPrologueWorklist
.pop_back();
2130 while (!FunctionPersonalityFnWorklist
.empty()) {
2131 unsigned ValID
= FunctionPersonalityFnWorklist
.back().second
;
2132 if (ValID
>= ValueList
.size()) {
2133 FunctionPersonalityFns
.push_back(FunctionPersonalityFnWorklist
.back());
2135 if (Constant
*C
= dyn_cast_or_null
<Constant
>(ValueList
[ValID
]))
2136 FunctionPersonalityFnWorklist
.back().first
->setPersonalityFn(C
);
2138 return error("Expected a constant");
2140 FunctionPersonalityFnWorklist
.pop_back();
2143 return Error::success();
2146 static APInt
readWideAPInt(ArrayRef
<uint64_t> Vals
, unsigned TypeBits
) {
2147 SmallVector
<uint64_t, 8> Words(Vals
.size());
2148 transform(Vals
, Words
.begin(),
2149 BitcodeReader::decodeSignRotatedValue
);
2151 return APInt(TypeBits
, Words
);
2154 Error
BitcodeReader::parseConstants() {
2155 if (Stream
.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID
))
2156 return error("Invalid record");
2158 SmallVector
<uint64_t, 64> Record
;
2160 // Read all the records for this value table.
2161 Type
*CurTy
= Type::getInt32Ty(Context
);
2162 unsigned NextCstNo
= ValueList
.size();
2165 BitstreamEntry Entry
= Stream
.advanceSkippingSubblocks();
2167 switch (Entry
.Kind
) {
2168 case BitstreamEntry::SubBlock
: // Handled for us already.
2169 case BitstreamEntry::Error
:
2170 return error("Malformed block");
2171 case BitstreamEntry::EndBlock
:
2172 if (NextCstNo
!= ValueList
.size())
2173 return error("Invalid constant reference");
2175 // Once all the constants have been read, go through and resolve forward
2177 ValueList
.resolveConstantForwardRefs();
2178 return Error::success();
2179 case BitstreamEntry::Record
:
2180 // The interesting case.
2186 Type
*VoidType
= Type::getVoidTy(Context
);
2188 unsigned BitCode
= Stream
.readRecord(Entry
.ID
, Record
);
2190 default: // Default behavior: unknown constant
2191 case bitc::CST_CODE_UNDEF
: // UNDEF
2192 V
= UndefValue::get(CurTy
);
2194 case bitc::CST_CODE_SETTYPE
: // SETTYPE: [typeid]
2196 return error("Invalid record");
2197 if (Record
[0] >= TypeList
.size() || !TypeList
[Record
[0]])
2198 return error("Invalid record");
2199 if (TypeList
[Record
[0]] == VoidType
)
2200 return error("Invalid constant type");
2201 CurTy
= TypeList
[Record
[0]];
2202 continue; // Skip the ValueList manipulation.
2203 case bitc::CST_CODE_NULL
: // NULL
2204 V
= Constant::getNullValue(CurTy
);
2206 case bitc::CST_CODE_INTEGER
: // INTEGER: [intval]
2207 if (!CurTy
->isIntegerTy() || Record
.empty())
2208 return error("Invalid record");
2209 V
= ConstantInt::get(CurTy
, decodeSignRotatedValue(Record
[0]));
2211 case bitc::CST_CODE_WIDE_INTEGER
: {// WIDE_INTEGER: [n x intval]
2212 if (!CurTy
->isIntegerTy() || Record
.empty())
2213 return error("Invalid record");
2216 readWideAPInt(Record
, cast
<IntegerType
>(CurTy
)->getBitWidth());
2217 V
= ConstantInt::get(Context
, VInt
);
2221 case bitc::CST_CODE_FLOAT
: { // FLOAT: [fpval]
2223 return error("Invalid record");
2224 if (CurTy
->isHalfTy())
2225 V
= ConstantFP::get(Context
, APFloat(APFloat::IEEEhalf(),
2226 APInt(16, (uint16_t)Record
[0])));
2227 else if (CurTy
->isFloatTy())
2228 V
= ConstantFP::get(Context
, APFloat(APFloat::IEEEsingle(),
2229 APInt(32, (uint32_t)Record
[0])));
2230 else if (CurTy
->isDoubleTy())
2231 V
= ConstantFP::get(Context
, APFloat(APFloat::IEEEdouble(),
2232 APInt(64, Record
[0])));
2233 else if (CurTy
->isX86_FP80Ty()) {
2234 // Bits are not stored the same way as a normal i80 APInt, compensate.
2235 uint64_t Rearrange
[2];
2236 Rearrange
[0] = (Record
[1] & 0xffffLL
) | (Record
[0] << 16);
2237 Rearrange
[1] = Record
[0] >> 48;
2238 V
= ConstantFP::get(Context
, APFloat(APFloat::x87DoubleExtended(),
2239 APInt(80, Rearrange
)));
2240 } else if (CurTy
->isFP128Ty())
2241 V
= ConstantFP::get(Context
, APFloat(APFloat::IEEEquad(),
2242 APInt(128, Record
)));
2243 else if (CurTy
->isPPC_FP128Ty())
2244 V
= ConstantFP::get(Context
, APFloat(APFloat::PPCDoubleDouble(),
2245 APInt(128, Record
)));
2247 V
= UndefValue::get(CurTy
);
2251 case bitc::CST_CODE_AGGREGATE
: {// AGGREGATE: [n x value number]
2253 return error("Invalid record");
2255 unsigned Size
= Record
.size();
2256 SmallVector
<Constant
*, 16> Elts
;
2258 if (StructType
*STy
= dyn_cast
<StructType
>(CurTy
)) {
2259 for (unsigned i
= 0; i
!= Size
; ++i
)
2260 Elts
.push_back(ValueList
.getConstantFwdRef(Record
[i
],
2261 STy
->getElementType(i
)));
2262 V
= ConstantStruct::get(STy
, Elts
);
2263 } else if (ArrayType
*ATy
= dyn_cast
<ArrayType
>(CurTy
)) {
2264 Type
*EltTy
= ATy
->getElementType();
2265 for (unsigned i
= 0; i
!= Size
; ++i
)
2266 Elts
.push_back(ValueList
.getConstantFwdRef(Record
[i
], EltTy
));
2267 V
= ConstantArray::get(ATy
, Elts
);
2268 } else if (VectorType
*VTy
= dyn_cast
<VectorType
>(CurTy
)) {
2269 Type
*EltTy
= VTy
->getElementType();
2270 for (unsigned i
= 0; i
!= Size
; ++i
)
2271 Elts
.push_back(ValueList
.getConstantFwdRef(Record
[i
], EltTy
));
2272 V
= ConstantVector::get(Elts
);
2274 V
= UndefValue::get(CurTy
);
2278 case bitc::CST_CODE_STRING
: // STRING: [values]
2279 case bitc::CST_CODE_CSTRING
: { // CSTRING: [values]
2281 return error("Invalid record");
2283 SmallString
<16> Elts(Record
.begin(), Record
.end());
2284 V
= ConstantDataArray::getString(Context
, Elts
,
2285 BitCode
== bitc::CST_CODE_CSTRING
);
2288 case bitc::CST_CODE_DATA
: {// DATA: [n x value]
2290 return error("Invalid record");
2292 Type
*EltTy
= cast
<SequentialType
>(CurTy
)->getElementType();
2293 if (EltTy
->isIntegerTy(8)) {
2294 SmallVector
<uint8_t, 16> Elts(Record
.begin(), Record
.end());
2295 if (isa
<VectorType
>(CurTy
))
2296 V
= ConstantDataVector::get(Context
, Elts
);
2298 V
= ConstantDataArray::get(Context
, Elts
);
2299 } else if (EltTy
->isIntegerTy(16)) {
2300 SmallVector
<uint16_t, 16> Elts(Record
.begin(), Record
.end());
2301 if (isa
<VectorType
>(CurTy
))
2302 V
= ConstantDataVector::get(Context
, Elts
);
2304 V
= ConstantDataArray::get(Context
, Elts
);
2305 } else if (EltTy
->isIntegerTy(32)) {
2306 SmallVector
<uint32_t, 16> Elts(Record
.begin(), Record
.end());
2307 if (isa
<VectorType
>(CurTy
))
2308 V
= ConstantDataVector::get(Context
, Elts
);
2310 V
= ConstantDataArray::get(Context
, Elts
);
2311 } else if (EltTy
->isIntegerTy(64)) {
2312 SmallVector
<uint64_t, 16> Elts(Record
.begin(), Record
.end());
2313 if (isa
<VectorType
>(CurTy
))
2314 V
= ConstantDataVector::get(Context
, Elts
);
2316 V
= ConstantDataArray::get(Context
, Elts
);
2317 } else if (EltTy
->isHalfTy()) {
2318 SmallVector
<uint16_t, 16> Elts(Record
.begin(), Record
.end());
2319 if (isa
<VectorType
>(CurTy
))
2320 V
= ConstantDataVector::getFP(Context
, Elts
);
2322 V
= ConstantDataArray::getFP(Context
, Elts
);
2323 } else if (EltTy
->isFloatTy()) {
2324 SmallVector
<uint32_t, 16> Elts(Record
.begin(), Record
.end());
2325 if (isa
<VectorType
>(CurTy
))
2326 V
= ConstantDataVector::getFP(Context
, Elts
);
2328 V
= ConstantDataArray::getFP(Context
, Elts
);
2329 } else if (EltTy
->isDoubleTy()) {
2330 SmallVector
<uint64_t, 16> Elts(Record
.begin(), Record
.end());
2331 if (isa
<VectorType
>(CurTy
))
2332 V
= ConstantDataVector::getFP(Context
, Elts
);
2334 V
= ConstantDataArray::getFP(Context
, Elts
);
2336 return error("Invalid type for value");
2340 case bitc::CST_CODE_CE_UNOP
: { // CE_UNOP: [opcode, opval]
2341 if (Record
.size() < 2)
2342 return error("Invalid record");
2343 int Opc
= getDecodedUnaryOpcode(Record
[0], CurTy
);
2345 V
= UndefValue::get(CurTy
); // Unknown unop.
2347 Constant
*LHS
= ValueList
.getConstantFwdRef(Record
[1], CurTy
);
2349 V
= ConstantExpr::get(Opc
, LHS
, Flags
);
2353 case bitc::CST_CODE_CE_BINOP
: { // CE_BINOP: [opcode, opval, opval]
2354 if (Record
.size() < 3)
2355 return error("Invalid record");
2356 int Opc
= getDecodedBinaryOpcode(Record
[0], CurTy
);
2358 V
= UndefValue::get(CurTy
); // Unknown binop.
2360 Constant
*LHS
= ValueList
.getConstantFwdRef(Record
[1], CurTy
);
2361 Constant
*RHS
= ValueList
.getConstantFwdRef(Record
[2], CurTy
);
2363 if (Record
.size() >= 4) {
2364 if (Opc
== Instruction::Add
||
2365 Opc
== Instruction::Sub
||
2366 Opc
== Instruction::Mul
||
2367 Opc
== Instruction::Shl
) {
2368 if (Record
[3] & (1 << bitc::OBO_NO_SIGNED_WRAP
))
2369 Flags
|= OverflowingBinaryOperator::NoSignedWrap
;
2370 if (Record
[3] & (1 << bitc::OBO_NO_UNSIGNED_WRAP
))
2371 Flags
|= OverflowingBinaryOperator::NoUnsignedWrap
;
2372 } else if (Opc
== Instruction::SDiv
||
2373 Opc
== Instruction::UDiv
||
2374 Opc
== Instruction::LShr
||
2375 Opc
== Instruction::AShr
) {
2376 if (Record
[3] & (1 << bitc::PEO_EXACT
))
2377 Flags
|= SDivOperator::IsExact
;
2380 V
= ConstantExpr::get(Opc
, LHS
, RHS
, Flags
);
2384 case bitc::CST_CODE_CE_CAST
: { // CE_CAST: [opcode, opty, opval]
2385 if (Record
.size() < 3)
2386 return error("Invalid record");
2387 int Opc
= getDecodedCastOpcode(Record
[0]);
2389 V
= UndefValue::get(CurTy
); // Unknown cast.
2391 Type
*OpTy
= getTypeByID(Record
[1]);
2393 return error("Invalid record");
2394 Constant
*Op
= ValueList
.getConstantFwdRef(Record
[2], OpTy
);
2395 V
= UpgradeBitCastExpr(Opc
, Op
, CurTy
);
2396 if (!V
) V
= ConstantExpr::getCast(Opc
, Op
, CurTy
);
2400 case bitc::CST_CODE_CE_INBOUNDS_GEP
: // [ty, n x operands]
2401 case bitc::CST_CODE_CE_GEP
: // [ty, n x operands]
2402 case bitc::CST_CODE_CE_GEP_WITH_INRANGE_INDEX
: { // [ty, flags, n x
2405 Type
*PointeeType
= nullptr;
2406 if (BitCode
== bitc::CST_CODE_CE_GEP_WITH_INRANGE_INDEX
||
2408 PointeeType
= getTypeByID(Record
[OpNum
++]);
2410 bool InBounds
= false;
2411 Optional
<unsigned> InRangeIndex
;
2412 if (BitCode
== bitc::CST_CODE_CE_GEP_WITH_INRANGE_INDEX
) {
2413 uint64_t Op
= Record
[OpNum
++];
2415 InRangeIndex
= Op
>> 1;
2416 } else if (BitCode
== bitc::CST_CODE_CE_INBOUNDS_GEP
)
2419 SmallVector
<Constant
*, 16> Elts
;
2420 while (OpNum
!= Record
.size()) {
2421 Type
*ElTy
= getTypeByID(Record
[OpNum
++]);
2423 return error("Invalid record");
2424 Elts
.push_back(ValueList
.getConstantFwdRef(Record
[OpNum
++], ElTy
));
2427 if (Elts
.size() < 1)
2428 return error("Invalid gep with no operands");
2430 Type
*ImplicitPointeeType
=
2431 cast
<PointerType
>(Elts
[0]->getType()->getScalarType())
2434 PointeeType
= ImplicitPointeeType
;
2435 else if (PointeeType
!= ImplicitPointeeType
)
2436 return error("Explicit gep operator type does not match pointee type "
2437 "of pointer operand");
2439 ArrayRef
<Constant
*> Indices(Elts
.begin() + 1, Elts
.end());
2440 V
= ConstantExpr::getGetElementPtr(PointeeType
, Elts
[0], Indices
,
2441 InBounds
, InRangeIndex
);
2444 case bitc::CST_CODE_CE_SELECT
: { // CE_SELECT: [opval#, opval#, opval#]
2445 if (Record
.size() < 3)
2446 return error("Invalid record");
2448 Type
*SelectorTy
= Type::getInt1Ty(Context
);
2450 // The selector might be an i1 or an <n x i1>
2451 // Get the type from the ValueList before getting a forward ref.
2452 if (VectorType
*VTy
= dyn_cast
<VectorType
>(CurTy
))
2453 if (Value
*V
= ValueList
[Record
[0]])
2454 if (SelectorTy
!= V
->getType())
2455 SelectorTy
= VectorType::get(SelectorTy
, VTy
->getNumElements());
2457 V
= ConstantExpr::getSelect(ValueList
.getConstantFwdRef(Record
[0],
2459 ValueList
.getConstantFwdRef(Record
[1],CurTy
),
2460 ValueList
.getConstantFwdRef(Record
[2],CurTy
));
2463 case bitc::CST_CODE_CE_EXTRACTELT
2464 : { // CE_EXTRACTELT: [opty, opval, opty, opval]
2465 if (Record
.size() < 3)
2466 return error("Invalid record");
2468 dyn_cast_or_null
<VectorType
>(getTypeByID(Record
[0]));
2470 return error("Invalid record");
2471 Constant
*Op0
= ValueList
.getConstantFwdRef(Record
[1], OpTy
);
2472 Constant
*Op1
= nullptr;
2473 if (Record
.size() == 4) {
2474 Type
*IdxTy
= getTypeByID(Record
[2]);
2476 return error("Invalid record");
2477 Op1
= ValueList
.getConstantFwdRef(Record
[3], IdxTy
);
2478 } else // TODO: Remove with llvm 4.0
2479 Op1
= ValueList
.getConstantFwdRef(Record
[2], Type::getInt32Ty(Context
));
2481 return error("Invalid record");
2482 V
= ConstantExpr::getExtractElement(Op0
, Op1
);
2485 case bitc::CST_CODE_CE_INSERTELT
2486 : { // CE_INSERTELT: [opval, opval, opty, opval]
2487 VectorType
*OpTy
= dyn_cast
<VectorType
>(CurTy
);
2488 if (Record
.size() < 3 || !OpTy
)
2489 return error("Invalid record");
2490 Constant
*Op0
= ValueList
.getConstantFwdRef(Record
[0], OpTy
);
2491 Constant
*Op1
= ValueList
.getConstantFwdRef(Record
[1],
2492 OpTy
->getElementType());
2493 Constant
*Op2
= nullptr;
2494 if (Record
.size() == 4) {
2495 Type
*IdxTy
= getTypeByID(Record
[2]);
2497 return error("Invalid record");
2498 Op2
= ValueList
.getConstantFwdRef(Record
[3], IdxTy
);
2499 } else // TODO: Remove with llvm 4.0
2500 Op2
= ValueList
.getConstantFwdRef(Record
[2], Type::getInt32Ty(Context
));
2502 return error("Invalid record");
2503 V
= ConstantExpr::getInsertElement(Op0
, Op1
, Op2
);
2506 case bitc::CST_CODE_CE_SHUFFLEVEC
: { // CE_SHUFFLEVEC: [opval, opval, opval]
2507 VectorType
*OpTy
= dyn_cast
<VectorType
>(CurTy
);
2508 if (Record
.size() < 3 || !OpTy
)
2509 return error("Invalid record");
2510 Constant
*Op0
= ValueList
.getConstantFwdRef(Record
[0], OpTy
);
2511 Constant
*Op1
= ValueList
.getConstantFwdRef(Record
[1], OpTy
);
2512 Type
*ShufTy
= VectorType::get(Type::getInt32Ty(Context
),
2513 OpTy
->getNumElements());
2514 Constant
*Op2
= ValueList
.getConstantFwdRef(Record
[2], ShufTy
);
2515 V
= ConstantExpr::getShuffleVector(Op0
, Op1
, Op2
);
2518 case bitc::CST_CODE_CE_SHUFVEC_EX
: { // [opty, opval, opval, opval]
2519 VectorType
*RTy
= dyn_cast
<VectorType
>(CurTy
);
2521 dyn_cast_or_null
<VectorType
>(getTypeByID(Record
[0]));
2522 if (Record
.size() < 4 || !RTy
|| !OpTy
)
2523 return error("Invalid record");
2524 Constant
*Op0
= ValueList
.getConstantFwdRef(Record
[1], OpTy
);
2525 Constant
*Op1
= ValueList
.getConstantFwdRef(Record
[2], OpTy
);
2526 Type
*ShufTy
= VectorType::get(Type::getInt32Ty(Context
),
2527 RTy
->getNumElements());
2528 Constant
*Op2
= ValueList
.getConstantFwdRef(Record
[3], ShufTy
);
2529 V
= ConstantExpr::getShuffleVector(Op0
, Op1
, Op2
);
2532 case bitc::CST_CODE_CE_CMP
: { // CE_CMP: [opty, opval, opval, pred]
2533 if (Record
.size() < 4)
2534 return error("Invalid record");
2535 Type
*OpTy
= getTypeByID(Record
[0]);
2537 return error("Invalid record");
2538 Constant
*Op0
= ValueList
.getConstantFwdRef(Record
[1], OpTy
);
2539 Constant
*Op1
= ValueList
.getConstantFwdRef(Record
[2], OpTy
);
2541 if (OpTy
->isFPOrFPVectorTy())
2542 V
= ConstantExpr::getFCmp(Record
[3], Op0
, Op1
);
2544 V
= ConstantExpr::getICmp(Record
[3], Op0
, Op1
);
2547 // This maintains backward compatibility, pre-asm dialect keywords.
2548 // FIXME: Remove with the 4.0 release.
2549 case bitc::CST_CODE_INLINEASM_OLD
: {
2550 if (Record
.size() < 2)
2551 return error("Invalid record");
2552 std::string AsmStr
, ConstrStr
;
2553 bool HasSideEffects
= Record
[0] & 1;
2554 bool IsAlignStack
= Record
[0] >> 1;
2555 unsigned AsmStrSize
= Record
[1];
2556 if (2+AsmStrSize
>= Record
.size())
2557 return error("Invalid record");
2558 unsigned ConstStrSize
= Record
[2+AsmStrSize
];
2559 if (3+AsmStrSize
+ConstStrSize
> Record
.size())
2560 return error("Invalid record");
2562 for (unsigned i
= 0; i
!= AsmStrSize
; ++i
)
2563 AsmStr
+= (char)Record
[2+i
];
2564 for (unsigned i
= 0; i
!= ConstStrSize
; ++i
)
2565 ConstrStr
+= (char)Record
[3+AsmStrSize
+i
];
2566 PointerType
*PTy
= cast
<PointerType
>(CurTy
);
2567 UpgradeInlineAsmString(&AsmStr
);
2568 V
= InlineAsm::get(cast
<FunctionType
>(PTy
->getElementType()),
2569 AsmStr
, ConstrStr
, HasSideEffects
, IsAlignStack
);
2572 // This version adds support for the asm dialect keywords (e.g.,
2574 case bitc::CST_CODE_INLINEASM
: {
2575 if (Record
.size() < 2)
2576 return error("Invalid record");
2577 std::string AsmStr
, ConstrStr
;
2578 bool HasSideEffects
= Record
[0] & 1;
2579 bool IsAlignStack
= (Record
[0] >> 1) & 1;
2580 unsigned AsmDialect
= Record
[0] >> 2;
2581 unsigned AsmStrSize
= Record
[1];
2582 if (2+AsmStrSize
>= Record
.size())
2583 return error("Invalid record");
2584 unsigned ConstStrSize
= Record
[2+AsmStrSize
];
2585 if (3+AsmStrSize
+ConstStrSize
> Record
.size())
2586 return error("Invalid record");
2588 for (unsigned i
= 0; i
!= AsmStrSize
; ++i
)
2589 AsmStr
+= (char)Record
[2+i
];
2590 for (unsigned i
= 0; i
!= ConstStrSize
; ++i
)
2591 ConstrStr
+= (char)Record
[3+AsmStrSize
+i
];
2592 PointerType
*PTy
= cast
<PointerType
>(CurTy
);
2593 UpgradeInlineAsmString(&AsmStr
);
2594 V
= InlineAsm::get(cast
<FunctionType
>(PTy
->getElementType()),
2595 AsmStr
, ConstrStr
, HasSideEffects
, IsAlignStack
,
2596 InlineAsm::AsmDialect(AsmDialect
));
2599 case bitc::CST_CODE_BLOCKADDRESS
:{
2600 if (Record
.size() < 3)
2601 return error("Invalid record");
2602 Type
*FnTy
= getTypeByID(Record
[0]);
2604 return error("Invalid record");
2606 dyn_cast_or_null
<Function
>(ValueList
.getConstantFwdRef(Record
[1],FnTy
));
2608 return error("Invalid record");
2610 // If the function is already parsed we can insert the block address right
2613 unsigned BBID
= Record
[2];
2615 // Invalid reference to entry block.
2616 return error("Invalid ID");
2618 Function::iterator BBI
= Fn
->begin(), BBE
= Fn
->end();
2619 for (size_t I
= 0, E
= BBID
; I
!= E
; ++I
) {
2621 return error("Invalid ID");
2626 // Otherwise insert a placeholder and remember it so it can be inserted
2627 // when the function is parsed.
2628 auto &FwdBBs
= BasicBlockFwdRefs
[Fn
];
2630 BasicBlockFwdRefQueue
.push_back(Fn
);
2631 if (FwdBBs
.size() < BBID
+ 1)
2632 FwdBBs
.resize(BBID
+ 1);
2634 FwdBBs
[BBID
] = BasicBlock::Create(Context
);
2637 V
= BlockAddress::get(Fn
, BB
);
2642 ValueList
.assignValue(V
, NextCstNo
);
2647 Error
BitcodeReader::parseUseLists() {
2648 if (Stream
.EnterSubBlock(bitc::USELIST_BLOCK_ID
))
2649 return error("Invalid record");
2651 // Read all the records.
2652 SmallVector
<uint64_t, 64> Record
;
2655 BitstreamEntry Entry
= Stream
.advanceSkippingSubblocks();
2657 switch (Entry
.Kind
) {
2658 case BitstreamEntry::SubBlock
: // Handled for us already.
2659 case BitstreamEntry::Error
:
2660 return error("Malformed block");
2661 case BitstreamEntry::EndBlock
:
2662 return Error::success();
2663 case BitstreamEntry::Record
:
2664 // The interesting case.
2668 // Read a use list record.
2671 switch (Stream
.readRecord(Entry
.ID
, Record
)) {
2672 default: // Default behavior: unknown type.
2674 case bitc::USELIST_CODE_BB
:
2677 case bitc::USELIST_CODE_DEFAULT
: {
2678 unsigned RecordLength
= Record
.size();
2679 if (RecordLength
< 3)
2680 // Records should have at least an ID and two indexes.
2681 return error("Invalid record");
2682 unsigned ID
= Record
.back();
2687 assert(ID
< FunctionBBs
.size() && "Basic block not found");
2688 V
= FunctionBBs
[ID
];
2691 unsigned NumUses
= 0;
2692 SmallDenseMap
<const Use
*, unsigned, 16> Order
;
2693 for (const Use
&U
: V
->materialized_uses()) {
2694 if (++NumUses
> Record
.size())
2696 Order
[&U
] = Record
[NumUses
- 1];
2698 if (Order
.size() != Record
.size() || NumUses
> Record
.size())
2699 // Mismatches can happen if the functions are being materialized lazily
2700 // (out-of-order), or a value has been upgraded.
2703 V
->sortUseList([&](const Use
&L
, const Use
&R
) {
2704 return Order
.lookup(&L
) < Order
.lookup(&R
);
2712 /// When we see the block for metadata, remember where it is and then skip it.
2713 /// This lets us lazily deserialize the metadata.
2714 Error
BitcodeReader::rememberAndSkipMetadata() {
2715 // Save the current stream state.
2716 uint64_t CurBit
= Stream
.GetCurrentBitNo();
2717 DeferredMetadataInfo
.push_back(CurBit
);
2719 // Skip over the block for now.
2720 if (Stream
.SkipBlock())
2721 return error("Invalid record");
2722 return Error::success();
2725 Error
BitcodeReader::materializeMetadata() {
2726 for (uint64_t BitPos
: DeferredMetadataInfo
) {
2727 // Move the bit stream to the saved position.
2728 Stream
.JumpToBit(BitPos
);
2729 if (Error Err
= MDLoader
->parseModuleMetadata())
2733 // Upgrade "Linker Options" module flag to "llvm.linker.options" module-level
2735 if (Metadata
*Val
= TheModule
->getModuleFlag("Linker Options")) {
2736 NamedMDNode
*LinkerOpts
=
2737 TheModule
->getOrInsertNamedMetadata("llvm.linker.options");
2738 for (const MDOperand
&MDOptions
: cast
<MDNode
>(Val
)->operands())
2739 LinkerOpts
->addOperand(cast
<MDNode
>(MDOptions
));
2742 DeferredMetadataInfo
.clear();
2743 return Error::success();
2746 void BitcodeReader::setStripDebugInfo() { StripDebugInfo
= true; }
2748 /// When we see the block for a function body, remember where it is and then
2749 /// skip it. This lets us lazily deserialize the functions.
2750 Error
BitcodeReader::rememberAndSkipFunctionBody() {
2751 // Get the function we are talking about.
2752 if (FunctionsWithBodies
.empty())
2753 return error("Insufficient function protos");
2755 Function
*Fn
= FunctionsWithBodies
.back();
2756 FunctionsWithBodies
.pop_back();
2758 // Save the current stream state.
2759 uint64_t CurBit
= Stream
.GetCurrentBitNo();
2761 (DeferredFunctionInfo
[Fn
] == 0 || DeferredFunctionInfo
[Fn
] == CurBit
) &&
2762 "Mismatch between VST and scanned function offsets");
2763 DeferredFunctionInfo
[Fn
] = CurBit
;
2765 // Skip over the function block for now.
2766 if (Stream
.SkipBlock())
2767 return error("Invalid record");
2768 return Error::success();
2771 Error
BitcodeReader::globalCleanup() {
2772 // Patch the initializers for globals and aliases up.
2773 if (Error Err
= resolveGlobalAndIndirectSymbolInits())
2775 if (!GlobalInits
.empty() || !IndirectSymbolInits
.empty())
2776 return error("Malformed global initializer set");
2778 // Look for intrinsic functions which need to be upgraded at some point
2779 for (Function
&F
: *TheModule
) {
2780 MDLoader
->upgradeDebugIntrinsics(F
);
2782 if (UpgradeIntrinsicFunction(&F
, NewFn
))
2783 UpgradedIntrinsics
[&F
] = NewFn
;
2784 else if (auto Remangled
= Intrinsic::remangleIntrinsicFunction(&F
))
2785 // Some types could be renamed during loading if several modules are
2786 // loaded in the same LLVMContext (LTO scenario). In this case we should
2787 // remangle intrinsics names as well.
2788 RemangledIntrinsics
[&F
] = Remangled
.getValue();
2791 // Look for global variables which need to be renamed.
2792 for (GlobalVariable
&GV
: TheModule
->globals())
2793 UpgradeGlobalVariable(&GV
);
2795 // Force deallocation of memory for these vectors to favor the client that
2796 // want lazy deserialization.
2797 std::vector
<std::pair
<GlobalVariable
*, unsigned>>().swap(GlobalInits
);
2798 std::vector
<std::pair
<GlobalIndirectSymbol
*, unsigned>>().swap(
2799 IndirectSymbolInits
);
2800 return Error::success();
2803 /// Support for lazy parsing of function bodies. This is required if we
2804 /// either have an old bitcode file without a VST forward declaration record,
2805 /// or if we have an anonymous function being materialized, since anonymous
2806 /// functions do not have a name and are therefore not in the VST.
2807 Error
BitcodeReader::rememberAndSkipFunctionBodies() {
2808 Stream
.JumpToBit(NextUnreadBit
);
2810 if (Stream
.AtEndOfStream())
2811 return error("Could not find function in stream");
2813 if (!SeenFirstFunctionBody
)
2814 return error("Trying to materialize functions before seeing function blocks");
2816 // An old bitcode file with the symbol table at the end would have
2817 // finished the parse greedily.
2818 assert(SeenValueSymbolTable
);
2820 SmallVector
<uint64_t, 64> Record
;
2823 BitstreamEntry Entry
= Stream
.advance();
2824 switch (Entry
.Kind
) {
2826 return error("Expect SubBlock");
2827 case BitstreamEntry::SubBlock
:
2830 return error("Expect function block");
2831 case bitc::FUNCTION_BLOCK_ID
:
2832 if (Error Err
= rememberAndSkipFunctionBody())
2834 NextUnreadBit
= Stream
.GetCurrentBitNo();
2835 return Error::success();
2841 bool BitcodeReaderBase::readBlockInfo() {
2842 Optional
<BitstreamBlockInfo
> NewBlockInfo
= Stream
.ReadBlockInfoBlock();
2845 BlockInfo
= std::move(*NewBlockInfo
);
2849 Error
BitcodeReader::parseComdatRecord(ArrayRef
<uint64_t> Record
) {
2850 // v1: [selection_kind, name]
2851 // v2: [strtab_offset, strtab_size, selection_kind]
2853 std::tie(Name
, Record
) = readNameFromStrtab(Record
);
2856 return error("Invalid record");
2857 Comdat::SelectionKind SK
= getDecodedComdatSelectionKind(Record
[0]);
2858 std::string OldFormatName
;
2860 if (Record
.size() < 2)
2861 return error("Invalid record");
2862 unsigned ComdatNameSize
= Record
[1];
2863 OldFormatName
.reserve(ComdatNameSize
);
2864 for (unsigned i
= 0; i
!= ComdatNameSize
; ++i
)
2865 OldFormatName
+= (char)Record
[2 + i
];
2866 Name
= OldFormatName
;
2868 Comdat
*C
= TheModule
->getOrInsertComdat(Name
);
2869 C
->setSelectionKind(SK
);
2870 ComdatList
.push_back(C
);
2871 return Error::success();
2874 static void inferDSOLocal(GlobalValue
*GV
) {
2875 // infer dso_local from linkage and visibility if it is not encoded.
2876 if (GV
->hasLocalLinkage() ||
2877 (!GV
->hasDefaultVisibility() && !GV
->hasExternalWeakLinkage()))
2878 GV
->setDSOLocal(true);
2881 Error
BitcodeReader::parseGlobalVarRecord(ArrayRef
<uint64_t> Record
) {
2882 // v1: [pointer type, isconst, initid, linkage, alignment, section,
2883 // visibility, threadlocal, unnamed_addr, externally_initialized,
2884 // dllstorageclass, comdat, attributes, preemption specifier] (name in VST)
2885 // v2: [strtab_offset, strtab_size, v1]
2887 std::tie(Name
, Record
) = readNameFromStrtab(Record
);
2889 if (Record
.size() < 6)
2890 return error("Invalid record");
2891 Type
*Ty
= getTypeByID(Record
[0]);
2893 return error("Invalid record");
2894 bool isConstant
= Record
[1] & 1;
2895 bool explicitType
= Record
[1] & 2;
2896 unsigned AddressSpace
;
2898 AddressSpace
= Record
[1] >> 2;
2900 if (!Ty
->isPointerTy())
2901 return error("Invalid type for value");
2902 AddressSpace
= cast
<PointerType
>(Ty
)->getAddressSpace();
2903 Ty
= cast
<PointerType
>(Ty
)->getElementType();
2906 uint64_t RawLinkage
= Record
[3];
2907 GlobalValue::LinkageTypes Linkage
= getDecodedLinkage(RawLinkage
);
2909 if (Error Err
= parseAlignmentValue(Record
[4], Alignment
))
2911 std::string Section
;
2913 if (Record
[5] - 1 >= SectionTable
.size())
2914 return error("Invalid ID");
2915 Section
= SectionTable
[Record
[5] - 1];
2917 GlobalValue::VisibilityTypes Visibility
= GlobalValue::DefaultVisibility
;
2918 // Local linkage must have default visibility.
2919 if (Record
.size() > 6 && !GlobalValue::isLocalLinkage(Linkage
))
2920 // FIXME: Change to an error if non-default in 4.0.
2921 Visibility
= getDecodedVisibility(Record
[6]);
2923 GlobalVariable::ThreadLocalMode TLM
= GlobalVariable::NotThreadLocal
;
2924 if (Record
.size() > 7)
2925 TLM
= getDecodedThreadLocalMode(Record
[7]);
2927 GlobalValue::UnnamedAddr UnnamedAddr
= GlobalValue::UnnamedAddr::None
;
2928 if (Record
.size() > 8)
2929 UnnamedAddr
= getDecodedUnnamedAddrType(Record
[8]);
2931 bool ExternallyInitialized
= false;
2932 if (Record
.size() > 9)
2933 ExternallyInitialized
= Record
[9];
2935 GlobalVariable
*NewGV
=
2936 new GlobalVariable(*TheModule
, Ty
, isConstant
, Linkage
, nullptr, Name
,
2937 nullptr, TLM
, AddressSpace
, ExternallyInitialized
);
2938 NewGV
->setAlignment(Alignment
);
2939 if (!Section
.empty())
2940 NewGV
->setSection(Section
);
2941 NewGV
->setVisibility(Visibility
);
2942 NewGV
->setUnnamedAddr(UnnamedAddr
);
2944 if (Record
.size() > 10)
2945 NewGV
->setDLLStorageClass(getDecodedDLLStorageClass(Record
[10]));
2947 upgradeDLLImportExportLinkage(NewGV
, RawLinkage
);
2949 ValueList
.push_back(NewGV
);
2951 // Remember which value to use for the global initializer.
2952 if (unsigned InitID
= Record
[2])
2953 GlobalInits
.push_back(std::make_pair(NewGV
, InitID
- 1));
2955 if (Record
.size() > 11) {
2956 if (unsigned ComdatID
= Record
[11]) {
2957 if (ComdatID
> ComdatList
.size())
2958 return error("Invalid global variable comdat ID");
2959 NewGV
->setComdat(ComdatList
[ComdatID
- 1]);
2961 } else if (hasImplicitComdat(RawLinkage
)) {
2962 NewGV
->setComdat(reinterpret_cast<Comdat
*>(1));
2965 if (Record
.size() > 12) {
2966 auto AS
= getAttributes(Record
[12]).getFnAttributes();
2967 NewGV
->setAttributes(AS
);
2970 if (Record
.size() > 13) {
2971 NewGV
->setDSOLocal(getDecodedDSOLocal(Record
[13]));
2973 inferDSOLocal(NewGV
);
2975 return Error::success();
2978 Error
BitcodeReader::parseFunctionRecord(ArrayRef
<uint64_t> Record
) {
2979 // v1: [type, callingconv, isproto, linkage, paramattr, alignment, section,
2980 // visibility, gc, unnamed_addr, prologuedata, dllstorageclass, comdat,
2981 // prefixdata, personalityfn, preemption specifier, addrspace] (name in VST)
2982 // v2: [strtab_offset, strtab_size, v1]
2984 std::tie(Name
, Record
) = readNameFromStrtab(Record
);
2986 if (Record
.size() < 8)
2987 return error("Invalid record");
2988 Type
*Ty
= getTypeByID(Record
[0]);
2990 return error("Invalid record");
2991 if (auto *PTy
= dyn_cast
<PointerType
>(Ty
))
2992 Ty
= PTy
->getElementType();
2993 auto *FTy
= dyn_cast
<FunctionType
>(Ty
);
2995 return error("Invalid type for value");
2996 auto CC
= static_cast<CallingConv::ID
>(Record
[1]);
2997 if (CC
& ~CallingConv::MaxID
)
2998 return error("Invalid calling convention ID");
3000 unsigned AddrSpace
= TheModule
->getDataLayout().getProgramAddressSpace();
3001 if (Record
.size() > 16)
3002 AddrSpace
= Record
[16];
3004 Function
*Func
= Function::Create(FTy
, GlobalValue::ExternalLinkage
,
3005 AddrSpace
, Name
, TheModule
);
3007 Func
->setCallingConv(CC
);
3008 bool isProto
= Record
[2];
3009 uint64_t RawLinkage
= Record
[3];
3010 Func
->setLinkage(getDecodedLinkage(RawLinkage
));
3011 Func
->setAttributes(getAttributes(Record
[4]));
3014 if (Error Err
= parseAlignmentValue(Record
[5], Alignment
))
3016 Func
->setAlignment(Alignment
);
3018 if (Record
[6] - 1 >= SectionTable
.size())
3019 return error("Invalid ID");
3020 Func
->setSection(SectionTable
[Record
[6] - 1]);
3022 // Local linkage must have default visibility.
3023 if (!Func
->hasLocalLinkage())
3024 // FIXME: Change to an error if non-default in 4.0.
3025 Func
->setVisibility(getDecodedVisibility(Record
[7]));
3026 if (Record
.size() > 8 && Record
[8]) {
3027 if (Record
[8] - 1 >= GCTable
.size())
3028 return error("Invalid ID");
3029 Func
->setGC(GCTable
[Record
[8] - 1]);
3031 GlobalValue::UnnamedAddr UnnamedAddr
= GlobalValue::UnnamedAddr::None
;
3032 if (Record
.size() > 9)
3033 UnnamedAddr
= getDecodedUnnamedAddrType(Record
[9]);
3034 Func
->setUnnamedAddr(UnnamedAddr
);
3035 if (Record
.size() > 10 && Record
[10] != 0)
3036 FunctionPrologues
.push_back(std::make_pair(Func
, Record
[10] - 1));
3038 if (Record
.size() > 11)
3039 Func
->setDLLStorageClass(getDecodedDLLStorageClass(Record
[11]));
3041 upgradeDLLImportExportLinkage(Func
, RawLinkage
);
3043 if (Record
.size() > 12) {
3044 if (unsigned ComdatID
= Record
[12]) {
3045 if (ComdatID
> ComdatList
.size())
3046 return error("Invalid function comdat ID");
3047 Func
->setComdat(ComdatList
[ComdatID
- 1]);
3049 } else if (hasImplicitComdat(RawLinkage
)) {
3050 Func
->setComdat(reinterpret_cast<Comdat
*>(1));
3053 if (Record
.size() > 13 && Record
[13] != 0)
3054 FunctionPrefixes
.push_back(std::make_pair(Func
, Record
[13] - 1));
3056 if (Record
.size() > 14 && Record
[14] != 0)
3057 FunctionPersonalityFns
.push_back(std::make_pair(Func
, Record
[14] - 1));
3059 if (Record
.size() > 15) {
3060 Func
->setDSOLocal(getDecodedDSOLocal(Record
[15]));
3062 inferDSOLocal(Func
);
3064 ValueList
.push_back(Func
);
3066 // If this is a function with a body, remember the prototype we are
3067 // creating now, so that we can match up the body with them later.
3069 Func
->setIsMaterializable(true);
3070 FunctionsWithBodies
.push_back(Func
);
3071 DeferredFunctionInfo
[Func
] = 0;
3073 return Error::success();
3076 Error
BitcodeReader::parseGlobalIndirectSymbolRecord(
3077 unsigned BitCode
, ArrayRef
<uint64_t> Record
) {
3078 // v1 ALIAS_OLD: [alias type, aliasee val#, linkage] (name in VST)
3079 // v1 ALIAS: [alias type, addrspace, aliasee val#, linkage, visibility,
3080 // dllstorageclass, threadlocal, unnamed_addr,
3081 // preemption specifier] (name in VST)
3082 // v1 IFUNC: [alias type, addrspace, aliasee val#, linkage,
3083 // visibility, dllstorageclass, threadlocal, unnamed_addr,
3084 // preemption specifier] (name in VST)
3085 // v2: [strtab_offset, strtab_size, v1]
3087 std::tie(Name
, Record
) = readNameFromStrtab(Record
);
3089 bool NewRecord
= BitCode
!= bitc::MODULE_CODE_ALIAS_OLD
;
3090 if (Record
.size() < (3 + (unsigned)NewRecord
))
3091 return error("Invalid record");
3093 Type
*Ty
= getTypeByID(Record
[OpNum
++]);
3095 return error("Invalid record");
3099 auto *PTy
= dyn_cast
<PointerType
>(Ty
);
3101 return error("Invalid type for value");
3102 Ty
= PTy
->getElementType();
3103 AddrSpace
= PTy
->getAddressSpace();
3105 AddrSpace
= Record
[OpNum
++];
3108 auto Val
= Record
[OpNum
++];
3109 auto Linkage
= Record
[OpNum
++];
3110 GlobalIndirectSymbol
*NewGA
;
3111 if (BitCode
== bitc::MODULE_CODE_ALIAS
||
3112 BitCode
== bitc::MODULE_CODE_ALIAS_OLD
)
3113 NewGA
= GlobalAlias::create(Ty
, AddrSpace
, getDecodedLinkage(Linkage
), Name
,
3116 NewGA
= GlobalIFunc::create(Ty
, AddrSpace
, getDecodedLinkage(Linkage
), Name
,
3117 nullptr, TheModule
);
3118 // Old bitcode files didn't have visibility field.
3119 // Local linkage must have default visibility.
3120 if (OpNum
!= Record
.size()) {
3121 auto VisInd
= OpNum
++;
3122 if (!NewGA
->hasLocalLinkage())
3123 // FIXME: Change to an error if non-default in 4.0.
3124 NewGA
->setVisibility(getDecodedVisibility(Record
[VisInd
]));
3126 if (BitCode
== bitc::MODULE_CODE_ALIAS
||
3127 BitCode
== bitc::MODULE_CODE_ALIAS_OLD
) {
3128 if (OpNum
!= Record
.size())
3129 NewGA
->setDLLStorageClass(getDecodedDLLStorageClass(Record
[OpNum
++]));
3131 upgradeDLLImportExportLinkage(NewGA
, Linkage
);
3132 if (OpNum
!= Record
.size())
3133 NewGA
->setThreadLocalMode(getDecodedThreadLocalMode(Record
[OpNum
++]));
3134 if (OpNum
!= Record
.size())
3135 NewGA
->setUnnamedAddr(getDecodedUnnamedAddrType(Record
[OpNum
++]));
3137 if (OpNum
!= Record
.size())
3138 NewGA
->setDSOLocal(getDecodedDSOLocal(Record
[OpNum
++]));
3139 inferDSOLocal(NewGA
);
3141 ValueList
.push_back(NewGA
);
3142 IndirectSymbolInits
.push_back(std::make_pair(NewGA
, Val
));
3143 return Error::success();
3146 Error
BitcodeReader::parseModule(uint64_t ResumeBit
,
3147 bool ShouldLazyLoadMetadata
) {
3149 Stream
.JumpToBit(ResumeBit
);
3150 else if (Stream
.EnterSubBlock(bitc::MODULE_BLOCK_ID
))
3151 return error("Invalid record");
3153 SmallVector
<uint64_t, 64> Record
;
3155 // Read all the records for this module.
3157 BitstreamEntry Entry
= Stream
.advance();
3159 switch (Entry
.Kind
) {
3160 case BitstreamEntry::Error
:
3161 return error("Malformed block");
3162 case BitstreamEntry::EndBlock
:
3163 return globalCleanup();
3165 case BitstreamEntry::SubBlock
:
3167 default: // Skip unknown content.
3168 if (Stream
.SkipBlock())
3169 return error("Invalid record");
3171 case bitc::BLOCKINFO_BLOCK_ID
:
3172 if (readBlockInfo())
3173 return error("Malformed block");
3175 case bitc::PARAMATTR_BLOCK_ID
:
3176 if (Error Err
= parseAttributeBlock())
3179 case bitc::PARAMATTR_GROUP_BLOCK_ID
:
3180 if (Error Err
= parseAttributeGroupBlock())
3183 case bitc::TYPE_BLOCK_ID_NEW
:
3184 if (Error Err
= parseTypeTable())
3187 case bitc::VALUE_SYMTAB_BLOCK_ID
:
3188 if (!SeenValueSymbolTable
) {
3189 // Either this is an old form VST without function index and an
3190 // associated VST forward declaration record (which would have caused
3191 // the VST to be jumped to and parsed before it was encountered
3192 // normally in the stream), or there were no function blocks to
3193 // trigger an earlier parsing of the VST.
3194 assert(VSTOffset
== 0 || FunctionsWithBodies
.empty());
3195 if (Error Err
= parseValueSymbolTable())
3197 SeenValueSymbolTable
= true;
3199 // We must have had a VST forward declaration record, which caused
3200 // the parser to jump to and parse the VST earlier.
3201 assert(VSTOffset
> 0);
3202 if (Stream
.SkipBlock())
3203 return error("Invalid record");
3206 case bitc::CONSTANTS_BLOCK_ID
:
3207 if (Error Err
= parseConstants())
3209 if (Error Err
= resolveGlobalAndIndirectSymbolInits())
3212 case bitc::METADATA_BLOCK_ID
:
3213 if (ShouldLazyLoadMetadata
) {
3214 if (Error Err
= rememberAndSkipMetadata())
3218 assert(DeferredMetadataInfo
.empty() && "Unexpected deferred metadata");
3219 if (Error Err
= MDLoader
->parseModuleMetadata())
3222 case bitc::METADATA_KIND_BLOCK_ID
:
3223 if (Error Err
= MDLoader
->parseMetadataKinds())
3226 case bitc::FUNCTION_BLOCK_ID
:
3227 // If this is the first function body we've seen, reverse the
3228 // FunctionsWithBodies list.
3229 if (!SeenFirstFunctionBody
) {
3230 std::reverse(FunctionsWithBodies
.begin(), FunctionsWithBodies
.end());
3231 if (Error Err
= globalCleanup())
3233 SeenFirstFunctionBody
= true;
3236 if (VSTOffset
> 0) {
3237 // If we have a VST forward declaration record, make sure we
3238 // parse the VST now if we haven't already. It is needed to
3239 // set up the DeferredFunctionInfo vector for lazy reading.
3240 if (!SeenValueSymbolTable
) {
3241 if (Error Err
= BitcodeReader::parseValueSymbolTable(VSTOffset
))
3243 SeenValueSymbolTable
= true;
3244 // Fall through so that we record the NextUnreadBit below.
3245 // This is necessary in case we have an anonymous function that
3246 // is later materialized. Since it will not have a VST entry we
3247 // need to fall back to the lazy parse to find its offset.
3249 // If we have a VST forward declaration record, but have already
3250 // parsed the VST (just above, when the first function body was
3251 // encountered here), then we are resuming the parse after
3252 // materializing functions. The ResumeBit points to the
3253 // start of the last function block recorded in the
3254 // DeferredFunctionInfo map. Skip it.
3255 if (Stream
.SkipBlock())
3256 return error("Invalid record");
3261 // Support older bitcode files that did not have the function
3262 // index in the VST, nor a VST forward declaration record, as
3263 // well as anonymous functions that do not have VST entries.
3264 // Build the DeferredFunctionInfo vector on the fly.
3265 if (Error Err
= rememberAndSkipFunctionBody())
3268 // Suspend parsing when we reach the function bodies. Subsequent
3269 // materialization calls will resume it when necessary. If the bitcode
3270 // file is old, the symbol table will be at the end instead and will not
3271 // have been seen yet. In this case, just finish the parse now.
3272 if (SeenValueSymbolTable
) {
3273 NextUnreadBit
= Stream
.GetCurrentBitNo();
3274 // After the VST has been parsed, we need to make sure intrinsic name
3275 // are auto-upgraded.
3276 return globalCleanup();
3279 case bitc::USELIST_BLOCK_ID
:
3280 if (Error Err
= parseUseLists())
3283 case bitc::OPERAND_BUNDLE_TAGS_BLOCK_ID
:
3284 if (Error Err
= parseOperandBundleTags())
3287 case bitc::SYNC_SCOPE_NAMES_BLOCK_ID
:
3288 if (Error Err
= parseSyncScopeNames())
3294 case BitstreamEntry::Record
:
3295 // The interesting case.
3300 auto BitCode
= Stream
.readRecord(Entry
.ID
, Record
);
3302 default: break; // Default behavior, ignore unknown content.
3303 case bitc::MODULE_CODE_VERSION
: {
3304 Expected
<unsigned> VersionOrErr
= parseVersionRecord(Record
);
3306 return VersionOrErr
.takeError();
3307 UseRelativeIDs
= *VersionOrErr
>= 1;
3310 case bitc::MODULE_CODE_TRIPLE
: { // TRIPLE: [strchr x N]
3312 if (convertToString(Record
, 0, S
))
3313 return error("Invalid record");
3314 TheModule
->setTargetTriple(S
);
3317 case bitc::MODULE_CODE_DATALAYOUT
: { // DATALAYOUT: [strchr x N]
3319 if (convertToString(Record
, 0, S
))
3320 return error("Invalid record");
3321 TheModule
->setDataLayout(S
);
3324 case bitc::MODULE_CODE_ASM
: { // ASM: [strchr x N]
3326 if (convertToString(Record
, 0, S
))
3327 return error("Invalid record");
3328 TheModule
->setModuleInlineAsm(S
);
3331 case bitc::MODULE_CODE_DEPLIB
: { // DEPLIB: [strchr x N]
3332 // FIXME: Remove in 4.0.
3334 if (convertToString(Record
, 0, S
))
3335 return error("Invalid record");
3339 case bitc::MODULE_CODE_SECTIONNAME
: { // SECTIONNAME: [strchr x N]
3341 if (convertToString(Record
, 0, S
))
3342 return error("Invalid record");
3343 SectionTable
.push_back(S
);
3346 case bitc::MODULE_CODE_GCNAME
: { // SECTIONNAME: [strchr x N]
3348 if (convertToString(Record
, 0, S
))
3349 return error("Invalid record");
3350 GCTable
.push_back(S
);
3353 case bitc::MODULE_CODE_COMDAT
:
3354 if (Error Err
= parseComdatRecord(Record
))
3357 case bitc::MODULE_CODE_GLOBALVAR
:
3358 if (Error Err
= parseGlobalVarRecord(Record
))
3361 case bitc::MODULE_CODE_FUNCTION
:
3362 if (Error Err
= parseFunctionRecord(Record
))
3365 case bitc::MODULE_CODE_IFUNC
:
3366 case bitc::MODULE_CODE_ALIAS
:
3367 case bitc::MODULE_CODE_ALIAS_OLD
:
3368 if (Error Err
= parseGlobalIndirectSymbolRecord(BitCode
, Record
))
3371 /// MODULE_CODE_VSTOFFSET: [offset]
3372 case bitc::MODULE_CODE_VSTOFFSET
:
3373 if (Record
.size() < 1)
3374 return error("Invalid record");
3375 // Note that we subtract 1 here because the offset is relative to one word
3376 // before the start of the identification or module block, which was
3377 // historically always the start of the regular bitcode header.
3378 VSTOffset
= Record
[0] - 1;
3380 /// MODULE_CODE_SOURCE_FILENAME: [namechar x N]
3381 case bitc::MODULE_CODE_SOURCE_FILENAME
:
3382 SmallString
<128> ValueName
;
3383 if (convertToString(Record
, 0, ValueName
))
3384 return error("Invalid record");
3385 TheModule
->setSourceFileName(ValueName
);
3392 Error
BitcodeReader::parseBitcodeInto(Module
*M
, bool ShouldLazyLoadMetadata
,
3395 MDLoader
= MetadataLoader(Stream
, *M
, ValueList
, IsImporting
,
3396 [&](unsigned ID
) { return getTypeByID(ID
); });
3397 return parseModule(0, ShouldLazyLoadMetadata
);
3400 Error
BitcodeReader::typeCheckLoadStoreInst(Type
*ValType
, Type
*PtrType
) {
3401 if (!isa
<PointerType
>(PtrType
))
3402 return error("Load/Store operand is not a pointer type");
3403 Type
*ElemType
= cast
<PointerType
>(PtrType
)->getElementType();
3405 if (ValType
&& ValType
!= ElemType
)
3406 return error("Explicit load/store type does not match pointee "
3407 "type of pointer operand");
3408 if (!PointerType::isLoadableOrStorableType(ElemType
))
3409 return error("Cannot load/store from pointer");
3410 return Error::success();
3413 /// Lazily parse the specified function body block.
3414 Error
BitcodeReader::parseFunctionBody(Function
*F
) {
3415 if (Stream
.EnterSubBlock(bitc::FUNCTION_BLOCK_ID
))
3416 return error("Invalid record");
3418 // Unexpected unresolved metadata when parsing function.
3419 if (MDLoader
->hasFwdRefs())
3420 return error("Invalid function metadata: incoming forward references");
3422 InstructionList
.clear();
3423 unsigned ModuleValueListSize
= ValueList
.size();
3424 unsigned ModuleMDLoaderSize
= MDLoader
->size();
3426 // Add all the function arguments to the value table.
3427 for (Argument
&I
: F
->args())
3428 ValueList
.push_back(&I
);
3430 unsigned NextValueNo
= ValueList
.size();
3431 BasicBlock
*CurBB
= nullptr;
3432 unsigned CurBBNo
= 0;
3435 auto getLastInstruction
= [&]() -> Instruction
* {
3436 if (CurBB
&& !CurBB
->empty())
3437 return &CurBB
->back();
3438 else if (CurBBNo
&& FunctionBBs
[CurBBNo
- 1] &&
3439 !FunctionBBs
[CurBBNo
- 1]->empty())
3440 return &FunctionBBs
[CurBBNo
- 1]->back();
3444 std::vector
<OperandBundleDef
> OperandBundles
;
3446 // Read all the records.
3447 SmallVector
<uint64_t, 64> Record
;
3450 BitstreamEntry Entry
= Stream
.advance();
3452 switch (Entry
.Kind
) {
3453 case BitstreamEntry::Error
:
3454 return error("Malformed block");
3455 case BitstreamEntry::EndBlock
:
3456 goto OutOfRecordLoop
;
3458 case BitstreamEntry::SubBlock
:
3460 default: // Skip unknown content.
3461 if (Stream
.SkipBlock())
3462 return error("Invalid record");
3464 case bitc::CONSTANTS_BLOCK_ID
:
3465 if (Error Err
= parseConstants())
3467 NextValueNo
= ValueList
.size();
3469 case bitc::VALUE_SYMTAB_BLOCK_ID
:
3470 if (Error Err
= parseValueSymbolTable())
3473 case bitc::METADATA_ATTACHMENT_ID
:
3474 if (Error Err
= MDLoader
->parseMetadataAttachment(*F
, InstructionList
))
3477 case bitc::METADATA_BLOCK_ID
:
3478 assert(DeferredMetadataInfo
.empty() &&
3479 "Must read all module-level metadata before function-level");
3480 if (Error Err
= MDLoader
->parseFunctionMetadata())
3483 case bitc::USELIST_BLOCK_ID
:
3484 if (Error Err
= parseUseLists())
3490 case BitstreamEntry::Record
:
3491 // The interesting case.
3497 Instruction
*I
= nullptr;
3498 unsigned BitCode
= Stream
.readRecord(Entry
.ID
, Record
);
3500 default: // Default behavior: reject
3501 return error("Invalid value");
3502 case bitc::FUNC_CODE_DECLAREBLOCKS
: { // DECLAREBLOCKS: [nblocks]
3503 if (Record
.size() < 1 || Record
[0] == 0)
3504 return error("Invalid record");
3505 // Create all the basic blocks for the function.
3506 FunctionBBs
.resize(Record
[0]);
3508 // See if anything took the address of blocks in this function.
3509 auto BBFRI
= BasicBlockFwdRefs
.find(F
);
3510 if (BBFRI
== BasicBlockFwdRefs
.end()) {
3511 for (unsigned i
= 0, e
= FunctionBBs
.size(); i
!= e
; ++i
)
3512 FunctionBBs
[i
] = BasicBlock::Create(Context
, "", F
);
3514 auto &BBRefs
= BBFRI
->second
;
3515 // Check for invalid basic block references.
3516 if (BBRefs
.size() > FunctionBBs
.size())
3517 return error("Invalid ID");
3518 assert(!BBRefs
.empty() && "Unexpected empty array");
3519 assert(!BBRefs
.front() && "Invalid reference to entry block");
3520 for (unsigned I
= 0, E
= FunctionBBs
.size(), RE
= BBRefs
.size(); I
!= E
;
3522 if (I
< RE
&& BBRefs
[I
]) {
3523 BBRefs
[I
]->insertInto(F
);
3524 FunctionBBs
[I
] = BBRefs
[I
];
3526 FunctionBBs
[I
] = BasicBlock::Create(Context
, "", F
);
3529 // Erase from the table.
3530 BasicBlockFwdRefs
.erase(BBFRI
);
3533 CurBB
= FunctionBBs
[0];
3537 case bitc::FUNC_CODE_DEBUG_LOC_AGAIN
: // DEBUG_LOC_AGAIN
3538 // This record indicates that the last instruction is at the same
3539 // location as the previous instruction with a location.
3540 I
= getLastInstruction();
3543 return error("Invalid record");
3544 I
->setDebugLoc(LastLoc
);
3548 case bitc::FUNC_CODE_DEBUG_LOC
: { // DEBUG_LOC: [line, col, scope, ia]
3549 I
= getLastInstruction();
3550 if (!I
|| Record
.size() < 4)
3551 return error("Invalid record");
3553 unsigned Line
= Record
[0], Col
= Record
[1];
3554 unsigned ScopeID
= Record
[2], IAID
= Record
[3];
3555 bool isImplicitCode
= Record
.size() == 5 && Record
[4];
3557 MDNode
*Scope
= nullptr, *IA
= nullptr;
3559 Scope
= dyn_cast_or_null
<MDNode
>(
3560 MDLoader
->getMetadataFwdRefOrLoad(ScopeID
- 1));
3562 return error("Invalid record");
3565 IA
= dyn_cast_or_null
<MDNode
>(
3566 MDLoader
->getMetadataFwdRefOrLoad(IAID
- 1));
3568 return error("Invalid record");
3570 LastLoc
= DebugLoc::get(Line
, Col
, Scope
, IA
, isImplicitCode
);
3571 I
->setDebugLoc(LastLoc
);
3575 case bitc::FUNC_CODE_INST_UNOP
: { // UNOP: [opval, ty, opcode]
3578 if (getValueTypePair(Record
, OpNum
, NextValueNo
, LHS
) ||
3579 OpNum
+1 > Record
.size())
3580 return error("Invalid record");
3582 int Opc
= getDecodedUnaryOpcode(Record
[OpNum
++], LHS
->getType());
3584 return error("Invalid record");
3585 I
= UnaryOperator::Create((Instruction::UnaryOps
)Opc
, LHS
);
3586 InstructionList
.push_back(I
);
3587 if (OpNum
< Record
.size()) {
3588 if (isa
<FPMathOperator
>(I
)) {
3589 FastMathFlags FMF
= getDecodedFastMathFlags(Record
[OpNum
]);
3591 I
->setFastMathFlags(FMF
);
3596 case bitc::FUNC_CODE_INST_BINOP
: { // BINOP: [opval, ty, opval, opcode]
3599 if (getValueTypePair(Record
, OpNum
, NextValueNo
, LHS
) ||
3600 popValue(Record
, OpNum
, NextValueNo
, LHS
->getType(), RHS
) ||
3601 OpNum
+1 > Record
.size())
3602 return error("Invalid record");
3604 int Opc
= getDecodedBinaryOpcode(Record
[OpNum
++], LHS
->getType());
3606 return error("Invalid record");
3607 I
= BinaryOperator::Create((Instruction::BinaryOps
)Opc
, LHS
, RHS
);
3608 InstructionList
.push_back(I
);
3609 if (OpNum
< Record
.size()) {
3610 if (Opc
== Instruction::Add
||
3611 Opc
== Instruction::Sub
||
3612 Opc
== Instruction::Mul
||
3613 Opc
== Instruction::Shl
) {
3614 if (Record
[OpNum
] & (1 << bitc::OBO_NO_SIGNED_WRAP
))
3615 cast
<BinaryOperator
>(I
)->setHasNoSignedWrap(true);
3616 if (Record
[OpNum
] & (1 << bitc::OBO_NO_UNSIGNED_WRAP
))
3617 cast
<BinaryOperator
>(I
)->setHasNoUnsignedWrap(true);
3618 } else if (Opc
== Instruction::SDiv
||
3619 Opc
== Instruction::UDiv
||
3620 Opc
== Instruction::LShr
||
3621 Opc
== Instruction::AShr
) {
3622 if (Record
[OpNum
] & (1 << bitc::PEO_EXACT
))
3623 cast
<BinaryOperator
>(I
)->setIsExact(true);
3624 } else if (isa
<FPMathOperator
>(I
)) {
3625 FastMathFlags FMF
= getDecodedFastMathFlags(Record
[OpNum
]);
3627 I
->setFastMathFlags(FMF
);
3633 case bitc::FUNC_CODE_INST_CAST
: { // CAST: [opval, opty, destty, castopc]
3636 if (getValueTypePair(Record
, OpNum
, NextValueNo
, Op
) ||
3637 OpNum
+2 != Record
.size())
3638 return error("Invalid record");
3640 Type
*ResTy
= getTypeByID(Record
[OpNum
]);
3641 int Opc
= getDecodedCastOpcode(Record
[OpNum
+ 1]);
3642 if (Opc
== -1 || !ResTy
)
3643 return error("Invalid record");
3644 Instruction
*Temp
= nullptr;
3645 if ((I
= UpgradeBitCastInst(Opc
, Op
, ResTy
, Temp
))) {
3647 InstructionList
.push_back(Temp
);
3648 CurBB
->getInstList().push_back(Temp
);
3651 auto CastOp
= (Instruction::CastOps
)Opc
;
3652 if (!CastInst::castIsValid(CastOp
, Op
, ResTy
))
3653 return error("Invalid cast");
3654 I
= CastInst::Create(CastOp
, Op
, ResTy
);
3656 InstructionList
.push_back(I
);
3659 case bitc::FUNC_CODE_INST_INBOUNDS_GEP_OLD
:
3660 case bitc::FUNC_CODE_INST_GEP_OLD
:
3661 case bitc::FUNC_CODE_INST_GEP
: { // GEP: type, [n x operands]
3667 if (BitCode
== bitc::FUNC_CODE_INST_GEP
) {
3668 InBounds
= Record
[OpNum
++];
3669 Ty
= getTypeByID(Record
[OpNum
++]);
3671 InBounds
= BitCode
== bitc::FUNC_CODE_INST_INBOUNDS_GEP_OLD
;
3676 if (getValueTypePair(Record
, OpNum
, NextValueNo
, BasePtr
))
3677 return error("Invalid record");
3680 Ty
= cast
<PointerType
>(BasePtr
->getType()->getScalarType())
3683 cast
<PointerType
>(BasePtr
->getType()->getScalarType())
3686 "Explicit gep type does not match pointee type of pointer operand");
3688 SmallVector
<Value
*, 16> GEPIdx
;
3689 while (OpNum
!= Record
.size()) {
3691 if (getValueTypePair(Record
, OpNum
, NextValueNo
, Op
))
3692 return error("Invalid record");
3693 GEPIdx
.push_back(Op
);
3696 I
= GetElementPtrInst::Create(Ty
, BasePtr
, GEPIdx
);
3698 InstructionList
.push_back(I
);
3700 cast
<GetElementPtrInst
>(I
)->setIsInBounds(true);
3704 case bitc::FUNC_CODE_INST_EXTRACTVAL
: {
3705 // EXTRACTVAL: [opty, opval, n x indices]
3708 if (getValueTypePair(Record
, OpNum
, NextValueNo
, Agg
))
3709 return error("Invalid record");
3711 unsigned RecSize
= Record
.size();
3712 if (OpNum
== RecSize
)
3713 return error("EXTRACTVAL: Invalid instruction with 0 indices");
3715 SmallVector
<unsigned, 4> EXTRACTVALIdx
;
3716 Type
*CurTy
= Agg
->getType();
3717 for (; OpNum
!= RecSize
; ++OpNum
) {
3718 bool IsArray
= CurTy
->isArrayTy();
3719 bool IsStruct
= CurTy
->isStructTy();
3720 uint64_t Index
= Record
[OpNum
];
3722 if (!IsStruct
&& !IsArray
)
3723 return error("EXTRACTVAL: Invalid type");
3724 if ((unsigned)Index
!= Index
)
3725 return error("Invalid value");
3726 if (IsStruct
&& Index
>= CurTy
->getStructNumElements())
3727 return error("EXTRACTVAL: Invalid struct index");
3728 if (IsArray
&& Index
>= CurTy
->getArrayNumElements())
3729 return error("EXTRACTVAL: Invalid array index");
3730 EXTRACTVALIdx
.push_back((unsigned)Index
);
3733 CurTy
= CurTy
->getStructElementType(Index
);
3735 CurTy
= CurTy
->getArrayElementType();
3738 I
= ExtractValueInst::Create(Agg
, EXTRACTVALIdx
);
3739 InstructionList
.push_back(I
);
3743 case bitc::FUNC_CODE_INST_INSERTVAL
: {
3744 // INSERTVAL: [opty, opval, opty, opval, n x indices]
3747 if (getValueTypePair(Record
, OpNum
, NextValueNo
, Agg
))
3748 return error("Invalid record");
3750 if (getValueTypePair(Record
, OpNum
, NextValueNo
, Val
))
3751 return error("Invalid record");
3753 unsigned RecSize
= Record
.size();
3754 if (OpNum
== RecSize
)
3755 return error("INSERTVAL: Invalid instruction with 0 indices");
3757 SmallVector
<unsigned, 4> INSERTVALIdx
;
3758 Type
*CurTy
= Agg
->getType();
3759 for (; OpNum
!= RecSize
; ++OpNum
) {
3760 bool IsArray
= CurTy
->isArrayTy();
3761 bool IsStruct
= CurTy
->isStructTy();
3762 uint64_t Index
= Record
[OpNum
];
3764 if (!IsStruct
&& !IsArray
)
3765 return error("INSERTVAL: Invalid type");
3766 if ((unsigned)Index
!= Index
)
3767 return error("Invalid value");
3768 if (IsStruct
&& Index
>= CurTy
->getStructNumElements())
3769 return error("INSERTVAL: Invalid struct index");
3770 if (IsArray
&& Index
>= CurTy
->getArrayNumElements())
3771 return error("INSERTVAL: Invalid array index");
3773 INSERTVALIdx
.push_back((unsigned)Index
);
3775 CurTy
= CurTy
->getStructElementType(Index
);
3777 CurTy
= CurTy
->getArrayElementType();
3780 if (CurTy
!= Val
->getType())
3781 return error("Inserted value type doesn't match aggregate type");
3783 I
= InsertValueInst::Create(Agg
, Val
, INSERTVALIdx
);
3784 InstructionList
.push_back(I
);
3788 case bitc::FUNC_CODE_INST_SELECT
: { // SELECT: [opval, ty, opval, opval]
3789 // obsolete form of select
3790 // handles select i1 ... in old bitcode
3792 Value
*TrueVal
, *FalseVal
, *Cond
;
3793 if (getValueTypePair(Record
, OpNum
, NextValueNo
, TrueVal
) ||
3794 popValue(Record
, OpNum
, NextValueNo
, TrueVal
->getType(), FalseVal
) ||
3795 popValue(Record
, OpNum
, NextValueNo
, Type::getInt1Ty(Context
), Cond
))
3796 return error("Invalid record");
3798 I
= SelectInst::Create(Cond
, TrueVal
, FalseVal
);
3799 InstructionList
.push_back(I
);
3803 case bitc::FUNC_CODE_INST_VSELECT
: {// VSELECT: [ty,opval,opval,predty,pred]
3804 // new form of select
3805 // handles select i1 or select [N x i1]
3807 Value
*TrueVal
, *FalseVal
, *Cond
;
3808 if (getValueTypePair(Record
, OpNum
, NextValueNo
, TrueVal
) ||
3809 popValue(Record
, OpNum
, NextValueNo
, TrueVal
->getType(), FalseVal
) ||
3810 getValueTypePair(Record
, OpNum
, NextValueNo
, Cond
))
3811 return error("Invalid record");
3813 // select condition can be either i1 or [N x i1]
3814 if (VectorType
* vector_type
=
3815 dyn_cast
<VectorType
>(Cond
->getType())) {
3817 if (vector_type
->getElementType() != Type::getInt1Ty(Context
))
3818 return error("Invalid type for value");
3821 if (Cond
->getType() != Type::getInt1Ty(Context
))
3822 return error("Invalid type for value");
3825 I
= SelectInst::Create(Cond
, TrueVal
, FalseVal
);
3826 InstructionList
.push_back(I
);
3830 case bitc::FUNC_CODE_INST_EXTRACTELT
: { // EXTRACTELT: [opty, opval, opval]
3833 if (getValueTypePair(Record
, OpNum
, NextValueNo
, Vec
) ||
3834 getValueTypePair(Record
, OpNum
, NextValueNo
, Idx
))
3835 return error("Invalid record");
3836 if (!Vec
->getType()->isVectorTy())
3837 return error("Invalid type for value");
3838 I
= ExtractElementInst::Create(Vec
, Idx
);
3839 InstructionList
.push_back(I
);
3843 case bitc::FUNC_CODE_INST_INSERTELT
: { // INSERTELT: [ty, opval,opval,opval]
3845 Value
*Vec
, *Elt
, *Idx
;
3846 if (getValueTypePair(Record
, OpNum
, NextValueNo
, Vec
))
3847 return error("Invalid record");
3848 if (!Vec
->getType()->isVectorTy())
3849 return error("Invalid type for value");
3850 if (popValue(Record
, OpNum
, NextValueNo
,
3851 cast
<VectorType
>(Vec
->getType())->getElementType(), Elt
) ||
3852 getValueTypePair(Record
, OpNum
, NextValueNo
, Idx
))
3853 return error("Invalid record");
3854 I
= InsertElementInst::Create(Vec
, Elt
, Idx
);
3855 InstructionList
.push_back(I
);
3859 case bitc::FUNC_CODE_INST_SHUFFLEVEC
: {// SHUFFLEVEC: [opval,ty,opval,opval]
3861 Value
*Vec1
, *Vec2
, *Mask
;
3862 if (getValueTypePair(Record
, OpNum
, NextValueNo
, Vec1
) ||
3863 popValue(Record
, OpNum
, NextValueNo
, Vec1
->getType(), Vec2
))
3864 return error("Invalid record");
3866 if (getValueTypePair(Record
, OpNum
, NextValueNo
, Mask
))
3867 return error("Invalid record");
3868 if (!Vec1
->getType()->isVectorTy() || !Vec2
->getType()->isVectorTy())
3869 return error("Invalid type for value");
3870 I
= new ShuffleVectorInst(Vec1
, Vec2
, Mask
);
3871 InstructionList
.push_back(I
);
3875 case bitc::FUNC_CODE_INST_CMP
: // CMP: [opty, opval, opval, pred]
3876 // Old form of ICmp/FCmp returning bool
3877 // Existed to differentiate between icmp/fcmp and vicmp/vfcmp which were
3878 // both legal on vectors but had different behaviour.
3879 case bitc::FUNC_CODE_INST_CMP2
: { // CMP2: [opty, opval, opval, pred]
3880 // FCmp/ICmp returning bool or vector of bool
3884 if (getValueTypePair(Record
, OpNum
, NextValueNo
, LHS
) ||
3885 popValue(Record
, OpNum
, NextValueNo
, LHS
->getType(), RHS
))
3886 return error("Invalid record");
3888 unsigned PredVal
= Record
[OpNum
];
3889 bool IsFP
= LHS
->getType()->isFPOrFPVectorTy();
3891 if (IsFP
&& Record
.size() > OpNum
+1)
3892 FMF
= getDecodedFastMathFlags(Record
[++OpNum
]);
3894 if (OpNum
+1 != Record
.size())
3895 return error("Invalid record");
3897 if (LHS
->getType()->isFPOrFPVectorTy())
3898 I
= new FCmpInst((FCmpInst::Predicate
)PredVal
, LHS
, RHS
);
3900 I
= new ICmpInst((ICmpInst::Predicate
)PredVal
, LHS
, RHS
);
3903 I
->setFastMathFlags(FMF
);
3904 InstructionList
.push_back(I
);
3908 case bitc::FUNC_CODE_INST_RET
: // RET: [opty,opval<optional>]
3910 unsigned Size
= Record
.size();
3912 I
= ReturnInst::Create(Context
);
3913 InstructionList
.push_back(I
);
3918 Value
*Op
= nullptr;
3919 if (getValueTypePair(Record
, OpNum
, NextValueNo
, Op
))
3920 return error("Invalid record");
3921 if (OpNum
!= Record
.size())
3922 return error("Invalid record");
3924 I
= ReturnInst::Create(Context
, Op
);
3925 InstructionList
.push_back(I
);
3928 case bitc::FUNC_CODE_INST_BR
: { // BR: [bb#, bb#, opval] or [bb#]
3929 if (Record
.size() != 1 && Record
.size() != 3)
3930 return error("Invalid record");
3931 BasicBlock
*TrueDest
= getBasicBlock(Record
[0]);
3933 return error("Invalid record");
3935 if (Record
.size() == 1) {
3936 I
= BranchInst::Create(TrueDest
);
3937 InstructionList
.push_back(I
);
3940 BasicBlock
*FalseDest
= getBasicBlock(Record
[1]);
3941 Value
*Cond
= getValue(Record
, 2, NextValueNo
,
3942 Type::getInt1Ty(Context
));
3943 if (!FalseDest
|| !Cond
)
3944 return error("Invalid record");
3945 I
= BranchInst::Create(TrueDest
, FalseDest
, Cond
);
3946 InstructionList
.push_back(I
);
3950 case bitc::FUNC_CODE_INST_CLEANUPRET
: { // CLEANUPRET: [val] or [val,bb#]
3951 if (Record
.size() != 1 && Record
.size() != 2)
3952 return error("Invalid record");
3955 getValue(Record
, Idx
++, NextValueNo
, Type::getTokenTy(Context
));
3957 return error("Invalid record");
3958 BasicBlock
*UnwindDest
= nullptr;
3959 if (Record
.size() == 2) {
3960 UnwindDest
= getBasicBlock(Record
[Idx
++]);
3962 return error("Invalid record");
3965 I
= CleanupReturnInst::Create(CleanupPad
, UnwindDest
);
3966 InstructionList
.push_back(I
);
3969 case bitc::FUNC_CODE_INST_CATCHRET
: { // CATCHRET: [val,bb#]
3970 if (Record
.size() != 2)
3971 return error("Invalid record");
3974 getValue(Record
, Idx
++, NextValueNo
, Type::getTokenTy(Context
));
3976 return error("Invalid record");
3977 BasicBlock
*BB
= getBasicBlock(Record
[Idx
++]);
3979 return error("Invalid record");
3981 I
= CatchReturnInst::Create(CatchPad
, BB
);
3982 InstructionList
.push_back(I
);
3985 case bitc::FUNC_CODE_INST_CATCHSWITCH
: { // CATCHSWITCH: [tok,num,(bb)*,bb?]
3986 // We must have, at minimum, the outer scope and the number of arguments.
3987 if (Record
.size() < 2)
3988 return error("Invalid record");
3993 getValue(Record
, Idx
++, NextValueNo
, Type::getTokenTy(Context
));
3995 unsigned NumHandlers
= Record
[Idx
++];
3997 SmallVector
<BasicBlock
*, 2> Handlers
;
3998 for (unsigned Op
= 0; Op
!= NumHandlers
; ++Op
) {
3999 BasicBlock
*BB
= getBasicBlock(Record
[Idx
++]);
4001 return error("Invalid record");
4002 Handlers
.push_back(BB
);
4005 BasicBlock
*UnwindDest
= nullptr;
4006 if (Idx
+ 1 == Record
.size()) {
4007 UnwindDest
= getBasicBlock(Record
[Idx
++]);
4009 return error("Invalid record");
4012 if (Record
.size() != Idx
)
4013 return error("Invalid record");
4016 CatchSwitchInst::Create(ParentPad
, UnwindDest
, NumHandlers
);
4017 for (BasicBlock
*Handler
: Handlers
)
4018 CatchSwitch
->addHandler(Handler
);
4020 InstructionList
.push_back(I
);
4023 case bitc::FUNC_CODE_INST_CATCHPAD
:
4024 case bitc::FUNC_CODE_INST_CLEANUPPAD
: { // [tok,num,(ty,val)*]
4025 // We must have, at minimum, the outer scope and the number of arguments.
4026 if (Record
.size() < 2)
4027 return error("Invalid record");
4032 getValue(Record
, Idx
++, NextValueNo
, Type::getTokenTy(Context
));
4034 unsigned NumArgOperands
= Record
[Idx
++];
4036 SmallVector
<Value
*, 2> Args
;
4037 for (unsigned Op
= 0; Op
!= NumArgOperands
; ++Op
) {
4039 if (getValueTypePair(Record
, Idx
, NextValueNo
, Val
))
4040 return error("Invalid record");
4041 Args
.push_back(Val
);
4044 if (Record
.size() != Idx
)
4045 return error("Invalid record");
4047 if (BitCode
== bitc::FUNC_CODE_INST_CLEANUPPAD
)
4048 I
= CleanupPadInst::Create(ParentPad
, Args
);
4050 I
= CatchPadInst::Create(ParentPad
, Args
);
4051 InstructionList
.push_back(I
);
4054 case bitc::FUNC_CODE_INST_SWITCH
: { // SWITCH: [opty, op0, op1, ...]
4056 if ((Record
[0] >> 16) == SWITCH_INST_MAGIC
) {
4057 // "New" SwitchInst format with case ranges. The changes to write this
4058 // format were reverted but we still recognize bitcode that uses it.
4059 // Hopefully someday we will have support for case ranges and can use
4060 // this format again.
4062 Type
*OpTy
= getTypeByID(Record
[1]);
4063 unsigned ValueBitWidth
= cast
<IntegerType
>(OpTy
)->getBitWidth();
4065 Value
*Cond
= getValue(Record
, 2, NextValueNo
, OpTy
);
4066 BasicBlock
*Default
= getBasicBlock(Record
[3]);
4067 if (!OpTy
|| !Cond
|| !Default
)
4068 return error("Invalid record");
4070 unsigned NumCases
= Record
[4];
4072 SwitchInst
*SI
= SwitchInst::Create(Cond
, Default
, NumCases
);
4073 InstructionList
.push_back(SI
);
4075 unsigned CurIdx
= 5;
4076 for (unsigned i
= 0; i
!= NumCases
; ++i
) {
4077 SmallVector
<ConstantInt
*, 1> CaseVals
;
4078 unsigned NumItems
= Record
[CurIdx
++];
4079 for (unsigned ci
= 0; ci
!= NumItems
; ++ci
) {
4080 bool isSingleNumber
= Record
[CurIdx
++];
4083 unsigned ActiveWords
= 1;
4084 if (ValueBitWidth
> 64)
4085 ActiveWords
= Record
[CurIdx
++];
4086 Low
= readWideAPInt(makeArrayRef(&Record
[CurIdx
], ActiveWords
),
4088 CurIdx
+= ActiveWords
;
4090 if (!isSingleNumber
) {
4092 if (ValueBitWidth
> 64)
4093 ActiveWords
= Record
[CurIdx
++];
4094 APInt High
= readWideAPInt(
4095 makeArrayRef(&Record
[CurIdx
], ActiveWords
), ValueBitWidth
);
4096 CurIdx
+= ActiveWords
;
4098 // FIXME: It is not clear whether values in the range should be
4099 // compared as signed or unsigned values. The partially
4100 // implemented changes that used this format in the past used
4101 // unsigned comparisons.
4102 for ( ; Low
.ule(High
); ++Low
)
4103 CaseVals
.push_back(ConstantInt::get(Context
, Low
));
4105 CaseVals
.push_back(ConstantInt::get(Context
, Low
));
4107 BasicBlock
*DestBB
= getBasicBlock(Record
[CurIdx
++]);
4108 for (SmallVector
<ConstantInt
*, 1>::iterator cvi
= CaseVals
.begin(),
4109 cve
= CaseVals
.end(); cvi
!= cve
; ++cvi
)
4110 SI
->addCase(*cvi
, DestBB
);
4116 // Old SwitchInst format without case ranges.
4118 if (Record
.size() < 3 || (Record
.size() & 1) == 0)
4119 return error("Invalid record");
4120 Type
*OpTy
= getTypeByID(Record
[0]);
4121 Value
*Cond
= getValue(Record
, 1, NextValueNo
, OpTy
);
4122 BasicBlock
*Default
= getBasicBlock(Record
[2]);
4123 if (!OpTy
|| !Cond
|| !Default
)
4124 return error("Invalid record");
4125 unsigned NumCases
= (Record
.size()-3)/2;
4126 SwitchInst
*SI
= SwitchInst::Create(Cond
, Default
, NumCases
);
4127 InstructionList
.push_back(SI
);
4128 for (unsigned i
= 0, e
= NumCases
; i
!= e
; ++i
) {
4129 ConstantInt
*CaseVal
=
4130 dyn_cast_or_null
<ConstantInt
>(getFnValueByID(Record
[3+i
*2], OpTy
));
4131 BasicBlock
*DestBB
= getBasicBlock(Record
[1+3+i
*2]);
4132 if (!CaseVal
|| !DestBB
) {
4134 return error("Invalid record");
4136 SI
->addCase(CaseVal
, DestBB
);
4141 case bitc::FUNC_CODE_INST_INDIRECTBR
: { // INDIRECTBR: [opty, op0, op1, ...]
4142 if (Record
.size() < 2)
4143 return error("Invalid record");
4144 Type
*OpTy
= getTypeByID(Record
[0]);
4145 Value
*Address
= getValue(Record
, 1, NextValueNo
, OpTy
);
4146 if (!OpTy
|| !Address
)
4147 return error("Invalid record");
4148 unsigned NumDests
= Record
.size()-2;
4149 IndirectBrInst
*IBI
= IndirectBrInst::Create(Address
, NumDests
);
4150 InstructionList
.push_back(IBI
);
4151 for (unsigned i
= 0, e
= NumDests
; i
!= e
; ++i
) {
4152 if (BasicBlock
*DestBB
= getBasicBlock(Record
[2+i
])) {
4153 IBI
->addDestination(DestBB
);
4156 return error("Invalid record");
4163 case bitc::FUNC_CODE_INST_INVOKE
: {
4164 // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...]
4165 if (Record
.size() < 4)
4166 return error("Invalid record");
4168 AttributeList PAL
= getAttributes(Record
[OpNum
++]);
4169 unsigned CCInfo
= Record
[OpNum
++];
4170 BasicBlock
*NormalBB
= getBasicBlock(Record
[OpNum
++]);
4171 BasicBlock
*UnwindBB
= getBasicBlock(Record
[OpNum
++]);
4173 FunctionType
*FTy
= nullptr;
4174 if (CCInfo
>> 13 & 1 &&
4175 !(FTy
= dyn_cast
<FunctionType
>(getTypeByID(Record
[OpNum
++]))))
4176 return error("Explicit invoke type is not a function type");
4179 if (getValueTypePair(Record
, OpNum
, NextValueNo
, Callee
))
4180 return error("Invalid record");
4182 PointerType
*CalleeTy
= dyn_cast
<PointerType
>(Callee
->getType());
4184 return error("Callee is not a pointer");
4186 FTy
= dyn_cast
<FunctionType
>(CalleeTy
->getElementType());
4188 return error("Callee is not of pointer to function type");
4189 } else if (CalleeTy
->getElementType() != FTy
)
4190 return error("Explicit invoke type does not match pointee type of "
4192 if (Record
.size() < FTy
->getNumParams() + OpNum
)
4193 return error("Insufficient operands to call");
4195 SmallVector
<Value
*, 16> Ops
;
4196 for (unsigned i
= 0, e
= FTy
->getNumParams(); i
!= e
; ++i
, ++OpNum
) {
4197 Ops
.push_back(getValue(Record
, OpNum
, NextValueNo
,
4198 FTy
->getParamType(i
)));
4200 return error("Invalid record");
4203 if (!FTy
->isVarArg()) {
4204 if (Record
.size() != OpNum
)
4205 return error("Invalid record");
4207 // Read type/value pairs for varargs params.
4208 while (OpNum
!= Record
.size()) {
4210 if (getValueTypePair(Record
, OpNum
, NextValueNo
, Op
))
4211 return error("Invalid record");
4216 I
= InvokeInst::Create(FTy
, Callee
, NormalBB
, UnwindBB
, Ops
,
4218 OperandBundles
.clear();
4219 InstructionList
.push_back(I
);
4220 cast
<InvokeInst
>(I
)->setCallingConv(
4221 static_cast<CallingConv::ID
>(CallingConv::MaxID
& CCInfo
));
4222 cast
<InvokeInst
>(I
)->setAttributes(PAL
);
4225 case bitc::FUNC_CODE_INST_RESUME
: { // RESUME: [opval]
4227 Value
*Val
= nullptr;
4228 if (getValueTypePair(Record
, Idx
, NextValueNo
, Val
))
4229 return error("Invalid record");
4230 I
= ResumeInst::Create(Val
);
4231 InstructionList
.push_back(I
);
4234 case bitc::FUNC_CODE_INST_CALLBR
: {
4235 // CALLBR: [attr, cc, norm, transfs, fty, fnid, args]
4237 AttributeList PAL
= getAttributes(Record
[OpNum
++]);
4238 unsigned CCInfo
= Record
[OpNum
++];
4240 BasicBlock
*DefaultDest
= getBasicBlock(Record
[OpNum
++]);
4241 unsigned NumIndirectDests
= Record
[OpNum
++];
4242 SmallVector
<BasicBlock
*, 16> IndirectDests
;
4243 for (unsigned i
= 0, e
= NumIndirectDests
; i
!= e
; ++i
)
4244 IndirectDests
.push_back(getBasicBlock(Record
[OpNum
++]));
4246 FunctionType
*FTy
= nullptr;
4247 if (CCInfo
>> bitc::CALL_EXPLICIT_TYPE
& 1 &&
4248 !(FTy
= dyn_cast
<FunctionType
>(getTypeByID(Record
[OpNum
++]))))
4249 return error("Explicit call type is not a function type");
4252 if (getValueTypePair(Record
, OpNum
, NextValueNo
, Callee
))
4253 return error("Invalid record");
4255 PointerType
*OpTy
= dyn_cast
<PointerType
>(Callee
->getType());
4257 return error("Callee is not a pointer type");
4259 FTy
= dyn_cast
<FunctionType
>(OpTy
->getElementType());
4261 return error("Callee is not of pointer to function type");
4262 } else if (OpTy
->getElementType() != FTy
)
4263 return error("Explicit call type does not match pointee type of "
4265 if (Record
.size() < FTy
->getNumParams() + OpNum
)
4266 return error("Insufficient operands to call");
4268 SmallVector
<Value
*, 16> Args
;
4269 // Read the fixed params.
4270 for (unsigned i
= 0, e
= FTy
->getNumParams(); i
!= e
; ++i
, ++OpNum
) {
4271 if (FTy
->getParamType(i
)->isLabelTy())
4272 Args
.push_back(getBasicBlock(Record
[OpNum
]));
4274 Args
.push_back(getValue(Record
, OpNum
, NextValueNo
,
4275 FTy
->getParamType(i
)));
4277 return error("Invalid record");
4280 // Read type/value pairs for varargs params.
4281 if (!FTy
->isVarArg()) {
4282 if (OpNum
!= Record
.size())
4283 return error("Invalid record");
4285 while (OpNum
!= Record
.size()) {
4287 if (getValueTypePair(Record
, OpNum
, NextValueNo
, Op
))
4288 return error("Invalid record");
4293 I
= CallBrInst::Create(FTy
, Callee
, DefaultDest
, IndirectDests
, Args
,
4295 OperandBundles
.clear();
4296 InstructionList
.push_back(I
);
4297 cast
<CallBrInst
>(I
)->setCallingConv(
4298 static_cast<CallingConv::ID
>((0x7ff & CCInfo
) >> bitc::CALL_CCONV
));
4299 cast
<CallBrInst
>(I
)->setAttributes(PAL
);
4302 case bitc::FUNC_CODE_INST_UNREACHABLE
: // UNREACHABLE
4303 I
= new UnreachableInst(Context
);
4304 InstructionList
.push_back(I
);
4306 case bitc::FUNC_CODE_INST_PHI
: { // PHI: [ty, val0,bb0, ...]
4307 if (Record
.size() < 1 || ((Record
.size()-1)&1))
4308 return error("Invalid record");
4309 Type
*Ty
= getTypeByID(Record
[0]);
4311 return error("Invalid record");
4313 PHINode
*PN
= PHINode::Create(Ty
, (Record
.size()-1)/2);
4314 InstructionList
.push_back(PN
);
4316 for (unsigned i
= 0, e
= Record
.size()-1; i
!= e
; i
+= 2) {
4318 // With the new function encoding, it is possible that operands have
4319 // negative IDs (for forward references). Use a signed VBR
4320 // representation to keep the encoding small.
4322 V
= getValueSigned(Record
, 1+i
, NextValueNo
, Ty
);
4324 V
= getValue(Record
, 1+i
, NextValueNo
, Ty
);
4325 BasicBlock
*BB
= getBasicBlock(Record
[2+i
]);
4327 return error("Invalid record");
4328 PN
->addIncoming(V
, BB
);
4334 case bitc::FUNC_CODE_INST_LANDINGPAD
:
4335 case bitc::FUNC_CODE_INST_LANDINGPAD_OLD
: {
4336 // LANDINGPAD: [ty, val, val, num, (id0,val0 ...)?]
4338 if (BitCode
== bitc::FUNC_CODE_INST_LANDINGPAD
) {
4339 if (Record
.size() < 3)
4340 return error("Invalid record");
4342 assert(BitCode
== bitc::FUNC_CODE_INST_LANDINGPAD_OLD
);
4343 if (Record
.size() < 4)
4344 return error("Invalid record");
4346 Type
*Ty
= getTypeByID(Record
[Idx
++]);
4348 return error("Invalid record");
4349 if (BitCode
== bitc::FUNC_CODE_INST_LANDINGPAD_OLD
) {
4350 Value
*PersFn
= nullptr;
4351 if (getValueTypePair(Record
, Idx
, NextValueNo
, PersFn
))
4352 return error("Invalid record");
4354 if (!F
->hasPersonalityFn())
4355 F
->setPersonalityFn(cast
<Constant
>(PersFn
));
4356 else if (F
->getPersonalityFn() != cast
<Constant
>(PersFn
))
4357 return error("Personality function mismatch");
4360 bool IsCleanup
= !!Record
[Idx
++];
4361 unsigned NumClauses
= Record
[Idx
++];
4362 LandingPadInst
*LP
= LandingPadInst::Create(Ty
, NumClauses
);
4363 LP
->setCleanup(IsCleanup
);
4364 for (unsigned J
= 0; J
!= NumClauses
; ++J
) {
4365 LandingPadInst::ClauseType CT
=
4366 LandingPadInst::ClauseType(Record
[Idx
++]); (void)CT
;
4369 if (getValueTypePair(Record
, Idx
, NextValueNo
, Val
)) {
4371 return error("Invalid record");
4374 assert((CT
!= LandingPadInst::Catch
||
4375 !isa
<ArrayType
>(Val
->getType())) &&
4376 "Catch clause has a invalid type!");
4377 assert((CT
!= LandingPadInst::Filter
||
4378 isa
<ArrayType
>(Val
->getType())) &&
4379 "Filter clause has invalid type!");
4380 LP
->addClause(cast
<Constant
>(Val
));
4384 InstructionList
.push_back(I
);
4388 case bitc::FUNC_CODE_INST_ALLOCA
: { // ALLOCA: [instty, opty, op, align]
4389 if (Record
.size() != 4)
4390 return error("Invalid record");
4391 uint64_t AlignRecord
= Record
[3];
4392 const uint64_t InAllocaMask
= uint64_t(1) << 5;
4393 const uint64_t ExplicitTypeMask
= uint64_t(1) << 6;
4394 const uint64_t SwiftErrorMask
= uint64_t(1) << 7;
4395 const uint64_t FlagMask
= InAllocaMask
| ExplicitTypeMask
|
4397 bool InAlloca
= AlignRecord
& InAllocaMask
;
4398 bool SwiftError
= AlignRecord
& SwiftErrorMask
;
4399 Type
*Ty
= getTypeByID(Record
[0]);
4400 if ((AlignRecord
& ExplicitTypeMask
) == 0) {
4401 auto *PTy
= dyn_cast_or_null
<PointerType
>(Ty
);
4403 return error("Old-style alloca with a non-pointer type");
4404 Ty
= PTy
->getElementType();
4406 Type
*OpTy
= getTypeByID(Record
[1]);
4407 Value
*Size
= getFnValueByID(Record
[2], OpTy
);
4409 if (Error Err
= parseAlignmentValue(AlignRecord
& ~FlagMask
, Align
)) {
4413 return error("Invalid record");
4415 // FIXME: Make this an optional field.
4416 const DataLayout
&DL
= TheModule
->getDataLayout();
4417 unsigned AS
= DL
.getAllocaAddrSpace();
4419 AllocaInst
*AI
= new AllocaInst(Ty
, AS
, Size
, Align
);
4420 AI
->setUsedWithInAlloca(InAlloca
);
4421 AI
->setSwiftError(SwiftError
);
4423 InstructionList
.push_back(I
);
4426 case bitc::FUNC_CODE_INST_LOAD
: { // LOAD: [opty, op, align, vol]
4429 if (getValueTypePair(Record
, OpNum
, NextValueNo
, Op
) ||
4430 (OpNum
+ 2 != Record
.size() && OpNum
+ 3 != Record
.size()))
4431 return error("Invalid record");
4434 if (OpNum
+ 3 == Record
.size())
4435 Ty
= getTypeByID(Record
[OpNum
++]);
4436 if (Error Err
= typeCheckLoadStoreInst(Ty
, Op
->getType()))
4439 Ty
= cast
<PointerType
>(Op
->getType())->getElementType();
4442 if (Error Err
= parseAlignmentValue(Record
[OpNum
], Align
))
4444 I
= new LoadInst(Ty
, Op
, "", Record
[OpNum
+ 1], Align
);
4446 InstructionList
.push_back(I
);
4449 case bitc::FUNC_CODE_INST_LOADATOMIC
: {
4450 // LOADATOMIC: [opty, op, align, vol, ordering, ssid]
4453 if (getValueTypePair(Record
, OpNum
, NextValueNo
, Op
) ||
4454 (OpNum
+ 4 != Record
.size() && OpNum
+ 5 != Record
.size()))
4455 return error("Invalid record");
4458 if (OpNum
+ 5 == Record
.size())
4459 Ty
= getTypeByID(Record
[OpNum
++]);
4460 if (Error Err
= typeCheckLoadStoreInst(Ty
, Op
->getType()))
4463 Ty
= cast
<PointerType
>(Op
->getType())->getElementType();
4465 AtomicOrdering Ordering
= getDecodedOrdering(Record
[OpNum
+ 2]);
4466 if (Ordering
== AtomicOrdering::NotAtomic
||
4467 Ordering
== AtomicOrdering::Release
||
4468 Ordering
== AtomicOrdering::AcquireRelease
)
4469 return error("Invalid record");
4470 if (Ordering
!= AtomicOrdering::NotAtomic
&& Record
[OpNum
] == 0)
4471 return error("Invalid record");
4472 SyncScope::ID SSID
= getDecodedSyncScopeID(Record
[OpNum
+ 3]);
4475 if (Error Err
= parseAlignmentValue(Record
[OpNum
], Align
))
4477 I
= new LoadInst(Ty
, Op
, "", Record
[OpNum
+ 1], Align
, Ordering
, SSID
);
4479 InstructionList
.push_back(I
);
4482 case bitc::FUNC_CODE_INST_STORE
:
4483 case bitc::FUNC_CODE_INST_STORE_OLD
: { // STORE2:[ptrty, ptr, val, align, vol]
4486 if (getValueTypePair(Record
, OpNum
, NextValueNo
, Ptr
) ||
4487 (BitCode
== bitc::FUNC_CODE_INST_STORE
4488 ? getValueTypePair(Record
, OpNum
, NextValueNo
, Val
)
4489 : popValue(Record
, OpNum
, NextValueNo
,
4490 cast
<PointerType
>(Ptr
->getType())->getElementType(),
4492 OpNum
+ 2 != Record
.size())
4493 return error("Invalid record");
4495 if (Error Err
= typeCheckLoadStoreInst(Val
->getType(), Ptr
->getType()))
4498 if (Error Err
= parseAlignmentValue(Record
[OpNum
], Align
))
4500 I
= new StoreInst(Val
, Ptr
, Record
[OpNum
+1], Align
);
4501 InstructionList
.push_back(I
);
4504 case bitc::FUNC_CODE_INST_STOREATOMIC
:
4505 case bitc::FUNC_CODE_INST_STOREATOMIC_OLD
: {
4506 // STOREATOMIC: [ptrty, ptr, val, align, vol, ordering, ssid]
4509 if (getValueTypePair(Record
, OpNum
, NextValueNo
, Ptr
) ||
4510 !isa
<PointerType
>(Ptr
->getType()) ||
4511 (BitCode
== bitc::FUNC_CODE_INST_STOREATOMIC
4512 ? getValueTypePair(Record
, OpNum
, NextValueNo
, Val
)
4513 : popValue(Record
, OpNum
, NextValueNo
,
4514 cast
<PointerType
>(Ptr
->getType())->getElementType(),
4516 OpNum
+ 4 != Record
.size())
4517 return error("Invalid record");
4519 if (Error Err
= typeCheckLoadStoreInst(Val
->getType(), Ptr
->getType()))
4521 AtomicOrdering Ordering
= getDecodedOrdering(Record
[OpNum
+ 2]);
4522 if (Ordering
== AtomicOrdering::NotAtomic
||
4523 Ordering
== AtomicOrdering::Acquire
||
4524 Ordering
== AtomicOrdering::AcquireRelease
)
4525 return error("Invalid record");
4526 SyncScope::ID SSID
= getDecodedSyncScopeID(Record
[OpNum
+ 3]);
4527 if (Ordering
!= AtomicOrdering::NotAtomic
&& Record
[OpNum
] == 0)
4528 return error("Invalid record");
4531 if (Error Err
= parseAlignmentValue(Record
[OpNum
], Align
))
4533 I
= new StoreInst(Val
, Ptr
, Record
[OpNum
+1], Align
, Ordering
, SSID
);
4534 InstructionList
.push_back(I
);
4537 case bitc::FUNC_CODE_INST_CMPXCHG_OLD
:
4538 case bitc::FUNC_CODE_INST_CMPXCHG
: {
4539 // CMPXCHG:[ptrty, ptr, cmp, new, vol, successordering, ssid,
4540 // failureordering?, isweak?]
4542 Value
*Ptr
, *Cmp
, *New
;
4543 if (getValueTypePair(Record
, OpNum
, NextValueNo
, Ptr
) ||
4544 (BitCode
== bitc::FUNC_CODE_INST_CMPXCHG
4545 ? getValueTypePair(Record
, OpNum
, NextValueNo
, Cmp
)
4546 : popValue(Record
, OpNum
, NextValueNo
,
4547 cast
<PointerType
>(Ptr
->getType())->getElementType(),
4549 popValue(Record
, OpNum
, NextValueNo
, Cmp
->getType(), New
) ||
4550 Record
.size() < OpNum
+ 3 || Record
.size() > OpNum
+ 5)
4551 return error("Invalid record");
4552 AtomicOrdering SuccessOrdering
= getDecodedOrdering(Record
[OpNum
+ 1]);
4553 if (SuccessOrdering
== AtomicOrdering::NotAtomic
||
4554 SuccessOrdering
== AtomicOrdering::Unordered
)
4555 return error("Invalid record");
4556 SyncScope::ID SSID
= getDecodedSyncScopeID(Record
[OpNum
+ 2]);
4558 if (Error Err
= typeCheckLoadStoreInst(Cmp
->getType(), Ptr
->getType()))
4560 AtomicOrdering FailureOrdering
;
4561 if (Record
.size() < 7)
4563 AtomicCmpXchgInst::getStrongestFailureOrdering(SuccessOrdering
);
4565 FailureOrdering
= getDecodedOrdering(Record
[OpNum
+ 3]);
4567 I
= new AtomicCmpXchgInst(Ptr
, Cmp
, New
, SuccessOrdering
, FailureOrdering
,
4569 cast
<AtomicCmpXchgInst
>(I
)->setVolatile(Record
[OpNum
]);
4571 if (Record
.size() < 8) {
4572 // Before weak cmpxchgs existed, the instruction simply returned the
4573 // value loaded from memory, so bitcode files from that era will be
4574 // expecting the first component of a modern cmpxchg.
4575 CurBB
->getInstList().push_back(I
);
4576 I
= ExtractValueInst::Create(I
, 0);
4578 cast
<AtomicCmpXchgInst
>(I
)->setWeak(Record
[OpNum
+4]);
4581 InstructionList
.push_back(I
);
4584 case bitc::FUNC_CODE_INST_ATOMICRMW
: {
4585 // ATOMICRMW:[ptrty, ptr, val, op, vol, ordering, ssid]
4588 if (getValueTypePair(Record
, OpNum
, NextValueNo
, Ptr
) ||
4589 !isa
<PointerType
>(Ptr
->getType()) ||
4590 popValue(Record
, OpNum
, NextValueNo
,
4591 cast
<PointerType
>(Ptr
->getType())->getElementType(), Val
) ||
4592 OpNum
+4 != Record
.size())
4593 return error("Invalid record");
4594 AtomicRMWInst::BinOp Operation
= getDecodedRMWOperation(Record
[OpNum
]);
4595 if (Operation
< AtomicRMWInst::FIRST_BINOP
||
4596 Operation
> AtomicRMWInst::LAST_BINOP
)
4597 return error("Invalid record");
4598 AtomicOrdering Ordering
= getDecodedOrdering(Record
[OpNum
+ 2]);
4599 if (Ordering
== AtomicOrdering::NotAtomic
||
4600 Ordering
== AtomicOrdering::Unordered
)
4601 return error("Invalid record");
4602 SyncScope::ID SSID
= getDecodedSyncScopeID(Record
[OpNum
+ 3]);
4603 I
= new AtomicRMWInst(Operation
, Ptr
, Val
, Ordering
, SSID
);
4604 cast
<AtomicRMWInst
>(I
)->setVolatile(Record
[OpNum
+1]);
4605 InstructionList
.push_back(I
);
4608 case bitc::FUNC_CODE_INST_FENCE
: { // FENCE:[ordering, ssid]
4609 if (2 != Record
.size())
4610 return error("Invalid record");
4611 AtomicOrdering Ordering
= getDecodedOrdering(Record
[0]);
4612 if (Ordering
== AtomicOrdering::NotAtomic
||
4613 Ordering
== AtomicOrdering::Unordered
||
4614 Ordering
== AtomicOrdering::Monotonic
)
4615 return error("Invalid record");
4616 SyncScope::ID SSID
= getDecodedSyncScopeID(Record
[1]);
4617 I
= new FenceInst(Context
, Ordering
, SSID
);
4618 InstructionList
.push_back(I
);
4621 case bitc::FUNC_CODE_INST_CALL
: {
4622 // CALL: [paramattrs, cc, fmf, fnty, fnid, arg0, arg1...]
4623 if (Record
.size() < 3)
4624 return error("Invalid record");
4627 AttributeList PAL
= getAttributes(Record
[OpNum
++]);
4628 unsigned CCInfo
= Record
[OpNum
++];
4631 if ((CCInfo
>> bitc::CALL_FMF
) & 1) {
4632 FMF
= getDecodedFastMathFlags(Record
[OpNum
++]);
4634 return error("Fast math flags indicator set for call with no FMF");
4637 FunctionType
*FTy
= nullptr;
4638 if (CCInfo
>> bitc::CALL_EXPLICIT_TYPE
& 1 &&
4639 !(FTy
= dyn_cast
<FunctionType
>(getTypeByID(Record
[OpNum
++]))))
4640 return error("Explicit call type is not a function type");
4643 if (getValueTypePair(Record
, OpNum
, NextValueNo
, Callee
))
4644 return error("Invalid record");
4646 PointerType
*OpTy
= dyn_cast
<PointerType
>(Callee
->getType());
4648 return error("Callee is not a pointer type");
4650 FTy
= dyn_cast
<FunctionType
>(OpTy
->getElementType());
4652 return error("Callee is not of pointer to function type");
4653 } else if (OpTy
->getElementType() != FTy
)
4654 return error("Explicit call type does not match pointee type of "
4656 if (Record
.size() < FTy
->getNumParams() + OpNum
)
4657 return error("Insufficient operands to call");
4659 SmallVector
<Value
*, 16> Args
;
4660 // Read the fixed params.
4661 for (unsigned i
= 0, e
= FTy
->getNumParams(); i
!= e
; ++i
, ++OpNum
) {
4662 if (FTy
->getParamType(i
)->isLabelTy())
4663 Args
.push_back(getBasicBlock(Record
[OpNum
]));
4665 Args
.push_back(getValue(Record
, OpNum
, NextValueNo
,
4666 FTy
->getParamType(i
)));
4668 return error("Invalid record");
4671 // Read type/value pairs for varargs params.
4672 if (!FTy
->isVarArg()) {
4673 if (OpNum
!= Record
.size())
4674 return error("Invalid record");
4676 while (OpNum
!= Record
.size()) {
4678 if (getValueTypePair(Record
, OpNum
, NextValueNo
, Op
))
4679 return error("Invalid record");
4684 I
= CallInst::Create(FTy
, Callee
, Args
, OperandBundles
);
4685 OperandBundles
.clear();
4686 InstructionList
.push_back(I
);
4687 cast
<CallInst
>(I
)->setCallingConv(
4688 static_cast<CallingConv::ID
>((0x7ff & CCInfo
) >> bitc::CALL_CCONV
));
4689 CallInst::TailCallKind TCK
= CallInst::TCK_None
;
4690 if (CCInfo
& 1 << bitc::CALL_TAIL
)
4691 TCK
= CallInst::TCK_Tail
;
4692 if (CCInfo
& (1 << bitc::CALL_MUSTTAIL
))
4693 TCK
= CallInst::TCK_MustTail
;
4694 if (CCInfo
& (1 << bitc::CALL_NOTAIL
))
4695 TCK
= CallInst::TCK_NoTail
;
4696 cast
<CallInst
>(I
)->setTailCallKind(TCK
);
4697 cast
<CallInst
>(I
)->setAttributes(PAL
);
4699 if (!isa
<FPMathOperator
>(I
))
4700 return error("Fast-math-flags specified for call without "
4701 "floating-point scalar or vector return type");
4702 I
->setFastMathFlags(FMF
);
4706 case bitc::FUNC_CODE_INST_VAARG
: { // VAARG: [valistty, valist, instty]
4707 if (Record
.size() < 3)
4708 return error("Invalid record");
4709 Type
*OpTy
= getTypeByID(Record
[0]);
4710 Value
*Op
= getValue(Record
, 1, NextValueNo
, OpTy
);
4711 Type
*ResTy
= getTypeByID(Record
[2]);
4712 if (!OpTy
|| !Op
|| !ResTy
)
4713 return error("Invalid record");
4714 I
= new VAArgInst(Op
, ResTy
);
4715 InstructionList
.push_back(I
);
4719 case bitc::FUNC_CODE_OPERAND_BUNDLE
: {
4720 // A call or an invoke can be optionally prefixed with some variable
4721 // number of operand bundle blocks. These blocks are read into
4722 // OperandBundles and consumed at the next call or invoke instruction.
4724 if (Record
.size() < 1 || Record
[0] >= BundleTags
.size())
4725 return error("Invalid record");
4727 std::vector
<Value
*> Inputs
;
4730 while (OpNum
!= Record
.size()) {
4732 if (getValueTypePair(Record
, OpNum
, NextValueNo
, Op
))
4733 return error("Invalid record");
4734 Inputs
.push_back(Op
);
4737 OperandBundles
.emplace_back(BundleTags
[Record
[0]], std::move(Inputs
));
4742 // Add instruction to end of current BB. If there is no current BB, reject
4746 return error("Invalid instruction with no BB");
4748 if (!OperandBundles
.empty()) {
4750 return error("Operand bundles found with no consumer");
4752 CurBB
->getInstList().push_back(I
);
4754 // If this was a terminator instruction, move to the next block.
4755 if (I
->isTerminator()) {
4757 CurBB
= CurBBNo
< FunctionBBs
.size() ? FunctionBBs
[CurBBNo
] : nullptr;
4760 // Non-void values get registered in the value table for future use.
4761 if (I
&& !I
->getType()->isVoidTy())
4762 ValueList
.assignValue(I
, NextValueNo
++);
4767 if (!OperandBundles
.empty())
4768 return error("Operand bundles found with no consumer");
4770 // Check the function list for unresolved values.
4771 if (Argument
*A
= dyn_cast
<Argument
>(ValueList
.back())) {
4772 if (!A
->getParent()) {
4773 // We found at least one unresolved value. Nuke them all to avoid leaks.
4774 for (unsigned i
= ModuleValueListSize
, e
= ValueList
.size(); i
!= e
; ++i
){
4775 if ((A
= dyn_cast_or_null
<Argument
>(ValueList
[i
])) && !A
->getParent()) {
4776 A
->replaceAllUsesWith(UndefValue::get(A
->getType()));
4780 return error("Never resolved value found in function");
4784 // Unexpected unresolved metadata about to be dropped.
4785 if (MDLoader
->hasFwdRefs())
4786 return error("Invalid function metadata: outgoing forward refs");
4788 // Trim the value list down to the size it was before we parsed this function.
4789 ValueList
.shrinkTo(ModuleValueListSize
);
4790 MDLoader
->shrinkTo(ModuleMDLoaderSize
);
4791 std::vector
<BasicBlock
*>().swap(FunctionBBs
);
4792 return Error::success();
4795 /// Find the function body in the bitcode stream
4796 Error
BitcodeReader::findFunctionInStream(
4798 DenseMap
<Function
*, uint64_t>::iterator DeferredFunctionInfoIterator
) {
4799 while (DeferredFunctionInfoIterator
->second
== 0) {
4800 // This is the fallback handling for the old format bitcode that
4801 // didn't contain the function index in the VST, or when we have
4802 // an anonymous function which would not have a VST entry.
4803 // Assert that we have one of those two cases.
4804 assert(VSTOffset
== 0 || !F
->hasName());
4805 // Parse the next body in the stream and set its position in the
4806 // DeferredFunctionInfo map.
4807 if (Error Err
= rememberAndSkipFunctionBodies())
4810 return Error::success();
4813 SyncScope::ID
BitcodeReader::getDecodedSyncScopeID(unsigned Val
) {
4814 if (Val
== SyncScope::SingleThread
|| Val
== SyncScope::System
)
4815 return SyncScope::ID(Val
);
4816 if (Val
>= SSIDs
.size())
4817 return SyncScope::System
; // Map unknown synchronization scopes to system.
4821 //===----------------------------------------------------------------------===//
4822 // GVMaterializer implementation
4823 //===----------------------------------------------------------------------===//
4825 Error
BitcodeReader::materialize(GlobalValue
*GV
) {
4826 Function
*F
= dyn_cast
<Function
>(GV
);
4827 // If it's not a function or is already material, ignore the request.
4828 if (!F
|| !F
->isMaterializable())
4829 return Error::success();
4831 DenseMap
<Function
*, uint64_t>::iterator DFII
= DeferredFunctionInfo
.find(F
);
4832 assert(DFII
!= DeferredFunctionInfo
.end() && "Deferred function not found!");
4833 // If its position is recorded as 0, its body is somewhere in the stream
4834 // but we haven't seen it yet.
4835 if (DFII
->second
== 0)
4836 if (Error Err
= findFunctionInStream(F
, DFII
))
4839 // Materialize metadata before parsing any function bodies.
4840 if (Error Err
= materializeMetadata())
4843 // Move the bit stream to the saved position of the deferred function body.
4844 Stream
.JumpToBit(DFII
->second
);
4846 if (Error Err
= parseFunctionBody(F
))
4848 F
->setIsMaterializable(false);
4853 // Upgrade any old intrinsic calls in the function.
4854 for (auto &I
: UpgradedIntrinsics
) {
4855 for (auto UI
= I
.first
->materialized_user_begin(), UE
= I
.first
->user_end();
4859 if (CallInst
*CI
= dyn_cast
<CallInst
>(U
))
4860 UpgradeIntrinsicCall(CI
, I
.second
);
4864 // Update calls to the remangled intrinsics
4865 for (auto &I
: RemangledIntrinsics
)
4866 for (auto UI
= I
.first
->materialized_user_begin(), UE
= I
.first
->user_end();
4868 // Don't expect any other users than call sites
4869 CallSite(*UI
++).setCalledFunction(I
.second
);
4871 // Finish fn->subprogram upgrade for materialized functions.
4872 if (DISubprogram
*SP
= MDLoader
->lookupSubprogramForFunction(F
))
4873 F
->setSubprogram(SP
);
4875 // Check if the TBAA Metadata are valid, otherwise we will need to strip them.
4876 if (!MDLoader
->isStrippingTBAA()) {
4877 for (auto &I
: instructions(F
)) {
4878 MDNode
*TBAA
= I
.getMetadata(LLVMContext::MD_tbaa
);
4879 if (!TBAA
|| TBAAVerifyHelper
.visitTBAAMetadata(I
, TBAA
))
4881 MDLoader
->setStripTBAA(true);
4882 stripTBAA(F
->getParent());
4886 // Bring in any functions that this function forward-referenced via
4888 return materializeForwardReferencedFunctions();
4891 Error
BitcodeReader::materializeModule() {
4892 if (Error Err
= materializeMetadata())
4895 // Promise to materialize all forward references.
4896 WillMaterializeAllForwardRefs
= true;
4898 // Iterate over the module, deserializing any functions that are still on
4900 for (Function
&F
: *TheModule
) {
4901 if (Error Err
= materialize(&F
))
4904 // At this point, if there are any function bodies, parse the rest of
4905 // the bits in the module past the last function block we have recorded
4906 // through either lazy scanning or the VST.
4907 if (LastFunctionBlockBit
|| NextUnreadBit
)
4908 if (Error Err
= parseModule(LastFunctionBlockBit
> NextUnreadBit
4909 ? LastFunctionBlockBit
4913 // Check that all block address forward references got resolved (as we
4915 if (!BasicBlockFwdRefs
.empty())
4916 return error("Never resolved function from blockaddress");
4918 // Upgrade any intrinsic calls that slipped through (should not happen!) and
4919 // delete the old functions to clean up. We can't do this unless the entire
4920 // module is materialized because there could always be another function body
4921 // with calls to the old function.
4922 for (auto &I
: UpgradedIntrinsics
) {
4923 for (auto *U
: I
.first
->users()) {
4924 if (CallInst
*CI
= dyn_cast
<CallInst
>(U
))
4925 UpgradeIntrinsicCall(CI
, I
.second
);
4927 if (!I
.first
->use_empty())
4928 I
.first
->replaceAllUsesWith(I
.second
);
4929 I
.first
->eraseFromParent();
4931 UpgradedIntrinsics
.clear();
4932 // Do the same for remangled intrinsics
4933 for (auto &I
: RemangledIntrinsics
) {
4934 I
.first
->replaceAllUsesWith(I
.second
);
4935 I
.first
->eraseFromParent();
4937 RemangledIntrinsics
.clear();
4939 UpgradeDebugInfo(*TheModule
);
4941 UpgradeModuleFlags(*TheModule
);
4943 UpgradeRetainReleaseMarker(*TheModule
);
4945 return Error::success();
4948 std::vector
<StructType
*> BitcodeReader::getIdentifiedStructTypes() const {
4949 return IdentifiedStructTypes
;
4952 ModuleSummaryIndexBitcodeReader::ModuleSummaryIndexBitcodeReader(
4953 BitstreamCursor Cursor
, StringRef Strtab
, ModuleSummaryIndex
&TheIndex
,
4954 StringRef ModulePath
, unsigned ModuleId
)
4955 : BitcodeReaderBase(std::move(Cursor
), Strtab
), TheIndex(TheIndex
),
4956 ModulePath(ModulePath
), ModuleId(ModuleId
) {}
4958 void ModuleSummaryIndexBitcodeReader::addThisModule() {
4959 TheIndex
.addModule(ModulePath
, ModuleId
);
4962 ModuleSummaryIndex::ModuleInfo
*
4963 ModuleSummaryIndexBitcodeReader::getThisModule() {
4964 return TheIndex
.getModule(ModulePath
);
4967 std::pair
<ValueInfo
, GlobalValue::GUID
>
4968 ModuleSummaryIndexBitcodeReader::getValueInfoFromValueId(unsigned ValueId
) {
4969 auto VGI
= ValueIdToValueInfoMap
[ValueId
];
4974 void ModuleSummaryIndexBitcodeReader::setValueGUID(
4975 uint64_t ValueID
, StringRef ValueName
, GlobalValue::LinkageTypes Linkage
,
4976 StringRef SourceFileName
) {
4977 std::string GlobalId
=
4978 GlobalValue::getGlobalIdentifier(ValueName
, Linkage
, SourceFileName
);
4979 auto ValueGUID
= GlobalValue::getGUID(GlobalId
);
4980 auto OriginalNameID
= ValueGUID
;
4981 if (GlobalValue::isLocalLinkage(Linkage
))
4982 OriginalNameID
= GlobalValue::getGUID(ValueName
);
4983 if (PrintSummaryGUIDs
)
4984 dbgs() << "GUID " << ValueGUID
<< "(" << OriginalNameID
<< ") is "
4985 << ValueName
<< "\n";
4987 // UseStrtab is false for legacy summary formats and value names are
4988 // created on stack. In that case we save the name in a string saver in
4989 // the index so that the value name can be recorded.
4990 ValueIdToValueInfoMap
[ValueID
] = std::make_pair(
4991 TheIndex
.getOrInsertValueInfo(
4993 UseStrtab
? ValueName
: TheIndex
.saveString(ValueName
)),
4997 // Specialized value symbol table parser used when reading module index
4998 // blocks where we don't actually create global values. The parsed information
4999 // is saved in the bitcode reader for use when later parsing summaries.
5000 Error
ModuleSummaryIndexBitcodeReader::parseValueSymbolTable(
5002 DenseMap
<unsigned, GlobalValue::LinkageTypes
> &ValueIdToLinkageMap
) {
5003 // With a strtab the VST is not required to parse the summary.
5005 return Error::success();
5007 assert(Offset
> 0 && "Expected non-zero VST offset");
5008 uint64_t CurrentBit
= jumpToValueSymbolTable(Offset
, Stream
);
5010 if (Stream
.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID
))
5011 return error("Invalid record");
5013 SmallVector
<uint64_t, 64> Record
;
5015 // Read all the records for this value table.
5016 SmallString
<128> ValueName
;
5019 BitstreamEntry Entry
= Stream
.advanceSkippingSubblocks();
5021 switch (Entry
.Kind
) {
5022 case BitstreamEntry::SubBlock
: // Handled for us already.
5023 case BitstreamEntry::Error
:
5024 return error("Malformed block");
5025 case BitstreamEntry::EndBlock
:
5026 // Done parsing VST, jump back to wherever we came from.
5027 Stream
.JumpToBit(CurrentBit
);
5028 return Error::success();
5029 case BitstreamEntry::Record
:
5030 // The interesting case.
5036 switch (Stream
.readRecord(Entry
.ID
, Record
)) {
5037 default: // Default behavior: ignore (e.g. VST_CODE_BBENTRY records).
5039 case bitc::VST_CODE_ENTRY
: { // VST_CODE_ENTRY: [valueid, namechar x N]
5040 if (convertToString(Record
, 1, ValueName
))
5041 return error("Invalid record");
5042 unsigned ValueID
= Record
[0];
5043 assert(!SourceFileName
.empty());
5044 auto VLI
= ValueIdToLinkageMap
.find(ValueID
);
5045 assert(VLI
!= ValueIdToLinkageMap
.end() &&
5046 "No linkage found for VST entry?");
5047 auto Linkage
= VLI
->second
;
5048 setValueGUID(ValueID
, ValueName
, Linkage
, SourceFileName
);
5052 case bitc::VST_CODE_FNENTRY
: {
5053 // VST_CODE_FNENTRY: [valueid, offset, namechar x N]
5054 if (convertToString(Record
, 2, ValueName
))
5055 return error("Invalid record");
5056 unsigned ValueID
= Record
[0];
5057 assert(!SourceFileName
.empty());
5058 auto VLI
= ValueIdToLinkageMap
.find(ValueID
);
5059 assert(VLI
!= ValueIdToLinkageMap
.end() &&
5060 "No linkage found for VST entry?");
5061 auto Linkage
= VLI
->second
;
5062 setValueGUID(ValueID
, ValueName
, Linkage
, SourceFileName
);
5066 case bitc::VST_CODE_COMBINED_ENTRY
: {
5067 // VST_CODE_COMBINED_ENTRY: [valueid, refguid]
5068 unsigned ValueID
= Record
[0];
5069 GlobalValue::GUID RefGUID
= Record
[1];
5070 // The "original name", which is the second value of the pair will be
5071 // overriden later by a FS_COMBINED_ORIGINAL_NAME in the combined index.
5072 ValueIdToValueInfoMap
[ValueID
] =
5073 std::make_pair(TheIndex
.getOrInsertValueInfo(RefGUID
), RefGUID
);
5080 // Parse just the blocks needed for building the index out of the module.
5081 // At the end of this routine the module Index is populated with a map
5082 // from global value id to GlobalValueSummary objects.
5083 Error
ModuleSummaryIndexBitcodeReader::parseModule() {
5084 if (Stream
.EnterSubBlock(bitc::MODULE_BLOCK_ID
))
5085 return error("Invalid record");
5087 SmallVector
<uint64_t, 64> Record
;
5088 DenseMap
<unsigned, GlobalValue::LinkageTypes
> ValueIdToLinkageMap
;
5089 unsigned ValueId
= 0;
5091 // Read the index for this module.
5093 BitstreamEntry Entry
= Stream
.advance();
5095 switch (Entry
.Kind
) {
5096 case BitstreamEntry::Error
:
5097 return error("Malformed block");
5098 case BitstreamEntry::EndBlock
:
5099 return Error::success();
5101 case BitstreamEntry::SubBlock
:
5103 default: // Skip unknown content.
5104 if (Stream
.SkipBlock())
5105 return error("Invalid record");
5107 case bitc::BLOCKINFO_BLOCK_ID
:
5108 // Need to parse these to get abbrev ids (e.g. for VST)
5109 if (readBlockInfo())
5110 return error("Malformed block");
5112 case bitc::VALUE_SYMTAB_BLOCK_ID
:
5113 // Should have been parsed earlier via VSTOffset, unless there
5114 // is no summary section.
5115 assert(((SeenValueSymbolTable
&& VSTOffset
> 0) ||
5116 !SeenGlobalValSummary
) &&
5117 "Expected early VST parse via VSTOffset record");
5118 if (Stream
.SkipBlock())
5119 return error("Invalid record");
5121 case bitc::GLOBALVAL_SUMMARY_BLOCK_ID
:
5122 case bitc::FULL_LTO_GLOBALVAL_SUMMARY_BLOCK_ID
:
5123 // Add the module if it is a per-module index (has a source file name).
5124 if (!SourceFileName
.empty())
5126 assert(!SeenValueSymbolTable
&&
5127 "Already read VST when parsing summary block?");
5128 // We might not have a VST if there were no values in the
5129 // summary. An empty summary block generated when we are
5130 // performing ThinLTO compiles so we don't later invoke
5131 // the regular LTO process on them.
5132 if (VSTOffset
> 0) {
5133 if (Error Err
= parseValueSymbolTable(VSTOffset
, ValueIdToLinkageMap
))
5135 SeenValueSymbolTable
= true;
5137 SeenGlobalValSummary
= true;
5138 if (Error Err
= parseEntireSummary(Entry
.ID
))
5141 case bitc::MODULE_STRTAB_BLOCK_ID
:
5142 if (Error Err
= parseModuleStringTable())
5148 case BitstreamEntry::Record
: {
5150 auto BitCode
= Stream
.readRecord(Entry
.ID
, Record
);
5153 break; // Default behavior, ignore unknown content.
5154 case bitc::MODULE_CODE_VERSION
: {
5155 if (Error Err
= parseVersionRecord(Record
).takeError())
5159 /// MODULE_CODE_SOURCE_FILENAME: [namechar x N]
5160 case bitc::MODULE_CODE_SOURCE_FILENAME
: {
5161 SmallString
<128> ValueName
;
5162 if (convertToString(Record
, 0, ValueName
))
5163 return error("Invalid record");
5164 SourceFileName
= ValueName
.c_str();
5167 /// MODULE_CODE_HASH: [5*i32]
5168 case bitc::MODULE_CODE_HASH
: {
5169 if (Record
.size() != 5)
5170 return error("Invalid hash length " + Twine(Record
.size()).str());
5171 auto &Hash
= getThisModule()->second
.second
;
5173 for (auto &Val
: Record
) {
5174 assert(!(Val
>> 32) && "Unexpected high bits set");
5179 /// MODULE_CODE_VSTOFFSET: [offset]
5180 case bitc::MODULE_CODE_VSTOFFSET
:
5181 if (Record
.size() < 1)
5182 return error("Invalid record");
5183 // Note that we subtract 1 here because the offset is relative to one
5184 // word before the start of the identification or module block, which
5185 // was historically always the start of the regular bitcode header.
5186 VSTOffset
= Record
[0] - 1;
5188 // v1 GLOBALVAR: [pointer type, isconst, initid, linkage, ...]
5189 // v1 FUNCTION: [type, callingconv, isproto, linkage, ...]
5190 // v1 ALIAS: [alias type, addrspace, aliasee val#, linkage, ...]
5191 // v2: [strtab offset, strtab size, v1]
5192 case bitc::MODULE_CODE_GLOBALVAR
:
5193 case bitc::MODULE_CODE_FUNCTION
:
5194 case bitc::MODULE_CODE_ALIAS
: {
5196 ArrayRef
<uint64_t> GVRecord
;
5197 std::tie(Name
, GVRecord
) = readNameFromStrtab(Record
);
5198 if (GVRecord
.size() <= 3)
5199 return error("Invalid record");
5200 uint64_t RawLinkage
= GVRecord
[3];
5201 GlobalValue::LinkageTypes Linkage
= getDecodedLinkage(RawLinkage
);
5203 ValueIdToLinkageMap
[ValueId
++] = Linkage
;
5207 setValueGUID(ValueId
++, Name
, Linkage
, SourceFileName
);
5217 std::vector
<ValueInfo
>
5218 ModuleSummaryIndexBitcodeReader::makeRefList(ArrayRef
<uint64_t> Record
) {
5219 std::vector
<ValueInfo
> Ret
;
5220 Ret
.reserve(Record
.size());
5221 for (uint64_t RefValueId
: Record
)
5222 Ret
.push_back(getValueInfoFromValueId(RefValueId
).first
);
5226 std::vector
<FunctionSummary::EdgeTy
>
5227 ModuleSummaryIndexBitcodeReader::makeCallList(ArrayRef
<uint64_t> Record
,
5228 bool IsOldProfileFormat
,
5229 bool HasProfile
, bool HasRelBF
) {
5230 std::vector
<FunctionSummary::EdgeTy
> Ret
;
5231 Ret
.reserve(Record
.size());
5232 for (unsigned I
= 0, E
= Record
.size(); I
!= E
; ++I
) {
5233 CalleeInfo::HotnessType Hotness
= CalleeInfo::HotnessType::Unknown
;
5235 ValueInfo Callee
= getValueInfoFromValueId(Record
[I
]).first
;
5236 if (IsOldProfileFormat
) {
5237 I
+= 1; // Skip old callsitecount field
5239 I
+= 1; // Skip old profilecount field
5240 } else if (HasProfile
)
5241 Hotness
= static_cast<CalleeInfo::HotnessType
>(Record
[++I
]);
5243 RelBF
= Record
[++I
];
5244 Ret
.push_back(FunctionSummary::EdgeTy
{Callee
, CalleeInfo(Hotness
, RelBF
)});
5250 parseWholeProgramDevirtResolutionByArg(ArrayRef
<uint64_t> Record
, size_t &Slot
,
5251 WholeProgramDevirtResolution
&Wpd
) {
5252 uint64_t ArgNum
= Record
[Slot
++];
5253 WholeProgramDevirtResolution::ByArg
&B
=
5254 Wpd
.ResByArg
[{Record
.begin() + Slot
, Record
.begin() + Slot
+ ArgNum
}];
5258 static_cast<WholeProgramDevirtResolution::ByArg::Kind
>(Record
[Slot
++]);
5259 B
.Info
= Record
[Slot
++];
5260 B
.Byte
= Record
[Slot
++];
5261 B
.Bit
= Record
[Slot
++];
5264 static void parseWholeProgramDevirtResolution(ArrayRef
<uint64_t> Record
,
5265 StringRef Strtab
, size_t &Slot
,
5266 TypeIdSummary
&TypeId
) {
5267 uint64_t Id
= Record
[Slot
++];
5268 WholeProgramDevirtResolution
&Wpd
= TypeId
.WPDRes
[Id
];
5270 Wpd
.TheKind
= static_cast<WholeProgramDevirtResolution::Kind
>(Record
[Slot
++]);
5271 Wpd
.SingleImplName
= {Strtab
.data() + Record
[Slot
],
5272 static_cast<size_t>(Record
[Slot
+ 1])};
5275 uint64_t ResByArgNum
= Record
[Slot
++];
5276 for (uint64_t I
= 0; I
!= ResByArgNum
; ++I
)
5277 parseWholeProgramDevirtResolutionByArg(Record
, Slot
, Wpd
);
5280 static void parseTypeIdSummaryRecord(ArrayRef
<uint64_t> Record
,
5282 ModuleSummaryIndex
&TheIndex
) {
5284 TypeIdSummary
&TypeId
= TheIndex
.getOrInsertTypeIdSummary(
5285 {Strtab
.data() + Record
[Slot
], static_cast<size_t>(Record
[Slot
+ 1])});
5288 TypeId
.TTRes
.TheKind
= static_cast<TypeTestResolution::Kind
>(Record
[Slot
++]);
5289 TypeId
.TTRes
.SizeM1BitWidth
= Record
[Slot
++];
5290 TypeId
.TTRes
.AlignLog2
= Record
[Slot
++];
5291 TypeId
.TTRes
.SizeM1
= Record
[Slot
++];
5292 TypeId
.TTRes
.BitMask
= Record
[Slot
++];
5293 TypeId
.TTRes
.InlineBits
= Record
[Slot
++];
5295 while (Slot
< Record
.size())
5296 parseWholeProgramDevirtResolution(Record
, Strtab
, Slot
, TypeId
);
5299 static void setImmutableRefs(std::vector
<ValueInfo
> &Refs
, unsigned Count
) {
5300 // Read-only refs are in the end of the refs list.
5301 for (unsigned RefNo
= Refs
.size() - Count
; RefNo
< Refs
.size(); ++RefNo
)
5302 Refs
[RefNo
].setReadOnly();
5305 // Eagerly parse the entire summary block. This populates the GlobalValueSummary
5306 // objects in the index.
5307 Error
ModuleSummaryIndexBitcodeReader::parseEntireSummary(unsigned ID
) {
5308 if (Stream
.EnterSubBlock(ID
))
5309 return error("Invalid record");
5310 SmallVector
<uint64_t, 64> Record
;
5314 BitstreamEntry Entry
= Stream
.advanceSkippingSubblocks();
5315 if (Entry
.Kind
!= BitstreamEntry::Record
)
5316 return error("Invalid Summary Block: record for version expected");
5317 if (Stream
.readRecord(Entry
.ID
, Record
) != bitc::FS_VERSION
)
5318 return error("Invalid Summary Block: version expected");
5320 const uint64_t Version
= Record
[0];
5321 const bool IsOldProfileFormat
= Version
== 1;
5322 if (Version
< 1 || Version
> 6)
5323 return error("Invalid summary version " + Twine(Version
) +
5324 ". Version should be in the range [1-6].");
5327 // Keep around the last seen summary to be used when we see an optional
5328 // "OriginalName" attachement.
5329 GlobalValueSummary
*LastSeenSummary
= nullptr;
5330 GlobalValue::GUID LastSeenGUID
= 0;
5332 // We can expect to see any number of type ID information records before
5333 // each function summary records; these variables store the information
5334 // collected so far so that it can be used to create the summary object.
5335 std::vector
<GlobalValue::GUID
> PendingTypeTests
;
5336 std::vector
<FunctionSummary::VFuncId
> PendingTypeTestAssumeVCalls
,
5337 PendingTypeCheckedLoadVCalls
;
5338 std::vector
<FunctionSummary::ConstVCall
> PendingTypeTestAssumeConstVCalls
,
5339 PendingTypeCheckedLoadConstVCalls
;
5342 BitstreamEntry Entry
= Stream
.advanceSkippingSubblocks();
5344 switch (Entry
.Kind
) {
5345 case BitstreamEntry::SubBlock
: // Handled for us already.
5346 case BitstreamEntry::Error
:
5347 return error("Malformed block");
5348 case BitstreamEntry::EndBlock
:
5349 return Error::success();
5350 case BitstreamEntry::Record
:
5351 // The interesting case.
5355 // Read a record. The record format depends on whether this
5356 // is a per-module index or a combined index file. In the per-module
5357 // case the records contain the associated value's ID for correlation
5358 // with VST entries. In the combined index the correlation is done
5359 // via the bitcode offset of the summary records (which were saved
5360 // in the combined index VST entries). The records also contain
5361 // information used for ThinLTO renaming and importing.
5363 auto BitCode
= Stream
.readRecord(Entry
.ID
, Record
);
5365 default: // Default behavior: ignore.
5367 case bitc::FS_FLAGS
: { // [flags]
5368 uint64_t Flags
= Record
[0];
5370 assert(Flags
<= 0x1f && "Unexpected bits in flag");
5372 // 1 bit: WithGlobalValueDeadStripping flag.
5373 // Set on combined index only.
5375 TheIndex
.setWithGlobalValueDeadStripping();
5376 // 1 bit: SkipModuleByDistributedBackend flag.
5377 // Set on combined index only.
5379 TheIndex
.setSkipModuleByDistributedBackend();
5380 // 1 bit: HasSyntheticEntryCounts flag.
5381 // Set on combined index only.
5383 TheIndex
.setHasSyntheticEntryCounts();
5384 // 1 bit: DisableSplitLTOUnit flag.
5385 // Set on per module indexes. It is up to the client to validate
5386 // the consistency of this flag across modules being linked.
5388 TheIndex
.setEnableSplitLTOUnit();
5389 // 1 bit: PartiallySplitLTOUnits flag.
5390 // Set on combined index only.
5392 TheIndex
.setPartiallySplitLTOUnits();
5395 case bitc::FS_VALUE_GUID
: { // [valueid, refguid]
5396 uint64_t ValueID
= Record
[0];
5397 GlobalValue::GUID RefGUID
= Record
[1];
5398 ValueIdToValueInfoMap
[ValueID
] =
5399 std::make_pair(TheIndex
.getOrInsertValueInfo(RefGUID
), RefGUID
);
5402 // FS_PERMODULE: [valueid, flags, instcount, fflags, numrefs,
5403 // numrefs x valueid, n x (valueid)]
5404 // FS_PERMODULE_PROFILE: [valueid, flags, instcount, fflags, numrefs,
5405 // numrefs x valueid,
5406 // n x (valueid, hotness)]
5407 // FS_PERMODULE_RELBF: [valueid, flags, instcount, fflags, numrefs,
5408 // numrefs x valueid,
5409 // n x (valueid, relblockfreq)]
5410 case bitc::FS_PERMODULE
:
5411 case bitc::FS_PERMODULE_RELBF
:
5412 case bitc::FS_PERMODULE_PROFILE
: {
5413 unsigned ValueID
= Record
[0];
5414 uint64_t RawFlags
= Record
[1];
5415 unsigned InstCount
= Record
[2];
5416 uint64_t RawFunFlags
= 0;
5417 unsigned NumRefs
= Record
[3];
5418 unsigned NumImmutableRefs
= 0;
5419 int RefListStartIndex
= 4;
5421 RawFunFlags
= Record
[3];
5422 NumRefs
= Record
[4];
5423 RefListStartIndex
= 5;
5425 NumImmutableRefs
= Record
[5];
5426 RefListStartIndex
= 6;
5430 auto Flags
= getDecodedGVSummaryFlags(RawFlags
, Version
);
5431 // The module path string ref set in the summary must be owned by the
5432 // index's module string table. Since we don't have a module path
5433 // string table section in the per-module index, we create a single
5434 // module path string table entry with an empty (0) ID to take
5436 int CallGraphEdgeStartIndex
= RefListStartIndex
+ NumRefs
;
5437 assert(Record
.size() >= RefListStartIndex
+ NumRefs
&&
5438 "Record size inconsistent with number of references");
5439 std::vector
<ValueInfo
> Refs
= makeRefList(
5440 ArrayRef
<uint64_t>(Record
).slice(RefListStartIndex
, NumRefs
));
5441 bool HasProfile
= (BitCode
== bitc::FS_PERMODULE_PROFILE
);
5442 bool HasRelBF
= (BitCode
== bitc::FS_PERMODULE_RELBF
);
5443 std::vector
<FunctionSummary::EdgeTy
> Calls
= makeCallList(
5444 ArrayRef
<uint64_t>(Record
).slice(CallGraphEdgeStartIndex
),
5445 IsOldProfileFormat
, HasProfile
, HasRelBF
);
5446 setImmutableRefs(Refs
, NumImmutableRefs
);
5447 auto FS
= llvm::make_unique
<FunctionSummary
>(
5448 Flags
, InstCount
, getDecodedFFlags(RawFunFlags
), /*EntryCount=*/0,
5449 std::move(Refs
), std::move(Calls
), std::move(PendingTypeTests
),
5450 std::move(PendingTypeTestAssumeVCalls
),
5451 std::move(PendingTypeCheckedLoadVCalls
),
5452 std::move(PendingTypeTestAssumeConstVCalls
),
5453 std::move(PendingTypeCheckedLoadConstVCalls
));
5454 PendingTypeTests
.clear();
5455 PendingTypeTestAssumeVCalls
.clear();
5456 PendingTypeCheckedLoadVCalls
.clear();
5457 PendingTypeTestAssumeConstVCalls
.clear();
5458 PendingTypeCheckedLoadConstVCalls
.clear();
5459 auto VIAndOriginalGUID
= getValueInfoFromValueId(ValueID
);
5460 FS
->setModulePath(getThisModule()->first());
5461 FS
->setOriginalName(VIAndOriginalGUID
.second
);
5462 TheIndex
.addGlobalValueSummary(VIAndOriginalGUID
.first
, std::move(FS
));
5465 // FS_ALIAS: [valueid, flags, valueid]
5466 // Aliases must be emitted (and parsed) after all FS_PERMODULE entries, as
5467 // they expect all aliasee summaries to be available.
5468 case bitc::FS_ALIAS
: {
5469 unsigned ValueID
= Record
[0];
5470 uint64_t RawFlags
= Record
[1];
5471 unsigned AliaseeID
= Record
[2];
5472 auto Flags
= getDecodedGVSummaryFlags(RawFlags
, Version
);
5473 auto AS
= llvm::make_unique
<AliasSummary
>(Flags
);
5474 // The module path string ref set in the summary must be owned by the
5475 // index's module string table. Since we don't have a module path
5476 // string table section in the per-module index, we create a single
5477 // module path string table entry with an empty (0) ID to take
5479 AS
->setModulePath(getThisModule()->first());
5481 GlobalValue::GUID AliaseeGUID
=
5482 getValueInfoFromValueId(AliaseeID
).first
.getGUID();
5483 auto AliaseeInModule
=
5484 TheIndex
.findSummaryInModule(AliaseeGUID
, ModulePath
);
5485 if (!AliaseeInModule
)
5486 return error("Alias expects aliasee summary to be parsed");
5487 AS
->setAliasee(AliaseeInModule
);
5488 AS
->setAliaseeGUID(AliaseeGUID
);
5490 auto GUID
= getValueInfoFromValueId(ValueID
);
5491 AS
->setOriginalName(GUID
.second
);
5492 TheIndex
.addGlobalValueSummary(GUID
.first
, std::move(AS
));
5495 // FS_PERMODULE_GLOBALVAR_INIT_REFS: [valueid, flags, varflags, n x valueid]
5496 case bitc::FS_PERMODULE_GLOBALVAR_INIT_REFS
: {
5497 unsigned ValueID
= Record
[0];
5498 uint64_t RawFlags
= Record
[1];
5499 unsigned RefArrayStart
= 2;
5500 GlobalVarSummary::GVarFlags GVF
;
5501 auto Flags
= getDecodedGVSummaryFlags(RawFlags
, Version
);
5503 GVF
= getDecodedGVarFlags(Record
[2]);
5506 std::vector
<ValueInfo
> Refs
=
5507 makeRefList(ArrayRef
<uint64_t>(Record
).slice(RefArrayStart
));
5509 llvm::make_unique
<GlobalVarSummary
>(Flags
, GVF
, std::move(Refs
));
5510 FS
->setModulePath(getThisModule()->first());
5511 auto GUID
= getValueInfoFromValueId(ValueID
);
5512 FS
->setOriginalName(GUID
.second
);
5513 TheIndex
.addGlobalValueSummary(GUID
.first
, std::move(FS
));
5516 // FS_COMBINED: [valueid, modid, flags, instcount, fflags, numrefs,
5517 // numrefs x valueid, n x (valueid)]
5518 // FS_COMBINED_PROFILE: [valueid, modid, flags, instcount, fflags, numrefs,
5519 // numrefs x valueid, n x (valueid, hotness)]
5520 case bitc::FS_COMBINED
:
5521 case bitc::FS_COMBINED_PROFILE
: {
5522 unsigned ValueID
= Record
[0];
5523 uint64_t ModuleId
= Record
[1];
5524 uint64_t RawFlags
= Record
[2];
5525 unsigned InstCount
= Record
[3];
5526 uint64_t RawFunFlags
= 0;
5527 uint64_t EntryCount
= 0;
5528 unsigned NumRefs
= Record
[4];
5529 unsigned NumImmutableRefs
= 0;
5530 int RefListStartIndex
= 5;
5533 RawFunFlags
= Record
[4];
5534 RefListStartIndex
= 6;
5535 size_t NumRefsIndex
= 5;
5537 RefListStartIndex
= 7;
5540 EntryCount
= Record
[5];
5541 RefListStartIndex
= 8;
5543 NumImmutableRefs
= Record
[RefListStartIndex
- 1];
5545 NumRefs
= Record
[NumRefsIndex
];
5548 auto Flags
= getDecodedGVSummaryFlags(RawFlags
, Version
);
5549 int CallGraphEdgeStartIndex
= RefListStartIndex
+ NumRefs
;
5550 assert(Record
.size() >= RefListStartIndex
+ NumRefs
&&
5551 "Record size inconsistent with number of references");
5552 std::vector
<ValueInfo
> Refs
= makeRefList(
5553 ArrayRef
<uint64_t>(Record
).slice(RefListStartIndex
, NumRefs
));
5554 bool HasProfile
= (BitCode
== bitc::FS_COMBINED_PROFILE
);
5555 std::vector
<FunctionSummary::EdgeTy
> Edges
= makeCallList(
5556 ArrayRef
<uint64_t>(Record
).slice(CallGraphEdgeStartIndex
),
5557 IsOldProfileFormat
, HasProfile
, false);
5558 ValueInfo VI
= getValueInfoFromValueId(ValueID
).first
;
5559 setImmutableRefs(Refs
, NumImmutableRefs
);
5560 auto FS
= llvm::make_unique
<FunctionSummary
>(
5561 Flags
, InstCount
, getDecodedFFlags(RawFunFlags
), EntryCount
,
5562 std::move(Refs
), std::move(Edges
), std::move(PendingTypeTests
),
5563 std::move(PendingTypeTestAssumeVCalls
),
5564 std::move(PendingTypeCheckedLoadVCalls
),
5565 std::move(PendingTypeTestAssumeConstVCalls
),
5566 std::move(PendingTypeCheckedLoadConstVCalls
));
5567 PendingTypeTests
.clear();
5568 PendingTypeTestAssumeVCalls
.clear();
5569 PendingTypeCheckedLoadVCalls
.clear();
5570 PendingTypeTestAssumeConstVCalls
.clear();
5571 PendingTypeCheckedLoadConstVCalls
.clear();
5572 LastSeenSummary
= FS
.get();
5573 LastSeenGUID
= VI
.getGUID();
5574 FS
->setModulePath(ModuleIdMap
[ModuleId
]);
5575 TheIndex
.addGlobalValueSummary(VI
, std::move(FS
));
5578 // FS_COMBINED_ALIAS: [valueid, modid, flags, valueid]
5579 // Aliases must be emitted (and parsed) after all FS_COMBINED entries, as
5580 // they expect all aliasee summaries to be available.
5581 case bitc::FS_COMBINED_ALIAS
: {
5582 unsigned ValueID
= Record
[0];
5583 uint64_t ModuleId
= Record
[1];
5584 uint64_t RawFlags
= Record
[2];
5585 unsigned AliaseeValueId
= Record
[3];
5586 auto Flags
= getDecodedGVSummaryFlags(RawFlags
, Version
);
5587 auto AS
= llvm::make_unique
<AliasSummary
>(Flags
);
5588 LastSeenSummary
= AS
.get();
5589 AS
->setModulePath(ModuleIdMap
[ModuleId
]);
5592 getValueInfoFromValueId(AliaseeValueId
).first
.getGUID();
5593 auto AliaseeInModule
=
5594 TheIndex
.findSummaryInModule(AliaseeGUID
, AS
->modulePath());
5595 AS
->setAliasee(AliaseeInModule
);
5596 AS
->setAliaseeGUID(AliaseeGUID
);
5598 ValueInfo VI
= getValueInfoFromValueId(ValueID
).first
;
5599 LastSeenGUID
= VI
.getGUID();
5600 TheIndex
.addGlobalValueSummary(VI
, std::move(AS
));
5603 // FS_COMBINED_GLOBALVAR_INIT_REFS: [valueid, modid, flags, n x valueid]
5604 case bitc::FS_COMBINED_GLOBALVAR_INIT_REFS
: {
5605 unsigned ValueID
= Record
[0];
5606 uint64_t ModuleId
= Record
[1];
5607 uint64_t RawFlags
= Record
[2];
5608 unsigned RefArrayStart
= 3;
5609 GlobalVarSummary::GVarFlags GVF
;
5610 auto Flags
= getDecodedGVSummaryFlags(RawFlags
, Version
);
5612 GVF
= getDecodedGVarFlags(Record
[3]);
5615 std::vector
<ValueInfo
> Refs
=
5616 makeRefList(ArrayRef
<uint64_t>(Record
).slice(RefArrayStart
));
5618 llvm::make_unique
<GlobalVarSummary
>(Flags
, GVF
, std::move(Refs
));
5619 LastSeenSummary
= FS
.get();
5620 FS
->setModulePath(ModuleIdMap
[ModuleId
]);
5621 ValueInfo VI
= getValueInfoFromValueId(ValueID
).first
;
5622 LastSeenGUID
= VI
.getGUID();
5623 TheIndex
.addGlobalValueSummary(VI
, std::move(FS
));
5626 // FS_COMBINED_ORIGINAL_NAME: [original_name]
5627 case bitc::FS_COMBINED_ORIGINAL_NAME
: {
5628 uint64_t OriginalName
= Record
[0];
5629 if (!LastSeenSummary
)
5630 return error("Name attachment that does not follow a combined record");
5631 LastSeenSummary
->setOriginalName(OriginalName
);
5632 TheIndex
.addOriginalName(LastSeenGUID
, OriginalName
);
5633 // Reset the LastSeenSummary
5634 LastSeenSummary
= nullptr;
5638 case bitc::FS_TYPE_TESTS
:
5639 assert(PendingTypeTests
.empty());
5640 PendingTypeTests
.insert(PendingTypeTests
.end(), Record
.begin(),
5644 case bitc::FS_TYPE_TEST_ASSUME_VCALLS
:
5645 assert(PendingTypeTestAssumeVCalls
.empty());
5646 for (unsigned I
= 0; I
!= Record
.size(); I
+= 2)
5647 PendingTypeTestAssumeVCalls
.push_back({Record
[I
], Record
[I
+1]});
5650 case bitc::FS_TYPE_CHECKED_LOAD_VCALLS
:
5651 assert(PendingTypeCheckedLoadVCalls
.empty());
5652 for (unsigned I
= 0; I
!= Record
.size(); I
+= 2)
5653 PendingTypeCheckedLoadVCalls
.push_back({Record
[I
], Record
[I
+1]});
5656 case bitc::FS_TYPE_TEST_ASSUME_CONST_VCALL
:
5657 PendingTypeTestAssumeConstVCalls
.push_back(
5658 {{Record
[0], Record
[1]}, {Record
.begin() + 2, Record
.end()}});
5661 case bitc::FS_TYPE_CHECKED_LOAD_CONST_VCALL
:
5662 PendingTypeCheckedLoadConstVCalls
.push_back(
5663 {{Record
[0], Record
[1]}, {Record
.begin() + 2, Record
.end()}});
5666 case bitc::FS_CFI_FUNCTION_DEFS
: {
5667 std::set
<std::string
> &CfiFunctionDefs
= TheIndex
.cfiFunctionDefs();
5668 for (unsigned I
= 0; I
!= Record
.size(); I
+= 2)
5669 CfiFunctionDefs
.insert(
5670 {Strtab
.data() + Record
[I
], static_cast<size_t>(Record
[I
+ 1])});
5674 case bitc::FS_CFI_FUNCTION_DECLS
: {
5675 std::set
<std::string
> &CfiFunctionDecls
= TheIndex
.cfiFunctionDecls();
5676 for (unsigned I
= 0; I
!= Record
.size(); I
+= 2)
5677 CfiFunctionDecls
.insert(
5678 {Strtab
.data() + Record
[I
], static_cast<size_t>(Record
[I
+ 1])});
5682 case bitc::FS_TYPE_ID
:
5683 parseTypeIdSummaryRecord(Record
, Strtab
, TheIndex
);
5687 llvm_unreachable("Exit infinite loop");
5690 // Parse the module string table block into the Index.
5691 // This populates the ModulePathStringTable map in the index.
5692 Error
ModuleSummaryIndexBitcodeReader::parseModuleStringTable() {
5693 if (Stream
.EnterSubBlock(bitc::MODULE_STRTAB_BLOCK_ID
))
5694 return error("Invalid record");
5696 SmallVector
<uint64_t, 64> Record
;
5698 SmallString
<128> ModulePath
;
5699 ModuleSummaryIndex::ModuleInfo
*LastSeenModule
= nullptr;
5702 BitstreamEntry Entry
= Stream
.advanceSkippingSubblocks();
5704 switch (Entry
.Kind
) {
5705 case BitstreamEntry::SubBlock
: // Handled for us already.
5706 case BitstreamEntry::Error
:
5707 return error("Malformed block");
5708 case BitstreamEntry::EndBlock
:
5709 return Error::success();
5710 case BitstreamEntry::Record
:
5711 // The interesting case.
5716 switch (Stream
.readRecord(Entry
.ID
, Record
)) {
5717 default: // Default behavior: ignore.
5719 case bitc::MST_CODE_ENTRY
: {
5720 // MST_ENTRY: [modid, namechar x N]
5721 uint64_t ModuleId
= Record
[0];
5723 if (convertToString(Record
, 1, ModulePath
))
5724 return error("Invalid record");
5726 LastSeenModule
= TheIndex
.addModule(ModulePath
, ModuleId
);
5727 ModuleIdMap
[ModuleId
] = LastSeenModule
->first();
5732 /// MST_CODE_HASH: [5*i32]
5733 case bitc::MST_CODE_HASH
: {
5734 if (Record
.size() != 5)
5735 return error("Invalid hash length " + Twine(Record
.size()).str());
5736 if (!LastSeenModule
)
5737 return error("Invalid hash that does not follow a module path");
5739 for (auto &Val
: Record
) {
5740 assert(!(Val
>> 32) && "Unexpected high bits set");
5741 LastSeenModule
->second
.second
[Pos
++] = Val
;
5743 // Reset LastSeenModule to avoid overriding the hash unexpectedly.
5744 LastSeenModule
= nullptr;
5749 llvm_unreachable("Exit infinite loop");
5754 // FIXME: This class is only here to support the transition to llvm::Error. It
5755 // will be removed once this transition is complete. Clients should prefer to
5756 // deal with the Error value directly, rather than converting to error_code.
5757 class BitcodeErrorCategoryType
: public std::error_category
{
5758 const char *name() const noexcept override
{
5759 return "llvm.bitcode";
5762 std::string
message(int IE
) const override
{
5763 BitcodeError E
= static_cast<BitcodeError
>(IE
);
5765 case BitcodeError::CorruptedBitcode
:
5766 return "Corrupted bitcode";
5768 llvm_unreachable("Unknown error type!");
5772 } // end anonymous namespace
5774 static ManagedStatic
<BitcodeErrorCategoryType
> ErrorCategory
;
5776 const std::error_category
&llvm::BitcodeErrorCategory() {
5777 return *ErrorCategory
;
5780 static Expected
<StringRef
> readBlobInRecord(BitstreamCursor
&Stream
,
5781 unsigned Block
, unsigned RecordID
) {
5782 if (Stream
.EnterSubBlock(Block
))
5783 return error("Invalid record");
5787 BitstreamEntry Entry
= Stream
.advance();
5788 switch (Entry
.Kind
) {
5789 case BitstreamEntry::EndBlock
:
5792 case BitstreamEntry::Error
:
5793 return error("Malformed block");
5795 case BitstreamEntry::SubBlock
:
5796 if (Stream
.SkipBlock())
5797 return error("Malformed block");
5800 case BitstreamEntry::Record
:
5802 SmallVector
<uint64_t, 1> Record
;
5803 if (Stream
.readRecord(Entry
.ID
, Record
, &Blob
) == RecordID
)
5810 //===----------------------------------------------------------------------===//
5811 // External interface
5812 //===----------------------------------------------------------------------===//
5814 Expected
<std::vector
<BitcodeModule
>>
5815 llvm::getBitcodeModuleList(MemoryBufferRef Buffer
) {
5816 auto FOrErr
= getBitcodeFileContents(Buffer
);
5818 return FOrErr
.takeError();
5819 return std::move(FOrErr
->Mods
);
5822 Expected
<BitcodeFileContents
>
5823 llvm::getBitcodeFileContents(MemoryBufferRef Buffer
) {
5824 Expected
<BitstreamCursor
> StreamOrErr
= initStream(Buffer
);
5826 return StreamOrErr
.takeError();
5827 BitstreamCursor
&Stream
= *StreamOrErr
;
5829 BitcodeFileContents F
;
5831 uint64_t BCBegin
= Stream
.getCurrentByteNo();
5833 // We may be consuming bitcode from a client that leaves garbage at the end
5834 // of the bitcode stream (e.g. Apple's ar tool). If we are close enough to
5835 // the end that there cannot possibly be another module, stop looking.
5836 if (BCBegin
+ 8 >= Stream
.getBitcodeBytes().size())
5839 BitstreamEntry Entry
= Stream
.advance();
5840 switch (Entry
.Kind
) {
5841 case BitstreamEntry::EndBlock
:
5842 case BitstreamEntry::Error
:
5843 return error("Malformed block");
5845 case BitstreamEntry::SubBlock
: {
5846 uint64_t IdentificationBit
= -1ull;
5847 if (Entry
.ID
== bitc::IDENTIFICATION_BLOCK_ID
) {
5848 IdentificationBit
= Stream
.GetCurrentBitNo() - BCBegin
* 8;
5849 if (Stream
.SkipBlock())
5850 return error("Malformed block");
5852 Entry
= Stream
.advance();
5853 if (Entry
.Kind
!= BitstreamEntry::SubBlock
||
5854 Entry
.ID
!= bitc::MODULE_BLOCK_ID
)
5855 return error("Malformed block");
5858 if (Entry
.ID
== bitc::MODULE_BLOCK_ID
) {
5859 uint64_t ModuleBit
= Stream
.GetCurrentBitNo() - BCBegin
* 8;
5860 if (Stream
.SkipBlock())
5861 return error("Malformed block");
5863 F
.Mods
.push_back({Stream
.getBitcodeBytes().slice(
5864 BCBegin
, Stream
.getCurrentByteNo() - BCBegin
),
5865 Buffer
.getBufferIdentifier(), IdentificationBit
,
5870 if (Entry
.ID
== bitc::STRTAB_BLOCK_ID
) {
5871 Expected
<StringRef
> Strtab
=
5872 readBlobInRecord(Stream
, bitc::STRTAB_BLOCK_ID
, bitc::STRTAB_BLOB
);
5874 return Strtab
.takeError();
5875 // This string table is used by every preceding bitcode module that does
5876 // not have its own string table. A bitcode file may have multiple
5877 // string tables if it was created by binary concatenation, for example
5878 // with "llvm-cat -b".
5879 for (auto I
= F
.Mods
.rbegin(), E
= F
.Mods
.rend(); I
!= E
; ++I
) {
5880 if (!I
->Strtab
.empty())
5882 I
->Strtab
= *Strtab
;
5884 // Similarly, the string table is used by every preceding symbol table;
5885 // normally there will be just one unless the bitcode file was created
5886 // by binary concatenation.
5887 if (!F
.Symtab
.empty() && F
.StrtabForSymtab
.empty())
5888 F
.StrtabForSymtab
= *Strtab
;
5892 if (Entry
.ID
== bitc::SYMTAB_BLOCK_ID
) {
5893 Expected
<StringRef
> SymtabOrErr
=
5894 readBlobInRecord(Stream
, bitc::SYMTAB_BLOCK_ID
, bitc::SYMTAB_BLOB
);
5896 return SymtabOrErr
.takeError();
5898 // We can expect the bitcode file to have multiple symbol tables if it
5899 // was created by binary concatenation. In that case we silently
5900 // ignore any subsequent symbol tables, which is fine because this is a
5901 // low level function. The client is expected to notice that the number
5902 // of modules in the symbol table does not match the number of modules
5903 // in the input file and regenerate the symbol table.
5904 if (F
.Symtab
.empty())
5905 F
.Symtab
= *SymtabOrErr
;
5909 if (Stream
.SkipBlock())
5910 return error("Malformed block");
5913 case BitstreamEntry::Record
:
5914 Stream
.skipRecord(Entry
.ID
);
5920 /// Get a lazy one-at-time loading module from bitcode.
5922 /// This isn't always used in a lazy context. In particular, it's also used by
5923 /// \a parseModule(). If this is truly lazy, then we need to eagerly pull
5924 /// in forward-referenced functions from block address references.
5926 /// \param[in] MaterializeAll Set to \c true if we should materialize
5928 Expected
<std::unique_ptr
<Module
>>
5929 BitcodeModule::getModuleImpl(LLVMContext
&Context
, bool MaterializeAll
,
5930 bool ShouldLazyLoadMetadata
, bool IsImporting
) {
5931 BitstreamCursor
Stream(Buffer
);
5933 std::string ProducerIdentification
;
5934 if (IdentificationBit
!= -1ull) {
5935 Stream
.JumpToBit(IdentificationBit
);
5936 Expected
<std::string
> ProducerIdentificationOrErr
=
5937 readIdentificationBlock(Stream
);
5938 if (!ProducerIdentificationOrErr
)
5939 return ProducerIdentificationOrErr
.takeError();
5941 ProducerIdentification
= *ProducerIdentificationOrErr
;
5944 Stream
.JumpToBit(ModuleBit
);
5945 auto *R
= new BitcodeReader(std::move(Stream
), Strtab
, ProducerIdentification
,
5948 std::unique_ptr
<Module
> M
=
5949 llvm::make_unique
<Module
>(ModuleIdentifier
, Context
);
5950 M
->setMaterializer(R
);
5952 // Delay parsing Metadata if ShouldLazyLoadMetadata is true.
5954 R
->parseBitcodeInto(M
.get(), ShouldLazyLoadMetadata
, IsImporting
))
5955 return std::move(Err
);
5957 if (MaterializeAll
) {
5958 // Read in the entire module, and destroy the BitcodeReader.
5959 if (Error Err
= M
->materializeAll())
5960 return std::move(Err
);
5962 // Resolve forward references from blockaddresses.
5963 if (Error Err
= R
->materializeForwardReferencedFunctions())
5964 return std::move(Err
);
5966 return std::move(M
);
5969 Expected
<std::unique_ptr
<Module
>>
5970 BitcodeModule::getLazyModule(LLVMContext
&Context
, bool ShouldLazyLoadMetadata
,
5972 return getModuleImpl(Context
, false, ShouldLazyLoadMetadata
, IsImporting
);
5975 // Parse the specified bitcode buffer and merge the index into CombinedIndex.
5976 // We don't use ModuleIdentifier here because the client may need to control the
5977 // module path used in the combined summary (e.g. when reading summaries for
5978 // regular LTO modules).
5979 Error
BitcodeModule::readSummary(ModuleSummaryIndex
&CombinedIndex
,
5980 StringRef ModulePath
, uint64_t ModuleId
) {
5981 BitstreamCursor
Stream(Buffer
);
5982 Stream
.JumpToBit(ModuleBit
);
5984 ModuleSummaryIndexBitcodeReader
R(std::move(Stream
), Strtab
, CombinedIndex
,
5985 ModulePath
, ModuleId
);
5986 return R
.parseModule();
5989 // Parse the specified bitcode buffer, returning the function info index.
5990 Expected
<std::unique_ptr
<ModuleSummaryIndex
>> BitcodeModule::getSummary() {
5991 BitstreamCursor
Stream(Buffer
);
5992 Stream
.JumpToBit(ModuleBit
);
5994 auto Index
= llvm::make_unique
<ModuleSummaryIndex
>(/*HaveGVs=*/false);
5995 ModuleSummaryIndexBitcodeReader
R(std::move(Stream
), Strtab
, *Index
,
5996 ModuleIdentifier
, 0);
5998 if (Error Err
= R
.parseModule())
5999 return std::move(Err
);
6001 return std::move(Index
);
6004 static Expected
<bool> getEnableSplitLTOUnitFlag(BitstreamCursor
&Stream
,
6006 if (Stream
.EnterSubBlock(ID
))
6007 return error("Invalid record");
6008 SmallVector
<uint64_t, 64> Record
;
6011 BitstreamEntry Entry
= Stream
.advanceSkippingSubblocks();
6013 switch (Entry
.Kind
) {
6014 case BitstreamEntry::SubBlock
: // Handled for us already.
6015 case BitstreamEntry::Error
:
6016 return error("Malformed block");
6017 case BitstreamEntry::EndBlock
:
6018 // If no flags record found, conservatively return true to mimic
6019 // behavior before this flag was added.
6021 case BitstreamEntry::Record
:
6022 // The interesting case.
6026 // Look for the FS_FLAGS record.
6028 auto BitCode
= Stream
.readRecord(Entry
.ID
, Record
);
6030 default: // Default behavior: ignore.
6032 case bitc::FS_FLAGS
: { // [flags]
6033 uint64_t Flags
= Record
[0];
6035 assert(Flags
<= 0x1f && "Unexpected bits in flag");
6041 llvm_unreachable("Exit infinite loop");
6044 // Check if the given bitcode buffer contains a global value summary block.
6045 Expected
<BitcodeLTOInfo
> BitcodeModule::getLTOInfo() {
6046 BitstreamCursor
Stream(Buffer
);
6047 Stream
.JumpToBit(ModuleBit
);
6049 if (Stream
.EnterSubBlock(bitc::MODULE_BLOCK_ID
))
6050 return error("Invalid record");
6053 BitstreamEntry Entry
= Stream
.advance();
6055 switch (Entry
.Kind
) {
6056 case BitstreamEntry::Error
:
6057 return error("Malformed block");
6058 case BitstreamEntry::EndBlock
:
6059 return BitcodeLTOInfo
{/*IsThinLTO=*/false, /*HasSummary=*/false,
6060 /*EnableSplitLTOUnit=*/false};
6062 case BitstreamEntry::SubBlock
:
6063 if (Entry
.ID
== bitc::GLOBALVAL_SUMMARY_BLOCK_ID
) {
6064 Expected
<bool> EnableSplitLTOUnit
=
6065 getEnableSplitLTOUnitFlag(Stream
, Entry
.ID
);
6066 if (!EnableSplitLTOUnit
)
6067 return EnableSplitLTOUnit
.takeError();
6068 return BitcodeLTOInfo
{/*IsThinLTO=*/true, /*HasSummary=*/true,
6069 *EnableSplitLTOUnit
};
6072 if (Entry
.ID
== bitc::FULL_LTO_GLOBALVAL_SUMMARY_BLOCK_ID
) {
6073 Expected
<bool> EnableSplitLTOUnit
=
6074 getEnableSplitLTOUnitFlag(Stream
, Entry
.ID
);
6075 if (!EnableSplitLTOUnit
)
6076 return EnableSplitLTOUnit
.takeError();
6077 return BitcodeLTOInfo
{/*IsThinLTO=*/false, /*HasSummary=*/true,
6078 *EnableSplitLTOUnit
};
6081 // Ignore other sub-blocks.
6082 if (Stream
.SkipBlock())
6083 return error("Malformed block");
6086 case BitstreamEntry::Record
:
6087 Stream
.skipRecord(Entry
.ID
);
6093 static Expected
<BitcodeModule
> getSingleModule(MemoryBufferRef Buffer
) {
6094 Expected
<std::vector
<BitcodeModule
>> MsOrErr
= getBitcodeModuleList(Buffer
);
6096 return MsOrErr
.takeError();
6098 if (MsOrErr
->size() != 1)
6099 return error("Expected a single module");
6101 return (*MsOrErr
)[0];
6104 Expected
<std::unique_ptr
<Module
>>
6105 llvm::getLazyBitcodeModule(MemoryBufferRef Buffer
, LLVMContext
&Context
,
6106 bool ShouldLazyLoadMetadata
, bool IsImporting
) {
6107 Expected
<BitcodeModule
> BM
= getSingleModule(Buffer
);
6109 return BM
.takeError();
6111 return BM
->getLazyModule(Context
, ShouldLazyLoadMetadata
, IsImporting
);
6114 Expected
<std::unique_ptr
<Module
>> llvm::getOwningLazyBitcodeModule(
6115 std::unique_ptr
<MemoryBuffer
> &&Buffer
, LLVMContext
&Context
,
6116 bool ShouldLazyLoadMetadata
, bool IsImporting
) {
6117 auto MOrErr
= getLazyBitcodeModule(*Buffer
, Context
, ShouldLazyLoadMetadata
,
6120 (*MOrErr
)->setOwnedMemoryBuffer(std::move(Buffer
));
6124 Expected
<std::unique_ptr
<Module
>>
6125 BitcodeModule::parseModule(LLVMContext
&Context
) {
6126 return getModuleImpl(Context
, true, false, false);
6127 // TODO: Restore the use-lists to the in-memory state when the bitcode was
6128 // written. We must defer until the Module has been fully materialized.
6131 Expected
<std::unique_ptr
<Module
>> llvm::parseBitcodeFile(MemoryBufferRef Buffer
,
6132 LLVMContext
&Context
) {
6133 Expected
<BitcodeModule
> BM
= getSingleModule(Buffer
);
6135 return BM
.takeError();
6137 return BM
->parseModule(Context
);
6140 Expected
<std::string
> llvm::getBitcodeTargetTriple(MemoryBufferRef Buffer
) {
6141 Expected
<BitstreamCursor
> StreamOrErr
= initStream(Buffer
);
6143 return StreamOrErr
.takeError();
6145 return readTriple(*StreamOrErr
);
6148 Expected
<bool> llvm::isBitcodeContainingObjCCategory(MemoryBufferRef Buffer
) {
6149 Expected
<BitstreamCursor
> StreamOrErr
= initStream(Buffer
);
6151 return StreamOrErr
.takeError();
6153 return hasObjCCategory(*StreamOrErr
);
6156 Expected
<std::string
> llvm::getBitcodeProducerString(MemoryBufferRef Buffer
) {
6157 Expected
<BitstreamCursor
> StreamOrErr
= initStream(Buffer
);
6159 return StreamOrErr
.takeError();
6161 return readIdentificationCode(*StreamOrErr
);
6164 Error
llvm::readModuleSummaryIndex(MemoryBufferRef Buffer
,
6165 ModuleSummaryIndex
&CombinedIndex
,
6166 uint64_t ModuleId
) {
6167 Expected
<BitcodeModule
> BM
= getSingleModule(Buffer
);
6169 return BM
.takeError();
6171 return BM
->readSummary(CombinedIndex
, BM
->getModuleIdentifier(), ModuleId
);
6174 Expected
<std::unique_ptr
<ModuleSummaryIndex
>>
6175 llvm::getModuleSummaryIndex(MemoryBufferRef Buffer
) {
6176 Expected
<BitcodeModule
> BM
= getSingleModule(Buffer
);
6178 return BM
.takeError();
6180 return BM
->getSummary();
6183 Expected
<BitcodeLTOInfo
> llvm::getBitcodeLTOInfo(MemoryBufferRef Buffer
) {
6184 Expected
<BitcodeModule
> BM
= getSingleModule(Buffer
);
6186 return BM
.takeError();
6188 return BM
->getLTOInfo();
6191 Expected
<std::unique_ptr
<ModuleSummaryIndex
>>
6192 llvm::getModuleSummaryIndexForFile(StringRef Path
,
6193 bool IgnoreEmptyThinLTOIndexFile
) {
6194 ErrorOr
<std::unique_ptr
<MemoryBuffer
>> FileOrErr
=
6195 MemoryBuffer::getFileOrSTDIN(Path
);
6197 return errorCodeToError(FileOrErr
.getError());
6198 if (IgnoreEmptyThinLTOIndexFile
&& !(*FileOrErr
)->getBufferSize())
6200 return getModuleSummaryIndex(**FileOrErr
);