Bug Summary

File:llvm/lib/Bitcode/Reader/BitcodeReader.cpp
Warning:line 6138, column 7
Method called on moved-from object 'PendingTypeCheckedLoadConstVCalls' of type 'std::vector'

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 -setup-static-analyzer -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mthread-model posix -mframe-pointer=none -fmath-errno -fno-rounding-math -masm-verbose -mconstructor-aliases -munwind-tables -fuse-init-array -target-cpu x86-64 -dwarf-column-info -debugger-tuning=gdb -ffunction-sections -fdata-sections -resource-dir /usr/lib/llvm-10/lib/clang/10.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/build-llvm/lib/Bitcode/Reader -I /build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/lib/Bitcode/Reader -I /build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/build-llvm/include -I /build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/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/local/include -internal-isystem /usr/lib/llvm-10/lib/clang/10.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++14 -fdeprecated-macro -fdebug-compilation-dir /build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/build-llvm/lib/Bitcode/Reader -fdebug-prefix-map=/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809=. -ferror-limit 19 -fmessage-length 0 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -fobjc-runtime=gcc -fdiagnostics-show-option -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -o /tmp/scan-build-2019-12-11-181444-25759-1 -x c++ /build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/lib/Bitcode/Reader/BitcodeReader.cpp

/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/lib/Bitcode/Reader/BitcodeReader.cpp

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

/usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0/bits/unique_ptr.h

