Bug Summary

File:include/llvm/Support/Error.h
Warning:line 200, column 5
Potential leak of memory pointed to by 'Payload._M_t._M_head_impl'

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -disable-llvm-verifier -discard-value-names -main-file-name BitcodeReader.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mthread-model posix -fmath-errno -masm-verbose -mconstructor-aliases -munwind-tables -fuse-init-array -target-cpu x86-64 -dwarf-column-info -debugger-tuning=gdb -momit-leaf-frame-pointer -ffunction-sections -fdata-sections -resource-dir /usr/lib/llvm-9/lib/clang/9.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-9~svn362543/build-llvm/lib/Bitcode/Reader -I /build/llvm-toolchain-snapshot-9~svn362543/lib/Bitcode/Reader -I /build/llvm-toolchain-snapshot-9~svn362543/build-llvm/include -I /build/llvm-toolchain-snapshot-9~svn362543/include -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0/backward -internal-isystem /usr/include/clang/9.0.0/include/ -internal-isystem /usr/local/include -internal-isystem /usr/lib/llvm-9/lib/clang/9.0.0/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -O2 -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-comment -std=c++11 -fdeprecated-macro -fdebug-compilation-dir /build/llvm-toolchain-snapshot-9~svn362543/build-llvm/lib/Bitcode/Reader -fdebug-prefix-map=/build/llvm-toolchain-snapshot-9~svn362543=. -ferror-limit 19 -fmessage-length 0 -fvisibility-inlines-hidden -stack-protector 2 -fobjc-runtime=gcc -fdiagnostics-show-option -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -o /tmp/scan-build-2019-06-05-060531-1271-1 -x c++ /build/llvm-toolchain-snapshot-9~svn362543/lib/Bitcode/Reader/BitcodeReader.cpp -faddrsig

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

/build/llvm-toolchain-snapshot-9~svn362543/include/llvm/Support/Error.h

