Bug Summary

File:lib/Bitcode/Reader/BitcodeReader.cpp
Warning:line 4654, column 9
Called C++ object pointer is null

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -disable-llvm-verifier -discard-value-names -main-file-name BitcodeReader.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mthread-model posix -fmath-errno -masm-verbose -mconstructor-aliases -munwind-tables -fuse-init-array -target-cpu x86-64 -dwarf-column-info -debugger-tuning=gdb -momit-leaf-frame-pointer -ffunction-sections -fdata-sections -resource-dir /usr/lib/llvm-9/lib/clang/9.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-9~svn362543/build-llvm/lib/Bitcode/Reader -I /build/llvm-toolchain-snapshot-9~svn362543/lib/Bitcode/Reader -I /build/llvm-toolchain-snapshot-9~svn362543/build-llvm/include -I /build/llvm-toolchain-snapshot-9~svn362543/include -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0/backward -internal-isystem /usr/include/clang/9.0.0/include/ -internal-isystem /usr/local/include -internal-isystem /usr/lib/llvm-9/lib/clang/9.0.0/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -O2 -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-comment -std=c++11 -fdeprecated-macro -fdebug-compilation-dir /build/llvm-toolchain-snapshot-9~svn362543/build-llvm/lib/Bitcode/Reader -fdebug-prefix-map=/build/llvm-toolchain-snapshot-9~svn362543=. -ferror-limit 19 -fmessage-length 0 -fvisibility-inlines-hidden -stack-protector 2 -fobjc-runtime=gcc -fdiagnostics-show-option -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -o /tmp/scan-build-2019-06-05-060531-1271-1 -x c++ /build/llvm-toolchain-snapshot-9~svn362543/lib/Bitcode/Reader/BitcodeReader.cpp -faddrsig
1//===- BitcodeReader.cpp - Internal BitcodeReader implementation ----------===//
2//
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
6//
7//===----------------------------------------------------------------------===//
8
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"
74#include <algorithm>
75#include <cassert>
76#include <cstddef>
77#include <cstdint>
78#include <deque>
79#include <map>
80#include <memory>
81#include <set>
82#include <string>
83#include <system_error>
84#include <tuple>
85#include <utility>
86#include <vector>
87
88using namespace llvm;
89
90static cl::opt<bool> PrintSummaryGUIDs(
91 "print-summary-global-ids", cl::init(false), cl::Hidden,
92 cl::desc(
93 "Print the global id for each value when reading the module summary"));
94
95namespace {
96
97enum {
98 SWITCH_INST_MAGIC = 0x4B5 // May 2012 => 1205 => Hex
99};
100
101} // end anonymous namespace
102
103static Error error(const Twine &Message) {
104 return make_error<StringError>(
105 Message, make_error_code(BitcodeError::CorruptedBitcode));
106}
107
108/// Helper to read the header common to all bitcode files.
109static 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)
118 return false;
119 return true;
120}
121
122static Expected<BitstreamCursor> initStream(MemoryBufferRef Buffer) {
123 const unsigned char *BufPtr = (const unsigned char *)Buffer.getBufferStart();
124 const unsigned char *BufEnd = BufPtr + Buffer.getBufferSize();
125
126 if (Buffer.getBufferSize() & 3)
127 return error("Invalid bitcode signature");
128
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");
134
135 BitstreamCursor Stream(ArrayRef<uint8_t>(BufPtr, BufEnd));
136 if (!hasValidBitcodeHeader(Stream))
137 return error("Invalid bitcode signature");
138
139 return std::move(Stream);
140}
141
142/// Convert a string from a record into an std::string, return true on failure.
143template <typename StrTy>
144static bool convertToString(ArrayRef<uint64_t> Record, unsigned Idx,
145 StrTy &Result) {
146 if (Idx > Record.size())
147 return true;
148
149 for (unsigned i = Idx, e = Record.size(); i != e; ++i)
150 Result += (char)Record[i];
151 return false;
152}
153
154// Strip all the TBAA attachment for the module.
155static void stripTBAA(Module *M) {
156 for (auto &F : *M) {
157 if (F.isMaterializable())
158 continue;
159 for (auto &I : instructions(F))
160 I.setMetadata(LLVMContext::MD_tbaa, nullptr);
161 }
162}
163
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.
166static Expected<std::string> readIdentificationBlock(BitstreamCursor &Stream) {
167 if (Stream.EnterSubBlock(bitc::IDENTIFICATION_BLOCK_ID))
168 return error("Invalid record");
169
170 // Read all the records.
171 SmallVector<uint64_t, 64> Record;
172
173 std::string ProducerIdentification;
174
175 while (true) {
176 BitstreamEntry Entry = Stream.advance();
177
178 switch (Entry.Kind) {
179 default:
180 case BitstreamEntry::Error:
181 return error("Malformed block");
182 case BitstreamEntry::EndBlock:
183 return ProducerIdentification;
184 case BitstreamEntry::Record:
185 // The interesting case.
186 break;
187 }
188
189 // Read a record.
190 Record.clear();
191 unsigned BitCode = Stream.readRecord(Entry.ID, Record);
192 switch (BitCode) {
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);
197 break;
198 case bitc::IDENTIFICATION_CODE_EPOCH: { // EPOCH: [epoch#]
199 unsigned epoch = (unsigned)Record[0];
200 if (epoch != bitc::BITCODE_CURRENT_EPOCH) {
201 return error(
202 Twine("Incompatible epoch: Bitcode '") + Twine(epoch) +
203 "' vs current: '" + Twine(bitc::BITCODE_CURRENT_EPOCH) + "'");
204 }
205 }
206 }
207 }
208}
209
210static 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.
213 while (true) {
214 if (Stream.AtEndOfStream())
215 return "";
216
217 BitstreamEntry Entry = Stream.advance();
218 switch (Entry.Kind) {
219 case BitstreamEntry::EndBlock:
220 case BitstreamEntry::Error:
221 return error("Malformed block");
222
223 case BitstreamEntry::SubBlock:
224 if (Entry.ID == bitc::IDENTIFICATION_BLOCK_ID)
225 return readIdentificationBlock(Stream);
226
227 // Ignore other sub-blocks.
228 if (Stream.SkipBlock())
229 return error("Malformed block");
230 continue;
231 case BitstreamEntry::Record:
232 Stream.skipRecord(Entry.ID);
233 continue;
234 }
235 }
236}
237
238static Expected<bool> hasObjCCategoryInModule(BitstreamCursor &Stream) {
239 if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
240 return error("Invalid record");
241
242 SmallVector<uint64_t, 64> Record;
243 // Read all the records for this module.
244
245 while (true) {
246 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
247
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:
253 return false;
254 case BitstreamEntry::Record:
255 // The interesting case.
256 break;
257 }
258
259 // Read a record.
260 switch (Stream.readRecord(Entry.ID, Record)) {
261 default:
262 break; // Default behavior, ignore unknown content.
263 case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N]
264 std::string S;
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)
270 return true;
271 break;
272 }
273 }
274 Record.clear();
275 }
276 llvm_unreachable("Exit infinite loop")::llvm::llvm_unreachable_internal("Exit infinite loop", "/build/llvm-toolchain-snapshot-9~svn362543/lib/Bitcode/Reader/BitcodeReader.cpp"
, 276)
;
277}
278
279static 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.
282 while (true) {
283 BitstreamEntry Entry = Stream.advance();
284
285 switch (Entry.Kind) {
286 case BitstreamEntry::Error:
287 return error("Malformed block");
288 case BitstreamEntry::EndBlock:
289 return false;
290
291 case BitstreamEntry::SubBlock:
292 if (Entry.ID == bitc::MODULE_BLOCK_ID)
293 return hasObjCCategoryInModule(Stream);
294
295 // Ignore other sub-blocks.
296 if (Stream.SkipBlock())
297 return error("Malformed block");
298 continue;
299
300 case BitstreamEntry::Record:
301 Stream.skipRecord(Entry.ID);
302 continue;
303 }
304 }
305}
306
307static Expected<std::string> readModuleTriple(BitstreamCursor &Stream) {
308 if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
309 return error("Invalid record");
310
311 SmallVector<uint64_t, 64> Record;
312
313 std::string Triple;
314
315 // Read all the records for this module.
316 while (true) {
317 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
318
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:
324 return Triple;
325 case BitstreamEntry::Record:
326 // The interesting case.
327 break;
328 }
329
330 // Read a record.
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]
334 std::string S;
335 if (convertToString(Record, 0, S))
336 return error("Invalid record");
337 Triple = S;
338 break;
339 }
340 }
341 Record.clear();
342 }
343 llvm_unreachable("Exit infinite loop")::llvm::llvm_unreachable_internal("Exit infinite loop", "/build/llvm-toolchain-snapshot-9~svn362543/lib/Bitcode/Reader/BitcodeReader.cpp"
, 343)
;
344}
345
346static 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.
349 while (true) {
350 BitstreamEntry Entry = Stream.advance();
351
352 switch (Entry.Kind) {
353 case BitstreamEntry::Error:
354 return error("Malformed block");
355 case BitstreamEntry::EndBlock:
356 return "";
357
358 case BitstreamEntry::SubBlock:
359 if (Entry.ID == bitc::MODULE_BLOCK_ID)
360 return readModuleTriple(Stream);
361
362 // Ignore other sub-blocks.
363 if (Stream.SkipBlock())
364 return error("Malformed block");
365 continue;
366
367 case BitstreamEntry::Record:
368 Stream.skipRecord(Entry.ID);
369 continue;
370 }
371 }
372}
373
374namespace {
375
376class BitcodeReaderBase {
377protected:
378 BitcodeReaderBase(BitstreamCursor Stream, StringRef Strtab)
379 : Stream(std::move(Stream)), Strtab(Strtab) {
380 this->Stream.setBlockInfo(&BlockInfo);
381 }
382
383 BitstreamBlockInfo BlockInfo;
384 BitstreamCursor Stream;
385 StringRef Strtab;
386
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;
390
391 Expected<unsigned> parseVersionRecord(ArrayRef<uint64_t> Record);
392
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);
398
399 bool readBlockInfo();
400
401 // Contains an arbitrary and optional string identifying the bitcode producer
402 std::string ProducerIdentification;
403
404 Error error(const Twine &Message);
405};
406
407} // end anonymous namespace
408
409Error 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"9.0.0" "')";
414 return ::error(FullMsg);
415}
416
417Expected<unsigned>
418BitcodeReaderBase::parseVersionRecord(ArrayRef<uint64_t> Record) {
419 if (Record.empty())
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;
426}
427
428std::pair<StringRef, ArrayRef<uint64_t>>
429BitcodeReaderBase::readNameFromStrtab(ArrayRef<uint64_t> Record) {
430 if (!UseStrtab)
431 return {"", Record};
432 // Invalid reference. Let the caller complain about the record being empty.
433 if (Record[0] + Record[1] > Strtab.size())
434 return {"", {}};
435 return {StringRef(Strtab.data() + Record[0], Record[1]), Record.slice(2)};
436}
437
438namespace {
439
440class 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;
449
450 std::vector<std::string> SectionTable;
451 std::vector<std::string> GCTable;
452
453 std::vector<Type*> TypeList;
454 BitcodeReaderValueList ValueList;
455 Optional<MetadataLoader> MDLoader;
456 std::vector<Comdat *> ComdatList;
457 SmallVector<Instruction *, 64> InstructionList;
458
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;
464
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;
468
469 /// The set of attribute groups.
470 std::map<unsigned, AttributeList> MAttributeGroups;
471
472 /// While parsing a function body, this is a list of the basic blocks for the
473 /// function.
474 std::vector<BasicBlock*> FunctionBBs;
475
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;
479
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;
486
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;
491
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;
495
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;
500
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;
506
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;
514
515 /// True if all functions will be materialized, negating the need to process
516 /// (e.g.) blockaddress forward references.
517 bool WillMaterializeAllForwardRefs = false;
518
519 bool StripDebugInfo = false;
520 TBAAVerifier TBAAVerifyHelper;
521
522 std::vector<std::string> BundleTags;
523 SmallVector<SyncScope::ID, 8> SSIDs;
524
525public:
526 BitcodeReader(BitstreamCursor Stream, StringRef Strtab,
527 StringRef ProducerIdentification, LLVMContext &Context);
528
529 Error materializeForwardReferencedFunctions();
530
531 Error materialize(GlobalValue *GV) override;
532 Error materializeModule() override;
533 std::vector<StructType *> getIdentifiedStructTypes() const override;
534
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);
539
540 static uint64_t decodeSignRotatedValue(uint64_t V);
541
542 /// Materialize any deferred Metadata block.
543 Error materializeMetadata() override;
544
545 void setStripDebugInfo() override;
546
547private:
548 std::vector<StructType *> IdentifiedStructTypes;
549 StructType *createIdentifiedStructType(LLVMContext &Context, StringRef Name);
550 StructType *createIdentifiedStructType(LLVMContext &Context);
551
552 Type *getTypeByID(unsigned ID);
553
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);
558 }
559
560 Metadata *getFnMetadataByID(unsigned ID) {
561 return MDLoader->getMetadataFwdRefOrLoad(ID);
562 }
563
564 BasicBlock *getBasicBlock(unsigned ID) const {
565 if (ID >= FunctionBBs.size()) return nullptr; // Invalid ID
566 return FunctionBBs[ID];
567 }
568
569 AttributeList getAttributes(unsigned i) const {
570 if (i-1 < MAttributes.size())
571 return MAttributes[i-1];
572 return AttributeList();
573 }
574
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
577 /// failure.
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.
583 if (UseRelativeIDs)
584 ValNo = InstNum - ValNo;
585 if (ValNo < InstNum) {
586 // If this is not a forward reference, just return the value we already
587 // have.
588 ResVal = getFnValueByID(ValNo, nullptr);
589 return ResVal == nullptr;
590 }
591 if (Slot == Record.size())
592 return true;
593
594 unsigned TypeNo = (unsigned)Record[Slot++];
595 ResVal = getFnValueByID(ValNo, getTypeByID(TypeNo));
596 return ResVal == nullptr;
597 }
598
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))
605 return true;
606 // All values currently take a single record slot.
607 ++Slot;
608 return false;
609 }
610
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;
616 }
617
618 /// Version of getValue that returns ResVal directly, or 0 if there is an
619 /// error.
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.
625 if (UseRelativeIDs)
626 ValNo = InstNum - ValNo;
627 return getFnValueByID(ValNo, Ty);
628 }
629
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.
636 if (UseRelativeIDs)
637 ValNo = InstNum - ValNo;
638 return getFnValueByID(ValNo, Ty);
639 }
640
641 /// Upgrades old-style typeless byval attributes by adding the corresponding
642 /// argument's pointee type.
643 void propagateByValTypes(CallBase *CB);
644
645 /// Converts alignment exponent (i.e. power of two (or zero)) to the
646 /// corresponding alignment to use. If alignment is too large, returns
647 /// a corresponding error code.
648 Error parseAlignmentValue(uint64_t Exponent, unsigned &Alignment);
649 Error parseAttrKind(uint64_t Code, Attribute::AttrKind *Kind);
650 Error parseModule(uint64_t ResumeBit, bool ShouldLazyLoadMetadata = false);
651
652 Error parseComdatRecord(ArrayRef<uint64_t> Record);
653 Error parseGlobalVarRecord(ArrayRef<uint64_t> Record);
654 Error parseFunctionRecord(ArrayRef<uint64_t> Record);
655 Error parseGlobalIndirectSymbolRecord(unsigned BitCode,
656 ArrayRef<uint64_t> Record);
657
658 Error parseAttributeBlock();
659 Error parseAttributeGroupBlock();
660 Error parseTypeTable();
661 Error parseTypeTableBody();
662 Error parseOperandBundleTags();
663 Error parseSyncScopeNames();
664
665 Expected<Value *> recordValue(SmallVectorImpl<uint64_t> &Record,
666 unsigned NameIndex, Triple &TT);
667 void setDeferredFunctionInfo(unsigned FuncBitcodeOffsetDelta, Function *F,
668 ArrayRef<uint64_t> Record);
669 Error parseValueSymbolTable(uint64_t Offset = 0);
670 Error parseGlobalValueSymbolTable();
671 Error parseConstants();
672 Error rememberAndSkipFunctionBodies();
673 Error rememberAndSkipFunctionBody();
674 /// Save the positions of the Metadata blocks and skip parsing the blocks.
675 Error rememberAndSkipMetadata();
676 Error typeCheckLoadStoreInst(Type *ValType, Type *PtrType);
677 Error parseFunctionBody(Function *F);
678 Error globalCleanup();
679 Error resolveGlobalAndIndirectSymbolInits();
680 Error parseUseLists();
681 Error findFunctionInStream(
682 Function *F,
683 DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator);
684
685 SyncScope::ID getDecodedSyncScopeID(unsigned Val);
686};
687
688/// Class to manage reading and parsing function summary index bitcode
689/// files/sections.
690class ModuleSummaryIndexBitcodeReader : public BitcodeReaderBase {
691 /// The module index built during parsing.
692 ModuleSummaryIndex &TheIndex;
693
694 /// Indicates whether we have encountered a global value summary section
695 /// yet during parsing.
696 bool SeenGlobalValSummary = false;
697
698 /// Indicates whether we have already parsed the VST, used for error checking.
699 bool SeenValueSymbolTable = false;
700
701 /// Set to the offset of the VST recorded in the MODULE_CODE_VSTOFFSET record.
702 /// Used to enable on-demand parsing of the VST.
703 uint64_t VSTOffset = 0;
704
705 // Map to save ValueId to ValueInfo association that was recorded in the
706 // ValueSymbolTable. It is used after the VST is parsed to convert
707 // call graph edges read from the function summary from referencing
708 // callees by their ValueId to using the ValueInfo instead, which is how
709 // they are recorded in the summary index being built.
710 // We save a GUID which refers to the same global as the ValueInfo, but
711 // ignoring the linkage, i.e. for values other than local linkage they are
712 // identical.
713 DenseMap<unsigned, std::pair<ValueInfo, GlobalValue::GUID>>
714 ValueIdToValueInfoMap;
715
716 /// Map populated during module path string table parsing, from the
717 /// module ID to a string reference owned by the index's module
718 /// path string table, used to correlate with combined index
719 /// summary records.
720 DenseMap<uint64_t, StringRef> ModuleIdMap;
721
722 /// Original source file name recorded in a bitcode record.
723 std::string SourceFileName;
724
725 /// The string identifier given to this module by the client, normally the
726 /// path to the bitcode file.
727 StringRef ModulePath;
728
729 /// For per-module summary indexes, the unique numerical identifier given to
730 /// this module by the client.
731 unsigned ModuleId;
732
733public:
734 ModuleSummaryIndexBitcodeReader(BitstreamCursor Stream, StringRef Strtab,
735 ModuleSummaryIndex &TheIndex,
736 StringRef ModulePath, unsigned ModuleId);
737
738 Error parseModule();
739
740private:
741 void setValueGUID(uint64_t ValueID, StringRef ValueName,
742 GlobalValue::LinkageTypes Linkage,
743 StringRef SourceFileName);
744 Error parseValueSymbolTable(
745 uint64_t Offset,
746 DenseMap<unsigned, GlobalValue::LinkageTypes> &ValueIdToLinkageMap);
747 std::vector<ValueInfo> makeRefList(ArrayRef<uint64_t> Record);
748 std::vector<FunctionSummary::EdgeTy> makeCallList(ArrayRef<uint64_t> Record,
749 bool IsOldProfileFormat,
750 bool HasProfile,
751 bool HasRelBF);
752 Error parseEntireSummary(unsigned ID);
753 Error parseModuleStringTable();
754
755 std::pair<ValueInfo, GlobalValue::GUID>
756 getValueInfoFromValueId(unsigned ValueId);
757
758 void addThisModule();
759 ModuleSummaryIndex::ModuleInfo *getThisModule();
760};
761
762} // end anonymous namespace
763
764std::error_code llvm::errorToErrorCodeAndEmitErrors(LLVMContext &Ctx,
765 Error Err) {
766 if (Err) {
767 std::error_code EC;
768 handleAllErrors(std::move(Err), [&](ErrorInfoBase &EIB) {
769 EC = EIB.convertToErrorCode();
770 Ctx.emitError(EIB.message());
771 });
772 return EC;
773 }
774 return std::error_code();
775}
776
777BitcodeReader::BitcodeReader(BitstreamCursor Stream, StringRef Strtab,
778 StringRef ProducerIdentification,
779 LLVMContext &Context)
780 : BitcodeReaderBase(std::move(Stream), Strtab), Context(Context),
781 ValueList(Context) {
782 this->ProducerIdentification = ProducerIdentification;
783}
784
785Error BitcodeReader::materializeForwardReferencedFunctions() {
786 if (WillMaterializeAllForwardRefs)
787 return Error::success();
788
789 // Prevent recursion.
790 WillMaterializeAllForwardRefs = true;
791
792 while (!BasicBlockFwdRefQueue.empty()) {
793 Function *F = BasicBlockFwdRefQueue.front();
794 BasicBlockFwdRefQueue.pop_front();
795 assert(F && "Expected valid function")((F && "Expected valid function") ? static_cast<void
> (0) : __assert_fail ("F && \"Expected valid function\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Bitcode/Reader/BitcodeReader.cpp"
, 795, __PRETTY_FUNCTION__))
;
796 if (!BasicBlockFwdRefs.count(F))
797 // Already materialized.
798 continue;
799
800 // Check for a function that isn't materializable to prevent an infinite
801 // loop. When parsing a blockaddress stored in a global variable, there
802 // isn't a trivial way to check if a function will have a body without a
803 // linear search through FunctionsWithBodies, so just check it here.
804 if (!F->isMaterializable())
805 return error("Never resolved function from blockaddress");
806
807 // Try to materialize F.
808 if (Error Err = materialize(F))
809 return Err;
810 }
811 assert(BasicBlockFwdRefs.empty() && "Function missing from queue")((BasicBlockFwdRefs.empty() && "Function missing from queue"
) ? static_cast<void> (0) : __assert_fail ("BasicBlockFwdRefs.empty() && \"Function missing from queue\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Bitcode/Reader/BitcodeReader.cpp"
, 811, __PRETTY_FUNCTION__))
;
812
813 // Reset state.
814 WillMaterializeAllForwardRefs = false;
815 return Error::success();
816}
817
818//===----------------------------------------------------------------------===//
819// Helper functions to implement forward reference resolution, etc.
820//===----------------------------------------------------------------------===//
821
822static bool hasImplicitComdat(size_t Val) {
823 switch (Val) {
824 default:
825 return false;
826 case 1: // Old WeakAnyLinkage
827 case 4: // Old LinkOnceAnyLinkage
828 case 10: // Old WeakODRLinkage
829 case 11: // Old LinkOnceODRLinkage
830 return true;
831 }
832}
833
834static GlobalValue::LinkageTypes getDecodedLinkage(unsigned Val) {
835 switch (Val) {
836 default: // Map unknown/new linkages to external
837 case 0:
838 return GlobalValue::ExternalLinkage;
839 case 2:
840 return GlobalValue::AppendingLinkage;
841 case 3:
842 return GlobalValue::InternalLinkage;
843 case 5:
844 return GlobalValue::ExternalLinkage; // Obsolete DLLImportLinkage
845 case 6:
846 return GlobalValue::ExternalLinkage; // Obsolete DLLExportLinkage
847 case 7:
848 return GlobalValue::ExternalWeakLinkage;
849 case 8:
850 return GlobalValue::CommonLinkage;
851 case 9:
852 return GlobalValue::PrivateLinkage;
853 case 12:
854 return GlobalValue::AvailableExternallyLinkage;
855 case 13:
856 return GlobalValue::PrivateLinkage; // Obsolete LinkerPrivateLinkage
857 case 14:
858 return GlobalValue::PrivateLinkage; // Obsolete LinkerPrivateWeakLinkage
859 case 15:
860 return GlobalValue::ExternalLinkage; // Obsolete LinkOnceODRAutoHideLinkage
861 case 1: // Old value with implicit comdat.
862 case 16:
863 return GlobalValue::WeakAnyLinkage;
864 case 10: // Old value with implicit comdat.
865 case 17:
866 return GlobalValue::WeakODRLinkage;
867 case 4: // Old value with implicit comdat.
868 case 18:
869 return GlobalValue::LinkOnceAnyLinkage;
870 case 11: // Old value with implicit comdat.
871 case 19:
872 return GlobalValue::LinkOnceODRLinkage;
873 }
874}
875
876static FunctionSummary::FFlags getDecodedFFlags(uint64_t RawFlags) {
877 FunctionSummary::FFlags Flags;
878 Flags.ReadNone = RawFlags & 0x1;
879 Flags.ReadOnly = (RawFlags >> 1) & 0x1;
880 Flags.NoRecurse = (RawFlags >> 2) & 0x1;
881 Flags.ReturnDoesNotAlias = (RawFlags >> 3) & 0x1;
882 Flags.NoInline = (RawFlags >> 4) & 0x1;
883 return Flags;
884}
885
886/// Decode the flags for GlobalValue in the summary.
887static GlobalValueSummary::GVFlags getDecodedGVSummaryFlags(uint64_t RawFlags,
888 uint64_t Version) {
889 // Summary were not emitted before LLVM 3.9, we don't need to upgrade Linkage
890 // like getDecodedLinkage() above. Any future change to the linkage enum and
891 // to getDecodedLinkage() will need to be taken into account here as above.
892 auto Linkage = GlobalValue::LinkageTypes(RawFlags & 0xF); // 4 bits
893 RawFlags = RawFlags >> 4;
894 bool NotEligibleToImport = (RawFlags & 0x1) || Version < 3;
895 // The Live flag wasn't introduced until version 3. For dead stripping
896 // to work correctly on earlier versions, we must conservatively treat all
897 // values as live.
898 bool Live = (RawFlags & 0x2) || Version < 3;
899 bool Local = (RawFlags & 0x4);
900 bool AutoHide = (RawFlags & 0x8);
901
902 return GlobalValueSummary::GVFlags(Linkage, NotEligibleToImport, Live, Local, AutoHide);
903}
904
905// Decode the flags for GlobalVariable in the summary
906static GlobalVarSummary::GVarFlags getDecodedGVarFlags(uint64_t RawFlags) {
907 return GlobalVarSummary::GVarFlags((RawFlags & 0x1) ? true : false);
908}
909
910static GlobalValue::VisibilityTypes getDecodedVisibility(unsigned Val) {
911 switch (Val) {
912 default: // Map unknown visibilities to default.
913 case 0: return GlobalValue::DefaultVisibility;
914 case 1: return GlobalValue::HiddenVisibility;
915 case 2: return GlobalValue::ProtectedVisibility;
916 }
917}
918
919static GlobalValue::DLLStorageClassTypes
920getDecodedDLLStorageClass(unsigned Val) {
921 switch (Val) {
922 default: // Map unknown values to default.
923 case 0: return GlobalValue::DefaultStorageClass;
924 case 1: return GlobalValue::DLLImportStorageClass;
925 case 2: return GlobalValue::DLLExportStorageClass;
926 }
927}
928
929static bool getDecodedDSOLocal(unsigned Val) {
930 switch(Val) {
931 default: // Map unknown values to preemptable.
932 case 0: return false;
933 case 1: return true;
934 }
935}
936
937static GlobalVariable::ThreadLocalMode getDecodedThreadLocalMode(unsigned Val) {
938 switch (Val) {
939 case 0: return GlobalVariable::NotThreadLocal;
940 default: // Map unknown non-zero value to general dynamic.
941 case 1: return GlobalVariable::GeneralDynamicTLSModel;
942 case 2: return GlobalVariable::LocalDynamicTLSModel;
943 case 3: return GlobalVariable::InitialExecTLSModel;
944 case 4: return GlobalVariable::LocalExecTLSModel;
945 }
946}
947
948static GlobalVariable::UnnamedAddr getDecodedUnnamedAddrType(unsigned Val) {
949 switch (Val) {
950 default: // Map unknown to UnnamedAddr::None.
951 case 0: return GlobalVariable::UnnamedAddr::None;
952 case 1: return GlobalVariable::UnnamedAddr::Global;
953 case 2: return GlobalVariable::UnnamedAddr::Local;
954 }
955}
956
957static int getDecodedCastOpcode(unsigned Val) {
958 switch (Val) {
959 default: return -1;
960 case bitc::CAST_TRUNC : return Instruction::Trunc;
961 case bitc::CAST_ZEXT : return Instruction::ZExt;
962 case bitc::CAST_SEXT : return Instruction::SExt;
963 case bitc::CAST_FPTOUI : return Instruction::FPToUI;
964 case bitc::CAST_FPTOSI : return Instruction::FPToSI;
965 case bitc::CAST_UITOFP : return Instruction::UIToFP;
966 case bitc::CAST_SITOFP : return Instruction::SIToFP;
967 case bitc::CAST_FPTRUNC : return Instruction::FPTrunc;
968 case bitc::CAST_FPEXT : return Instruction::FPExt;
969 case bitc::CAST_PTRTOINT: return Instruction::PtrToInt;
970 case bitc::CAST_INTTOPTR: return Instruction::IntToPtr;
971 case bitc::CAST_BITCAST : return Instruction::BitCast;
972 case bitc::CAST_ADDRSPACECAST: return Instruction::AddrSpaceCast;
973 }
974}
975
976static int getDecodedUnaryOpcode(unsigned Val, Type *Ty) {
977 bool IsFP = Ty->isFPOrFPVectorTy();
978 // UnOps are only valid for int/fp or vector of int/fp types
979 if (!IsFP && !Ty->isIntOrIntVectorTy())
980 return -1;
981
982 switch (Val) {
983 default:
984 return -1;
985 case bitc::UNOP_NEG:
986 return IsFP ? Instruction::FNeg : -1;
987 }
988}
989
990static int getDecodedBinaryOpcode(unsigned Val, Type *Ty) {
991 bool IsFP = Ty->isFPOrFPVectorTy();
992 // BinOps are only valid for int/fp or vector of int/fp types
993 if (!IsFP && !Ty->isIntOrIntVectorTy())
994 return -1;
995
996 switch (Val) {
997 default:
998 return -1;
999 case bitc::BINOP_ADD:
1000 return IsFP ? Instruction::FAdd : Instruction::Add;
1001 case bitc::BINOP_SUB:
1002 return IsFP ? Instruction::FSub : Instruction::Sub;
1003 case bitc::BINOP_MUL:
1004 return IsFP ? Instruction::FMul : Instruction::Mul;
1005 case bitc::BINOP_UDIV:
1006 return IsFP ? -1 : Instruction::UDiv;
1007 case bitc::BINOP_SDIV:
1008 return IsFP ? Instruction::FDiv : Instruction::SDiv;
1009 case bitc::BINOP_UREM:
1010 return IsFP ? -1 : Instruction::URem;
1011 case bitc::BINOP_SREM:
1012 return IsFP ? Instruction::FRem : Instruction::SRem;
1013 case bitc::BINOP_SHL:
1014 return IsFP ? -1 : Instruction::Shl;
1015 case bitc::BINOP_LSHR:
1016 return IsFP ? -1 : Instruction::LShr;
1017 case bitc::BINOP_ASHR:
1018 return IsFP ? -1 : Instruction::AShr;
1019 case bitc::BINOP_AND:
1020 return IsFP ? -1 : Instruction::And;
1021 case bitc::BINOP_OR:
1022 return IsFP ? -1 : Instruction::Or;
1023 case bitc::BINOP_XOR:
1024 return IsFP ? -1 : Instruction::Xor;
1025 }
1026}
1027
1028static AtomicRMWInst::BinOp getDecodedRMWOperation(unsigned Val) {
1029 switch (Val) {
1030 default: return AtomicRMWInst::BAD_BINOP;
1031 case bitc::RMW_XCHG: return AtomicRMWInst::Xchg;
1032 case bitc::RMW_ADD: return AtomicRMWInst::Add;
1033 case bitc::RMW_SUB: return AtomicRMWInst::Sub;
1034 case bitc::RMW_AND: return AtomicRMWInst::And;
1035 case bitc::RMW_NAND: return AtomicRMWInst::Nand;
1036 case bitc::RMW_OR: return AtomicRMWInst::Or;
1037 case bitc::RMW_XOR: return AtomicRMWInst::Xor;
1038 case bitc::RMW_MAX: return AtomicRMWInst::Max;
1039 case bitc::RMW_MIN: return AtomicRMWInst::Min;
1040 case bitc::RMW_UMAX: return AtomicRMWInst::UMax;
1041 case bitc::RMW_UMIN: return AtomicRMWInst::UMin;
1042 case bitc::RMW_FADD: return AtomicRMWInst::FAdd;
1043 case bitc::RMW_FSUB: return AtomicRMWInst::FSub;
1044 }
1045}
1046
1047static AtomicOrdering getDecodedOrdering(unsigned Val) {
1048 switch (Val) {
1049 case bitc::ORDERING_NOTATOMIC: return AtomicOrdering::NotAtomic;
1050 case bitc::ORDERING_UNORDERED: return AtomicOrdering::Unordered;
1051 case bitc::ORDERING_MONOTONIC: return AtomicOrdering::Monotonic;
1052 case bitc::ORDERING_ACQUIRE: return AtomicOrdering::Acquire;
1053 case bitc::ORDERING_RELEASE: return AtomicOrdering::Release;
1054 case bitc::ORDERING_ACQREL: return AtomicOrdering::AcquireRelease;
1055 default: // Map unknown orderings to sequentially-consistent.
1056 case bitc::ORDERING_SEQCST: return AtomicOrdering::SequentiallyConsistent;
1057 }
1058}
1059
1060static Comdat::SelectionKind getDecodedComdatSelectionKind(unsigned Val) {
1061 switch (Val) {
1062 default: // Map unknown selection kinds to any.
1063 case bitc::COMDAT_SELECTION_KIND_ANY:
1064 return Comdat::Any;
1065 case bitc::COMDAT_SELECTION_KIND_EXACT_MATCH:
1066 return Comdat::ExactMatch;
1067 case bitc::COMDAT_SELECTION_KIND_LARGEST:
1068 return Comdat::Largest;
1069 case bitc::COMDAT_SELECTION_KIND_NO_DUPLICATES:
1070 return Comdat::NoDuplicates;
1071 case bitc::COMDAT_SELECTION_KIND_SAME_SIZE:
1072 return Comdat::SameSize;
1073 }
1074}
1075
1076static FastMathFlags getDecodedFastMathFlags(unsigned Val) {
1077 FastMathFlags FMF;
1078 if (0 != (Val & bitc::UnsafeAlgebra))
1079 FMF.setFast();
1080 if (0 != (Val & bitc::AllowReassoc))
1081 FMF.setAllowReassoc();
1082 if (0 != (Val & bitc::NoNaNs))
1083 FMF.setNoNaNs();
1084 if (0 != (Val & bitc::NoInfs))
1085 FMF.setNoInfs();
1086 if (0 != (Val & bitc::NoSignedZeros))
1087 FMF.setNoSignedZeros();
1088 if (0 != (Val & bitc::AllowReciprocal))
1089 FMF.setAllowReciprocal();
1090 if (0 != (Val & bitc::AllowContract))
1091 FMF.setAllowContract(true);
1092 if (0 != (Val & bitc::ApproxFunc))
1093 FMF.setApproxFunc();
1094 return FMF;
1095}
1096
1097static void upgradeDLLImportExportLinkage(GlobalValue *GV, unsigned Val) {
1098 switch (Val) {
1099 case 5: GV->setDLLStorageClass(GlobalValue::DLLImportStorageClass); break;
1100 case 6: GV->setDLLStorageClass(GlobalValue::DLLExportStorageClass); break;
1101 }
1102}
1103
1104Type *BitcodeReader::getTypeByID(unsigned ID) {
1105 // The type table size is always specified correctly.
1106 if (ID >= TypeList.size())
1107 return nullptr;
1108
1109 if (Type *Ty = TypeList[ID])
1110 return Ty;
1111
1112 // If we have a forward reference, the only possible case is when it is to a
1113 // named struct. Just create a placeholder for now.
1114 return TypeList[ID] = createIdentifiedStructType(Context);
1115}
1116
1117StructType *BitcodeReader::createIdentifiedStructType(LLVMContext &Context,
1118 StringRef Name) {
1119 auto *Ret = StructType::create(Context, Name);
1120 IdentifiedStructTypes.push_back(Ret);
1121 return Ret;
1122}
1123
1124StructType *BitcodeReader::createIdentifiedStructType(LLVMContext &Context) {
1125 auto *Ret = StructType::create(Context);
1126 IdentifiedStructTypes.push_back(Ret);
1127 return Ret;
1128}
1129
1130//===----------------------------------------------------------------------===//
1131// Functions for parsing blocks from the bitcode file
1132//===----------------------------------------------------------------------===//
1133
1134static uint64_t getRawAttributeMask(Attribute::AttrKind Val) {
1135 switch (Val) {
1136 case Attribute::EndAttrKinds:
1137 llvm_unreachable("Synthetic enumerators which should never get here")::llvm::llvm_unreachable_internal("Synthetic enumerators which should never get here"
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Bitcode/Reader/BitcodeReader.cpp"
, 1137)
;
1138
1139 case Attribute::None: return 0;
1140 case Attribute::ZExt: return 1 << 0;
1141 case Attribute::SExt: return 1 << 1;
1142 case Attribute::NoReturn: return 1 << 2;
1143 case Attribute::InReg: return 1 << 3;
1144 case Attribute::StructRet: return 1 << 4;
1145 case Attribute::NoUnwind: return 1 << 5;
1146 case Attribute::NoAlias: return 1 << 6;
1147 case Attribute::ByVal: return 1 << 7;
1148 case Attribute::Nest: return 1 << 8;
1149 case Attribute::ReadNone: return 1 << 9;
1150 case Attribute::ReadOnly: return 1 << 10;
1151 case Attribute::NoInline: return 1 << 11;
1152 case Attribute::AlwaysInline: return 1 << 12;
1153 case Attribute::OptimizeForSize: return 1 << 13;
1154 case Attribute::StackProtect: return 1 << 14;
1155 case Attribute::StackProtectReq: return 1 << 15;
1156 case Attribute::Alignment: return 31 << 16;
1157 case Attribute::NoCapture: return 1 << 21;
1158 case Attribute::NoRedZone: return 1 << 22;
1159 case Attribute::NoImplicitFloat: return 1 << 23;
1160 case Attribute::Naked: return 1 << 24;
1161 case Attribute::InlineHint: return 1 << 25;
1162 case Attribute::StackAlignment: return 7 << 26;
1163 case Attribute::ReturnsTwice: return 1 << 29;
1164 case Attribute::UWTable: return 1 << 30;
1165 case Attribute::NonLazyBind: return 1U << 31;
1166 case Attribute::SanitizeAddress: return 1ULL << 32;
1167 case Attribute::MinSize: return 1ULL << 33;
1168 case Attribute::NoDuplicate: return 1ULL << 34;
1169 case Attribute::StackProtectStrong: return 1ULL << 35;
1170 case Attribute::SanitizeThread: return 1ULL << 36;
1171 case Attribute::SanitizeMemory: return 1ULL << 37;
1172 case Attribute::NoBuiltin: return 1ULL << 38;
1173 case Attribute::Returned: return 1ULL << 39;
1174 case Attribute::Cold: return 1ULL << 40;
1175 case Attribute::Builtin: return 1ULL << 41;
1176 case Attribute::OptimizeNone: return 1ULL << 42;
1177 case Attribute::InAlloca: return 1ULL << 43;
1178 case Attribute::NonNull: return 1ULL << 44;
1179 case Attribute::JumpTable: return 1ULL << 45;
1180 case Attribute::Convergent: return 1ULL << 46;
1181 case Attribute::SafeStack: return 1ULL << 47;
1182 case Attribute::NoRecurse: return 1ULL << 48;
1183 case Attribute::InaccessibleMemOnly: return 1ULL << 49;
1184 case Attribute::InaccessibleMemOrArgMemOnly: return 1ULL << 50;
1185 case Attribute::SwiftSelf: return 1ULL << 51;
1186 case Attribute::SwiftError: return 1ULL << 52;
1187 case Attribute::WriteOnly: return 1ULL << 53;
1188 case Attribute::Speculatable: return 1ULL << 54;
1189 case Attribute::StrictFP: return 1ULL << 55;
1190 case Attribute::SanitizeHWAddress: return 1ULL << 56;
1191 case Attribute::NoCfCheck: return 1ULL << 57;
1192 case Attribute::OptForFuzzing: return 1ULL << 58;
1193 case Attribute::ShadowCallStack: return 1ULL << 59;
1194 case Attribute::SpeculativeLoadHardening:
1195 return 1ULL << 60;
1196 case Attribute::ImmArg:
1197 return 1ULL << 61;
1198 case Attribute::Dereferenceable:
1199 llvm_unreachable("dereferenceable attribute not supported in raw format")::llvm::llvm_unreachable_internal("dereferenceable attribute not supported in raw format"
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Bitcode/Reader/BitcodeReader.cpp"
, 1199)
;
1200 break;
1201 case Attribute::DereferenceableOrNull:
1202 llvm_unreachable("dereferenceable_or_null attribute not supported in raw "::llvm::llvm_unreachable_internal("dereferenceable_or_null attribute not supported in raw "
"format", "/build/llvm-toolchain-snapshot-9~svn362543/lib/Bitcode/Reader/BitcodeReader.cpp"
, 1203)
1203 "format")::llvm::llvm_unreachable_internal("dereferenceable_or_null attribute not supported in raw "
"format", "/build/llvm-toolchain-snapshot-9~svn362543/lib/Bitcode/Reader/BitcodeReader.cpp"
, 1203)
;
1204 break;
1205 case Attribute::ArgMemOnly:
1206 llvm_unreachable("argmemonly attribute not supported in raw format")::llvm::llvm_unreachable_internal("argmemonly attribute not supported in raw format"
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Bitcode/Reader/BitcodeReader.cpp"
, 1206)
;
1207 break;
1208 case Attribute::AllocSize:
1209 llvm_unreachable("allocsize not supported in raw format")::llvm::llvm_unreachable_internal("allocsize not supported in raw format"
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Bitcode/Reader/BitcodeReader.cpp"
, 1209)
;
1210 break;
1211 }
1212 llvm_unreachable("Unsupported attribute type")::llvm::llvm_unreachable_internal("Unsupported attribute type"
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Bitcode/Reader/BitcodeReader.cpp"
, 1212)
;
1213}
1214
1215static void addRawAttributeValue(AttrBuilder &B, uint64_t Val) {
1216 if (!Val) return;
1217
1218 for (Attribute::AttrKind I = Attribute::None; I != Attribute::EndAttrKinds;
1219 I = Attribute::AttrKind(I + 1)) {
1220 if (I == Attribute::Dereferenceable ||
1221 I == Attribute::DereferenceableOrNull ||
1222 I == Attribute::ArgMemOnly ||
1223 I == Attribute::AllocSize)
1224 continue;
1225 if (uint64_t A = (Val & getRawAttributeMask(I))) {
1226 if (I == Attribute::Alignment)
1227 B.addAlignmentAttr(1ULL << ((A >> 16) - 1));
1228 else if (I == Attribute::StackAlignment)
1229 B.addStackAlignmentAttr(1ULL << ((A >> 26)-1));
1230 else
1231 B.addAttribute(I);
1232 }
1233 }
1234}
1235
1236/// This fills an AttrBuilder object with the LLVM attributes that have
1237/// been decoded from the given integer. This function must stay in sync with
1238/// 'encodeLLVMAttributesForBitcode'.
1239static void decodeLLVMAttributesForBitcode(AttrBuilder &B,
1240 uint64_t EncodedAttrs) {
1241 // FIXME: Remove in 4.0.
1242
1243 // The alignment is stored as a 16-bit raw value from bits 31--16. We shift
1244 // the bits above 31 down by 11 bits.
1245 unsigned Alignment = (EncodedAttrs & (0xffffULL << 16)) >> 16;
1246 assert((!Alignment || isPowerOf2_32(Alignment)) &&(((!Alignment || isPowerOf2_32(Alignment)) && "Alignment must be a power of two."
) ? static_cast<void> (0) : __assert_fail ("(!Alignment || isPowerOf2_32(Alignment)) && \"Alignment must be a power of two.\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Bitcode/Reader/BitcodeReader.cpp"
, 1247, __PRETTY_FUNCTION__))
1247 "Alignment must be a power of two.")(((!Alignment || isPowerOf2_32(Alignment)) && "Alignment must be a power of two."
) ? static_cast<void> (0) : __assert_fail ("(!Alignment || isPowerOf2_32(Alignment)) && \"Alignment must be a power of two.\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Bitcode/Reader/BitcodeReader.cpp"
, 1247, __PRETTY_FUNCTION__))
;
1248
1249 if (Alignment)
1250 B.addAlignmentAttr(Alignment);
1251 addRawAttributeValue(B, ((EncodedAttrs & (0xfffffULL << 32)) >> 11) |
1252 (EncodedAttrs & 0xffff));
1253}
1254
1255Error BitcodeReader::parseAttributeBlock() {
1256 if (Stream.EnterSubBlock(bitc::PARAMATTR_BLOCK_ID))
1257 return error("Invalid record");
1258
1259 if (!MAttributes.empty())
1260 return error("Invalid multiple blocks");
1261
1262 SmallVector<uint64_t, 64> Record;
1263
1264 SmallVector<AttributeList, 8> Attrs;
1265
1266 // Read all the records.
1267 while (true) {
1268 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1269
1270 switch (Entry.Kind) {
1271 case BitstreamEntry::SubBlock: // Handled for us already.
1272 case BitstreamEntry::Error:
1273 return error("Malformed block");
1274 case BitstreamEntry::EndBlock:
1275 return Error::success();
1276 case BitstreamEntry::Record:
1277 // The interesting case.
1278 break;
1279 }
1280
1281 // Read a record.
1282 Record.clear();
1283 switch (Stream.readRecord(Entry.ID, Record)) {
1284 default: // Default behavior: ignore.
1285 break;
1286 case bitc::PARAMATTR_CODE_ENTRY_OLD: // ENTRY: [paramidx0, attr0, ...]
1287 // FIXME: Remove in 4.0.
1288 if (Record.size() & 1)
1289 return error("Invalid record");
1290
1291 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
1292 AttrBuilder B;
1293 decodeLLVMAttributesForBitcode(B, Record[i+1]);
1294 Attrs.push_back(AttributeList::get(Context, Record[i], B));
1295 }
1296
1297 MAttributes.push_back(AttributeList::get(Context, Attrs));
1298 Attrs.clear();
1299 break;
1300 case bitc::PARAMATTR_CODE_ENTRY: // ENTRY: [attrgrp0, attrgrp1, ...]
1301 for (unsigned i = 0, e = Record.size(); i != e; ++i)
1302 Attrs.push_back(MAttributeGroups[Record[i]]);
1303
1304 MAttributes.push_back(AttributeList::get(Context, Attrs));
1305 Attrs.clear();
1306 break;
1307 }
1308 }
1309}
1310
1311// Returns Attribute::None on unrecognized codes.
1312static Attribute::AttrKind getAttrFromCode(uint64_t Code) {
1313 switch (Code) {
1314 default:
1315 return Attribute::None;
1316 case bitc::ATTR_KIND_ALIGNMENT:
1317 return Attribute::Alignment;
1318 case bitc::ATTR_KIND_ALWAYS_INLINE:
1319 return Attribute::AlwaysInline;
1320 case bitc::ATTR_KIND_ARGMEMONLY:
1321 return Attribute::ArgMemOnly;
1322 case bitc::ATTR_KIND_BUILTIN:
1323 return Attribute::Builtin;
1324 case bitc::ATTR_KIND_BY_VAL:
1325 return Attribute::ByVal;
1326 case bitc::ATTR_KIND_IN_ALLOCA:
1327 return Attribute::InAlloca;
1328 case bitc::ATTR_KIND_COLD:
1329 return Attribute::Cold;
1330 case bitc::ATTR_KIND_CONVERGENT:
1331 return Attribute::Convergent;
1332 case bitc::ATTR_KIND_INACCESSIBLEMEM_ONLY:
1333 return Attribute::InaccessibleMemOnly;
1334 case bitc::ATTR_KIND_INACCESSIBLEMEM_OR_ARGMEMONLY:
1335 return Attribute::InaccessibleMemOrArgMemOnly;
1336 case bitc::ATTR_KIND_INLINE_HINT:
1337 return Attribute::InlineHint;
1338 case bitc::ATTR_KIND_IN_REG:
1339 return Attribute::InReg;
1340 case bitc::ATTR_KIND_JUMP_TABLE:
1341 return Attribute::JumpTable;
1342 case bitc::ATTR_KIND_MIN_SIZE:
1343 return Attribute::MinSize;
1344 case bitc::ATTR_KIND_NAKED:
1345 return Attribute::Naked;
1346 case bitc::ATTR_KIND_NEST:
1347 return Attribute::Nest;
1348 case bitc::ATTR_KIND_NO_ALIAS:
1349 return Attribute::NoAlias;
1350 case bitc::ATTR_KIND_NO_BUILTIN:
1351 return Attribute::NoBuiltin;
1352 case bitc::ATTR_KIND_NO_CAPTURE:
1353 return Attribute::NoCapture;
1354 case bitc::ATTR_KIND_NO_DUPLICATE:
1355 return Attribute::NoDuplicate;
1356 case bitc::ATTR_KIND_NO_IMPLICIT_FLOAT:
1357 return Attribute::NoImplicitFloat;
1358 case bitc::ATTR_KIND_NO_INLINE:
1359 return Attribute::NoInline;
1360 case bitc::ATTR_KIND_NO_RECURSE:
1361 return Attribute::NoRecurse;
1362 case bitc::ATTR_KIND_NON_LAZY_BIND:
1363 return Attribute::NonLazyBind;
1364 case bitc::ATTR_KIND_NON_NULL:
1365 return Attribute::NonNull;
1366 case bitc::ATTR_KIND_DEREFERENCEABLE:
1367 return Attribute::Dereferenceable;
1368 case bitc::ATTR_KIND_DEREFERENCEABLE_OR_NULL:
1369 return Attribute::DereferenceableOrNull;
1370 case bitc::ATTR_KIND_ALLOC_SIZE:
1371 return Attribute::AllocSize;
1372 case bitc::ATTR_KIND_NO_RED_ZONE:
1373 return Attribute::NoRedZone;
1374 case bitc::ATTR_KIND_NO_RETURN:
1375 return Attribute::NoReturn;
1376 case bitc::ATTR_KIND_NOCF_CHECK:
1377 return Attribute::NoCfCheck;
1378 case bitc::ATTR_KIND_NO_UNWIND:
1379 return Attribute::NoUnwind;
1380 case bitc::ATTR_KIND_OPT_FOR_FUZZING:
1381 return Attribute::OptForFuzzing;
1382 case bitc::ATTR_KIND_OPTIMIZE_FOR_SIZE:
1383 return Attribute::OptimizeForSize;
1384 case bitc::ATTR_KIND_OPTIMIZE_NONE:
1385 return Attribute::OptimizeNone;
1386 case bitc::ATTR_KIND_READ_NONE:
1387 return Attribute::ReadNone;
1388 case bitc::ATTR_KIND_READ_ONLY:
1389 return Attribute::ReadOnly;
1390 case bitc::ATTR_KIND_RETURNED:
1391 return Attribute::Returned;
1392 case bitc::ATTR_KIND_RETURNS_TWICE:
1393 return Attribute::ReturnsTwice;
1394 case bitc::ATTR_KIND_S_EXT:
1395 return Attribute::SExt;
1396 case bitc::ATTR_KIND_SPECULATABLE:
1397 return Attribute::Speculatable;
1398 case bitc::ATTR_KIND_STACK_ALIGNMENT:
1399 return Attribute::StackAlignment;
1400 case bitc::ATTR_KIND_STACK_PROTECT:
1401 return Attribute::StackProtect;
1402 case bitc::ATTR_KIND_STACK_PROTECT_REQ:
1403 return Attribute::StackProtectReq;
1404 case bitc::ATTR_KIND_STACK_PROTECT_STRONG:
1405 return Attribute::StackProtectStrong;
1406 case bitc::ATTR_KIND_SAFESTACK:
1407 return Attribute::SafeStack;
1408 case bitc::ATTR_KIND_SHADOWCALLSTACK:
1409 return Attribute::ShadowCallStack;
1410 case bitc::ATTR_KIND_STRICT_FP:
1411 return Attribute::StrictFP;
1412 case bitc::ATTR_KIND_STRUCT_RET:
1413 return Attribute::StructRet;
1414 case bitc::ATTR_KIND_SANITIZE_ADDRESS:
1415 return Attribute::SanitizeAddress;
1416 case bitc::ATTR_KIND_SANITIZE_HWADDRESS:
1417 return Attribute::SanitizeHWAddress;
1418 case bitc::ATTR_KIND_SANITIZE_THREAD:
1419 return Attribute::SanitizeThread;
1420 case bitc::ATTR_KIND_SANITIZE_MEMORY:
1421 return Attribute::SanitizeMemory;
1422 case bitc::ATTR_KIND_SPECULATIVE_LOAD_HARDENING:
1423 return Attribute::SpeculativeLoadHardening;
1424 case bitc::ATTR_KIND_SWIFT_ERROR:
1425 return Attribute::SwiftError;
1426 case bitc::ATTR_KIND_SWIFT_SELF:
1427 return Attribute::SwiftSelf;
1428 case bitc::ATTR_KIND_UW_TABLE:
1429 return Attribute::UWTable;
1430 case bitc::ATTR_KIND_WRITEONLY:
1431 return Attribute::WriteOnly;
1432 case bitc::ATTR_KIND_Z_EXT:
1433 return Attribute::ZExt;
1434 case bitc::ATTR_KIND_IMMARG:
1435 return Attribute::ImmArg;
1436 }
1437}
1438
1439Error BitcodeReader::parseAlignmentValue(uint64_t Exponent,
1440 unsigned &Alignment) {
1441 // Note: Alignment in bitcode files is incremented by 1, so that zero
1442 // can be used for default alignment.
1443 if (Exponent > Value::MaxAlignmentExponent + 1)
1444 return error("Invalid alignment value");
1445 Alignment = (1 << static_cast<unsigned>(Exponent)) >> 1;
1446 return Error::success();
1447}
1448
1449Error BitcodeReader::parseAttrKind(uint64_t Code, Attribute::AttrKind *Kind) {
1450 *Kind = getAttrFromCode(Code);
1451 if (*Kind == Attribute::None)
1452 return error("Unknown attribute kind (" + Twine(Code) + ")");
1453 return Error::success();
1454}
1455
1456Error BitcodeReader::parseAttributeGroupBlock() {
1457 if (Stream.EnterSubBlock(bitc::PARAMATTR_GROUP_BLOCK_ID))
1458 return error("Invalid record");
1459
1460 if (!MAttributeGroups.empty())
1461 return error("Invalid multiple blocks");
1462
1463 SmallVector<uint64_t, 64> Record;
1464
1465 // Read all the records.
1466 while (true) {
1467 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1468
1469 switch (Entry.Kind) {
1470 case BitstreamEntry::SubBlock: // Handled for us already.
1471 case BitstreamEntry::Error:
1472 return error("Malformed block");
1473 case BitstreamEntry::EndBlock:
1474 return Error::success();
1475 case BitstreamEntry::Record:
1476 // The interesting case.
1477 break;
1478 }
1479
1480 // Read a record.
1481 Record.clear();
1482 switch (Stream.readRecord(Entry.ID, Record)) {
1483 default: // Default behavior: ignore.
1484 break;
1485 case bitc::PARAMATTR_GRP_CODE_ENTRY: { // ENTRY: [grpid, idx, a0, a1, ...]
1486 if (Record.size() < 3)
1487 return error("Invalid record");
1488
1489 uint64_t GrpID = Record[0];
1490 uint64_t Idx = Record[1]; // Index of the object this attribute refers to.
1491
1492 AttrBuilder B;
1493 for (unsigned i = 2, e = Record.size(); i != e; ++i) {
1494 if (Record[i] == 0) { // Enum attribute
1495 Attribute::AttrKind Kind;
1496 if (Error Err = parseAttrKind(Record[++i], &Kind))
1497 return Err;
1498
1499 // Upgrade old-style byval attribute to one with a type, even if it's
1500 // nullptr. We will have to insert the real type when we associate
1501 // this AttributeList with a function.
1502 if (Kind == Attribute::ByVal)
1503 B.addByValAttr(nullptr);
1504
1505 B.addAttribute(Kind);
1506 } else if (Record[i] == 1) { // Integer attribute
1507 Attribute::AttrKind Kind;
1508 if (Error Err = parseAttrKind(Record[++i], &Kind))
1509 return Err;
1510 if (Kind == Attribute::Alignment)
1511 B.addAlignmentAttr(Record[++i]);
1512 else if (Kind == Attribute::StackAlignment)
1513 B.addStackAlignmentAttr(Record[++i]);
1514 else if (Kind == Attribute::Dereferenceable)
1515 B.addDereferenceableAttr(Record[++i]);
1516 else if (Kind == Attribute::DereferenceableOrNull)
1517 B.addDereferenceableOrNullAttr(Record[++i]);
1518 else if (Kind == Attribute::AllocSize)
1519 B.addAllocSizeAttrFromRawRepr(Record[++i]);
1520 } else if (Record[i] == 3 || Record[i] == 4) { // String attribute
1521 bool HasValue = (Record[i++] == 4);
1522 SmallString<64> KindStr;
1523 SmallString<64> ValStr;
1524
1525 while (Record[i] != 0 && i != e)
1526 KindStr += Record[i++];
1527 assert(Record[i] == 0 && "Kind string not null terminated")((Record[i] == 0 && "Kind string not null terminated"
) ? static_cast<void> (0) : __assert_fail ("Record[i] == 0 && \"Kind string not null terminated\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Bitcode/Reader/BitcodeReader.cpp"
, 1527, __PRETTY_FUNCTION__))
;
1528
1529 if (HasValue) {
1530 // Has a value associated with it.
1531 ++i; // Skip the '0' that terminates the "kind" string.
1532 while (Record[i] != 0 && i != e)
1533 ValStr += Record[i++];
1534 assert(Record[i] == 0 && "Value string not null terminated")((Record[i] == 0 && "Value string not null terminated"
) ? static_cast<void> (0) : __assert_fail ("Record[i] == 0 && \"Value string not null terminated\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Bitcode/Reader/BitcodeReader.cpp"
, 1534, __PRETTY_FUNCTION__))
;
1535 }
1536
1537 B.addAttribute(KindStr.str(), ValStr.str());
1538 } else {
1539 assert((Record[i] == 5 || Record[i] == 6) &&(((Record[i] == 5 || Record[i] == 6) && "Invalid attribute group entry"
) ? static_cast<void> (0) : __assert_fail ("(Record[i] == 5 || Record[i] == 6) && \"Invalid attribute group entry\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Bitcode/Reader/BitcodeReader.cpp"
, 1540, __PRETTY_FUNCTION__))
1540 "Invalid attribute group entry")(((Record[i] == 5 || Record[i] == 6) && "Invalid attribute group entry"
) ? static_cast<void> (0) : __assert_fail ("(Record[i] == 5 || Record[i] == 6) && \"Invalid attribute group entry\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Bitcode/Reader/BitcodeReader.cpp"
, 1540, __PRETTY_FUNCTION__))
;
1541 bool HasType = Record[i] == 6;
1542 Attribute::AttrKind Kind;
1543 if (Error Err = parseAttrKind(Record[++i], &Kind))
1544 return Err;
1545 if (Kind == Attribute::ByVal)
1546 B.addByValAttr(HasType ? getTypeByID(Record[++i]) : nullptr);
1547 }
1548 }
1549
1550 MAttributeGroups[GrpID] = AttributeList::get(Context, Idx, B);
1551 break;
1552 }
1553 }
1554 }
1555}
1556
1557Error BitcodeReader::parseTypeTable() {
1558 if (Stream.EnterSubBlock(bitc::TYPE_BLOCK_ID_NEW))
1559 return error("Invalid record");
1560
1561 return parseTypeTableBody();
1562}
1563
1564Error BitcodeReader::parseTypeTableBody() {
1565 if (!TypeList.empty())
1566 return error("Invalid multiple blocks");
1567
1568 SmallVector<uint64_t, 64> Record;
1569 unsigned NumRecords = 0;
1570
1571 SmallString<64> TypeName;
1572
1573 // Read all the records for this type table.
1574 while (true) {
1575 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1576
1577 switch (Entry.Kind) {
1578 case BitstreamEntry::SubBlock: // Handled for us already.
1579 case BitstreamEntry::Error:
1580 return error("Malformed block");
1581 case BitstreamEntry::EndBlock:
1582 if (NumRecords != TypeList.size())
1583 return error("Malformed block");
1584 return Error::success();
1585 case BitstreamEntry::Record:
1586 // The interesting case.
1587 break;
1588 }
1589
1590 // Read a record.
1591 Record.clear();
1592 Type *ResultTy = nullptr;
1593 switch (Stream.readRecord(Entry.ID, Record)) {
1594 default:
1595 return error("Invalid value");
1596 case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries]
1597 // TYPE_CODE_NUMENTRY contains a count of the number of types in the
1598 // type list. This allows us to reserve space.
1599 if (Record.size() < 1)
1600 return error("Invalid record");
1601 TypeList.resize(Record[0]);
1602 continue;
1603 case bitc::TYPE_CODE_VOID: // VOID
1604 ResultTy = Type::getVoidTy(Context);
1605 break;
1606 case bitc::TYPE_CODE_HALF: // HALF
1607 ResultTy = Type::getHalfTy(Context);
1608 break;
1609 case bitc::TYPE_CODE_FLOAT: // FLOAT
1610 ResultTy = Type::getFloatTy(Context);
1611 break;
1612 case bitc::TYPE_CODE_DOUBLE: // DOUBLE
1613 ResultTy = Type::getDoubleTy(Context);
1614 break;
1615 case bitc::TYPE_CODE_X86_FP80: // X86_FP80
1616 ResultTy = Type::getX86_FP80Ty(Context);
1617 break;
1618 case bitc::TYPE_CODE_FP128: // FP128
1619 ResultTy = Type::getFP128Ty(Context);
1620 break;
1621 case bitc::TYPE_CODE_PPC_FP128: // PPC_FP128
1622 ResultTy = Type::getPPC_FP128Ty(Context);
1623 break;
1624 case bitc::TYPE_CODE_LABEL: // LABEL
1625 ResultTy = Type::getLabelTy(Context);
1626 break;
1627 case bitc::TYPE_CODE_METADATA: // METADATA
1628 ResultTy = Type::getMetadataTy(Context);
1629 break;
1630 case bitc::TYPE_CODE_X86_MMX: // X86_MMX
1631 ResultTy = Type::getX86_MMXTy(Context);
1632 break;
1633 case bitc::TYPE_CODE_TOKEN: // TOKEN
1634 ResultTy = Type::getTokenTy(Context);
1635 break;
1636 case bitc::TYPE_CODE_INTEGER: { // INTEGER: [width]
1637 if (Record.size() < 1)
1638 return error("Invalid record");
1639
1640 uint64_t NumBits = Record[0];
1641 if (NumBits < IntegerType::MIN_INT_BITS ||
1642 NumBits > IntegerType::MAX_INT_BITS)
1643 return error("Bitwidth for integer type out of range");
1644 ResultTy = IntegerType::get(Context, NumBits);
1645 break;
1646 }
1647 case bitc::TYPE_CODE_POINTER: { // POINTER: [pointee type] or
1648 // [pointee type, address space]
1649 if (Record.size() < 1)
1650 return error("Invalid record");
1651 unsigned AddressSpace = 0;
1652 if (Record.size() == 2)
1653 AddressSpace = Record[1];
1654 ResultTy = getTypeByID(Record[0]);
1655 if (!ResultTy ||
1656 !PointerType::isValidElementType(ResultTy))
1657 return error("Invalid type");
1658 ResultTy = PointerType::get(ResultTy, AddressSpace);
1659 break;
1660 }
1661 case bitc::TYPE_CODE_FUNCTION_OLD: {
1662 // FIXME: attrid is dead, remove it in LLVM 4.0
1663 // FUNCTION: [vararg, attrid, retty, paramty x N]
1664 if (Record.size() < 3)
1665 return error("Invalid record");
1666 SmallVector<Type*, 8> ArgTys;
1667 for (unsigned i = 3, e = Record.size(); i != e; ++i) {
1668 if (Type *T = getTypeByID(Record[i]))
1669 ArgTys.push_back(T);
1670 else
1671 break;
1672 }
1673
1674 ResultTy = getTypeByID(Record[2]);
1675 if (!ResultTy || ArgTys.size() < Record.size()-3)
1676 return error("Invalid type");
1677
1678 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
1679 break;
1680 }
1681 case bitc::TYPE_CODE_FUNCTION: {
1682 // FUNCTION: [vararg, retty, paramty x N]
1683 if (Record.size() < 2)
1684 return error("Invalid record");
1685 SmallVector<Type*, 8> ArgTys;
1686 for (unsigned i = 2, e = Record.size(); i != e; ++i) {
1687 if (Type *T = getTypeByID(Record[i])) {
1688 if (!FunctionType::isValidArgumentType(T))
1689 return error("Invalid function argument type");
1690 ArgTys.push_back(T);
1691 }
1692 else
1693 break;
1694 }
1695
1696 ResultTy = getTypeByID(Record[1]);
1697 if (!ResultTy || ArgTys.size() < Record.size()-2)
1698 return error("Invalid type");
1699
1700 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
1701 break;
1702 }
1703 case bitc::TYPE_CODE_STRUCT_ANON: { // STRUCT: [ispacked, eltty x N]
1704 if (Record.size() < 1)
1705 return error("Invalid record");
1706 SmallVector<Type*, 8> EltTys;
1707 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
1708 if (Type *T = getTypeByID(Record[i]))
1709 EltTys.push_back(T);
1710 else
1711 break;
1712 }
1713 if (EltTys.size() != Record.size()-1)
1714 return error("Invalid type");
1715 ResultTy = StructType::get(Context, EltTys, Record[0]);
1716 break;
1717 }
1718 case bitc::TYPE_CODE_STRUCT_NAME: // STRUCT_NAME: [strchr x N]
1719 if (convertToString(Record, 0, TypeName))
1720 return error("Invalid record");
1721 continue;
1722
1723 case bitc::TYPE_CODE_STRUCT_NAMED: { // STRUCT: [ispacked, eltty x N]
1724 if (Record.size() < 1)
1725 return error("Invalid record");
1726
1727 if (NumRecords >= TypeList.size())
1728 return error("Invalid TYPE table");
1729
1730 // Check to see if this was forward referenced, if so fill in the temp.
1731 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
1732 if (Res) {
1733 Res->setName(TypeName);
1734 TypeList[NumRecords] = nullptr;
1735 } else // Otherwise, create a new struct.
1736 Res = createIdentifiedStructType(Context, TypeName);
1737 TypeName.clear();
1738
1739 SmallVector<Type*, 8> EltTys;
1740 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
1741 if (Type *T = getTypeByID(Record[i]))
1742 EltTys.push_back(T);
1743 else
1744 break;
1745 }
1746 if (EltTys.size() != Record.size()-1)
1747 return error("Invalid record");
1748 Res->setBody(EltTys, Record[0]);
1749 ResultTy = Res;
1750 break;
1751 }
1752 case bitc::TYPE_CODE_OPAQUE: { // OPAQUE: []
1753 if (Record.size() != 1)
1754 return error("Invalid record");
1755
1756 if (NumRecords >= TypeList.size())
1757 return error("Invalid TYPE table");
1758
1759 // Check to see if this was forward referenced, if so fill in the temp.
1760 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
1761 if (Res) {
1762 Res->setName(TypeName);
1763 TypeList[NumRecords] = nullptr;
1764 } else // Otherwise, create a new struct with no body.
1765 Res = createIdentifiedStructType(Context, TypeName);
1766 TypeName.clear();
1767 ResultTy = Res;
1768 break;
1769 }
1770 case bitc::TYPE_CODE_ARRAY: // ARRAY: [numelts, eltty]
1771 if (Record.size() < 2)
1772 return error("Invalid record");
1773 ResultTy = getTypeByID(Record[1]);
1774 if (!ResultTy || !ArrayType::isValidElementType(ResultTy))
1775 return error("Invalid type");
1776 ResultTy = ArrayType::get(ResultTy, Record[0]);
1777 break;
1778 case bitc::TYPE_CODE_VECTOR: // VECTOR: [numelts, eltty] or
1779 // [numelts, eltty, scalable]
1780 if (Record.size() < 2)
1781 return error("Invalid record");
1782 if (Record[0] == 0)
1783 return error("Invalid vector length");
1784 ResultTy = getTypeByID(Record[1]);
1785 if (!ResultTy || !StructType::isValidElementType(ResultTy))
1786 return error("Invalid type");
1787 bool Scalable = Record.size() > 2 ? Record[2] : false;
1788 ResultTy = VectorType::get(ResultTy, Record[0], Scalable);
1789 break;
1790 }
1791
1792 if (NumRecords >= TypeList.size())
1793 return error("Invalid TYPE table");
1794 if (TypeList[NumRecords])
1795 return error(
1796 "Invalid TYPE table: Only named structs can be forward referenced");
1797 assert(ResultTy && "Didn't read a type?")((ResultTy && "Didn't read a type?") ? static_cast<
void> (0) : __assert_fail ("ResultTy && \"Didn't read a type?\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Bitcode/Reader/BitcodeReader.cpp"
, 1797, __PRETTY_FUNCTION__))
;
1798 TypeList[NumRecords++] = ResultTy;
1799 }
1800}
1801
1802Error BitcodeReader::parseOperandBundleTags() {
1803 if (Stream.EnterSubBlock(bitc::OPERAND_BUNDLE_TAGS_BLOCK_ID))
1804 return error("Invalid record");
1805
1806 if (!BundleTags.empty())
1807 return error("Invalid multiple blocks");
1808
1809 SmallVector<uint64_t, 64> Record;
1810
1811 while (true) {
1812 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1813
1814 switch (Entry.Kind) {
1815 case BitstreamEntry::SubBlock: // Handled for us already.
1816 case BitstreamEntry::Error:
1817 return error("Malformed block");
1818 case BitstreamEntry::EndBlock:
1819 return Error::success();
1820 case BitstreamEntry::Record:
1821 // The interesting case.
1822 break;
1823 }
1824
1825 // Tags are implicitly mapped to integers by their order.
1826
1827 if (Stream.readRecord(Entry.ID, Record) != bitc::OPERAND_BUNDLE_TAG)
1828 return error("Invalid record");
1829
1830 // OPERAND_BUNDLE_TAG: [strchr x N]
1831 BundleTags.emplace_back();
1832 if (convertToString(Record, 0, BundleTags.back()))
1833 return error("Invalid record");
1834 Record.clear();
1835 }
1836}
1837
1838Error BitcodeReader::parseSyncScopeNames() {
1839 if (Stream.EnterSubBlock(bitc::SYNC_SCOPE_NAMES_BLOCK_ID))
1840 return error("Invalid record");
1841
1842 if (!SSIDs.empty())
1843 return error("Invalid multiple synchronization scope names blocks");
1844
1845 SmallVector<uint64_t, 64> Record;
1846 while (true) {
1847 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1848 switch (Entry.Kind) {
1849 case BitstreamEntry::SubBlock: // Handled for us already.
1850 case BitstreamEntry::Error:
1851 return error("Malformed block");
1852 case BitstreamEntry::EndBlock:
1853 if (SSIDs.empty())
1854 return error("Invalid empty synchronization scope names block");
1855 return Error::success();
1856 case BitstreamEntry::Record:
1857 // The interesting case.
1858 break;
1859 }
1860
1861 // Synchronization scope names are implicitly mapped to synchronization
1862 // scope IDs by their order.
1863
1864 if (Stream.readRecord(Entry.ID, Record) != bitc::SYNC_SCOPE_NAME)
1865 return error("Invalid record");
1866
1867 SmallString<16> SSN;
1868 if (convertToString(Record, 0, SSN))
1869 return error("Invalid record");
1870
1871 SSIDs.push_back(Context.getOrInsertSyncScopeID(SSN));
1872 Record.clear();
1873 }
1874}
1875
1876/// Associate a value with its name from the given index in the provided record.
1877Expected<Value *> BitcodeReader::recordValue(SmallVectorImpl<uint64_t> &Record,
1878 unsigned NameIndex, Triple &TT) {
1879 SmallString<128> ValueName;
1880 if (convertToString(Record, NameIndex, ValueName))
1881 return error("Invalid record");
1882 unsigned ValueID = Record[0];
1883 if (ValueID >= ValueList.size() || !ValueList[ValueID])
1884 return error("Invalid record");
1885 Value *V = ValueList[ValueID];
1886
1887 StringRef NameStr(ValueName.data(), ValueName.size());
1888 if (NameStr.find_first_of(0) != StringRef::npos)
1889 return error("Invalid value name");
1890 V->setName(NameStr);
1891 auto *GO = dyn_cast<GlobalObject>(V);
1892 if (GO) {
1893 if (GO->getComdat() == reinterpret_cast<Comdat *>(1)) {
1894 if (TT.supportsCOMDAT())
1895 GO->setComdat(TheModule->getOrInsertComdat(V->getName()));
1896 else
1897 GO->setComdat(nullptr);
1898 }
1899 }
1900 return V;
1901}
1902
1903/// Helper to note and return the current location, and jump to the given
1904/// offset.
1905static uint64_t jumpToValueSymbolTable(uint64_t Offset,
1906 BitstreamCursor &Stream) {
1907 // Save the current parsing location so we can jump back at the end
1908 // of the VST read.
1909 uint64_t CurrentBit = Stream.GetCurrentBitNo();
1910 Stream.JumpToBit(Offset * 32);
1911#ifndef NDEBUG
1912 // Do some checking if we are in debug mode.
1913 BitstreamEntry Entry = Stream.advance();
1914 assert(Entry.Kind == BitstreamEntry::SubBlock)((Entry.Kind == BitstreamEntry::SubBlock) ? static_cast<void
> (0) : __assert_fail ("Entry.Kind == BitstreamEntry::SubBlock"
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Bitcode/Reader/BitcodeReader.cpp"
, 1914, __PRETTY_FUNCTION__))
;
1915 assert(Entry.ID == bitc::VALUE_SYMTAB_BLOCK_ID)((Entry.ID == bitc::VALUE_SYMTAB_BLOCK_ID) ? static_cast<void
> (0) : __assert_fail ("Entry.ID == bitc::VALUE_SYMTAB_BLOCK_ID"
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Bitcode/Reader/BitcodeReader.cpp"
, 1915, __PRETTY_FUNCTION__))
;
1916#else
1917 // In NDEBUG mode ignore the output so we don't get an unused variable
1918 // warning.
1919 Stream.advance();
1920#endif
1921 return CurrentBit;
1922}
1923
1924void BitcodeReader::setDeferredFunctionInfo(unsigned FuncBitcodeOffsetDelta,
1925 Function *F,
1926 ArrayRef<uint64_t> Record) {
1927 // Note that we subtract 1 here because the offset is relative to one word
1928 // before the start of the identification or module block, which was
1929 // historically always the start of the regular bitcode header.
1930 uint64_t FuncWordOffset = Record[1] - 1;
1931 uint64_t FuncBitOffset = FuncWordOffset * 32;
1932 DeferredFunctionInfo[F] = FuncBitOffset + FuncBitcodeOffsetDelta;
1933 // Set the LastFunctionBlockBit to point to the last function block.
1934 // Later when parsing is resumed after function materialization,
1935 // we can simply skip that last function block.
1936 if (FuncBitOffset > LastFunctionBlockBit)
1937 LastFunctionBlockBit = FuncBitOffset;
1938}
1939
1940/// Read a new-style GlobalValue symbol table.
1941Error BitcodeReader::parseGlobalValueSymbolTable() {
1942 unsigned FuncBitcodeOffsetDelta =
1943 Stream.getAbbrevIDWidth() + bitc::BlockIDWidth;
1944
1945 if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
1946 return error("Invalid record");
1947
1948 SmallVector<uint64_t, 64> Record;
1949 while (true) {
1950 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1951
1952 switch (Entry.Kind) {
1953 case BitstreamEntry::SubBlock:
1954 case BitstreamEntry::Error:
1955 return error("Malformed block");
1956 case BitstreamEntry::EndBlock:
1957 return Error::success();
1958 case BitstreamEntry::Record:
1959 break;
1960 }
1961
1962 Record.clear();
1963 switch (Stream.readRecord(Entry.ID, Record)) {
1964 case bitc::VST_CODE_FNENTRY: // [valueid, offset]
1965 setDeferredFunctionInfo(FuncBitcodeOffsetDelta,
1966 cast<Function>(ValueList[Record[0]]), Record);
1967 break;
1968 }
1969 }
1970}
1971
1972/// Parse the value symbol table at either the current parsing location or
1973/// at the given bit offset if provided.
1974Error BitcodeReader::parseValueSymbolTable(uint64_t Offset) {
1975 uint64_t CurrentBit;
1976 // Pass in the Offset to distinguish between calling for the module-level
1977 // VST (where we want to jump to the VST offset) and the function-level
1978 // VST (where we don't).
1979 if (Offset > 0) {
1980 CurrentBit = jumpToValueSymbolTable(Offset, Stream);
1981 // If this module uses a string table, read this as a module-level VST.
1982 if (UseStrtab) {
1983 if (Error Err = parseGlobalValueSymbolTable())
1984 return Err;
1985 Stream.JumpToBit(CurrentBit);
1986 return Error::success();
1987 }
1988 // Otherwise, the VST will be in a similar format to a function-level VST,
1989 // and will contain symbol names.
1990 }
1991
1992 // Compute the delta between the bitcode indices in the VST (the word offset
1993 // to the word-aligned ENTER_SUBBLOCK for the function block, and that
1994 // expected by the lazy reader. The reader's EnterSubBlock expects to have
1995 // already read the ENTER_SUBBLOCK code (size getAbbrevIDWidth) and BlockID
1996 // (size BlockIDWidth). Note that we access the stream's AbbrevID width here
1997 // just before entering the VST subblock because: 1) the EnterSubBlock
1998 // changes the AbbrevID width; 2) the VST block is nested within the same
1999 // outer MODULE_BLOCK as the FUNCTION_BLOCKs and therefore have the same
2000 // AbbrevID width before calling EnterSubBlock; and 3) when we want to
2001 // jump to the FUNCTION_BLOCK using this offset later, we don't want
2002 // to rely on the stream's AbbrevID width being that of the MODULE_BLOCK.
2003 unsigned FuncBitcodeOffsetDelta =
2004 Stream.getAbbrevIDWidth() + bitc::BlockIDWidth;
2005
2006 if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
2007 return error("Invalid record");
2008
2009 SmallVector<uint64_t, 64> Record;
2010
2011 Triple TT(TheModule->getTargetTriple());
2012
2013 // Read all the records for this value table.
2014 SmallString<128> ValueName;
2015
2016 while (true) {
2017 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
2018
2019 switch (Entry.Kind) {
2020 case BitstreamEntry::SubBlock: // Handled for us already.
2021 case BitstreamEntry::Error:
2022 return error("Malformed block");
2023 case BitstreamEntry::EndBlock:
2024 if (Offset > 0)
2025 Stream.JumpToBit(CurrentBit);
2026 return Error::success();
2027 case BitstreamEntry::Record:
2028 // The interesting case.
2029 break;
2030 }
2031
2032 // Read a record.
2033 Record.clear();
2034 switch (Stream.readRecord(Entry.ID, Record)) {
2035 default: // Default behavior: unknown type.
2036 break;
2037 case bitc::VST_CODE_ENTRY: { // VST_CODE_ENTRY: [valueid, namechar x N]
2038 Expected<Value *> ValOrErr = recordValue(Record, 1, TT);
2039 if (Error Err = ValOrErr.takeError())
2040 return Err;
2041 ValOrErr.get();
2042 break;
2043 }
2044 case bitc::VST_CODE_FNENTRY: {
2045 // VST_CODE_FNENTRY: [valueid, offset, namechar x N]
2046 Expected<Value *> ValOrErr = recordValue(Record, 2, TT);
2047 if (Error Err = ValOrErr.takeError())
2048 return Err;
2049 Value *V = ValOrErr.get();
2050
2051 // Ignore function offsets emitted for aliases of functions in older
2052 // versions of LLVM.
2053 if (auto *F = dyn_cast<Function>(V))
2054 setDeferredFunctionInfo(FuncBitcodeOffsetDelta, F, Record);
2055 break;
2056 }
2057 case bitc::VST_CODE_BBENTRY: {
2058 if (convertToString(Record, 1, ValueName))
2059 return error("Invalid record");
2060 BasicBlock *BB = getBasicBlock(Record[0]);
2061 if (!BB)
2062 return error("Invalid record");
2063
2064 BB->setName(StringRef(ValueName.data(), ValueName.size()));
2065 ValueName.clear();
2066 break;
2067 }
2068 }
2069 }
2070}
2071
2072/// Decode a signed value stored with the sign bit in the LSB for dense VBR
2073/// encoding.
2074uint64_t BitcodeReader::decodeSignRotatedValue(uint64_t V) {
2075 if ((V & 1) == 0)
2076 return V >> 1;
2077 if (V != 1)
2078 return -(V >> 1);
2079 // There is no such thing as -0 with integers. "-0" really means MININT.
2080 return 1ULL << 63;
2081}
2082
2083/// Resolve all of the initializers for global values and aliases that we can.
2084Error BitcodeReader::resolveGlobalAndIndirectSymbolInits() {
2085 std::vector<std::pair<GlobalVariable *, unsigned>> GlobalInitWorklist;
2086 std::vector<std::pair<GlobalIndirectSymbol *, unsigned>>
2087 IndirectSymbolInitWorklist;
2088 std::vector<std::pair<Function *, unsigned>> FunctionPrefixWorklist;
2089 std::vector<std::pair<Function *, unsigned>> FunctionPrologueWorklist;
2090 std::vector<std::pair<Function *, unsigned>> FunctionPersonalityFnWorklist;
2091
2092 GlobalInitWorklist.swap(GlobalInits);
2093 IndirectSymbolInitWorklist.swap(IndirectSymbolInits);
2094 FunctionPrefixWorklist.swap(FunctionPrefixes);
2095 FunctionPrologueWorklist.swap(FunctionPrologues);
2096 FunctionPersonalityFnWorklist.swap(FunctionPersonalityFns);
2097
2098 while (!GlobalInitWorklist.empty()) {
2099 unsigned ValID = GlobalInitWorklist.back().second;
2100 if (ValID >= ValueList.size()) {
2101 // Not ready to resolve this yet, it requires something later in the file.
2102 GlobalInits.push_back(GlobalInitWorklist.back());
2103 } else {
2104 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
2105 GlobalInitWorklist.back().first->setInitializer(C);
2106 else
2107 return error("Expected a constant");
2108 }
2109 GlobalInitWorklist.pop_back();
2110 }
2111
2112 while (!IndirectSymbolInitWorklist.empty()) {
2113 unsigned ValID = IndirectSymbolInitWorklist.back().second;
2114 if (ValID >= ValueList.size()) {
2115 IndirectSymbolInits.push_back(IndirectSymbolInitWorklist.back());
2116 } else {
2117 Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]);
2118 if (!C)
2119 return error("Expected a constant");
2120 GlobalIndirectSymbol *GIS = IndirectSymbolInitWorklist.back().first;
2121 if (isa<GlobalAlias>(GIS) && C->getType() != GIS->getType())
2122 return error("Alias and aliasee types don't match");
2123 GIS->setIndirectSymbol(C);
2124 }
2125 IndirectSymbolInitWorklist.pop_back();
2126 }
2127
2128 while (!FunctionPrefixWorklist.empty()) {
2129 unsigned ValID = FunctionPrefixWorklist.back().second;
2130 if (ValID >= ValueList.size()) {
2131 FunctionPrefixes.push_back(FunctionPrefixWorklist.back());
2132 } else {
2133 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
2134 FunctionPrefixWorklist.back().first->setPrefixData(C);
2135 else
2136 return error("Expected a constant");
2137 }
2138 FunctionPrefixWorklist.pop_back();
2139 }
2140
2141 while (!FunctionPrologueWorklist.empty()) {
2142 unsigned ValID = FunctionPrologueWorklist.back().second;
2143 if (ValID >= ValueList.size()) {
2144 FunctionPrologues.push_back(FunctionPrologueWorklist.back());
2145 } else {
2146 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
2147 FunctionPrologueWorklist.back().first->setPrologueData(C);
2148 else
2149 return error("Expected a constant");
2150 }
2151 FunctionPrologueWorklist.pop_back();
2152 }
2153
2154 while (!FunctionPersonalityFnWorklist.empty()) {
2155 unsigned ValID = FunctionPersonalityFnWorklist.back().second;
2156 if (ValID >= ValueList.size()) {
2157 FunctionPersonalityFns.push_back(FunctionPersonalityFnWorklist.back());
2158 } else {
2159 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
2160 FunctionPersonalityFnWorklist.back().first->setPersonalityFn(C);
2161 else
2162 return error("Expected a constant");
2163 }
2164 FunctionPersonalityFnWorklist.pop_back();
2165 }
2166
2167 return Error::success();
2168}
2169
2170static APInt readWideAPInt(ArrayRef<uint64_t> Vals, unsigned TypeBits) {
2171 SmallVector<uint64_t, 8> Words(Vals.size());
2172 transform(Vals, Words.begin(),
2173 BitcodeReader::decodeSignRotatedValue);
2174
2175 return APInt(TypeBits, Words);
2176}
2177
2178Error BitcodeReader::parseConstants() {
2179 if (Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID))
2180 return error("Invalid record");
2181
2182 SmallVector<uint64_t, 64> Record;
2183
2184 // Read all the records for this value table.
2185 Type *CurTy = Type::getInt32Ty(Context);
2186 unsigned NextCstNo = ValueList.size();
2187
2188 while (true) {
2189 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
2190
2191 switch (Entry.Kind) {
2192 case BitstreamEntry::SubBlock: // Handled for us already.
2193 case BitstreamEntry::Error:
2194 return error("Malformed block");
2195 case BitstreamEntry::EndBlock:
2196 if (NextCstNo != ValueList.size())
2197 return error("Invalid constant reference");
2198
2199 // Once all the constants have been read, go through and resolve forward
2200 // references.
2201 ValueList.resolveConstantForwardRefs();
2202 return Error::success();
2203 case BitstreamEntry::Record:
2204 // The interesting case.
2205 break;
2206 }
2207
2208 // Read a record.
2209 Record.clear();
2210 Type *VoidType = Type::getVoidTy(Context);
2211 Value *V = nullptr;
2212 unsigned BitCode = Stream.readRecord(Entry.ID, Record);
2213 switch (BitCode) {
2214 default: // Default behavior: unknown constant
2215 case bitc::CST_CODE_UNDEF: // UNDEF
2216 V = UndefValue::get(CurTy);
2217 break;
2218 case bitc::CST_CODE_SETTYPE: // SETTYPE: [typeid]
2219 if (Record.empty())
2220 return error("Invalid record");
2221 if (Record[0] >= TypeList.size() || !TypeList[Record[0]])
2222 return error("Invalid record");
2223 if (TypeList[Record[0]] == VoidType)
2224 return error("Invalid constant type");
2225 CurTy = TypeList[Record[0]];
2226 continue; // Skip the ValueList manipulation.
2227 case bitc::CST_CODE_NULL: // NULL
2228 V = Constant::getNullValue(CurTy);
2229 break;
2230 case bitc::CST_CODE_INTEGER: // INTEGER: [intval]
2231 if (!CurTy->isIntegerTy() || Record.empty())
2232 return error("Invalid record");
2233 V = ConstantInt::get(CurTy, decodeSignRotatedValue(Record[0]));
2234 break;
2235 case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval]
2236 if (!CurTy->isIntegerTy() || Record.empty())
2237 return error("Invalid record");
2238
2239 APInt VInt =
2240 readWideAPInt(Record, cast<IntegerType>(CurTy)->getBitWidth());
2241 V = ConstantInt::get(Context, VInt);
2242
2243 break;
2244 }
2245 case bitc::CST_CODE_FLOAT: { // FLOAT: [fpval]
2246 if (Record.empty())
2247 return error("Invalid record");
2248 if (CurTy->isHalfTy())
2249 V = ConstantFP::get(Context, APFloat(APFloat::IEEEhalf(),
2250 APInt(16, (uint16_t)Record[0])));
2251 else if (CurTy->isFloatTy())
2252 V = ConstantFP::get(Context, APFloat(APFloat::IEEEsingle(),
2253 APInt(32, (uint32_t)Record[0])));
2254 else if (CurTy->isDoubleTy())
2255 V = ConstantFP::get(Context, APFloat(APFloat::IEEEdouble(),
2256 APInt(64, Record[0])));
2257 else if (CurTy->isX86_FP80Ty()) {
2258 // Bits are not stored the same way as a normal i80 APInt, compensate.
2259 uint64_t Rearrange[2];
2260 Rearrange[0] = (Record[1] & 0xffffLL) | (Record[0] << 16);
2261 Rearrange[1] = Record[0] >> 48;
2262 V = ConstantFP::get(Context, APFloat(APFloat::x87DoubleExtended(),
2263 APInt(80, Rearrange)));
2264 } else if (CurTy->isFP128Ty())
2265 V = ConstantFP::get(Context, APFloat(APFloat::IEEEquad(),
2266 APInt(128, Record)));
2267 else if (CurTy->isPPC_FP128Ty())
2268 V = ConstantFP::get(Context, APFloat(APFloat::PPCDoubleDouble(),
2269 APInt(128, Record)));
2270 else
2271 V = UndefValue::get(CurTy);
2272 break;
2273 }
2274
2275 case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number]
2276 if (Record.empty())
2277 return error("Invalid record");
2278
2279 unsigned Size = Record.size();
2280 SmallVector<Constant*, 16> Elts;
2281
2282 if (StructType *STy = dyn_cast<StructType>(CurTy)) {
2283 for (unsigned i = 0; i != Size; ++i)
2284 Elts.push_back(ValueList.getConstantFwdRef(Record[i],
2285 STy->getElementType(i)));
2286 V = ConstantStruct::get(STy, Elts);
2287 } else if (ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) {
2288 Type *EltTy = ATy->getElementType();
2289 for (unsigned i = 0; i != Size; ++i)
2290 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
2291 V = ConstantArray::get(ATy, Elts);
2292 } else if (VectorType *VTy = dyn_cast<VectorType>(CurTy)) {
2293 Type *EltTy = VTy->getElementType();
2294 for (unsigned i = 0; i != Size; ++i)
2295 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
2296 V = ConstantVector::get(Elts);
2297 } else {
2298 V = UndefValue::get(CurTy);
2299 }
2300 break;
2301 }
2302 case bitc::CST_CODE_STRING: // STRING: [values]
2303 case bitc::CST_CODE_CSTRING: { // CSTRING: [values]
2304 if (Record.empty())
2305 return error("Invalid record");
2306
2307 SmallString<16> Elts(Record.begin(), Record.end());
2308 V = ConstantDataArray::getString(Context, Elts,
2309 BitCode == bitc::CST_CODE_CSTRING);
2310 break;
2311 }
2312 case bitc::CST_CODE_DATA: {// DATA: [n x value]
2313 if (Record.empty())
2314 return error("Invalid record");
2315
2316 Type *EltTy = cast<SequentialType>(CurTy)->getElementType();
2317 if (EltTy->isIntegerTy(8)) {
2318 SmallVector<uint8_t, 16> Elts(Record.begin(), Record.end());
2319 if (isa<VectorType>(CurTy))
2320 V = ConstantDataVector::get(Context, Elts);
2321 else
2322 V = ConstantDataArray::get(Context, Elts);
2323 } else if (EltTy->isIntegerTy(16)) {
2324 SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end());
2325 if (isa<VectorType>(CurTy))
2326 V = ConstantDataVector::get(Context, Elts);
2327 else
2328 V = ConstantDataArray::get(Context, Elts);
2329 } else if (EltTy->isIntegerTy(32)) {
2330 SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end());
2331 if (isa<VectorType>(CurTy))
2332 V = ConstantDataVector::get(Context, Elts);
2333 else
2334 V = ConstantDataArray::get(Context, Elts);
2335 } else if (EltTy->isIntegerTy(64)) {
2336 SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end());
2337 if (isa<VectorType>(CurTy))
2338 V = ConstantDataVector::get(Context, Elts);
2339 else
2340 V = ConstantDataArray::get(Context, Elts);
2341 } else if (EltTy->isHalfTy()) {
2342 SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end());
2343 if (isa<VectorType>(CurTy))
2344 V = ConstantDataVector::getFP(Context, Elts);
2345 else
2346 V = ConstantDataArray::getFP(Context, Elts);
2347 } else if (EltTy->isFloatTy()) {
2348 SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end());
2349 if (isa<VectorType>(CurTy))
2350 V = ConstantDataVector::getFP(Context, Elts);
2351 else
2352 V = ConstantDataArray::getFP(Context, Elts);
2353 } else if (EltTy->isDoubleTy()) {
2354 SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end());
2355 if (isa<VectorType>(CurTy))
2356 V = ConstantDataVector::getFP(Context, Elts);
2357 else
2358 V = ConstantDataArray::getFP(Context, Elts);
2359 } else {
2360 return error("Invalid type for value");
2361 }
2362 break;
2363 }
2364 case bitc::CST_CODE_CE_UNOP: { // CE_UNOP: [opcode, opval]
2365 if (Record.size() < 2)
2366 return error("Invalid record");
2367 int Opc = getDecodedUnaryOpcode(Record[0], CurTy);
2368 if (Opc < 0) {
2369 V = UndefValue::get(CurTy); // Unknown unop.
2370 } else {
2371 Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy);
2372 unsigned Flags = 0;
2373 V = ConstantExpr::get(Opc, LHS, Flags);
2374 }
2375 break;
2376 }
2377 case bitc::CST_CODE_CE_BINOP: { // CE_BINOP: [opcode, opval, opval]
2378 if (Record.size() < 3)
2379 return error("Invalid record");
2380 int Opc = getDecodedBinaryOpcode(Record[0], CurTy);
2381 if (Opc < 0) {
2382 V = UndefValue::get(CurTy); // Unknown binop.
2383 } else {
2384 Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy);
2385 Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy);
2386 unsigned Flags = 0;
2387 if (Record.size() >= 4) {
2388 if (Opc == Instruction::Add ||
2389 Opc == Instruction::Sub ||
2390 Opc == Instruction::Mul ||
2391 Opc == Instruction::Shl) {
2392 if (Record[3] & (1 << bitc::OBO_NO_SIGNED_WRAP))
2393 Flags |= OverflowingBinaryOperator::NoSignedWrap;
2394 if (Record[3] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
2395 Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
2396 } else if (Opc == Instruction::SDiv ||
2397 Opc == Instruction::UDiv ||
2398 Opc == Instruction::LShr ||
2399 Opc == Instruction::AShr) {
2400 if (Record[3] & (1 << bitc::PEO_EXACT))
2401 Flags |= SDivOperator::IsExact;
2402 }
2403 }
2404 V = ConstantExpr::get(Opc, LHS, RHS, Flags);
2405 }
2406 break;
2407 }
2408 case bitc::CST_CODE_CE_CAST: { // CE_CAST: [opcode, opty, opval]
2409 if (Record.size() < 3)
2410 return error("Invalid record");
2411 int Opc = getDecodedCastOpcode(Record[0]);
2412 if (Opc < 0) {
2413 V = UndefValue::get(CurTy); // Unknown cast.
2414 } else {
2415 Type *OpTy = getTypeByID(Record[1]);
2416 if (!OpTy)
2417 return error("Invalid record");
2418 Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy);
2419 V = UpgradeBitCastExpr(Opc, Op, CurTy);
2420 if (!V) V = ConstantExpr::getCast(Opc, Op, CurTy);
2421 }
2422 break;
2423 }
2424 case bitc::CST_CODE_CE_INBOUNDS_GEP: // [ty, n x operands]
2425 case bitc::CST_CODE_CE_GEP: // [ty, n x operands]
2426 case bitc::CST_CODE_CE_GEP_WITH_INRANGE_INDEX: { // [ty, flags, n x
2427 // operands]
2428 unsigned OpNum = 0;
2429 Type *PointeeType = nullptr;
2430 if (BitCode == bitc::CST_CODE_CE_GEP_WITH_INRANGE_INDEX ||
2431 Record.size() % 2)
2432 PointeeType = getTypeByID(Record[OpNum++]);
2433
2434 bool InBounds = false;
2435 Optional<unsigned> InRangeIndex;
2436 if (BitCode == bitc::CST_CODE_CE_GEP_WITH_INRANGE_INDEX) {
2437 uint64_t Op = Record[OpNum++];
2438 InBounds = Op & 1;
2439 InRangeIndex = Op >> 1;
2440 } else if (BitCode == bitc::CST_CODE_CE_INBOUNDS_GEP)
2441 InBounds = true;
2442
2443 SmallVector<Constant*, 16> Elts;
2444 while (OpNum != Record.size()) {
2445 Type *ElTy = getTypeByID(Record[OpNum++]);
2446 if (!ElTy)
2447 return error("Invalid record");
2448 Elts.push_back(ValueList.getConstantFwdRef(Record[OpNum++], ElTy));
2449 }
2450
2451 if (Elts.size() < 1)
2452 return error("Invalid gep with no operands");
2453
2454 Type *ImplicitPointeeType =
2455 cast<PointerType>(Elts[0]->getType()->getScalarType())
2456 ->getElementType();
2457 if (!PointeeType)
2458 PointeeType = ImplicitPointeeType;
2459 else if (PointeeType != ImplicitPointeeType)
2460 return error("Explicit gep operator type does not match pointee type "
2461 "of pointer operand");
2462
2463 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
2464 V = ConstantExpr::getGetElementPtr(PointeeType, Elts[0], Indices,
2465 InBounds, InRangeIndex);
2466 break;
2467 }
2468 case bitc::CST_CODE_CE_SELECT: { // CE_SELECT: [opval#, opval#, opval#]
2469 if (Record.size() < 3)
2470 return error("Invalid record");
2471
2472 Type *SelectorTy = Type::getInt1Ty(Context);
2473
2474 // The selector might be an i1 or an <n x i1>
2475 // Get the type from the ValueList before getting a forward ref.
2476 if (VectorType *VTy = dyn_cast<VectorType>(CurTy))
2477 if (Value *V = ValueList[Record[0]])
2478 if (SelectorTy != V->getType())
2479 SelectorTy = VectorType::get(SelectorTy, VTy->getNumElements());
2480
2481 V = ConstantExpr::getSelect(ValueList.getConstantFwdRef(Record[0],
2482 SelectorTy),
2483 ValueList.getConstantFwdRef(Record[1],CurTy),
2484 ValueList.getConstantFwdRef(Record[2],CurTy));
2485 break;
2486 }
2487 case bitc::CST_CODE_CE_EXTRACTELT
2488 : { // CE_EXTRACTELT: [opty, opval, opty, opval]
2489 if (Record.size() < 3)
2490 return error("Invalid record");
2491 VectorType *OpTy =
2492 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
2493 if (!OpTy)
2494 return error("Invalid record");
2495 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
2496 Constant *Op1 = nullptr;
2497 if (Record.size() == 4) {
2498 Type *IdxTy = getTypeByID(Record[2]);
2499 if (!IdxTy)
2500 return error("Invalid record");
2501 Op1 = ValueList.getConstantFwdRef(Record[3], IdxTy);
2502 } else // TODO: Remove with llvm 4.0
2503 Op1 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
2504 if (!Op1)
2505 return error("Invalid record");
2506 V = ConstantExpr::getExtractElement(Op0, Op1);
2507 break;
2508 }
2509 case bitc::CST_CODE_CE_INSERTELT
2510 : { // CE_INSERTELT: [opval, opval, opty, opval]
2511 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
2512 if (Record.size() < 3 || !OpTy)
2513 return error("Invalid record");
2514 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
2515 Constant *Op1 = ValueList.getConstantFwdRef(Record[1],
2516 OpTy->getElementType());
2517 Constant *Op2 = nullptr;
2518 if (Record.size() == 4) {
2519 Type *IdxTy = getTypeByID(Record[2]);
2520 if (!IdxTy)
2521 return error("Invalid record");
2522 Op2 = ValueList.getConstantFwdRef(Record[3], IdxTy);
2523 } else // TODO: Remove with llvm 4.0
2524 Op2 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
2525 if (!Op2)
2526 return error("Invalid record");
2527 V = ConstantExpr::getInsertElement(Op0, Op1, Op2);
2528 break;
2529 }
2530 case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval]
2531 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
2532 if (Record.size() < 3 || !OpTy)
2533 return error("Invalid record");
2534 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
2535 Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy);
2536 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
2537 OpTy->getNumElements());
2538 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy);
2539 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
2540 break;
2541 }
2542 case bitc::CST_CODE_CE_SHUFVEC_EX: { // [opty, opval, opval, opval]
2543 VectorType *RTy = dyn_cast<VectorType>(CurTy);
2544 VectorType *OpTy =
2545 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
2546 if (Record.size() < 4 || !RTy || !OpTy)
2547 return error("Invalid record");
2548 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
2549 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
2550 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
2551 RTy->getNumElements());
2552 Constant *Op2 = ValueList.getConstantFwdRef(Record[3], ShufTy);
2553 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
2554 break;
2555 }
2556 case bitc::CST_CODE_CE_CMP: { // CE_CMP: [opty, opval, opval, pred]
2557 if (Record.size() < 4)
2558 return error("Invalid record");
2559 Type *OpTy = getTypeByID(Record[0]);
2560 if (!OpTy)
2561 return error("Invalid record");
2562 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
2563 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
2564
2565 if (OpTy->isFPOrFPVectorTy())
2566 V = ConstantExpr::getFCmp(Record[3], Op0, Op1);
2567 else
2568 V = ConstantExpr::getICmp(Record[3], Op0, Op1);
2569 break;
2570 }
2571 // This maintains backward compatibility, pre-asm dialect keywords.
2572 // FIXME: Remove with the 4.0 release.
2573 case bitc::CST_CODE_INLINEASM_OLD: {
2574 if (Record.size() < 2)
2575 return error("Invalid record");
2576 std::string AsmStr, ConstrStr;
2577 bool HasSideEffects = Record[0] & 1;
2578 bool IsAlignStack = Record[0] >> 1;
2579 unsigned AsmStrSize = Record[1];
2580 if (2+AsmStrSize >= Record.size())
2581 return error("Invalid record");
2582 unsigned ConstStrSize = Record[2+AsmStrSize];
2583 if (3+AsmStrSize+ConstStrSize > Record.size())
2584 return error("Invalid record");
2585
2586 for (unsigned i = 0; i != AsmStrSize; ++i)
2587 AsmStr += (char)Record[2+i];
2588 for (unsigned i = 0; i != ConstStrSize; ++i)
2589 ConstrStr += (char)Record[3+AsmStrSize+i];
2590 PointerType *PTy = cast<PointerType>(CurTy);
2591 UpgradeInlineAsmString(&AsmStr);
2592 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
2593 AsmStr, ConstrStr, HasSideEffects, IsAlignStack);
2594 break;
2595 }
2596 // This version adds support for the asm dialect keywords (e.g.,
2597 // inteldialect).
2598 case bitc::CST_CODE_INLINEASM: {
2599 if (Record.size() < 2)
2600 return error("Invalid record");
2601 std::string AsmStr, ConstrStr;
2602 bool HasSideEffects = Record[0] & 1;
2603 bool IsAlignStack = (Record[0] >> 1) & 1;
2604 unsigned AsmDialect = Record[0] >> 2;
2605 unsigned AsmStrSize = Record[1];
2606 if (2+AsmStrSize >= Record.size())
2607 return error("Invalid record");
2608 unsigned ConstStrSize = Record[2+AsmStrSize];
2609 if (3+AsmStrSize+ConstStrSize > Record.size())
2610 return error("Invalid record");
2611
2612 for (unsigned i = 0; i != AsmStrSize; ++i)
2613 AsmStr += (char)Record[2+i];
2614 for (unsigned i = 0; i != ConstStrSize; ++i)
2615 ConstrStr += (char)Record[3+AsmStrSize+i];
2616 PointerType *PTy = cast<PointerType>(CurTy);
2617 UpgradeInlineAsmString(&AsmStr);
2618 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
2619 AsmStr, ConstrStr, HasSideEffects, IsAlignStack,
2620 InlineAsm::AsmDialect(AsmDialect));
2621 break;
2622 }
2623 case bitc::CST_CODE_BLOCKADDRESS:{
2624 if (Record.size() < 3)
2625 return error("Invalid record");
2626 Type *FnTy = getTypeByID(Record[0]);
2627 if (!FnTy)
2628 return error("Invalid record");
2629 Function *Fn =
2630 dyn_cast_or_null<Function>(ValueList.getConstantFwdRef(Record[1],FnTy));
2631 if (!Fn)
2632 return error("Invalid record");
2633
2634 // If the function is already parsed we can insert the block address right
2635 // away.
2636 BasicBlock *BB;
2637 unsigned BBID = Record[2];
2638 if (!BBID)
2639 // Invalid reference to entry block.
2640 return error("Invalid ID");
2641 if (!Fn->empty()) {
2642 Function::iterator BBI = Fn->begin(), BBE = Fn->end();
2643 for (size_t I = 0, E = BBID; I != E; ++I) {
2644 if (BBI == BBE)
2645 return error("Invalid ID");
2646 ++BBI;
2647 }
2648 BB = &*BBI;
2649 } else {
2650 // Otherwise insert a placeholder and remember it so it can be inserted
2651 // when the function is parsed.
2652 auto &FwdBBs = BasicBlockFwdRefs[Fn];
2653 if (FwdBBs.empty())
2654 BasicBlockFwdRefQueue.push_back(Fn);
2655 if (FwdBBs.size() < BBID + 1)
2656 FwdBBs.resize(BBID + 1);
2657 if (!FwdBBs[BBID])
2658 FwdBBs[BBID] = BasicBlock::Create(Context);
2659 BB = FwdBBs[BBID];
2660 }
2661 V = BlockAddress::get(Fn, BB);
2662 break;
2663 }
2664 }
2665
2666 ValueList.assignValue(V, NextCstNo);
2667 ++NextCstNo;
2668 }
2669}
2670
2671Error BitcodeReader::parseUseLists() {
2672 if (Stream.EnterSubBlock(bitc::USELIST_BLOCK_ID))
2673 return error("Invalid record");
2674
2675 // Read all the records.
2676 SmallVector<uint64_t, 64> Record;
2677
2678 while (true) {
2679 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
2680
2681 switch (Entry.Kind) {
2682 case BitstreamEntry::SubBlock: // Handled for us already.
2683 case BitstreamEntry::Error:
2684 return error("Malformed block");
2685 case BitstreamEntry::EndBlock:
2686 return Error::success();
2687 case BitstreamEntry::Record:
2688 // The interesting case.
2689 break;
2690 }
2691
2692 // Read a use list record.
2693 Record.clear();
2694 bool IsBB = false;
2695 switch (Stream.readRecord(Entry.ID, Record)) {
2696 default: // Default behavior: unknown type.
2697 break;
2698 case bitc::USELIST_CODE_BB:
2699 IsBB = true;
2700 LLVM_FALLTHROUGH[[clang::fallthrough]];
2701 case bitc::USELIST_CODE_DEFAULT: {
2702 unsigned RecordLength = Record.size();
2703 if (RecordLength < 3)
2704 // Records should have at least an ID and two indexes.
2705 return error("Invalid record");
2706 unsigned ID = Record.back();
2707 Record.pop_back();
2708
2709 Value *V;
2710 if (IsBB) {
2711 assert(ID < FunctionBBs.size() && "Basic block not found")((ID < FunctionBBs.size() && "Basic block not found"
) ? static_cast<void> (0) : __assert_fail ("ID < FunctionBBs.size() && \"Basic block not found\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Bitcode/Reader/BitcodeReader.cpp"
, 2711, __PRETTY_FUNCTION__))
;
2712 V = FunctionBBs[ID];
2713 } else
2714 V = ValueList[ID];
2715 unsigned NumUses = 0;
2716 SmallDenseMap<const Use *, unsigned, 16> Order;
2717 for (const Use &U : V->materialized_uses()) {
2718 if (++NumUses > Record.size())
2719 break;
2720 Order[&U] = Record[NumUses - 1];
2721 }
2722 if (Order.size() != Record.size() || NumUses > Record.size())
2723 // Mismatches can happen if the functions are being materialized lazily
2724 // (out-of-order), or a value has been upgraded.
2725 break;
2726
2727 V->sortUseList([&](const Use &L, const Use &R) {
2728 return Order.lookup(&L) < Order.lookup(&R);
2729 });
2730 break;
2731 }
2732 }
2733 }
2734}
2735
2736/// When we see the block for metadata, remember where it is and then skip it.
2737/// This lets us lazily deserialize the metadata.
2738Error BitcodeReader::rememberAndSkipMetadata() {
2739 // Save the current stream state.
2740 uint64_t CurBit = Stream.GetCurrentBitNo();
2741 DeferredMetadataInfo.push_back(CurBit);
2742
2743 // Skip over the block for now.
2744 if (Stream.SkipBlock())
2745 return error("Invalid record");
2746 return Error::success();
2747}
2748
2749Error BitcodeReader::materializeMetadata() {
2750 for (uint64_t BitPos : DeferredMetadataInfo) {
2751 // Move the bit stream to the saved position.
2752 Stream.JumpToBit(BitPos);
2753 if (Error Err = MDLoader->parseModuleMetadata())
2754 return Err;
2755 }
2756
2757 // Upgrade "Linker Options" module flag to "llvm.linker.options" module-level
2758 // metadata.
2759 if (Metadata *Val = TheModule->getModuleFlag("Linker Options")) {
2760 NamedMDNode *LinkerOpts =
2761 TheModule->getOrInsertNamedMetadata("llvm.linker.options");
2762 for (const MDOperand &MDOptions : cast<MDNode>(Val)->operands())
2763 LinkerOpts->addOperand(cast<MDNode>(MDOptions));
2764 }
2765
2766 DeferredMetadataInfo.clear();
2767 return Error::success();
2768}
2769
2770void BitcodeReader::setStripDebugInfo() { StripDebugInfo = true; }
2771
2772/// When we see the block for a function body, remember where it is and then
2773/// skip it. This lets us lazily deserialize the functions.
2774Error BitcodeReader::rememberAndSkipFunctionBody() {
2775 // Get the function we are talking about.
2776 if (FunctionsWithBodies.empty())
2777 return error("Insufficient function protos");
2778
2779 Function *Fn = FunctionsWithBodies.back();
2780 FunctionsWithBodies.pop_back();
2781
2782 // Save the current stream state.
2783 uint64_t CurBit = Stream.GetCurrentBitNo();
2784 assert((((DeferredFunctionInfo[Fn] == 0 || DeferredFunctionInfo[Fn] ==
CurBit) && "Mismatch between VST and scanned function offsets"
) ? static_cast<void> (0) : __assert_fail ("(DeferredFunctionInfo[Fn] == 0 || DeferredFunctionInfo[Fn] == CurBit) && \"Mismatch between VST and scanned function offsets\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Bitcode/Reader/BitcodeReader.cpp"
, 2786, __PRETTY_FUNCTION__))
2785 (DeferredFunctionInfo[Fn] == 0 || DeferredFunctionInfo[Fn] == CurBit) &&(((DeferredFunctionInfo[Fn] == 0 || DeferredFunctionInfo[Fn] ==
CurBit) && "Mismatch between VST and scanned function offsets"
) ? static_cast<void> (0) : __assert_fail ("(DeferredFunctionInfo[Fn] == 0 || DeferredFunctionInfo[Fn] == CurBit) && \"Mismatch between VST and scanned function offsets\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Bitcode/Reader/BitcodeReader.cpp"
, 2786, __PRETTY_FUNCTION__))
2786 "Mismatch between VST and scanned function offsets")(((DeferredFunctionInfo[Fn] == 0 || DeferredFunctionInfo[Fn] ==
CurBit) && "Mismatch between VST and scanned function offsets"
) ? static_cast<void> (0) : __assert_fail ("(DeferredFunctionInfo[Fn] == 0 || DeferredFunctionInfo[Fn] == CurBit) && \"Mismatch between VST and scanned function offsets\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Bitcode/Reader/BitcodeReader.cpp"
, 2786, __PRETTY_FUNCTION__))
;
2787 DeferredFunctionInfo[Fn] = CurBit;
2788
2789 // Skip over the function block for now.
2790 if (Stream.SkipBlock())
2791 return error("Invalid record");
2792 return Error::success();
2793}
2794
2795Error BitcodeReader::globalCleanup() {
2796 // Patch the initializers for globals and aliases up.
2797 if (Error Err = resolveGlobalAndIndirectSymbolInits())
2798 return Err;
2799 if (!GlobalInits.empty() || !IndirectSymbolInits.empty())
2800 return error("Malformed global initializer set");
2801
2802 // Look for intrinsic functions which need to be upgraded at some point
2803 for (Function &F : *TheModule) {
2804 MDLoader->upgradeDebugIntrinsics(F);
2805 Function *NewFn;
2806 if (UpgradeIntrinsicFunction(&F, NewFn))
2807 UpgradedIntrinsics[&F] = NewFn;
2808 else if (auto Remangled = Intrinsic::remangleIntrinsicFunction(&F))
2809 // Some types could be renamed during loading if several modules are
2810 // loaded in the same LLVMContext (LTO scenario). In this case we should
2811 // remangle intrinsics names as well.
2812 RemangledIntrinsics[&F] = Remangled.getValue();
2813 }
2814
2815 // Look for global variables which need to be renamed.
2816 std::vector<std::pair<GlobalVariable *, GlobalVariable *>> UpgradedVariables;
2817 for (GlobalVariable &GV : TheModule->globals())
2818 if (GlobalVariable *Upgraded = UpgradeGlobalVariable(&GV))
2819 UpgradedVariables.emplace_back(&GV, Upgraded);
2820 for (auto &Pair : UpgradedVariables) {
2821 Pair.first->eraseFromParent();
2822 TheModule->getGlobalList().push_back(Pair.second);
2823 }
2824
2825 // Force deallocation of memory for these vectors to favor the client that
2826 // want lazy deserialization.
2827 std::vector<std::pair<GlobalVariable *, unsigned>>().swap(GlobalInits);
2828 std::vector<std::pair<GlobalIndirectSymbol *, unsigned>>().swap(
2829 IndirectSymbolInits);
2830 return Error::success();
2831}
2832
2833/// Support for lazy parsing of function bodies. This is required if we
2834/// either have an old bitcode file without a VST forward declaration record,
2835/// or if we have an anonymous function being materialized, since anonymous
2836/// functions do not have a name and are therefore not in the VST.
2837Error BitcodeReader::rememberAndSkipFunctionBodies() {
2838 Stream.JumpToBit(NextUnreadBit);
2839
2840 if (Stream.AtEndOfStream())
2841 return error("Could not find function in stream");
2842
2843 if (!SeenFirstFunctionBody)
2844 return error("Trying to materialize functions before seeing function blocks");
2845
2846 // An old bitcode file with the symbol table at the end would have
2847 // finished the parse greedily.
2848 assert(SeenValueSymbolTable)((SeenValueSymbolTable) ? static_cast<void> (0) : __assert_fail
("SeenValueSymbolTable", "/build/llvm-toolchain-snapshot-9~svn362543/lib/Bitcode/Reader/BitcodeReader.cpp"
, 2848, __PRETTY_FUNCTION__))
;
2849
2850 SmallVector<uint64_t, 64> Record;
2851
2852 while (true) {
2853 BitstreamEntry Entry = Stream.advance();
2854 switch (Entry.Kind) {
2855 default:
2856 return error("Expect SubBlock");
2857 case BitstreamEntry::SubBlock:
2858 switch (Entry.ID) {
2859 default:
2860 return error("Expect function block");
2861 case bitc::FUNCTION_BLOCK_ID:
2862 if (Error Err = rememberAndSkipFunctionBody())
2863 return Err;
2864 NextUnreadBit = Stream.GetCurrentBitNo();
2865 return Error::success();
2866 }
2867 }
2868 }
2869}
2870
2871bool BitcodeReaderBase::readBlockInfo() {
2872 Optional<BitstreamBlockInfo> NewBlockInfo = Stream.ReadBlockInfoBlock();
2873 if (!NewBlockInfo)
2874 return true;
2875 BlockInfo = std::move(*NewBlockInfo);
2876 return false;
2877}
2878
2879Error BitcodeReader::parseComdatRecord(ArrayRef<uint64_t> Record) {
2880 // v1: [selection_kind, name]
2881 // v2: [strtab_offset, strtab_size, selection_kind]
2882 StringRef Name;
2883 std::tie(Name, Record) = readNameFromStrtab(Record);
2884
2885 if (Record.empty())
2886 return error("Invalid record");
2887 Comdat::SelectionKind SK = getDecodedComdatSelectionKind(Record[0]);
2888 std::string OldFormatName;
2889 if (!UseStrtab) {
2890 if (Record.size() < 2)
2891 return error("Invalid record");
2892 unsigned ComdatNameSize = Record[1];
2893 OldFormatName.reserve(ComdatNameSize);
2894 for (unsigned i = 0; i != ComdatNameSize; ++i)
2895 OldFormatName += (char)Record[2 + i];
2896 Name = OldFormatName;
2897 }
2898 Comdat *C = TheModule->getOrInsertComdat(Name);
2899 C->setSelectionKind(SK);
2900 ComdatList.push_back(C);
2901 return Error::success();
2902}
2903
2904static void inferDSOLocal(GlobalValue *GV) {
2905 // infer dso_local from linkage and visibility if it is not encoded.
2906 if (GV->hasLocalLinkage() ||
2907 (!GV->hasDefaultVisibility() && !GV->hasExternalWeakLinkage()))
2908 GV->setDSOLocal(true);
2909}
2910
2911Error BitcodeReader::parseGlobalVarRecord(ArrayRef<uint64_t> Record) {
2912 // v1: [pointer type, isconst, initid, linkage, alignment, section,
2913 // visibility, threadlocal, unnamed_addr, externally_initialized,
2914 // dllstorageclass, comdat, attributes, preemption specifier,
2915 // partition strtab offset, partition strtab size] (name in VST)
2916 // v2: [strtab_offset, strtab_size, v1]
2917 StringRef Name;
2918 std::tie(Name, Record) = readNameFromStrtab(Record);
2919
2920 if (Record.size() < 6)
2921 return error("Invalid record");
2922 Type *Ty = getTypeByID(Record[0]);
2923 if (!Ty)
2924 return error("Invalid record");
2925 bool isConstant = Record[1] & 1;
2926 bool explicitType = Record[1] & 2;
2927 unsigned AddressSpace;
2928 if (explicitType) {
2929 AddressSpace = Record[1] >> 2;
2930 } else {
2931 if (!Ty->isPointerTy())
2932 return error("Invalid type for value");
2933 AddressSpace = cast<PointerType>(Ty)->getAddressSpace();
2934 Ty = cast<PointerType>(Ty)->getElementType();
2935 }
2936
2937 uint64_t RawLinkage = Record[3];
2938 GlobalValue::LinkageTypes Linkage = getDecodedLinkage(RawLinkage);
2939 unsigned Alignment;
2940 if (Error Err = parseAlignmentValue(Record[4], Alignment))
2941 return Err;
2942 std::string Section;
2943 if (Record[5]) {
2944 if (Record[5] - 1 >= SectionTable.size())
2945 return error("Invalid ID");
2946 Section = SectionTable[Record[5] - 1];
2947 }
2948 GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;
2949 // Local linkage must have default visibility.
2950 if (Record.size() > 6 && !GlobalValue::isLocalLinkage(Linkage))
2951 // FIXME: Change to an error if non-default in 4.0.
2952 Visibility = getDecodedVisibility(Record[6]);
2953
2954 GlobalVariable::ThreadLocalMode TLM = GlobalVariable::NotThreadLocal;
2955 if (Record.size() > 7)
2956 TLM = getDecodedThreadLocalMode(Record[7]);
2957
2958 GlobalValue::UnnamedAddr UnnamedAddr = GlobalValue::UnnamedAddr::None;
2959 if (Record.size() > 8)
2960 UnnamedAddr = getDecodedUnnamedAddrType(Record[8]);
2961
2962 bool ExternallyInitialized = false;
2963 if (Record.size() > 9)
2964 ExternallyInitialized = Record[9];
2965
2966 GlobalVariable *NewGV =
2967 new GlobalVariable(*TheModule, Ty, isConstant, Linkage, nullptr, Name,
2968 nullptr, TLM, AddressSpace, ExternallyInitialized);
2969 NewGV->setAlignment(Alignment);
2970 if (!Section.empty())
2971 NewGV->setSection(Section);
2972 NewGV->setVisibility(Visibility);
2973 NewGV->setUnnamedAddr(UnnamedAddr);
2974
2975 if (Record.size() > 10)
2976 NewGV->setDLLStorageClass(getDecodedDLLStorageClass(Record[10]));
2977 else
2978 upgradeDLLImportExportLinkage(NewGV, RawLinkage);
2979
2980 ValueList.push_back(NewGV);
2981
2982 // Remember which value to use for the global initializer.
2983 if (unsigned InitID = Record[2])
2984 GlobalInits.push_back(std::make_pair(NewGV, InitID - 1));
2985
2986 if (Record.size() > 11) {
2987 if (unsigned ComdatID = Record[11]) {
2988 if (ComdatID > ComdatList.size())
2989 return error("Invalid global variable comdat ID");
2990 NewGV->setComdat(ComdatList[ComdatID - 1]);
2991 }
2992 } else if (hasImplicitComdat(RawLinkage)) {
2993 NewGV->setComdat(reinterpret_cast<Comdat *>(1));
2994 }
2995
2996 if (Record.size() > 12) {
2997 auto AS = getAttributes(Record[12]).getFnAttributes();
2998 NewGV->setAttributes(AS);
2999 }
3000
3001 if (Record.size() > 13) {
3002 NewGV->setDSOLocal(getDecodedDSOLocal(Record[13]));
3003 }
3004 inferDSOLocal(NewGV);
3005
3006 // Check whether we have enough values to read a partition name.
3007 if (Record.size() > 15)
3008 NewGV->setPartition(StringRef(Strtab.data() + Record[14], Record[15]));
3009
3010 return Error::success();
3011}
3012
3013Error BitcodeReader::parseFunctionRecord(ArrayRef<uint64_t> Record) {
3014 // v1: [type, callingconv, isproto, linkage, paramattr, alignment, section,
3015 // visibility, gc, unnamed_addr, prologuedata, dllstorageclass, comdat,
3016 // prefixdata, personalityfn, preemption specifier, addrspace] (name in VST)
3017 // v2: [strtab_offset, strtab_size, v1]
3018 StringRef Name;
3019 std::tie(Name, Record) = readNameFromStrtab(Record);
3020
3021 if (Record.size() < 8)
3022 return error("Invalid record");
3023 Type *Ty = getTypeByID(Record[0]);
3024 if (!Ty)
3025 return error("Invalid record");
3026 if (auto *PTy = dyn_cast<PointerType>(Ty))
3027 Ty = PTy->getElementType();
3028 auto *FTy = dyn_cast<FunctionType>(Ty);
3029 if (!FTy)
3030 return error("Invalid type for value");
3031 auto CC = static_cast<CallingConv::ID>(Record[1]);
3032 if (CC & ~CallingConv::MaxID)
3033 return error("Invalid calling convention ID");
3034
3035 unsigned AddrSpace = TheModule->getDataLayout().getProgramAddressSpace();
3036 if (Record.size() > 16)
3037 AddrSpace = Record[16];
3038
3039 Function *Func = Function::Create(FTy, GlobalValue::ExternalLinkage,
3040 AddrSpace, Name, TheModule);
3041
3042 Func->setCallingConv(CC);
3043 bool isProto = Record[2];
3044 uint64_t RawLinkage = Record[3];
3045 Func->setLinkage(getDecodedLinkage(RawLinkage));
3046 Func->setAttributes(getAttributes(Record[4]));
3047
3048 // Upgrade any old-style byval without a type by propagating the argument's
3049 // pointee type. There should be no opaque pointers where the byval type is
3050 // implicit.
3051 for (auto &Arg : Func->args()) {
3052 if (Arg.hasByValAttr() && !Arg.getParamByValType()) {
3053 Arg.removeAttr(Attribute::ByVal);
3054 Arg.addAttr(Attribute::getWithByValType(
3055 Context, Arg.getType()->getPointerElementType()));
3056 }
3057 }
3058
3059 unsigned Alignment;
3060 if (Error Err = parseAlignmentValue(Record[5], Alignment))
3061 return Err;
3062 Func->setAlignment(Alignment);
3063 if (Record[6]) {
3064 if (Record[6] - 1 >= SectionTable.size())
3065 return error("Invalid ID");
3066 Func->setSection(SectionTable[Record[6] - 1]);
3067 }
3068 // Local linkage must have default visibility.
3069 if (!Func->hasLocalLinkage())
3070 // FIXME: Change to an error if non-default in 4.0.
3071 Func->setVisibility(getDecodedVisibility(Record[7]));
3072 if (Record.size() > 8 && Record[8]) {
3073 if (Record[8] - 1 >= GCTable.size())
3074 return error("Invalid ID");
3075 Func->setGC(GCTable[Record[8] - 1]);
3076 }
3077 GlobalValue::UnnamedAddr UnnamedAddr = GlobalValue::UnnamedAddr::None;
3078 if (Record.size() > 9)
3079 UnnamedAddr = getDecodedUnnamedAddrType(Record[9]);
3080 Func->setUnnamedAddr(UnnamedAddr);
3081 if (Record.size() > 10 && Record[10] != 0)
3082 FunctionPrologues.push_back(std::make_pair(Func, Record[10] - 1));
3083
3084 if (Record.size() > 11)
3085 Func->setDLLStorageClass(getDecodedDLLStorageClass(Record[11]));
3086 else
3087 upgradeDLLImportExportLinkage(Func, RawLinkage);
3088
3089 if (Record.size() > 12) {
3090 if (unsigned ComdatID = Record[12]) {
3091 if (ComdatID > ComdatList.size())
3092 return error("Invalid function comdat ID");
3093 Func->setComdat(ComdatList[ComdatID - 1]);
3094 }
3095 } else if (hasImplicitComdat(RawLinkage)) {
3096 Func->setComdat(reinterpret_cast<Comdat *>(1));
3097 }
3098
3099 if (Record.size() > 13 && Record[13] != 0)
3100 FunctionPrefixes.push_back(std::make_pair(Func, Record[13] - 1));
3101
3102 if (Record.size() > 14 && Record[14] != 0)
3103 FunctionPersonalityFns.push_back(std::make_pair(Func, Record[14] - 1));
3104
3105 if (Record.size() > 15) {
3106 Func->setDSOLocal(getDecodedDSOLocal(Record[15]));
3107 }
3108 inferDSOLocal(Func);
3109
3110 // Record[16] is the address space number.
3111
3112 // Check whether we have enough values to read a partition name.
3113 if (Record.size() > 18)
3114 Func->setPartition(StringRef(Strtab.data() + Record[17], Record[18]));
3115
3116 ValueList.push_back(Func);
3117
3118 // If this is a function with a body, remember the prototype we are
3119 // creating now, so that we can match up the body with them later.
3120 if (!isProto) {
3121 Func->setIsMaterializable(true);
3122 FunctionsWithBodies.push_back(Func);
3123 DeferredFunctionInfo[Func] = 0;
3124 }
3125 return Error::success();
3126}
3127
3128Error BitcodeReader::parseGlobalIndirectSymbolRecord(
3129 unsigned BitCode, ArrayRef<uint64_t> Record) {
3130 // v1 ALIAS_OLD: [alias type, aliasee val#, linkage] (name in VST)
3131 // v1 ALIAS: [alias type, addrspace, aliasee val#, linkage, visibility,
3132 // dllstorageclass, threadlocal, unnamed_addr,
3133 // preemption specifier] (name in VST)
3134 // v1 IFUNC: [alias type, addrspace, aliasee val#, linkage,
3135 // visibility, dllstorageclass, threadlocal, unnamed_addr,
3136 // preemption specifier] (name in VST)
3137 // v2: [strtab_offset, strtab_size, v1]
3138 StringRef Name;
3139 std::tie(Name, Record) = readNameFromStrtab(Record);
3140
3141 bool NewRecord = BitCode != bitc::MODULE_CODE_ALIAS_OLD;
3142 if (Record.size() < (3 + (unsigned)NewRecord))
3143 return error("Invalid record");
3144 unsigned OpNum = 0;
3145 Type *Ty = getTypeByID(Record[OpNum++]);
3146 if (!Ty)
3147 return error("Invalid record");
3148
3149 unsigned AddrSpace;
3150 if (!NewRecord) {
3151 auto *PTy = dyn_cast<PointerType>(Ty);
3152 if (!PTy)
3153 return error("Invalid type for value");
3154 Ty = PTy->getElementType();
3155 AddrSpace = PTy->getAddressSpace();
3156 } else {
3157 AddrSpace = Record[OpNum++];
3158 }
3159
3160 auto Val = Record[OpNum++];
3161 auto Linkage = Record[OpNum++];
3162 GlobalIndirectSymbol *NewGA;
3163 if (BitCode == bitc::MODULE_CODE_ALIAS ||
3164 BitCode == bitc::MODULE_CODE_ALIAS_OLD)
3165 NewGA = GlobalAlias::create(Ty, AddrSpace, getDecodedLinkage(Linkage), Name,
3166 TheModule);
3167 else
3168 NewGA = GlobalIFunc::create(Ty, AddrSpace, getDecodedLinkage(Linkage), Name,
3169 nullptr, TheModule);
3170 // Old bitcode files didn't have visibility field.
3171 // Local linkage must have default visibility.
3172 if (OpNum != Record.size()) {
3173 auto VisInd = OpNum++;
3174 if (!NewGA->hasLocalLinkage())
3175 // FIXME: Change to an error if non-default in 4.0.
3176 NewGA->setVisibility(getDecodedVisibility(Record[VisInd]));
3177 }
3178 if (BitCode == bitc::MODULE_CODE_ALIAS ||
3179 BitCode == bitc::MODULE_CODE_ALIAS_OLD) {
3180 if (OpNum != Record.size())
3181 NewGA->setDLLStorageClass(getDecodedDLLStorageClass(Record[OpNum++]));
3182 else
3183 upgradeDLLImportExportLinkage(NewGA, Linkage);
3184 if (OpNum != Record.size())
3185 NewGA->setThreadLocalMode(getDecodedThreadLocalMode(Record[OpNum++]));
3186 if (OpNum != Record.size())
3187 NewGA->setUnnamedAddr(getDecodedUnnamedAddrType(Record[OpNum++]));
3188 }
3189 if (OpNum != Record.size())
3190 NewGA->setDSOLocal(getDecodedDSOLocal(Record[OpNum++]));
3191 inferDSOLocal(NewGA);
3192
3193 // Check whether we have enough values to read a partition name.
3194 if (OpNum + 1 < Record.size()) {
3195 NewGA->setPartition(
3196 StringRef(Strtab.data() + Record[OpNum], Record[OpNum + 1]));
3197 OpNum += 2;
3198 }
3199
3200 ValueList.push_back(NewGA);
3201 IndirectSymbolInits.push_back(std::make_pair(NewGA, Val));
3202 return Error::success();
3203}
3204
3205Error BitcodeReader::parseModule(uint64_t ResumeBit,
3206 bool ShouldLazyLoadMetadata) {
3207 if (ResumeBit)
3208 Stream.JumpToBit(ResumeBit);
3209 else if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
3210 return error("Invalid record");
3211
3212 SmallVector<uint64_t, 64> Record;
3213
3214 // Read all the records for this module.
3215 while (true) {
3216 BitstreamEntry Entry = Stream.advance();
3217
3218 switch (Entry.Kind) {
3219 case BitstreamEntry::Error:
3220 return error("Malformed block");
3221 case BitstreamEntry::EndBlock:
3222 return globalCleanup();
3223
3224 case BitstreamEntry::SubBlock:
3225 switch (Entry.ID) {
3226 default: // Skip unknown content.
3227 if (Stream.SkipBlock())
3228 return error("Invalid record");
3229 break;
3230 case bitc::BLOCKINFO_BLOCK_ID:
3231 if (readBlockInfo())
3232 return error("Malformed block");
3233 break;
3234 case bitc::PARAMATTR_BLOCK_ID:
3235 if (Error Err = parseAttributeBlock())
3236 return Err;
3237 break;
3238 case bitc::PARAMATTR_GROUP_BLOCK_ID:
3239 if (Error Err = parseAttributeGroupBlock())
3240 return Err;
3241 break;
3242 case bitc::TYPE_BLOCK_ID_NEW:
3243 if (Error Err = parseTypeTable())
3244 return Err;
3245 break;
3246 case bitc::VALUE_SYMTAB_BLOCK_ID:
3247 if (!SeenValueSymbolTable) {
3248 // Either this is an old form VST without function index and an
3249 // associated VST forward declaration record (which would have caused
3250 // the VST to be jumped to and parsed before it was encountered
3251 // normally in the stream), or there were no function blocks to
3252 // trigger an earlier parsing of the VST.
3253 assert(VSTOffset == 0 || FunctionsWithBodies.empty())((VSTOffset == 0 || FunctionsWithBodies.empty()) ? static_cast
<void> (0) : __assert_fail ("VSTOffset == 0 || FunctionsWithBodies.empty()"
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Bitcode/Reader/BitcodeReader.cpp"
, 3253, __PRETTY_FUNCTION__))
;
3254 if (Error Err = parseValueSymbolTable())
3255 return Err;
3256 SeenValueSymbolTable = true;
3257 } else {
3258 // We must have had a VST forward declaration record, which caused
3259 // the parser to jump to and parse the VST earlier.
3260 assert(VSTOffset > 0)((VSTOffset > 0) ? static_cast<void> (0) : __assert_fail
("VSTOffset > 0", "/build/llvm-toolchain-snapshot-9~svn362543/lib/Bitcode/Reader/BitcodeReader.cpp"
, 3260, __PRETTY_FUNCTION__))
;
3261 if (Stream.SkipBlock())
3262 return error("Invalid record");
3263 }
3264 break;
3265 case bitc::CONSTANTS_BLOCK_ID:
3266 if (Error Err = parseConstants())
3267 return Err;
3268 if (Error Err = resolveGlobalAndIndirectSymbolInits())
3269 return Err;
3270 break;
3271 case bitc::METADATA_BLOCK_ID:
3272 if (ShouldLazyLoadMetadata) {
3273 if (Error Err = rememberAndSkipMetadata())
3274 return Err;
3275 break;
3276 }
3277 assert(DeferredMetadataInfo.empty() && "Unexpected deferred metadata")((DeferredMetadataInfo.empty() && "Unexpected deferred metadata"
) ? static_cast<void> (0) : __assert_fail ("DeferredMetadataInfo.empty() && \"Unexpected deferred metadata\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Bitcode/Reader/BitcodeReader.cpp"
, 3277, __PRETTY_FUNCTION__))
;
3278 if (Error Err = MDLoader->parseModuleMetadata())
3279 return Err;
3280 break;
3281 case bitc::METADATA_KIND_BLOCK_ID:
3282 if (Error Err = MDLoader->parseMetadataKinds())
3283 return Err;
3284 break;
3285 case bitc::FUNCTION_BLOCK_ID:
3286 // If this is the first function body we've seen, reverse the
3287 // FunctionsWithBodies list.
3288 if (!SeenFirstFunctionBody) {
3289 std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
3290 if (Error Err = globalCleanup())
3291 return Err;
3292 SeenFirstFunctionBody = true;
3293 }
3294
3295 if (VSTOffset > 0) {
3296 // If we have a VST forward declaration record, make sure we
3297 // parse the VST now if we haven't already. It is needed to
3298 // set up the DeferredFunctionInfo vector for lazy reading.
3299 if (!SeenValueSymbolTable) {
3300 if (Error Err = BitcodeReader::parseValueSymbolTable(VSTOffset))
3301 return Err;
3302 SeenValueSymbolTable = true;
3303 // Fall through so that we record the NextUnreadBit below.
3304 // This is necessary in case we have an anonymous function that
3305 // is later materialized. Since it will not have a VST entry we
3306 // need to fall back to the lazy parse to find its offset.
3307 } else {
3308 // If we have a VST forward declaration record, but have already
3309 // parsed the VST (just above, when the first function body was
3310 // encountered here), then we are resuming the parse after
3311 // materializing functions. The ResumeBit points to the
3312 // start of the last function block recorded in the
3313 // DeferredFunctionInfo map. Skip it.
3314 if (Stream.SkipBlock())
3315 return error("Invalid record");
3316 continue;
3317 }
3318 }
3319
3320 // Support older bitcode files that did not have the function
3321 // index in the VST, nor a VST forward declaration record, as
3322 // well as anonymous functions that do not have VST entries.
3323 // Build the DeferredFunctionInfo vector on the fly.
3324 if (Error Err = rememberAndSkipFunctionBody())
3325 return Err;
3326
3327 // Suspend parsing when we reach the function bodies. Subsequent
3328 // materialization calls will resume it when necessary. If the bitcode
3329 // file is old, the symbol table will be at the end instead and will not
3330 // have been seen yet. In this case, just finish the parse now.
3331 if (SeenValueSymbolTable) {
3332 NextUnreadBit = Stream.GetCurrentBitNo();
3333 // After the VST has been parsed, we need to make sure intrinsic name
3334 // are auto-upgraded.
3335 return globalCleanup();
3336 }
3337 break;
3338 case bitc::USELIST_BLOCK_ID:
3339 if (Error Err = parseUseLists())
3340 return Err;
3341 break;
3342 case bitc::OPERAND_BUNDLE_TAGS_BLOCK_ID:
3343 if (Error Err = parseOperandBundleTags())
3344 return Err;
3345 break;
3346 case bitc::SYNC_SCOPE_NAMES_BLOCK_ID:
3347 if (Error Err = parseSyncScopeNames())
3348 return Err;
3349 break;
3350 }
3351 continue;
3352
3353 case BitstreamEntry::Record:
3354 // The interesting case.
3355 break;
3356 }
3357
3358 // Read a record.
3359 auto BitCode = Stream.readRecord(Entry.ID, Record);
3360 switch (BitCode) {
3361 default: break; // Default behavior, ignore unknown content.
3362 case bitc::MODULE_CODE_VERSION: {
3363 Expected<unsigned> VersionOrErr = parseVersionRecord(Record);
3364 if (!VersionOrErr)
3365 return VersionOrErr.takeError();
3366 UseRelativeIDs = *VersionOrErr >= 1;
3367 break;
3368 }
3369 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
3370 std::string S;
3371 if (convertToString(Record, 0, S))
3372 return error("Invalid record");
3373 TheModule->setTargetTriple(S);
3374 break;
3375 }
3376 case bitc::MODULE_CODE_DATALAYOUT: { // DATALAYOUT: [strchr x N]
3377 std::string S;
3378 if (convertToString(Record, 0, S))
3379 return error("Invalid record");
3380 TheModule->setDataLayout(S);
3381 break;
3382 }
3383 case bitc::MODULE_CODE_ASM: { // ASM: [strchr x N]
3384 std::string S;
3385 if (convertToString(Record, 0, S))
3386 return error("Invalid record");
3387 TheModule->setModuleInlineAsm(S);
3388 break;
3389 }
3390 case bitc::MODULE_CODE_DEPLIB: { // DEPLIB: [strchr x N]
3391 // FIXME: Remove in 4.0.
3392 std::string S;
3393 if (convertToString(Record, 0, S))
3394 return error("Invalid record");
3395 // Ignore value.
3396 break;
3397 }
3398 case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N]
3399 std::string S;
3400 if (convertToString(Record, 0, S))
3401 return error("Invalid record");
3402 SectionTable.push_back(S);
3403 break;
3404 }
3405 case bitc::MODULE_CODE_GCNAME: { // SECTIONNAME: [strchr x N]
3406 std::string S;
3407 if (convertToString(Record, 0, S))
3408 return error("Invalid record");
3409 GCTable.push_back(S);
3410 break;
3411 }
3412 case bitc::MODULE_CODE_COMDAT:
3413 if (Error Err = parseComdatRecord(Record))
3414 return Err;
3415 break;
3416 case bitc::MODULE_CODE_GLOBALVAR:
3417 if (Error Err = parseGlobalVarRecord(Record))
3418 return Err;
3419 break;
3420 case bitc::MODULE_CODE_FUNCTION:
3421 if (Error Err = parseFunctionRecord(Record))
3422 return Err;
3423 break;
3424 case bitc::MODULE_CODE_IFUNC:
3425 case bitc::MODULE_CODE_ALIAS:
3426 case bitc::MODULE_CODE_ALIAS_OLD:
3427 if (Error Err = parseGlobalIndirectSymbolRecord(BitCode, Record))
3428 return Err;
3429 break;
3430 /// MODULE_CODE_VSTOFFSET: [offset]
3431 case bitc::MODULE_CODE_VSTOFFSET:
3432 if (Record.size() < 1)
3433 return error("Invalid record");
3434 // Note that we subtract 1 here because the offset is relative to one word
3435 // before the start of the identification or module block, which was
3436 // historically always the start of the regular bitcode header.
3437 VSTOffset = Record[0] - 1;
3438 break;
3439 /// MODULE_CODE_SOURCE_FILENAME: [namechar x N]
3440 case bitc::MODULE_CODE_SOURCE_FILENAME:
3441 SmallString<128> ValueName;
3442 if (convertToString(Record, 0, ValueName))
3443 return error("Invalid record");
3444 TheModule->setSourceFileName(ValueName);
3445 break;
3446 }
3447 Record.clear();
3448 }
3449}
3450
3451Error BitcodeReader::parseBitcodeInto(Module *M, bool ShouldLazyLoadMetadata,
3452 bool IsImporting) {
3453 TheModule = M;
3454 MDLoader = MetadataLoader(Stream, *M, ValueList, IsImporting,
3455 [&](unsigned ID) { return getTypeByID(ID); });
3456 return parseModule(0, ShouldLazyLoadMetadata);
3457}
3458
3459Error BitcodeReader::typeCheckLoadStoreInst(Type *ValType, Type *PtrType) {
3460 if (!isa<PointerType>(PtrType))
3461 return error("Load/Store operand is not a pointer type");
3462 Type *ElemType = cast<PointerType>(PtrType)->getElementType();
3463
3464 if (ValType && ValType != ElemType)
3465 return error("Explicit load/store type does not match pointee "
3466 "type of pointer operand");
3467 if (!PointerType::isLoadableOrStorableType(ElemType))
3468 return error("Cannot load/store from pointer");
3469 return Error::success();
3470}
3471
3472void BitcodeReader::propagateByValTypes(CallBase *CB) {
3473 for (unsigned i = 0; i < CB->getNumArgOperands(); ++i) {
3474 if (CB->paramHasAttr(i, Attribute::ByVal) &&
3475 !CB->getAttribute(i, Attribute::ByVal).getValueAsType()) {
3476 CB->removeParamAttr(i, Attribute::ByVal);
3477 CB->addParamAttr(
3478 i, Attribute::getWithByValType(
3479 Context,
3480 CB->getArgOperand(i)->getType()->getPointerElementType()));
3481 }
3482 }
3483}
3484
3485/// Lazily parse the specified function body block.
3486Error BitcodeReader::parseFunctionBody(Function *F) {
3487 if (Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID))
1
Assuming the condition is false
2
Taking false branch
3488 return error("Invalid record");
3489
3490 // Unexpected unresolved metadata when parsing function.
3491 if (MDLoader->hasFwdRefs())
3
Assuming the condition is false
4
Taking false branch
3492 return error("Invalid function metadata: incoming forward references");
3493
3494 InstructionList.clear();
3495 unsigned ModuleValueListSize = ValueList.size();
3496 unsigned ModuleMDLoaderSize = MDLoader->size();
3497
3498 // Add all the function arguments to the value table.
3499 for (Argument &I : F->args())
5
Assuming '__begin1' is equal to '__end1'
3500 ValueList.push_back(&I);
3501
3502 unsigned NextValueNo = ValueList.size();
3503 BasicBlock *CurBB = nullptr;
6
'CurBB' initialized to a null pointer value
3504 unsigned CurBBNo = 0;
3505
3506 DebugLoc LastLoc;
3507 auto getLastInstruction = [&]() -> Instruction * {
3508 if (CurBB && !CurBB->empty())
3509 return &CurBB->back();
3510 else if (CurBBNo && FunctionBBs[CurBBNo - 1] &&
3511 !FunctionBBs[CurBBNo - 1]->empty())
3512 return &FunctionBBs[CurBBNo - 1]->back();
3513 return nullptr;
3514 };
3515
3516 std::vector<OperandBundleDef> OperandBundles;
3517
3518 // Read all the records.
3519 SmallVector<uint64_t, 64> Record;
3520
3521 while (true) {
7
Loop condition is true. Entering loop body
3522 BitstreamEntry Entry = Stream.advance();
3523
3524 switch (Entry.Kind) {
8
Control jumps to 'case Record:' at line 3562
3525 case BitstreamEntry::Error:
3526 return error("Malformed block");
3527 case BitstreamEntry::EndBlock:
3528 goto OutOfRecordLoop;
3529
3530 case BitstreamEntry::SubBlock:
3531 switch (Entry.ID) {
3532 default: // Skip unknown content.
3533 if (Stream.SkipBlock())
3534 return error("Invalid record");
3535 break;
3536 case bitc::CONSTANTS_BLOCK_ID:
3537 if (Error Err = parseConstants())
3538 return Err;
3539 NextValueNo = ValueList.size();
3540 break;
3541 case bitc::VALUE_SYMTAB_BLOCK_ID:
3542 if (Error Err = parseValueSymbolTable())
3543 return Err;
3544 break;
3545 case bitc::METADATA_ATTACHMENT_ID:
3546 if (Error Err = MDLoader->parseMetadataAttachment(*F, InstructionList))
3547 return Err;
3548 break;
3549 case bitc::METADATA_BLOCK_ID:
3550 assert(DeferredMetadataInfo.empty() &&((DeferredMetadataInfo.empty() && "Must read all module-level metadata before function-level"
) ? static_cast<void> (0) : __assert_fail ("DeferredMetadataInfo.empty() && \"Must read all module-level metadata before function-level\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Bitcode/Reader/BitcodeReader.cpp"
, 3551, __PRETTY_FUNCTION__))
3551 "Must read all module-level metadata before function-level")((DeferredMetadataInfo.empty() && "Must read all module-level metadata before function-level"
) ? static_cast<void> (0) : __assert_fail ("DeferredMetadataInfo.empty() && \"Must read all module-level metadata before function-level\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Bitcode/Reader/BitcodeReader.cpp"
, 3551, __PRETTY_FUNCTION__))
;
3552 if (Error Err = MDLoader->parseFunctionMetadata())
3553 return Err;
3554 break;
3555 case bitc::USELIST_BLOCK_ID:
3556 if (Error Err = parseUseLists())
3557 return Err;
3558 break;
3559 }
3560 continue;
3561
3562 case BitstreamEntry::Record:
3563 // The interesting case.
3564 break;
9
Execution continues on line 3568
3565 }
3566
3567 // Read a record.
3568 Record.clear();
3569 Instruction *I = nullptr;
3570 unsigned BitCode = Stream.readRecord(Entry.ID, Record);
3571 switch (BitCode) {
10
Control jumps to 'case FUNC_CODE_INST_CMPXCHG_OLD:' at line 4616
3572 default: // Default behavior: reject
3573 return error("Invalid value");
3574 case bitc::FUNC_CODE_DECLAREBLOCKS: { // DECLAREBLOCKS: [nblocks]
3575 if (Record.size() < 1 || Record[0] == 0)
3576 return error("Invalid record");
3577 // Create all the basic blocks for the function.
3578 FunctionBBs.resize(Record[0]);
3579
3580 // See if anything took the address of blocks in this function.
3581 auto BBFRI = BasicBlockFwdRefs.find(F);
3582 if (BBFRI == BasicBlockFwdRefs.end()) {
3583 for (unsigned i = 0, e = FunctionBBs.size(); i != e; ++i)
3584 FunctionBBs[i] = BasicBlock::Create(Context, "", F);
3585 } else {
3586 auto &BBRefs = BBFRI->second;
3587 // Check for invalid basic block references.
3588 if (BBRefs.size() > FunctionBBs.size())
3589 return error("Invalid ID");
3590 assert(!BBRefs.empty() && "Unexpected empty array")((!BBRefs.empty() && "Unexpected empty array") ? static_cast
<void> (0) : __assert_fail ("!BBRefs.empty() && \"Unexpected empty array\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Bitcode/Reader/BitcodeReader.cpp"
, 3590, __PRETTY_FUNCTION__))
;
3591 assert(!BBRefs.front() && "Invalid reference to entry block")((!BBRefs.front() && "Invalid reference to entry block"
) ? static_cast<void> (0) : __assert_fail ("!BBRefs.front() && \"Invalid reference to entry block\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Bitcode/Reader/BitcodeReader.cpp"
, 3591, __PRETTY_FUNCTION__))
;
3592 for (unsigned I = 0, E = FunctionBBs.size(), RE = BBRefs.size(); I != E;
3593 ++I)
3594 if (I < RE && BBRefs[I]) {
3595 BBRefs[I]->insertInto(F);
3596 FunctionBBs[I] = BBRefs[I];
3597 } else {
3598 FunctionBBs[I] = BasicBlock::Create(Context, "", F);
3599 }
3600
3601 // Erase from the table.
3602 BasicBlockFwdRefs.erase(BBFRI);
3603 }
3604
3605 CurBB = FunctionBBs[0];
3606 continue;
3607 }
3608
3609 case bitc::FUNC_CODE_DEBUG_LOC_AGAIN: // DEBUG_LOC_AGAIN
3610 // This record indicates that the last instruction is at the same
3611 // location as the previous instruction with a location.
3612 I = getLastInstruction();
3613
3614 if (!I)
3615 return error("Invalid record");
3616 I->setDebugLoc(LastLoc);
3617 I = nullptr;
3618 continue;
3619
3620 case bitc::FUNC_CODE_DEBUG_LOC: { // DEBUG_LOC: [line, col, scope, ia]
3621 I = getLastInstruction();
3622 if (!I || Record.size() < 4)
3623 return error("Invalid record");
3624
3625 unsigned Line = Record[0], Col = Record[1];
3626 unsigned ScopeID = Record[2], IAID = Record[3];
3627 bool isImplicitCode = Record.size() == 5 && Record[4];
3628
3629 MDNode *Scope = nullptr, *IA = nullptr;
3630 if (ScopeID) {
3631 Scope = dyn_cast_or_null<MDNode>(
3632 MDLoader->getMetadataFwdRefOrLoad(ScopeID - 1));
3633 if (!Scope)
3634 return error("Invalid record");
3635 }
3636 if (IAID) {
3637 IA = dyn_cast_or_null<MDNode>(
3638 MDLoader->getMetadataFwdRefOrLoad(IAID - 1));
3639 if (!IA)
3640 return error("Invalid record");
3641 }
3642 LastLoc = DebugLoc::get(Line, Col, Scope, IA, isImplicitCode);
3643 I->setDebugLoc(LastLoc);
3644 I = nullptr;
3645 continue;
3646 }
3647 case bitc::FUNC_CODE_INST_UNOP: { // UNOP: [opval, ty, opcode]
3648 unsigned OpNum = 0;
3649 Value *LHS;
3650 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
3651 OpNum+1 > Record.size())
3652 return error("Invalid record");
3653
3654 int Opc = getDecodedUnaryOpcode(Record[OpNum++], LHS->getType());
3655 if (Opc == -1)
3656 return error("Invalid record");
3657 I = UnaryOperator::Create((Instruction::UnaryOps)Opc, LHS);
3658 InstructionList.push_back(I);
3659 if (OpNum < Record.size()) {
3660 if (isa<FPMathOperator>(I)) {
3661 FastMathFlags FMF = getDecodedFastMathFlags(Record[OpNum]);
3662 if (FMF.any())
3663 I->setFastMathFlags(FMF);
3664 }
3665 }
3666 break;
3667 }
3668 case bitc::FUNC_CODE_INST_BINOP: { // BINOP: [opval, ty, opval, opcode]
3669 unsigned OpNum = 0;
3670 Value *LHS, *RHS;
3671 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
3672 popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) ||
3673 OpNum+1 > Record.size())
3674 return error("Invalid record");
3675
3676 int Opc = getDecodedBinaryOpcode(Record[OpNum++], LHS->getType());
3677 if (Opc == -1)
3678 return error("Invalid record");
3679 I = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3680 InstructionList.push_back(I);
3681 if (OpNum < Record.size()) {
3682 if (Opc == Instruction::Add ||
3683 Opc == Instruction::Sub ||
3684 Opc == Instruction::Mul ||
3685 Opc == Instruction::Shl) {
3686 if (Record[OpNum] & (1 << bitc::OBO_NO_SIGNED_WRAP))
3687 cast<BinaryOperator>(I)->setHasNoSignedWrap(true);
3688 if (Record[OpNum] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
3689 cast<BinaryOperator>(I)->setHasNoUnsignedWrap(true);
3690 } else if (Opc == Instruction::SDiv ||
3691 Opc == Instruction::UDiv ||
3692 Opc == Instruction::LShr ||
3693 Opc == Instruction::AShr) {
3694 if (Record[OpNum] & (1 << bitc::PEO_EXACT))
3695 cast<BinaryOperator>(I)->setIsExact(true);
3696 } else if (isa<FPMathOperator>(I)) {
3697 FastMathFlags FMF = getDecodedFastMathFlags(Record[OpNum]);
3698 if (FMF.any())
3699 I->setFastMathFlags(FMF);
3700 }
3701
3702 }
3703 break;
3704 }
3705 case bitc::FUNC_CODE_INST_CAST: { // CAST: [opval, opty, destty, castopc]
3706 unsigned OpNum = 0;
3707 Value *Op;
3708 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
3709 OpNum+2 != Record.size())
3710 return error("Invalid record");
3711
3712 Type *ResTy = getTypeByID(Record[OpNum]);
3713 int Opc = getDecodedCastOpcode(Record[OpNum + 1]);
3714 if (Opc == -1 || !ResTy)
3715 return error("Invalid record");
3716 Instruction *Temp = nullptr;
3717 if ((I = UpgradeBitCastInst(Opc, Op, ResTy, Temp))) {
3718 if (Temp) {
3719 InstructionList.push_back(Temp);
3720 CurBB->getInstList().push_back(Temp);
3721 }
3722 } else {
3723 auto CastOp = (Instruction::CastOps)Opc;
3724 if (!CastInst::castIsValid(CastOp, Op, ResTy))
3725 return error("Invalid cast");
3726 I = CastInst::Create(CastOp, Op, ResTy);
3727 }
3728 InstructionList.push_back(I);
3729 break;
3730 }
3731 case bitc::FUNC_CODE_INST_INBOUNDS_GEP_OLD:
3732 case bitc::FUNC_CODE_INST_GEP_OLD:
3733 case bitc::FUNC_CODE_INST_GEP: { // GEP: type, [n x operands]
3734 unsigned OpNum = 0;
3735
3736 Type *Ty;
3737 bool InBounds;
3738
3739 if (BitCode == bitc::FUNC_CODE_INST_GEP) {
3740 InBounds = Record[OpNum++];
3741 Ty = getTypeByID(Record[OpNum++]);
3742 } else {
3743 InBounds = BitCode == bitc::FUNC_CODE_INST_INBOUNDS_GEP_OLD;
3744 Ty = nullptr;
3745 }
3746
3747 Value *BasePtr;
3748 if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr))
3749 return error("Invalid record");
3750
3751 if (!Ty)
3752 Ty = cast<PointerType>(BasePtr->getType()->getScalarType())
3753 ->getElementType();
3754 else if (Ty !=
3755 cast<PointerType>(BasePtr->getType()->getScalarType())
3756 ->getElementType())
3757 return error(
3758 "Explicit gep type does not match pointee type of pointer operand");
3759
3760 SmallVector<Value*, 16> GEPIdx;
3761 while (OpNum != Record.size()) {
3762 Value *Op;
3763 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
3764 return error("Invalid record");
3765 GEPIdx.push_back(Op);
3766 }
3767
3768 I = GetElementPtrInst::Create(Ty, BasePtr, GEPIdx);
3769
3770 InstructionList.push_back(I);
3771 if (InBounds)
3772 cast<GetElementPtrInst>(I)->setIsInBounds(true);
3773 break;
3774 }
3775
3776 case bitc::FUNC_CODE_INST_EXTRACTVAL: {
3777 // EXTRACTVAL: [opty, opval, n x indices]
3778 unsigned OpNum = 0;
3779 Value *Agg;
3780 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
3781 return error("Invalid record");
3782
3783 unsigned RecSize = Record.size();
3784 if (OpNum == RecSize)
3785 return error("EXTRACTVAL: Invalid instruction with 0 indices");
3786
3787 SmallVector<unsigned, 4> EXTRACTVALIdx;
3788 Type *CurTy = Agg->getType();
3789 for (; OpNum != RecSize; ++OpNum) {
3790 bool IsArray = CurTy->isArrayTy();
3791 bool IsStruct = CurTy->isStructTy();
3792 uint64_t Index = Record[OpNum];
3793
3794 if (!IsStruct && !IsArray)
3795 return error("EXTRACTVAL: Invalid type");
3796 if ((unsigned)Index != Index)
3797 return error("Invalid value");
3798 if (IsStruct && Index >= CurTy->getStructNumElements())
3799 return error("EXTRACTVAL: Invalid struct index");
3800 if (IsArray && Index >= CurTy->getArrayNumElements())
3801 return error("EXTRACTVAL: Invalid array index");
3802 EXTRACTVALIdx.push_back((unsigned)Index);
3803
3804 if (IsStruct)
3805 CurTy = CurTy->getStructElementType(Index);
3806 else
3807 CurTy = CurTy->getArrayElementType();
3808 }
3809
3810 I = ExtractValueInst::Create(Agg, EXTRACTVALIdx);
3811 InstructionList.push_back(I);
3812 break;
3813 }
3814
3815 case bitc::FUNC_CODE_INST_INSERTVAL: {
3816 // INSERTVAL: [opty, opval, opty, opval, n x indices]
3817 unsigned OpNum = 0;
3818 Value *Agg;
3819 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
3820 return error("Invalid record");
3821 Value *Val;
3822 if (getValueTypePair(Record, OpNum, NextValueNo, Val))
3823 return error("Invalid record");
3824
3825 unsigned RecSize = Record.size();
3826 if (OpNum == RecSize)
3827 return error("INSERTVAL: Invalid instruction with 0 indices");
3828
3829 SmallVector<unsigned, 4> INSERTVALIdx;
3830 Type *CurTy = Agg->getType();
3831 for (; OpNum != RecSize; ++OpNum) {
3832 bool IsArray = CurTy->isArrayTy();
3833 bool IsStruct = CurTy->isStructTy();
3834 uint64_t Index = Record[OpNum];
3835
3836 if (!IsStruct && !IsArray)
3837 return error("INSERTVAL: Invalid type");
3838 if ((unsigned)Index != Index)
3839 return error("Invalid value");
3840 if (IsStruct && Index >= CurTy->getStructNumElements())
3841 return error("INSERTVAL: Invalid struct index");
3842 if (IsArray && Index >= CurTy->getArrayNumElements())
3843 return error("INSERTVAL: Invalid array index");
3844
3845 INSERTVALIdx.push_back((unsigned)Index);
3846 if (IsStruct)
3847 CurTy = CurTy->getStructElementType(Index);
3848 else
3849 CurTy = CurTy->getArrayElementType();
3850 }
3851
3852 if (CurTy != Val->getType())
3853 return error("Inserted value type doesn't match aggregate type");
3854
3855 I = InsertValueInst::Create(Agg, Val, INSERTVALIdx);
3856 InstructionList.push_back(I);
3857 break;
3858 }
3859
3860 case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval]
3861 // obsolete form of select
3862 // handles select i1 ... in old bitcode
3863 unsigned OpNum = 0;
3864 Value *TrueVal, *FalseVal, *Cond;
3865 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
3866 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
3867 popValue(Record, OpNum, NextValueNo, Type::getInt1Ty(Context), Cond))
3868 return error("Invalid record");
3869
3870 I = SelectInst::Create(Cond, TrueVal, FalseVal);
3871 InstructionList.push_back(I);
3872 break;
3873 }
3874
3875 case bitc::FUNC_CODE_INST_VSELECT: {// VSELECT: [ty,opval,opval,predty,pred]
3876 // new form of select
3877 // handles select i1 or select [N x i1]
3878 unsigned OpNum = 0;
3879 Value *TrueVal, *FalseVal, *Cond;
3880 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
3881 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
3882 getValueTypePair(Record, OpNum, NextValueNo, Cond))
3883 return error("Invalid record");
3884
3885 // select condition can be either i1 or [N x i1]
3886 if (VectorType* vector_type =
3887 dyn_cast<VectorType>(Cond->getType())) {
3888 // expect <n x i1>
3889 if (vector_type->getElementType() != Type::getInt1Ty(Context))
3890 return error("Invalid type for value");
3891 } else {
3892 // expect i1
3893 if (Cond->getType() != Type::getInt1Ty(Context))
3894 return error("Invalid type for value");
3895 }
3896
3897 I = SelectInst::Create(Cond, TrueVal, FalseVal);
3898 InstructionList.push_back(I);
3899 if (OpNum < Record.size() && isa<FPMathOperator>(I)) {
3900 FastMathFlags FMF = getDecodedFastMathFlags(Record[OpNum]);
3901 if (FMF.any())
3902 I->setFastMathFlags(FMF);
3903 }
3904 break;
3905 }
3906
3907 case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval]
3908 unsigned OpNum = 0;
3909 Value *Vec, *Idx;
3910 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
3911 getValueTypePair(Record, OpNum, NextValueNo, Idx))
3912 return error("Invalid record");
3913 if (!Vec->getType()->isVectorTy())
3914 return error("Invalid type for value");
3915 I = ExtractElementInst::Create(Vec, Idx);
3916 InstructionList.push_back(I);
3917 break;
3918 }
3919
3920 case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval]
3921 unsigned OpNum = 0;
3922 Value *Vec, *Elt, *Idx;
3923 if (getValueTypePair(Record, OpNum, NextValueNo, Vec))
3924 return error("Invalid record");
3925 if (!Vec->getType()->isVectorTy())
3926 return error("Invalid type for value");
3927 if (popValue(Record, OpNum, NextValueNo,
3928 cast<VectorType>(Vec->getType())->getElementType(), Elt) ||
3929 getValueTypePair(Record, OpNum, NextValueNo, Idx))
3930 return error("Invalid record");
3931 I = InsertElementInst::Create(Vec, Elt, Idx);
3932 InstructionList.push_back(I);
3933 break;
3934 }
3935
3936 case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval]
3937 unsigned OpNum = 0;
3938 Value *Vec1, *Vec2, *Mask;
3939 if (getValueTypePair(Record, OpNum, NextValueNo, Vec1) ||
3940 popValue(Record, OpNum, NextValueNo, Vec1->getType(), Vec2))
3941 return error("Invalid record");
3942
3943 if (getValueTypePair(Record, OpNum, NextValueNo, Mask))
3944 return error("Invalid record");
3945 if (!Vec1->getType()->isVectorTy() || !Vec2->getType()->isVectorTy())
3946 return error("Invalid type for value");
3947 I = new ShuffleVectorInst(Vec1, Vec2, Mask);
3948 InstructionList.push_back(I);
3949 break;
3950 }
3951
3952 case bitc::FUNC_CODE_INST_CMP: // CMP: [opty, opval, opval, pred]
3953 // Old form of ICmp/FCmp returning bool
3954 // Existed to differentiate between icmp/fcmp and vicmp/vfcmp which were
3955 // both legal on vectors but had different behaviour.
3956 case bitc::FUNC_CODE_INST_CMP2: { // CMP2: [opty, opval, opval, pred]
3957 // FCmp/ICmp returning bool or vector of bool
3958
3959 unsigned OpNum = 0;
3960 Value *LHS, *RHS;
3961 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
3962 popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS))
3963 return error("Invalid record");
3964
3965 unsigned PredVal = Record[OpNum];
3966 bool IsFP = LHS->getType()->isFPOrFPVectorTy();
3967 FastMathFlags FMF;
3968 if (IsFP && Record.size() > OpNum+1)
3969 FMF = getDecodedFastMathFlags(Record[++OpNum]);
3970
3971 if (OpNum+1 != Record.size())
3972 return error("Invalid record");
3973
3974 if (LHS->getType()->isFPOrFPVectorTy())
3975 I = new FCmpInst((FCmpInst::Predicate)PredVal, LHS, RHS);
3976 else
3977 I = new ICmpInst((ICmpInst::Predicate)PredVal, LHS, RHS);
3978
3979 if (FMF.any())
3980 I->setFastMathFlags(FMF);
3981 InstructionList.push_back(I);
3982 break;
3983 }
3984
3985 case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>]
3986 {
3987 unsigned Size = Record.size();
3988 if (Size == 0) {
3989 I = ReturnInst::Create(Context);
3990 InstructionList.push_back(I);
3991 break;
3992 }
3993
3994 unsigned OpNum = 0;
3995 Value *Op = nullptr;
3996 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
3997 return error("Invalid record");
3998 if (OpNum != Record.size())
3999 return error("Invalid record");
4000
4001 I = ReturnInst::Create(Context, Op);
4002 InstructionList.push_back(I);
4003 break;
4004 }
4005 case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#]
4006 if (Record.size() != 1 && Record.size() != 3)
4007 return error("Invalid record");
4008 BasicBlock *TrueDest = getBasicBlock(Record[0]);
4009 if (!TrueDest)
4010 return error("Invalid record");
4011
4012 if (Record.size() == 1) {
4013 I = BranchInst::Create(TrueDest);
4014 InstructionList.push_back(I);
4015 }
4016 else {
4017 BasicBlock *FalseDest = getBasicBlock(Record[1]);
4018 Value *Cond = getValue(Record, 2, NextValueNo,
4019 Type::getInt1Ty(Context));
4020 if (!FalseDest || !Cond)
4021 return error("Invalid record");
4022 I = BranchInst::Create(TrueDest, FalseDest, Cond);
4023 InstructionList.push_back(I);
4024 }
4025 break;
4026 }
4027 case bitc::FUNC_CODE_INST_CLEANUPRET: { // CLEANUPRET: [val] or [val,bb#]
4028 if (Record.size() != 1 && Record.size() != 2)
4029 return error("Invalid record");
4030 unsigned Idx = 0;
4031 Value *CleanupPad =
4032 getValue(Record, Idx++, NextValueNo, Type::getTokenTy(Context));
4033 if (!CleanupPad)
4034 return error("Invalid record");
4035 BasicBlock *UnwindDest = nullptr;
4036 if (Record.size() == 2) {
4037 UnwindDest = getBasicBlock(Record[Idx++]);
4038 if (!UnwindDest)
4039 return error("Invalid record");
4040 }
4041
4042 I = CleanupReturnInst::Create(CleanupPad, UnwindDest);
4043 InstructionList.push_back(I);
4044 break;
4045 }
4046 case bitc::FUNC_CODE_INST_CATCHRET: { // CATCHRET: [val,bb#]
4047 if (Record.size() != 2)
4048 return error("Invalid record");
4049 unsigned Idx = 0;
4050 Value *CatchPad =
4051 getValue(Record, Idx++, NextValueNo, Type::getTokenTy(Context));
4052 if (!CatchPad)
4053 return error("Invalid record");
4054 BasicBlock *BB = getBasicBlock(Record[Idx++]);
4055 if (!BB)
4056 return error("Invalid record");
4057
4058 I = CatchReturnInst::Create(CatchPad, BB);
4059 InstructionList.push_back(I);
4060 break;
4061 }
4062 case bitc::FUNC_CODE_INST_CATCHSWITCH: { // CATCHSWITCH: [tok,num,(bb)*,bb?]
4063 // We must have, at minimum, the outer scope and the number of arguments.
4064 if (Record.size() < 2)
4065 return error("Invalid record");
4066
4067 unsigned Idx = 0;
4068
4069 Value *ParentPad =
4070 getValue(Record, Idx++, NextValueNo, Type::getTokenTy(Context));
4071
4072 unsigned NumHandlers = Record[Idx++];
4073
4074 SmallVector<BasicBlock *, 2> Handlers;
4075 for (unsigned Op = 0; Op != NumHandlers; ++Op) {
4076 BasicBlock *BB = getBasicBlock(Record[Idx++]);
4077 if (!BB)
4078 return error("Invalid record");
4079 Handlers.push_back(BB);
4080 }
4081
4082 BasicBlock *UnwindDest = nullptr;
4083 if (Idx + 1 == Record.size()) {
4084 UnwindDest = getBasicBlock(Record[Idx++]);
4085 if (!UnwindDest)
4086 return error("Invalid record");
4087 }
4088
4089 if (Record.size() != Idx)
4090 return error("Invalid record");
4091
4092 auto *CatchSwitch =
4093 CatchSwitchInst::Create(ParentPad, UnwindDest, NumHandlers);
4094 for (BasicBlock *Handler : Handlers)
4095 CatchSwitch->addHandler(Handler);
4096 I = CatchSwitch;
4097 InstructionList.push_back(I);
4098 break;
4099 }
4100 case bitc::FUNC_CODE_INST_CATCHPAD:
4101 case bitc::FUNC_CODE_INST_CLEANUPPAD: { // [tok,num,(ty,val)*]
4102 // We must have, at minimum, the outer scope and the number of arguments.
4103 if (Record.size() < 2)
4104 return error("Invalid record");
4105
4106 unsigned Idx = 0;
4107
4108 Value *ParentPad =
4109 getValue(Record, Idx++, NextValueNo, Type::getTokenTy(Context));
4110
4111 unsigned NumArgOperands = Record[Idx++];
4112
4113 SmallVector<Value *, 2> Args;
4114 for (unsigned Op = 0; Op != NumArgOperands; ++Op) {
4115 Value *Val;
4116 if (getValueTypePair(Record, Idx, NextValueNo, Val))
4117 return error("Invalid record");
4118 Args.push_back(Val);
4119 }
4120
4121 if (Record.size() != Idx)
4122 return error("Invalid record");
4123
4124 if (BitCode == bitc::FUNC_CODE_INST_CLEANUPPAD)
4125 I = CleanupPadInst::Create(ParentPad, Args);
4126 else
4127 I = CatchPadInst::Create(ParentPad, Args);
4128 InstructionList.push_back(I);
4129 break;
4130 }
4131 case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, op0, op1, ...]
4132 // Check magic
4133 if ((Record[0] >> 16) == SWITCH_INST_MAGIC) {
4134 // "New" SwitchInst format with case ranges. The changes to write this
4135 // format were reverted but we still recognize bitcode that uses it.
4136 // Hopefully someday we will have support for case ranges and can use
4137 // this format again.
4138
4139 Type *OpTy = getTypeByID(Record[1]);
4140 unsigned ValueBitWidth = cast<IntegerType>(OpTy)->getBitWidth();
4141
4142 Value *Cond = getValue(Record, 2, NextValueNo, OpTy);
4143 BasicBlock *Default = getBasicBlock(Record[3]);
4144 if (!OpTy || !Cond || !Default)
4145 return error("Invalid record");
4146
4147 unsigned NumCases = Record[4];
4148
4149 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
4150 InstructionList.push_back(SI);
4151
4152 unsigned CurIdx = 5;
4153 for (unsigned i = 0; i != NumCases; ++i) {
4154 SmallVector<ConstantInt*, 1> CaseVals;
4155 unsigned NumItems = Record[CurIdx++];
4156 for (unsigned ci = 0; ci != NumItems; ++ci) {
4157 bool isSingleNumber = Record[CurIdx++];
4158
4159 APInt Low;
4160 unsigned ActiveWords = 1;
4161 if (ValueBitWidth > 64)
4162 ActiveWords = Record[CurIdx++];
4163 Low = readWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords),
4164 ValueBitWidth);
4165 CurIdx += ActiveWords;
4166
4167 if (!isSingleNumber) {
4168 ActiveWords = 1;
4169 if (ValueBitWidth > 64)
4170 ActiveWords = Record[CurIdx++];
4171 APInt High = readWideAPInt(
4172 makeArrayRef(&Record[CurIdx], ActiveWords), ValueBitWidth);
4173 CurIdx += ActiveWords;
4174
4175 // FIXME: It is not clear whether values in the range should be
4176 // compared as signed or unsigned values. The partially
4177 // implemented changes that used this format in the past used
4178 // unsigned comparisons.
4179 for ( ; Low.ule(High); ++Low)
4180 CaseVals.push_back(ConstantInt::get(Context, Low));
4181 } else
4182 CaseVals.push_back(ConstantInt::get(Context, Low));
4183 }
4184 BasicBlock *DestBB = getBasicBlock(Record[CurIdx++]);
4185 for (SmallVector<ConstantInt*, 1>::iterator cvi = CaseVals.begin(),
4186 cve = CaseVals.end(); cvi != cve; ++cvi)
4187 SI->addCase(*cvi, DestBB);
4188 }
4189 I = SI;
4190 break;
4191 }
4192
4193 // Old SwitchInst format without case ranges.
4194
4195 if (Record.size() < 3 || (Record.size() & 1) == 0)
4196 return error("Invalid record");
4197 Type *OpTy = getTypeByID(Record[0]);
4198 Value *Cond = getValue(Record, 1, NextValueNo, OpTy);
4199 BasicBlock *Default = getBasicBlock(Record[2]);
4200 if (!OpTy || !Cond || !Default)
4201 return error("Invalid record");
4202 unsigned NumCases = (Record.size()-3)/2;
4203 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
4204 InstructionList.push_back(SI);
4205 for (unsigned i = 0, e = NumCases; i != e; ++i) {
4206 ConstantInt *CaseVal =
4207 dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy));
4208 BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]);
4209 if (!CaseVal || !DestBB) {
4210 delete SI;
4211 return error("Invalid record");
4212 }
4213 SI->addCase(CaseVal, DestBB);
4214 }
4215 I = SI;
4216 break;
4217 }
4218 case bitc::FUNC_CODE_INST_INDIRECTBR: { // INDIRECTBR: [opty, op0, op1, ...]
4219 if (Record.size() < 2)
4220 return error("Invalid record");
4221 Type *OpTy = getTypeByID(Record[0]);
4222 Value *Address = getValue(Record, 1, NextValueNo, OpTy);
4223 if (!OpTy || !Address)
4224 return error("Invalid record");
4225 unsigned NumDests = Record.size()-2;
4226 IndirectBrInst *IBI = IndirectBrInst::Create(Address, NumDests);
4227 InstructionList.push_back(IBI);
4228 for (unsigned i = 0, e = NumDests; i != e; ++i) {
4229 if (BasicBlock *DestBB = getBasicBlock(Record[2+i])) {
4230 IBI->addDestination(DestBB);
4231 } else {
4232 delete IBI;
4233 return error("Invalid record");
4234 }
4235 }
4236 I = IBI;
4237 break;
4238 }
4239
4240 case bitc::FUNC_CODE_INST_INVOKE: {
4241 // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...]
4242 if (Record.size() < 4)
4243 return error("Invalid record");
4244 unsigned OpNum = 0;
4245 AttributeList PAL = getAttributes(Record[OpNum++]);
4246 unsigned CCInfo = Record[OpNum++];
4247 BasicBlock *NormalBB = getBasicBlock(Record[OpNum++]);
4248 BasicBlock *UnwindBB = getBasicBlock(Record[OpNum++]);
4249
4250 FunctionType *FTy = nullptr;
4251 if (CCInfo >> 13 & 1 &&
4252 !(FTy = dyn_cast<FunctionType>(getTypeByID(Record[OpNum++]))))
4253 return error("Explicit invoke type is not a function type");
4254
4255 Value *Callee;
4256 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
4257 return error("Invalid record");
4258
4259 PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType());
4260 if (!CalleeTy)
4261 return error("Callee is not a pointer");
4262 if (!FTy) {
4263 FTy = dyn_cast<FunctionType>(CalleeTy->getElementType());
4264 if (!FTy)
4265 return error("Callee is not of pointer to function type");
4266 } else if (CalleeTy->getElementType() != FTy)
4267 return error("Explicit invoke type does not match pointee type of "
4268 "callee operand");
4269 if (Record.size() < FTy->getNumParams() + OpNum)
4270 return error("Insufficient operands to call");
4271
4272 SmallVector<Value*, 16> Ops;
4273 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
4274 Ops.push_back(getValue(Record, OpNum, NextValueNo,
4275 FTy->getParamType(i)));
4276 if (!Ops.back())
4277 return error("Invalid record");
4278 }
4279
4280 if (!FTy->isVarArg()) {
4281 if (Record.size() != OpNum)
4282 return error("Invalid record");
4283 } else {
4284 // Read type/value pairs for varargs params.
4285 while (OpNum != Record.size()) {
4286 Value *Op;
4287 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
4288 return error("Invalid record");
4289 Ops.push_back(Op);
4290 }
4291 }
4292
4293 I = InvokeInst::Create(FTy, Callee, NormalBB, UnwindBB, Ops,
4294 OperandBundles);
4295 OperandBundles.clear();
4296 InstructionList.push_back(I);
4297 cast<InvokeInst>(I)->setCallingConv(
4298 static_cast<CallingConv::ID>(CallingConv::MaxID & CCInfo));
4299 cast<InvokeInst>(I)->setAttributes(PAL);
4300 propagateByValTypes(cast<CallBase>(I));
4301
4302 break;
4303 }
4304 case bitc::FUNC_CODE_INST_RESUME: { // RESUME: [opval]
4305 unsigned Idx = 0;
4306 Value *Val = nullptr;
4307 if (getValueTypePair(Record, Idx, NextValueNo, Val))
4308 return error("Invalid record");
4309 I = ResumeInst::Create(Val);
4310 InstructionList.push_back(I);
4311 break;
4312 }
4313 case bitc::FUNC_CODE_INST_CALLBR: {
4314 // CALLBR: [attr, cc, norm, transfs, fty, fnid, args]
4315 unsigned OpNum = 0;
4316 AttributeList PAL = getAttributes(Record[OpNum++]);
4317 unsigned CCInfo = Record[OpNum++];
4318
4319 BasicBlock *DefaultDest = getBasicBlock(Record[OpNum++]);
4320 unsigned NumIndirectDests = Record[OpNum++];
4321 SmallVector<BasicBlock *, 16> IndirectDests;
4322 for (unsigned i = 0, e = NumIndirectDests; i != e; ++i)
4323 IndirectDests.push_back(getBasicBlock(Record[OpNum++]));
4324
4325 FunctionType *FTy = nullptr;
4326 if (CCInfo >> bitc::CALL_EXPLICIT_TYPE & 1 &&
4327 !(FTy = dyn_cast<FunctionType>(getTypeByID(Record[OpNum++]))))
4328 return error("Explicit call type is not a function type");
4329
4330 Value *Callee;
4331 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
4332 return error("Invalid record");
4333
4334 PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());
4335 if (!OpTy)
4336 return error("Callee is not a pointer type");
4337 if (!FTy) {
4338 FTy = dyn_cast<FunctionType>(OpTy->getElementType());
4339 if (!FTy)
4340 return error("Callee is not of pointer to function type");
4341 } else if (OpTy->getElementType() != FTy)
4342 return error("Explicit call type does not match pointee type of "
4343 "callee operand");
4344 if (Record.size() < FTy->getNumParams() + OpNum)
4345 return error("Insufficient operands to call");
4346
4347 SmallVector<Value*, 16> Args;
4348 // Read the fixed params.
4349 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
4350 if (FTy->getParamType(i)->isLabelTy())
4351 Args.push_back(getBasicBlock(Record[OpNum]));
4352 else
4353 Args.push_back(getValue(Record, OpNum, NextValueNo,
4354 FTy->getParamType(i)));
4355 if (!Args.back())
4356 return error("Invalid record");
4357 }
4358
4359 // Read type/value pairs for varargs params.
4360 if (!FTy->isVarArg()) {
4361 if (OpNum != Record.size())
4362 return error("Invalid record");
4363 } else {
4364 while (OpNum != Record.size()) {
4365 Value *Op;
4366 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
4367 return error("Invalid record");
4368 Args.push_back(Op);
4369 }
4370 }
4371
4372 I = CallBrInst::Create(FTy, Callee, DefaultDest, IndirectDests, Args,
4373 OperandBundles);
4374 OperandBundles.clear();
4375 InstructionList.push_back(I);
4376 cast<CallBrInst>(I)->setCallingConv(
4377 static_cast<CallingConv::ID>((0x7ff & CCInfo) >> bitc::CALL_CCONV));
4378 cast<CallBrInst>(I)->setAttributes(PAL);
4379 break;
4380 }
4381 case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE
4382 I = new UnreachableInst(Context);
4383 InstructionList.push_back(I);
4384 break;
4385 case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...]
4386 if (Record.size() < 1 || ((Record.size()-1)&1))
4387 return error("Invalid record");
4388 Type *Ty = getTypeByID(Record[0]);
4389 if (!Ty)
4390 return error("Invalid record");
4391
4392 PHINode *PN = PHINode::Create(Ty, (Record.size()-1)/2);
4393 InstructionList.push_back(PN);
4394
4395 for (unsigned i = 0, e = Record.size()-1; i != e; i += 2) {
4396 Value *V;
4397 // With the new function encoding, it is possible that operands have
4398 // negative IDs (for forward references). Use a signed VBR
4399 // representation to keep the encoding small.
4400 if (UseRelativeIDs)
4401 V = getValueSigned(Record, 1+i, NextValueNo, Ty);
4402 else
4403 V = getValue(Record, 1+i, NextValueNo, Ty);
4404 BasicBlock *BB = getBasicBlock(Record[2+i]);
4405 if (!V || !BB)
4406 return error("Invalid record");
4407 PN->addIncoming(V, BB);
4408 }
4409 I = PN;
4410 break;
4411 }
4412
4413 case bitc::FUNC_CODE_INST_LANDINGPAD:
4414 case bitc::FUNC_CODE_INST_LANDINGPAD_OLD: {
4415 // LANDINGPAD: [ty, val, val, num, (id0,val0 ...)?]
4416 unsigned Idx = 0;
4417 if (BitCode == bitc::FUNC_CODE_INST_LANDINGPAD) {
4418 if (Record.size() < 3)
4419 return error("Invalid record");
4420 } else {
4421 assert(BitCode == bitc::FUNC_CODE_INST_LANDINGPAD_OLD)((BitCode == bitc::FUNC_CODE_INST_LANDINGPAD_OLD) ? static_cast
<void> (0) : __assert_fail ("BitCode == bitc::FUNC_CODE_INST_LANDINGPAD_OLD"
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Bitcode/Reader/BitcodeReader.cpp"
, 4421, __PRETTY_FUNCTION__))
;
4422 if (Record.size() < 4)
4423 return error("Invalid record");
4424 }
4425 Type *Ty = getTypeByID(Record[Idx++]);
4426 if (!Ty)
4427 return error("Invalid record");
4428 if (BitCode == bitc::FUNC_CODE_INST_LANDINGPAD_OLD) {
4429 Value *PersFn = nullptr;
4430 if (getValueTypePair(Record, Idx, NextValueNo, PersFn))
4431 return error("Invalid record");
4432
4433 if (!F->hasPersonalityFn())
4434 F->setPersonalityFn(cast<Constant>(PersFn));
4435 else if (F->getPersonalityFn() != cast<Constant>(PersFn))
4436 return error("Personality function mismatch");
4437 }
4438
4439 bool IsCleanup = !!Record[Idx++];
4440 unsigned NumClauses = Record[Idx++];
4441 LandingPadInst *LP = LandingPadInst::Create(Ty, NumClauses);
4442 LP->setCleanup(IsCleanup);
4443 for (unsigned J = 0; J != NumClauses; ++J) {
4444 LandingPadInst::ClauseType CT =
4445 LandingPadInst::ClauseType(Record[Idx++]); (void)CT;
4446 Value *Val;
4447
4448 if (getValueTypePair(Record, Idx, NextValueNo, Val)) {
4449 delete LP;
4450 return error("Invalid record");
4451 }
4452
4453 assert((CT != LandingPadInst::Catch ||(((CT != LandingPadInst::Catch || !isa<ArrayType>(Val->
getType())) && "Catch clause has a invalid type!") ? static_cast
<void> (0) : __assert_fail ("(CT != LandingPadInst::Catch || !isa<ArrayType>(Val->getType())) && \"Catch clause has a invalid type!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Bitcode/Reader/BitcodeReader.cpp"
, 4455, __PRETTY_FUNCTION__))
4454 !isa<ArrayType>(Val->getType())) &&(((CT != LandingPadInst::Catch || !isa<ArrayType>(Val->
getType())) && "Catch clause has a invalid type!") ? static_cast
<void> (0) : __assert_fail ("(CT != LandingPadInst::Catch || !isa<ArrayType>(Val->getType())) && \"Catch clause has a invalid type!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Bitcode/Reader/BitcodeReader.cpp"
, 4455, __PRETTY_FUNCTION__))
4455 "Catch clause has a invalid type!")(((CT != LandingPadInst::Catch || !isa<ArrayType>(Val->
getType())) && "Catch clause has a invalid type!") ? static_cast
<void> (0) : __assert_fail ("(CT != LandingPadInst::Catch || !isa<ArrayType>(Val->getType())) && \"Catch clause has a invalid type!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Bitcode/Reader/BitcodeReader.cpp"
, 4455, __PRETTY_FUNCTION__))
;
4456 assert((CT != LandingPadInst::Filter ||(((CT != LandingPadInst::Filter || isa<ArrayType>(Val->
getType())) && "Filter clause has invalid type!") ? static_cast
<void> (0) : __assert_fail ("(CT != LandingPadInst::Filter || isa<ArrayType>(Val->getType())) && \"Filter clause has invalid type!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Bitcode/Reader/BitcodeReader.cpp"
, 4458, __PRETTY_FUNCTION__))
4457 isa<ArrayType>(Val->getType())) &&(((CT != LandingPadInst::Filter || isa<ArrayType>(Val->
getType())) && "Filter clause has invalid type!") ? static_cast
<void> (0) : __assert_fail ("(CT != LandingPadInst::Filter || isa<ArrayType>(Val->getType())) && \"Filter clause has invalid type!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Bitcode/Reader/BitcodeReader.cpp"
, 4458, __PRETTY_FUNCTION__))
4458 "Filter clause has invalid type!")(((CT != LandingPadInst::Filter || isa<ArrayType>(Val->
getType())) && "Filter clause has invalid type!") ? static_cast
<void> (0) : __assert_fail ("(CT != LandingPadInst::Filter || isa<ArrayType>(Val->getType())) && \"Filter clause has invalid type!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Bitcode/Reader/BitcodeReader.cpp"
, 4458, __PRETTY_FUNCTION__))
;
4459 LP->addClause(cast<Constant>(Val));
4460 }
4461
4462 I = LP;
4463 InstructionList.push_back(I);
4464 break;
4465 }
4466
4467 case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, opty, op, align]
4468 if (Record.size() != 4)
4469 return error("Invalid record");
4470 uint64_t AlignRecord = Record[3];
4471 const uint64_t InAllocaMask = uint64_t(1) << 5;
4472 const uint64_t ExplicitTypeMask = uint64_t(1) << 6;
4473 const uint64_t SwiftErrorMask = uint64_t(1) << 7;
4474 const uint64_t FlagMask = InAllocaMask | ExplicitTypeMask |
4475 SwiftErrorMask;
4476 bool InAlloca = AlignRecord & InAllocaMask;
4477 bool SwiftError = AlignRecord & SwiftErrorMask;
4478 Type *Ty = getTypeByID(Record[0]);
4479 if ((AlignRecord & ExplicitTypeMask) == 0) {
4480 auto *PTy = dyn_cast_or_null<PointerType>(Ty);
4481 if (!PTy)
4482 return error("Old-style alloca with a non-pointer type");
4483 Ty = PTy->getElementType();
4484 }
4485 Type *OpTy = getTypeByID(Record[1]);
4486 Value *Size = getFnValueByID(Record[2], OpTy);
4487 unsigned Align;
4488 if (Error Err = parseAlignmentValue(AlignRecord & ~FlagMask, Align)) {
4489 return Err;
4490 }
4491 if (!Ty || !Size)
4492 return error("Invalid record");
4493
4494 // FIXME: Make this an optional field.
4495 const DataLayout &DL = TheModule->getDataLayout();
4496 unsigned AS = DL.getAllocaAddrSpace();
4497
4498 AllocaInst *AI = new AllocaInst(Ty, AS, Size, Align);
4499 AI->setUsedWithInAlloca(InAlloca);
4500 AI->setSwiftError(SwiftError);
4501 I = AI;
4502 InstructionList.push_back(I);
4503 break;
4504 }
4505 case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol]
4506 unsigned OpNum = 0;
4507 Value *Op;
4508 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
4509 (OpNum + 2 != Record.size() && OpNum + 3 != Record.size()))
4510 return error("Invalid record");
4511
4512 Type *Ty = nullptr;
4513 if (OpNum + 3 == Record.size())
4514 Ty = getTypeByID(Record[OpNum++]);
4515 if (Error Err = typeCheckLoadStoreInst(Ty, Op->getType()))
4516 return Err;
4517 if (!Ty)
4518 Ty = cast<PointerType>(Op->getType())->getElementType();
4519
4520 unsigned Align;
4521 if (Error Err = parseAlignmentValue(Record[OpNum], Align))
4522 return Err;
4523 I = new LoadInst(Ty, Op, "", Record[OpNum + 1], Align);
4524
4525 InstructionList.push_back(I);
4526 break;
4527 }
4528 case bitc::FUNC_CODE_INST_LOADATOMIC: {
4529 // LOADATOMIC: [opty, op, align, vol, ordering, ssid]
4530 unsigned OpNum = 0;
4531 Value *Op;
4532 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
4533 (OpNum + 4 != Record.size() && OpNum + 5 != Record.size()))
4534 return error("Invalid record");
4535
4536 Type *Ty = nullptr;
4537 if (OpNum + 5 == Record.size())
4538 Ty = getTypeByID(Record[OpNum++]);
4539 if (Error Err = typeCheckLoadStoreInst(Ty, Op->getType()))
4540 return Err;
4541 if (!Ty)
4542 Ty = cast<PointerType>(Op->getType())->getElementType();
4543
4544 AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]);
4545 if (Ordering == AtomicOrdering::NotAtomic ||
4546 Ordering == AtomicOrdering::Release ||
4547 Ordering == AtomicOrdering::AcquireRelease)
4548 return error("Invalid record");
4549 if (Ordering != AtomicOrdering::NotAtomic && Record[OpNum] == 0)
4550 return error("Invalid record");
4551 SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 3]);
4552
4553 unsigned Align;
4554 if (Error Err = parseAlignmentValue(Record[OpNum], Align))
4555 return Err;
4556 I = new LoadInst(Ty, Op, "", Record[OpNum + 1], Align, Ordering, SSID);
4557
4558 InstructionList.push_back(I);
4559 break;
4560 }
4561 case bitc::FUNC_CODE_INST_STORE:
4562 case bitc::FUNC_CODE_INST_STORE_OLD: { // STORE2:[ptrty, ptr, val, align, vol]
4563 unsigned OpNum = 0;
4564 Value *Val, *Ptr;
4565 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
4566 (BitCode == bitc::FUNC_CODE_INST_STORE
4567 ? getValueTypePair(Record, OpNum, NextValueNo, Val)
4568 : popValue(Record, OpNum, NextValueNo,
4569 cast<PointerType>(Ptr->getType())->getElementType(),
4570 Val)) ||
4571 OpNum + 2 != Record.size())
4572 return error("Invalid record");
4573
4574 if (Error Err = typeCheckLoadStoreInst(Val->getType(), Ptr->getType()))
4575 return Err;
4576 unsigned Align;
4577 if (Error Err = parseAlignmentValue(Record[OpNum], Align))
4578 return Err;
4579 I = new StoreInst(Val, Ptr, Record[OpNum+1], Align);
4580 InstructionList.push_back(I);
4581 break;
4582 }
4583 case bitc::FUNC_CODE_INST_STOREATOMIC:
4584 case bitc::FUNC_CODE_INST_STOREATOMIC_OLD: {
4585 // STOREATOMIC: [ptrty, ptr, val, align, vol, ordering, ssid]
4586 unsigned OpNum = 0;
4587 Value *Val, *Ptr;
4588 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
4589 !isa<PointerType>(Ptr->getType()) ||
4590 (BitCode == bitc::FUNC_CODE_INST_STOREATOMIC
4591 ? getValueTypePair(Record, OpNum, NextValueNo, Val)
4592 : popValue(Record, OpNum, NextValueNo,
4593 cast<PointerType>(Ptr->getType())->getElementType(),
4594 Val)) ||
4595 OpNum + 4 != Record.size())
4596 return error("Invalid record");
4597
4598 if (Error Err = typeCheckLoadStoreInst(Val->getType(), Ptr->getType()))
4599 return Err;
4600 AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]);
4601 if (Ordering == AtomicOrdering::NotAtomic ||
4602 Ordering == AtomicOrdering::Acquire ||
4603 Ordering == AtomicOrdering::AcquireRelease)
4604 return error("Invalid record");
4605 SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 3]);
4606 if (Ordering != AtomicOrdering::NotAtomic && Record[OpNum] == 0)
4607 return error("Invalid record");
4608
4609 unsigned Align;
4610 if (Error Err = parseAlignmentValue(Record[OpNum], Align))
4611 return Err;
4612 I = new StoreInst(Val, Ptr, Record[OpNum+1], Align, Ordering, SSID);
4613 InstructionList.push_back(I);
4614 break;
4615 }
4616 case bitc::FUNC_CODE_INST_CMPXCHG_OLD:
4617 case bitc::FUNC_CODE_INST_CMPXCHG: {
4618 // CMPXCHG:[ptrty, ptr, cmp, new, vol, successordering, ssid,
4619 // failureordering?, isweak?]
4620 unsigned OpNum = 0;
4621 Value *Ptr, *Cmp, *New;
4622 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
14
Taking false branch
4623 (BitCode == bitc::FUNC_CODE_INST_CMPXCHG
11
'?' condition is false
4624 ? getValueTypePair(Record, OpNum, NextValueNo, Cmp)
4625 : popValue(Record, OpNum, NextValueNo,
4626 cast<PointerType>(Ptr->getType())->getElementType(),
4627 Cmp)) ||
4628 popValue(Record, OpNum, NextValueNo, Cmp->getType(), New) ||
4629 Record.size() < OpNum + 3 || Record.size() > OpNum + 5)
12
Assuming the condition is false
13
Assuming the condition is false
4630 return error("Invalid record");
4631 AtomicOrdering SuccessOrdering = getDecodedOrdering(Record[OpNum + 1]);
4632 if (SuccessOrdering == AtomicOrdering::NotAtomic ||
15
Taking false branch
4633 SuccessOrdering == AtomicOrdering::Unordered)
4634 return error("Invalid record");
4635 SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 2]);
4636
4637 if (Error Err = typeCheckLoadStoreInst(Cmp->getType(), Ptr->getType()))
16
Taking false branch
4638 return Err;
4639 AtomicOrdering FailureOrdering;
4640 if (Record.size() < 7)
17
Assuming the condition is false
18
Taking false branch
4641 FailureOrdering =
4642 AtomicCmpXchgInst::getStrongestFailureOrdering(SuccessOrdering);
4643 else
4644 FailureOrdering = getDecodedOrdering(Record[OpNum + 3]);
4645
4646 I = new AtomicCmpXchgInst(Ptr, Cmp, New, SuccessOrdering, FailureOrdering,
4647 SSID);
4648 cast<AtomicCmpXchgInst>(I)->setVolatile(Record[OpNum]);
4649
4650 if (Record.size() < 8) {
19
Assuming the condition is true
20
Taking true branch
4651 // Before weak cmpxchgs existed, the instruction simply returned the
4652 // value loaded from memory, so bitcode files from that era will be
4653 // expecting the first component of a modern cmpxchg.
4654 CurBB->getInstList().push_back(I);
21
Called C++ object pointer is null
4655 I = ExtractValueInst::Create(I, 0);
4656 } else {
4657 cast<AtomicCmpXchgInst>(I)->setWeak(Record[OpNum+4]);
4658 }
4659
4660 InstructionList.push_back(I);
4661 break;
4662 }
4663 case bitc::FUNC_CODE_INST_ATOMICRMW: {
4664 // ATOMICRMW:[ptrty, ptr, val, op, vol, ordering, ssid]
4665 unsigned OpNum = 0;
4666 Value *Ptr, *Val;
4667 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
4668 !isa<PointerType>(Ptr->getType()) ||
4669 popValue(Record, OpNum, NextValueNo,
4670 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
4671 OpNum+4 != Record.size())
4672 return error("Invalid record");
4673 AtomicRMWInst::BinOp Operation = getDecodedRMWOperation(Record[OpNum]);
4674 if (Operation < AtomicRMWInst::FIRST_BINOP ||
4675 Operation > AtomicRMWInst::LAST_BINOP)
4676 return error("Invalid record");
4677 AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]);
4678 if (Ordering == AtomicOrdering::NotAtomic ||
4679 Ordering == AtomicOrdering::Unordered)
4680 return error("Invalid record");
4681 SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 3]);
4682 I = new AtomicRMWInst(Operation, Ptr, Val, Ordering, SSID);
4683 cast<AtomicRMWInst>(I)->setVolatile(Record[OpNum+1]);
4684 InstructionList.push_back(I);
4685 break;
4686 }
4687 case bitc::FUNC_CODE_INST_FENCE: { // FENCE:[ordering, ssid]
4688 if (2 != Record.size())
4689 return error("Invalid record");
4690 AtomicOrdering Ordering = getDecodedOrdering(Record[0]);
4691 if (Ordering == AtomicOrdering::NotAtomic ||
4692 Ordering == AtomicOrdering::Unordered ||
4693 Ordering == AtomicOrdering::Monotonic)
4694 return error("Invalid record");
4695 SyncScope::ID SSID = getDecodedSyncScopeID(Record[1]);
4696 I = new FenceInst(Context, Ordering, SSID);
4697 InstructionList.push_back(I);
4698 break;
4699 }
4700 case bitc::FUNC_CODE_INST_CALL: {
4701 // CALL: [paramattrs, cc, fmf, fnty, fnid, arg0, arg1...]
4702 if (Record.size() < 3)
4703 return error("Invalid record");
4704
4705 unsigned OpNum = 0;
4706 AttributeList PAL = getAttributes(Record[OpNum++]);
4707 unsigned CCInfo = Record[OpNum++];
4708
4709 FastMathFlags FMF;
4710 if ((CCInfo >> bitc::CALL_FMF) & 1) {
4711 FMF = getDecodedFastMathFlags(Record[OpNum++]);
4712 if (!FMF.any())
4713 return error("Fast math flags indicator set for call with no FMF");
4714 }
4715
4716 FunctionType *FTy = nullptr;
4717 if (CCInfo >> bitc::CALL_EXPLICIT_TYPE & 1 &&
4718 !(FTy = dyn_cast<FunctionType>(getTypeByID(Record[OpNum++]))))
4719 return error("Explicit call type is not a function type");
4720
4721 Value *Callee;
4722 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
4723 return error("Invalid record");
4724
4725 PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());
4726 if (!OpTy)
4727 return error("Callee is not a pointer type");
4728 if (!FTy) {
4729 FTy = dyn_cast<FunctionType>(OpTy->getElementType());
4730 if (!FTy)
4731 return error("Callee is not of pointer to function type");
4732 } else if (OpTy->getElementType() != FTy)
4733 return error("Explicit call type does not match pointee type of "
4734 "callee operand");
4735 if (Record.size() < FTy->getNumParams() + OpNum)
4736 return error("Insufficient operands to call");
4737
4738 SmallVector<Value*, 16> Args;
4739 // Read the fixed params.
4740 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
4741 if (FTy->getParamType(i)->isLabelTy())
4742 Args.push_back(getBasicBlock(Record[OpNum]));
4743 else
4744 Args.push_back(getValue(Record, OpNum, NextValueNo,
4745 FTy->getParamType(i)));
4746 if (!Args.back())
4747 return error("Invalid record");
4748 }
4749
4750 // Read type/value pairs for varargs params.
4751 if (!FTy->isVarArg()) {
4752 if (OpNum != Record.size())
4753 return error("Invalid record");
4754 } else {
4755 while (OpNum != Record.size()) {
4756 Value *Op;
4757 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
4758 return error("Invalid record");
4759 Args.push_back(Op);
4760 }
4761 }
4762
4763 I = CallInst::Create(FTy, Callee, Args, OperandBundles);
4764 OperandBundles.clear();
4765 InstructionList.push_back(I);
4766 cast<CallInst>(I)->setCallingConv(
4767 static_cast<CallingConv::ID>((0x7ff & CCInfo) >> bitc::CALL_CCONV));
4768 CallInst::TailCallKind TCK = CallInst::TCK_None;
4769 if (CCInfo & 1 << bitc::CALL_TAIL)
4770 TCK = CallInst::TCK_Tail;
4771 if (CCInfo & (1 << bitc::CALL_MUSTTAIL))
4772 TCK = CallInst::TCK_MustTail;
4773 if (CCInfo & (1 << bitc::CALL_NOTAIL))
4774 TCK = CallInst::TCK_NoTail;
4775 cast<CallInst>(I)->setTailCallKind(TCK);
4776 cast<CallInst>(I)->setAttributes(PAL);
4777 propagateByValTypes(cast<CallBase>(I));
4778 if (FMF.any()) {
4779 if (!isa<FPMathOperator>(I))
4780 return error("Fast-math-flags specified for call without "
4781 "floating-point scalar or vector return type");
4782 I->setFastMathFlags(FMF);
4783 }
4784 break;
4785 }
4786 case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty]
4787 if (Record.size() < 3)
4788 return error("Invalid record");
4789 Type *OpTy = getTypeByID(Record[0]);
4790 Value *Op = getValue(Record, 1, NextValueNo, OpTy);
4791 Type *ResTy = getTypeByID(Record[2]);
4792 if (!OpTy || !Op || !ResTy)
4793 return error("Invalid record");
4794 I = new VAArgInst(Op, ResTy);
4795 InstructionList.push_back(I);
4796 break;
4797 }
4798
4799 case bitc::FUNC_CODE_OPERAND_BUNDLE: {
4800 // A call or an invoke can be optionally prefixed with some variable
4801 // number of operand bundle blocks. These blocks are read into
4802 // OperandBundles and consumed at the next call or invoke instruction.
4803
4804 if (Record.size() < 1 || Record[0] >= BundleTags.size())
4805 return error("Invalid record");
4806
4807 std::vector<Value *> Inputs;
4808
4809 unsigned OpNum = 1;
4810 while (OpNum != Record.size()) {
4811 Value *Op;
4812 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
4813 return error("Invalid record");
4814 Inputs.push_back(Op);
4815 }
4816
4817 OperandBundles.emplace_back(BundleTags[Record[0]], std::move(Inputs));
4818 continue;
4819 }
4820 }
4821
4822 // Add instruction to end of current BB. If there is no current BB, reject
4823 // this file.
4824 if (!CurBB) {
4825 I->deleteValue();
4826 return error("Invalid instruction with no BB");
4827 }
4828 if (!OperandBundles.empty()) {
4829 I->deleteValue();
4830 return error("Operand bundles found with no consumer");
4831 }
4832 CurBB->getInstList().push_back(I);
4833
4834 // If this was a terminator instruction, move to the next block.
4835 if (I->isTerminator()) {
4836 ++CurBBNo;
4837 CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : nullptr;
4838 }
4839
4840 // Non-void values get registered in the value table for future use.
4841 if (I && !I->getType()->isVoidTy())
4842 ValueList.assignValue(I, NextValueNo++);
4843 }
4844
4845OutOfRecordLoop:
4846
4847 if (!OperandBundles.empty())
4848 return error("Operand bundles found with no consumer");
4849
4850 // Check the function list for unresolved values.
4851 if (Argument *A = dyn_cast<Argument>(ValueList.back())) {
4852 if (!A->getParent()) {
4853 // We found at least one unresolved value. Nuke them all to avoid leaks.
4854 for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){
4855 if ((A = dyn_cast_or_null<Argument>(ValueList[i])) && !A->getParent()) {
4856 A->replaceAllUsesWith(UndefValue::get(A->getType()));
4857 delete A;
4858 }
4859 }
4860 return error("Never resolved value found in function");
4861 }
4862 }
4863
4864 // Unexpected unresolved metadata about to be dropped.
4865 if (MDLoader->hasFwdRefs())
4866 return error("Invalid function metadata: outgoing forward refs");
4867
4868 // Trim the value list down to the size it was before we parsed this function.
4869 ValueList.shrinkTo(ModuleValueListSize);
4870 MDLoader->shrinkTo(ModuleMDLoaderSize);
4871 std::vector<BasicBlock*>().swap(FunctionBBs);
4872 return Error::success();
4873}
4874
4875/// Find the function body in the bitcode stream
4876Error BitcodeReader::findFunctionInStream(
4877 Function *F,
4878 DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator) {
4879 while (DeferredFunctionInfoIterator->second == 0) {
4880 // This is the fallback handling for the old format bitcode that
4881 // didn't contain the function index in the VST, or when we have
4882 // an anonymous function which would not have a VST entry.
4883 // Assert that we have one of those two cases.
4884 assert(VSTOffset == 0 || !F->hasName())((VSTOffset == 0 || !F->hasName()) ? static_cast<void>
(0) : __assert_fail ("VSTOffset == 0 || !F->hasName()", "/build/llvm-toolchain-snapshot-9~svn362543/lib/Bitcode/Reader/BitcodeReader.cpp"
, 4884, __PRETTY_FUNCTION__))
;
4885 // Parse the next body in the stream and set its position in the
4886 // DeferredFunctionInfo map.
4887 if (Error Err = rememberAndSkipFunctionBodies())
4888 return Err;
4889 }
4890 return Error::success();
4891}
4892
4893SyncScope::ID BitcodeReader::getDecodedSyncScopeID(unsigned Val) {
4894 if (Val == SyncScope::SingleThread || Val == SyncScope::System)
4895 return SyncScope::ID(Val);
4896 if (Val >= SSIDs.size())
4897 return SyncScope::System; // Map unknown synchronization scopes to system.
4898 return SSIDs[Val];
4899}
4900
4901//===----------------------------------------------------------------------===//
4902// GVMaterializer implementation
4903//===----------------------------------------------------------------------===//
4904
4905Error BitcodeReader::materialize(GlobalValue *GV) {
4906 Function *F = dyn_cast<Function>(GV);
4907 // If it's not a function or is already material, ignore the request.
4908 if (!F || !F->isMaterializable())
4909 return Error::success();
4910
4911 DenseMap<Function*, uint64_t>::iterator DFII = DeferredFunctionInfo.find(F);
4912 assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!")((DFII != DeferredFunctionInfo.end() && "Deferred function not found!"
) ? static_cast<void> (0) : __assert_fail ("DFII != DeferredFunctionInfo.end() && \"Deferred function not found!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Bitcode/Reader/BitcodeReader.cpp"
, 4912, __PRETTY_FUNCTION__))
;
4913 // If its position is recorded as 0, its body is somewhere in the stream
4914 // but we haven't seen it yet.
4915 if (DFII->second == 0)
4916 if (Error Err = findFunctionInStream(F, DFII))
4917 return Err;
4918
4919 // Materialize metadata before parsing any function bodies.
4920 if (Error Err = materializeMetadata())
4921 return Err;
4922
4923 // Move the bit stream to the saved position of the deferred function body.
4924 Stream.JumpToBit(DFII->second);
4925
4926 if (Error Err = parseFunctionBody(F))
4927 return Err;
4928 F->setIsMaterializable(false);
4929
4930 if (StripDebugInfo)
4931 stripDebugInfo(*F);
4932
4933 // Upgrade any old intrinsic calls in the function.
4934 for (auto &I : UpgradedIntrinsics) {
4935 for (auto UI = I.first->materialized_user_begin(), UE = I.first->user_end();
4936 UI != UE;) {
4937 User *U = *UI;
4938 ++UI;
4939 if (CallInst *CI = dyn_cast<CallInst>(U))
4940 UpgradeIntrinsicCall(CI, I.second);
4941 }
4942 }
4943
4944 // Update calls to the remangled intrinsics
4945 for (auto &I : RemangledIntrinsics)
4946 for (auto UI = I.first->materialized_user_begin(), UE = I.first->user_end();
4947 UI != UE;)
4948 // Don't expect any other users than call sites
4949 CallSite(*UI++).setCalledFunction(I.second);
4950
4951 // Finish fn->subprogram upgrade for materialized functions.
4952 if (DISubprogram *SP = MDLoader->lookupSubprogramForFunction(F))
4953 F->setSubprogram(SP);
4954
4955 // Check if the TBAA Metadata are valid, otherwise we will need to strip them.
4956 if (!MDLoader->isStrippingTBAA()) {
4957 for (auto &I : instructions(F)) {
4958 MDNode *TBAA = I.getMetadata(LLVMContext::MD_tbaa);
4959 if (!TBAA || TBAAVerifyHelper.visitTBAAMetadata(I, TBAA))
4960 continue;
4961 MDLoader->setStripTBAA(true);
4962 stripTBAA(F->getParent());
4963 }
4964 }
4965
4966 // Bring in any functions that this function forward-referenced via
4967 // blockaddresses.
4968 return materializeForwardReferencedFunctions();
4969}
4970
4971Error BitcodeReader::materializeModule() {
4972 if (Error Err = materializeMetadata())
4973 return Err;
4974
4975 // Promise to materialize all forward references.
4976 WillMaterializeAllForwardRefs = true;
4977
4978 // Iterate over the module, deserializing any functions that are still on
4979 // disk.
4980 for (Function &F : *TheModule) {
4981 if (Error Err = materialize(&F))
4982 return Err;
4983 }
4984 // At this point, if there are any function bodies, parse the rest of
4985 // the bits in the module past the last function block we have recorded
4986 // through either lazy scanning or the VST.
4987 if (LastFunctionBlockBit || NextUnreadBit)
4988 if (Error Err = parseModule(LastFunctionBlockBit > NextUnreadBit
4989 ? LastFunctionBlockBit
4990 : NextUnreadBit))
4991 return Err;
4992
4993 // Check that all block address forward references got resolved (as we
4994 // promised above).
4995 if (!BasicBlockFwdRefs.empty())
4996 return error("Never resolved function from blockaddress");
4997
4998 // Upgrade any intrinsic calls that slipped through (should not happen!) and
4999 // delete the old functions to clean up. We can't do this unless the entire
5000 // module is materialized because there could always be another function body
5001 // with calls to the old function.
5002 for (auto &I : UpgradedIntrinsics) {
5003 for (auto *U : I.first->users()) {
5004 if (CallInst *CI = dyn_cast<CallInst>(U))
5005 UpgradeIntrinsicCall(CI, I.second);
5006 }
5007 if (!I.first->use_empty())
5008 I.first->replaceAllUsesWith(I.second);
5009 I.first->eraseFromParent();
5010 }
5011 UpgradedIntrinsics.clear();
5012 // Do the same for remangled intrinsics
5013 for (auto &I : RemangledIntrinsics) {
5014 I.first->replaceAllUsesWith(I.second);
5015 I.first->eraseFromParent();
5016 }
5017 RemangledIntrinsics.clear();
5018
5019 UpgradeDebugInfo(*TheModule);
5020
5021 UpgradeModuleFlags(*TheModule);
5022
5023 UpgradeRetainReleaseMarker(*TheModule);
5024
5025 return Error::success();
5026}
5027
5028std::vector<StructType *> BitcodeReader::getIdentifiedStructTypes() const {
5029 return IdentifiedStructTypes;
5030}
5031
5032ModuleSummaryIndexBitcodeReader::ModuleSummaryIndexBitcodeReader(
5033 BitstreamCursor Cursor, StringRef Strtab, ModuleSummaryIndex &TheIndex,
5034 StringRef ModulePath, unsigned ModuleId)
5035 : BitcodeReaderBase(std::move(Cursor), Strtab), TheIndex(TheIndex),
5036 ModulePath(ModulePath), ModuleId(ModuleId) {}
5037
5038void ModuleSummaryIndexBitcodeReader::addThisModule() {
5039 TheIndex.addModule(ModulePath, ModuleId);
5040}
5041
5042ModuleSummaryIndex::ModuleInfo *
5043ModuleSummaryIndexBitcodeReader::getThisModule() {
5044 return TheIndex.getModule(ModulePath);
5045}
5046
5047std::pair<ValueInfo, GlobalValue::GUID>
5048ModuleSummaryIndexBitcodeReader::getValueInfoFromValueId(unsigned ValueId) {
5049 auto VGI = ValueIdToValueInfoMap[ValueId];
5050 assert(VGI.first)((VGI.first) ? static_cast<void> (0) : __assert_fail ("VGI.first"
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Bitcode/Reader/BitcodeReader.cpp"
, 5050, __PRETTY_FUNCTION__))
;
5051 return VGI;
5052}
5053
5054void ModuleSummaryIndexBitcodeReader::setValueGUID(
5055 uint64_t ValueID, StringRef ValueName, GlobalValue::LinkageTypes Linkage,
5056 StringRef SourceFileName) {
5057 std::string GlobalId =
5058 GlobalValue::getGlobalIdentifier(ValueName, Linkage, SourceFileName);
5059 auto ValueGUID = GlobalValue::getGUID(GlobalId);
5060 auto OriginalNameID = ValueGUID;
5061 if (GlobalValue::isLocalLinkage(Linkage))
5062 OriginalNameID = GlobalValue::getGUID(ValueName);
5063 if (PrintSummaryGUIDs)
5064 dbgs() << "GUID " << ValueGUID << "(" << OriginalNameID << ") is "
5065 << ValueName << "\n";
5066
5067 // UseStrtab is false for legacy summary formats and value names are
5068 // created on stack. In that case we save the name in a string saver in
5069 // the index so that the value name can be recorded.
5070 ValueIdToValueInfoMap[ValueID] = std::make_pair(
5071 TheIndex.getOrInsertValueInfo(
5072 ValueGUID,
5073 UseStrtab ? ValueName : TheIndex.saveString(ValueName)),
5074 OriginalNameID);
5075}
5076
5077// Specialized value symbol table parser used when reading module index
5078// blocks where we don't actually create global values. The parsed information
5079// is saved in the bitcode reader for use when later parsing summaries.
5080Error ModuleSummaryIndexBitcodeReader::parseValueSymbolTable(
5081 uint64_t Offset,
5082 DenseMap<unsigned, GlobalValue::LinkageTypes> &ValueIdToLinkageMap) {
5083 // With a strtab the VST is not required to parse the summary.
5084 if (UseStrtab)
5085 return Error::success();
5086
5087 assert(Offset > 0 && "Expected non-zero VST offset")((Offset > 0 && "Expected non-zero VST offset") ? static_cast
<void> (0) : __assert_fail ("Offset > 0 && \"Expected non-zero VST offset\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Bitcode/Reader/BitcodeReader.cpp"
, 5087, __PRETTY_FUNCTION__))
;
5088 uint64_t CurrentBit = jumpToValueSymbolTable(Offset, Stream);
5089
5090 if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
5091 return error("Invalid record");
5092
5093 SmallVector<uint64_t, 64> Record;
5094
5095 // Read all the records for this value table.
5096 SmallString<128> ValueName;
5097
5098 while (true) {
5099 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
5100
5101 switch (Entry.Kind) {
5102 case BitstreamEntry::SubBlock: // Handled for us already.
5103 case BitstreamEntry::Error:
5104 return error("Malformed block");
5105 case BitstreamEntry::EndBlock:
5106 // Done parsing VST, jump back to wherever we came from.
5107 Stream.JumpToBit(CurrentBit);
5108 return Error::success();
5109 case BitstreamEntry::Record:
5110 // The interesting case.
5111 break;
5112 }
5113
5114 // Read a record.
5115 Record.clear();
5116 switch (Stream.readRecord(Entry.ID, Record)) {
5117 default: // Default behavior: ignore (e.g. VST_CODE_BBENTRY records).
5118 break;
5119 case bitc::VST_CODE_ENTRY: { // VST_CODE_ENTRY: [valueid, namechar x N]
5120 if (convertToString(Record, 1, ValueName))
5121 return error("Invalid record");
5122 unsigned ValueID = Record[0];
5123 assert(!SourceFileName.empty())((!SourceFileName.empty()) ? static_cast<void> (0) : __assert_fail
("!SourceFileName.empty()", "/build/llvm-toolchain-snapshot-9~svn362543/lib/Bitcode/Reader/BitcodeReader.cpp"
, 5123, __PRETTY_FUNCTION__))
;
5124 auto VLI = ValueIdToLinkageMap.find(ValueID);
5125 assert(VLI != ValueIdToLinkageMap.end() &&((VLI != ValueIdToLinkageMap.end() && "No linkage found for VST entry?"
) ? static_cast<void> (0) : __assert_fail ("VLI != ValueIdToLinkageMap.end() && \"No linkage found for VST entry?\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Bitcode/Reader/BitcodeReader.cpp"
, 5126, __PRETTY_FUNCTION__))
5126 "No linkage found for VST entry?")((VLI != ValueIdToLinkageMap.end() && "No linkage found for VST entry?"
) ? static_cast<void> (0) : __assert_fail ("VLI != ValueIdToLinkageMap.end() && \"No linkage found for VST entry?\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Bitcode/Reader/BitcodeReader.cpp"
, 5126, __PRETTY_FUNCTION__))
;
5127 auto Linkage = VLI->second;
5128 setValueGUID(ValueID, ValueName, Linkage, SourceFileName);
5129 ValueName.clear();
5130 break;
5131 }
5132 case bitc::VST_CODE_FNENTRY: {
5133 // VST_CODE_FNENTRY: [valueid, offset, namechar x N]
5134 if (convertToString(Record, 2, ValueName))
5135 return error("Invalid record");
5136 unsigned ValueID = Record[0];
5137 assert(!SourceFileName.empty())((!SourceFileName.empty()) ? static_cast<void> (0) : __assert_fail
("!SourceFileName.empty()", "/build/llvm-toolchain-snapshot-9~svn362543/lib/Bitcode/Reader/BitcodeReader.cpp"
, 5137, __PRETTY_FUNCTION__))
;
5138 auto VLI = ValueIdToLinkageMap.find(ValueID);
5139 assert(VLI != ValueIdToLinkageMap.end() &&((VLI != ValueIdToLinkageMap.end() && "No linkage found for VST entry?"
) ? static_cast<void> (0) : __assert_fail ("VLI != ValueIdToLinkageMap.end() && \"No linkage found for VST entry?\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Bitcode/Reader/BitcodeReader.cpp"
, 5140, __PRETTY_FUNCTION__))
5140 "No linkage found for VST entry?")((VLI != ValueIdToLinkageMap.end() && "No linkage found for VST entry?"
) ? static_cast<void> (0) : __assert_fail ("VLI != ValueIdToLinkageMap.end() && \"No linkage found for VST entry?\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Bitcode/Reader/BitcodeReader.cpp"
, 5140, __PRETTY_FUNCTION__))
;
5141 auto Linkage = VLI->second;
5142 setValueGUID(ValueID, ValueName, Linkage, SourceFileName);
5143 ValueName.clear();
5144 break;
5145 }
5146 case bitc::VST_CODE_COMBINED_ENTRY: {
5147 // VST_CODE_COMBINED_ENTRY: [valueid, refguid]
5148 unsigned ValueID = Record[0];
5149 GlobalValue::GUID RefGUID = Record[1];
5150 // The "original name", which is the second value of the pair will be
5151 // overriden later by a FS_COMBINED_ORIGINAL_NAME in the combined index.
5152 ValueIdToValueInfoMap[ValueID] =
5153 std::make_pair(TheIndex.getOrInsertValueInfo(RefGUID), RefGUID);
5154 break;
5155 }
5156 }
5157 }
5158}
5159
5160// Parse just the blocks needed for building the index out of the module.
5161// At the end of this routine the module Index is populated with a map
5162// from global value id to GlobalValueSummary objects.
5163Error ModuleSummaryIndexBitcodeReader::parseModule() {
5164 if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
5165 return error("Invalid record");
5166
5167 SmallVector<uint64_t, 64> Record;
5168 DenseMap<unsigned, GlobalValue::LinkageTypes> ValueIdToLinkageMap;
5169 unsigned ValueId = 0;
5170
5171 // Read the index for this module.
5172 while (true) {
5173 BitstreamEntry Entry = Stream.advance();
5174
5175 switch (Entry.Kind) {
5176 case BitstreamEntry::Error:
5177 return error("Malformed block");
5178 case BitstreamEntry::EndBlock:
5179 return Error::success();
5180
5181 case BitstreamEntry::SubBlock:
5182 switch (Entry.ID) {
5183 default: // Skip unknown content.
5184 if (Stream.SkipBlock())
5185 return error("Invalid record");
5186 break;
5187 case bitc::BLOCKINFO_BLOCK_ID:
5188 // Need to parse these to get abbrev ids (e.g. for VST)
5189 if (readBlockInfo())
5190 return error("Malformed block");
5191 break;
5192 case bitc::VALUE_SYMTAB_BLOCK_ID:
5193 // Should have been parsed earlier via VSTOffset, unless there
5194 // is no summary section.
5195 assert(((SeenValueSymbolTable && VSTOffset > 0) ||((((SeenValueSymbolTable && VSTOffset > 0) || !SeenGlobalValSummary
) && "Expected early VST parse via VSTOffset record")
? static_cast<void> (0) : __assert_fail ("((SeenValueSymbolTable && VSTOffset > 0) || !SeenGlobalValSummary) && \"Expected early VST parse via VSTOffset record\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Bitcode/Reader/BitcodeReader.cpp"
, 5197, __PRETTY_FUNCTION__))
5196 !SeenGlobalValSummary) &&((((SeenValueSymbolTable && VSTOffset > 0) || !SeenGlobalValSummary
) && "Expected early VST parse via VSTOffset record")
? static_cast<void> (0) : __assert_fail ("((SeenValueSymbolTable && VSTOffset > 0) || !SeenGlobalValSummary) && \"Expected early VST parse via VSTOffset record\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Bitcode/Reader/BitcodeReader.cpp"
, 5197, __PRETTY_FUNCTION__))
5197 "Expected early VST parse via VSTOffset record")((((SeenValueSymbolTable && VSTOffset > 0) || !SeenGlobalValSummary
) && "Expected early VST parse via VSTOffset record")
? static_cast<void> (0) : __assert_fail ("((SeenValueSymbolTable && VSTOffset > 0) || !SeenGlobalValSummary) && \"Expected early VST parse via VSTOffset record\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Bitcode/Reader/BitcodeReader.cpp"
, 5197, __PRETTY_FUNCTION__))
;
5198 if (Stream.SkipBlock())
5199 return error("Invalid record");
5200 break;
5201 case bitc::GLOBALVAL_SUMMARY_BLOCK_ID:
5202 case bitc::FULL_LTO_GLOBALVAL_SUMMARY_BLOCK_ID:
5203 // Add the module if it is a per-module index (has a source file name).
5204 if (!SourceFileName.empty())
5205 addThisModule();
5206 assert(!SeenValueSymbolTable &&((!SeenValueSymbolTable && "Already read VST when parsing summary block?"
) ? static_cast<void> (0) : __assert_fail ("!SeenValueSymbolTable && \"Already read VST when parsing summary block?\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Bitcode/Reader/BitcodeReader.cpp"
, 5207, __PRETTY_FUNCTION__))
5207 "Already read VST when parsing summary block?")((!SeenValueSymbolTable && "Already read VST when parsing summary block?"
) ? static_cast<void> (0) : __assert_fail ("!SeenValueSymbolTable && \"Already read VST when parsing summary block?\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Bitcode/Reader/BitcodeReader.cpp"
, 5207, __PRETTY_FUNCTION__))
;
5208 // We might not have a VST if there were no values in the
5209 // summary. An empty summary block generated when we are
5210 // performing ThinLTO compiles so we don't later invoke
5211 // the regular LTO process on them.
5212 if (VSTOffset > 0) {
5213 if (Error Err = parseValueSymbolTable(VSTOffset, ValueIdToLinkageMap))
5214 return Err;
5215 SeenValueSymbolTable = true;
5216 }
5217 SeenGlobalValSummary = true;
5218 if (Error Err = parseEntireSummary(Entry.ID))
5219 return Err;
5220 break;
5221 case bitc::MODULE_STRTAB_BLOCK_ID:
5222 if (Error Err = parseModuleStringTable())
5223 return Err;
5224 break;
5225 }
5226 continue;
5227
5228 case BitstreamEntry::Record: {
5229 Record.clear();
5230 auto BitCode = Stream.readRecord(Entry.ID, Record);
5231 switch (BitCode) {
5232 default:
5233 break; // Default behavior, ignore unknown content.
5234 case bitc::MODULE_CODE_VERSION: {
5235 if (Error Err = parseVersionRecord(Record).takeError())
5236 return Err;
5237 break;
5238 }
5239 /// MODULE_CODE_SOURCE_FILENAME: [namechar x N]
5240 case bitc::MODULE_CODE_SOURCE_FILENAME: {
5241 SmallString<128> ValueName;
5242 if (convertToString(Record, 0, ValueName))
5243 return error("Invalid record");
5244 SourceFileName = ValueName.c_str();
5245 break;
5246 }
5247 /// MODULE_CODE_HASH: [5*i32]
5248 case bitc::MODULE_CODE_HASH: {
5249 if (Record.size() != 5)
5250 return error("Invalid hash length " + Twine(Record.size()).str());
5251 auto &Hash = getThisModule()->second.second;
5252 int Pos = 0;
5253 for (auto &Val : Record) {
5254 assert(!(Val >> 32) && "Unexpected high bits set")((!(Val >> 32) && "Unexpected high bits set") ?
static_cast<void> (0) : __assert_fail ("!(Val >> 32) && \"Unexpected high bits set\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Bitcode/Reader/BitcodeReader.cpp"
, 5254, __PRETTY_FUNCTION__))
;
5255 Hash[Pos++] = Val;
5256 }
5257 break;
5258 }
5259 /// MODULE_CODE_VSTOFFSET: [offset]
5260 case bitc::MODULE_CODE_VSTOFFSET:
5261 if (Record.size() < 1)
5262 return error("Invalid record");
5263 // Note that we subtract 1 here because the offset is relative to one
5264 // word before the start of the identification or module block, which
5265 // was historically always the start of the regular bitcode header.
5266 VSTOffset = Record[0] - 1;
5267 break;
5268 // v1 GLOBALVAR: [pointer type, isconst, initid, linkage, ...]
5269 // v1 FUNCTION: [type, callingconv, isproto, linkage, ...]
5270 // v1 ALIAS: [alias type, addrspace, aliasee val#, linkage, ...]
5271 // v2: [strtab offset, strtab size, v1]
5272 case bitc::MODULE_CODE_GLOBALVAR:
5273 case bitc::MODULE_CODE_FUNCTION:
5274 case bitc::MODULE_CODE_ALIAS: {
5275 StringRef Name;
5276 ArrayRef<uint64_t> GVRecord;
5277 std::tie(Name, GVRecord) = readNameFromStrtab(Record);
5278 if (GVRecord.size() <= 3)
5279 return error("Invalid record");
5280 uint64_t RawLinkage = GVRecord[3];
5281 GlobalValue::LinkageTypes Linkage = getDecodedLinkage(RawLinkage);
5282 if (!UseStrtab) {
5283 ValueIdToLinkageMap[ValueId++] = Linkage;
5284 break;
5285 }
5286
5287 setValueGUID(ValueId++, Name, Linkage, SourceFileName);
5288 break;
5289 }
5290 }
5291 }
5292 continue;
5293 }
5294 }
5295}
5296
5297std::vector<ValueInfo>
5298ModuleSummaryIndexBitcodeReader::makeRefList(ArrayRef<uint64_t> Record) {
5299 std::vector<ValueInfo> Ret;
5300 Ret.reserve(Record.size());
5301 for (uint64_t RefValueId : Record)
5302 Ret.push_back(getValueInfoFromValueId(RefValueId).first);
5303 return Ret;
5304}
5305
5306std::vector<FunctionSummary::EdgeTy>
5307ModuleSummaryIndexBitcodeReader::makeCallList(ArrayRef<uint64_t> Record,
5308 bool IsOldProfileFormat,
5309 bool HasProfile, bool HasRelBF) {
5310 std::vector<FunctionSummary::EdgeTy> Ret;
5311 Ret.reserve(Record.size());
5312 for (unsigned I = 0, E = Record.size(); I != E; ++I) {
5313 CalleeInfo::HotnessType Hotness = CalleeInfo::HotnessType::Unknown;
5314 uint64_t RelBF = 0;
5315 ValueInfo Callee = getValueInfoFromValueId(Record[I]).first;
5316 if (IsOldProfileFormat) {
5317 I += 1; // Skip old callsitecount field
5318 if (HasProfile)
5319 I += 1; // Skip old profilecount field
5320 } else if (HasProfile)
5321 Hotness = static_cast<CalleeInfo::HotnessType>(Record[++I]);
5322 else if (HasRelBF)
5323 RelBF = Record[++I];
5324 Ret.push_back(FunctionSummary::EdgeTy{Callee, CalleeInfo(Hotness, RelBF)});
5325 }
5326 return Ret;
5327}
5328
5329static void
5330parseWholeProgramDevirtResolutionByArg(ArrayRef<uint64_t> Record, size_t &Slot,
5331 WholeProgramDevirtResolution &Wpd) {
5332 uint64_t ArgNum = Record[Slot++];
5333 WholeProgramDevirtResolution::ByArg &B =
5334 Wpd.ResByArg[{Record.begin() + Slot, Record.begin() + Slot + ArgNum}];
5335 Slot += ArgNum;
5336
5337 B.TheKind =
5338 static_cast<WholeProgramDevirtResolution::ByArg::Kind>(Record[Slot++]);
5339 B.Info = Record[Slot++];
5340 B.Byte = Record[Slot++];
5341 B.Bit = Record[Slot++];
5342}
5343
5344static void parseWholeProgramDevirtResolution(ArrayRef<uint64_t> Record,
5345 StringRef Strtab, size_t &Slot,
5346 TypeIdSummary &TypeId) {
5347 uint64_t Id = Record[Slot++];
5348 WholeProgramDevirtResolution &Wpd = TypeId.WPDRes[Id];
5349
5350 Wpd.TheKind = static_cast<WholeProgramDevirtResolution::Kind>(Record[Slot++]);
5351 Wpd.SingleImplName = {Strtab.data() + Record[Slot],
5352 static_cast<size_t>(Record[Slot + 1])};
5353 Slot += 2;
5354
5355 uint64_t ResByArgNum = Record[Slot++];
5356 for (uint64_t I = 0; I != ResByArgNum; ++I)
5357 parseWholeProgramDevirtResolutionByArg(Record, Slot, Wpd);
5358}
5359
5360static void parseTypeIdSummaryRecord(ArrayRef<uint64_t> Record,
5361 StringRef Strtab,
5362 ModuleSummaryIndex &TheIndex) {
5363 size_t Slot = 0;
5364 TypeIdSummary &TypeId = TheIndex.getOrInsertTypeIdSummary(
5365 {Strtab.data() + Record[Slot], static_cast<size_t>(Record[Slot + 1])});
5366 Slot += 2;
5367
5368 TypeId.TTRes.TheKind = static_cast<TypeTestResolution::Kind>(Record[Slot++]);
5369 TypeId.TTRes.SizeM1BitWidth = Record[Slot++];
5370 TypeId.TTRes.AlignLog2 = Record[Slot++];
5371 TypeId.TTRes.SizeM1 = Record[Slot++];
5372 TypeId.TTRes.BitMask = Record[Slot++];
5373 TypeId.TTRes.InlineBits = Record[Slot++];
5374
5375 while (Slot < Record.size())
5376 parseWholeProgramDevirtResolution(Record, Strtab, Slot, TypeId);
5377}
5378
5379static void setImmutableRefs(std::vector<ValueInfo> &Refs, unsigned Count) {
5380 // Read-only refs are in the end of the refs list.
5381 for (unsigned RefNo = Refs.size() - Count; RefNo < Refs.size(); ++RefNo)
5382 Refs[RefNo].setReadOnly();
5383}
5384
5385// Eagerly parse the entire summary block. This populates the GlobalValueSummary
5386// objects in the index.
5387Error ModuleSummaryIndexBitcodeReader::parseEntireSummary(unsigned ID) {
5388 if (Stream.EnterSubBlock(ID))
5389 return error("Invalid record");
5390 SmallVector<uint64_t, 64> Record;
5391
5392 // Parse version
5393 {
5394 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
5395 if (Entry.Kind != BitstreamEntry::Record)
5396 return error("Invalid Summary Block: record for version expected");
5397 if (Stream.readRecord(Entry.ID, Record) != bitc::FS_VERSION)
5398 return error("Invalid Summary Block: version expected");
5399 }
5400 const uint64_t Version = Record[0];
5401 const bool IsOldProfileFormat = Version == 1;
5402 if (Version < 1 || Version > 6)
5403 return error("Invalid summary version " + Twine(Version) +
5404 ". Version should be in the range [1-6].");
5405 Record.clear();
5406
5407 // Keep around the last seen summary to be used when we see an optional
5408 // "OriginalName" attachement.
5409 GlobalValueSummary *LastSeenSummary = nullptr;
5410 GlobalValue::GUID LastSeenGUID = 0;
5411
5412 // We can expect to see any number of type ID information records before
5413 // each function summary records; these variables store the information
5414 // collected so far so that it can be used to create the summary object.
5415 std::vector<GlobalValue::GUID> PendingTypeTests;
5416 std::vector<FunctionSummary::VFuncId> PendingTypeTestAssumeVCalls,
5417 PendingTypeCheckedLoadVCalls;
5418 std::vector<FunctionSummary::ConstVCall> PendingTypeTestAssumeConstVCalls,
5419 PendingTypeCheckedLoadConstVCalls;
5420
5421 while (true) {
5422 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
5423
5424 switch (Entry.Kind) {
5425 case BitstreamEntry::SubBlock: // Handled for us already.
5426 case BitstreamEntry::Error:
5427 return error("Malformed block");
5428 case BitstreamEntry::EndBlock:
5429 return Error::success();
5430 case BitstreamEntry::Record:
5431 // The interesting case.
5432 break;
5433 }
5434
5435 // Read a record. The record format depends on whether this
5436 // is a per-module index or a combined index file. In the per-module
5437 // case the records contain the associated value's ID for correlation
5438 // with VST entries. In the combined index the correlation is done
5439 // via the bitcode offset of the summary records (which were saved
5440 // in the combined index VST entries). The records also contain
5441 // information used for ThinLTO renaming and importing.
5442 Record.clear();
5443 auto BitCode = Stream.readRecord(Entry.ID, Record);
5444 switch (BitCode) {
5445 default: // Default behavior: ignore.
5446 break;
5447 case bitc::FS_FLAGS: { // [flags]
5448 uint64_t Flags = Record[0];
5449 // Scan flags.
5450 assert(Flags <= 0x1f && "Unexpected bits in flag")((Flags <= 0x1f && "Unexpected bits in flag") ? static_cast
<void> (0) : __assert_fail ("Flags <= 0x1f && \"Unexpected bits in flag\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Bitcode/Reader/BitcodeReader.cpp"
, 5450, __PRETTY_FUNCTION__))
;
5451
5452 // 1 bit: WithGlobalValueDeadStripping flag.
5453 // Set on combined index only.
5454 if (Flags & 0x1)
5455 TheIndex.setWithGlobalValueDeadStripping();
5456 // 1 bit: SkipModuleByDistributedBackend flag.
5457 // Set on combined index only.
5458 if (Flags & 0x2)
5459 TheIndex.setSkipModuleByDistributedBackend();
5460 // 1 bit: HasSyntheticEntryCounts flag.
5461 // Set on combined index only.
5462 if (Flags & 0x4)
5463 TheIndex.setHasSyntheticEntryCounts();
5464 // 1 bit: DisableSplitLTOUnit flag.
5465 // Set on per module indexes. It is up to the client to validate
5466 // the consistency of this flag across modules being linked.
5467 if (Flags & 0x8)
5468 TheIndex.setEnableSplitLTOUnit();
5469 // 1 bit: PartiallySplitLTOUnits flag.
5470 // Set on combined index only.
5471 if (Flags & 0x10)
5472 TheIndex.setPartiallySplitLTOUnits();
5473 break;
5474 }
5475 case bitc::FS_VALUE_GUID: { // [valueid, refguid]
5476 uint64_t ValueID = Record[0];
5477 GlobalValue::GUID RefGUID = Record[1];
5478 ValueIdToValueInfoMap[ValueID] =
5479 std::make_pair(TheIndex.getOrInsertValueInfo(RefGUID), RefGUID);
5480 break;
5481 }
5482 // FS_PERMODULE: [valueid, flags, instcount, fflags, numrefs,
5483 // numrefs x valueid, n x (valueid)]
5484 // FS_PERMODULE_PROFILE: [valueid, flags, instcount, fflags, numrefs,
5485 // numrefs x valueid,
5486 // n x (valueid, hotness)]
5487 // FS_PERMODULE_RELBF: [valueid, flags, instcount, fflags, numrefs,
5488 // numrefs x valueid,
5489 // n x (valueid, relblockfreq)]
5490 case bitc::FS_PERMODULE:
5491 case bitc::FS_PERMODULE_RELBF:
5492 case bitc::FS_PERMODULE_PROFILE: {
5493 unsigned ValueID = Record[0];
5494 uint64_t RawFlags = Record[1];
5495 unsigned InstCount = Record[2];
5496 uint64_t RawFunFlags = 0;
5497 unsigned NumRefs = Record[3];
5498 unsigned NumImmutableRefs = 0;
5499 int RefListStartIndex = 4;
5500 if (Version >= 4) {
5501 RawFunFlags = Record[3];
5502 NumRefs = Record[4];
5503 RefListStartIndex = 5;
5504 if (Version >= 5) {
5505 NumImmutableRefs = Record[5];
5506 RefListStartIndex = 6;
5507 }
5508 }
5509
5510 auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
5511 // The module path string ref set in the summary must be owned by the
5512 // index's module string table. Since we don't have a module path
5513 // string table section in the per-module index, we create a single
5514 // module path string table entry with an empty (0) ID to take
5515 // ownership.
5516 int CallGraphEdgeStartIndex = RefListStartIndex + NumRefs;
5517 assert(Record.size() >= RefListStartIndex + NumRefs &&((Record.size() >= RefListStartIndex + NumRefs && "Record size inconsistent with number of references"
) ? static_cast<void> (0) : __assert_fail ("Record.size() >= RefListStartIndex + NumRefs && \"Record size inconsistent with number of references\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Bitcode/Reader/BitcodeReader.cpp"
, 5518, __PRETTY_FUNCTION__))
5518 "Record size inconsistent with number of references")((Record.size() >= RefListStartIndex + NumRefs && "Record size inconsistent with number of references"
) ? static_cast<void> (0) : __assert_fail ("Record.size() >= RefListStartIndex + NumRefs && \"Record size inconsistent with number of references\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Bitcode/Reader/BitcodeReader.cpp"
, 5518, __PRETTY_FUNCTION__))
;
5519 std::vector<ValueInfo> Refs = makeRefList(
5520 ArrayRef<uint64_t>(Record).slice(RefListStartIndex, NumRefs));
5521 bool HasProfile = (BitCode == bitc::FS_PERMODULE_PROFILE);
5522 bool HasRelBF = (BitCode == bitc::FS_PERMODULE_RELBF);
5523 std::vector<FunctionSummary::EdgeTy> Calls = makeCallList(
5524 ArrayRef<uint64_t>(Record).slice(CallGraphEdgeStartIndex),
5525 IsOldProfileFormat, HasProfile, HasRelBF);
5526 setImmutableRefs(Refs, NumImmutableRefs);
5527 auto FS = llvm::make_unique<FunctionSummary>(
5528 Flags, InstCount, getDecodedFFlags(RawFunFlags), /*EntryCount=*/0,
5529 std::move(Refs), std::move(Calls), std::move(PendingTypeTests),
5530 std::move(PendingTypeTestAssumeVCalls),
5531 std::move(PendingTypeCheckedLoadVCalls),
5532 std::move(PendingTypeTestAssumeConstVCalls),
5533 std::move(PendingTypeCheckedLoadConstVCalls));
5534 PendingTypeTests.clear();
5535 PendingTypeTestAssumeVCalls.clear();
5536 PendingTypeCheckedLoadVCalls.clear();
5537 PendingTypeTestAssumeConstVCalls.clear();
5538 PendingTypeCheckedLoadConstVCalls.clear();
5539 auto VIAndOriginalGUID = getValueInfoFromValueId(ValueID);
5540 FS->setModulePath(getThisModule()->first());
5541 FS->setOriginalName(VIAndOriginalGUID.second);
5542 TheIndex.addGlobalValueSummary(VIAndOriginalGUID.first, std::move(FS));
5543 break;
5544 }
5545 // FS_ALIAS: [valueid, flags, valueid]
5546 // Aliases must be emitted (and parsed) after all FS_PERMODULE entries, as
5547 // they expect all aliasee summaries to be available.
5548 case bitc::FS_ALIAS: {
5549 unsigned ValueID = Record[0];
5550 uint64_t RawFlags = Record[1];
5551 unsigned AliaseeID = Record[2];
5552 auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
5553 auto AS = llvm::make_unique<AliasSummary>(Flags);
5554 // The module path string ref set in the summary must be owned by the
5555 // index's module string table. Since we don't have a module path
5556 // string table section in the per-module index, we create a single
5557 // module path string table entry with an empty (0) ID to take
5558 // ownership.
5559 AS->setModulePath(getThisModule()->first());
5560
5561 auto AliaseeVI = getValueInfoFromValueId(AliaseeID).first;
5562 auto AliaseeInModule = TheIndex.findSummaryInModule(AliaseeVI, ModulePath);
5563 if (!AliaseeInModule)
5564 return error("Alias expects aliasee summary to be parsed");
5565 AS->setAliasee(AliaseeVI, AliaseeInModule);
5566
5567 auto GUID = getValueInfoFromValueId(ValueID);
5568 AS->setOriginalName(GUID.second);
5569 TheIndex.addGlobalValueSummary(GUID.first, std::move(AS));
5570 break;
5571 }
5572 // FS_PERMODULE_GLOBALVAR_INIT_REFS: [valueid, flags, varflags, n x valueid]
5573 case bitc::FS_PERMODULE_GLOBALVAR_INIT_REFS: {
5574 unsigned ValueID = Record[0];
5575 uint64_t RawFlags = Record[1];
5576 unsigned RefArrayStart = 2;
5577 GlobalVarSummary::GVarFlags GVF;
5578 auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
5579 if (Version >= 5) {
5580 GVF = getDecodedGVarFlags(Record[2]);
5581 RefArrayStart = 3;
5582 }
5583 std::vector<ValueInfo> Refs =
5584 makeRefList(ArrayRef<uint64_t>(Record).slice(RefArrayStart));
5585 auto FS =
5586 llvm::make_unique<GlobalVarSummary>(Flags, GVF, std::move(Refs));
5587 FS->setModulePath(getThisModule()->first());
5588 auto GUID = getValueInfoFromValueId(ValueID);
5589 FS->setOriginalName(GUID.second);
5590 TheIndex.addGlobalValueSummary(GUID.first, std::move(FS));
5591 break;
5592 }
5593 // FS_COMBINED: [valueid, modid, flags, instcount, fflags, numrefs,
5594 // numrefs x valueid, n x (valueid)]
5595 // FS_COMBINED_PROFILE: [valueid, modid, flags, instcount, fflags, numrefs,
5596 // numrefs x valueid, n x (valueid, hotness)]
5597 case bitc::FS_COMBINED:
5598 case bitc::FS_COMBINED_PROFILE: {
5599 unsigned ValueID = Record[0];
5600 uint64_t ModuleId = Record[1];
5601 uint64_t RawFlags = Record[2];
5602 unsigned InstCount = Record[3];
5603 uint64_t RawFunFlags = 0;
5604 uint64_t EntryCount = 0;
5605 unsigned NumRefs = Record[4];
5606 unsigned NumImmutableRefs = 0;
5607 int RefListStartIndex = 5;
5608
5609 if (Version >= 4) {
5610 RawFunFlags = Record[4];
5611 RefListStartIndex = 6;
5612 size_t NumRefsIndex = 5;
5613 if (Version >= 5) {
5614 RefListStartIndex = 7;
5615 if (Version >= 6) {
5616 NumRefsIndex = 6;
5617 EntryCount = Record[5];
5618 RefListStartIndex = 8;
5619 }
5620 NumImmutableRefs = Record[RefListStartIndex - 1];
5621 }
5622 NumRefs = Record[NumRefsIndex];
5623 }
5624
5625 auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
5626 int CallGraphEdgeStartIndex = RefListStartIndex + NumRefs;
5627 assert(Record.size() >= RefListStartIndex + NumRefs &&((Record.size() >= RefListStartIndex + NumRefs && "Record size inconsistent with number of references"
) ? static_cast<void> (0) : __assert_fail ("Record.size() >= RefListStartIndex + NumRefs && \"Record size inconsistent with number of references\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Bitcode/Reader/BitcodeReader.cpp"
, 5628, __PRETTY_FUNCTION__))
5628 "Record size inconsistent with number of references")((Record.size() >= RefListStartIndex + NumRefs && "Record size inconsistent with number of references"
) ? static_cast<void> (0) : __assert_fail ("Record.size() >= RefListStartIndex + NumRefs && \"Record size inconsistent with number of references\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Bitcode/Reader/BitcodeReader.cpp"
, 5628, __PRETTY_FUNCTION__))
;
5629 std::vector<ValueInfo> Refs = makeRefList(
5630 ArrayRef<uint64_t>(Record).slice(RefListStartIndex, NumRefs));
5631 bool HasProfile = (BitCode == bitc::FS_COMBINED_PROFILE);
5632 std::vector<FunctionSummary::EdgeTy> Edges = makeCallList(
5633 ArrayRef<uint64_t>(Record).slice(CallGraphEdgeStartIndex),
5634 IsOldProfileFormat, HasProfile, false);
5635 ValueInfo VI = getValueInfoFromValueId(ValueID).first;
5636 setImmutableRefs(Refs, NumImmutableRefs);
5637 auto FS = llvm::make_unique<FunctionSummary>(
5638 Flags, InstCount, getDecodedFFlags(RawFunFlags), EntryCount,
5639 std::move(Refs), std::move(Edges), std::move(PendingTypeTests),
5640 std::move(PendingTypeTestAssumeVCalls),
5641 std::move(PendingTypeCheckedLoadVCalls),
5642 std::move(PendingTypeTestAssumeConstVCalls),
5643 std::move(PendingTypeCheckedLoadConstVCalls));
5644 PendingTypeTests.clear();
5645 PendingTypeTestAssumeVCalls.clear();
5646 PendingTypeCheckedLoadVCalls.clear();
5647 PendingTypeTestAssumeConstVCalls.clear();
5648 PendingTypeCheckedLoadConstVCalls.clear();
5649 LastSeenSummary = FS.get();
5650 LastSeenGUID = VI.getGUID();
5651 FS->setModulePath(ModuleIdMap[ModuleId]);
5652 TheIndex.addGlobalValueSummary(VI, std::move(FS));
5653 break;
5654 }
5655 // FS_COMBINED_ALIAS: [valueid, modid, flags, valueid]
5656 // Aliases must be emitted (and parsed) after all FS_COMBINED entries, as
5657 // they expect all aliasee summaries to be available.
5658 case bitc::FS_COMBINED_ALIAS: {
5659 unsigned ValueID = Record[0];
5660 uint64_t ModuleId = Record[1];
5661 uint64_t RawFlags = Record[2];
5662 unsigned AliaseeValueId = Record[3];
5663 auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
5664 auto AS = llvm::make_unique<AliasSummary>(Flags);
5665 LastSeenSummary = AS.get();
5666 AS->setModulePath(ModuleIdMap[ModuleId]);
5667
5668 auto AliaseeVI = getValueInfoFromValueId(AliaseeValueId).first;
5669 auto AliaseeInModule = TheIndex.findSummaryInModule(AliaseeVI, AS->modulePath());
5670 AS->setAliasee(AliaseeVI, AliaseeInModule);
5671
5672 ValueInfo VI = getValueInfoFromValueId(ValueID).first;
5673 LastSeenGUID = VI.getGUID();
5674 TheIndex.addGlobalValueSummary(VI, std::move(AS));
5675 break;
5676 }
5677 // FS_COMBINED_GLOBALVAR_INIT_REFS: [valueid, modid, flags, n x valueid]
5678 case bitc::FS_COMBINED_GLOBALVAR_INIT_REFS: {
5679 unsigned ValueID = Record[0];
5680 uint64_t ModuleId = Record[1];
5681 uint64_t RawFlags = Record[2];
5682 unsigned RefArrayStart = 3;
5683 GlobalVarSummary::GVarFlags GVF;
5684 auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
5685 if (Version >= 5) {
5686 GVF = getDecodedGVarFlags(Record[3]);
5687 RefArrayStart = 4;
5688 }
5689 std::vector<ValueInfo> Refs =
5690 makeRefList(ArrayRef<uint64_t>(Record).slice(RefArrayStart));
5691 auto FS =
5692 llvm::make_unique<GlobalVarSummary>(Flags, GVF, std::move(Refs));
5693 LastSeenSummary = FS.get();
5694 FS->setModulePath(ModuleIdMap[ModuleId]);
5695 ValueInfo VI = getValueInfoFromValueId(ValueID).first;
5696 LastSeenGUID = VI.getGUID();
5697 TheIndex.addGlobalValueSummary(VI, std::move(FS));
5698 break;
5699 }
5700 // FS_COMBINED_ORIGINAL_NAME: [original_name]
5701 case bitc::FS_COMBINED_ORIGINAL_NAME: {
5702 uint64_t OriginalName = Record[0];
5703 if (!LastSeenSummary)
5704 return error("Name attachment that does not follow a combined record");
5705 LastSeenSummary->setOriginalName(OriginalName);
5706 TheIndex.addOriginalName(LastSeenGUID, OriginalName);
5707 // Reset the LastSeenSummary
5708 LastSeenSummary = nullptr;
5709 LastSeenGUID = 0;
5710 break;
5711 }
5712 case bitc::FS_TYPE_TESTS:
5713 assert(PendingTypeTests.empty())((PendingTypeTests.empty()) ? static_cast<void> (0) : __assert_fail
("PendingTypeTests.empty()", "/build/llvm-toolchain-snapshot-9~svn362543/lib/Bitcode/Reader/BitcodeReader.cpp"
, 5713, __PRETTY_FUNCTION__))
;
5714 PendingTypeTests.insert(PendingTypeTests.end(), Record.begin(),
5715 Record.end());
5716 break;
5717
5718 case bitc::FS_TYPE_TEST_ASSUME_VCALLS:
5719 assert(PendingTypeTestAssumeVCalls.empty())((PendingTypeTestAssumeVCalls.empty()) ? static_cast<void>
(0) : __assert_fail ("PendingTypeTestAssumeVCalls.empty()", "/build/llvm-toolchain-snapshot-9~svn362543/lib/Bitcode/Reader/BitcodeReader.cpp"
, 5719, __PRETTY_FUNCTION__))
;
5720 for (unsigned I = 0; I != Record.size(); I += 2)
5721 PendingTypeTestAssumeVCalls.push_back({Record[I], Record[I+1]});
5722 break;
5723
5724 case bitc::FS_TYPE_CHECKED_LOAD_VCALLS:
5725 assert(PendingTypeCheckedLoadVCalls.empty())((PendingTypeCheckedLoadVCalls.empty()) ? static_cast<void
> (0) : __assert_fail ("PendingTypeCheckedLoadVCalls.empty()"
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Bitcode/Reader/BitcodeReader.cpp"
, 5725, __PRETTY_FUNCTION__))
;
5726 for (unsigned I = 0; I != Record.size(); I += 2)
5727 PendingTypeCheckedLoadVCalls.push_back({Record[I], Record[I+1]});
5728 break;
5729
5730 case bitc::FS_TYPE_TEST_ASSUME_CONST_VCALL:
5731 PendingTypeTestAssumeConstVCalls.push_back(
5732 {{Record[0], Record[1]}, {Record.begin() + 2, Record.end()}});
5733 break;
5734
5735 case bitc::FS_TYPE_CHECKED_LOAD_CONST_VCALL:
5736 PendingTypeCheckedLoadConstVCalls.push_back(
5737 {{Record[0], Record[1]}, {Record.begin() + 2, Record.end()}});
5738 break;
5739
5740 case bitc::FS_CFI_FUNCTION_DEFS: {
5741 std::set<std::string> &CfiFunctionDefs = TheIndex.cfiFunctionDefs();
5742 for (unsigned I = 0; I != Record.size(); I += 2)
5743 CfiFunctionDefs.insert(
5744 {Strtab.data() + Record[I], static_cast<size_t>(Record[I + 1])});
5745 break;
5746 }
5747
5748 case bitc::FS_CFI_FUNCTION_DECLS: {
5749 std::set<std::string> &CfiFunctionDecls = TheIndex.cfiFunctionDecls();
5750 for (unsigned I = 0; I != Record.size(); I += 2)
5751 CfiFunctionDecls.insert(
5752 {Strtab.data() + Record[I], static_cast<size_t>(Record[I + 1])});
5753 break;
5754 }
5755
5756 case bitc::FS_TYPE_ID:
5757 parseTypeIdSummaryRecord(Record, Strtab, TheIndex);
5758 break;
5759 }
5760 }
5761 llvm_unreachable("Exit infinite loop")::llvm::llvm_unreachable_internal("Exit infinite loop", "/build/llvm-toolchain-snapshot-9~svn362543/lib/Bitcode/Reader/BitcodeReader.cpp"
, 5761)
;
5762}
5763
5764// Parse the module string table block into the Index.
5765// This populates the ModulePathStringTable map in the index.
5766Error ModuleSummaryIndexBitcodeReader::parseModuleStringTable() {
5767 if (Stream.EnterSubBlock(bitc::MODULE_STRTAB_BLOCK_ID))
5768 return error("Invalid record");
5769
5770 SmallVector<uint64_t, 64> Record;
5771
5772 SmallString<128> ModulePath;
5773 ModuleSummaryIndex::ModuleInfo *LastSeenModule = nullptr;
5774
5775 while (true) {
5776 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
5777
5778 switch (Entry.Kind) {
5779 case BitstreamEntry::SubBlock: // Handled for us already.
5780 case BitstreamEntry::Error:
5781 return error("Malformed block");
5782 case BitstreamEntry::EndBlock:
5783 return Error::success();
5784 case BitstreamEntry::Record:
5785 // The interesting case.
5786 break;
5787 }
5788
5789 Record.clear();
5790 switch (Stream.readRecord(Entry.ID, Record)) {
5791 default: // Default behavior: ignore.
5792 break;
5793 case bitc::MST_CODE_ENTRY: {
5794 // MST_ENTRY: [modid, namechar x N]
5795 uint64_t ModuleId = Record[0];
5796
5797 if (convertToString(Record, 1, ModulePath))
5798 return error("Invalid record");
5799
5800 LastSeenModule = TheIndex.addModule(ModulePath, ModuleId);
5801 ModuleIdMap[ModuleId] = LastSeenModule->first();
5802
5803 ModulePath.clear();
5804 break;
5805 }
5806 /// MST_CODE_HASH: [5*i32]
5807 case bitc::MST_CODE_HASH: {
5808 if (Record.size() != 5)
5809 return error("Invalid hash length " + Twine(Record.size()).str());
5810 if (!LastSeenModule)
5811 return error("Invalid hash that does not follow a module path");
5812 int Pos = 0;
5813 for (auto &Val : Record) {
5814 assert(!(Val >> 32) && "Unexpected high bits set")((!(Val >> 32) && "Unexpected high bits set") ?
static_cast<void> (0) : __assert_fail ("!(Val >> 32) && \"Unexpected high bits set\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Bitcode/Reader/BitcodeReader.cpp"
, 5814, __PRETTY_FUNCTION__))
;
5815 LastSeenModule->second.second[Pos++] = Val;
5816 }
5817 // Reset LastSeenModule to avoid overriding the hash unexpectedly.
5818 LastSeenModule = nullptr;
5819 break;
5820 }
5821 }
5822 }
5823 llvm_unreachable("Exit infinite loop")::llvm::llvm_unreachable_internal("Exit infinite loop", "/build/llvm-toolchain-snapshot-9~svn362543/lib/Bitcode/Reader/BitcodeReader.cpp"
, 5823)
;
5824}
5825
5826namespace {
5827
5828// FIXME: This class is only here to support the transition to llvm::Error. It
5829// will be removed once this transition is complete. Clients should prefer to
5830// deal with the Error value directly, rather than converting to error_code.
5831class BitcodeErrorCategoryType : public std::error_category {
5832 const char *name() const noexcept override {
5833 return "llvm.bitcode";
5834 }
5835
5836 std::string message(int IE) const override {
5837 BitcodeError E = static_cast<BitcodeError>(IE);
5838 switch (E) {
5839 case BitcodeError::CorruptedBitcode:
5840 return "Corrupted bitcode";
5841 }
5842 llvm_unreachable("Unknown error type!")::llvm::llvm_unreachable_internal("Unknown error type!", "/build/llvm-toolchain-snapshot-9~svn362543/lib/Bitcode/Reader/BitcodeReader.cpp"
, 5842)
;
5843 }
5844};
5845
5846} // end anonymous namespace
5847
5848static ManagedStatic<BitcodeErrorCategoryType> ErrorCategory;
5849
5850const std::error_category &llvm::BitcodeErrorCategory() {
5851 return *ErrorCategory;
5852}
5853
5854static Expected<StringRef> readBlobInRecord(BitstreamCursor &Stream,
5855 unsigned Block, unsigned RecordID) {
5856 if (Stream.EnterSubBlock(Block))
5857 return error("Invalid record");
5858
5859 StringRef Strtab;
5860 while (true) {
5861 BitstreamEntry Entry = Stream.advance();
5862 switch (Entry.Kind) {
5863 case BitstreamEntry::EndBlock:
5864 return Strtab;
5865
5866 case BitstreamEntry::Error:
5867 return error("Malformed block");
5868
5869 case BitstreamEntry::SubBlock:
5870 if (Stream.SkipBlock())
5871 return error("Malformed block");
5872 break;
5873
5874 case BitstreamEntry::Record:
5875 StringRef Blob;
5876 SmallVector<uint64_t, 1> Record;
5877 if (Stream.readRecord(Entry.ID, Record, &Blob) == RecordID)
5878 Strtab = Blob;
5879 break;
5880 }
5881 }
5882}
5883
5884//===----------------------------------------------------------------------===//
5885// External interface
5886//===----------------------------------------------------------------------===//
5887
5888Expected<std::vector<BitcodeModule>>
5889llvm::getBitcodeModuleList(MemoryBufferRef Buffer) {
5890 auto FOrErr = getBitcodeFileContents(Buffer);
5891 if (!FOrErr)
5892 return FOrErr.takeError();
5893 return std::move(FOrErr->Mods);
5894}
5895
5896Expected<BitcodeFileContents>
5897llvm::getBitcodeFileContents(MemoryBufferRef Buffer) {
5898 Expected<BitstreamCursor> StreamOrErr = initStream(Buffer);
5899 if (!StreamOrErr)
5900 return StreamOrErr.takeError();
5901 BitstreamCursor &Stream = *StreamOrErr;
5902
5903 BitcodeFileContents F;
5904 while (true) {
5905 uint64_t BCBegin = Stream.getCurrentByteNo();
5906
5907 // We may be consuming bitcode from a client that leaves garbage at the end
5908 // of the bitcode stream (e.g. Apple's ar tool). If we are close enough to
5909 // the end that there cannot possibly be another module, stop looking.
5910 if (BCBegin + 8 >= Stream.getBitcodeBytes().size())
5911 return F;
5912
5913 BitstreamEntry Entry = Stream.advance();
5914 switch (Entry.Kind) {
5915 case BitstreamEntry::EndBlock:
5916 case BitstreamEntry::Error:
5917 return error("Malformed block");
5918
5919 case BitstreamEntry::SubBlock: {
5920 uint64_t IdentificationBit = -1ull;
5921 if (Entry.ID == bitc::IDENTIFICATION_BLOCK_ID) {
5922 IdentificationBit = Stream.GetCurrentBitNo() - BCBegin * 8;
5923 if (Stream.SkipBlock())
5924 return error("Malformed block");
5925
5926 Entry = Stream.advance();
5927 if (Entry.Kind != BitstreamEntry::SubBlock ||
5928 Entry.ID != bitc::MODULE_BLOCK_ID)
5929 return error("Malformed block");
5930 }
5931
5932 if (Entry.ID == bitc::MODULE_BLOCK_ID) {
5933 uint64_t ModuleBit = Stream.GetCurrentBitNo() - BCBegin * 8;
5934 if (Stream.SkipBlock())
5935 return error("Malformed block");
5936
5937 F.Mods.push_back({Stream.getBitcodeBytes().slice(
5938 BCBegin, Stream.getCurrentByteNo() - BCBegin),
5939 Buffer.getBufferIdentifier(), IdentificationBit,
5940 ModuleBit});
5941 continue;
5942 }
5943
5944 if (Entry.ID == bitc::STRTAB_BLOCK_ID) {
5945 Expected<StringRef> Strtab =
5946 readBlobInRecord(Stream, bitc::STRTAB_BLOCK_ID, bitc::STRTAB_BLOB);
5947 if (!Strtab)
5948 return Strtab.takeError();
5949 // This string table is used by every preceding bitcode module that does
5950 // not have its own string table. A bitcode file may have multiple
5951 // string tables if it was created by binary concatenation, for example
5952 // with "llvm-cat -b".
5953 for (auto I = F.Mods.rbegin(), E = F.Mods.rend(); I != E; ++I) {
5954 if (!I->Strtab.empty())
5955 break;
5956 I->Strtab = *Strtab;
5957 }
5958 // Similarly, the string table is used by every preceding symbol table;
5959 // normally there will be just one unless the bitcode file was created
5960 // by binary concatenation.
5961 if (!F.Symtab.empty() && F.StrtabForSymtab.empty())
5962 F.StrtabForSymtab = *Strtab;
5963 continue;
5964 }
5965
5966 if (Entry.ID == bitc::SYMTAB_BLOCK_ID) {
5967 Expected<StringRef> SymtabOrErr =
5968 readBlobInRecord(Stream, bitc::SYMTAB_BLOCK_ID, bitc::SYMTAB_BLOB);
5969 if (!SymtabOrErr)
5970 return SymtabOrErr.takeError();
5971
5972 // We can expect the bitcode file to have multiple symbol tables if it
5973 // was created by binary concatenation. In that case we silently
5974 // ignore any subsequent symbol tables, which is fine because this is a
5975 // low level function. The client is expected to notice that the number
5976 // of modules in the symbol table does not match the number of modules
5977 // in the input file and regenerate the symbol table.
5978 if (F.Symtab.empty())
5979 F.Symtab = *SymtabOrErr;
5980 continue;
5981 }
5982
5983 if (Stream.SkipBlock())
5984 return error("Malformed block");
5985 continue;
5986 }
5987 case BitstreamEntry::Record:
5988 Stream.skipRecord(Entry.ID);
5989 continue;
5990 }
5991 }
5992}
5993
5994/// Get a lazy one-at-time loading module from bitcode.
5995///
5996/// This isn't always used in a lazy context. In particular, it's also used by
5997/// \a parseModule(). If this is truly lazy, then we need to eagerly pull
5998/// in forward-referenced functions from block address references.
5999///
6000/// \param[in] MaterializeAll Set to \c true if we should materialize
6001/// everything.
6002Expected<std::unique_ptr<Module>>
6003BitcodeModule::getModuleImpl(LLVMContext &Context, bool MaterializeAll,
6004 bool ShouldLazyLoadMetadata, bool IsImporting) {