1// unique_ptr implementation -*- C++ -*-
2
3// Copyright (C) 2008-2016 Free Software Foundation, Inc.
4//
5// This file is part of the GNU ISO C++ Library. This library is free
6// software; you can redistribute it and/or modify it under the
7// terms of the GNU General Public License as published by the
8// Free Software Foundation; either version 3, or (at your option)
9// any later version.
10
11// This library is distributed in the hope that it will be useful,
12// but WITHOUT ANY WARRANTY; without even the implied warranty of
13// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14// GNU General Public License for more details.
15
16// Under Section 7 of GPL version 3, you are granted additional
17// permissions described in the GCC Runtime Library Exception, version
18// 3.1, as published by the Free Software Foundation.
19
20// You should have received a copy of the GNU General Public License and
21// a copy of the GCC Runtime Library Exception along with this program;
22// see the files COPYING3 and COPYING.RUNTIME respectively. If not, see
23// <http://www.gnu.org/licenses/>.
24
25/** @file bits/unique_ptr.h
26 * This is an internal header file, included by other library headers.
27 * Do not attempt to use it directly. @headername{memory}
28 */
29
30#ifndef _UNIQUE_PTR_H1
31#define _UNIQUE_PTR_H1 1
32
33#include <bits/c++config.h>
34#include <debug/assertions.h>
35#include <type_traits>
36#include <utility>
37#include <tuple>
38
39namespace std _GLIBCXX_VISIBILITY(default)__attribute__ ((__visibility__ ("default")))
40{
41_GLIBCXX_BEGIN_NAMESPACE_VERSION
42
43 /**
44 * @addtogroup pointer_abstractions
45 * @{
46 */
47
48#if _GLIBCXX_USE_DEPRECATED1
49 template<typename> class auto_ptr;
50#endif
51
52 /// Primary template of default_delete, used by unique_ptr
53 template<typename _Tp>
54 struct default_delete
55 {
56 /// Default constructor
57 constexpr default_delete() noexcept = default;
58
59 /** @brief Converting constructor.
60 *
61 * Allows conversion from a deleter for arrays of another type, @p _Up,
62 * only if @p _Up* is convertible to @p _Tp*.
63 */
64 template<typename _Up, typename = typename
65 enable_if<is_convertible<_Up*, _Tp*>::value>::type>
66 default_delete(const default_delete<_Up>&) noexcept { }
67
68 /// Calls @c delete @p __ptr
69 void
70 operator()(_Tp* __ptr) const
71 {
72 static_assert(!is_void<_Tp>::value,
73 "can't delete pointer to incomplete type");
74 static_assert(sizeof(_Tp)>0,
75 "can't delete pointer to incomplete type");
76 delete __ptr;
77 }
78 };
79
80 // _GLIBCXX_RESOLVE_LIB_DEFECTS
81 // DR 740 - omit specialization for array objects with a compile time length
82 /// Specialization for arrays, default_delete.
83 template<typename _Tp>
84 struct default_delete<_Tp[]>
85 {
86 public:
87 /// Default constructor
88 constexpr default_delete() noexcept = default;
89
90 /** @brief Converting constructor.
91 *
92 * Allows conversion from a deleter for arrays of another type, such as
93 * a const-qualified version of @p _Tp.
94 *
95 * Conversions from types derived from @c _Tp are not allowed because
96 * it is unsafe to @c delete[] an array of derived types through a
97 * pointer to the base type.
98 */
99 template<typename _Up, typename = typename
100 enable_if<is_convertible<_Up(*)[], _Tp(*)[]>::value>::type>
101 default_delete(const default_delete<_Up[]>&) noexcept { }
102
103 /// Calls @c delete[] @p __ptr
104 template<typename _Up>
105 typename enable_if<is_convertible<_Up(*)[], _Tp(*)[]>::value>::type
106 operator()(_Up* __ptr) const
107 {
108 static_assert(sizeof(_Tp)>0,
109 "can't delete pointer to incomplete type");
110 delete [] __ptr;
111 }
112 };
113
114 /// 20.7.1.2 unique_ptr for single objects.
115 template <typename _Tp, typename _Dp = default_delete<_Tp> >
116 class unique_ptr
117 {
118 // use SFINAE to determine whether _Del::pointer exists
119 class _Pointer
120 {
121 template<typename _Up>
122 static typename _Up::pointer __test(typename _Up::pointer*);
123
124 template<typename _Up>
125 static _Tp* __test(...);
126
127 typedef typename remove_reference<_Dp>::type _Del;
128
129 public:
130 typedef decltype(__test<_Del>(0)) type;
131 };
132
133 typedef std::tuple<typename _Pointer::type, _Dp> __tuple_type;
134 __tuple_type _M_t;
135
136 public:
137 typedef typename _Pointer::type pointer;
138 typedef _Tp element_type;
139 typedef _Dp deleter_type;
140
141
142 // helper template for detecting a safe conversion from another
143 // unique_ptr
144 template<typename _Up, typename _Ep>
145 using __safe_conversion_up = __and_<
146 is_convertible<typename unique_ptr<_Up, _Ep>::pointer, pointer>,
147 __not_<is_array<_Up>>,
148 __or_<__and_<is_reference<deleter_type>,
149 is_same<deleter_type, _Ep>>,
150 __and_<__not_<is_reference<deleter_type>>,
151 is_convertible<_Ep, deleter_type>>
152 >
153 >;
154
155 // Constructors.
156
157 /// Default constructor, creates a unique_ptr that owns nothing.
158 constexpr unique_ptr() noexcept
159 : _M_t()
160 { static_assert(!is_pointer<deleter_type>::value,
161 "constructed with null function pointer deleter"); }
162
163 /** Takes ownership of a pointer.
164 *
165 * @param __p A pointer to an object of @c element_type
166 *
167 * The deleter will be value-initialized.
168 */
169 explicit
170 unique_ptr(pointer __p) noexcept
171 : _M_t()
172 {
173 std::get<0>(_M_t) = __p;
174 static_assert(!is_pointer<deleter_type>::value,
175 "constructed with null function pointer deleter");
176 }
177
178 /** Takes ownership of a pointer.
179 *
180 * @param __p A pointer to an object of @c element_type
181 * @param __d A reference to a deleter.
182 *
183 * The deleter will be initialized with @p __d
184 */
185 unique_ptr(pointer __p,
186 typename conditional<is_reference<deleter_type>::value,
187 deleter_type, const deleter_type&>::type __d) noexcept
188 : _M_t(__p, __d) { }
189
190 /** Takes ownership of a pointer.
191 *
192 * @param __p A pointer to an object of @c element_type
193 * @param __d An rvalue reference to a deleter.
194 *
195 * The deleter will be initialized with @p std::move(__d)
196 */
197 unique_ptr(pointer __p,
198 typename remove_reference<deleter_type>::type&& __d) noexcept
199 : _M_t(std::move(__p), std::move(__d))
200 { static_assert(!std::is_reference<deleter_type>::value,
201 "rvalue deleter bound to reference"); }
202
203 /// Creates a unique_ptr that owns nothing.
204 constexpr unique_ptr(nullptr_t) noexcept : unique_ptr() { }
205
206 // Move constructors.
207
208 /// Move constructor.
209 unique_ptr(unique_ptr&& __u) noexcept
210 : _M_t(__u.release(), std::forward<deleter_type>(__u.get_deleter())) { }
211
212 /** @brief Converting constructor from another type
213 *
214 * Requires that the pointer owned by @p __u is convertible to the
215 * type of pointer owned by this object, @p __u does not own an array,
216 * and @p __u has a compatible deleter type.
217 */
218 template<typename _Up, typename _Ep, typename = _Require<
219 __safe_conversion_up<_Up, _Ep>,
220 typename conditional<is_reference<_Dp>::value,
221 is_same<_Ep, _Dp>,
222 is_convertible<_Ep, _Dp>>::type>>
223 unique_ptr(unique_ptr<_Up, _Ep>&& __u) noexcept
224 : _M_t(__u.release(), std::forward<_Ep>(__u.get_deleter()))
225 { }
226
227#if _GLIBCXX_USE_DEPRECATED1
228 /// Converting constructor from @c auto_ptr
229 template<typename _Up, typename = _Require<
230 is_convertible<_Up*, _Tp*>, is_same<_Dp, default_delete<_Tp>>>>
231 unique_ptr(auto_ptr<_Up>&& __u) noexcept;
232#endif
233
234 /// Destructor, invokes the deleter if the stored pointer is not null.
235 ~unique_ptr() noexcept
236 {
237 auto& __ptr = std::get<0>(_M_t);
238 if (__ptr != nullptr)
239 get_deleter()(__ptr);
240 __ptr = pointer();
241 }
242
243 // Assignment.
244
245 /** @brief Move assignment operator.
246 *
247 * @param __u The object to transfer ownership from.
248 *
249 * Invokes the deleter first if this object owns a pointer.
250 */
251 unique_ptr&
252 operator=(unique_ptr&& __u) noexcept
253 {
254 reset(__u.release());
255 get_deleter() = std::forward<deleter_type>(__u.get_deleter());
256 return *this;
257 }
258
259 /** @brief Assignment from another type.
260 *
261 * @param __u The object to transfer ownership from, which owns a
262 * convertible pointer to a non-array object.
263 *
264 * Invokes the deleter first if this object owns a pointer.
265 */
266 template<typename _Up, typename _Ep>
267 typename enable_if< __and_<
268 __safe_conversion_up<_Up, _Ep>,
269 is_assignable<deleter_type&, _Ep&&>
270 >::value,
271 unique_ptr&>::type
272 operator=(unique_ptr<_Up, _Ep>&& __u) noexcept
273 {
274 reset(__u.release());
275 get_deleter() = std::forward<_Ep>(__u.get_deleter());
276 return *this;
277 }
278
279 /// Reset the %unique_ptr to empty, invoking the deleter if necessary.
280 unique_ptr&
281 operator=(nullptr_t) noexcept
282 {
283 reset();
284 return *this;
285 }
286
287 // Observers.
288
289 /// Dereference the stored pointer.
290 typename add_lvalue_reference<element_type>::type
291 operator*() const
292 {
293 __glibcxx_assert(get() != pointer());
294 return *get();
295 }
296
297 /// Return the stored pointer.
298 pointer
299 operator->() const noexcept
300 {
301 _GLIBCXX_DEBUG_PEDASSERT(get() != pointer());
302 return get();
303 }
304
305 /// Return the stored pointer.
306 pointer
307 get() const noexcept
308 { return std::get<0>(_M_t); }
309
310 /// Return a reference to the stored deleter.
311 deleter_type&
312 get_deleter() noexcept
313 { return std::get<1>(_M_t); }
314
315 /// Return a reference to the stored deleter.
316 const deleter_type&
317 get_deleter() const noexcept
318 { return std::get<1>(_M_t); }
319
320 /// Return @c true if the stored pointer is not null.
321 explicit operator bool() const noexcept
322 { return get() == pointer() ? false : true; }
323
324 // Modifiers.
325
326 /// Release ownership of any stored pointer.
327 pointer
328 release() noexcept
329 {
330 pointer __p = get();
331 std::get<0>(_M_t) = pointer();
332 return __p;
333 }
334
335 /** @brief Replace the stored pointer.
336 *
337 * @param __p The new pointer to store.
338 *
339 * The deleter will be invoked if a pointer is already owned.
340 */
341 void
342 reset(pointer __p = pointer()) noexcept
343 {
344 using std::swap;
345 swap(std::get<0>(_M_t), __p);
346 if (__p != pointer())
347 get_deleter()(__p);
348 }
349
350 /// Exchange the pointer and deleter with another object.
351 void
352 swap(unique_ptr& __u) noexcept
353 {
354 using std::swap;
355 swap(_M_t, __u._M_t);
356 }
357
358 // Disable copy from lvalue.
359 unique_ptr(const unique_ptr&) = delete;
360 unique_ptr& operator=(const unique_ptr&) = delete;
361 };
362
363 /// 20.7.1.3 unique_ptr for array objects with a runtime length
364 // [unique.ptr.runtime]
365 // _GLIBCXX_RESOLVE_LIB_DEFECTS
366 // DR 740 - omit specialization for array objects with a compile time length
367 template<typename _Tp, typename _Dp>
368 class unique_ptr<_Tp[], _Dp>
369 {
370 // use SFINAE to determine whether _Del::pointer exists
371 class _Pointer
372 {
373 template<typename _Up>
374 static typename _Up::pointer __test(typename _Up::pointer*);
375
376 template<typename _Up>
377 static _Tp* __test(...);
378
379 typedef typename remove_reference<_Dp>::type _Del;
380
381 public:
382 typedef decltype(__test<_Del>(0)) type;
383 };
384
385 typedef std::tuple<typename _Pointer::type, _Dp> __tuple_type;
386 __tuple_type _M_t;
387
388 template<typename _Up>
389 using __remove_cv = typename remove_cv<_Up>::type;
390
391 // like is_base_of<_Tp, _Up> but false if unqualified types are the same
392 template<typename _Up>
393 using __is_derived_Tp
394 = __and_< is_base_of<_Tp, _Up>,
395 __not_<is_same<__remove_cv<_Tp>, __remove_cv<_Up>>> >;
396
397
398 public:
399 typedef typename _Pointer::type pointer;
400 typedef _Tp element_type;
401 typedef _Dp deleter_type;
402
403 // helper template for detecting a safe conversion from another
404 // unique_ptr
405 template<typename _Up, typename _Ep,
406 typename _Up_up = unique_ptr<_Up, _Ep>,
407 typename _Up_element_type = typename _Up_up::element_type>
408 using __safe_conversion_up = __and_<
409 is_array<_Up>,
410 is_same<pointer, element_type*>,
411 is_same<typename _Up_up::pointer, _Up_element_type*>,
412 is_convertible<_Up_element_type(*)[], element_type(*)[]>,
413 __or_<__and_<is_reference<deleter_type>, is_same<deleter_type, _Ep>>,
414 __and_<__not_<is_reference<deleter_type>>,
415 is_convertible<_Ep, deleter_type>>>
416 >;
417
418 // helper template for detecting a safe conversion from a raw pointer
419 template<typename _Up>
420 using __safe_conversion_raw = __and_<
421 __or_<__or_<is_same<_Up, pointer>,
422 is_same<_Up, nullptr_t>>,
423 __and_<is_pointer<_Up>,
424 is_same<pointer, element_type*>,
425 is_convertible<
426 typename remove_pointer<_Up>::type(*)[],
427 element_type(*)[]>
428 >
429 >
430 >;
431
432 // Constructors.
433
434 /// Default constructor, creates a unique_ptr that owns nothing.
435 constexpr unique_ptr() noexcept
436 : _M_t()
437 { static_assert(!std::is_pointer<deleter_type>::value,
438 "constructed with null function pointer deleter"); }
439
440 /** Takes ownership of a pointer.
441 *
442 * @param __p A pointer to an array of a type safely convertible
443 * to an array of @c element_type
444 *
445 * The deleter will be value-initialized.
446 */
447 template<typename _Up,
448 typename = typename enable_if<
449 __safe_conversion_raw<_Up>::value, bool>::type>
450 explicit
451 unique_ptr(_Up __p) noexcept
452 : _M_t(__p, deleter_type())
453 { static_assert(!is_pointer<deleter_type>::value,
454 "constructed with null function pointer deleter"); }
455
456 /** Takes ownership of a pointer.
457 *
458 * @param __p A pointer to an array of a type safely convertible
459 * to an array of @c element_type
460 * @param __d A reference to a deleter.
461 *
462 * The deleter will be initialized with @p __d
463 */
464 template<typename _Up,
465 typename = typename enable_if<
466 __safe_conversion_raw<_Up>::value, bool>::type>
467 unique_ptr(_Up __p,
468 typename conditional<is_reference<deleter_type>::value,
469 deleter_type, const deleter_type&>::type __d) noexcept
470 : _M_t(__p, __d) { }
471
472 /** Takes ownership of a pointer.
473 *
474 * @param __p A pointer to an array of a type safely convertible
475 * to an array of @c element_type
476 * @param __d A reference to a deleter.
477 *
478 * The deleter will be initialized with @p std::move(__d)
479 */
480 template<typename _Up,
481 typename = typename enable_if<
482 __safe_conversion_raw<_Up>::value, bool>::type>
483 unique_ptr(_Up __p, typename
484 remove_reference<deleter_type>::type&& __d) noexcept
485 : _M_t(std::move(__p), std::move(__d))
486 { static_assert(!is_reference<deleter_type>::value,
487 "rvalue deleter bound to reference"); }
488
489 /// Move constructor.
490 unique_ptr(unique_ptr&& __u) noexcept
491 : _M_t(__u.release(), std::forward<deleter_type>(__u.get_deleter())) { }
492
493 /// Creates a unique_ptr that owns nothing.
494 constexpr unique_ptr(nullptr_t) noexcept : unique_ptr() { }
495
496 template<typename _Up, typename _Ep,
497 typename = _Require<__safe_conversion_up<_Up, _Ep>>>
498 unique_ptr(unique_ptr<_Up, _Ep>&& __u) noexcept
499 : _M_t(__u.release(), std::forward<_Ep>(__u.get_deleter()))
500 { }
501
502 /// Destructor, invokes the deleter if the stored pointer is not null.
503 ~unique_ptr()
504 {
505 auto& __ptr = std::get<0>(_M_t);
506 if (__ptr != nullptr)
507 get_deleter()(__ptr);
508 __ptr = pointer();
509 }
510
511 // Assignment.
512
513 /** @brief Move assignment operator.
514 *
515 * @param __u The object to transfer ownership from.
516 *
517 * Invokes the deleter first if this object owns a pointer.
518 */
519 unique_ptr&
520 operator=(unique_ptr&& __u) noexcept
521 {
522 reset(__u.release());
523 get_deleter() = std::forward<deleter_type>(__u.get_deleter());
524 return *this;
525 }
526
527 /** @brief Assignment from another type.
528 *
529 * @param __u The object to transfer ownership from, which owns a
530 * convertible pointer to an array object.
531 *
532 * Invokes the deleter first if this object owns a pointer.
533 */
534 template<typename _Up, typename _Ep>
535 typename
536 enable_if<__and_<__safe_conversion_up<_Up, _Ep>,
537 is_assignable<deleter_type&, _Ep&&>
538 >::value,
539 unique_ptr&>::type
540 operator=(unique_ptr<_Up, _Ep>&& __u) noexcept
541 {
542 reset(__u.release());
543 get_deleter() = std::forward<_Ep>(__u.get_deleter());
544 return *this;
545 }
546
547 /// Reset the %unique_ptr to empty, invoking the deleter if necessary.
548 unique_ptr&
549 operator=(nullptr_t) noexcept
550 {
551 reset();
552 return *this;
553 }
554
555 // Observers.
556
557 /// Access an element of owned array.
558 typename std::add_lvalue_reference<element_type>::type
559 operator[](size_t __i) const
560 {
561 __glibcxx_assert(get() != pointer());
562 return get()[__i];
563 }
564
565 /// Return the stored pointer.
566 pointer
567 get() const noexcept
568 { return std::get<0>(_M_t); }
569
570 /// Return a reference to the stored deleter.
571 deleter_type&
572 get_deleter() noexcept
573 { return std::get<1>(_M_t); }
574
575 /// Return a reference to the stored deleter.
576 const deleter_type&
577 get_deleter() const noexcept
578 { return std::get<1>(_M_t); }
579
580 /// Return @c true if the stored pointer is not null.
581 explicit operator bool() const noexcept
582 { return get() == pointer() ? false : true; }
583
584 // Modifiers.
585
586 /// Release ownership of any stored pointer.
587 pointer
588 release() noexcept
589 {
590 pointer __p = get();
591 std::get<0>(_M_t) = pointer();
592 return __p;
593 }
594
595 /** @brief Replace the stored pointer.
596 *
597 * @param __p The new pointer to store.
598 *
599 * The deleter will be invoked if a pointer is already owned.
600 */
601 template <typename _Up,
602 typename = _Require<
603 __or_<is_same<_Up, pointer>,
604 __and_<is_same<pointer, element_type*>,
605 is_pointer<_Up>,
606 is_convertible<
607 typename remove_pointer<_Up>::type(*)[],
608 element_type(*)[]
609 >
610 >
611 >
612 >>
613 void
614 reset(_Up __p) noexcept
615 {
616 pointer __ptr = __p;
617 using std::swap;
618 swap(std::get<0>(_M_t), __ptr);
619 if (__ptr != nullptr)
620 get_deleter()(__ptr);
621 }
622
623 void reset(nullptr_t = nullptr) noexcept
624 {
625 reset(pointer());
626 }
627
628 /// Exchange the pointer and deleter with another object.
629 void
630 swap(unique_ptr& __u) noexcept
631 {
632 using std::swap;
633 swap(_M_t, __u._M_t);
634 }
635
636 // Disable copy from lvalue.
637 unique_ptr(const unique_ptr&) = delete;
638 unique_ptr& operator=(const unique_ptr&) = delete;
639 };
640
641 template<typename _Tp, typename _Dp>
642 inline void
643 swap(unique_ptr<_Tp, _Dp>& __x,
644 unique_ptr<_Tp, _Dp>& __y) noexcept
645 { __x.swap(__y); }
646
647 template<typename _Tp, typename _Dp,
648 typename _Up, typename _Ep>
649 inline bool
650 operator==(const unique_ptr<_Tp, _Dp>& __x,
651 const unique_ptr<_Up, _Ep>& __y)
652 { return __x.get() == __y.get(); }
653
654 template<typename _Tp, typename _Dp>
655 inline bool
656 operator==(const unique_ptr<_Tp, _Dp>& __x, nullptr_t) noexcept
657 { return !__x; }
658
659 template<typename _Tp, typename _Dp>
660 inline bool
661 operator==(nullptr_t, const unique_ptr<_Tp, _Dp>& __x) noexcept
662 { return !__x; }
663
664 template<typename _Tp, typename _Dp,
665 typename _Up, typename _Ep>
666 inline bool
667 operator!=(const unique_ptr<_Tp, _Dp>& __x,
668 const unique_ptr<_Up, _Ep>& __y)
669 { return __x.get() != __y.get(); }
670
671 template<typename _Tp, typename _Dp>
672 inline bool
673 operator!=(const unique_ptr<_Tp, _Dp>& __x, nullptr_t) noexcept
674 { return (bool)__x; }
675
676 template<typename _Tp, typename _Dp>
677 inline bool
678 operator!=(nullptr_t, const unique_ptr<_Tp, _Dp>& __x) noexcept
679 { return (bool)__x; }
680
681 template<typename _Tp, typename _Dp,
682 typename _Up, typename _Ep>
683 inline bool
684 operator<(const unique_ptr<_Tp, _Dp>& __x,
685 const unique_ptr<_Up, _Ep>& __y)
686 {
687 typedef typename
688 std::common_type<typename unique_ptr<_Tp, _Dp>::pointer,
689 typename unique_ptr<_Up, _Ep>::pointer>::type _CT;
690 return std::less<_CT>()(__x.get(), __y.get());
691 }
692
693 template<typename _Tp, typename _Dp>
694 inline bool
695 operator<(const unique_ptr<_Tp, _Dp>& __x, nullptr_t)
696 { return std::less<typename unique_ptr<_Tp, _Dp>::pointer>()(__x.get(),
697 nullptr); }
698
699 template<typename _Tp, typename _Dp>
700 inline bool
701 operator<(nullptr_t, const unique_ptr<_Tp, _Dp>& __x)
702 { return std::less<typename unique_ptr<_Tp, _Dp>::pointer>()(nullptr,
703 __x.get()); }
704
705 template<typename _Tp, typename _Dp,
706 typename _Up, typename _Ep>
707 inline bool
708 operator<=(const unique_ptr<_Tp, _Dp>& __x,
709 const unique_ptr<_Up, _Ep>& __y)
710 { return !(__y < __x); }
711
712 template<typename _Tp, typename _Dp>
713 inline bool
714 operator<=(const unique_ptr<_Tp, _Dp>& __x, nullptr_t)
715 { return !(nullptr < __x); }
716
717 template<typename _Tp, typename _Dp>
718 inline bool
719 operator<=(nullptr_t, const unique_ptr<_Tp, _Dp>& __x)
720 { return !(__x < nullptr); }
721
722 template<typename _Tp, typename _Dp,
723 typename _Up, typename _Ep>
724 inline bool
725 operator>(const unique_ptr<_Tp, _Dp>& __x,
726 const unique_ptr<_Up, _Ep>& __y)
727 { return (__y < __x); }
728
729 template<typename _Tp, typename _Dp>
730 inline bool
731 operator>(const unique_ptr<_Tp, _Dp>& __x, nullptr_t)
732 { return std::less<typename unique_ptr<_Tp, _Dp>::pointer>()(nullptr,
733 __x.get()); }
734
735 template<typename _Tp, typename _Dp>
736 inline bool
737 operator>(nullptr_t, const unique_ptr<_Tp, _Dp>& __x)
738 { return std::less<typename unique_ptr<_Tp, _Dp>::pointer>()(__x.get(),
739 nullptr); }
740
741 template<typename _Tp, typename _Dp,
742 typename _Up, typename _Ep>
743 inline bool
744 operator>=(const unique_ptr<_Tp, _Dp>& __x,
745 const unique_ptr<_Up, _Ep>& __y)
746 { return !(__x < __y); }
747
748 template<typename _Tp, typename _Dp>
749 inline bool
750 operator>=(const unique_ptr<_Tp, _Dp>& __x, nullptr_t)
751 { return !(__x < nullptr); }
752
753 template<typename _Tp, typename _Dp>
754 inline bool
755 operator>=(nullptr_t, const unique_ptr<_Tp, _Dp>& __x)
756 { return !(nullptr < __x); }
757
758 /// std::hash specialization for unique_ptr.
759 template<typename _Tp, typename _Dp>
760 struct hash<unique_ptr<_Tp, _Dp>>
761 : public __hash_base<size_t, unique_ptr<_Tp, _Dp>>
762 {
763 size_t
764 operator()(const unique_ptr<_Tp, _Dp>& __u) const noexcept
765 {
766 typedef unique_ptr<_Tp, _Dp> _UP;
767 return std::hash<typename _UP::pointer>()(__u.get());
768 }
769 };
770
771#if __cplusplus201402L > 201103L
772
773#define __cpp_lib_make_unique201304 201304
774
775 template<typename _Tp>
776 struct _MakeUniq
777 { typedef unique_ptr<_Tp> __single_object; };
778
779 template<typename _Tp>
780 struct _MakeUniq<_Tp[]>
781 { typedef unique_ptr<_Tp[]> __array; };
782
783 template<typename _Tp, size_t _Bound>
784 struct _MakeUniq<_Tp[_Bound]>
785 { struct __invalid_type { }; };
786
787 /// std::make_unique for single objects
788 template<typename _Tp, typename... _Args>
789 inline typename _MakeUniq<_Tp>::__single_object
790 make_unique(_Args&&... __args)
791 { return unique_ptr<_Tp>(new _Tp(std::forward<_Args>(__args)...)); }
24
Object 'PendingTypeCheckedLoadConstVCalls' of type 'std::vector' is left in a valid but unspecified state after move
792
793 /// std::make_unique for arrays of unknown bound
794 template<typename _Tp>
795 inline typename _MakeUniq<_Tp>::__array
796 make_unique(size_t __num)
797 { return unique_ptr<_Tp>(new remove_extent_t<_Tp>[__num]()); }
798
799 /// Disable std::make_unique for arrays of known bound
800 template<typename _Tp, typename... _Args>
801 inline typename _MakeUniq<_Tp>::__invalid_type
802 make_unique(_Args&&...) = delete;
803#endif
804
805 // @} group pointer_abstractions
806
807_GLIBCXX_END_NAMESPACE_VERSION
808} // namespace
809
810#endif /* _UNIQUE_PTR_H */