1//===- llvm/Support/Error.h - Recoverable error handling --------*- C++ -*-===//
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// This file defines an API used to report recoverable errors.
10//
11//===----------------------------------------------------------------------===//
12
13#ifndef LLVM_SUPPORT_ERROR_H
14#define LLVM_SUPPORT_ERROR_H
15
16#include "llvm-c/Error.h"
17#include "llvm/ADT/STLExtras.h"
18#include "llvm/ADT/SmallVector.h"
19#include "llvm/ADT/StringExtras.h"
20#include "llvm/ADT/Twine.h"
21#include "llvm/Config/abi-breaking.h"
22#include "llvm/Support/AlignOf.h"
23#include "llvm/Support/Compiler.h"
24#include "llvm/Support/Debug.h"
25#include "llvm/Support/ErrorHandling.h"
26#include "llvm/Support/ErrorOr.h"
27#include "llvm/Support/Format.h"
28#include "llvm/Support/raw_ostream.h"
29#include <algorithm>
30#include <cassert>
31#include <cstdint>
32#include <cstdlib>
33#include <functional>
34#include <memory>
35#include <new>
36#include <string>
37#include <system_error>
38#include <type_traits>
39#include <utility>
40#include <vector>
41
42namespace llvm {
43
44class ErrorSuccess;
45
46/// Base class for error info classes. Do not extend this directly: Extend
47/// the ErrorInfo template subclass instead.
48class ErrorInfoBase {
49public:
50 virtual ~ErrorInfoBase() = default;
51
52 /// Print an error message to an output stream.
53 virtual void log(raw_ostream &OS) const = 0;
54
55 /// Return the error message as a string.
56 virtual std::string message() const {
57 std::string Msg;
58 raw_string_ostream OS(Msg);
59 log(OS);
60 return OS.str();
61 }
62
63 /// Convert this error to a std::error_code.
64 ///
65 /// This is a temporary crutch to enable interaction with code still
66 /// using std::error_code. It will be removed in the future.
67 virtual std::error_code convertToErrorCode() const = 0;
68
69 // Returns the class ID for this type.
70 static const void *classID() { return &ID; }
71
72 // Returns the class ID for the dynamic type of this ErrorInfoBase instance.
73 virtual const void *dynamicClassID() const = 0;
74
75 // Check whether this instance is a subclass of the class identified by
76 // ClassID.
77 virtual bool isA(const void *const ClassID) const {
78 return ClassID == classID();
79 }
80
81 // Check whether this instance is a subclass of ErrorInfoT.
82 template <typename ErrorInfoT> bool isA() const {
83 return isA(ErrorInfoT::classID());
84 }
85
86private:
87 virtual void anchor();
88
89 static char ID;
90};
91
92/// Lightweight error class with error context and mandatory checking.
93///
94/// Instances of this class wrap a ErrorInfoBase pointer. Failure states
95/// are represented by setting the pointer to a ErrorInfoBase subclass
96/// instance containing information describing the failure. Success is
97/// represented by a null pointer value.
98///
99/// Instances of Error also contains a 'Checked' flag, which must be set
100/// before the destructor is called, otherwise the destructor will trigger a
101/// runtime error. This enforces at runtime the requirement that all Error
102/// instances be checked or returned to the caller.
103///
104/// There are two ways to set the checked flag, depending on what state the
105/// Error instance is in. For Error instances indicating success, it
106/// is sufficient to invoke the boolean conversion operator. E.g.:
107///
108/// @code{.cpp}
109/// Error foo(<...>);
110///
111/// if (auto E = foo(<...>))
112/// return E; // <- Return E if it is in the error state.
113/// // We have verified that E was in the success state. It can now be safely
114/// // destroyed.
115/// @endcode
116///
117/// A success value *can not* be dropped. For example, just calling 'foo(<...>)'
118/// without testing the return value will raise a runtime error, even if foo
119/// returns success.
120///
121/// For Error instances representing failure, you must use either the
122/// handleErrors or handleAllErrors function with a typed handler. E.g.:
123///
124/// @code{.cpp}
125/// class MyErrorInfo : public ErrorInfo<MyErrorInfo> {
126/// // Custom error info.
127/// };
128///
129/// Error foo(<...>) { return make_error<MyErrorInfo>(...); }
130///
131/// auto E = foo(<...>); // <- foo returns failure with MyErrorInfo.
132/// auto NewE =
133/// handleErrors(E,
134/// [](const MyErrorInfo &M) {
135/// // Deal with the error.
136/// },
137/// [](std::unique_ptr<OtherError> M) -> Error {
138/// if (canHandle(*M)) {
139/// // handle error.
140/// return Error::success();
141/// }
142/// // Couldn't handle this error instance. Pass it up the stack.
143/// return Error(std::move(M));
144/// );
145/// // Note - we must check or return NewE in case any of the handlers
146/// // returned a new error.
147/// @endcode
148///
149/// The handleAllErrors function is identical to handleErrors, except
150/// that it has a void return type, and requires all errors to be handled and
151/// no new errors be returned. It prevents errors (assuming they can all be
152/// handled) from having to be bubbled all the way to the top-level.
153///
154/// *All* Error instances must be checked before destruction, even if
155/// they're moved-assigned or constructed from Success values that have already
156/// been checked. This enforces checking through all levels of the call stack.
157class LLVM_NODISCARD[[clang::warn_unused_result]] Error {
158 // Both ErrorList and FileError need to be able to yank ErrorInfoBase
159 // pointers out of this class to add to the error list.
160 friend class ErrorList;
161 friend class FileError;
162
163 // handleErrors needs to be able to set the Checked flag.
164 template <typename... HandlerTs>
165 friend Error handleErrors(Error E, HandlerTs &&... Handlers);
166
167 // Expected<T> needs to be able to steal the payload when constructed from an
168 // error.
169 template <typename T> friend class Expected;
170
171 // wrap needs to be able to steal the payload.
172 friend LLVMErrorRef wrap(Error);
173
174protected:
175 /// Create a success value. Prefer using 'Error::success()' for readability
176 Error() {
177 setPtr(nullptr);
178 setChecked(false);
179 }
180
181public:
182 /// Create a success value.
183 static ErrorSuccess success();
184
185 // Errors are not copy-constructable.
186 Error(const Error &Other) = delete;
187
188 /// Move-construct an error value. The newly constructed error is considered
189 /// unchecked, even if the source error had been checked. The original error
190 /// becomes a checked Success value, regardless of its original state.
191 Error(Error &&Other) {
192 setChecked(true);
193 *this = std::move(Other);
194 }
195
196 /// Create an error value. Prefer using the 'make_error' function, but
197 /// this constructor can be useful when "re-throwing" errors from handlers.
198 Error(std::unique_ptr<ErrorInfoBase> Payload) {
199 setPtr(Payload.release());
200 setChecked(false);
9
Potential leak of memory pointed to by 'Payload._M_t._M_head_impl'
201 }
202
203 // Errors are not copy-assignable.
204 Error &operator=(const Error &Other) = delete;
205
206 /// Move-assign an error value. The current error must represent success, you
207 /// you cannot overwrite an unhandled error. The current error is then
208 /// considered unchecked. The source error becomes a checked success value,
209 /// regardless of its original state.
210 Error &operator=(Error &&Other) {
211 // Don't allow overwriting of unchecked values.
212 assertIsChecked();
213 setPtr(Other.getPtr());
214
215 // This Error is unchecked, even if the source error was checked.
216 setChecked(false);
217
218 // Null out Other's payload and set its checked bit.
219 Other.setPtr(nullptr);
220 Other.setChecked(true);
221
222 return *this;
223 }
224
225 /// Destroy a Error. Fails with a call to abort() if the error is
226 /// unchecked.
227 ~Error() {
228 assertIsChecked();
229 delete getPtr();
230 }
231
232 /// Bool conversion. Returns true if this Error is in a failure state,
233 /// and false if it is in an accept state. If the error is in a Success state
234 /// it will be considered checked.
235 explicit operator bool() {
236 setChecked(getPtr() == nullptr);
237 return getPtr() != nullptr;
238 }
239
240 /// Check whether one error is a subclass of another.
241 template <typename ErrT> bool isA() const {
242 return getPtr() && getPtr()->isA(ErrT::classID());
243 }
244
245 /// Returns the dynamic class id of this error, or null if this is a success
246 /// value.
247 const void* dynamicClassID() const {
248 if (!getPtr())
249 return nullptr;
250 return getPtr()->dynamicClassID();
251 }
252
253private:
254#if LLVM_ENABLE_ABI_BREAKING_CHECKS1
255 // assertIsChecked() happens very frequently, but under normal circumstances
256 // is supposed to be a no-op. So we want it to be inlined, but having a bunch
257 // of debug prints can cause the function to be too large for inlining. So
258 // it's important that we define this function out of line so that it can't be
259 // inlined.
260 LLVM_ATTRIBUTE_NORETURN__attribute__((noreturn))
261 void fatalUncheckedError() const;
262#endif
263
264 void assertIsChecked() {
265#if LLVM_ENABLE_ABI_BREAKING_CHECKS1
266 if (LLVM_UNLIKELY(!getChecked() || getPtr())__builtin_expect((bool)(!getChecked() || getPtr()), false))
267 fatalUncheckedError();
268#endif
269 }
270
271 ErrorInfoBase *getPtr() const {
272 return reinterpret_cast<ErrorInfoBase*>(
273 reinterpret_cast<uintptr_t>(Payload) &
274 ~static_cast<uintptr_t>(0x1));
275 }
276
277 void setPtr(ErrorInfoBase *EI) {
278#if LLVM_ENABLE_ABI_BREAKING_CHECKS1
279 Payload = reinterpret_cast<ErrorInfoBase*>(
280 (reinterpret_cast<uintptr_t>(EI) &
281 ~static_cast<uintptr_t>(0x1)) |
282 (reinterpret_cast<uintptr_t>(Payload) & 0x1));
283#else
284 Payload = EI;
285#endif
286 }
287
288 bool getChecked() const {
289#if LLVM_ENABLE_ABI_BREAKING_CHECKS1
290 return (reinterpret_cast<uintptr_t>(Payload) & 0x1) == 0;
291#else
292 return true;
293#endif
294 }
295
296 void setChecked(bool V) {
297 Payload = reinterpret_cast<ErrorInfoBase*>(
298 (reinterpret_cast<uintptr_t>(Payload) &
299 ~static_cast<uintptr_t>(0x1)) |
300 (V ? 0 : 1));
301 }
302
303 std::unique_ptr<ErrorInfoBase> takePayload() {
304 std::unique_ptr<ErrorInfoBase> Tmp(getPtr());
305 setPtr(nullptr);
306 setChecked(true);
307 return Tmp;
308 }
309
310 friend raw_ostream &operator<<(raw_ostream &OS, const Error &E) {
311 if (auto P = E.getPtr())
312 P->log(OS);
313 else
314 OS << "success";
315 return OS;
316 }
317
318 ErrorInfoBase *Payload = nullptr;
319};
320
321/// Subclass of Error for the sole purpose of identifying the success path in
322/// the type system. This allows to catch invalid conversion to Expected<T> at
323/// compile time.
324class ErrorSuccess final : public Error {};
325
326inline ErrorSuccess Error::success() { return ErrorSuccess(); }
327
328/// Make a Error instance representing failure using the given error info
329/// type.
330template <typename ErrT, typename... ArgTs> Error make_error(ArgTs &&... Args) {
331 return Error(llvm::make_unique<ErrT>(std::forward<ArgTs>(Args)...));
5
Calling 'make_unique<llvm::StringError, const llvm::Twine &, std::error_code>'
7
Returned allocated memory
8
Calling constructor for 'Error'
332}
333
334/// Base class for user error types. Users should declare their error types
335/// like:
336///
337/// class MyError : public ErrorInfo<MyError> {
338/// ....
339/// };
340///
341/// This class provides an implementation of the ErrorInfoBase::kind
342/// method, which is used by the Error RTTI system.
343template <typename ThisErrT, typename ParentErrT = ErrorInfoBase>
344class ErrorInfo : public ParentErrT {
345public:
346 using ParentErrT::ParentErrT; // inherit constructors
347
348 static const void *classID() { return &ThisErrT::ID; }
349
350 const void *dynamicClassID() const override { return &ThisErrT::ID; }
351
352 bool isA(const void *const ClassID) const override {
353 return ClassID == classID() || ParentErrT::isA(ClassID);
354 }
355};
356
357/// Special ErrorInfo subclass representing a list of ErrorInfos.
358/// Instances of this class are constructed by joinError.
359class ErrorList final : public ErrorInfo<ErrorList> {
360 // handleErrors needs to be able to iterate the payload list of an
361 // ErrorList.
362 template <typename... HandlerTs>
363 friend Error handleErrors(Error E, HandlerTs &&... Handlers);
364
365 // joinErrors is implemented in terms of join.
366 friend Error joinErrors(Error, Error);
367
368public:
369 void log(raw_ostream &OS) const override {
370 OS << "Multiple errors:\n";
371 for (auto &ErrPayload : Payloads) {
372 ErrPayload->log(OS);
373 OS << "\n";
374 }
375 }
376
377 std::error_code convertToErrorCode() const override;
378
379 // Used by ErrorInfo::classID.
380 static char ID;
381
382private:
383 ErrorList(std::unique_ptr<ErrorInfoBase> Payload1,
384 std::unique_ptr<ErrorInfoBase> Payload2) {
385 assert(!Payload1->isA<ErrorList>() && !Payload2->isA<ErrorList>() &&((!Payload1->isA<ErrorList>() && !Payload2->
isA<ErrorList>() && "ErrorList constructor payloads should be singleton errors"
) ? static_cast<void> (0) : __assert_fail ("!Payload1->isA<ErrorList>() && !Payload2->isA<ErrorList>() && \"ErrorList constructor payloads should be singleton errors\""
, "/build/llvm-toolchain-snapshot-9~svn362543/include/llvm/Support/Error.h"
, 386, __PRETTY_FUNCTION__))
386 "ErrorList constructor payloads should be singleton errors")((!Payload1->isA<ErrorList>() && !Payload2->
isA<ErrorList>() && "ErrorList constructor payloads should be singleton errors"
) ? static_cast<void> (0) : __assert_fail ("!Payload1->isA<ErrorList>() && !Payload2->isA<ErrorList>() && \"ErrorList constructor payloads should be singleton errors\""
, "/build/llvm-toolchain-snapshot-9~svn362543/include/llvm/Support/Error.h"
, 386, __PRETTY_FUNCTION__))
;
387 Payloads.push_back(std::move(Payload1));
388 Payloads.push_back(std::move(Payload2));
389 }
390
391 static Error join(Error E1, Error E2) {
392 if (!E1)
393 return E2;
394 if (!E2)
395 return E1;
396 if (E1.isA<ErrorList>()) {
397 auto &E1List = static_cast<ErrorList &>(*E1.getPtr());
398 if (E2.isA<ErrorList>()) {
399 auto E2Payload = E2.takePayload();
400 auto &E2List = static_cast<ErrorList &>(*E2Payload);
401 for (auto &Payload : E2List.Payloads)
402 E1List.Payloads.push_back(std::move(Payload));
403 } else
404 E1List.Payloads.push_back(E2.takePayload());
405
406 return E1;
407 }
408 if (E2.isA<ErrorList>()) {
409 auto &E2List = static_cast<ErrorList &>(*E2.getPtr());
410 E2List.Payloads.insert(E2List.Payloads.begin(), E1.takePayload());
411 return E2;
412 }
413 return Error(std::unique_ptr<ErrorList>(
414 new ErrorList(E1.takePayload(), E2.takePayload())));
415 }
416
417 std::vector<std::unique_ptr<ErrorInfoBase>> Payloads;
418};
419
420/// Concatenate errors. The resulting Error is unchecked, and contains the
421/// ErrorInfo(s), if any, contained in E1, followed by the
422/// ErrorInfo(s), if any, contained in E2.
423inline Error joinErrors(Error E1, Error E2) {
424 return ErrorList::join(std::move(E1), std::move(E2));
425}
426
427/// Tagged union holding either a T or a Error.
428///
429/// This class parallels ErrorOr, but replaces error_code with Error. Since
430/// Error cannot be copied, this class replaces getError() with
431/// takeError(). It also adds an bool errorIsA<ErrT>() method for testing the
432/// error class type.
433template <class T> class LLVM_NODISCARD[[clang::warn_unused_result]] Expected {
434 template <class T1> friend class ExpectedAsOutParameter;
435 template <class OtherT> friend class Expected;
436
437 static const bool isRef = std::is_reference<T>::value;
438
439 using wrap = std::reference_wrapper<typename std::remove_reference<T>::type>;
440
441 using error_type = std::unique_ptr<ErrorInfoBase>;
442
443public:
444 using storage_type = typename std::conditional<isRef, wrap, T>::type;
445 using value_type = T;
446
447private:
448 using reference = typename std::remove_reference<T>::type &;
449 using const_reference = const typename std::remove_reference<T>::type &;
450 using pointer = typename std::remove_reference<T>::type *;
451 using const_pointer = const typename std::remove_reference<T>::type *;
452
453public:
454 /// Create an Expected<T> error value from the given Error.
455 Expected(Error Err)
456 : HasError(true)
457#if LLVM_ENABLE_ABI_BREAKING_CHECKS1
458 // Expected is unchecked upon construction in Debug builds.
459 , Unchecked(true)
460#endif
461 {
462 assert(Err && "Cannot create Expected<T> from Error success value.")((Err && "Cannot create Expected<T> from Error success value."
) ? static_cast<void> (0) : __assert_fail ("Err && \"Cannot create Expected<T> from Error success value.\""
, "/build/llvm-toolchain-snapshot-9~svn362543/include/llvm/Support/Error.h"
, 462, __PRETTY_FUNCTION__))
;
463 new (getErrorStorage()) error_type(Err.takePayload());
464 }
465
466 /// Forbid to convert from Error::success() implicitly, this avoids having
467 /// Expected<T> foo() { return Error::success(); } which compiles otherwise
468 /// but triggers the assertion above.
469 Expected(ErrorSuccess) = delete;
470
471 /// Create an Expected<T> success value from the given OtherT value, which
472 /// must be convertible to T.
473 template <typename OtherT>
474 Expected(OtherT &&Val,
475 typename std::enable_if<std::is_convertible<OtherT, T>::value>::type
476 * = nullptr)
477 : HasError(false)
478#if LLVM_ENABLE_ABI_BREAKING_CHECKS1
479 // Expected is unchecked upon construction in Debug builds.
480 , Unchecked(true)
481#endif
482 {
483 new (getStorage()) storage_type(std::forward<OtherT>(Val));
484 }
485
486 /// Move construct an Expected<T> value.
487 Expected(Expected &&Other) { moveConstruct(std::move(Other)); }
488
489 /// Move construct an Expected<T> value from an Expected<OtherT>, where OtherT
490 /// must be convertible to T.
491 template <class OtherT>
492 Expected(Expected<OtherT> &&Other,
493 typename std::enable_if<std::is_convertible<OtherT, T>::value>::type
494 * = nullptr) {
495 moveConstruct(std::move(Other));
496 }
497
498 /// Move construct an Expected<T> value from an Expected<OtherT>, where OtherT
499 /// isn't convertible to T.
500 template <class OtherT>
501 explicit Expected(
502 Expected<OtherT> &&Other,
503 typename std::enable_if<!std::is_convertible<OtherT, T>::value>::type * =
504 nullptr) {
505 moveConstruct(std::move(Other));
506 }
507
508 /// Move-assign from another Expected<T>.
509 Expected &operator=(Expected &&Other) {
510 moveAssign(std::move(Other));
511 return *this;
512 }
513
514 /// Destroy an Expected<T>.
515 ~Expected() {
516 assertIsChecked();
517 if (!HasError)
518 getStorage()->~storage_type();
519 else
520 getErrorStorage()->~error_type();
521 }
522
523 /// Return false if there is an error.
524 explicit operator bool() {
525#if LLVM_ENABLE_ABI_BREAKING_CHECKS1
526 Unchecked = HasError;
527#endif
528 return !HasError;
529 }
530
531 /// Returns a reference to the stored T value.
532 reference get() {
533 assertIsChecked();
534 return *getStorage();
535 }
536
537 /// Returns a const reference to the stored T value.
538 const_reference get() const {
539 assertIsChecked();
540 return const_cast<Expected<T> *>(this)->get();
541 }
542
543 /// Check that this Expected<T> is an error of type ErrT.
544 template <typename ErrT> bool errorIsA() const {
545 return HasError && (*getErrorStorage())->template isA<ErrT>();
546 }
547
548 /// Take ownership of the stored error.
549 /// After calling this the Expected<T> is in an indeterminate state that can
550 /// only be safely destructed. No further calls (beside the destructor) should
551 /// be made on the Expected<T> vaule.
552 Error takeError() {
553#if LLVM_ENABLE_ABI_BREAKING_CHECKS1
554 Unchecked = false;
555#endif
556 return HasError ? Error(std::move(*getErrorStorage())) : Error::success();
557 }
558
559 /// Returns a pointer to the stored T value.
560 pointer operator->() {
561 assertIsChecked();
562 return toPointer(getStorage());
563 }
564
565 /// Returns a const pointer to the stored T value.
566 const_pointer operator->() const {
567 assertIsChecked();
568 return toPointer(getStorage());
569 }
570
571 /// Returns a reference to the stored T value.
572 reference operator*() {
573 assertIsChecked();
574 return *getStorage();
575 }
576
577 /// Returns a const reference to the stored T value.
578 const_reference operator*() const {
579 assertIsChecked();
580 return *getStorage();
581 }
582
583private:
584 template <class T1>
585 static bool compareThisIfSameType(const T1 &a, const T1 &b) {
586 return &a == &b;
587 }
588
589 template <class T1, class T2>
590 static bool compareThisIfSameType(const T1 &a, const T2 &b) {
591 return false;
592 }
593
594 template <class OtherT> void moveConstruct(Expected<OtherT> &&Other) {
595 HasError = Other.HasError;
596#if LLVM_ENABLE_ABI_BREAKING_CHECKS1
597 Unchecked = true;
598 Other.Unchecked = false;
599#endif
600
601 if (!HasError)
602 new (getStorage()) storage_type(std::move(*Other.getStorage()));
603 else
604 new (getErrorStorage()) error_type(std::move(*Other.getErrorStorage()));
605 }
606
607 template <class OtherT> void moveAssign(Expected<OtherT> &&Other) {
608 assertIsChecked();
609
610 if (compareThisIfSameType(*this, Other))
611 return;
612
613 this->~Expected();
614 new (this) Expected(std::move(Other));
615 }
616
617 pointer toPointer(pointer Val) { return Val; }
618
619 const_pointer toPointer(const_pointer Val) const { return Val; }
620
621 pointer toPointer(wrap *Val) { return &Val->get(); }
622
623 const_pointer toPointer(const wrap *Val) const { return &Val->get(); }
624
625 storage_type *getStorage() {
626 assert(!HasError && "Cannot get value when an error exists!")((!HasError && "Cannot get value when an error exists!"
) ? static_cast<void> (0) : __assert_fail ("!HasError && \"Cannot get value when an error exists!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/include/llvm/Support/Error.h"
, 626, __PRETTY_FUNCTION__))
;
627 return reinterpret_cast<storage_type *>(TStorage.buffer);
628 }
629
630 const storage_type *getStorage() const {
631 assert(!HasError && "Cannot get value when an error exists!")((!HasError && "Cannot get value when an error exists!"
) ? static_cast<void> (0) : __assert_fail ("!HasError && \"Cannot get value when an error exists!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/include/llvm/Support/Error.h"
, 631, __PRETTY_FUNCTION__))
;
632 return reinterpret_cast<const storage_type *>(TStorage.buffer);
633 }
634
635 error_type *getErrorStorage() {
636 assert(HasError && "Cannot get error when a value exists!")((HasError && "Cannot get error when a value exists!"
) ? static_cast<void> (0) : __assert_fail ("HasError && \"Cannot get error when a value exists!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/include/llvm/Support/Error.h"
, 636, __PRETTY_FUNCTION__))
;
637 return reinterpret_cast<error_type *>(ErrorStorage.buffer);
638 }
639
640 const error_type *getErrorStorage() const {
641 assert(HasError && "Cannot get error when a value exists!")((HasError && "Cannot get error when a value exists!"
) ? static_cast<void> (0) : __assert_fail ("HasError && \"Cannot get error when a value exists!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/include/llvm/Support/Error.h"
, 641, __PRETTY_FUNCTION__))
;
642 return reinterpret_cast<const error_type *>(ErrorStorage.buffer);
643 }
644
645 // Used by ExpectedAsOutParameter to reset the checked flag.
646 void setUnchecked() {
647#if LLVM_ENABLE_ABI_BREAKING_CHECKS1
648 Unchecked = true;
649#endif
650 }
651
652#if LLVM_ENABLE_ABI_BREAKING_CHECKS1
653 LLVM_ATTRIBUTE_NORETURN__attribute__((noreturn))
654 LLVM_ATTRIBUTE_NOINLINE__attribute__((noinline))
655 void fatalUncheckedExpected() const {
656 dbgs() << "Expected<T> must be checked before access or destruction.\n";
657 if (HasError) {
658 dbgs() << "Unchecked Expected<T> contained error:\n";
659 (*getErrorStorage())->log(dbgs());
660 } else
661 dbgs() << "Expected<T> value was in success state. (Note: Expected<T> "
662 "values in success mode must still be checked prior to being "
663 "destroyed).\n";
664 abort();
665 }
666#endif
667
668 void assertIsChecked() {
669#if LLVM_ENABLE_ABI_BREAKING_CHECKS1
670 if (LLVM_UNLIKELY(Unchecked)__builtin_expect((bool)(Unchecked), false))
671 fatalUncheckedExpected();
672#endif
673 }
674
675 union {
676 AlignedCharArrayUnion<storage_type> TStorage;
677 AlignedCharArrayUnion<error_type> ErrorStorage;
678 };
679 bool HasError : 1;
680#if LLVM_ENABLE_ABI_BREAKING_CHECKS1
681 bool Unchecked : 1;
682#endif
683};
684
685/// Report a serious error, calling any installed error handler. See
686/// ErrorHandling.h.
687LLVM_ATTRIBUTE_NORETURN__attribute__((noreturn)) void report_fatal_error(Error Err,
688 bool gen_crash_diag = true);
689
690/// Report a fatal error if Err is a failure value.
691///
692/// This function can be used to wrap calls to fallible functions ONLY when it
693/// is known that the Error will always be a success value. E.g.
694///
695/// @code{.cpp}
696/// // foo only attempts the fallible operation if DoFallibleOperation is
697/// // true. If DoFallibleOperation is false then foo always returns
698/// // Error::success().
699/// Error foo(bool DoFallibleOperation);
700///
701/// cantFail(foo(false));
702/// @endcode
703inline void cantFail(Error Err, const char *Msg = nullptr) {
704 if (Err) {
705 if (!Msg)
706 Msg = "Failure value returned from cantFail wrapped call";
707 llvm_unreachable(Msg)::llvm::llvm_unreachable_internal(Msg, "/build/llvm-toolchain-snapshot-9~svn362543/include/llvm/Support/Error.h"
, 707)
;
708 }
709}
710
711/// Report a fatal error if ValOrErr is a failure value, otherwise unwraps and
712/// returns the contained value.
713///
714/// This function can be used to wrap calls to fallible functions ONLY when it
715/// is known that the Error will always be a success value. E.g.
716///
717/// @code{.cpp}
718/// // foo only attempts the fallible operation if DoFallibleOperation is
719/// // true. If DoFallibleOperation is false then foo always returns an int.
720/// Expected<int> foo(bool DoFallibleOperation);
721///
722/// int X = cantFail(foo(false));
723/// @endcode
724template <typename T>
725T cantFail(Expected<T> ValOrErr, const char *Msg = nullptr) {
726 if (ValOrErr)
727 return std::move(*ValOrErr);
728 else {
729 if (!Msg)
730 Msg = "Failure value returned from cantFail wrapped call";
731 llvm_unreachable(Msg)::llvm::llvm_unreachable_internal(Msg, "/build/llvm-toolchain-snapshot-9~svn362543/include/llvm/Support/Error.h"
, 731)
;
732 }
733}
734
735/// Report a fatal error if ValOrErr is a failure value, otherwise unwraps and
736/// returns the contained reference.
737///
738/// This function can be used to wrap calls to fallible functions ONLY when it
739/// is known that the Error will always be a success value. E.g.
740///
741/// @code{.cpp}
742/// // foo only attempts the fallible operation if DoFallibleOperation is
743/// // true. If DoFallibleOperation is false then foo always returns a Bar&.
744/// Expected<Bar&> foo(bool DoFallibleOperation);
745///
746/// Bar &X = cantFail(foo(false));
747/// @endcode
748template <typename T>
749T& cantFail(Expected<T&> ValOrErr, const char *Msg = nullptr) {
750 if (ValOrErr)
751 return *ValOrErr;
752 else {
753 if (!Msg)
754 Msg = "Failure value returned from cantFail wrapped call";
755 llvm_unreachable(Msg)::llvm::llvm_unreachable_internal(Msg, "/build/llvm-toolchain-snapshot-9~svn362543/include/llvm/Support/Error.h"
, 755)
;
756 }
757}
758
759/// Helper for testing applicability of, and applying, handlers for
760/// ErrorInfo types.
761template <typename HandlerT>
762class ErrorHandlerTraits
763 : public ErrorHandlerTraits<decltype(
764 &std::remove_reference<HandlerT>::type::operator())> {};
765
766// Specialization functions of the form 'Error (const ErrT&)'.
767template <typename ErrT> class ErrorHandlerTraits<Error (&)(ErrT &)> {
768public:
769 static bool appliesTo(const ErrorInfoBase &E) {
770 return E.template isA<ErrT>();
771 }
772
773 template <typename HandlerT>
774 static Error apply(HandlerT &&H, std::unique_ptr<ErrorInfoBase> E) {
775 assert(appliesTo(*E) && "Applying incorrect handler")((appliesTo(*E) && "Applying incorrect handler") ? static_cast
<void> (0) : __assert_fail ("appliesTo(*E) && \"Applying incorrect handler\""
, "/build/llvm-toolchain-snapshot-9~svn362543/include/llvm/Support/Error.h"
, 775, __PRETTY_FUNCTION__))
;
776 return H(static_cast<ErrT &>(*E));
777 }
778};
779
780// Specialization functions of the form 'void (const ErrT&)'.
781template <typename ErrT> class ErrorHandlerTraits<void (&)(ErrT &)> {
782public:
783 static bool appliesTo(const ErrorInfoBase &E) {
784 return E.template isA<ErrT>();
785 }
786
787 template <typename HandlerT>
788 static Error apply(HandlerT &&H, std::unique_ptr<ErrorInfoBase> E) {
789 assert(appliesTo(*E) && "Applying incorrect handler")((appliesTo(*E) && "Applying incorrect handler") ? static_cast
<void> (0) : __assert_fail ("appliesTo(*E) && \"Applying incorrect handler\""
, "/build/llvm-toolchain-snapshot-9~svn362543/include/llvm/Support/Error.h"
, 789, __PRETTY_FUNCTION__))
;
790 H(static_cast<ErrT &>(*E));
791 return Error::success();
792 }
793};
794
795/// Specialization for functions of the form 'Error (std::unique_ptr<ErrT>)'.
796template <typename ErrT>
797class ErrorHandlerTraits<Error (&)(std::unique_ptr<ErrT>)> {
798public:
799 static bool appliesTo(const ErrorInfoBase &E) {
800 return E.template isA<ErrT>();
801 }
802
803 template <typename HandlerT>
804 static Error apply(HandlerT &&H, std::unique_ptr<ErrorInfoBase> E) {
805 assert(appliesTo(*E) && "Applying incorrect handler")((appliesTo(*E) && "Applying incorrect handler") ? static_cast
<void> (0) : __assert_fail ("appliesTo(*E) && \"Applying incorrect handler\""
, "/build/llvm-toolchain-snapshot-9~svn362543/include/llvm/Support/Error.h"
, 805, __PRETTY_FUNCTION__))
;
806 std::unique_ptr<ErrT> SubE(static_cast<ErrT *>(E.release()));
807 return H(std::move(SubE));
808 }
809};
810
811/// Specialization for functions of the form 'void (std::unique_ptr<ErrT>)'.
812template <typename ErrT>
813class ErrorHandlerTraits<void (&)(std::unique_ptr<ErrT>)> {
814public:
815 static bool appliesTo(const ErrorInfoBase &E) {
816 return E.template isA<ErrT>();
817 }
818
819 template <typename HandlerT>
820 static Error apply(HandlerT &&H, std::unique_ptr<ErrorInfoBase> E) {
821 assert(appliesTo(*E) && "Applying incorrect handler")((appliesTo(*E) && "Applying incorrect handler") ? static_cast
<void> (0) : __assert_fail ("appliesTo(*E) && \"Applying incorrect handler\""
, "/build/llvm-toolchain-snapshot-9~svn362543/include/llvm/Support/Error.h"
, 821, __PRETTY_FUNCTION__))
;
822 std::unique_ptr<ErrT> SubE(static_cast<ErrT *>(E.release()));
823 H(std::move(SubE));
824 return Error::success();
825 }
826};
827
828// Specialization for member functions of the form 'RetT (const ErrT&)'.
829template <typename C, typename RetT, typename ErrT>
830class ErrorHandlerTraits<RetT (C::*)(ErrT &)>
831 : public ErrorHandlerTraits<RetT (&)(ErrT &)> {};
832
833// Specialization for member functions of the form 'RetT (const ErrT&) const'.
834template <typename C, typename RetT, typename ErrT>
835class ErrorHandlerTraits<RetT (C::*)(ErrT &) const>
836 : public ErrorHandlerTraits<RetT (&)(ErrT &)> {};
837
838// Specialization for member functions of the form 'RetT (const ErrT&)'.
839template <typename C, typename RetT, typename ErrT>
840class ErrorHandlerTraits<RetT (C::*)(const ErrT &)>
841 : public ErrorHandlerTraits<RetT (&)(ErrT &)> {};
842
843// Specialization for member functions of the form 'RetT (const ErrT&) const'.
844template <typename C, typename RetT, typename ErrT>
845class ErrorHandlerTraits<RetT (C::*)(const ErrT &) const>
846 : public ErrorHandlerTraits<RetT (&)(ErrT &)> {};
847
848/// Specialization for member functions of the form
849/// 'RetT (std::unique_ptr<ErrT>)'.
850template <typename C, typename RetT, typename ErrT>
851class ErrorHandlerTraits<RetT (C::*)(std::unique_ptr<ErrT>)>
852 : public ErrorHandlerTraits<RetT (&)(std::unique_ptr<ErrT>)> {};
853
854/// Specialization for member functions of the form
855/// 'RetT (std::unique_ptr<ErrT>) const'.
856template <typename C, typename RetT, typename ErrT>
857class ErrorHandlerTraits<RetT (C::*)(std::unique_ptr<ErrT>) const>
858 : public ErrorHandlerTraits<RetT (&)(std::unique_ptr<ErrT>)> {};
859
860inline Error handleErrorImpl(std::unique_ptr<ErrorInfoBase> Payload) {
861 return Error(std::move(Payload));
862}
863
864template <typename HandlerT, typename... HandlerTs>
865Error handleErrorImpl(std::unique_ptr<ErrorInfoBase> Payload,
866 HandlerT &&Handler, HandlerTs &&... Handlers) {
867 if (ErrorHandlerTraits<HandlerT>::appliesTo(*Payload))
868 return ErrorHandlerTraits<HandlerT>::apply(std::forward<HandlerT>(Handler),
869 std::move(Payload));
870 return handleErrorImpl(std::move(Payload),
871 std::forward<HandlerTs>(Handlers)...);
872}
873
874/// Pass the ErrorInfo(s) contained in E to their respective handlers. Any
875/// unhandled errors (or Errors returned by handlers) are re-concatenated and
876/// returned.
877/// Because this function returns an error, its result must also be checked
878/// or returned. If you intend to handle all errors use handleAllErrors
879/// (which returns void, and will abort() on unhandled errors) instead.
880template <typename... HandlerTs>
881Error handleErrors(Error E, HandlerTs &&... Hs) {
882 if (!E)
883 return Error::success();
884
885 std::unique_ptr<ErrorInfoBase> Payload = E.takePayload();
886
887 if (Payload->isA<ErrorList>()) {
888 ErrorList &List = static_cast<ErrorList &>(*Payload);
889 Error R;
890 for (auto &P : List.Payloads)
891 R = ErrorList::join(
892 std::move(R),
893 handleErrorImpl(std::move(P), std::forward<HandlerTs>(Hs)...));
894 return R;
895 }
896
897 return handleErrorImpl(std::move(Payload), std::forward<HandlerTs>(Hs)...);
898}
899
900/// Behaves the same as handleErrors, except that by contract all errors
901/// *must* be handled by the given handlers (i.e. there must be no remaining
902/// errors after running the handlers, or llvm_unreachable is called).
903template <typename... HandlerTs>
904void handleAllErrors(Error E, HandlerTs &&... Handlers) {
905 cantFail(handleErrors(std::move(E), std::forward<HandlerTs>(Handlers)...));
906}
907
908/// Check that E is a non-error, then drop it.
909/// If E is an error, llvm_unreachable will be called.
910inline void handleAllErrors(Error E) {
911 cantFail(std::move(E));
912}
913
914/// Handle any errors (if present) in an Expected<T>, then try a recovery path.
915///
916/// If the incoming value is a success value it is returned unmodified. If it
917/// is a failure value then it the contained error is passed to handleErrors.
918/// If handleErrors is able to handle the error then the RecoveryPath functor
919/// is called to supply the final result. If handleErrors is not able to
920/// handle all errors then the unhandled errors are returned.
921///
922/// This utility enables the follow pattern:
923///
924/// @code{.cpp}
925/// enum FooStrategy { Aggressive, Conservative };
926/// Expected<Foo> foo(FooStrategy S);
927///
928/// auto ResultOrErr =
929/// handleExpected(
930/// foo(Aggressive),
931/// []() { return foo(Conservative); },
932/// [](AggressiveStrategyError&) {
933/// // Implicitly conusme this - we'll recover by using a conservative
934/// // strategy.
935/// });
936///
937/// @endcode
938template <typename T, typename RecoveryFtor, typename... HandlerTs>
939Expected<T> handleExpected(Expected<T> ValOrErr, RecoveryFtor &&RecoveryPath,
940 HandlerTs &&... Handlers) {
941 if (ValOrErr)
942 return ValOrErr;
943
944 if (auto Err = handleErrors(ValOrErr.takeError(),
945 std::forward<HandlerTs>(Handlers)...))
946 return std::move(Err);
947
948 return RecoveryPath();
949}
950
951/// Log all errors (if any) in E to OS. If there are any errors, ErrorBanner
952/// will be printed before the first one is logged. A newline will be printed
953/// after each error.
954///
955/// This function is compatible with the helpers from Support/WithColor.h. You
956/// can pass any of them as the OS. Please consider using them instead of
957/// including 'error: ' in the ErrorBanner.
958///
959/// This is useful in the base level of your program to allow clean termination
960/// (allowing clean deallocation of resources, etc.), while reporting error
961/// information to the user.
962void logAllUnhandledErrors(Error E, raw_ostream &OS, Twine ErrorBanner = {});
963
964/// Write all error messages (if any) in E to a string. The newline character
965/// is used to separate error messages.
966inline std::string toString(Error E) {
967 SmallVector<std::string, 2> Errors;
968 handleAllErrors(std::move(E), [&Errors](const ErrorInfoBase &EI) {
969 Errors.push_back(EI.message());
970 });
971 return join(Errors.begin(), Errors.end(), "\n");
972}
973
974/// Consume a Error without doing anything. This method should be used
975/// only where an error can be considered a reasonable and expected return
976/// value.
977///
978/// Uses of this method are potentially indicative of design problems: If it's
979/// legitimate to do nothing while processing an "error", the error-producer
980/// might be more clearly refactored to return an Optional<T>.
981inline void consumeError(Error Err) {
982 handleAllErrors(std::move(Err), [](const ErrorInfoBase &) {});
983}
984
985/// Helper for converting an Error to a bool.
986///
987/// This method returns true if Err is in an error state, or false if it is
988/// in a success state. Puts Err in a checked state in both cases (unlike
989/// Error::operator bool(), which only does this for success states).
990inline bool errorToBool(Error Err) {
991 bool IsError = static_cast<bool>(Err);
992 if (IsError)
993 consumeError(std::move(Err));
994 return IsError;
995}
996
997/// Helper for Errors used as out-parameters.
998///
999/// This helper is for use with the Error-as-out-parameter idiom, where an error
1000/// is passed to a function or method by reference, rather than being returned.
1001/// In such cases it is helpful to set the checked bit on entry to the function
1002/// so that the error can be written to (unchecked Errors abort on assignment)
1003/// and clear the checked bit on exit so that clients cannot accidentally forget
1004/// to check the result. This helper performs these actions automatically using
1005/// RAII:
1006///
1007/// @code{.cpp}
1008/// Result foo(Error &Err) {
1009/// ErrorAsOutParameter ErrAsOutParam(&Err); // 'Checked' flag set
1010/// // <body of foo>
1011/// // <- 'Checked' flag auto-cleared when ErrAsOutParam is destructed.
1012/// }
1013/// @endcode
1014///
1015/// ErrorAsOutParameter takes an Error* rather than Error& so that it can be
1016/// used with optional Errors (Error pointers that are allowed to be null). If
1017/// ErrorAsOutParameter took an Error reference, an instance would have to be
1018/// created inside every condition that verified that Error was non-null. By
1019/// taking an Error pointer we can just create one instance at the top of the
1020/// function.
1021class ErrorAsOutParameter {
1022public:
1023 ErrorAsOutParameter(Error *Err) : Err(Err) {
1024 // Raise the checked bit if Err is success.
1025 if (Err)
1026 (void)!!*Err;
1027 }
1028
1029 ~ErrorAsOutParameter() {
1030 // Clear the checked bit.
1031 if (Err && !*Err)
1032 *Err = Error::success();
1033 }
1034
1035private:
1036 Error *Err;
1037};
1038
1039/// Helper for Expected<T>s used as out-parameters.
1040///
1041/// See ErrorAsOutParameter.
1042template <typename T>
1043class ExpectedAsOutParameter {
1044public:
1045 ExpectedAsOutParameter(Expected<T> *ValOrErr)
1046 : ValOrErr(ValOrErr) {
1047 if (ValOrErr)
1048 (void)!!*ValOrErr;
1049 }
1050
1051 ~ExpectedAsOutParameter() {
1052 if (ValOrErr)
1053 ValOrErr->setUnchecked();
1054 }
1055
1056private:
1057 Expected<T> *ValOrErr;
1058};
1059
1060/// This class wraps a std::error_code in a Error.
1061///
1062/// This is useful if you're writing an interface that returns a Error
1063/// (or Expected) and you want to call code that still returns
1064/// std::error_codes.
1065class ECError : public ErrorInfo<ECError> {
1066 friend Error errorCodeToError(std::error_code);
1067
1068 virtual void anchor() override;
1069
1070public:
1071 void setErrorCode(std::error_code EC) { this->EC = EC; }
1072 std::error_code convertToErrorCode() const override { return EC; }
1073 void log(raw_ostream &OS) const override { OS << EC.message(); }
1074
1075 // Used by ErrorInfo::classID.
1076 static char ID;
1077
1078protected:
1079 ECError() = default;
1080 ECError(std::error_code EC) : EC(EC) {}
1081
1082 std::error_code EC;
1083};
1084
1085/// The value returned by this function can be returned from convertToErrorCode
1086/// for Error values where no sensible translation to std::error_code exists.
1087/// It should only be used in this situation, and should never be used where a
1088/// sensible conversion to std::error_code is available, as attempts to convert
1089/// to/from this error will result in a fatal error. (i.e. it is a programmatic
1090///error to try to convert such a value).
1091std::error_code inconvertibleErrorCode();
1092
1093/// Helper for converting an std::error_code to a Error.
1094Error errorCodeToError(std::error_code EC);
1095
1096/// Helper for converting an ECError to a std::error_code.
1097///
1098/// This method requires that Err be Error() or an ECError, otherwise it
1099/// will trigger a call to abort().
1100std::error_code errorToErrorCode(Error Err);
1101
1102/// Convert an ErrorOr<T> to an Expected<T>.
1103template <typename T> Expected<T> errorOrToExpected(ErrorOr<T> &&EO) {
1104 if (auto EC = EO.getError())
1105 return errorCodeToError(EC);
1106 return std::move(*EO);
1107}
1108
1109/// Convert an Expected<T> to an ErrorOr<T>.
1110template <typename T> ErrorOr<T> expectedToErrorOr(Expected<T> &&E) {
1111 if (auto Err = E.takeError())
1112 return errorToErrorCode(std::move(Err));
1113 return std::move(*E);
1114}
1115
1116/// This class wraps a string in an Error.
1117///
1118/// StringError is useful in cases where the client is not expected to be able
1119/// to consume the specific error message programmatically (for example, if the
1120/// error message is to be presented to the user).
1121///
1122/// StringError can also be used when additional information is to be printed
1123/// along with a error_code message. Depending on the constructor called, this
1124/// class can either display:
1125/// 1. the error_code message (ECError behavior)
1126/// 2. a string
1127/// 3. the error_code message and a string
1128///
1129/// These behaviors are useful when subtyping is required; for example, when a
1130/// specific library needs an explicit error type. In the example below,
1131/// PDBError is derived from StringError:
1132///
1133/// @code{.cpp}
1134/// Expected<int> foo() {
1135/// return llvm::make_error<PDBError>(pdb_error_code::dia_failed_loading,
1136/// "Additional information");
1137/// }
1138/// @endcode
1139///
1140class StringError : public ErrorInfo<StringError> {
1141public:
1142 static char ID;
1143
1144 // Prints EC + S and converts to EC
1145 StringError(std::error_code EC, const Twine &S = Twine());
1146
1147 // Prints S and converts to EC
1148 StringError(const Twine &S, std::error_code EC);
1149
1150 void log(raw_ostream &OS) const override;
1151 std::error_code convertToErrorCode() const override;
1152
1153 const std::string &getMessage() const { return Msg; }
1154
1155private:
1156 std::string Msg;
1157 std::error_code EC;
1158 const bool PrintMsgOnly = false;
1159};
1160
1161/// Create formatted StringError object.
1162template <typename... Ts>
1163Error createStringError(std::error_code EC, char const *Fmt,
1164 const Ts &... Vals) {
1165 std::string Buffer;
1166 raw_string_ostream Stream(Buffer);
1167 Stream << format(Fmt, Vals...);
1168 return make_error<StringError>(Stream.str(), EC);
1169}
1170
1171Error createStringError(std::error_code EC, char const *Msg);
1172
1173/// This class wraps a filename and another Error.
1174///
1175/// In some cases, an error needs to live along a 'source' name, in order to
1176/// show more detailed information to the user.
1177class FileError final : public ErrorInfo<FileError> {
1178
1179 friend Error createFileError(const Twine &, Error);
1180 friend Error createFileError(const Twine &, size_t, Error);
1181
1182public:
1183 void log(raw_ostream &OS) const override {
1184 assert(Err && !FileName.empty() && "Trying to log after takeError().")((Err && !FileName.empty() && "Trying to log after takeError()."
) ? static_cast<void> (0) : __assert_fail ("Err && !FileName.empty() && \"Trying to log after takeError().\""
, "/build/llvm-toolchain-snapshot-9~svn362543/include/llvm/Support/Error.h"
, 1184, __PRETTY_FUNCTION__))
;
1185 OS << "'" << FileName << "': ";
1186 if (Line.hasValue())
1187 OS << "line " << Line.getValue() << ": ";
1188 Err->log(OS);
1189 }
1190
1191 Error takeError() { return Error(std::move(Err)); }
1192
1193 std::error_code convertToErrorCode() const override;
1194
1195 // Used by ErrorInfo::classID.
1196 static char ID;
1197
1198private:
1199 FileError(const Twine &F, Optional<size_t> LineNum,
1200 std::unique_ptr<ErrorInfoBase> E) {
1201 assert(E && "Cannot create FileError from Error success value.")((E && "Cannot create FileError from Error success value."
) ? static_cast<void> (0) : __assert_fail ("E && \"Cannot create FileError from Error success value.\""
, "/build/llvm-toolchain-snapshot-9~svn362543/include/llvm/Support/Error.h"
, 1201, __PRETTY_FUNCTION__))
;
1202 assert(!F.isTriviallyEmpty() &&((!F.isTriviallyEmpty() && "The file name provided to FileError must not be empty."
) ? static_cast<void> (0) : __assert_fail ("!F.isTriviallyEmpty() && \"The file name provided to FileError must not be empty.\""
, "/build/llvm-toolchain-snapshot-9~svn362543/include/llvm/Support/Error.h"
, 1203, __PRETTY_FUNCTION__))
1203 "The file name provided to FileError must not be empty.")((!F.isTriviallyEmpty() && "The file name provided to FileError must not be empty."
) ? static_cast<void> (0) : __assert_fail ("!F.isTriviallyEmpty() && \"The file name provided to FileError must not be empty.\""
, "/build/llvm-toolchain-snapshot-9~svn362543/include/llvm/Support/Error.h"
, 1203, __PRETTY_FUNCTION__))
;
1204 FileName = F.str();
1205 Err = std::move(E);
1206 Line = std::move(LineNum);
1207 }
1208
1209 static Error build(const Twine &F, Optional<size_t> Line, Error E) {
1210 return Error(
1211 std::unique_ptr<FileError>(new FileError(F, Line, E.takePayload())));
1212 }
1213
1214 std::string FileName;
1215 Optional<size_t> Line;
1216 std::unique_ptr<ErrorInfoBase> Err;
1217};
1218
1219/// Concatenate a source file path and/or name with an Error. The resulting
1220/// Error is unchecked.
1221inline Error createFileError(const Twine &F, Error E) {
1222 return FileError::build(F, Optional<size_t>(), std::move(E));
1223}
1224
1225/// Concatenate a source file path and/or name with line number and an Error.
1226/// The resulting Error is unchecked.
1227inline Error createFileError(const Twine &F, size_t Line, Error E) {
1228 return FileError::build(F, Optional<size_t>(Line), std::move(E));
1229}
1230
1231/// Concatenate a source file path and/or name with a std::error_code
1232/// to form an Error object.
1233inline Error createFileError(const Twine &F, std::error_code EC) {
1234 return createFileError(F, errorCodeToError(EC));
1235}
1236
1237/// Concatenate a source file path and/or name with line number and
1238/// std::error_code to form an Error object.
1239inline Error createFileError(const Twine &F, size_t Line, std::error_code EC) {
1240 return createFileError(F, Line, errorCodeToError(EC));
1241}
1242
1243Error createFileError(const Twine &F, ErrorSuccess) = delete;
1244
1245/// Helper for check-and-exit error handling.
1246///
1247/// For tool use only. NOT FOR USE IN LIBRARY CODE.
1248///
1249class ExitOnError {
1250public:
1251 /// Create an error on exit helper.
1252 ExitOnError(std::string Banner = "", int DefaultErrorExitCode = 1)
1253 : Banner(std::move(Banner)),
1254 GetExitCode([=](const Error &) { return DefaultErrorExitCode; }) {}
1255
1256 /// Set the banner string for any errors caught by operator().
1257 void setBanner(std::string Banner) { this->Banner = std::move(Banner); }
1258
1259 /// Set the exit-code mapper function.
1260 void setExitCodeMapper(std::function<int(const Error &)> GetExitCode) {
1261 this->GetExitCode = std::move(GetExitCode);
1262 }
1263
1264 /// Check Err. If it's in a failure state log the error(s) and exit.
1265 void operator()(Error Err) const { checkError(std::move(Err)); }
1266
1267 /// Check E. If it's in a success state then return the contained value. If
1268 /// it's in a failure state log the error(s) and exit.
1269 template <typename T> T operator()(Expected<T> &&E) const {
1270 checkError(E.takeError());
1271 return std::move(*E);
1272 }
1273
1274 /// Check E. If it's in a success state then return the contained reference. If
1275 /// it's in a failure state log the error(s) and exit.
1276 template <typename T> T& operator()(Expected<T&> &&E) const {
1277 checkError(E.takeError());
1278 return *E;
1279 }
1280
1281private:
1282 void checkError(Error Err) const {
1283 if (Err) {
1284 int ExitCode = GetExitCode(Err);
1285 logAllUnhandledErrors(std::move(Err), errs(), Banner);
1286 exit(ExitCode);
1287 }
1288 }
1289
1290 std::string Banner;
1291 std::function<int(const Error &)> GetExitCode;
1292};
1293
1294/// Conversion from Error to LLVMErrorRef for C error bindings.
1295inline LLVMErrorRef wrap(Error Err) {
1296 return reinterpret_cast<LLVMErrorRef>(Err.takePayload().release());
1297}
1298
1299/// Conversion from LLVMErrorRef to Error for C error bindings.
1300inline Error unwrap(LLVMErrorRef ErrRef) {
1301 return Error(std::unique_ptr<ErrorInfoBase>(
1302 reinterpret_cast<ErrorInfoBase *>(ErrRef)));
1303}
1304
1305} // end namespace llvm
1306
1307#endif // LLVM_SUPPORT_ERROR_H

/build/llvm-toolchain-snapshot-9~svn362543/include/llvm/ADT/STLExtras.h

1//===- llvm/ADT/STLExtras.h - Useful STL related functions ------*- C++ -*-===//
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// This file contains some templates that are useful if you are working with the
10// STL at all.
11//
12// No library is required when using these functions.
13//
14//===----------------------------------------------------------------------===//
15
16#ifndef LLVM_ADT_STLEXTRAS_H
17#define LLVM_ADT_STLEXTRAS_H
18
19#include "llvm/ADT/Optional.h"
20#include "llvm/ADT/SmallVector.h"
21#include "llvm/ADT/iterator.h"
22#include "llvm/ADT/iterator_range.h"
23#include "llvm/Config/abi-breaking.h"
24#include "llvm/Support/ErrorHandling.h"
25#include <algorithm>
26#include <cassert>
27#include <cstddef>
28#include <cstdint>
29#include <cstdlib>
30#include <functional>
31#include <initializer_list>
32#include <iterator>
33#include <limits>
34#include <memory>
35#include <tuple>
36#include <type_traits>
37#include <utility>
38
39#ifdef EXPENSIVE_CHECKS
40#include <random> // for std::mt19937
41#endif
42
43namespace llvm {
44
45// Only used by compiler if both template types are the same. Useful when
46// using SFINAE to test for the existence of member functions.
47template <typename T, T> struct SameType;
48
49namespace detail {
50
51template <typename RangeT>
52using IterOfRange = decltype(std::begin(std::declval<RangeT &>()));
53
54template <typename RangeT>
55using ValueOfRange = typename std::remove_reference<decltype(
56 *std::begin(std::declval<RangeT &>()))>::type;
57
58} // end namespace detail
59
60//===----------------------------------------------------------------------===//
61// Extra additions to <type_traits>
62//===----------------------------------------------------------------------===//
63
64template <typename T>
65struct negation : std::integral_constant<bool, !bool(T::value)> {};
66
67template <typename...> struct conjunction : std::true_type {};
68template <typename B1> struct conjunction<B1> : B1 {};
69template <typename B1, typename... Bn>
70struct conjunction<B1, Bn...>
71 : std::conditional<bool(B1::value), conjunction<Bn...>, B1>::type {};
72
73template <typename T> struct make_const_ptr {
74 using type =
75 typename std::add_pointer<typename std::add_const<T>::type>::type;
76};
77
78template <typename T> struct make_const_ref {
79 using type = typename std::add_lvalue_reference<
80 typename std::add_const<T>::type>::type;
81};
82
83//===----------------------------------------------------------------------===//
84// Extra additions to <functional>
85//===----------------------------------------------------------------------===//
86
87template <class Ty> struct identity {
88 using argument_type = Ty;
89
90 Ty &operator()(Ty &self) const {
91 return self;
92 }
93 const Ty &operator()(const Ty &self) const {
94 return self;
95 }
96};
97
98template <class Ty> struct less_ptr {
99 bool operator()(const Ty* left, const Ty* right) const {
100 return *left < *right;
101 }
102};
103
104template <class Ty> struct greater_ptr {
105 bool operator()(const Ty* left, const Ty* right) const {
106 return *right < *left;
107 }
108};
109
110/// An efficient, type-erasing, non-owning reference to a callable. This is
111/// intended for use as the type of a function parameter that is not used
112/// after the function in question returns.
113///
114/// This class does not own the callable, so it is not in general safe to store
115/// a function_ref.
116template<typename Fn> class function_ref;
117
118template<typename Ret, typename ...Params>
119class function_ref<Ret(Params...)> {
120 Ret (*callback)(intptr_t callable, Params ...params) = nullptr;
121 intptr_t callable;
122
123 template<typename Callable>
124 static Ret callback_fn(intptr_t callable, Params ...params) {
125 return (*reinterpret_cast<Callable*>(callable))(
126 std::forward<Params>(params)...);
127 }
128
129public:
130 function_ref() = default;
131 function_ref(std::nullptr_t) {}
132
133 template <typename Callable>
134 function_ref(Callable &&callable,
135 typename std::enable_if<
136 !std::is_same<typename std::remove_reference<Callable>::type,
137 function_ref>::value>::type * = nullptr)
138 : callback(callback_fn<typename std::remove_reference<Callable>::type>),
139 callable(reinterpret_cast<intptr_t>(&callable)) {}
140
141 Ret operator()(Params ...params) const {
142 return callback(callable, std::forward<Params>(params)...);
143 }
144
145 operator bool() const { return callback; }
146};
147
148// deleter - Very very very simple method that is used to invoke operator
149// delete on something. It is used like this:
150//
151// for_each(V.begin(), B.end(), deleter<Interval>);
152template <class T>
153inline void deleter(T *Ptr) {
154 delete Ptr;
155}
156
157//===----------------------------------------------------------------------===//
158// Extra additions to <iterator>
159//===----------------------------------------------------------------------===//
160
161namespace adl_detail {
162
163using std::begin;
164
165template <typename ContainerTy>
166auto adl_begin(ContainerTy &&container)
167 -> decltype(begin(std::forward<ContainerTy>(container))) {
168 return begin(std::forward<ContainerTy>(container));
169}
170
171using std::end;
172
173template <typename ContainerTy>
174auto adl_end(ContainerTy &&container)
175 -> decltype(end(std::forward<ContainerTy>(container))) {
176 return end(std::forward<ContainerTy>(container));
177}
178
179using std::swap;
180
181template <typename T>
182void adl_swap(T &&lhs, T &&rhs) noexcept(noexcept(swap(std::declval<T>(),
183 std::declval<T>()))) {
184 swap(std::forward<T>(lhs), std::forward<T>(rhs));
185}
186
187} // end namespace adl_detail
188
189template <typename ContainerTy>
190auto adl_begin(ContainerTy &&container)
191 -> decltype(adl_detail::adl_begin(std::forward<ContainerTy>(container))) {
192 return adl_detail::adl_begin(std::forward<ContainerTy>(container));
193}
194
195template <typename ContainerTy>
196auto adl_end(ContainerTy &&container)
197 -> decltype(adl_detail::adl_end(std::forward<ContainerTy>(container))) {
198 return adl_detail::adl_end(std::forward<ContainerTy>(container));
199}
200
201template <typename T>
202void adl_swap(T &&lhs, T &&rhs) noexcept(
203 noexcept(adl_detail::adl_swap(std::declval<T>(), std::declval<T>()))) {
204 adl_detail::adl_swap(std::forward<T>(lhs), std::forward<T>(rhs));
205}
206
207/// Test whether \p RangeOrContainer is empty. Similar to C++17 std::empty.
208template <typename T>
209constexpr bool empty(const T &RangeOrContainer) {
210 return adl_begin(RangeOrContainer) == adl_end(RangeOrContainer);
211}
212
213// mapped_iterator - This is a simple iterator adapter that causes a function to
214// be applied whenever operator* is invoked on the iterator.
215
216template <typename ItTy, typename FuncTy,
217 typename FuncReturnTy =
218 decltype(std::declval<FuncTy>()(*std::declval<ItTy>()))>
219class mapped_iterator
220 : public iterator_adaptor_base<
221 mapped_iterator<ItTy, FuncTy>, ItTy,
222 typename std::iterator_traits<ItTy>::iterator_category,
223 typename std::remove_reference<FuncReturnTy>::type> {
224public:
225 mapped_iterator(ItTy U, FuncTy F)
226 : mapped_iterator::iterator_adaptor_base(std::move(U)), F(std::move(F)) {}
227
228 ItTy getCurrent() { return this->I; }
229
230 FuncReturnTy operator*() { return F(*this->I); }
231
232private:
233 FuncTy F;
234};
235
236// map_iterator - Provide a convenient way to create mapped_iterators, just like
237// make_pair is useful for creating pairs...
238template <class ItTy, class FuncTy>
239inline mapped_iterator<ItTy, FuncTy> map_iterator(ItTy I, FuncTy F) {
240 return mapped_iterator<ItTy, FuncTy>(std::move(I), std::move(F));
241}
242
243/// Helper to determine if type T has a member called rbegin().
244template <typename Ty> class has_rbegin_impl {
245 using yes = char[1];
246 using no = char[2];
247
248 template <typename Inner>
249 static yes& test(Inner *I, decltype(I->rbegin()) * = nullptr);
250
251 template <typename>
252 static no& test(...);
253
254public:
255 static const bool value = sizeof(test<Ty>(nullptr)) == sizeof(yes);
256};
257
258/// Metafunction to determine if T& or T has a member called rbegin().
259template <typename Ty>
260struct has_rbegin : has_rbegin_impl<typename std::remove_reference<Ty>::type> {
261};
262
263// Returns an iterator_range over the given container which iterates in reverse.
264// Note that the container must have rbegin()/rend() methods for this to work.
265template <typename ContainerTy>
266auto reverse(ContainerTy &&C,
267 typename std::enable_if<has_rbegin<ContainerTy>::value>::type * =
268 nullptr) -> decltype(make_range(C.rbegin(), C.rend())) {
269 return make_range(C.rbegin(), C.rend());
270}
271
272// Returns a std::reverse_iterator wrapped around the given iterator.
273template <typename IteratorTy>
274std::reverse_iterator<IteratorTy> make_reverse_iterator(IteratorTy It) {
275 return std::reverse_iterator<IteratorTy>(It);
276}
277
278// Returns an iterator_range over the given container which iterates in reverse.
279// Note that the container must have begin()/end() methods which return
280// bidirectional iterators for this to work.
281template <typename ContainerTy>
282auto reverse(
283 ContainerTy &&C,
284 typename std::enable_if<!has_rbegin<ContainerTy>::value>::type * = nullptr)
285 -> decltype(make_range(llvm::make_reverse_iterator(std::end(C)),
286 llvm::make_reverse_iterator(std::begin(C)))) {
287 return make_range(llvm::make_reverse_iterator(std::end(C)),
288 llvm::make_reverse_iterator(std::begin(C)));
289}
290
291/// An iterator adaptor that filters the elements of given inner iterators.
292///
293/// The predicate parameter should be a callable object that accepts the wrapped
294/// iterator's reference type and returns a bool. When incrementing or
295/// decrementing the iterator, it will call the predicate on each element and
296/// skip any where it returns false.
297///
298/// \code
299/// int A[] = { 1, 2, 3, 4 };
300/// auto R = make_filter_range(A, [](int N) { return N % 2 == 1; });
301/// // R contains { 1, 3 }.
302/// \endcode
303///
304/// Note: filter_iterator_base implements support for forward iteration.
305/// filter_iterator_impl exists to provide support for bidirectional iteration,
306/// conditional on whether the wrapped iterator supports it.
307template <typename WrappedIteratorT, typename PredicateT, typename IterTag>
308class filter_iterator_base
309 : public iterator_adaptor_base<
310 filter_iterator_base<WrappedIteratorT, PredicateT, IterTag>,
311 WrappedIteratorT,
312 typename std::common_type<
313 IterTag, typename std::iterator_traits<
314 WrappedIteratorT>::iterator_category>::type> {
315 using BaseT = iterator_adaptor_base<
316 filter_iterator_base<WrappedIteratorT, PredicateT, IterTag>,
317 WrappedIteratorT,
318 typename std::common_type<
319 IterTag, typename std::iterator_traits<
320 WrappedIteratorT>::iterator_category>::type>;
321
322protected:
323 WrappedIteratorT End;
324 PredicateT Pred;
325
326 void findNextValid() {
327 while (this->I != End && !Pred(*this->I))
328 BaseT::operator++();
329 }
330
331 // Construct the iterator. The begin iterator needs to know where the end
332 // is, so that it can properly stop when it gets there. The end iterator only
333 // needs the predicate to support bidirectional iteration.
334 filter_iterator_base(WrappedIteratorT Begin, WrappedIteratorT End,
335 PredicateT Pred)
336 : BaseT(Begin), End(End), Pred(Pred) {
337 findNextValid();
338 }
339
340public:
341 using BaseT::operator++;
342
343 filter_iterator_base &operator++() {
344 BaseT::operator++();
345 findNextValid();
346 return *this;
347 }
348};
349
350/// Specialization of filter_iterator_base for forward iteration only.
351template <typename WrappedIteratorT, typename PredicateT,
352 typename IterTag = std::forward_iterator_tag>
353class filter_iterator_impl
354 : public filter_iterator_base<WrappedIteratorT, PredicateT, IterTag> {
355 using BaseT = filter_iterator_base<WrappedIteratorT, PredicateT, IterTag>;
356
357public:
358 filter_iterator_impl(WrappedIteratorT Begin, WrappedIteratorT End,
359 PredicateT Pred)
360 : BaseT(Begin, End, Pred) {}
361};
362
363/// Specialization of filter_iterator_base for bidirectional iteration.
364template <typename WrappedIteratorT, typename PredicateT>
365class filter_iterator_impl<WrappedIteratorT, PredicateT,
366 std::bidirectional_iterator_tag>
367 : public filter_iterator_base<WrappedIteratorT, PredicateT,
368 std::bidirectional_iterator_tag> {
369 using BaseT = filter_iterator_base<WrappedIteratorT, PredicateT,
370 std::bidirectional_iterator_tag>;
371 void findPrevValid() {
372 while (!this->Pred(*this->I))
373 BaseT::operator--();
374 }
375
376public:
377 using BaseT::operator--;
378
379 filter_iterator_impl(WrappedIteratorT Begin, WrappedIteratorT End,
380 PredicateT Pred)
381 : BaseT(Begin, End, Pred) {}
382
383 filter_iterator_impl &operator--() {
384 BaseT::operator--();
385 findPrevValid();
386 return *this;
387 }
388};
389
390namespace detail {
391
392template <bool is_bidirectional> struct fwd_or_bidi_tag_impl {
393 using type = std::forward_iterator_tag;
394};
395
396template <> struct fwd_or_bidi_tag_impl<true> {
397 using type = std::bidirectional_iterator_tag;
398};
399
400/// Helper which sets its type member to forward_iterator_tag if the category
401/// of \p IterT does not derive from bidirectional_iterator_tag, and to
402/// bidirectional_iterator_tag otherwise.
403template <typename IterT> struct fwd_or_bidi_tag {
404 using type = typename fwd_or_bidi_tag_impl<std::is_base_of<
405 std::bidirectional_iterator_tag,
406 typename std::iterator_traits<IterT>::iterator_category>::value>::type;
407};
408
409} // namespace detail
410
411/// Defines filter_iterator to a suitable specialization of
412/// filter_iterator_impl, based on the underlying iterator's category.
413template <typename WrappedIteratorT, typename PredicateT>
414using filter_iterator = filter_iterator_impl<
415 WrappedIteratorT, PredicateT,
416 typename detail::fwd_or_bidi_tag<WrappedIteratorT>::type>;
417
418/// Convenience function that takes a range of elements and a predicate,
419/// and return a new filter_iterator range.
420///
421/// FIXME: Currently if RangeT && is a rvalue reference to a temporary, the
422/// lifetime of that temporary is not kept by the returned range object, and the
423/// temporary is going to be dropped on the floor after the make_iterator_range
424/// full expression that contains this function call.
425template <typename RangeT, typename PredicateT>
426iterator_range<filter_iterator<detail::IterOfRange<RangeT>, PredicateT>>
427make_filter_range(RangeT &&Range, PredicateT Pred) {
428 using FilterIteratorT =
429 filter_iterator<detail::IterOfRange<RangeT>, PredicateT>;
430 return make_range(
431 FilterIteratorT(std::begin(std::forward<RangeT>(Range)),
432 std::end(std::forward<RangeT>(Range)), Pred),
433 FilterIteratorT(std::end(std::forward<RangeT>(Range)),
434 std::end(std::forward<RangeT>(Range)), Pred));
435}
436
437/// A pseudo-iterator adaptor that is designed to implement "early increment"
438/// style loops.
439///
440/// This is *not a normal iterator* and should almost never be used directly. It
441/// is intended primarily to be used with range based for loops and some range
442/// algorithms.
443///
444/// The iterator isn't quite an `OutputIterator` or an `InputIterator` but
445/// somewhere between them. The constraints of these iterators are:
446///
447/// - On construction or after being incremented, it is comparable and
448/// dereferencable. It is *not* incrementable.
449/// - After being dereferenced, it is neither comparable nor dereferencable, it
450/// is only incrementable.
451///
452/// This means you can only dereference the iterator once, and you can only
453/// increment it once between dereferences.
454template <typename WrappedIteratorT>
455class early_inc_iterator_impl
456 : public iterator_adaptor_base<early_inc_iterator_impl<WrappedIteratorT>,
457 WrappedIteratorT, std::input_iterator_tag> {
458 using BaseT =
459 iterator_adaptor_base<early_inc_iterator_impl<WrappedIteratorT>,
460 WrappedIteratorT, std::input_iterator_tag>;
461
462 using PointerT = typename std::iterator_traits<WrappedIteratorT>::pointer;
463
464protected:
465#if LLVM_ENABLE_ABI_BREAKING_CHECKS1
466 bool IsEarlyIncremented = false;
467#endif
468
469public:
470 early_inc_iterator_impl(WrappedIteratorT I) : BaseT(I) {}
471
472 using BaseT::operator*;
473 typename BaseT::reference operator*() {
474#if LLVM_ENABLE_ABI_BREAKING_CHECKS1
475 assert(!IsEarlyIncremented && "Cannot dereference twice!")((!IsEarlyIncremented && "Cannot dereference twice!")
? static_cast<void> (0) : __assert_fail ("!IsEarlyIncremented && \"Cannot dereference twice!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/include/llvm/ADT/STLExtras.h"
, 475, __PRETTY_FUNCTION__))
;
476 IsEarlyIncremented = true;
477#endif
478 return *(this->I)++;
479 }
480
481 using BaseT::operator++;
482 early_inc_iterator_impl &operator++() {
483#if LLVM_ENABLE_ABI_BREAKING_CHECKS1
484 assert(IsEarlyIncremented && "Cannot increment before dereferencing!")((IsEarlyIncremented && "Cannot increment before dereferencing!"
) ? static_cast<void> (0) : __assert_fail ("IsEarlyIncremented && \"Cannot increment before dereferencing!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/include/llvm/ADT/STLExtras.h"
, 484, __PRETTY_FUNCTION__))
;
485 IsEarlyIncremented = false;
486#endif
487 return *this;
488 }
489
490 using BaseT::operator==;
491 bool operator==(const early_inc_iterator_impl &RHS) const {
492#if LLVM_ENABLE_ABI_BREAKING_CHECKS1
493 assert(!IsEarlyIncremented && "Cannot compare after dereferencing!")((!IsEarlyIncremented && "Cannot compare after dereferencing!"
) ? static_cast<void> (0) : __assert_fail ("!IsEarlyIncremented && \"Cannot compare after dereferencing!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/include/llvm/ADT/STLExtras.h"
, 493, __PRETTY_FUNCTION__))
;
494#endif
495 return BaseT::operator==(RHS);
496 }
497};
498
499/// Make a range that does early increment to allow mutation of the underlying
500/// range without disrupting iteration.
501///
502/// The underlying iterator will be incremented immediately after it is
503/// dereferenced, allowing deletion of the current node or insertion of nodes to
504/// not disrupt iteration provided they do not invalidate the *next* iterator --
505/// the current iterator can be invalidated.
506///
507/// This requires a very exact pattern of use that is only really suitable to
508/// range based for loops and other range algorithms that explicitly guarantee
509/// to dereference exactly once each element, and to increment exactly once each
510/// element.
511template <typename RangeT>
512iterator_range<early_inc_iterator_impl<detail::IterOfRange<RangeT>>>
513make_early_inc_range(RangeT &&Range) {
514 using EarlyIncIteratorT =
515 early_inc_iterator_impl<detail::IterOfRange<RangeT>>;
516 return make_range(EarlyIncIteratorT(std::begin(std::forward<RangeT>(Range))),
517 EarlyIncIteratorT(std::end(std::forward<RangeT>(Range))));
518}
519
520// forward declarations required by zip_shortest/zip_first/zip_longest
521template <typename R, typename UnaryPredicate>
522bool all_of(R &&range, UnaryPredicate P);
523template <typename R, typename UnaryPredicate>
524bool any_of(R &&range, UnaryPredicate P);
525
526template <size_t... I> struct index_sequence;
527
528template <class... Ts> struct index_sequence_for;
529
530namespace detail {
531
532using std::declval;
533
534// We have to alias this since inlining the actual type at the usage site
535// in the parameter list of iterator_facade_base<> below ICEs MSVC 2017.
536template<typename... Iters> struct ZipTupleType {
537 using type = std::tuple<decltype(*declval<Iters>())...>;
538};
539
540template <typename ZipType, typename... Iters>
541using zip_traits = iterator_facade_base<
542 ZipType, typename std::common_type<std::bidirectional_iterator_tag,
543 typename std::iterator_traits<
544 Iters>::iterator_category...>::type,
545 // ^ TODO: Implement random access methods.
546 typename ZipTupleType<Iters...>::type,
547 typename std::iterator_traits<typename std::tuple_element<
548 0, std::tuple<Iters...>>::type>::difference_type,
549 // ^ FIXME: This follows boost::make_zip_iterator's assumption that all
550 // inner iterators have the same difference_type. It would fail if, for
551 // instance, the second field's difference_type were non-numeric while the
552 // first is.
553 typename ZipTupleType<Iters...>::type *,
554 typename ZipTupleType<Iters...>::type>;
555
556template <typename ZipType, typename... Iters>
557struct zip_common : public zip_traits<ZipType, Iters...> {
558 using Base = zip_traits<ZipType, Iters...>;
559 using value_type = typename Base::value_type;
560
561 std::tuple<Iters...> iterators;
562
563protected:
564 template <size_t... Ns> value_type deref(index_sequence<Ns...>) const {
565 return value_type(*std::get<Ns>(iterators)...);
566 }
567
568 template <size_t... Ns>
569 decltype(iterators) tup_inc(index_sequence<Ns...>) const {
570 return std::tuple<Iters...>(std::next(std::get<Ns>(iterators))...);
571 }
572
573 template <size_t... Ns>
574 decltype(iterators) tup_dec(index_sequence<Ns...>) const {
575 return std::tuple<Iters...>(std::prev(std::get<Ns>(iterators))...);
576 }
577
578public:
579 zip_common(Iters &&... ts) : iterators(std::forward<Iters>(ts)...) {}
580
581 value_type operator*() { return deref(index_sequence_for<Iters...>{}); }
582
583 const value_type operator*() const {
584 return deref(index_sequence_for<Iters...>{});
585 }
586
587 ZipType &operator++() {
588 iterators = tup_inc(index_sequence_for<Iters...>{});
589 return *reinterpret_cast<ZipType *>(this);
590 }
591
592 ZipType &operator--() {
593 static_assert(Base::IsBidirectional,
594 "All inner iterators must be at least bidirectional.");
595 iterators = tup_dec(index_sequence_for<Iters...>{});
596 return *reinterpret_cast<ZipType *>(this);
597 }
598};
599
600template <typename... Iters>
601struct zip_first : public zip_common<zip_first<Iters...>, Iters...> {
602 using Base = zip_common<zip_first<Iters...>, Iters...>;
603
604 bool operator==(const zip_first<Iters...> &other) const {
605 return std::get<0>(this->iterators) == std::get<0>(other.iterators);
606 }
607
608 zip_first(Iters &&... ts) : Base(std::forward<Iters>(ts)...) {}
609};
610
611template <typename... Iters>
612class zip_shortest : public zip_common<zip_shortest<Iters...>, Iters...> {
613 template <size_t... Ns>
614 bool test(const zip_shortest<Iters...> &other, index_sequence<Ns...>) const {
615 return all_of(std::initializer_list<bool>{std::get<Ns>(this->iterators) !=
616 std::get<Ns>(other.iterators)...},
617 identity<bool>{});
618 }
619
620public:
621 using Base = zip_common<zip_shortest<Iters...>, Iters...>;
622
623 zip_shortest(Iters &&... ts) : Base(std::forward<Iters>(ts)...) {}
624
625 bool operator==(const zip_shortest<Iters...> &other) const {
626 return !test(other, index_sequence_for<Iters...>{});
627 }
628};
629
630template <template <typename...> class ItType, typename... Args> class zippy {
631public:
632 using iterator = ItType<decltype(std::begin(std::declval<Args>()))...>;
633 using iterator_category = typename iterator::iterator_category;
634 using value_type = typename iterator::value_type;
635 using difference_type = typename iterator::difference_type;
636 using pointer = typename iterator::pointer;
637 using reference = typename iterator::reference;
638
639private:
640 std::tuple<Args...> ts;
641
642 template <size_t... Ns> iterator begin_impl(index_sequence<Ns...>) const {
643 return iterator(std::begin(std::get<Ns>(ts))...);
644 }
645 template <size_t... Ns> iterator end_impl(index_sequence<Ns...>) const {
646 return iterator(std::end(std::get<Ns>(ts))...);
647 }
648
649public:
650 zippy(Args &&... ts_) : ts(std::forward<Args>(ts_)...) {}
651
652 iterator begin() const { return begin_impl(index_sequence_for<Args...>{}); }
653 iterator end() const { return end_impl(index_sequence_for<Args...>{}); }
654};
655
656} // end namespace detail
657
658/// zip iterator for two or more iteratable types.
659template <typename T, typename U, typename... Args>
660detail::zippy<detail::zip_shortest, T, U, Args...> zip(T &&t, U &&u,
661 Args &&... args) {
662 return detail::zippy<detail::zip_shortest, T, U, Args...>(
663 std::forward<T>(t), std::forward<U>(u), std::forward<Args>(args)...);
664}
665
666/// zip iterator that, for the sake of efficiency, assumes the first iteratee to
667/// be the shortest.
668template <typename T, typename U, typename... Args>
669detail::zippy<detail::zip_first, T, U, Args...> zip_first(T &&t, U &&u,
670 Args &&... args) {
671 return detail::zippy<detail::zip_first, T, U, Args...>(
672 std::forward<T>(t), std::forward<U>(u), std::forward<Args>(args)...);
673}
674
675namespace detail {
676template <typename Iter>
677static Iter next_or_end(const Iter &I, const Iter &End) {
678 if (I == End)
679 return End;
680 return std::next(I);
681}
682
683template <typename Iter>
684static auto deref_or_none(const Iter &I, const Iter &End)
685 -> llvm::Optional<typename std::remove_const<
686 typename std::remove_reference<decltype(*I)>::type>::type> {
687 if (I == End)
688 return None;
689 return *I;
690}
691
692template <typename Iter> struct ZipLongestItemType {
693 using type =
694 llvm::Optional<typename std::remove_const<typename std::remove_reference<
695 decltype(*std::declval<Iter>())>::type>::type>;
696};
697
698template <typename... Iters> struct ZipLongestTupleType {
699 using type = std::tuple<typename ZipLongestItemType<Iters>::type...>;
700};
701
702template <typename... Iters>
703class zip_longest_iterator
704 : public iterator_facade_base<
705 zip_longest_iterator<Iters...>,
706 typename std::common_type<
707 std::forward_iterator_tag,
708 typename std::iterator_traits<Iters>::iterator_category...>::type,
709 typename ZipLongestTupleType<Iters...>::type,
710 typename std::iterator_traits<typename std::tuple_element<
711 0, std::tuple<Iters...>>::type>::difference_type,
712 typename ZipLongestTupleType<Iters...>::type *,
713 typename ZipLongestTupleType<Iters...>::type> {
714public:
715 using value_type = typename ZipLongestTupleType<Iters...>::type;
716
717private:
718 std::tuple<Iters...> iterators;
719 std::tuple<Iters...> end_iterators;
720
721 template <size_t... Ns>
722 bool test(const zip_longest_iterator<Iters...> &other,
723 index_sequence<Ns...>) const {
724 return llvm::any_of(
725 std::initializer_list<bool>{std::get<Ns>(this->iterators) !=
726 std::get<Ns>(other.iterators)...},
727 identity<bool>{});
728 }
729
730 template <size_t... Ns> value_type deref(index_sequence<Ns...>) const {
731 return value_type(
732 deref_or_none(std::get<Ns>(iterators), std::get<Ns>(end_iterators))...);
733 }
734
735 template <size_t... Ns>
736 decltype(iterators) tup_inc(index_sequence<Ns...>) const {
737 return std::tuple<Iters...>(
738 next_or_end(std::get<Ns>(iterators), std::get<Ns>(end_iterators))...);
739 }
740
741public:
742 zip_longest_iterator(std::pair<Iters &&, Iters &&>... ts)
743 : iterators(std::forward<Iters>(ts.first)...),
744 end_iterators(std::forward<Iters>(ts.second)...) {}
745
746 value_type operator*() { return deref(index_sequence_for<Iters...>{}); }
747
748 value_type operator*() const { return deref(index_sequence_for<Iters...>{}); }
749
750 zip_longest_iterator<Iters...> &operator++() {
751 iterators = tup_inc(index_sequence_for<Iters...>{});
752 return *this;
753 }
754
755 bool operator==(const zip_longest_iterator<Iters...> &other) const {
756 return !test(other, index_sequence_for<Iters...>{});
757 }
758};
759
760template <typename... Args> class zip_longest_range {
761public:
762 using iterator =
763 zip_longest_iterator<decltype(adl_begin(std::declval<Args>()))...>;
764 using iterator_category = typename iterator::iterator_category;
765 using value_type = typename iterator::value_type;
766 using difference_type = typename iterator::difference_type;
767 using pointer = typename iterator::pointer;
768 using reference = typename iterator::reference;
769
770private:
771 std::tuple<Args...> ts;
772
773 template <size_t... Ns> iterator begin_impl(index_sequence<Ns...>) const {
774 return iterator(std::make_pair(adl_begin(std::get<Ns>(ts)),
775 adl_end(std::get<Ns>(ts)))...);
776 }
777
778 template <size_t... Ns> iterator end_impl(index_sequence<Ns...>) const {
779 return iterator(std::make_pair(adl_end(std::get<Ns>(ts)),
780 adl_end(std::get<Ns>(ts)))...);
781 }
782
783public:
784 zip_longest_range(Args &&... ts_) : ts(std::forward<Args>(ts_)...) {}
785
786 iterator begin() const { return begin_impl(index_sequence_for<Args...>{}); }
787 iterator end() const { return end_impl(index_sequence_for<Args...>{}); }
788};
789} // namespace detail
790
791/// Iterate over two or more iterators at the same time. Iteration continues
792/// until all iterators reach the end. The llvm::Optional only contains a value
793/// if the iterator has not reached the end.
794template <typename T, typename U, typename... Args>
795detail::zip_longest_range<T, U, Args...> zip_longest(T &&t, U &&u,
796 Args &&... args) {
797 return detail::zip_longest_range<T, U, Args...>(
798 std::forward<T>(t), std::forward<U>(u), std::forward<Args>(args)...);
799}
800
801/// Iterator wrapper that concatenates sequences together.
802///
803/// This can concatenate different iterators, even with different types, into
804/// a single iterator provided the value types of all the concatenated
805/// iterators expose `reference` and `pointer` types that can be converted to
806/// `ValueT &` and `ValueT *` respectively. It doesn't support more
807/// interesting/customized pointer or reference types.
808///
809/// Currently this only supports forward or higher iterator categories as
810/// inputs and always exposes a forward iterator interface.
811template <typename ValueT, typename... IterTs>
812class concat_iterator
813 : public iterator_facade_base<concat_iterator<ValueT, IterTs...>,
814 std::forward_iterator_tag, ValueT> {
815 using BaseT = typename concat_iterator::iterator_facade_base;
816
817 /// We store both the current and end iterators for each concatenated
818 /// sequence in a tuple of pairs.
819 ///
820 /// Note that something like iterator_range seems nice at first here, but the
821 /// range properties are of little benefit and end up getting in the way
822 /// because we need to do mutation on the current iterators.
823 std::tuple<IterTs...> Begins;
824 std::tuple<IterTs...> Ends;
825
826 /// Attempts to increment a specific iterator.
827 ///
828 /// Returns true if it was able to increment the iterator. Returns false if
829 /// the iterator is already at the end iterator.
830 template <size_t Index> bool incrementHelper() {
831 auto &Begin = std::get<Index>(Begins);
832 auto &End = std::get<Index>(Ends);
833 if (Begin == End)
834 return false;
835
836 ++Begin;
837 return true;
838 }
839
840 /// Increments the first non-end iterator.
841 ///
842 /// It is an error to call this with all iterators at the end.
843 template <size_t... Ns> void increment(index_sequence<Ns...>) {
844 // Build a sequence of functions to increment each iterator if possible.
845 bool (concat_iterator::*IncrementHelperFns[])() = {
846 &concat_iterator::incrementHelper<Ns>...};
847
848 // Loop over them, and stop as soon as we succeed at incrementing one.
849 for (auto &IncrementHelperFn : IncrementHelperFns)
850 if ((this->*IncrementHelperFn)())
851 return;
852
853 llvm_unreachable("Attempted to increment an end concat iterator!")::llvm::llvm_unreachable_internal("Attempted to increment an end concat iterator!"
, "/build/llvm-toolchain-snapshot-9~svn362543/include/llvm/ADT/STLExtras.h"
, 853)
;
854 }
855
856 /// Returns null if the specified iterator is at the end. Otherwise,
857 /// dereferences the iterator and returns the address of the resulting
858 /// reference.
859 template <size_t Index> ValueT *getHelper() const {
860 auto &Begin = std::get<Index>(Begins);
861 auto &End = std::get<Index>(Ends);
862 if (Begin == End)
863 return nullptr;
864
865 return &*Begin;
866 }
867
868 /// Finds the first non-end iterator, dereferences, and returns the resulting
869 /// reference.
870 ///
871 /// It is an error to call this with all iterators at the end.
872 template <size_t... Ns> ValueT &get(index_sequence<Ns...>) const {
873 // Build a sequence of functions to get from iterator if possible.
874 ValueT *(concat_iterator::*GetHelperFns[])() const = {
875 &concat_iterator::getHelper<Ns>...};
876
877 // Loop over them, and return the first result we find.
878 for (auto &GetHelperFn : GetHelperFns)
879 if (ValueT *P = (this->*GetHelperFn)())
880 return *P;
881
882 llvm_unreachable("Attempted to get a pointer from an end concat iterator!")::llvm::llvm_unreachable_internal("Attempted to get a pointer from an end concat iterator!"
, "/build/llvm-toolchain-snapshot-9~svn362543/include/llvm/ADT/STLExtras.h"
, 882)
;
883 }
884
885public:
886 /// Constructs an iterator from a squence of ranges.
887 ///
888 /// We need the full range to know how to switch between each of the
889 /// iterators.
890 template <typename... RangeTs>
891 explicit concat_iterator(RangeTs &&... Ranges)
892 : Begins(std::begin(Ranges)...), Ends(std::end(Ranges)...) {}
893
894 using BaseT::operator++;
895
896 concat_iterator &operator++() {
897 increment(index_sequence_for<IterTs...>());
898 return *this;
899 }
900
901 ValueT &operator*() const { return get(index_sequence_for<IterTs...>()); }
902
903 bool operator==(const concat_iterator &RHS) const {
904 return Begins == RHS.Begins && Ends == RHS.Ends;
905 }
906};
907
908namespace detail {
909
910/// Helper to store a sequence of ranges being concatenated and access them.
911///
912/// This is designed to facilitate providing actual storage when temporaries
913/// are passed into the constructor such that we can use it as part of range
914/// based for loops.
915template <typename ValueT, typename... RangeTs> class concat_range {
916public:
917 using iterator =
918 concat_iterator<ValueT,
919 decltype(std::begin(std::declval<RangeTs &>()))...>;
920
921private:
922 std::tuple<RangeTs...> Ranges;
923
924 template <size_t... Ns> iterator begin_impl(index_sequence<Ns...>) {
925 return iterator(std::get<Ns>(Ranges)...);
926 }
927 template <size_t... Ns> iterator end_impl(index_sequence<Ns...>) {
928 return iterator(make_range(std::end(std::get<Ns>(Ranges)),
929 std::end(std::get<Ns>(Ranges)))...);
930 }
931
932public:
933 concat_range(RangeTs &&... Ranges)
934 : Ranges(std::forward<RangeTs>(Ranges)...) {}
935
936 iterator begin() { return begin_impl(index_sequence_for<RangeTs...>{}); }
937 iterator end() { return end_impl(index_sequence_for<RangeTs...>{}); }
938};
939
940} // end namespace detail
941
942/// Concatenated range across two or more ranges.
943///
944/// The desired value type must be explicitly specified.
945template <typename ValueT, typename... RangeTs>
946detail::concat_range<ValueT, RangeTs...> concat(RangeTs &&... Ranges) {
947 static_assert(sizeof...(RangeTs) > 1,
948 "Need more than one range to concatenate!");
949 return detail::concat_range<ValueT, RangeTs...>(
950 std::forward<RangeTs>(Ranges)...);
951}
952
953//===----------------------------------------------------------------------===//
954// Extra additions to <utility>
955//===----------------------------------------------------------------------===//
956
957/// Function object to check whether the first component of a std::pair
958/// compares less than the first component of another std::pair.
959struct less_first {
960 template <typename T> bool operator()(const T &lhs, const T &rhs) const {
961 return lhs.first < rhs.first;
962 }
963};
964
965/// Function object to check whether the second component of a std::pair
966/// compares less than the second component of another std::pair.
967struct less_second {
968 template <typename T> bool operator()(const T &lhs, const T &rhs) const {
969 return lhs.second < rhs.second;
970 }
971};
972
973/// \brief Function object to apply a binary function to the first component of
974/// a std::pair.
975template<typename FuncTy>
976struct on_first {
977 FuncTy func;
978
979 template <typename T>
980 auto operator()(const T &lhs, const T &rhs) const
981 -> decltype(func(lhs.first, rhs.first)) {
982 return func(lhs.first, rhs.first);
983 }
984};
985
986// A subset of N3658. More stuff can be added as-needed.
987
988/// Represents a compile-time sequence of integers.
989template <class T, T... I> struct integer_sequence {
990 using value_type = T;
991
992 static constexpr size_t size() { return sizeof...(I); }
993};
994
995/// Alias for the common case of a sequence of size_ts.
996template <size_t... I>
997struct index_sequence : integer_sequence<std::size_t, I...> {};
998
999template <std::size_t N, std::size_t... I>
1000struct build_index_impl : build_index_impl<N - 1, N - 1, I...> {};
1001template <std::size_t... I>
1002struct build_index_impl<0, I...> : index_sequence<I...> {};
1003
1004/// Creates a compile-time integer sequence for a parameter pack.
1005template <class... Ts>
1006struct index_sequence_for : build_index_impl<sizeof...(Ts)> {};
1007
1008/// Utility type to build an inheritance chain that makes it easy to rank
1009/// overload candidates.
1010template <int N> struct rank : rank<N - 1> {};
1011template <> struct rank<0> {};
1012
1013/// traits class for checking whether type T is one of any of the given
1014/// types in the variadic list.
1015template <typename T, typename... Ts> struct is_one_of {
1016 static const bool value = false;
1017};
1018
1019template <typename T, typename U, typename... Ts>
1020struct is_one_of<T, U, Ts...> {
1021 static const bool value =
1022 std::is_same<T, U>::value || is_one_of<T, Ts...>::value;
1023};
1024
1025/// traits class for checking whether type T is a base class for all
1026/// the given types in the variadic list.
1027template <typename T, typename... Ts> struct are_base_of {
1028 static const bool value = true;
1029};
1030
1031template <typename T, typename U, typename... Ts>
1032struct are_base_of<T, U, Ts...> {
1033 static const bool value =
1034 std::is_base_of<T, U>::value && are_base_of<T, Ts...>::value;
1035};
1036
1037//===----------------------------------------------------------------------===//
1038// Extra additions for arrays
1039//===----------------------------------------------------------------------===//
1040
1041/// Find the length of an array.
1042template <class T, std::size_t N>
1043constexpr inline size_t array_lengthof(T (&)[N]) {
1044 return N;
1045}
1046
1047/// Adapt std::less<T> for array_pod_sort.
1048template<typename T>
1049inline int array_pod_sort_comparator(const void *P1, const void *P2) {
1050 if (std::less<T>()(*reinterpret_cast<const T*>(P1),
1051 *reinterpret_cast<const T*>(P2)))
1052 return -1;
1053 if (std::less<T>()(*reinterpret_cast<const T*>(P2),
1054 *reinterpret_cast<const T*>(P1)))
1055 return 1;
1056 return 0;
1057}
1058
1059/// get_array_pod_sort_comparator - This is an internal helper function used to
1060/// get type deduction of T right.
1061template<typename T>
1062inline int (*get_array_pod_sort_comparator(const T &))
1063 (const void*, const void*) {
1064 return array_pod_sort_comparator<T>;
1065}
1066
1067/// array_pod_sort - This sorts an array with the specified start and end
1068/// extent. This is just like std::sort, except that it calls qsort instead of
1069/// using an inlined template. qsort is slightly slower than std::sort, but
1070/// most sorts are not performance critical in LLVM and std::sort has to be
1071/// template instantiated for each type, leading to significant measured code
1072/// bloat. This function should generally be used instead of std::sort where
1073/// possible.
1074///
1075/// This function assumes that you have simple POD-like types that can be
1076/// compared with std::less and can be moved with memcpy. If this isn't true,
1077/// you should use std::sort.
1078///
1079/// NOTE: If qsort_r were portable, we could allow a custom comparator and
1080/// default to std::less.
1081template<class IteratorTy>
1082inline void array_pod_sort(IteratorTy Start, IteratorTy End) {
1083 // Don't inefficiently call qsort with one element or trigger undefined
1084 // behavior with an empty sequence.
1085 auto NElts = End - Start;
1086 if (NElts <= 1) return;
1087#ifdef EXPENSIVE_CHECKS
1088 std::mt19937 Generator(std::random_device{}());
1089 std::shuffle(Start, End, Generator);
1090#endif
1091 qsort(&*Start, NElts, sizeof(*Start), get_array_pod_sort_comparator(*Start));
1092}
1093
1094template <class IteratorTy>
1095inline void array_pod_sort(
1096 IteratorTy Start, IteratorTy End,
1097 int (*Compare)(
1098 const typename std::iterator_traits<IteratorTy>::value_type *,
1099 const typename std::iterator_traits<IteratorTy>::value_type *)) {
1100 // Don't inefficiently call qsort with one element or trigger undefined
1101 // behavior with an empty sequence.
1102 auto NElts = End - Start;
1103 if (NElts <= 1) return;
1104#ifdef EXPENSIVE_CHECKS
1105 std::mt19937 Generator(std::random_device{}());
1106 std::shuffle(Start, End, Generator);
1107#endif
1108 qsort(&*Start, NElts, sizeof(*Start),
1109 reinterpret_cast<int (*)(const void *, const void *)>(Compare));
1110}
1111
1112// Provide wrappers to std::sort which shuffle the elements before sorting
1113// to help uncover non-deterministic behavior (PR35135).
1114template <typename IteratorTy>
1115inline void sort(IteratorTy Start, IteratorTy End) {
1116#ifdef EXPENSIVE_CHECKS
1117 std::mt19937 Generator(std::random_device{}());
1118 std::shuffle(Start, End, Generator);
1119#endif
1120 std::sort(Start, End);
1121}
1122
1123template <typename Container> inline void sort(Container &&C) {
1124 llvm::sort(adl_begin(C), adl_end(C));
1125}
1126
1127template <typename IteratorTy, typename Compare>
1128inline void sort(IteratorTy Start, IteratorTy End, Compare Comp) {
1129#ifdef EXPENSIVE_CHECKS
1130 std::mt19937 Generator(std::random_device{}());
1131 std::shuffle(Start, End, Generator);
1132#endif
1133 std::sort(Start, End, Comp);
1134}
1135
1136template <typename Container, typename Compare>
1137inline void sort(Container &&C, Compare Comp) {
1138 llvm::sort(adl_begin(C), adl_end(C), Comp);
1139}
1140
1141//===----------------------------------------------------------------------===//
1142// Extra additions to <algorithm>
1143//===----------------------------------------------------------------------===//
1144
1145/// For a container of pointers, deletes the pointers and then clears the
1146/// container.
1147template<typename Container>
1148void DeleteContainerPointers(Container &C) {
1149 for (auto V : C)
1150 delete V;
1151 C.clear();
1152}
1153
1154/// In a container of pairs (usually a map) whose second element is a pointer,
1155/// deletes the second elements and then clears the container.
1156template<typename Container>
1157void DeleteContainerSeconds(Container &C) {
1158 for (auto &V : C)
1159 delete V.second;
1160 C.clear();
1161}
1162
1163/// Get the size of a range. This is a wrapper function around std::distance
1164/// which is only enabled when the operation is O(1).
1165template <typename R>
1166auto size(R &&Range, typename std::enable_if<
1167 std::is_same<typename std::iterator_traits<decltype(
1168 Range.begin())>::iterator_category,
1169 std::random_access_iterator_tag>::value,
1170 void>::type * = nullptr)
1171 -> decltype(std::distance(Range.begin(), Range.end())) {
1172 return std::distance(Range.begin(), Range.end());
1173}
1174
1175/// Provide wrappers to std::for_each which take ranges instead of having to
1176/// pass begin/end explicitly.
1177template <typename R, typename UnaryPredicate>
1178UnaryPredicate for_each(R &&Range, UnaryPredicate P) {
1179 return std::for_each(adl_begin(Range), adl_end(Range), P);
1180}
1181
1182/// Provide wrappers to std::all_of which take ranges instead of having to pass
1183/// begin/end explicitly.
1184template <typename R, typename UnaryPredicate>
1185bool all_of(R &&Range, UnaryPredicate P) {
1186 return std::all_of(adl_begin(Range), adl_end(Range), P);
1187}
1188
1189/// Provide wrappers to std::any_of which take ranges instead of having to pass
1190/// begin/end explicitly.
1191template <typename R, typename UnaryPredicate>
1192bool any_of(R &&Range, UnaryPredicate P) {
1193 return std::any_of(adl_begin(Range), adl_end(Range), P);
1194}
1195
1196/// Provide wrappers to std::none_of which take ranges instead of having to pass
1197/// begin/end explicitly.
1198template <typename R, typename UnaryPredicate>
1199bool none_of(R &&Range, UnaryPredicate P) {
1200 return std::none_of(adl_begin(Range), adl_end(Range), P);
1201}
1202
1203/// Provide wrappers to std::find which take ranges instead of having to pass
1204/// begin/end explicitly.
1205template <typename R, typename T>
1206auto find(R &&Range, const T &Val) -> decltype(adl_begin(Range)) {
1207 return std::find(adl_begin(Range), adl_end(Range), Val);
1208}
1209
1210/// Provide wrappers to std::find_if which take ranges instead of having to pass
1211/// begin/end explicitly.
1212template <typename R, typename UnaryPredicate>
1213auto find_if(R &&Range, UnaryPredicate P) -> decltype(adl_begin(Range)) {
1214 return std::find_if(adl_begin(Range), adl_end(Range), P);
1215}
1216
1217template <typename R, typename UnaryPredicate>
1218auto find_if_not(R &&Range, UnaryPredicate P) -> decltype(adl_begin(Range)) {
1219 return std::find_if_not(adl_begin(Range), adl_end(Range), P);
1220}
1221
1222/// Provide wrappers to std::remove_if which take ranges instead of having to
1223/// pass begin/end explicitly.
1224template <typename R, typename UnaryPredicate>
1225auto remove_if(R &&Range, UnaryPredicate P) -> decltype(adl_begin(Range)) {
1226 return std::remove_if(adl_begin(Range), adl_end(Range), P);
1227}
1228
1229/// Provide wrappers to std::copy_if which take ranges instead of having to
1230/// pass begin/end explicitly.
1231template <typename R, typename OutputIt, typename UnaryPredicate>
1232OutputIt copy_if(R &&Range, OutputIt Out, UnaryPredicate P) {
1233 return std::copy_if(adl_begin(Range), adl_end(Range), Out, P);
1234}
1235
1236template <typename R, typename OutputIt>
1237OutputIt copy(R &&Range, OutputIt Out) {
1238 return std::copy(adl_begin(Range), adl_end(Range), Out);
1239}
1240
1241/// Wrapper function around std::find to detect if an element exists
1242/// in a container.
1243template <typename R, typename E>
1244bool is_contained(R &&Range, const E &Element) {
1245 return std::find(adl_begin(Range), adl_end(Range), Element) != adl_end(Range);
1246}
1247
1248/// Wrapper function around std::count to count the number of times an element
1249/// \p Element occurs in the given range \p Range.
1250template <typename R, typename E>
1251auto count(R &&Range, const E &Element) ->
1252 typename std::iterator_traits<decltype(adl_begin(Range))>::difference_type {
1253 return std::count(adl_begin(Range), adl_end(Range), Element);
1254}
1255
1256/// Wrapper function around std::count_if to count the number of times an
1257/// element satisfying a given predicate occurs in a range.
1258template <typename R, typename UnaryPredicate>
1259auto count_if(R &&Range, UnaryPredicate P) ->
1260 typename std::iterator_traits<decltype(adl_begin(Range))>::difference_type {
1261 return std::count_if(adl_begin(Range), adl_end(Range), P);
1262}
1263
1264/// Wrapper function around std::transform to apply a function to a range and
1265/// store the result elsewhere.
1266template <typename R, typename OutputIt, typename UnaryPredicate>
1267OutputIt transform(R &&Range, OutputIt d_first, UnaryPredicate P) {
1268 return std::transform(adl_begin(Range), adl_end(Range), d_first, P);
1269}
1270
1271/// Provide wrappers to std::partition which take ranges instead of having to
1272/// pass begin/end explicitly.
1273template <typename R, typename UnaryPredicate>
1274auto partition(R &&Range, UnaryPredicate P) -> decltype(adl_begin(Range)) {
1275 return std::partition(adl_begin(Range), adl_end(Range), P);
1276}
1277
1278/// Provide wrappers to std::lower_bound which take ranges instead of having to
1279/// pass begin/end explicitly.
1280template <typename R, typename T>
1281auto lower_bound(R &&Range, T &&Value) -> decltype(adl_begin(Range)) {
1282 return std::lower_bound(adl_begin(Range), adl_end(Range),
1283 std::forward<T>(Value));
1284}
1285
1286template <typename R, typename T, typename Compare>
1287auto lower_bound(R &&Range, T &&Value, Compare C)
1288 -> decltype(adl_begin(Range)) {
1289 return std::lower_bound(adl_begin(Range), adl_end(Range),
1290 std::forward<T>(Value), C);
1291}
1292
1293/// Provide wrappers to std::upper_bound which take ranges instead of having to
1294/// pass begin/end explicitly.
1295template <typename R, typename T>
1296auto upper_bound(R &&Range, T &&Value) -> decltype(adl_begin(Range)) {
1297 return std::upper_bound(adl_begin(Range), adl_end(Range),
1298 std::forward<T>(Value));
1299}
1300
1301template <typename R, typename T, typename Compare>
1302auto upper_bound(R &&Range, T &&Value, Compare C)
1303 -> decltype(adl_begin(Range)) {
1304 return std::upper_bound(adl_begin(Range), adl_end(Range),
1305 std::forward<T>(Value), C);
1306}
1307
1308template <typename R>
1309void stable_sort(R &&Range) {
1310 std::stable_sort(adl_begin(Range), adl_end(Range));
1311}
1312
1313template <typename R, typename Compare>
1314void stable_sort(R &&Range, Compare C) {
1315 std::stable_sort(adl_begin(Range), adl_end(Range), C);
1316}
1317
1318/// Binary search for the first index where a predicate is true.
1319/// Returns the first I in [Lo, Hi) where C(I) is true, or Hi if it never is.
1320/// Requires that C is always false below some limit, and always true above it.
1321///
1322/// Example:
1323/// size_t DawnModernEra = bsearch(1776, 2050, [](size_t Year){
1324/// return Presidents.for(Year).twitterHandle() != None;
1325/// });
1326///
1327/// Note the return value differs from std::binary_search!
1328template <typename Predicate>
1329size_t bsearch(size_t Lo, size_t Hi, Predicate P) {
1330 while (Lo != Hi) {
1331 assert(Hi > Lo)((Hi > Lo) ? static_cast<void> (0) : __assert_fail (
"Hi > Lo", "/build/llvm-toolchain-snapshot-9~svn362543/include/llvm/ADT/STLExtras.h"
, 1331, __PRETTY_FUNCTION__))
;
1332 size_t Mid = Lo + (Hi - Lo) / 2;
1333 if (P(Mid))
1334 Hi = Mid;
1335 else
1336 Lo = Mid + 1;
1337 }
1338 return Hi;
1339}
1340
1341/// Binary search for the first iterator where a predicate is true.
1342/// Returns the first I in [Lo, Hi) where C(*I) is true, or Hi if it never is.
1343/// Requires that C is always false below some limit, and always true above it.
1344template <typename It, typename Predicate,
1345 typename Val = decltype(*std::declval<It>())>
1346It bsearch(It Lo, It Hi, Predicate P) {
1347 return std::lower_bound(Lo, Hi, 0u,
1348 [&](const Val &V, unsigned) { return !P(V); });
1349}
1350
1351/// Binary search for the first iterator in a range where a predicate is true.
1352/// Requires that C is always false below some limit, and always true above it.
1353template <typename R, typename Predicate>
1354auto bsearch(R &&Range, Predicate P) -> decltype(adl_begin(Range)) {
1355 return bsearch(adl_begin(Range), adl_end(Range), P);
1356}
1357
1358/// Wrapper function around std::equal to detect if all elements
1359/// in a container are same.
1360template <typename R>
1361bool is_splat(R &&Range) {
1362 size_t range_size = size(Range);
1363 return range_size != 0 && (range_size == 1 ||
1364 std::equal(adl_begin(Range) + 1, adl_end(Range), adl_begin(Range)));
1365}
1366
1367/// Given a range of type R, iterate the entire range and return a
1368/// SmallVector with elements of the vector. This is useful, for example,
1369/// when you want to iterate a range and then sort the results.
1370template <unsigned Size, typename R>
1371SmallVector<typename std::remove_const<detail::ValueOfRange<R>>::type, Size>
1372to_vector(R &&Range) {
1373 return {adl_begin(Range), adl_end(Range)};
1374}
1375
1376/// Provide a container algorithm similar to C++ Library Fundamentals v2's
1377/// `erase_if` which is equivalent to:
1378///
1379/// C.erase(remove_if(C, pred), C.end());
1380///
1381/// This version works for any container with an erase method call accepting
1382/// two iterators.
1383template <typename Container, typename UnaryPredicate>
1384void erase_if(Container &C, UnaryPredicate P) {
1385 C.erase(remove_if(C, P), C.end());
1386}
1387
1388//===----------------------------------------------------------------------===//
1389// Extra additions to <memory>
1390//===----------------------------------------------------------------------===//
1391
1392// Implement make_unique according to N3656.
1393
1394/// Constructs a `new T()` with the given args and returns a
1395/// `unique_ptr<T>` which owns the object.
1396///
1397/// Example:
1398///
1399/// auto p = make_unique<int>();
1400/// auto p = make_unique<std::tuple<int, int>>(0, 1);
1401template <class T, class... Args>
1402typename std::enable_if<!std::is_array<T>::value, std::unique_ptr<T>>::type
1403make_unique(Args &&... args) {
1404 return std::unique_ptr<T>(new T(std::forward<Args>(args)...));
6
Memory is allocated
1405}
1406
1407/// Constructs a `new T[n]` with the given args and returns a
1408/// `unique_ptr<T[]>` which owns the object.
1409///
1410/// \param n size of the new array.
1411///
1412/// Example:
1413///
1414/// auto p = make_unique<int[]>(2); // value-initializes the array with 0's.
1415template <class T>
1416typename std::enable_if<std::is_array<T>::value && std::extent<T>::value == 0,
1417 std::unique_ptr<T>>::type
1418make_unique(size_t n) {
1419 return std::unique_ptr<T>(new typename std::remove_extent<T>::type[n]());
1420}
1421
1422/// This function isn't used and is only here to provide better compile errors.
1423template <class T, class... Args>
1424typename std::enable_if<std::extent<T>::value != 0>::type
1425make_unique(Args &&...) = delete;
1426
1427struct FreeDeleter {
1428 void operator()(void* v) {
1429 ::free(v);
1430 }
1431};
1432
1433template<typename First, typename Second>
1434struct pair_hash {
1435 size_t operator()(const std::pair<First, Second> &P) const {
1436 return std::hash<First>()(P.first) * 31 + std::hash<Second>()(P.second);
1437 }
1438};
1439
1440/// A functor like C++14's std::less<void> in its absence.
1441struct less {
1442 template <typename A, typename B> bool operator()(A &&a, B &&b) const {
1443 return std::forward<A>(a) < std::forward<B>(b);
1444 }
1445};
1446
1447/// A functor like C++14's std::equal<void> in its absence.
1448struct equal {
1449 template <typename A, typename B> bool operator()(A &&a, B &&b) const {
1450 return std::forward<A>(a) == std::forward<B>(b);
1451 }
1452};
1453
1454/// Binary functor that adapts to any other binary functor after dereferencing
1455/// operands.
1456template <typename T> struct deref {
1457 T func;
1458
1459 // Could be further improved to cope with non-derivable functors and
1460 // non-binary functors (should be a variadic template member function
1461 // operator()).
1462 template <typename A, typename B>
1463 auto operator()(A &lhs, B &rhs) const -> decltype(func(*lhs, *rhs)) {
1464 assert(lhs)((lhs) ? static_cast<void> (0) : __assert_fail ("lhs", "/build/llvm-toolchain-snapshot-9~svn362543/include/llvm/ADT/STLExtras.h"
, 1464, __PRETTY_FUNCTION__))
;
1465 assert(rhs)((rhs) ? static_cast<void> (0) : __assert_fail ("rhs", "/build/llvm-toolchain-snapshot-9~svn362543/include/llvm/ADT/STLExtras.h"
, 1465, __PRETTY_FUNCTION__))
;
1466 return func(*lhs, *rhs);
1467 }
1468};
1469
1470namespace detail {
1471
1472template <typename R> class enumerator_iter;
1473
1474template <typename R> struct result_pair {
1475 friend class enumerator_iter<R>;
1476
1477 result_pair() = default;
1478 result_pair(std::size_t Index, IterOfRange<R> Iter)
1479 : Index(Index), Iter(Iter) {}
1480
1481 result_pair<R> &operator=(const result_pair<R> &Other) {
1482 Index = Other.Index;
1483 Iter = Other.Iter;
1484 return *this;
1485 }
1486
1487 std::size_t index() const { return Index; }
1488 const ValueOfRange<R> &value() const { return *Iter; }
1489 ValueOfRange<R> &value() { return *Iter; }
1490
1491private:
1492 std::size_t Index = std::numeric_limits<std::size_t>::max();
1493 IterOfRange<R> Iter;
1494};
1495
1496template <typename R>
1497class enumerator_iter
1498 : public iterator_facade_base<
1499 enumerator_iter<R>, std::forward_iterator_tag, result_pair<R>,
1500 typename std::iterator_traits<IterOfRange<R>>::difference_type,
1501 typename std::iterator_traits<IterOfRange<R>>::pointer,
1502 typename std::iterator_traits<IterOfRange<R>>::reference> {
1503 using result_type = result_pair<R>;
1504
1505public:
1506 explicit enumerator_iter(IterOfRange<R> EndIter)
1507 : Result(std::numeric_limits<size_t>::max(), EndIter) {}
1508
1509 enumerator_iter(std::size_t Index, IterOfRange<R> Iter)
1510 : Result(Index, Iter) {}
1511
1512 result_type &operator*() { return Result; }
1513 const result_type &operator*() const { return Result; }
1514
1515 enumerator_iter<R> &operator++() {
1516 assert(Result.Index != std::numeric_limits<size_t>::max())((Result.Index != std::numeric_limits<size_t>::max()) ?
static_cast<void> (0) : __assert_fail ("Result.Index != std::numeric_limits<size_t>::max()"
, "/build/llvm-toolchain-snapshot-9~svn362543/include/llvm/ADT/STLExtras.h"
, 1516, __PRETTY_FUNCTION__))
;
1517 ++Result.Iter;
1518 ++Result.Index;
1519 return *this;
1520 }
1521
1522 bool operator==(const enumerator_iter<R> &RHS) const {
1523 // Don't compare indices here, only iterators. It's possible for an end
1524 // iterator to have different indices depending on whether it was created
1525 // by calling std::end() versus incrementing a valid iterator.
1526 return Result.Iter == RHS.Result.Iter;
1527 }
1528
1529 enumerator_iter<R> &operator=(const enumerator_iter<R> &Other) {
1530 Result = Other.Result;
1531 return *this;
1532 }
1533
1534private:
1535 result_type Result;
1536};
1537
1538template <typename R> class enumerator {
1539public:
1540 explicit enumerator(R &&Range) : TheRange(std::forward<R>(Range)) {}
1541
1542 enumerator_iter<R> begin() {
1543 return enumerator_iter<R>(0, std::begin(TheRange));
1544 }
1545
1546 enumerator_iter<R> end() {
1547 return enumerator_iter<R>(std::end(TheRange));
1548 }
1549
1550private:
1551 R TheRange;
1552};
1553
1554} // end namespace detail
1555
1556/// Given an input range, returns a new range whose values are are pair (A,B)
1557/// such that A is the 0-based index of the item in the sequence, and B is
1558/// the value from the original sequence. Example:
1559///
1560/// std::vector<char> Items = {'A', 'B', 'C', 'D'};
1561/// for (auto X : enumerate(Items)) {
1562/// printf("Item %d - %c\n", X.index(), X.value());
1563/// }
1564///
1565/// Output:
1566/// Item 0 - A
1567/// Item 1 - B
1568/// Item 2 - C
1569/// Item 3 - D
1570///
1571template <typename R> detail::enumerator<R> enumerate(R &&TheRange) {
1572 return detail::enumerator<R>(std::forward<R>(TheRange));
1573}
1574
1575namespace detail {
1576
1577template <typename F, typename Tuple, std::size_t... I>
1578auto apply_tuple_impl(F &&f, Tuple &&t, index_sequence<I...>)
1579 -> decltype(std::forward<F>(f)(std::get<I>(std::forward<Tuple>(t))...)) {
1580 return std::forward<F>(f)(std::get<I>(std::forward<Tuple>(t))...);
1581}
1582
1583} // end namespace detail
1584
1585/// Given an input tuple (a1, a2, ..., an), pass the arguments of the
1586/// tuple variadically to f as if by calling f(a1, a2, ..., an) and
1587/// return the result.
1588template <typename F, typename Tuple>
1589auto apply_tuple(F &&f, Tuple &&t) -> decltype(detail::apply_tuple_impl(
1590 std::forward<F>(f), std::forward<Tuple>(t),
1591 build_index_impl<
1592 std::tuple_size<typename std::decay<Tuple>::type>::value>{})) {
1593 using Indices = build_index_impl<
1594 std::tuple_size<typename std::decay<Tuple>::type>::value>;
1595
1596 return detail::apply_tuple_impl(std::forward<F>(f), std::forward<Tuple>(t),
1597 Indices{});
1598}
1599
1600/// Return true if the sequence [Begin, End) has exactly N items. Runs in O(N)
1601/// time. Not meant for use with random-access iterators.
1602template <typename IterTy>
1603bool hasNItems(
1604 IterTy &&Begin, IterTy &&End, unsigned N,
1605 typename std::enable_if<
1606 !std::is_same<
1607 typename std::iterator_traits<typename std::remove_reference<
1608 decltype(Begin)>::type>::iterator_category,
1609 std::random_access_iterator_tag>::value,
1610 void>::type * = nullptr) {
1611 for (; N; --N, ++Begin)
1612 if (Begin == End)
1613 return false; // Too few.
1614 return Begin == End;
1615}
1616
1617/// Return true if the sequence [Begin, End) has N or more items. Runs in O(N)
1618/// time. Not meant for use with random-access iterators.
1619template <typename IterTy>
1620bool hasNItemsOrMore(
1621 IterTy &&Begin, IterTy &&End, unsigned N,
1622 typename std::enable_if<
1623 !std::is_same<
1624 typename std::iterator_traits<typename std::remove_reference<
1625 decltype(Begin)>::type>::iterator_category,
1626 std::random_access_iterator_tag>::value,
1627 void>::type * = nullptr) {
1628 for (; N; --N, ++Begin)
1629 if (Begin == End)
1630 return false; // Too few.
1631 return true;
1632}
1633
1634/// Returns a raw pointer that represents the same address as the argument.
1635///
1636/// The late bound return should be removed once we move to C++14 to better
1637/// align with the C++20 declaration. Also, this implementation can be removed
1638/// once we move to C++20 where it's defined as std::to_addres()
1639///
1640/// The std::pointer_traits<>::to_address(p) variations of these overloads has
1641/// not been implemented.
1642template <class Ptr> auto to_address(const Ptr &P) -> decltype(P.operator->()) {
1643 return P.operator->();
1644}
1645template <class T> constexpr T *to_address(T *P) { return P; }
1646
1647} // end namespace llvm
1648
1649#endif // LLVM_ADT_STLEXTRAS_H