File: | llvm/lib/Bitcode/Reader/BitcodeReader.cpp |
Warning: | line 2708, column 50 Called C++ object pointer is null |
Press '?' to see keyboard shortcuts
Keyboard shortcuts:
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/BitcodeCommon.h" | ||||
24 | #include "llvm/Bitcode/LLVMBitCodes.h" | ||||
25 | #include "llvm/Bitstream/BitstreamReader.h" | ||||
26 | #include "llvm/Config/llvm-config.h" | ||||
27 | #include "llvm/IR/Argument.h" | ||||
28 | #include "llvm/IR/Attributes.h" | ||||
29 | #include "llvm/IR/AutoUpgrade.h" | ||||
30 | #include "llvm/IR/BasicBlock.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/GlobalObject.h" | ||||
45 | #include "llvm/IR/GlobalValue.h" | ||||
46 | #include "llvm/IR/GlobalVariable.h" | ||||
47 | #include "llvm/IR/InlineAsm.h" | ||||
48 | #include "llvm/IR/InstIterator.h" | ||||
49 | #include "llvm/IR/InstrTypes.h" | ||||
50 | #include "llvm/IR/Instruction.h" | ||||
51 | #include "llvm/IR/Instructions.h" | ||||
52 | #include "llvm/IR/Intrinsics.h" | ||||
53 | #include "llvm/IR/LLVMContext.h" | ||||
54 | #include "llvm/IR/Metadata.h" | ||||
55 | #include "llvm/IR/Module.h" | ||||
56 | #include "llvm/IR/ModuleSummaryIndex.h" | ||||
57 | #include "llvm/IR/Operator.h" | ||||
58 | #include "llvm/IR/Type.h" | ||||
59 | #include "llvm/IR/Value.h" | ||||
60 | #include "llvm/IR/Verifier.h" | ||||
61 | #include "llvm/Support/AtomicOrdering.h" | ||||
62 | #include "llvm/Support/Casting.h" | ||||
63 | #include "llvm/Support/CommandLine.h" | ||||
64 | #include "llvm/Support/Compiler.h" | ||||
65 | #include "llvm/Support/Debug.h" | ||||
66 | #include "llvm/Support/Error.h" | ||||
67 | #include "llvm/Support/ErrorHandling.h" | ||||
68 | #include "llvm/Support/ErrorOr.h" | ||||
69 | #include "llvm/Support/ManagedStatic.h" | ||||
70 | #include "llvm/Support/MathExtras.h" | ||||
71 | #include "llvm/Support/MemoryBuffer.h" | ||||
72 | #include "llvm/Support/raw_ostream.h" | ||||
73 | #include <algorithm> | ||||
74 | #include <cassert> | ||||
75 | #include <cstddef> | ||||
76 | #include <cstdint> | ||||
77 | #include <deque> | ||||
78 | #include <map> | ||||
79 | #include <memory> | ||||
80 | #include <set> | ||||
81 | #include <string> | ||||
82 | #include <system_error> | ||||
83 | #include <tuple> | ||||
84 | #include <utility> | ||||
85 | #include <vector> | ||||
86 | |||||
87 | using namespace llvm; | ||||
88 | |||||
89 | static cl::opt<bool> PrintSummaryGUIDs( | ||||
90 | "print-summary-global-ids", cl::init(false), cl::Hidden, | ||||
91 | cl::desc( | ||||
92 | "Print the global id for each value when reading the module summary")); | ||||
93 | |||||
94 | namespace { | ||||
95 | |||||
96 | enum { | ||||
97 | SWITCH_INST_MAGIC = 0x4B5 // May 2012 => 1205 => Hex | ||||
98 | }; | ||||
99 | |||||
100 | } // end anonymous namespace | ||||
101 | |||||
102 | static Error error(const Twine &Message) { | ||||
103 | return make_error<StringError>( | ||||
104 | Message, make_error_code(BitcodeError::CorruptedBitcode)); | ||||
105 | } | ||||
106 | |||||
107 | static Error hasInvalidBitcodeHeader(BitstreamCursor &Stream) { | ||||
108 | if (!Stream.canSkipToPos(4)) | ||||
109 | return createStringError(std::errc::illegal_byte_sequence, | ||||
110 | "file too small to contain bitcode header"); | ||||
111 | for (unsigned C : {'B', 'C'}) | ||||
112 | if (Expected<SimpleBitstreamCursor::word_t> Res = Stream.Read(8)) { | ||||
113 | if (Res.get() != C) | ||||
114 | return createStringError(std::errc::illegal_byte_sequence, | ||||
115 | "file doesn't start with bitcode header"); | ||||
116 | } else | ||||
117 | return Res.takeError(); | ||||
118 | for (unsigned C : {0x0, 0xC, 0xE, 0xD}) | ||||
119 | if (Expected<SimpleBitstreamCursor::word_t> Res = Stream.Read(4)) { | ||||
120 | if (Res.get() != C) | ||||
121 | return createStringError(std::errc::illegal_byte_sequence, | ||||
122 | "file doesn't start with bitcode header"); | ||||
123 | } else | ||||
124 | return Res.takeError(); | ||||
125 | return Error::success(); | ||||
126 | } | ||||
127 | |||||
128 | static Expected<BitstreamCursor> initStream(MemoryBufferRef Buffer) { | ||||
129 | const unsigned char *BufPtr = (const unsigned char *)Buffer.getBufferStart(); | ||||
130 | const unsigned char *BufEnd = BufPtr + Buffer.getBufferSize(); | ||||
131 | |||||
132 | if (Buffer.getBufferSize() & 3) | ||||
133 | return error("Invalid bitcode signature"); | ||||
134 | |||||
135 | // If we have a wrapper header, parse it and ignore the non-bc file contents. | ||||
136 | // The magic number is 0x0B17C0DE stored in little endian. | ||||
137 | if (isBitcodeWrapper(BufPtr, BufEnd)) | ||||
138 | if (SkipBitcodeWrapperHeader(BufPtr, BufEnd, true)) | ||||
139 | return error("Invalid bitcode wrapper header"); | ||||
140 | |||||
141 | BitstreamCursor Stream(ArrayRef<uint8_t>(BufPtr, BufEnd)); | ||||
142 | if (Error Err = hasInvalidBitcodeHeader(Stream)) | ||||
143 | return std::move(Err); | ||||
144 | |||||
145 | return std::move(Stream); | ||||
146 | } | ||||
147 | |||||
148 | /// Convert a string from a record into an std::string, return true on failure. | ||||
149 | template <typename StrTy> | ||||
150 | static bool convertToString(ArrayRef<uint64_t> Record, unsigned Idx, | ||||
151 | StrTy &Result) { | ||||
152 | if (Idx > Record.size()) | ||||
153 | return true; | ||||
154 | |||||
155 | Result.append(Record.begin() + Idx, Record.end()); | ||||
156 | return false; | ||||
157 | } | ||||
158 | |||||
159 | // Strip all the TBAA attachment for the module. | ||||
160 | static void stripTBAA(Module *M) { | ||||
161 | for (auto &F : *M) { | ||||
162 | if (F.isMaterializable()) | ||||
163 | continue; | ||||
164 | for (auto &I : instructions(F)) | ||||
165 | I.setMetadata(LLVMContext::MD_tbaa, nullptr); | ||||
166 | } | ||||
167 | } | ||||
168 | |||||
169 | /// Read the "IDENTIFICATION_BLOCK_ID" block, do some basic enforcement on the | ||||
170 | /// "epoch" encoded in the bitcode, and return the producer name if any. | ||||
171 | static Expected<std::string> readIdentificationBlock(BitstreamCursor &Stream) { | ||||
172 | if (Error Err = Stream.EnterSubBlock(bitc::IDENTIFICATION_BLOCK_ID)) | ||||
173 | return std::move(Err); | ||||
174 | |||||
175 | // Read all the records. | ||||
176 | SmallVector<uint64_t, 64> Record; | ||||
177 | |||||
178 | std::string ProducerIdentification; | ||||
179 | |||||
180 | while (true) { | ||||
181 | BitstreamEntry Entry; | ||||
182 | if (Error E = Stream.advance().moveInto(Entry)) | ||||
183 | return std::move(E); | ||||
184 | |||||
185 | switch (Entry.Kind) { | ||||
186 | default: | ||||
187 | case BitstreamEntry::Error: | ||||
188 | return error("Malformed block"); | ||||
189 | case BitstreamEntry::EndBlock: | ||||
190 | return ProducerIdentification; | ||||
191 | case BitstreamEntry::Record: | ||||
192 | // The interesting case. | ||||
193 | break; | ||||
194 | } | ||||
195 | |||||
196 | // Read a record. | ||||
197 | Record.clear(); | ||||
198 | Expected<unsigned> MaybeBitCode = Stream.readRecord(Entry.ID, Record); | ||||
199 | if (!MaybeBitCode) | ||||
200 | return MaybeBitCode.takeError(); | ||||
201 | switch (MaybeBitCode.get()) { | ||||
202 | default: // Default behavior: reject | ||||
203 | return error("Invalid value"); | ||||
204 | case bitc::IDENTIFICATION_CODE_STRING: // IDENTIFICATION: [strchr x N] | ||||
205 | convertToString(Record, 0, ProducerIdentification); | ||||
206 | break; | ||||
207 | case bitc::IDENTIFICATION_CODE_EPOCH: { // EPOCH: [epoch#] | ||||
208 | unsigned epoch = (unsigned)Record[0]; | ||||
209 | if (epoch != bitc::BITCODE_CURRENT_EPOCH) { | ||||
210 | return error( | ||||
211 | Twine("Incompatible epoch: Bitcode '") + Twine(epoch) + | ||||
212 | "' vs current: '" + Twine(bitc::BITCODE_CURRENT_EPOCH) + "'"); | ||||
213 | } | ||||
214 | } | ||||
215 | } | ||||
216 | } | ||||
217 | } | ||||
218 | |||||
219 | static Expected<std::string> readIdentificationCode(BitstreamCursor &Stream) { | ||||
220 | // We expect a number of well-defined blocks, though we don't necessarily | ||||
221 | // need to understand them all. | ||||
222 | while (true) { | ||||
223 | if (Stream.AtEndOfStream()) | ||||
224 | return ""; | ||||
225 | |||||
226 | BitstreamEntry Entry; | ||||
227 | if (Error E = Stream.advance().moveInto(Entry)) | ||||
228 | return std::move(E); | ||||
229 | |||||
230 | switch (Entry.Kind) { | ||||
231 | case BitstreamEntry::EndBlock: | ||||
232 | case BitstreamEntry::Error: | ||||
233 | return error("Malformed block"); | ||||
234 | |||||
235 | case BitstreamEntry::SubBlock: | ||||
236 | if (Entry.ID == bitc::IDENTIFICATION_BLOCK_ID) | ||||
237 | return readIdentificationBlock(Stream); | ||||
238 | |||||
239 | // Ignore other sub-blocks. | ||||
240 | if (Error Err = Stream.SkipBlock()) | ||||
241 | return std::move(Err); | ||||
242 | continue; | ||||
243 | case BitstreamEntry::Record: | ||||
244 | if (Error E = Stream.skipRecord(Entry.ID).takeError()) | ||||
245 | return std::move(E); | ||||
246 | continue; | ||||
247 | } | ||||
248 | } | ||||
249 | } | ||||
250 | |||||
251 | static Expected<bool> hasObjCCategoryInModule(BitstreamCursor &Stream) { | ||||
252 | if (Error Err = Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID)) | ||||
253 | return std::move(Err); | ||||
254 | |||||
255 | SmallVector<uint64_t, 64> Record; | ||||
256 | // Read all the records for this module. | ||||
257 | |||||
258 | while (true) { | ||||
259 | Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks(); | ||||
260 | if (!MaybeEntry) | ||||
261 | return MaybeEntry.takeError(); | ||||
262 | BitstreamEntry Entry = MaybeEntry.get(); | ||||
263 | |||||
264 | switch (Entry.Kind) { | ||||
265 | case BitstreamEntry::SubBlock: // Handled for us already. | ||||
266 | case BitstreamEntry::Error: | ||||
267 | return error("Malformed block"); | ||||
268 | case BitstreamEntry::EndBlock: | ||||
269 | return false; | ||||
270 | case BitstreamEntry::Record: | ||||
271 | // The interesting case. | ||||
272 | break; | ||||
273 | } | ||||
274 | |||||
275 | // Read a record. | ||||
276 | Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record); | ||||
277 | if (!MaybeRecord) | ||||
278 | return MaybeRecord.takeError(); | ||||
279 | switch (MaybeRecord.get()) { | ||||
280 | default: | ||||
281 | break; // Default behavior, ignore unknown content. | ||||
282 | case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N] | ||||
283 | std::string S; | ||||
284 | if (convertToString(Record, 0, S)) | ||||
285 | return error("Invalid record"); | ||||
286 | // Check for the i386 and other (x86_64, ARM) conventions | ||||
287 | if (S.find("__DATA,__objc_catlist") != std::string::npos || | ||||
288 | S.find("__OBJC,__category") != std::string::npos) | ||||
289 | return true; | ||||
290 | break; | ||||
291 | } | ||||
292 | } | ||||
293 | Record.clear(); | ||||
294 | } | ||||
295 | llvm_unreachable("Exit infinite loop")::llvm::llvm_unreachable_internal("Exit infinite loop", "llvm/lib/Bitcode/Reader/BitcodeReader.cpp" , 295); | ||||
296 | } | ||||
297 | |||||
298 | static Expected<bool> hasObjCCategory(BitstreamCursor &Stream) { | ||||
299 | // We expect a number of well-defined blocks, though we don't necessarily | ||||
300 | // need to understand them all. | ||||
301 | while (true) { | ||||
302 | BitstreamEntry Entry; | ||||
303 | if (Error E = Stream.advance().moveInto(Entry)) | ||||
304 | return std::move(E); | ||||
305 | |||||
306 | switch (Entry.Kind) { | ||||
307 | case BitstreamEntry::Error: | ||||
308 | return error("Malformed block"); | ||||
309 | case BitstreamEntry::EndBlock: | ||||
310 | return false; | ||||
311 | |||||
312 | case BitstreamEntry::SubBlock: | ||||
313 | if (Entry.ID == bitc::MODULE_BLOCK_ID) | ||||
314 | return hasObjCCategoryInModule(Stream); | ||||
315 | |||||
316 | // Ignore other sub-blocks. | ||||
317 | if (Error Err = Stream.SkipBlock()) | ||||
318 | return std::move(Err); | ||||
319 | continue; | ||||
320 | |||||
321 | case BitstreamEntry::Record: | ||||
322 | if (Error E = Stream.skipRecord(Entry.ID).takeError()) | ||||
323 | return std::move(E); | ||||
324 | continue; | ||||
325 | } | ||||
326 | } | ||||
327 | } | ||||
328 | |||||
329 | static Expected<std::string> readModuleTriple(BitstreamCursor &Stream) { | ||||
330 | if (Error Err = Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID)) | ||||
331 | return std::move(Err); | ||||
332 | |||||
333 | SmallVector<uint64_t, 64> Record; | ||||
334 | |||||
335 | std::string Triple; | ||||
336 | |||||
337 | // Read all the records for this module. | ||||
338 | while (true) { | ||||
339 | Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks(); | ||||
340 | if (!MaybeEntry) | ||||
341 | return MaybeEntry.takeError(); | ||||
342 | BitstreamEntry Entry = MaybeEntry.get(); | ||||
343 | |||||
344 | switch (Entry.Kind) { | ||||
345 | case BitstreamEntry::SubBlock: // Handled for us already. | ||||
346 | case BitstreamEntry::Error: | ||||
347 | return error("Malformed block"); | ||||
348 | case BitstreamEntry::EndBlock: | ||||
349 | return Triple; | ||||
350 | case BitstreamEntry::Record: | ||||
351 | // The interesting case. | ||||
352 | break; | ||||
353 | } | ||||
354 | |||||
355 | // Read a record. | ||||
356 | Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record); | ||||
357 | if (!MaybeRecord) | ||||
358 | return MaybeRecord.takeError(); | ||||
359 | switch (MaybeRecord.get()) { | ||||
360 | default: break; // Default behavior, ignore unknown content. | ||||
361 | case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N] | ||||
362 | std::string S; | ||||
363 | if (convertToString(Record, 0, S)) | ||||
364 | return error("Invalid record"); | ||||
365 | Triple = S; | ||||
366 | break; | ||||
367 | } | ||||
368 | } | ||||
369 | Record.clear(); | ||||
370 | } | ||||
371 | llvm_unreachable("Exit infinite loop")::llvm::llvm_unreachable_internal("Exit infinite loop", "llvm/lib/Bitcode/Reader/BitcodeReader.cpp" , 371); | ||||
372 | } | ||||
373 | |||||
374 | static Expected<std::string> readTriple(BitstreamCursor &Stream) { | ||||
375 | // We expect a number of well-defined blocks, though we don't necessarily | ||||
376 | // need to understand them all. | ||||
377 | while (true) { | ||||
378 | Expected<BitstreamEntry> MaybeEntry = Stream.advance(); | ||||
379 | if (!MaybeEntry) | ||||
380 | return MaybeEntry.takeError(); | ||||
381 | BitstreamEntry Entry = MaybeEntry.get(); | ||||
382 | |||||
383 | switch (Entry.Kind) { | ||||
384 | case BitstreamEntry::Error: | ||||
385 | return error("Malformed block"); | ||||
386 | case BitstreamEntry::EndBlock: | ||||
387 | return ""; | ||||
388 | |||||
389 | case BitstreamEntry::SubBlock: | ||||
390 | if (Entry.ID == bitc::MODULE_BLOCK_ID) | ||||
391 | return readModuleTriple(Stream); | ||||
392 | |||||
393 | // Ignore other sub-blocks. | ||||
394 | if (Error Err = Stream.SkipBlock()) | ||||
395 | return std::move(Err); | ||||
396 | continue; | ||||
397 | |||||
398 | case BitstreamEntry::Record: | ||||
399 | if (llvm::Expected<unsigned> Skipped = Stream.skipRecord(Entry.ID)) | ||||
400 | continue; | ||||
401 | else | ||||
402 | return Skipped.takeError(); | ||||
403 | } | ||||
404 | } | ||||
405 | } | ||||
406 | |||||
407 | namespace { | ||||
408 | |||||
409 | class BitcodeReaderBase { | ||||
410 | protected: | ||||
411 | BitcodeReaderBase(BitstreamCursor Stream, StringRef Strtab) | ||||
412 | : Stream(std::move(Stream)), Strtab(Strtab) { | ||||
413 | this->Stream.setBlockInfo(&BlockInfo); | ||||
414 | } | ||||
415 | |||||
416 | BitstreamBlockInfo BlockInfo; | ||||
417 | BitstreamCursor Stream; | ||||
418 | StringRef Strtab; | ||||
419 | |||||
420 | /// In version 2 of the bitcode we store names of global values and comdats in | ||||
421 | /// a string table rather than in the VST. | ||||
422 | bool UseStrtab = false; | ||||
423 | |||||
424 | Expected<unsigned> parseVersionRecord(ArrayRef<uint64_t> Record); | ||||
425 | |||||
426 | /// If this module uses a string table, pop the reference to the string table | ||||
427 | /// and return the referenced string and the rest of the record. Otherwise | ||||
428 | /// just return the record itself. | ||||
429 | std::pair<StringRef, ArrayRef<uint64_t>> | ||||
430 | readNameFromStrtab(ArrayRef<uint64_t> Record); | ||||
431 | |||||
432 | Error readBlockInfo(); | ||||
433 | |||||
434 | // Contains an arbitrary and optional string identifying the bitcode producer | ||||
435 | std::string ProducerIdentification; | ||||
436 | |||||
437 | Error error(const Twine &Message); | ||||
438 | }; | ||||
439 | |||||
440 | } // end anonymous namespace | ||||
441 | |||||
442 | Error BitcodeReaderBase::error(const Twine &Message) { | ||||
443 | std::string FullMsg = Message.str(); | ||||
444 | if (!ProducerIdentification.empty()) | ||||
445 | FullMsg += " (Producer: '" + ProducerIdentification + "' Reader: 'LLVM " + | ||||
446 | LLVM_VERSION_STRING"15.0.0" "')"; | ||||
447 | return ::error(FullMsg); | ||||
448 | } | ||||
449 | |||||
450 | Expected<unsigned> | ||||
451 | BitcodeReaderBase::parseVersionRecord(ArrayRef<uint64_t> Record) { | ||||
452 | if (Record.empty()) | ||||
453 | return error("Invalid record"); | ||||
454 | unsigned ModuleVersion = Record[0]; | ||||
455 | if (ModuleVersion > 2) | ||||
456 | return error("Invalid value"); | ||||
457 | UseStrtab = ModuleVersion >= 2; | ||||
458 | return ModuleVersion; | ||||
459 | } | ||||
460 | |||||
461 | std::pair<StringRef, ArrayRef<uint64_t>> | ||||
462 | BitcodeReaderBase::readNameFromStrtab(ArrayRef<uint64_t> Record) { | ||||
463 | if (!UseStrtab) | ||||
464 | return {"", Record}; | ||||
465 | // Invalid reference. Let the caller complain about the record being empty. | ||||
466 | if (Record[0] + Record[1] > Strtab.size()) | ||||
467 | return {"", {}}; | ||||
468 | return {StringRef(Strtab.data() + Record[0], Record[1]), Record.slice(2)}; | ||||
469 | } | ||||
470 | |||||
471 | namespace { | ||||
472 | |||||
473 | class BitcodeReader : public BitcodeReaderBase, public GVMaterializer { | ||||
474 | LLVMContext &Context; | ||||
475 | Module *TheModule = nullptr; | ||||
476 | // Next offset to start scanning for lazy parsing of function bodies. | ||||
477 | uint64_t NextUnreadBit = 0; | ||||
478 | // Last function offset found in the VST. | ||||
479 | uint64_t LastFunctionBlockBit = 0; | ||||
480 | bool SeenValueSymbolTable = false; | ||||
481 | uint64_t VSTOffset = 0; | ||||
482 | |||||
483 | std::vector<std::string> SectionTable; | ||||
484 | std::vector<std::string> GCTable; | ||||
485 | |||||
486 | std::vector<Type*> TypeList; | ||||
487 | DenseMap<Function *, FunctionType *> FunctionTypes; | ||||
488 | BitcodeReaderValueList ValueList; | ||||
489 | Optional<MetadataLoader> MDLoader; | ||||
490 | std::vector<Comdat *> ComdatList; | ||||
491 | DenseSet<GlobalObject *> ImplicitComdatObjects; | ||||
492 | SmallVector<Instruction *, 64> InstructionList; | ||||
493 | |||||
494 | std::vector<std::pair<GlobalVariable *, unsigned>> GlobalInits; | ||||
495 | std::vector<std::pair<GlobalValue *, unsigned>> IndirectSymbolInits; | ||||
496 | |||||
497 | struct FunctionOperandInfo { | ||||
498 | Function *F; | ||||
499 | unsigned PersonalityFn; | ||||
500 | unsigned Prefix; | ||||
501 | unsigned Prologue; | ||||
502 | }; | ||||
503 | std::vector<FunctionOperandInfo> FunctionOperands; | ||||
504 | |||||
505 | /// The set of attributes by index. Index zero in the file is for null, and | ||||
506 | /// is thus not represented here. As such all indices are off by one. | ||||
507 | std::vector<AttributeList> MAttributes; | ||||
508 | |||||
509 | /// The set of attribute groups. | ||||
510 | std::map<unsigned, AttributeList> MAttributeGroups; | ||||
511 | |||||
512 | /// While parsing a function body, this is a list of the basic blocks for the | ||||
513 | /// function. | ||||
514 | std::vector<BasicBlock*> FunctionBBs; | ||||
515 | |||||
516 | // When reading the module header, this list is populated with functions that | ||||
517 | // have bodies later in the file. | ||||
518 | std::vector<Function*> FunctionsWithBodies; | ||||
519 | |||||
520 | // When intrinsic functions are encountered which require upgrading they are | ||||
521 | // stored here with their replacement function. | ||||
522 | using UpdatedIntrinsicMap = DenseMap<Function *, Function *>; | ||||
523 | UpdatedIntrinsicMap UpgradedIntrinsics; | ||||
524 | // Intrinsics which were remangled because of types rename | ||||
525 | UpdatedIntrinsicMap RemangledIntrinsics; | ||||
526 | |||||
527 | // Several operations happen after the module header has been read, but | ||||
528 | // before function bodies are processed. This keeps track of whether | ||||
529 | // we've done this yet. | ||||
530 | bool SeenFirstFunctionBody = false; | ||||
531 | |||||
532 | /// When function bodies are initially scanned, this map contains info about | ||||
533 | /// where to find deferred function body in the stream. | ||||
534 | DenseMap<Function*, uint64_t> DeferredFunctionInfo; | ||||
535 | |||||
536 | /// When Metadata block is initially scanned when parsing the module, we may | ||||
537 | /// choose to defer parsing of the metadata. This vector contains info about | ||||
538 | /// which Metadata blocks are deferred. | ||||
539 | std::vector<uint64_t> DeferredMetadataInfo; | ||||
540 | |||||
541 | /// These are basic blocks forward-referenced by block addresses. They are | ||||
542 | /// inserted lazily into functions when they're loaded. The basic block ID is | ||||
543 | /// its index into the vector. | ||||
544 | DenseMap<Function *, std::vector<BasicBlock *>> BasicBlockFwdRefs; | ||||
545 | std::deque<Function *> BasicBlockFwdRefQueue; | ||||
546 | |||||
547 | /// Indicates that we are using a new encoding for instruction operands where | ||||
548 | /// most operands in the current FUNCTION_BLOCK are encoded relative to the | ||||
549 | /// instruction number, for a more compact encoding. Some instruction | ||||
550 | /// operands are not relative to the instruction ID: basic block numbers, and | ||||
551 | /// types. Once the old style function blocks have been phased out, we would | ||||
552 | /// not need this flag. | ||||
553 | bool UseRelativeIDs = false; | ||||
554 | |||||
555 | /// True if all functions will be materialized, negating the need to process | ||||
556 | /// (e.g.) blockaddress forward references. | ||||
557 | bool WillMaterializeAllForwardRefs = false; | ||||
558 | |||||
559 | bool StripDebugInfo = false; | ||||
560 | TBAAVerifier TBAAVerifyHelper; | ||||
561 | |||||
562 | std::vector<std::string> BundleTags; | ||||
563 | SmallVector<SyncScope::ID, 8> SSIDs; | ||||
564 | |||||
565 | public: | ||||
566 | BitcodeReader(BitstreamCursor Stream, StringRef Strtab, | ||||
567 | StringRef ProducerIdentification, LLVMContext &Context); | ||||
568 | |||||
569 | Error materializeForwardReferencedFunctions(); | ||||
570 | |||||
571 | Error materialize(GlobalValue *GV) override; | ||||
572 | Error materializeModule() override; | ||||
573 | std::vector<StructType *> getIdentifiedStructTypes() const override; | ||||
574 | |||||
575 | /// Main interface to parsing a bitcode buffer. | ||||
576 | /// \returns true if an error occurred. | ||||
577 | Error parseBitcodeInto( | ||||
578 | Module *M, bool ShouldLazyLoadMetadata = false, bool IsImporting = false, | ||||
579 | DataLayoutCallbackTy DataLayoutCallback = [](StringRef) { return None; }); | ||||
580 | |||||
581 | static uint64_t decodeSignRotatedValue(uint64_t V); | ||||
582 | |||||
583 | /// Materialize any deferred Metadata block. | ||||
584 | Error materializeMetadata() override; | ||||
585 | |||||
586 | void setStripDebugInfo() override; | ||||
587 | |||||
588 | private: | ||||
589 | std::vector<StructType *> IdentifiedStructTypes; | ||||
590 | StructType *createIdentifiedStructType(LLVMContext &Context, StringRef Name); | ||||
591 | StructType *createIdentifiedStructType(LLVMContext &Context); | ||||
592 | |||||
593 | Type *getTypeByID(unsigned ID); | ||||
594 | |||||
595 | Value *getFnValueByID(unsigned ID, Type *Ty) { | ||||
596 | if (Ty && Ty->isMetadataTy()) | ||||
597 | return MetadataAsValue::get(Ty->getContext(), getFnMetadataByID(ID)); | ||||
598 | return ValueList.getValueFwdRef(ID, Ty); | ||||
599 | } | ||||
600 | |||||
601 | Metadata *getFnMetadataByID(unsigned ID) { | ||||
602 | return MDLoader->getMetadataFwdRefOrLoad(ID); | ||||
603 | } | ||||
604 | |||||
605 | BasicBlock *getBasicBlock(unsigned ID) const { | ||||
606 | if (ID >= FunctionBBs.size()) return nullptr; // Invalid ID | ||||
607 | return FunctionBBs[ID]; | ||||
608 | } | ||||
609 | |||||
610 | AttributeList getAttributes(unsigned i) const { | ||||
611 | if (i-1 < MAttributes.size()) | ||||
612 | return MAttributes[i-1]; | ||||
613 | return AttributeList(); | ||||
614 | } | ||||
615 | |||||
616 | /// Read a value/type pair out of the specified record from slot 'Slot'. | ||||
617 | /// Increment Slot past the number of slots used in the record. Return true on | ||||
618 | /// failure. | ||||
619 | bool getValueTypePair(const SmallVectorImpl<uint64_t> &Record, unsigned &Slot, | ||||
620 | unsigned InstNum, Value *&ResVal) { | ||||
621 | if (Slot == Record.size()) return true; | ||||
622 | unsigned ValNo = (unsigned)Record[Slot++]; | ||||
623 | // Adjust the ValNo, if it was encoded relative to the InstNum. | ||||
624 | if (UseRelativeIDs) | ||||
625 | ValNo = InstNum - ValNo; | ||||
626 | if (ValNo < InstNum) { | ||||
627 | // If this is not a forward reference, just return the value we already | ||||
628 | // have. | ||||
629 | ResVal = getFnValueByID(ValNo, nullptr); | ||||
630 | return ResVal == nullptr; | ||||
631 | } | ||||
632 | if (Slot == Record.size()) | ||||
633 | return true; | ||||
634 | |||||
635 | unsigned TypeNo = (unsigned)Record[Slot++]; | ||||
636 | ResVal = getFnValueByID(ValNo, getTypeByID(TypeNo)); | ||||
637 | return ResVal == nullptr; | ||||
638 | } | ||||
639 | |||||
640 | /// Read a value out of the specified record from slot 'Slot'. Increment Slot | ||||
641 | /// past the number of slots used by the value in the record. Return true if | ||||
642 | /// there is an error. | ||||
643 | bool popValue(const SmallVectorImpl<uint64_t> &Record, unsigned &Slot, | ||||
644 | unsigned InstNum, Type *Ty, Value *&ResVal) { | ||||
645 | if (getValue(Record, Slot, InstNum, Ty, ResVal)) | ||||
646 | return true; | ||||
647 | // All values currently take a single record slot. | ||||
648 | ++Slot; | ||||
649 | return false; | ||||
650 | } | ||||
651 | |||||
652 | /// Like popValue, but does not increment the Slot number. | ||||
653 | bool getValue(const SmallVectorImpl<uint64_t> &Record, unsigned Slot, | ||||
654 | unsigned InstNum, Type *Ty, Value *&ResVal) { | ||||
655 | ResVal = getValue(Record, Slot, InstNum, Ty); | ||||
656 | return ResVal == nullptr; | ||||
657 | } | ||||
658 | |||||
659 | /// Version of getValue that returns ResVal directly, or 0 if there is an | ||||
660 | /// error. | ||||
661 | Value *getValue(const SmallVectorImpl<uint64_t> &Record, unsigned Slot, | ||||
662 | unsigned InstNum, Type *Ty) { | ||||
663 | if (Slot == Record.size()) return nullptr; | ||||
664 | unsigned ValNo = (unsigned)Record[Slot]; | ||||
665 | // Adjust the ValNo, if it was encoded relative to the InstNum. | ||||
666 | if (UseRelativeIDs) | ||||
667 | ValNo = InstNum - ValNo; | ||||
668 | return getFnValueByID(ValNo, Ty); | ||||
669 | } | ||||
670 | |||||
671 | /// Like getValue, but decodes signed VBRs. | ||||
672 | Value *getValueSigned(const SmallVectorImpl<uint64_t> &Record, unsigned Slot, | ||||
673 | unsigned InstNum, Type *Ty) { | ||||
674 | if (Slot == Record.size()) return nullptr; | ||||
675 | unsigned ValNo = (unsigned)decodeSignRotatedValue(Record[Slot]); | ||||
676 | // Adjust the ValNo, if it was encoded relative to the InstNum. | ||||
677 | if (UseRelativeIDs) | ||||
678 | ValNo = InstNum - ValNo; | ||||
679 | return getFnValueByID(ValNo, Ty); | ||||
680 | } | ||||
681 | |||||
682 | /// Upgrades old-style typeless byval/sret/inalloca attributes by adding the | ||||
683 | /// corresponding argument's pointee type. Also upgrades intrinsics that now | ||||
684 | /// require an elementtype attribute. | ||||
685 | void propagateAttributeTypes(CallBase *CB, ArrayRef<Type *> ArgsTys); | ||||
686 | |||||
687 | /// Converts alignment exponent (i.e. power of two (or zero)) to the | ||||
688 | /// corresponding alignment to use. If alignment is too large, returns | ||||
689 | /// a corresponding error code. | ||||
690 | Error parseAlignmentValue(uint64_t Exponent, MaybeAlign &Alignment); | ||||
691 | Error parseAttrKind(uint64_t Code, Attribute::AttrKind *Kind); | ||||
692 | Error parseModule( | ||||
693 | uint64_t ResumeBit, bool ShouldLazyLoadMetadata = false, | ||||
694 | DataLayoutCallbackTy DataLayoutCallback = [](StringRef) { return None; }); | ||||
695 | |||||
696 | Error parseComdatRecord(ArrayRef<uint64_t> Record); | ||||
697 | Error parseGlobalVarRecord(ArrayRef<uint64_t> Record); | ||||
698 | Error parseFunctionRecord(ArrayRef<uint64_t> Record); | ||||
699 | Error parseGlobalIndirectSymbolRecord(unsigned BitCode, | ||||
700 | ArrayRef<uint64_t> Record); | ||||
701 | |||||
702 | Error parseAttributeBlock(); | ||||
703 | Error parseAttributeGroupBlock(); | ||||
704 | Error parseTypeTable(); | ||||
705 | Error parseTypeTableBody(); | ||||
706 | Error parseOperandBundleTags(); | ||||
707 | Error parseSyncScopeNames(); | ||||
708 | |||||
709 | Expected<Value *> recordValue(SmallVectorImpl<uint64_t> &Record, | ||||
710 | unsigned NameIndex, Triple &TT); | ||||
711 | void setDeferredFunctionInfo(unsigned FuncBitcodeOffsetDelta, Function *F, | ||||
712 | ArrayRef<uint64_t> Record); | ||||
713 | Error parseValueSymbolTable(uint64_t Offset = 0); | ||||
714 | Error parseGlobalValueSymbolTable(); | ||||
715 | Error parseConstants(); | ||||
716 | Error rememberAndSkipFunctionBodies(); | ||||
717 | Error rememberAndSkipFunctionBody(); | ||||
718 | /// Save the positions of the Metadata blocks and skip parsing the blocks. | ||||
719 | Error rememberAndSkipMetadata(); | ||||
720 | Error typeCheckLoadStoreInst(Type *ValType, Type *PtrType); | ||||
721 | Error parseFunctionBody(Function *F); | ||||
722 | Error globalCleanup(); | ||||
723 | Error resolveGlobalAndIndirectSymbolInits(); | ||||
724 | Error parseUseLists(); | ||||
725 | Error findFunctionInStream( | ||||
726 | Function *F, | ||||
727 | DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator); | ||||
728 | |||||
729 | SyncScope::ID getDecodedSyncScopeID(unsigned Val); | ||||
730 | }; | ||||
731 | |||||
732 | /// Class to manage reading and parsing function summary index bitcode | ||||
733 | /// files/sections. | ||||
734 | class ModuleSummaryIndexBitcodeReader : public BitcodeReaderBase { | ||||
735 | /// The module index built during parsing. | ||||
736 | ModuleSummaryIndex &TheIndex; | ||||
737 | |||||
738 | /// Indicates whether we have encountered a global value summary section | ||||
739 | /// yet during parsing. | ||||
740 | bool SeenGlobalValSummary = false; | ||||
741 | |||||
742 | /// Indicates whether we have already parsed the VST, used for error checking. | ||||
743 | bool SeenValueSymbolTable = false; | ||||
744 | |||||
745 | /// Set to the offset of the VST recorded in the MODULE_CODE_VSTOFFSET record. | ||||
746 | /// Used to enable on-demand parsing of the VST. | ||||
747 | uint64_t VSTOffset = 0; | ||||
748 | |||||
749 | // Map to save ValueId to ValueInfo association that was recorded in the | ||||
750 | // ValueSymbolTable. It is used after the VST is parsed to convert | ||||
751 | // call graph edges read from the function summary from referencing | ||||
752 | // callees by their ValueId to using the ValueInfo instead, which is how | ||||
753 | // they are recorded in the summary index being built. | ||||
754 | // We save a GUID which refers to the same global as the ValueInfo, but | ||||
755 | // ignoring the linkage, i.e. for values other than local linkage they are | ||||
756 | // identical. | ||||
757 | DenseMap<unsigned, std::pair<ValueInfo, GlobalValue::GUID>> | ||||
758 | ValueIdToValueInfoMap; | ||||
759 | |||||
760 | /// Map populated during module path string table parsing, from the | ||||
761 | /// module ID to a string reference owned by the index's module | ||||
762 | /// path string table, used to correlate with combined index | ||||
763 | /// summary records. | ||||
764 | DenseMap<uint64_t, StringRef> ModuleIdMap; | ||||
765 | |||||
766 | /// Original source file name recorded in a bitcode record. | ||||
767 | std::string SourceFileName; | ||||
768 | |||||
769 | /// The string identifier given to this module by the client, normally the | ||||
770 | /// path to the bitcode file. | ||||
771 | StringRef ModulePath; | ||||
772 | |||||
773 | /// For per-module summary indexes, the unique numerical identifier given to | ||||
774 | /// this module by the client. | ||||
775 | unsigned ModuleId; | ||||
776 | |||||
777 | public: | ||||
778 | ModuleSummaryIndexBitcodeReader(BitstreamCursor Stream, StringRef Strtab, | ||||
779 | ModuleSummaryIndex &TheIndex, | ||||
780 | StringRef ModulePath, unsigned ModuleId); | ||||
781 | |||||
782 | Error parseModule(); | ||||
783 | |||||
784 | private: | ||||
785 | void setValueGUID(uint64_t ValueID, StringRef ValueName, | ||||
786 | GlobalValue::LinkageTypes Linkage, | ||||
787 | StringRef SourceFileName); | ||||
788 | Error parseValueSymbolTable( | ||||
789 | uint64_t Offset, | ||||
790 | DenseMap<unsigned, GlobalValue::LinkageTypes> &ValueIdToLinkageMap); | ||||
791 | std::vector<ValueInfo> makeRefList(ArrayRef<uint64_t> Record); | ||||
792 | std::vector<FunctionSummary::EdgeTy> makeCallList(ArrayRef<uint64_t> Record, | ||||
793 | bool IsOldProfileFormat, | ||||
794 | bool HasProfile, | ||||
795 | bool HasRelBF); | ||||
796 | Error parseEntireSummary(unsigned ID); | ||||
797 | Error parseModuleStringTable(); | ||||
798 | void parseTypeIdCompatibleVtableSummaryRecord(ArrayRef<uint64_t> Record); | ||||
799 | void parseTypeIdCompatibleVtableInfo(ArrayRef<uint64_t> Record, size_t &Slot, | ||||
800 | TypeIdCompatibleVtableInfo &TypeId); | ||||
801 | std::vector<FunctionSummary::ParamAccess> | ||||
802 | parseParamAccesses(ArrayRef<uint64_t> Record); | ||||
803 | |||||
804 | std::pair<ValueInfo, GlobalValue::GUID> | ||||
805 | getValueInfoFromValueId(unsigned ValueId); | ||||
806 | |||||
807 | void addThisModule(); | ||||
808 | ModuleSummaryIndex::ModuleInfo *getThisModule(); | ||||
809 | }; | ||||
810 | |||||
811 | } // end anonymous namespace | ||||
812 | |||||
813 | std::error_code llvm::errorToErrorCodeAndEmitErrors(LLVMContext &Ctx, | ||||
814 | Error Err) { | ||||
815 | if (Err) { | ||||
816 | std::error_code EC; | ||||
817 | handleAllErrors(std::move(Err), [&](ErrorInfoBase &EIB) { | ||||
818 | EC = EIB.convertToErrorCode(); | ||||
819 | Ctx.emitError(EIB.message()); | ||||
820 | }); | ||||
821 | return EC; | ||||
822 | } | ||||
823 | return std::error_code(); | ||||
824 | } | ||||
825 | |||||
826 | BitcodeReader::BitcodeReader(BitstreamCursor Stream, StringRef Strtab, | ||||
827 | StringRef ProducerIdentification, | ||||
828 | LLVMContext &Context) | ||||
829 | : BitcodeReaderBase(std::move(Stream), Strtab), Context(Context), | ||||
830 | ValueList(Context, Stream.SizeInBytes()) { | ||||
831 | this->ProducerIdentification = std::string(ProducerIdentification); | ||||
832 | } | ||||
833 | |||||
834 | Error BitcodeReader::materializeForwardReferencedFunctions() { | ||||
835 | if (WillMaterializeAllForwardRefs) | ||||
836 | return Error::success(); | ||||
837 | |||||
838 | // Prevent recursion. | ||||
839 | WillMaterializeAllForwardRefs = true; | ||||
840 | |||||
841 | while (!BasicBlockFwdRefQueue.empty()) { | ||||
842 | Function *F = BasicBlockFwdRefQueue.front(); | ||||
843 | BasicBlockFwdRefQueue.pop_front(); | ||||
844 | assert(F && "Expected valid function")(static_cast <bool> (F && "Expected valid function" ) ? void (0) : __assert_fail ("F && \"Expected valid function\"" , "llvm/lib/Bitcode/Reader/BitcodeReader.cpp", 844, __extension__ __PRETTY_FUNCTION__)); | ||||
845 | if (!BasicBlockFwdRefs.count(F)) | ||||
846 | // Already materialized. | ||||
847 | continue; | ||||
848 | |||||
849 | // Check for a function that isn't materializable to prevent an infinite | ||||
850 | // loop. When parsing a blockaddress stored in a global variable, there | ||||
851 | // isn't a trivial way to check if a function will have a body without a | ||||
852 | // linear search through FunctionsWithBodies, so just check it here. | ||||
853 | if (!F->isMaterializable()) | ||||
854 | return error("Never resolved function from blockaddress"); | ||||
855 | |||||
856 | // Try to materialize F. | ||||
857 | if (Error Err = materialize(F)) | ||||
858 | return Err; | ||||
859 | } | ||||
860 | assert(BasicBlockFwdRefs.empty() && "Function missing from queue")(static_cast <bool> (BasicBlockFwdRefs.empty() && "Function missing from queue") ? void (0) : __assert_fail ("BasicBlockFwdRefs.empty() && \"Function missing from queue\"" , "llvm/lib/Bitcode/Reader/BitcodeReader.cpp", 860, __extension__ __PRETTY_FUNCTION__)); | ||||
861 | |||||
862 | // Reset state. | ||||
863 | WillMaterializeAllForwardRefs = false; | ||||
864 | return Error::success(); | ||||
865 | } | ||||
866 | |||||
867 | //===----------------------------------------------------------------------===// | ||||
868 | // Helper functions to implement forward reference resolution, etc. | ||||
869 | //===----------------------------------------------------------------------===// | ||||
870 | |||||
871 | static bool hasImplicitComdat(size_t Val) { | ||||
872 | switch (Val) { | ||||
873 | default: | ||||
874 | return false; | ||||
875 | case 1: // Old WeakAnyLinkage | ||||
876 | case 4: // Old LinkOnceAnyLinkage | ||||
877 | case 10: // Old WeakODRLinkage | ||||
878 | case 11: // Old LinkOnceODRLinkage | ||||
879 | return true; | ||||
880 | } | ||||
881 | } | ||||
882 | |||||
883 | static GlobalValue::LinkageTypes getDecodedLinkage(unsigned Val) { | ||||
884 | switch (Val) { | ||||
885 | default: // Map unknown/new linkages to external | ||||
886 | case 0: | ||||
887 | return GlobalValue::ExternalLinkage; | ||||
888 | case 2: | ||||
889 | return GlobalValue::AppendingLinkage; | ||||
890 | case 3: | ||||
891 | return GlobalValue::InternalLinkage; | ||||
892 | case 5: | ||||
893 | return GlobalValue::ExternalLinkage; // Obsolete DLLImportLinkage | ||||
894 | case 6: | ||||
895 | return GlobalValue::ExternalLinkage; // Obsolete DLLExportLinkage | ||||
896 | case 7: | ||||
897 | return GlobalValue::ExternalWeakLinkage; | ||||
898 | case 8: | ||||
899 | return GlobalValue::CommonLinkage; | ||||
900 | case 9: | ||||
901 | return GlobalValue::PrivateLinkage; | ||||
902 | case 12: | ||||
903 | return GlobalValue::AvailableExternallyLinkage; | ||||
904 | case 13: | ||||
905 | return GlobalValue::PrivateLinkage; // Obsolete LinkerPrivateLinkage | ||||
906 | case 14: | ||||
907 | return GlobalValue::PrivateLinkage; // Obsolete LinkerPrivateWeakLinkage | ||||
908 | case 15: | ||||
909 | return GlobalValue::ExternalLinkage; // Obsolete LinkOnceODRAutoHideLinkage | ||||
910 | case 1: // Old value with implicit comdat. | ||||
911 | case 16: | ||||
912 | return GlobalValue::WeakAnyLinkage; | ||||
913 | case 10: // Old value with implicit comdat. | ||||
914 | case 17: | ||||
915 | return GlobalValue::WeakODRLinkage; | ||||
916 | case 4: // Old value with implicit comdat. | ||||
917 | case 18: | ||||
918 | return GlobalValue::LinkOnceAnyLinkage; | ||||
919 | case 11: // Old value with implicit comdat. | ||||
920 | case 19: | ||||
921 | return GlobalValue::LinkOnceODRLinkage; | ||||
922 | } | ||||
923 | } | ||||
924 | |||||
925 | static FunctionSummary::FFlags getDecodedFFlags(uint64_t RawFlags) { | ||||
926 | FunctionSummary::FFlags Flags; | ||||
927 | Flags.ReadNone = RawFlags & 0x1; | ||||
928 | Flags.ReadOnly = (RawFlags >> 1) & 0x1; | ||||
929 | Flags.NoRecurse = (RawFlags >> 2) & 0x1; | ||||
930 | Flags.ReturnDoesNotAlias = (RawFlags >> 3) & 0x1; | ||||
931 | Flags.NoInline = (RawFlags >> 4) & 0x1; | ||||
932 | Flags.AlwaysInline = (RawFlags >> 5) & 0x1; | ||||
933 | Flags.NoUnwind = (RawFlags >> 6) & 0x1; | ||||
934 | Flags.MayThrow = (RawFlags >> 7) & 0x1; | ||||
935 | Flags.HasUnknownCall = (RawFlags >> 8) & 0x1; | ||||
936 | Flags.MustBeUnreachable = (RawFlags >> 9) & 0x1; | ||||
937 | return Flags; | ||||
938 | } | ||||
939 | |||||
940 | // Decode the flags for GlobalValue in the summary. The bits for each attribute: | ||||
941 | // | ||||
942 | // linkage: [0,4), notEligibleToImport: 4, live: 5, local: 6, canAutoHide: 7, | ||||
943 | // visibility: [8, 10). | ||||
944 | static GlobalValueSummary::GVFlags getDecodedGVSummaryFlags(uint64_t RawFlags, | ||||
945 | uint64_t Version) { | ||||
946 | // Summary were not emitted before LLVM 3.9, we don't need to upgrade Linkage | ||||
947 | // like getDecodedLinkage() above. Any future change to the linkage enum and | ||||
948 | // to getDecodedLinkage() will need to be taken into account here as above. | ||||
949 | auto Linkage = GlobalValue::LinkageTypes(RawFlags & 0xF); // 4 bits | ||||
950 | auto Visibility = GlobalValue::VisibilityTypes((RawFlags >> 8) & 3); // 2 bits | ||||
951 | RawFlags = RawFlags >> 4; | ||||
952 | bool NotEligibleToImport = (RawFlags & 0x1) || Version < 3; | ||||
953 | // The Live flag wasn't introduced until version 3. For dead stripping | ||||
954 | // to work correctly on earlier versions, we must conservatively treat all | ||||
955 | // values as live. | ||||
956 | bool Live = (RawFlags & 0x2) || Version < 3; | ||||
957 | bool Local = (RawFlags & 0x4); | ||||
958 | bool AutoHide = (RawFlags & 0x8); | ||||
959 | |||||
960 | return GlobalValueSummary::GVFlags(Linkage, Visibility, NotEligibleToImport, | ||||
961 | Live, Local, AutoHide); | ||||
962 | } | ||||
963 | |||||
964 | // Decode the flags for GlobalVariable in the summary | ||||
965 | static GlobalVarSummary::GVarFlags getDecodedGVarFlags(uint64_t RawFlags) { | ||||
966 | return GlobalVarSummary::GVarFlags( | ||||
967 | (RawFlags & 0x1) ? true : false, (RawFlags & 0x2) ? true : false, | ||||
968 | (RawFlags & 0x4) ? true : false, | ||||
969 | (GlobalObject::VCallVisibility)(RawFlags >> 3)); | ||||
970 | } | ||||
971 | |||||
972 | static GlobalValue::VisibilityTypes getDecodedVisibility(unsigned Val) { | ||||
973 | switch (Val) { | ||||
974 | default: // Map unknown visibilities to default. | ||||
975 | case 0: return GlobalValue::DefaultVisibility; | ||||
976 | case 1: return GlobalValue::HiddenVisibility; | ||||
977 | case 2: return GlobalValue::ProtectedVisibility; | ||||
978 | } | ||||
979 | } | ||||
980 | |||||
981 | static GlobalValue::DLLStorageClassTypes | ||||
982 | getDecodedDLLStorageClass(unsigned Val) { | ||||
983 | switch (Val) { | ||||
984 | default: // Map unknown values to default. | ||||
985 | case 0: return GlobalValue::DefaultStorageClass; | ||||
986 | case 1: return GlobalValue::DLLImportStorageClass; | ||||
987 | case 2: return GlobalValue::DLLExportStorageClass; | ||||
988 | } | ||||
989 | } | ||||
990 | |||||
991 | static bool getDecodedDSOLocal(unsigned Val) { | ||||
992 | switch(Val) { | ||||
993 | default: // Map unknown values to preemptable. | ||||
994 | case 0: return false; | ||||
995 | case 1: return true; | ||||
996 | } | ||||
997 | } | ||||
998 | |||||
999 | static GlobalVariable::ThreadLocalMode getDecodedThreadLocalMode(unsigned Val) { | ||||
1000 | switch (Val) { | ||||
1001 | case 0: return GlobalVariable::NotThreadLocal; | ||||
1002 | default: // Map unknown non-zero value to general dynamic. | ||||
1003 | case 1: return GlobalVariable::GeneralDynamicTLSModel; | ||||
1004 | case 2: return GlobalVariable::LocalDynamicTLSModel; | ||||
1005 | case 3: return GlobalVariable::InitialExecTLSModel; | ||||
1006 | case 4: return GlobalVariable::LocalExecTLSModel; | ||||
1007 | } | ||||
1008 | } | ||||
1009 | |||||
1010 | static GlobalVariable::UnnamedAddr getDecodedUnnamedAddrType(unsigned Val) { | ||||
1011 | switch (Val) { | ||||
1012 | default: // Map unknown to UnnamedAddr::None. | ||||
1013 | case 0: return GlobalVariable::UnnamedAddr::None; | ||||
1014 | case 1: return GlobalVariable::UnnamedAddr::Global; | ||||
1015 | case 2: return GlobalVariable::UnnamedAddr::Local; | ||||
1016 | } | ||||
1017 | } | ||||
1018 | |||||
1019 | static int getDecodedCastOpcode(unsigned Val) { | ||||
1020 | switch (Val) { | ||||
1021 | default: return -1; | ||||
1022 | case bitc::CAST_TRUNC : return Instruction::Trunc; | ||||
1023 | case bitc::CAST_ZEXT : return Instruction::ZExt; | ||||
1024 | case bitc::CAST_SEXT : return Instruction::SExt; | ||||
1025 | case bitc::CAST_FPTOUI : return Instruction::FPToUI; | ||||
1026 | case bitc::CAST_FPTOSI : return Instruction::FPToSI; | ||||
1027 | case bitc::CAST_UITOFP : return Instruction::UIToFP; | ||||
1028 | case bitc::CAST_SITOFP : return Instruction::SIToFP; | ||||
1029 | case bitc::CAST_FPTRUNC : return Instruction::FPTrunc; | ||||
1030 | case bitc::CAST_FPEXT : return Instruction::FPExt; | ||||
1031 | case bitc::CAST_PTRTOINT: return Instruction::PtrToInt; | ||||
1032 | case bitc::CAST_INTTOPTR: return Instruction::IntToPtr; | ||||
1033 | case bitc::CAST_BITCAST : return Instruction::BitCast; | ||||
1034 | case bitc::CAST_ADDRSPACECAST: return Instruction::AddrSpaceCast; | ||||
1035 | } | ||||
1036 | } | ||||
1037 | |||||
1038 | static int getDecodedUnaryOpcode(unsigned Val, Type *Ty) { | ||||
1039 | bool IsFP = Ty->isFPOrFPVectorTy(); | ||||
1040 | // UnOps are only valid for int/fp or vector of int/fp types | ||||
1041 | if (!IsFP && !Ty->isIntOrIntVectorTy()) | ||||
1042 | return -1; | ||||
1043 | |||||
1044 | switch (Val) { | ||||
1045 | default: | ||||
1046 | return -1; | ||||
1047 | case bitc::UNOP_FNEG: | ||||
1048 | return IsFP ? Instruction::FNeg : -1; | ||||
1049 | } | ||||
1050 | } | ||||
1051 | |||||
1052 | static int getDecodedBinaryOpcode(unsigned Val, Type *Ty) { | ||||
1053 | bool IsFP = Ty->isFPOrFPVectorTy(); | ||||
1054 | // BinOps are only valid for int/fp or vector of int/fp types | ||||
1055 | if (!IsFP && !Ty->isIntOrIntVectorTy()) | ||||
1056 | return -1; | ||||
1057 | |||||
1058 | switch (Val) { | ||||
1059 | default: | ||||
1060 | return -1; | ||||
1061 | case bitc::BINOP_ADD: | ||||
1062 | return IsFP ? Instruction::FAdd : Instruction::Add; | ||||
1063 | case bitc::BINOP_SUB: | ||||
1064 | return IsFP ? Instruction::FSub : Instruction::Sub; | ||||
1065 | case bitc::BINOP_MUL: | ||||
1066 | return IsFP ? Instruction::FMul : Instruction::Mul; | ||||
1067 | case bitc::BINOP_UDIV: | ||||
1068 | return IsFP ? -1 : Instruction::UDiv; | ||||
1069 | case bitc::BINOP_SDIV: | ||||
1070 | return IsFP ? Instruction::FDiv : Instruction::SDiv; | ||||
1071 | case bitc::BINOP_UREM: | ||||
1072 | return IsFP ? -1 : Instruction::URem; | ||||
1073 | case bitc::BINOP_SREM: | ||||
1074 | return IsFP ? Instruction::FRem : Instruction::SRem; | ||||
1075 | case bitc::BINOP_SHL: | ||||
1076 | return IsFP ? -1 : Instruction::Shl; | ||||
1077 | case bitc::BINOP_LSHR: | ||||
1078 | return IsFP ? -1 : Instruction::LShr; | ||||
1079 | case bitc::BINOP_ASHR: | ||||
1080 | return IsFP ? -1 : Instruction::AShr; | ||||
1081 | case bitc::BINOP_AND: | ||||
1082 | return IsFP ? -1 : Instruction::And; | ||||
1083 | case bitc::BINOP_OR: | ||||
1084 | return IsFP ? -1 : Instruction::Or; | ||||
1085 | case bitc::BINOP_XOR: | ||||
1086 | return IsFP ? -1 : Instruction::Xor; | ||||
1087 | } | ||||
1088 | } | ||||
1089 | |||||
1090 | static AtomicRMWInst::BinOp getDecodedRMWOperation(unsigned Val) { | ||||
1091 | switch (Val) { | ||||
1092 | default: return AtomicRMWInst::BAD_BINOP; | ||||
1093 | case bitc::RMW_XCHG: return AtomicRMWInst::Xchg; | ||||
1094 | case bitc::RMW_ADD: return AtomicRMWInst::Add; | ||||
1095 | case bitc::RMW_SUB: return AtomicRMWInst::Sub; | ||||
1096 | case bitc::RMW_AND: return AtomicRMWInst::And; | ||||
1097 | case bitc::RMW_NAND: return AtomicRMWInst::Nand; | ||||
1098 | case bitc::RMW_OR: return AtomicRMWInst::Or; | ||||
1099 | case bitc::RMW_XOR: return AtomicRMWInst::Xor; | ||||
1100 | case bitc::RMW_MAX: return AtomicRMWInst::Max; | ||||
1101 | case bitc::RMW_MIN: return AtomicRMWInst::Min; | ||||
1102 | case bitc::RMW_UMAX: return AtomicRMWInst::UMax; | ||||
1103 | case bitc::RMW_UMIN: return AtomicRMWInst::UMin; | ||||
1104 | case bitc::RMW_FADD: return AtomicRMWInst::FAdd; | ||||
1105 | case bitc::RMW_FSUB: return AtomicRMWInst::FSub; | ||||
1106 | } | ||||
1107 | } | ||||
1108 | |||||
1109 | static AtomicOrdering getDecodedOrdering(unsigned Val) { | ||||
1110 | switch (Val) { | ||||
1111 | case bitc::ORDERING_NOTATOMIC: return AtomicOrdering::NotAtomic; | ||||
1112 | case bitc::ORDERING_UNORDERED: return AtomicOrdering::Unordered; | ||||
1113 | case bitc::ORDERING_MONOTONIC: return AtomicOrdering::Monotonic; | ||||
1114 | case bitc::ORDERING_ACQUIRE: return AtomicOrdering::Acquire; | ||||
1115 | case bitc::ORDERING_RELEASE: return AtomicOrdering::Release; | ||||
1116 | case bitc::ORDERING_ACQREL: return AtomicOrdering::AcquireRelease; | ||||
1117 | default: // Map unknown orderings to sequentially-consistent. | ||||
1118 | case bitc::ORDERING_SEQCST: return AtomicOrdering::SequentiallyConsistent; | ||||
1119 | } | ||||
1120 | } | ||||
1121 | |||||
1122 | static Comdat::SelectionKind getDecodedComdatSelectionKind(unsigned Val) { | ||||
1123 | switch (Val) { | ||||
1124 | default: // Map unknown selection kinds to any. | ||||
1125 | case bitc::COMDAT_SELECTION_KIND_ANY: | ||||
1126 | return Comdat::Any; | ||||
1127 | case bitc::COMDAT_SELECTION_KIND_EXACT_MATCH: | ||||
1128 | return Comdat::ExactMatch; | ||||
1129 | case bitc::COMDAT_SELECTION_KIND_LARGEST: | ||||
1130 | return Comdat::Largest; | ||||
1131 | case bitc::COMDAT_SELECTION_KIND_NO_DUPLICATES: | ||||
1132 | return Comdat::NoDeduplicate; | ||||
1133 | case bitc::COMDAT_SELECTION_KIND_SAME_SIZE: | ||||
1134 | return Comdat::SameSize; | ||||
1135 | } | ||||
1136 | } | ||||
1137 | |||||
1138 | static FastMathFlags getDecodedFastMathFlags(unsigned Val) { | ||||
1139 | FastMathFlags FMF; | ||||
1140 | if (0 != (Val & bitc::UnsafeAlgebra)) | ||||
1141 | FMF.setFast(); | ||||
1142 | if (0 != (Val & bitc::AllowReassoc)) | ||||
1143 | FMF.setAllowReassoc(); | ||||
1144 | if (0 != (Val & bitc::NoNaNs)) | ||||
1145 | FMF.setNoNaNs(); | ||||
1146 | if (0 != (Val & bitc::NoInfs)) | ||||
1147 | FMF.setNoInfs(); | ||||
1148 | if (0 != (Val & bitc::NoSignedZeros)) | ||||
1149 | FMF.setNoSignedZeros(); | ||||
1150 | if (0 != (Val & bitc::AllowReciprocal)) | ||||
1151 | FMF.setAllowReciprocal(); | ||||
1152 | if (0 != (Val & bitc::AllowContract)) | ||||
1153 | FMF.setAllowContract(true); | ||||
1154 | if (0 != (Val & bitc::ApproxFunc)) | ||||
1155 | FMF.setApproxFunc(); | ||||
1156 | return FMF; | ||||
1157 | } | ||||
1158 | |||||
1159 | static void upgradeDLLImportExportLinkage(GlobalValue *GV, unsigned Val) { | ||||
1160 | switch (Val) { | ||||
1161 | case 5: GV->setDLLStorageClass(GlobalValue::DLLImportStorageClass); break; | ||||
1162 | case 6: GV->setDLLStorageClass(GlobalValue::DLLExportStorageClass); break; | ||||
1163 | } | ||||
1164 | } | ||||
1165 | |||||
1166 | Type *BitcodeReader::getTypeByID(unsigned ID) { | ||||
1167 | // The type table size is always specified correctly. | ||||
1168 | if (ID >= TypeList.size()) | ||||
1169 | return nullptr; | ||||
1170 | |||||
1171 | if (Type *Ty = TypeList[ID]) | ||||
1172 | return Ty; | ||||
1173 | |||||
1174 | // If we have a forward reference, the only possible case is when it is to a | ||||
1175 | // named struct. Just create a placeholder for now. | ||||
1176 | return TypeList[ID] = createIdentifiedStructType(Context); | ||||
1177 | } | ||||
1178 | |||||
1179 | StructType *BitcodeReader::createIdentifiedStructType(LLVMContext &Context, | ||||
1180 | StringRef Name) { | ||||
1181 | auto *Ret = StructType::create(Context, Name); | ||||
1182 | IdentifiedStructTypes.push_back(Ret); | ||||
1183 | return Ret; | ||||
1184 | } | ||||
1185 | |||||
1186 | StructType *BitcodeReader::createIdentifiedStructType(LLVMContext &Context) { | ||||
1187 | auto *Ret = StructType::create(Context); | ||||
1188 | IdentifiedStructTypes.push_back(Ret); | ||||
1189 | return Ret; | ||||
1190 | } | ||||
1191 | |||||
1192 | //===----------------------------------------------------------------------===// | ||||
1193 | // Functions for parsing blocks from the bitcode file | ||||
1194 | //===----------------------------------------------------------------------===// | ||||
1195 | |||||
1196 | static uint64_t getRawAttributeMask(Attribute::AttrKind Val) { | ||||
1197 | switch (Val) { | ||||
1198 | case Attribute::EndAttrKinds: | ||||
1199 | case Attribute::EmptyKey: | ||||
1200 | case Attribute::TombstoneKey: | ||||
1201 | llvm_unreachable("Synthetic enumerators which should never get here")::llvm::llvm_unreachable_internal("Synthetic enumerators which should never get here" , "llvm/lib/Bitcode/Reader/BitcodeReader.cpp", 1201); | ||||
1202 | |||||
1203 | case Attribute::None: return 0; | ||||
1204 | case Attribute::ZExt: return 1 << 0; | ||||
1205 | case Attribute::SExt: return 1 << 1; | ||||
1206 | case Attribute::NoReturn: return 1 << 2; | ||||
1207 | case Attribute::InReg: return 1 << 3; | ||||
1208 | case Attribute::StructRet: return 1 << 4; | ||||
1209 | case Attribute::NoUnwind: return 1 << 5; | ||||
1210 | case Attribute::NoAlias: return 1 << 6; | ||||
1211 | case Attribute::ByVal: return 1 << 7; | ||||
1212 | case Attribute::Nest: return 1 << 8; | ||||
1213 | case Attribute::ReadNone: return 1 << 9; | ||||
1214 | case Attribute::ReadOnly: return 1 << 10; | ||||
1215 | case Attribute::NoInline: return 1 << 11; | ||||
1216 | case Attribute::AlwaysInline: return 1 << 12; | ||||
1217 | case Attribute::OptimizeForSize: return 1 << 13; | ||||
1218 | case Attribute::StackProtect: return 1 << 14; | ||||
1219 | case Attribute::StackProtectReq: return 1 << 15; | ||||
1220 | case Attribute::Alignment: return 31 << 16; | ||||
1221 | case Attribute::NoCapture: return 1 << 21; | ||||
1222 | case Attribute::NoRedZone: return 1 << 22; | ||||
1223 | case Attribute::NoImplicitFloat: return 1 << 23; | ||||
1224 | case Attribute::Naked: return 1 << 24; | ||||
1225 | case Attribute::InlineHint: return 1 << 25; | ||||
1226 | case Attribute::StackAlignment: return 7 << 26; | ||||
1227 | case Attribute::ReturnsTwice: return 1 << 29; | ||||
1228 | case Attribute::UWTable: return 1 << 30; | ||||
1229 | case Attribute::NonLazyBind: return 1U << 31; | ||||
1230 | case Attribute::SanitizeAddress: return 1ULL << 32; | ||||
1231 | case Attribute::MinSize: return 1ULL << 33; | ||||
1232 | case Attribute::NoDuplicate: return 1ULL << 34; | ||||
1233 | case Attribute::StackProtectStrong: return 1ULL << 35; | ||||
1234 | case Attribute::SanitizeThread: return 1ULL << 36; | ||||
1235 | case Attribute::SanitizeMemory: return 1ULL << 37; | ||||
1236 | case Attribute::NoBuiltin: return 1ULL << 38; | ||||
1237 | case Attribute::Returned: return 1ULL << 39; | ||||
1238 | case Attribute::Cold: return 1ULL << 40; | ||||
1239 | case Attribute::Builtin: return 1ULL << 41; | ||||
1240 | case Attribute::OptimizeNone: return 1ULL << 42; | ||||
1241 | case Attribute::InAlloca: return 1ULL << 43; | ||||
1242 | case Attribute::NonNull: return 1ULL << 44; | ||||
1243 | case Attribute::JumpTable: return 1ULL << 45; | ||||
1244 | case Attribute::Convergent: return 1ULL << 46; | ||||
1245 | case Attribute::SafeStack: return 1ULL << 47; | ||||
1246 | case Attribute::NoRecurse: return 1ULL << 48; | ||||
1247 | case Attribute::InaccessibleMemOnly: return 1ULL << 49; | ||||
1248 | case Attribute::InaccessibleMemOrArgMemOnly: return 1ULL << 50; | ||||
1249 | case Attribute::SwiftSelf: return 1ULL << 51; | ||||
1250 | case Attribute::SwiftError: return 1ULL << 52; | ||||
1251 | case Attribute::WriteOnly: return 1ULL << 53; | ||||
1252 | case Attribute::Speculatable: return 1ULL << 54; | ||||
1253 | case Attribute::StrictFP: return 1ULL << 55; | ||||
1254 | case Attribute::SanitizeHWAddress: return 1ULL << 56; | ||||
1255 | case Attribute::NoCfCheck: return 1ULL << 57; | ||||
1256 | case Attribute::OptForFuzzing: return 1ULL << 58; | ||||
1257 | case Attribute::ShadowCallStack: return 1ULL << 59; | ||||
1258 | case Attribute::SpeculativeLoadHardening: | ||||
1259 | return 1ULL << 60; | ||||
1260 | case Attribute::ImmArg: | ||||
1261 | return 1ULL << 61; | ||||
1262 | case Attribute::WillReturn: | ||||
1263 | return 1ULL << 62; | ||||
1264 | case Attribute::NoFree: | ||||
1265 | return 1ULL << 63; | ||||
1266 | default: | ||||
1267 | // Other attributes are not supported in the raw format, | ||||
1268 | // as we ran out of space. | ||||
1269 | return 0; | ||||
1270 | } | ||||
1271 | llvm_unreachable("Unsupported attribute type")::llvm::llvm_unreachable_internal("Unsupported attribute type" , "llvm/lib/Bitcode/Reader/BitcodeReader.cpp", 1271); | ||||
1272 | } | ||||
1273 | |||||
1274 | static void addRawAttributeValue(AttrBuilder &B, uint64_t Val) { | ||||
1275 | if (!Val) return; | ||||
1276 | |||||
1277 | for (Attribute::AttrKind I = Attribute::None; I != Attribute::EndAttrKinds; | ||||
1278 | I = Attribute::AttrKind(I + 1)) { | ||||
1279 | if (uint64_t A = (Val & getRawAttributeMask(I))) { | ||||
1280 | if (I == Attribute::Alignment) | ||||
1281 | B.addAlignmentAttr(1ULL << ((A >> 16) - 1)); | ||||
1282 | else if (I == Attribute::StackAlignment) | ||||
1283 | B.addStackAlignmentAttr(1ULL << ((A >> 26)-1)); | ||||
1284 | else if (Attribute::isTypeAttrKind(I)) | ||||
1285 | B.addTypeAttr(I, nullptr); // Type will be auto-upgraded. | ||||
1286 | else | ||||
1287 | B.addAttribute(I); | ||||
1288 | } | ||||
1289 | } | ||||
1290 | } | ||||
1291 | |||||
1292 | /// This fills an AttrBuilder object with the LLVM attributes that have | ||||
1293 | /// been decoded from the given integer. This function must stay in sync with | ||||
1294 | /// 'encodeLLVMAttributesForBitcode'. | ||||
1295 | static void decodeLLVMAttributesForBitcode(AttrBuilder &B, | ||||
1296 | uint64_t EncodedAttrs) { | ||||
1297 | // The alignment is stored as a 16-bit raw value from bits 31--16. We shift | ||||
1298 | // the bits above 31 down by 11 bits. | ||||
1299 | unsigned Alignment = (EncodedAttrs & (0xffffULL << 16)) >> 16; | ||||
1300 | assert((!Alignment || isPowerOf2_32(Alignment)) &&(static_cast <bool> ((!Alignment || isPowerOf2_32(Alignment )) && "Alignment must be a power of two.") ? void (0) : __assert_fail ("(!Alignment || isPowerOf2_32(Alignment)) && \"Alignment must be a power of two.\"" , "llvm/lib/Bitcode/Reader/BitcodeReader.cpp", 1301, __extension__ __PRETTY_FUNCTION__)) | ||||
1301 | "Alignment must be a power of two.")(static_cast <bool> ((!Alignment || isPowerOf2_32(Alignment )) && "Alignment must be a power of two.") ? void (0) : __assert_fail ("(!Alignment || isPowerOf2_32(Alignment)) && \"Alignment must be a power of two.\"" , "llvm/lib/Bitcode/Reader/BitcodeReader.cpp", 1301, __extension__ __PRETTY_FUNCTION__)); | ||||
1302 | |||||
1303 | if (Alignment) | ||||
1304 | B.addAlignmentAttr(Alignment); | ||||
1305 | addRawAttributeValue(B, ((EncodedAttrs & (0xfffffULL << 32)) >> 11) | | ||||
1306 | (EncodedAttrs & 0xffff)); | ||||
1307 | } | ||||
1308 | |||||
1309 | Error BitcodeReader::parseAttributeBlock() { | ||||
1310 | if (Error Err = Stream.EnterSubBlock(bitc::PARAMATTR_BLOCK_ID)) | ||||
1311 | return Err; | ||||
1312 | |||||
1313 | if (!MAttributes.empty()) | ||||
1314 | return error("Invalid multiple blocks"); | ||||
1315 | |||||
1316 | SmallVector<uint64_t, 64> Record; | ||||
1317 | |||||
1318 | SmallVector<AttributeList, 8> Attrs; | ||||
1319 | |||||
1320 | // Read all the records. | ||||
1321 | while (true) { | ||||
1322 | Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks(); | ||||
1323 | if (!MaybeEntry) | ||||
1324 | return MaybeEntry.takeError(); | ||||
1325 | BitstreamEntry Entry = MaybeEntry.get(); | ||||
1326 | |||||
1327 | switch (Entry.Kind) { | ||||
1328 | case BitstreamEntry::SubBlock: // Handled for us already. | ||||
1329 | case BitstreamEntry::Error: | ||||
1330 | return error("Malformed block"); | ||||
1331 | case BitstreamEntry::EndBlock: | ||||
1332 | return Error::success(); | ||||
1333 | case BitstreamEntry::Record: | ||||
1334 | // The interesting case. | ||||
1335 | break; | ||||
1336 | } | ||||
1337 | |||||
1338 | // Read a record. | ||||
1339 | Record.clear(); | ||||
1340 | Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record); | ||||
1341 | if (!MaybeRecord) | ||||
1342 | return MaybeRecord.takeError(); | ||||
1343 | switch (MaybeRecord.get()) { | ||||
1344 | default: // Default behavior: ignore. | ||||
1345 | break; | ||||
1346 | case bitc::PARAMATTR_CODE_ENTRY_OLD: // ENTRY: [paramidx0, attr0, ...] | ||||
1347 | // Deprecated, but still needed to read old bitcode files. | ||||
1348 | if (Record.size() & 1) | ||||
1349 | return error("Invalid record"); | ||||
1350 | |||||
1351 | for (unsigned i = 0, e = Record.size(); i != e; i += 2) { | ||||
1352 | AttrBuilder B(Context); | ||||
1353 | decodeLLVMAttributesForBitcode(B, Record[i+1]); | ||||
1354 | Attrs.push_back(AttributeList::get(Context, Record[i], B)); | ||||
1355 | } | ||||
1356 | |||||
1357 | MAttributes.push_back(AttributeList::get(Context, Attrs)); | ||||
1358 | Attrs.clear(); | ||||
1359 | break; | ||||
1360 | case bitc::PARAMATTR_CODE_ENTRY: // ENTRY: [attrgrp0, attrgrp1, ...] | ||||
1361 | for (unsigned i = 0, e = Record.size(); i != e; ++i) | ||||
1362 | Attrs.push_back(MAttributeGroups[Record[i]]); | ||||
1363 | |||||
1364 | MAttributes.push_back(AttributeList::get(Context, Attrs)); | ||||
1365 | Attrs.clear(); | ||||
1366 | break; | ||||
1367 | } | ||||
1368 | } | ||||
1369 | } | ||||
1370 | |||||
1371 | // Returns Attribute::None on unrecognized codes. | ||||
1372 | static Attribute::AttrKind getAttrFromCode(uint64_t Code) { | ||||
1373 | switch (Code) { | ||||
1374 | default: | ||||
1375 | return Attribute::None; | ||||
1376 | case bitc::ATTR_KIND_ALIGNMENT: | ||||
1377 | return Attribute::Alignment; | ||||
1378 | case bitc::ATTR_KIND_ALWAYS_INLINE: | ||||
1379 | return Attribute::AlwaysInline; | ||||
1380 | case bitc::ATTR_KIND_ARGMEMONLY: | ||||
1381 | return Attribute::ArgMemOnly; | ||||
1382 | case bitc::ATTR_KIND_BUILTIN: | ||||
1383 | return Attribute::Builtin; | ||||
1384 | case bitc::ATTR_KIND_BY_VAL: | ||||
1385 | return Attribute::ByVal; | ||||
1386 | case bitc::ATTR_KIND_IN_ALLOCA: | ||||
1387 | return Attribute::InAlloca; | ||||
1388 | case bitc::ATTR_KIND_COLD: | ||||
1389 | return Attribute::Cold; | ||||
1390 | case bitc::ATTR_KIND_CONVERGENT: | ||||
1391 | return Attribute::Convergent; | ||||
1392 | case bitc::ATTR_KIND_DISABLE_SANITIZER_INSTRUMENTATION: | ||||
1393 | return Attribute::DisableSanitizerInstrumentation; | ||||
1394 | case bitc::ATTR_KIND_ELEMENTTYPE: | ||||
1395 | return Attribute::ElementType; | ||||
1396 | case bitc::ATTR_KIND_INACCESSIBLEMEM_ONLY: | ||||
1397 | return Attribute::InaccessibleMemOnly; | ||||
1398 | case bitc::ATTR_KIND_INACCESSIBLEMEM_OR_ARGMEMONLY: | ||||
1399 | return Attribute::InaccessibleMemOrArgMemOnly; | ||||
1400 | case bitc::ATTR_KIND_INLINE_HINT: | ||||
1401 | return Attribute::InlineHint; | ||||
1402 | case bitc::ATTR_KIND_IN_REG: | ||||
1403 | return Attribute::InReg; | ||||
1404 | case bitc::ATTR_KIND_JUMP_TABLE: | ||||
1405 | return Attribute::JumpTable; | ||||
1406 | case bitc::ATTR_KIND_MIN_SIZE: | ||||
1407 | return Attribute::MinSize; | ||||
1408 | case bitc::ATTR_KIND_NAKED: | ||||
1409 | return Attribute::Naked; | ||||
1410 | case bitc::ATTR_KIND_NEST: | ||||
1411 | return Attribute::Nest; | ||||
1412 | case bitc::ATTR_KIND_NO_ALIAS: | ||||
1413 | return Attribute::NoAlias; | ||||
1414 | case bitc::ATTR_KIND_NO_BUILTIN: | ||||
1415 | return Attribute::NoBuiltin; | ||||
1416 | case bitc::ATTR_KIND_NO_CALLBACK: | ||||
1417 | return Attribute::NoCallback; | ||||
1418 | case bitc::ATTR_KIND_NO_CAPTURE: | ||||
1419 | return Attribute::NoCapture; | ||||
1420 | case bitc::ATTR_KIND_NO_DUPLICATE: | ||||
1421 | return Attribute::NoDuplicate; | ||||
1422 | case bitc::ATTR_KIND_NOFREE: | ||||
1423 | return Attribute::NoFree; | ||||
1424 | case bitc::ATTR_KIND_NO_IMPLICIT_FLOAT: | ||||
1425 | return Attribute::NoImplicitFloat; | ||||
1426 | case bitc::ATTR_KIND_NO_INLINE: | ||||
1427 | return Attribute::NoInline; | ||||
1428 | case bitc::ATTR_KIND_NO_RECURSE: | ||||
1429 | return Attribute::NoRecurse; | ||||
1430 | case bitc::ATTR_KIND_NO_MERGE: | ||||
1431 | return Attribute::NoMerge; | ||||
1432 | case bitc::ATTR_KIND_NON_LAZY_BIND: | ||||
1433 | return Attribute::NonLazyBind; | ||||
1434 | case bitc::ATTR_KIND_NON_NULL: | ||||
1435 | return Attribute::NonNull; | ||||
1436 | case bitc::ATTR_KIND_DEREFERENCEABLE: | ||||
1437 | return Attribute::Dereferenceable; | ||||
1438 | case bitc::ATTR_KIND_DEREFERENCEABLE_OR_NULL: | ||||
1439 | return Attribute::DereferenceableOrNull; | ||||
1440 | case bitc::ATTR_KIND_ALLOC_SIZE: | ||||
1441 | return Attribute::AllocSize; | ||||
1442 | case bitc::ATTR_KIND_NO_RED_ZONE: | ||||
1443 | return Attribute::NoRedZone; | ||||
1444 | case bitc::ATTR_KIND_NO_RETURN: | ||||
1445 | return Attribute::NoReturn; | ||||
1446 | case bitc::ATTR_KIND_NOSYNC: | ||||
1447 | return Attribute::NoSync; | ||||
1448 | case bitc::ATTR_KIND_NOCF_CHECK: | ||||
1449 | return Attribute::NoCfCheck; | ||||
1450 | case bitc::ATTR_KIND_NO_PROFILE: | ||||
1451 | return Attribute::NoProfile; | ||||
1452 | case bitc::ATTR_KIND_NO_UNWIND: | ||||
1453 | return Attribute::NoUnwind; | ||||
1454 | case bitc::ATTR_KIND_NO_SANITIZE_COVERAGE: | ||||
1455 | return Attribute::NoSanitizeCoverage; | ||||
1456 | case bitc::ATTR_KIND_NULL_POINTER_IS_VALID: | ||||
1457 | return Attribute::NullPointerIsValid; | ||||
1458 | case bitc::ATTR_KIND_OPT_FOR_FUZZING: | ||||
1459 | return Attribute::OptForFuzzing; | ||||
1460 | case bitc::ATTR_KIND_OPTIMIZE_FOR_SIZE: | ||||
1461 | return Attribute::OptimizeForSize; | ||||
1462 | case bitc::ATTR_KIND_OPTIMIZE_NONE: | ||||
1463 | return Attribute::OptimizeNone; | ||||
1464 | case bitc::ATTR_KIND_READ_NONE: | ||||
1465 | return Attribute::ReadNone; | ||||
1466 | case bitc::ATTR_KIND_READ_ONLY: | ||||
1467 | return Attribute::ReadOnly; | ||||
1468 | case bitc::ATTR_KIND_RETURNED: | ||||
1469 | return Attribute::Returned; | ||||
1470 | case bitc::ATTR_KIND_RETURNS_TWICE: | ||||
1471 | return Attribute::ReturnsTwice; | ||||
1472 | case bitc::ATTR_KIND_S_EXT: | ||||
1473 | return Attribute::SExt; | ||||
1474 | case bitc::ATTR_KIND_SPECULATABLE: | ||||
1475 | return Attribute::Speculatable; | ||||
1476 | case bitc::ATTR_KIND_STACK_ALIGNMENT: | ||||
1477 | return Attribute::StackAlignment; | ||||
1478 | case bitc::ATTR_KIND_STACK_PROTECT: | ||||
1479 | return Attribute::StackProtect; | ||||
1480 | case bitc::ATTR_KIND_STACK_PROTECT_REQ: | ||||
1481 | return Attribute::StackProtectReq; | ||||
1482 | case bitc::ATTR_KIND_STACK_PROTECT_STRONG: | ||||
1483 | return Attribute::StackProtectStrong; | ||||
1484 | case bitc::ATTR_KIND_SAFESTACK: | ||||
1485 | return Attribute::SafeStack; | ||||
1486 | case bitc::ATTR_KIND_SHADOWCALLSTACK: | ||||
1487 | return Attribute::ShadowCallStack; | ||||
1488 | case bitc::ATTR_KIND_STRICT_FP: | ||||
1489 | return Attribute::StrictFP; | ||||
1490 | case bitc::ATTR_KIND_STRUCT_RET: | ||||
1491 | return Attribute::StructRet; | ||||
1492 | case bitc::ATTR_KIND_SANITIZE_ADDRESS: | ||||
1493 | return Attribute::SanitizeAddress; | ||||
1494 | case bitc::ATTR_KIND_SANITIZE_HWADDRESS: | ||||
1495 | return Attribute::SanitizeHWAddress; | ||||
1496 | case bitc::ATTR_KIND_SANITIZE_THREAD: | ||||
1497 | return Attribute::SanitizeThread; | ||||
1498 | case bitc::ATTR_KIND_SANITIZE_MEMORY: | ||||
1499 | return Attribute::SanitizeMemory; | ||||
1500 | case bitc::ATTR_KIND_SPECULATIVE_LOAD_HARDENING: | ||||
1501 | return Attribute::SpeculativeLoadHardening; | ||||
1502 | case bitc::ATTR_KIND_SWIFT_ERROR: | ||||
1503 | return Attribute::SwiftError; | ||||
1504 | case bitc::ATTR_KIND_SWIFT_SELF: | ||||
1505 | return Attribute::SwiftSelf; | ||||
1506 | case bitc::ATTR_KIND_SWIFT_ASYNC: | ||||
1507 | return Attribute::SwiftAsync; | ||||
1508 | case bitc::ATTR_KIND_UW_TABLE: | ||||
1509 | return Attribute::UWTable; | ||||
1510 | case bitc::ATTR_KIND_VSCALE_RANGE: | ||||
1511 | return Attribute::VScaleRange; | ||||
1512 | case bitc::ATTR_KIND_WILLRETURN: | ||||
1513 | return Attribute::WillReturn; | ||||
1514 | case bitc::ATTR_KIND_WRITEONLY: | ||||
1515 | return Attribute::WriteOnly; | ||||
1516 | case bitc::ATTR_KIND_Z_EXT: | ||||
1517 | return Attribute::ZExt; | ||||
1518 | case bitc::ATTR_KIND_IMMARG: | ||||
1519 | return Attribute::ImmArg; | ||||
1520 | case bitc::ATTR_KIND_SANITIZE_MEMTAG: | ||||
1521 | return Attribute::SanitizeMemTag; | ||||
1522 | case bitc::ATTR_KIND_PREALLOCATED: | ||||
1523 | return Attribute::Preallocated; | ||||
1524 | case bitc::ATTR_KIND_NOUNDEF: | ||||
1525 | return Attribute::NoUndef; | ||||
1526 | case bitc::ATTR_KIND_BYREF: | ||||
1527 | return Attribute::ByRef; | ||||
1528 | case bitc::ATTR_KIND_MUSTPROGRESS: | ||||
1529 | return Attribute::MustProgress; | ||||
1530 | case bitc::ATTR_KIND_HOT: | ||||
1531 | return Attribute::Hot; | ||||
1532 | } | ||||
1533 | } | ||||
1534 | |||||
1535 | Error BitcodeReader::parseAlignmentValue(uint64_t Exponent, | ||||
1536 | MaybeAlign &Alignment) { | ||||
1537 | // Note: Alignment in bitcode files is incremented by 1, so that zero | ||||
1538 | // can be used for default alignment. | ||||
1539 | if (Exponent > Value::MaxAlignmentExponent + 1) | ||||
1540 | return error("Invalid alignment value"); | ||||
1541 | Alignment = decodeMaybeAlign(Exponent); | ||||
1542 | return Error::success(); | ||||
1543 | } | ||||
1544 | |||||
1545 | Error BitcodeReader::parseAttrKind(uint64_t Code, Attribute::AttrKind *Kind) { | ||||
1546 | *Kind = getAttrFromCode(Code); | ||||
1547 | if (*Kind == Attribute::None) | ||||
1548 | return error("Unknown attribute kind (" + Twine(Code) + ")"); | ||||
1549 | return Error::success(); | ||||
1550 | } | ||||
1551 | |||||
1552 | Error BitcodeReader::parseAttributeGroupBlock() { | ||||
1553 | if (Error Err = Stream.EnterSubBlock(bitc::PARAMATTR_GROUP_BLOCK_ID)) | ||||
1554 | return Err; | ||||
1555 | |||||
1556 | if (!MAttributeGroups.empty()) | ||||
1557 | return error("Invalid multiple blocks"); | ||||
1558 | |||||
1559 | SmallVector<uint64_t, 64> Record; | ||||
1560 | |||||
1561 | // Read all the records. | ||||
1562 | while (true) { | ||||
1563 | Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks(); | ||||
1564 | if (!MaybeEntry) | ||||
1565 | return MaybeEntry.takeError(); | ||||
1566 | BitstreamEntry Entry = MaybeEntry.get(); | ||||
1567 | |||||
1568 | switch (Entry.Kind) { | ||||
1569 | case BitstreamEntry::SubBlock: // Handled for us already. | ||||
1570 | case BitstreamEntry::Error: | ||||
1571 | return error("Malformed block"); | ||||
1572 | case BitstreamEntry::EndBlock: | ||||
1573 | return Error::success(); | ||||
1574 | case BitstreamEntry::Record: | ||||
1575 | // The interesting case. | ||||
1576 | break; | ||||
1577 | } | ||||
1578 | |||||
1579 | // Read a record. | ||||
1580 | Record.clear(); | ||||
1581 | Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record); | ||||
1582 | if (!MaybeRecord) | ||||
1583 | return MaybeRecord.takeError(); | ||||
1584 | switch (MaybeRecord.get()) { | ||||
1585 | default: // Default behavior: ignore. | ||||
1586 | break; | ||||
1587 | case bitc::PARAMATTR_GRP_CODE_ENTRY: { // ENTRY: [grpid, idx, a0, a1, ...] | ||||
1588 | if (Record.size() < 3) | ||||
1589 | return error("Invalid record"); | ||||
1590 | |||||
1591 | uint64_t GrpID = Record[0]; | ||||
1592 | uint64_t Idx = Record[1]; // Index of the object this attribute refers to. | ||||
1593 | |||||
1594 | AttrBuilder B(Context); | ||||
1595 | for (unsigned i = 2, e = Record.size(); i != e; ++i) { | ||||
1596 | if (Record[i] == 0) { // Enum attribute | ||||
1597 | Attribute::AttrKind Kind; | ||||
1598 | if (Error Err = parseAttrKind(Record[++i], &Kind)) | ||||
1599 | return Err; | ||||
1600 | |||||
1601 | // Upgrade old-style byval attribute to one with a type, even if it's | ||||
1602 | // nullptr. We will have to insert the real type when we associate | ||||
1603 | // this AttributeList with a function. | ||||
1604 | if (Kind == Attribute::ByVal) | ||||
1605 | B.addByValAttr(nullptr); | ||||
1606 | else if (Kind == Attribute::StructRet) | ||||
1607 | B.addStructRetAttr(nullptr); | ||||
1608 | else if (Kind == Attribute::InAlloca) | ||||
1609 | B.addInAllocaAttr(nullptr); | ||||
1610 | else if (Attribute::isEnumAttrKind(Kind)) | ||||
1611 | B.addAttribute(Kind); | ||||
1612 | else | ||||
1613 | return error("Not an enum attribute"); | ||||
1614 | } else if (Record[i] == 1) { // Integer attribute | ||||
1615 | Attribute::AttrKind Kind; | ||||
1616 | if (Error Err = parseAttrKind(Record[++i], &Kind)) | ||||
1617 | return Err; | ||||
1618 | if (!Attribute::isIntAttrKind(Kind)) | ||||
1619 | return error("Not an int attribute"); | ||||
1620 | if (Kind == Attribute::Alignment) | ||||
1621 | B.addAlignmentAttr(Record[++i]); | ||||
1622 | else if (Kind == Attribute::StackAlignment) | ||||
1623 | B.addStackAlignmentAttr(Record[++i]); | ||||
1624 | else if (Kind == Attribute::Dereferenceable) | ||||
1625 | B.addDereferenceableAttr(Record[++i]); | ||||
1626 | else if (Kind == Attribute::DereferenceableOrNull) | ||||
1627 | B.addDereferenceableOrNullAttr(Record[++i]); | ||||
1628 | else if (Kind == Attribute::AllocSize) | ||||
1629 | B.addAllocSizeAttrFromRawRepr(Record[++i]); | ||||
1630 | else if (Kind == Attribute::VScaleRange) | ||||
1631 | B.addVScaleRangeAttrFromRawRepr(Record[++i]); | ||||
1632 | } else if (Record[i] == 3 || Record[i] == 4) { // String attribute | ||||
1633 | bool HasValue = (Record[i++] == 4); | ||||
1634 | SmallString<64> KindStr; | ||||
1635 | SmallString<64> ValStr; | ||||
1636 | |||||
1637 | while (Record[i] != 0 && i != e) | ||||
1638 | KindStr += Record[i++]; | ||||
1639 | assert(Record[i] == 0 && "Kind string not null terminated")(static_cast <bool> (Record[i] == 0 && "Kind string not null terminated" ) ? void (0) : __assert_fail ("Record[i] == 0 && \"Kind string not null terminated\"" , "llvm/lib/Bitcode/Reader/BitcodeReader.cpp", 1639, __extension__ __PRETTY_FUNCTION__)); | ||||
1640 | |||||
1641 | if (HasValue) { | ||||
1642 | // Has a value associated with it. | ||||
1643 | ++i; // Skip the '0' that terminates the "kind" string. | ||||
1644 | while (Record[i] != 0 && i != e) | ||||
1645 | ValStr += Record[i++]; | ||||
1646 | assert(Record[i] == 0 && "Value string not null terminated")(static_cast <bool> (Record[i] == 0 && "Value string not null terminated" ) ? void (0) : __assert_fail ("Record[i] == 0 && \"Value string not null terminated\"" , "llvm/lib/Bitcode/Reader/BitcodeReader.cpp", 1646, __extension__ __PRETTY_FUNCTION__)); | ||||
1647 | } | ||||
1648 | |||||
1649 | B.addAttribute(KindStr.str(), ValStr.str()); | ||||
1650 | } else if (Record[i] == 5 || Record[i] == 6) { | ||||
1651 | bool HasType = Record[i] == 6; | ||||
1652 | Attribute::AttrKind Kind; | ||||
1653 | if (Error Err = parseAttrKind(Record[++i], &Kind)) | ||||
1654 | return Err; | ||||
1655 | if (!Attribute::isTypeAttrKind(Kind)) | ||||
1656 | return error("Not a type attribute"); | ||||
1657 | |||||
1658 | B.addTypeAttr(Kind, HasType ? getTypeByID(Record[++i]) : nullptr); | ||||
1659 | } else { | ||||
1660 | return error("Invalid attribute group entry"); | ||||
1661 | } | ||||
1662 | } | ||||
1663 | |||||
1664 | UpgradeAttributes(B); | ||||
1665 | MAttributeGroups[GrpID] = AttributeList::get(Context, Idx, B); | ||||
1666 | break; | ||||
1667 | } | ||||
1668 | } | ||||
1669 | } | ||||
1670 | } | ||||
1671 | |||||
1672 | Error BitcodeReader::parseTypeTable() { | ||||
1673 | if (Error Err = Stream.EnterSubBlock(bitc::TYPE_BLOCK_ID_NEW)) | ||||
1674 | return Err; | ||||
1675 | |||||
1676 | return parseTypeTableBody(); | ||||
1677 | } | ||||
1678 | |||||
1679 | Error BitcodeReader::parseTypeTableBody() { | ||||
1680 | if (!TypeList.empty()) | ||||
1681 | return error("Invalid multiple blocks"); | ||||
1682 | |||||
1683 | SmallVector<uint64_t, 64> Record; | ||||
1684 | unsigned NumRecords = 0; | ||||
1685 | |||||
1686 | SmallString<64> TypeName; | ||||
1687 | |||||
1688 | // Read all the records for this type table. | ||||
1689 | while (true) { | ||||
1690 | Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks(); | ||||
1691 | if (!MaybeEntry) | ||||
1692 | return MaybeEntry.takeError(); | ||||
1693 | BitstreamEntry Entry = MaybeEntry.get(); | ||||
1694 | |||||
1695 | switch (Entry.Kind) { | ||||
1696 | case BitstreamEntry::SubBlock: // Handled for us already. | ||||
1697 | case BitstreamEntry::Error: | ||||
1698 | return error("Malformed block"); | ||||
1699 | case BitstreamEntry::EndBlock: | ||||
1700 | if (NumRecords != TypeList.size()) | ||||
1701 | return error("Malformed block"); | ||||
1702 | return Error::success(); | ||||
1703 | case BitstreamEntry::Record: | ||||
1704 | // The interesting case. | ||||
1705 | break; | ||||
1706 | } | ||||
1707 | |||||
1708 | // Read a record. | ||||
1709 | Record.clear(); | ||||
1710 | Type *ResultTy = nullptr; | ||||
1711 | Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record); | ||||
1712 | if (!MaybeRecord) | ||||
1713 | return MaybeRecord.takeError(); | ||||
1714 | switch (MaybeRecord.get()) { | ||||
1715 | default: | ||||
1716 | return error("Invalid value"); | ||||
1717 | case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries] | ||||
1718 | // TYPE_CODE_NUMENTRY contains a count of the number of types in the | ||||
1719 | // type list. This allows us to reserve space. | ||||
1720 | if (Record.empty()) | ||||
1721 | return error("Invalid record"); | ||||
1722 | TypeList.resize(Record[0]); | ||||
1723 | continue; | ||||
1724 | case bitc::TYPE_CODE_VOID: // VOID | ||||
1725 | ResultTy = Type::getVoidTy(Context); | ||||
1726 | break; | ||||
1727 | case bitc::TYPE_CODE_HALF: // HALF | ||||
1728 | ResultTy = Type::getHalfTy(Context); | ||||
1729 | break; | ||||
1730 | case bitc::TYPE_CODE_BFLOAT: // BFLOAT | ||||
1731 | ResultTy = Type::getBFloatTy(Context); | ||||
1732 | break; | ||||
1733 | case bitc::TYPE_CODE_FLOAT: // FLOAT | ||||
1734 | ResultTy = Type::getFloatTy(Context); | ||||
1735 | break; | ||||
1736 | case bitc::TYPE_CODE_DOUBLE: // DOUBLE | ||||
1737 | ResultTy = Type::getDoubleTy(Context); | ||||
1738 | break; | ||||
1739 | case bitc::TYPE_CODE_X86_FP80: // X86_FP80 | ||||
1740 | ResultTy = Type::getX86_FP80Ty(Context); | ||||
1741 | break; | ||||
1742 | case bitc::TYPE_CODE_FP128: // FP128 | ||||
1743 | ResultTy = Type::getFP128Ty(Context); | ||||
1744 | break; | ||||
1745 | case bitc::TYPE_CODE_PPC_FP128: // PPC_FP128 | ||||
1746 | ResultTy = Type::getPPC_FP128Ty(Context); | ||||
1747 | break; | ||||
1748 | case bitc::TYPE_CODE_LABEL: // LABEL | ||||
1749 | ResultTy = Type::getLabelTy(Context); | ||||
1750 | break; | ||||
1751 | case bitc::TYPE_CODE_METADATA: // METADATA | ||||
1752 | ResultTy = Type::getMetadataTy(Context); | ||||
1753 | break; | ||||
1754 | case bitc::TYPE_CODE_X86_MMX: // X86_MMX | ||||
1755 | ResultTy = Type::getX86_MMXTy(Context); | ||||
1756 | break; | ||||
1757 | case bitc::TYPE_CODE_X86_AMX: // X86_AMX | ||||
1758 | ResultTy = Type::getX86_AMXTy(Context); | ||||
1759 | break; | ||||
1760 | case bitc::TYPE_CODE_TOKEN: // TOKEN | ||||
1761 | ResultTy = Type::getTokenTy(Context); | ||||
1762 | break; | ||||
1763 | case bitc::TYPE_CODE_INTEGER: { // INTEGER: [width] | ||||
1764 | if (Record.empty()) | ||||
1765 | return error("Invalid record"); | ||||
1766 | |||||
1767 | uint64_t NumBits = Record[0]; | ||||
1768 | if (NumBits < IntegerType::MIN_INT_BITS || | ||||
1769 | NumBits > IntegerType::MAX_INT_BITS) | ||||
1770 | return error("Bitwidth for integer type out of range"); | ||||
1771 | ResultTy = IntegerType::get(Context, NumBits); | ||||
1772 | break; | ||||
1773 | } | ||||
1774 | case bitc::TYPE_CODE_POINTER: { // POINTER: [pointee type] or | ||||
1775 | // [pointee type, address space] | ||||
1776 | if (Record.empty()) | ||||
1777 | return error("Invalid record"); | ||||
1778 | unsigned AddressSpace = 0; | ||||
1779 | if (Record.size() == 2) | ||||
1780 | AddressSpace = Record[1]; | ||||
1781 | ResultTy = getTypeByID(Record[0]); | ||||
1782 | if (!ResultTy || | ||||
1783 | !PointerType::isValidElementType(ResultTy)) | ||||
1784 | return error("Invalid type"); | ||||
1785 | ResultTy = PointerType::get(ResultTy, AddressSpace); | ||||
1786 | break; | ||||
1787 | } | ||||
1788 | case bitc::TYPE_CODE_OPAQUE_POINTER: { // OPAQUE_POINTER: [addrspace] | ||||
1789 | if (Record.size() != 1) | ||||
1790 | return error("Invalid record"); | ||||
1791 | if (Context.supportsTypedPointers()) | ||||
1792 | return error( | ||||
1793 | "Opaque pointers are only supported in -opaque-pointers mode"); | ||||
1794 | unsigned AddressSpace = Record[0]; | ||||
1795 | ResultTy = PointerType::get(Context, AddressSpace); | ||||
1796 | break; | ||||
1797 | } | ||||
1798 | case bitc::TYPE_CODE_FUNCTION_OLD: { | ||||
1799 | // Deprecated, but still needed to read old bitcode files. | ||||
1800 | // FUNCTION: [vararg, attrid, retty, paramty x N] | ||||
1801 | if (Record.size() < 3) | ||||
1802 | return error("Invalid record"); | ||||
1803 | SmallVector<Type*, 8> ArgTys; | ||||
1804 | for (unsigned i = 3, e = Record.size(); i != e; ++i) { | ||||
1805 | if (Type *T = getTypeByID(Record[i])) | ||||
1806 | ArgTys.push_back(T); | ||||
1807 | else | ||||
1808 | break; | ||||
1809 | } | ||||
1810 | |||||
1811 | ResultTy = getTypeByID(Record[2]); | ||||
1812 | if (!ResultTy || ArgTys.size() < Record.size()-3) | ||||
1813 | return error("Invalid type"); | ||||
1814 | |||||
1815 | ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]); | ||||
1816 | break; | ||||
1817 | } | ||||
1818 | case bitc::TYPE_CODE_FUNCTION: { | ||||
1819 | // FUNCTION: [vararg, retty, paramty x N] | ||||
1820 | if (Record.size() < 2) | ||||
1821 | return error("Invalid record"); | ||||
1822 | SmallVector<Type*, 8> ArgTys; | ||||
1823 | for (unsigned i = 2, e = Record.size(); i != e; ++i) { | ||||
1824 | if (Type *T = getTypeByID(Record[i])) { | ||||
1825 | if (!FunctionType::isValidArgumentType(T)) | ||||
1826 | return error("Invalid function argument type"); | ||||
1827 | ArgTys.push_back(T); | ||||
1828 | } | ||||
1829 | else | ||||
1830 | break; | ||||
1831 | } | ||||
1832 | |||||
1833 | ResultTy = getTypeByID(Record[1]); | ||||
1834 | if (!ResultTy || ArgTys.size() < Record.size()-2) | ||||
1835 | return error("Invalid type"); | ||||
1836 | |||||
1837 | ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]); | ||||
1838 | break; | ||||
1839 | } | ||||
1840 | case bitc::TYPE_CODE_STRUCT_ANON: { // STRUCT: [ispacked, eltty x N] | ||||
1841 | if (Record.empty()) | ||||
1842 | return error("Invalid record"); | ||||
1843 | SmallVector<Type*, 8> EltTys; | ||||
1844 | for (unsigned i = 1, e = Record.size(); i != e; ++i) { | ||||
1845 | if (Type *T = getTypeByID(Record[i])) | ||||
1846 | EltTys.push_back(T); | ||||
1847 | else | ||||
1848 | break; | ||||
1849 | } | ||||
1850 | if (EltTys.size() != Record.size()-1) | ||||
1851 | return error("Invalid type"); | ||||
1852 | ResultTy = StructType::get(Context, EltTys, Record[0]); | ||||
1853 | break; | ||||
1854 | } | ||||
1855 | case bitc::TYPE_CODE_STRUCT_NAME: // STRUCT_NAME: [strchr x N] | ||||
1856 | if (convertToString(Record, 0, TypeName)) | ||||
1857 | return error("Invalid record"); | ||||
1858 | continue; | ||||
1859 | |||||
1860 | case bitc::TYPE_CODE_STRUCT_NAMED: { // STRUCT: [ispacked, eltty x N] | ||||
1861 | if (Record.empty()) | ||||
1862 | return error("Invalid record"); | ||||
1863 | |||||
1864 | if (NumRecords >= TypeList.size()) | ||||
1865 | return error("Invalid TYPE table"); | ||||
1866 | |||||
1867 | // Check to see if this was forward referenced, if so fill in the temp. | ||||
1868 | StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]); | ||||
1869 | if (Res) { | ||||
1870 | Res->setName(TypeName); | ||||
1871 | TypeList[NumRecords] = nullptr; | ||||
1872 | } else // Otherwise, create a new struct. | ||||
1873 | Res = createIdentifiedStructType(Context, TypeName); | ||||
1874 | TypeName.clear(); | ||||
1875 | |||||
1876 | SmallVector<Type*, 8> EltTys; | ||||
1877 | for (unsigned i = 1, e = Record.size(); i != e; ++i) { | ||||
1878 | if (Type *T = getTypeByID(Record[i])) | ||||
1879 | EltTys.push_back(T); | ||||
1880 | else | ||||
1881 | break; | ||||
1882 | } | ||||
1883 | if (EltTys.size() != Record.size()-1) | ||||
1884 | return error("Invalid record"); | ||||
1885 | Res->setBody(EltTys, Record[0]); | ||||
1886 | ResultTy = Res; | ||||
1887 | break; | ||||
1888 | } | ||||
1889 | case bitc::TYPE_CODE_OPAQUE: { // OPAQUE: [] | ||||
1890 | if (Record.size() != 1) | ||||
1891 | return error("Invalid record"); | ||||
1892 | |||||
1893 | if (NumRecords >= TypeList.size()) | ||||
1894 | return error("Invalid TYPE table"); | ||||
1895 | |||||
1896 | // Check to see if this was forward referenced, if so fill in the temp. | ||||
1897 | StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]); | ||||
1898 | if (Res) { | ||||
1899 | Res->setName(TypeName); | ||||
1900 | TypeList[NumRecords] = nullptr; | ||||
1901 | } else // Otherwise, create a new struct with no body. | ||||
1902 | Res = createIdentifiedStructType(Context, TypeName); | ||||
1903 | TypeName.clear(); | ||||
1904 | ResultTy = Res; | ||||
1905 | break; | ||||
1906 | } | ||||
1907 | case bitc::TYPE_CODE_ARRAY: // ARRAY: [numelts, eltty] | ||||
1908 | if (Record.size() < 2) | ||||
1909 | return error("Invalid record"); | ||||
1910 | ResultTy = getTypeByID(Record[1]); | ||||
1911 | if (!ResultTy || !ArrayType::isValidElementType(ResultTy)) | ||||
1912 | return error("Invalid type"); | ||||
1913 | ResultTy = ArrayType::get(ResultTy, Record[0]); | ||||
1914 | break; | ||||
1915 | case bitc::TYPE_CODE_VECTOR: // VECTOR: [numelts, eltty] or | ||||
1916 | // [numelts, eltty, scalable] | ||||
1917 | if (Record.size() < 2) | ||||
1918 | return error("Invalid record"); | ||||
1919 | if (Record[0] == 0) | ||||
1920 | return error("Invalid vector length"); | ||||
1921 | ResultTy = getTypeByID(Record[1]); | ||||
1922 | if (!ResultTy || !VectorType::isValidElementType(ResultTy)) | ||||
1923 | return error("Invalid type"); | ||||
1924 | bool Scalable = Record.size() > 2 ? Record[2] : false; | ||||
1925 | ResultTy = VectorType::get(ResultTy, Record[0], Scalable); | ||||
1926 | break; | ||||
1927 | } | ||||
1928 | |||||
1929 | if (NumRecords >= TypeList.size()) | ||||
1930 | return error("Invalid TYPE table"); | ||||
1931 | if (TypeList[NumRecords]) | ||||
1932 | return error( | ||||
1933 | "Invalid TYPE table: Only named structs can be forward referenced"); | ||||
1934 | assert(ResultTy && "Didn't read a type?")(static_cast <bool> (ResultTy && "Didn't read a type?" ) ? void (0) : __assert_fail ("ResultTy && \"Didn't read a type?\"" , "llvm/lib/Bitcode/Reader/BitcodeReader.cpp", 1934, __extension__ __PRETTY_FUNCTION__)); | ||||
1935 | TypeList[NumRecords++] = ResultTy; | ||||
1936 | } | ||||
1937 | } | ||||
1938 | |||||
1939 | Error BitcodeReader::parseOperandBundleTags() { | ||||
1940 | if (Error Err = Stream.EnterSubBlock(bitc::OPERAND_BUNDLE_TAGS_BLOCK_ID)) | ||||
1941 | return Err; | ||||
1942 | |||||
1943 | if (!BundleTags.empty()) | ||||
1944 | return error("Invalid multiple blocks"); | ||||
1945 | |||||
1946 | SmallVector<uint64_t, 64> Record; | ||||
1947 | |||||
1948 | while (true) { | ||||
1949 | Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks(); | ||||
1950 | if (!MaybeEntry) | ||||
1951 | return MaybeEntry.takeError(); | ||||
1952 | BitstreamEntry Entry = MaybeEntry.get(); | ||||
1953 | |||||
1954 | switch (Entry.Kind) { | ||||
1955 | case BitstreamEntry::SubBlock: // Handled for us already. | ||||
1956 | case BitstreamEntry::Error: | ||||
1957 | return error("Malformed block"); | ||||
1958 | case BitstreamEntry::EndBlock: | ||||
1959 | return Error::success(); | ||||
1960 | case BitstreamEntry::Record: | ||||
1961 | // The interesting case. | ||||
1962 | break; | ||||
1963 | } | ||||
1964 | |||||
1965 | // Tags are implicitly mapped to integers by their order. | ||||
1966 | |||||
1967 | Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record); | ||||
1968 | if (!MaybeRecord) | ||||
1969 | return MaybeRecord.takeError(); | ||||
1970 | if (MaybeRecord.get() != bitc::OPERAND_BUNDLE_TAG) | ||||
1971 | return error("Invalid record"); | ||||
1972 | |||||
1973 | // OPERAND_BUNDLE_TAG: [strchr x N] | ||||
1974 | BundleTags.emplace_back(); | ||||
1975 | if (convertToString(Record, 0, BundleTags.back())) | ||||
1976 | return error("Invalid record"); | ||||
1977 | Record.clear(); | ||||
1978 | } | ||||
1979 | } | ||||
1980 | |||||
1981 | Error BitcodeReader::parseSyncScopeNames() { | ||||
1982 | if (Error Err = Stream.EnterSubBlock(bitc::SYNC_SCOPE_NAMES_BLOCK_ID)) | ||||
1983 | return Err; | ||||
1984 | |||||
1985 | if (!SSIDs.empty()) | ||||
1986 | return error("Invalid multiple synchronization scope names blocks"); | ||||
1987 | |||||
1988 | SmallVector<uint64_t, 64> Record; | ||||
1989 | while (true) { | ||||
1990 | Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks(); | ||||
1991 | if (!MaybeEntry) | ||||
1992 | return MaybeEntry.takeError(); | ||||
1993 | BitstreamEntry Entry = MaybeEntry.get(); | ||||
1994 | |||||
1995 | switch (Entry.Kind) { | ||||
1996 | case BitstreamEntry::SubBlock: // Handled for us already. | ||||
1997 | case BitstreamEntry::Error: | ||||
1998 | return error("Malformed block"); | ||||
1999 | case BitstreamEntry::EndBlock: | ||||
2000 | if (SSIDs.empty()) | ||||
2001 | return error("Invalid empty synchronization scope names block"); | ||||
2002 | return Error::success(); | ||||
2003 | case BitstreamEntry::Record: | ||||
2004 | // The interesting case. | ||||
2005 | break; | ||||
2006 | } | ||||
2007 | |||||
2008 | // Synchronization scope names are implicitly mapped to synchronization | ||||
2009 | // scope IDs by their order. | ||||
2010 | |||||
2011 | Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record); | ||||
2012 | if (!MaybeRecord) | ||||
2013 | return MaybeRecord.takeError(); | ||||
2014 | if (MaybeRecord.get() != bitc::SYNC_SCOPE_NAME) | ||||
2015 | return error("Invalid record"); | ||||
2016 | |||||
2017 | SmallString<16> SSN; | ||||
2018 | if (convertToString(Record, 0, SSN)) | ||||
2019 | return error("Invalid record"); | ||||
2020 | |||||
2021 | SSIDs.push_back(Context.getOrInsertSyncScopeID(SSN)); | ||||
2022 | Record.clear(); | ||||
2023 | } | ||||
2024 | } | ||||
2025 | |||||
2026 | /// Associate a value with its name from the given index in the provided record. | ||||
2027 | Expected<Value *> BitcodeReader::recordValue(SmallVectorImpl<uint64_t> &Record, | ||||
2028 | unsigned NameIndex, Triple &TT) { | ||||
2029 | SmallString<128> ValueName; | ||||
2030 | if (convertToString(Record, NameIndex, ValueName)) | ||||
2031 | return error("Invalid record"); | ||||
2032 | unsigned ValueID = Record[0]; | ||||
2033 | if (ValueID >= ValueList.size() || !ValueList[ValueID]) | ||||
2034 | return error("Invalid record"); | ||||
2035 | Value *V = ValueList[ValueID]; | ||||
2036 | |||||
2037 | StringRef NameStr(ValueName.data(), ValueName.size()); | ||||
2038 | if (NameStr.find_first_of(0) != StringRef::npos) | ||||
2039 | return error("Invalid value name"); | ||||
2040 | V->setName(NameStr); | ||||
2041 | auto *GO = dyn_cast<GlobalObject>(V); | ||||
2042 | if (GO && ImplicitComdatObjects.contains(GO) && TT.supportsCOMDAT()) | ||||
2043 | GO->setComdat(TheModule->getOrInsertComdat(V->getName())); | ||||
2044 | return V; | ||||
2045 | } | ||||
2046 | |||||
2047 | /// Helper to note and return the current location, and jump to the given | ||||
2048 | /// offset. | ||||
2049 | static Expected<uint64_t> jumpToValueSymbolTable(uint64_t Offset, | ||||
2050 | BitstreamCursor &Stream) { | ||||
2051 | // Save the current parsing location so we can jump back at the end | ||||
2052 | // of the VST read. | ||||
2053 | uint64_t CurrentBit = Stream.GetCurrentBitNo(); | ||||
2054 | if (Error JumpFailed = Stream.JumpToBit(Offset * 32)) | ||||
2055 | return std::move(JumpFailed); | ||||
2056 | Expected<BitstreamEntry> MaybeEntry = Stream.advance(); | ||||
2057 | if (!MaybeEntry) | ||||
2058 | return MaybeEntry.takeError(); | ||||
2059 | if (MaybeEntry.get().Kind != BitstreamEntry::SubBlock || | ||||
2060 | MaybeEntry.get().ID != bitc::VALUE_SYMTAB_BLOCK_ID) | ||||
2061 | return error("Expected value symbol table subblock"); | ||||
2062 | return CurrentBit; | ||||
2063 | } | ||||
2064 | |||||
2065 | void BitcodeReader::setDeferredFunctionInfo(unsigned FuncBitcodeOffsetDelta, | ||||
2066 | Function *F, | ||||
2067 | ArrayRef<uint64_t> Record) { | ||||
2068 | // Note that we subtract 1 here because the offset is relative to one word | ||||
2069 | // before the start of the identification or module block, which was | ||||
2070 | // historically always the start of the regular bitcode header. | ||||
2071 | uint64_t FuncWordOffset = Record[1] - 1; | ||||
2072 | uint64_t FuncBitOffset = FuncWordOffset * 32; | ||||
2073 | DeferredFunctionInfo[F] = FuncBitOffset + FuncBitcodeOffsetDelta; | ||||
2074 | // Set the LastFunctionBlockBit to point to the last function block. | ||||
2075 | // Later when parsing is resumed after function materialization, | ||||
2076 | // we can simply skip that last function block. | ||||
2077 | if (FuncBitOffset > LastFunctionBlockBit) | ||||
2078 | LastFunctionBlockBit = FuncBitOffset; | ||||
2079 | } | ||||
2080 | |||||
2081 | /// Read a new-style GlobalValue symbol table. | ||||
2082 | Error BitcodeReader::parseGlobalValueSymbolTable() { | ||||
2083 | unsigned FuncBitcodeOffsetDelta = | ||||
2084 | Stream.getAbbrevIDWidth() + bitc::BlockIDWidth; | ||||
2085 | |||||
2086 | if (Error Err = Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID)) | ||||
2087 | return Err; | ||||
2088 | |||||
2089 | SmallVector<uint64_t, 64> Record; | ||||
2090 | while (true) { | ||||
2091 | Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks(); | ||||
2092 | if (!MaybeEntry) | ||||
2093 | return MaybeEntry.takeError(); | ||||
2094 | BitstreamEntry Entry = MaybeEntry.get(); | ||||
2095 | |||||
2096 | switch (Entry.Kind) { | ||||
2097 | case BitstreamEntry::SubBlock: | ||||
2098 | case BitstreamEntry::Error: | ||||
2099 | return error("Malformed block"); | ||||
2100 | case BitstreamEntry::EndBlock: | ||||
2101 | return Error::success(); | ||||
2102 | case BitstreamEntry::Record: | ||||
2103 | break; | ||||
2104 | } | ||||
2105 | |||||
2106 | Record.clear(); | ||||
2107 | Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record); | ||||
2108 | if (!MaybeRecord) | ||||
2109 | return MaybeRecord.takeError(); | ||||
2110 | switch (MaybeRecord.get()) { | ||||
2111 | case bitc::VST_CODE_FNENTRY: { // [valueid, offset] | ||||
2112 | unsigned ValueID = Record[0]; | ||||
2113 | if (ValueID >= ValueList.size() || !ValueList[ValueID]) | ||||
2114 | return error("Invalid value reference in symbol table"); | ||||
2115 | setDeferredFunctionInfo(FuncBitcodeOffsetDelta, | ||||
2116 | cast<Function>(ValueList[ValueID]), Record); | ||||
2117 | break; | ||||
2118 | } | ||||
2119 | } | ||||
2120 | } | ||||
2121 | } | ||||
2122 | |||||
2123 | /// Parse the value symbol table at either the current parsing location or | ||||
2124 | /// at the given bit offset if provided. | ||||
2125 | Error BitcodeReader::parseValueSymbolTable(uint64_t Offset) { | ||||
2126 | uint64_t CurrentBit; | ||||
2127 | // Pass in the Offset to distinguish between calling for the module-level | ||||
2128 | // VST (where we want to jump to the VST offset) and the function-level | ||||
2129 | // VST (where we don't). | ||||
2130 | if (Offset > 0) { | ||||
2131 | Expected<uint64_t> MaybeCurrentBit = jumpToValueSymbolTable(Offset, Stream); | ||||
2132 | if (!MaybeCurrentBit) | ||||
2133 | return MaybeCurrentBit.takeError(); | ||||
2134 | CurrentBit = MaybeCurrentBit.get(); | ||||
2135 | // If this module uses a string table, read this as a module-level VST. | ||||
2136 | if (UseStrtab) { | ||||
2137 | if (Error Err = parseGlobalValueSymbolTable()) | ||||
2138 | return Err; | ||||
2139 | if (Error JumpFailed = Stream.JumpToBit(CurrentBit)) | ||||
2140 | return JumpFailed; | ||||
2141 | return Error::success(); | ||||
2142 | } | ||||
2143 | // Otherwise, the VST will be in a similar format to a function-level VST, | ||||
2144 | // and will contain symbol names. | ||||
2145 | } | ||||
2146 | |||||
2147 | // Compute the delta between the bitcode indices in the VST (the word offset | ||||
2148 | // to the word-aligned ENTER_SUBBLOCK for the function block, and that | ||||
2149 | // expected by the lazy reader. The reader's EnterSubBlock expects to have | ||||
2150 | // already read the ENTER_SUBBLOCK code (size getAbbrevIDWidth) and BlockID | ||||
2151 | // (size BlockIDWidth). Note that we access the stream's AbbrevID width here | ||||
2152 | // just before entering the VST subblock because: 1) the EnterSubBlock | ||||
2153 | // changes the AbbrevID width; 2) the VST block is nested within the same | ||||
2154 | // outer MODULE_BLOCK as the FUNCTION_BLOCKs and therefore have the same | ||||
2155 | // AbbrevID width before calling EnterSubBlock; and 3) when we want to | ||||
2156 | // jump to the FUNCTION_BLOCK using this offset later, we don't want | ||||
2157 | // to rely on the stream's AbbrevID width being that of the MODULE_BLOCK. | ||||
2158 | unsigned FuncBitcodeOffsetDelta = | ||||
2159 | Stream.getAbbrevIDWidth() + bitc::BlockIDWidth; | ||||
2160 | |||||
2161 | if (Error Err = Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID)) | ||||
2162 | return Err; | ||||
2163 | |||||
2164 | SmallVector<uint64_t, 64> Record; | ||||
2165 | |||||
2166 | Triple TT(TheModule->getTargetTriple()); | ||||
2167 | |||||
2168 | // Read all the records for this value table. | ||||
2169 | SmallString<128> ValueName; | ||||
2170 | |||||
2171 | while (true) { | ||||
2172 | Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks(); | ||||
2173 | if (!MaybeEntry) | ||||
2174 | return MaybeEntry.takeError(); | ||||
2175 | BitstreamEntry Entry = MaybeEntry.get(); | ||||
2176 | |||||
2177 | switch (Entry.Kind) { | ||||
2178 | case BitstreamEntry::SubBlock: // Handled for us already. | ||||
2179 | case BitstreamEntry::Error: | ||||
2180 | return error("Malformed block"); | ||||
2181 | case BitstreamEntry::EndBlock: | ||||
2182 | if (Offset > 0) | ||||
2183 | if (Error JumpFailed = Stream.JumpToBit(CurrentBit)) | ||||
2184 | return JumpFailed; | ||||
2185 | return Error::success(); | ||||
2186 | case BitstreamEntry::Record: | ||||
2187 | // The interesting case. | ||||
2188 | break; | ||||
2189 | } | ||||
2190 | |||||
2191 | // Read a record. | ||||
2192 | Record.clear(); | ||||
2193 | Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record); | ||||
2194 | if (!MaybeRecord) | ||||
2195 | return MaybeRecord.takeError(); | ||||
2196 | switch (MaybeRecord.get()) { | ||||
2197 | default: // Default behavior: unknown type. | ||||
2198 | break; | ||||
2199 | case bitc::VST_CODE_ENTRY: { // VST_CODE_ENTRY: [valueid, namechar x N] | ||||
2200 | Expected<Value *> ValOrErr = recordValue(Record, 1, TT); | ||||
2201 | if (Error Err = ValOrErr.takeError()) | ||||
2202 | return Err; | ||||
2203 | ValOrErr.get(); | ||||
2204 | break; | ||||
2205 | } | ||||
2206 | case bitc::VST_CODE_FNENTRY: { | ||||
2207 | // VST_CODE_FNENTRY: [valueid, offset, namechar x N] | ||||
2208 | Expected<Value *> ValOrErr = recordValue(Record, 2, TT); | ||||
2209 | if (Error Err = ValOrErr.takeError()) | ||||
2210 | return Err; | ||||
2211 | Value *V = ValOrErr.get(); | ||||
2212 | |||||
2213 | // Ignore function offsets emitted for aliases of functions in older | ||||
2214 | // versions of LLVM. | ||||
2215 | if (auto *F = dyn_cast<Function>(V)) | ||||
2216 | setDeferredFunctionInfo(FuncBitcodeOffsetDelta, F, Record); | ||||
2217 | break; | ||||
2218 | } | ||||
2219 | case bitc::VST_CODE_BBENTRY: { | ||||
2220 | if (convertToString(Record, 1, ValueName)) | ||||
2221 | return error("Invalid record"); | ||||
2222 | BasicBlock *BB = getBasicBlock(Record[0]); | ||||
2223 | if (!BB) | ||||
2224 | return error("Invalid record"); | ||||
2225 | |||||
2226 | BB->setName(StringRef(ValueName.data(), ValueName.size())); | ||||
2227 | ValueName.clear(); | ||||
2228 | break; | ||||
2229 | } | ||||
2230 | } | ||||
2231 | } | ||||
2232 | } | ||||
2233 | |||||
2234 | /// Decode a signed value stored with the sign bit in the LSB for dense VBR | ||||
2235 | /// encoding. | ||||
2236 | uint64_t BitcodeReader::decodeSignRotatedValue(uint64_t V) { | ||||
2237 | if ((V & 1) == 0) | ||||
2238 | return V >> 1; | ||||
2239 | if (V != 1) | ||||
2240 | return -(V >> 1); | ||||
2241 | // There is no such thing as -0 with integers. "-0" really means MININT. | ||||
2242 | return 1ULL << 63; | ||||
2243 | } | ||||
2244 | |||||
2245 | /// Resolve all of the initializers for global values and aliases that we can. | ||||
2246 | Error BitcodeReader::resolveGlobalAndIndirectSymbolInits() { | ||||
2247 | std::vector<std::pair<GlobalVariable *, unsigned>> GlobalInitWorklist; | ||||
2248 | std::vector<std::pair<GlobalValue *, unsigned>> IndirectSymbolInitWorklist; | ||||
2249 | std::vector<FunctionOperandInfo> FunctionOperandWorklist; | ||||
2250 | |||||
2251 | GlobalInitWorklist.swap(GlobalInits); | ||||
2252 | IndirectSymbolInitWorklist.swap(IndirectSymbolInits); | ||||
2253 | FunctionOperandWorklist.swap(FunctionOperands); | ||||
2254 | |||||
2255 | while (!GlobalInitWorklist.empty()) { | ||||
2256 | unsigned ValID = GlobalInitWorklist.back().second; | ||||
2257 | if (ValID >= ValueList.size()) { | ||||
2258 | // Not ready to resolve this yet, it requires something later in the file. | ||||
2259 | GlobalInits.push_back(GlobalInitWorklist.back()); | ||||
2260 | } else { | ||||
2261 | if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID])) | ||||
2262 | GlobalInitWorklist.back().first->setInitializer(C); | ||||
2263 | else | ||||
2264 | return error("Expected a constant"); | ||||
2265 | } | ||||
2266 | GlobalInitWorklist.pop_back(); | ||||
2267 | } | ||||
2268 | |||||
2269 | while (!IndirectSymbolInitWorklist.empty()) { | ||||
2270 | unsigned ValID = IndirectSymbolInitWorklist.back().second; | ||||
2271 | if (ValID >= ValueList.size()) { | ||||
2272 | IndirectSymbolInits.push_back(IndirectSymbolInitWorklist.back()); | ||||
2273 | } else { | ||||
2274 | Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]); | ||||
2275 | if (!C) | ||||
2276 | return error("Expected a constant"); | ||||
2277 | GlobalValue *GV = IndirectSymbolInitWorklist.back().first; | ||||
2278 | if (auto *GA = dyn_cast<GlobalAlias>(GV)) { | ||||
2279 | if (C->getType() != GV->getType()) | ||||
2280 | return error("Alias and aliasee types don't match"); | ||||
2281 | GA->setAliasee(C); | ||||
2282 | } else if (auto *GI = dyn_cast<GlobalIFunc>(GV)) { | ||||
2283 | Type *ResolverFTy = | ||||
2284 | GlobalIFunc::getResolverFunctionType(GI->getValueType()); | ||||
2285 | // Transparently fix up the type for compatiblity with older bitcode | ||||
2286 | GI->setResolver( | ||||
2287 | ConstantExpr::getBitCast(C, ResolverFTy->getPointerTo())); | ||||
2288 | } else { | ||||
2289 | return error("Expected an alias or an ifunc"); | ||||
2290 | } | ||||
2291 | } | ||||
2292 | IndirectSymbolInitWorklist.pop_back(); | ||||
2293 | } | ||||
2294 | |||||
2295 | while (!FunctionOperandWorklist.empty()) { | ||||
2296 | FunctionOperandInfo &Info = FunctionOperandWorklist.back(); | ||||
2297 | if (Info.PersonalityFn) { | ||||
2298 | unsigned ValID = Info.PersonalityFn - 1; | ||||
2299 | if (ValID < ValueList.size()) { | ||||
2300 | if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID])) | ||||
2301 | Info.F->setPersonalityFn(C); | ||||
2302 | else | ||||
2303 | return error("Expected a constant"); | ||||
2304 | Info.PersonalityFn = 0; | ||||
2305 | } | ||||
2306 | } | ||||
2307 | if (Info.Prefix) { | ||||
2308 | unsigned ValID = Info.Prefix - 1; | ||||
2309 | if (ValID < ValueList.size()) { | ||||
2310 | if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID])) | ||||
2311 | Info.F->setPrefixData(C); | ||||
2312 | else | ||||
2313 | return error("Expected a constant"); | ||||
2314 | Info.Prefix = 0; | ||||
2315 | } | ||||
2316 | } | ||||
2317 | if (Info.Prologue) { | ||||
2318 | unsigned ValID = Info.Prologue - 1; | ||||
2319 | if (ValID < ValueList.size()) { | ||||
2320 | if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID])) | ||||
2321 | Info.F->setPrologueData(C); | ||||
2322 | else | ||||
2323 | return error("Expected a constant"); | ||||
2324 | Info.Prologue = 0; | ||||
2325 | } | ||||
2326 | } | ||||
2327 | if (Info.PersonalityFn || Info.Prefix || Info.Prologue) | ||||
2328 | FunctionOperands.push_back(Info); | ||||
2329 | FunctionOperandWorklist.pop_back(); | ||||
2330 | } | ||||
2331 | |||||
2332 | return Error::success(); | ||||
2333 | } | ||||
2334 | |||||
2335 | APInt llvm::readWideAPInt(ArrayRef<uint64_t> Vals, unsigned TypeBits) { | ||||
2336 | SmallVector<uint64_t, 8> Words(Vals.size()); | ||||
2337 | transform(Vals, Words.begin(), | ||||
2338 | BitcodeReader::decodeSignRotatedValue); | ||||
2339 | |||||
2340 | return APInt(TypeBits, Words); | ||||
2341 | } | ||||
2342 | |||||
2343 | Error BitcodeReader::parseConstants() { | ||||
2344 | if (Error Err = Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID)) | ||||
| |||||
2345 | return Err; | ||||
2346 | |||||
2347 | SmallVector<uint64_t, 64> Record; | ||||
2348 | |||||
2349 | // Read all the records for this value table. | ||||
2350 | Type *CurTy = Type::getInt32Ty(Context); | ||||
2351 | unsigned NextCstNo = ValueList.size(); | ||||
2352 | |||||
2353 | struct DelayedShufTy { | ||||
2354 | VectorType *OpTy; | ||||
2355 | VectorType *RTy; | ||||
2356 | uint64_t Op0Idx; | ||||
2357 | uint64_t Op1Idx; | ||||
2358 | uint64_t Op2Idx; | ||||
2359 | unsigned CstNo; | ||||
2360 | }; | ||||
2361 | std::vector<DelayedShufTy> DelayedShuffles; | ||||
2362 | struct DelayedSelTy { | ||||
2363 | Type *OpTy; | ||||
2364 | uint64_t Op0Idx; | ||||
2365 | uint64_t Op1Idx; | ||||
2366 | uint64_t Op2Idx; | ||||
2367 | unsigned CstNo; | ||||
2368 | }; | ||||
2369 | std::vector<DelayedSelTy> DelayedSelectors; | ||||
2370 | |||||
2371 | while (true) { | ||||
2372 | Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks(); | ||||
2373 | if (!MaybeEntry) | ||||
2374 | return MaybeEntry.takeError(); | ||||
2375 | BitstreamEntry Entry = MaybeEntry.get(); | ||||
2376 | |||||
2377 | switch (Entry.Kind) { | ||||
2378 | case BitstreamEntry::SubBlock: // Handled for us already. | ||||
2379 | case BitstreamEntry::Error: | ||||
2380 | return error("Malformed block"); | ||||
2381 | case BitstreamEntry::EndBlock: | ||||
2382 | // Once all the constants have been read, go through and resolve forward | ||||
2383 | // references. | ||||
2384 | // | ||||
2385 | // We have to treat shuffles specially because they don't have three | ||||
2386 | // operands anymore. We need to convert the shuffle mask into an array, | ||||
2387 | // and we can't convert a forward reference. | ||||
2388 | for (auto &DelayedShuffle : DelayedShuffles) { | ||||
2389 | VectorType *OpTy = DelayedShuffle.OpTy; | ||||
2390 | VectorType *RTy = DelayedShuffle.RTy; | ||||
2391 | uint64_t Op0Idx = DelayedShuffle.Op0Idx; | ||||
2392 | uint64_t Op1Idx = DelayedShuffle.Op1Idx; | ||||
2393 | uint64_t Op2Idx = DelayedShuffle.Op2Idx; | ||||
2394 | uint64_t CstNo = DelayedShuffle.CstNo; | ||||
2395 | Constant *Op0 = ValueList.getConstantFwdRef(Op0Idx, OpTy); | ||||
2396 | Constant *Op1 = ValueList.getConstantFwdRef(Op1Idx, OpTy); | ||||
2397 | Type *ShufTy = | ||||
2398 | VectorType::get(Type::getInt32Ty(Context), RTy->getElementCount()); | ||||
2399 | Constant *Op2 = ValueList.getConstantFwdRef(Op2Idx, ShufTy); | ||||
2400 | if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2)) | ||||
2401 | return error("Invalid shufflevector operands"); | ||||
2402 | SmallVector<int, 16> Mask; | ||||
2403 | ShuffleVectorInst::getShuffleMask(Op2, Mask); | ||||
2404 | Value *V = ConstantExpr::getShuffleVector(Op0, Op1, Mask); | ||||
2405 | ValueList.assignValue(V, CstNo); | ||||
2406 | } | ||||
2407 | for (auto &DelayedSelector : DelayedSelectors) { | ||||
2408 | Type *OpTy = DelayedSelector.OpTy; | ||||
2409 | Type *SelectorTy = Type::getInt1Ty(Context); | ||||
2410 | uint64_t Op0Idx = DelayedSelector.Op0Idx; | ||||
2411 | uint64_t Op1Idx = DelayedSelector.Op1Idx; | ||||
2412 | uint64_t Op2Idx = DelayedSelector.Op2Idx; | ||||
2413 | uint64_t CstNo = DelayedSelector.CstNo; | ||||
2414 | Constant *Op1 = ValueList.getConstantFwdRef(Op1Idx, OpTy); | ||||
2415 | Constant *Op2 = ValueList.getConstantFwdRef(Op2Idx, OpTy); | ||||
2416 | // The selector might be an i1 or an <n x i1> | ||||
2417 | // Get the type from the ValueList before getting a forward ref. | ||||
2418 | if (VectorType *VTy = dyn_cast<VectorType>(OpTy)) { | ||||
2419 | Value *V = ValueList[Op0Idx]; | ||||
2420 | assert(V)(static_cast <bool> (V) ? void (0) : __assert_fail ("V" , "llvm/lib/Bitcode/Reader/BitcodeReader.cpp", 2420, __extension__ __PRETTY_FUNCTION__)); | ||||
2421 | if (SelectorTy != V->getType()) | ||||
2422 | SelectorTy = VectorType::get(SelectorTy, VTy->getElementCount()); | ||||
2423 | } | ||||
2424 | Constant *Op0 = ValueList.getConstantFwdRef(Op0Idx, SelectorTy); | ||||
2425 | Value *V = ConstantExpr::getSelect(Op0, Op1, Op2); | ||||
2426 | ValueList.assignValue(V, CstNo); | ||||
2427 | } | ||||
2428 | |||||
2429 | if (NextCstNo != ValueList.size()) | ||||
2430 | return error("Invalid constant reference"); | ||||
2431 | |||||
2432 | ValueList.resolveConstantForwardRefs(); | ||||
2433 | return Error::success(); | ||||
2434 | case BitstreamEntry::Record: | ||||
2435 | // The interesting case. | ||||
2436 | break; | ||||
2437 | } | ||||
2438 | |||||
2439 | // Read a record. | ||||
2440 | Record.clear(); | ||||
2441 | Type *VoidType = Type::getVoidTy(Context); | ||||
2442 | Value *V = nullptr; | ||||
2443 | Expected<unsigned> MaybeBitCode = Stream.readRecord(Entry.ID, Record); | ||||
2444 | if (!MaybeBitCode) | ||||
2445 | return MaybeBitCode.takeError(); | ||||
2446 | switch (unsigned BitCode = MaybeBitCode.get()) { | ||||
2447 | default: // Default behavior: unknown constant | ||||
2448 | case bitc::CST_CODE_UNDEF: // UNDEF | ||||
2449 | V = UndefValue::get(CurTy); | ||||
2450 | break; | ||||
2451 | case bitc::CST_CODE_POISON: // POISON | ||||
2452 | V = PoisonValue::get(CurTy); | ||||
2453 | break; | ||||
2454 | case bitc::CST_CODE_SETTYPE: // SETTYPE: [typeid] | ||||
2455 | if (Record.empty()) | ||||
2456 | return error("Invalid record"); | ||||
2457 | if (Record[0] >= TypeList.size() || !TypeList[Record[0]]) | ||||
2458 | return error("Invalid record"); | ||||
2459 | if (TypeList[Record[0]] == VoidType) | ||||
2460 | return error("Invalid constant type"); | ||||
2461 | CurTy = TypeList[Record[0]]; | ||||
2462 | continue; // Skip the ValueList manipulation. | ||||
2463 | case bitc::CST_CODE_NULL: // NULL | ||||
2464 | if (CurTy->isVoidTy() || CurTy->isFunctionTy() || CurTy->isLabelTy()) | ||||
2465 | return error("Invalid type for a constant null value"); | ||||
2466 | V = Constant::getNullValue(CurTy); | ||||
2467 | break; | ||||
2468 | case bitc::CST_CODE_INTEGER: // INTEGER: [intval] | ||||
2469 | if (!CurTy->isIntegerTy() || Record.empty()) | ||||
2470 | return error("Invalid record"); | ||||
2471 | V = ConstantInt::get(CurTy, decodeSignRotatedValue(Record[0])); | ||||
2472 | break; | ||||
2473 | case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval] | ||||
2474 | if (!CurTy->isIntegerTy() || Record.empty()) | ||||
2475 | return error("Invalid record"); | ||||
2476 | |||||
2477 | APInt VInt = | ||||
2478 | readWideAPInt(Record, cast<IntegerType>(CurTy)->getBitWidth()); | ||||
2479 | V = ConstantInt::get(Context, VInt); | ||||
2480 | |||||
2481 | break; | ||||
2482 | } | ||||
2483 | case bitc::CST_CODE_FLOAT: { // FLOAT: [fpval] | ||||
2484 | if (Record.empty()) | ||||
2485 | return error("Invalid record"); | ||||
2486 | if (CurTy->isHalfTy()) | ||||
2487 | V = ConstantFP::get(Context, APFloat(APFloat::IEEEhalf(), | ||||
2488 | APInt(16, (uint16_t)Record[0]))); | ||||
2489 | else if (CurTy->isBFloatTy()) | ||||
2490 | V = ConstantFP::get(Context, APFloat(APFloat::BFloat(), | ||||
2491 | APInt(16, (uint32_t)Record[0]))); | ||||
2492 | else if (CurTy->isFloatTy()) | ||||
2493 | V = ConstantFP::get(Context, APFloat(APFloat::IEEEsingle(), | ||||
2494 | APInt(32, (uint32_t)Record[0]))); | ||||
2495 | else if (CurTy->isDoubleTy()) | ||||
2496 | V = ConstantFP::get(Context, APFloat(APFloat::IEEEdouble(), | ||||
2497 | APInt(64, Record[0]))); | ||||
2498 | else if (CurTy->isX86_FP80Ty()) { | ||||
2499 | // Bits are not stored the same way as a normal i80 APInt, compensate. | ||||
2500 | uint64_t Rearrange[2]; | ||||
2501 | Rearrange[0] = (Record[1] & 0xffffLL) | (Record[0] << 16); | ||||
2502 | Rearrange[1] = Record[0] >> 48; | ||||
2503 | V = ConstantFP::get(Context, APFloat(APFloat::x87DoubleExtended(), | ||||
2504 | APInt(80, Rearrange))); | ||||
2505 | } else if (CurTy->isFP128Ty()) | ||||
2506 | V = ConstantFP::get(Context, APFloat(APFloat::IEEEquad(), | ||||
2507 | APInt(128, Record))); | ||||
2508 | else if (CurTy->isPPC_FP128Ty()) | ||||
2509 | V = ConstantFP::get(Context, APFloat(APFloat::PPCDoubleDouble(), | ||||
2510 | APInt(128, Record))); | ||||
2511 | else | ||||
2512 | V = UndefValue::get(CurTy); | ||||
2513 | break; | ||||
2514 | } | ||||
2515 | |||||
2516 | case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number] | ||||
2517 | if (Record.empty()) | ||||
2518 | return error("Invalid record"); | ||||
2519 | |||||
2520 | unsigned Size = Record.size(); | ||||
2521 | SmallVector<Constant*, 16> Elts; | ||||
2522 | |||||
2523 | if (StructType *STy = dyn_cast<StructType>(CurTy)) { | ||||
2524 | for (unsigned i = 0; i != Size; ++i) | ||||
2525 | Elts.push_back(ValueList.getConstantFwdRef(Record[i], | ||||
2526 | STy->getElementType(i))); | ||||
2527 | V = ConstantStruct::get(STy, Elts); | ||||
2528 | } else if (ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) { | ||||
2529 | Type *EltTy = ATy->getElementType(); | ||||
2530 | for (unsigned i = 0; i != Size; ++i) | ||||
2531 | Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy)); | ||||
2532 | V = ConstantArray::get(ATy, Elts); | ||||
2533 | } else if (VectorType *VTy = dyn_cast<VectorType>(CurTy)) { | ||||
2534 | Type *EltTy = VTy->getElementType(); | ||||
2535 | for (unsigned i = 0; i != Size; ++i) | ||||
2536 | Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy)); | ||||
2537 | V = ConstantVector::get(Elts); | ||||
2538 | } else { | ||||
2539 | V = UndefValue::get(CurTy); | ||||
2540 | } | ||||
2541 | break; | ||||
2542 | } | ||||
2543 | case bitc::CST_CODE_STRING: // STRING: [values] | ||||
2544 | case bitc::CST_CODE_CSTRING: { // CSTRING: [values] | ||||
2545 | if (Record.empty()) | ||||
2546 | return error("Invalid record"); | ||||
2547 | |||||
2548 | SmallString<16> Elts(Record.begin(), Record.end()); | ||||
2549 | V = ConstantDataArray::getString(Context, Elts, | ||||
2550 | BitCode == bitc::CST_CODE_CSTRING); | ||||
2551 | break; | ||||
2552 | } | ||||
2553 | case bitc::CST_CODE_DATA: {// DATA: [n x value] | ||||
2554 | if (Record.empty()) | ||||
2555 | return error("Invalid record"); | ||||
2556 | |||||
2557 | Type *EltTy; | ||||
2558 | if (auto *Array = dyn_cast<ArrayType>(CurTy)) | ||||
2559 | EltTy = Array->getElementType(); | ||||
2560 | else | ||||
2561 | EltTy = cast<VectorType>(CurTy)->getElementType(); | ||||
2562 | if (EltTy->isIntegerTy(8)) { | ||||
2563 | SmallVector<uint8_t, 16> Elts(Record.begin(), Record.end()); | ||||
2564 | if (isa<VectorType>(CurTy)) | ||||
2565 | V = ConstantDataVector::get(Context, Elts); | ||||
2566 | else | ||||
2567 | V = ConstantDataArray::get(Context, Elts); | ||||
2568 | } else if (EltTy->isIntegerTy(16)) { | ||||
2569 | SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end()); | ||||
2570 | if (isa<VectorType>(CurTy)) | ||||
2571 | V = ConstantDataVector::get(Context, Elts); | ||||
2572 | else | ||||
2573 | V = ConstantDataArray::get(Context, Elts); | ||||
2574 | } else if (EltTy->isIntegerTy(32)) { | ||||
2575 | SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end()); | ||||
2576 | if (isa<VectorType>(CurTy)) | ||||
2577 | V = ConstantDataVector::get(Context, Elts); | ||||
2578 | else | ||||
2579 | V = ConstantDataArray::get(Context, Elts); | ||||
2580 | } else if (EltTy->isIntegerTy(64)) { | ||||
2581 | SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end()); | ||||
2582 | if (isa<VectorType>(CurTy)) | ||||
2583 | V = ConstantDataVector::get(Context, Elts); | ||||
2584 | else | ||||
2585 | V = ConstantDataArray::get(Context, Elts); | ||||
2586 | } else if (EltTy->isHalfTy()) { | ||||
2587 | SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end()); | ||||
2588 | if (isa<VectorType>(CurTy)) | ||||
2589 | V = ConstantDataVector::getFP(EltTy, Elts); | ||||
2590 | else | ||||
2591 | V = ConstantDataArray::getFP(EltTy, Elts); | ||||
2592 | } else if (EltTy->isBFloatTy()) { | ||||
2593 | SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end()); | ||||
2594 | if (isa<VectorType>(CurTy)) | ||||
2595 | V = ConstantDataVector::getFP(EltTy, Elts); | ||||
2596 | else | ||||
2597 | V = ConstantDataArray::getFP(EltTy, Elts); | ||||
2598 | } else if (EltTy->isFloatTy()) { | ||||
2599 | SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end()); | ||||
2600 | if (isa<VectorType>(CurTy)) | ||||
2601 | V = ConstantDataVector::getFP(EltTy, Elts); | ||||
2602 | else | ||||
2603 | V = ConstantDataArray::getFP(EltTy, Elts); | ||||
2604 | } else if (EltTy->isDoubleTy()) { | ||||
2605 | SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end()); | ||||
2606 | if (isa<VectorType>(CurTy)) | ||||
2607 | V = ConstantDataVector::getFP(EltTy, Elts); | ||||
2608 | else | ||||
2609 | V = ConstantDataArray::getFP(EltTy, Elts); | ||||
2610 | } else { | ||||
2611 | return error("Invalid type for value"); | ||||
2612 | } | ||||
2613 | break; | ||||
2614 | } | ||||
2615 | case bitc::CST_CODE_CE_UNOP: { // CE_UNOP: [opcode, opval] | ||||
2616 | if (Record.size() < 2) | ||||
2617 | return error("Invalid record"); | ||||
2618 | int Opc = getDecodedUnaryOpcode(Record[0], CurTy); | ||||
2619 | if (Opc < 0) { | ||||
2620 | V = UndefValue::get(CurTy); // Unknown unop. | ||||
2621 | } else { | ||||
2622 | Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy); | ||||
2623 | unsigned Flags = 0; | ||||
2624 | V = ConstantExpr::get(Opc, LHS, Flags); | ||||
2625 | } | ||||
2626 | break; | ||||
2627 | } | ||||
2628 | case bitc::CST_CODE_CE_BINOP: { // CE_BINOP: [opcode, opval, opval] | ||||
2629 | if (Record.size() < 3) | ||||
2630 | return error("Invalid record"); | ||||
2631 | int Opc = getDecodedBinaryOpcode(Record[0], CurTy); | ||||
2632 | if (Opc < 0) { | ||||
2633 | V = UndefValue::get(CurTy); // Unknown binop. | ||||
2634 | } else { | ||||
2635 | Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy); | ||||
2636 | Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy); | ||||
2637 | unsigned Flags = 0; | ||||
2638 | if (Record.size() >= 4) { | ||||
2639 | if (Opc == Instruction::Add || | ||||
2640 | Opc == Instruction::Sub || | ||||
2641 | Opc == Instruction::Mul || | ||||
2642 | Opc == Instruction::Shl) { | ||||
2643 | if (Record[3] & (1 << bitc::OBO_NO_SIGNED_WRAP)) | ||||
2644 | Flags |= OverflowingBinaryOperator::NoSignedWrap; | ||||
2645 | if (Record[3] & (1 << bitc::OBO_NO_UNSIGNED_WRAP)) | ||||
2646 | Flags |= OverflowingBinaryOperator::NoUnsignedWrap; | ||||
2647 | } else if (Opc == Instruction::SDiv || | ||||
2648 | Opc == Instruction::UDiv || | ||||
2649 | Opc == Instruction::LShr || | ||||
2650 | Opc == Instruction::AShr) { | ||||
2651 | if (Record[3] & (1 << bitc::PEO_EXACT)) | ||||
2652 | Flags |= SDivOperator::IsExact; | ||||
2653 | } | ||||
2654 | } | ||||
2655 | V = ConstantExpr::get(Opc, LHS, RHS, Flags); | ||||
2656 | } | ||||
2657 | break; | ||||
2658 | } | ||||
2659 | case bitc::CST_CODE_CE_CAST: { // CE_CAST: [opcode, opty, opval] | ||||
2660 | if (Record.size() < 3) | ||||
2661 | return error("Invalid record"); | ||||
2662 | int Opc = getDecodedCastOpcode(Record[0]); | ||||
2663 | if (Opc < 0) { | ||||
2664 | V = UndefValue::get(CurTy); // Unknown cast. | ||||
2665 | } else { | ||||
2666 | Type *OpTy = getTypeByID(Record[1]); | ||||
2667 | if (!OpTy) | ||||
2668 | return error("Invalid record"); | ||||
2669 | Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy); | ||||
2670 | V = UpgradeBitCastExpr(Opc, Op, CurTy); | ||||
2671 | if (!V) V = ConstantExpr::getCast(Opc, Op, CurTy); | ||||
2672 | } | ||||
2673 | break; | ||||
2674 | } | ||||
2675 | case bitc::CST_CODE_CE_INBOUNDS_GEP: // [ty, n x operands] | ||||
2676 | case bitc::CST_CODE_CE_GEP: // [ty, n x operands] | ||||
2677 | case bitc::CST_CODE_CE_GEP_WITH_INRANGE_INDEX: { // [ty, flags, n x | ||||
2678 | // operands] | ||||
2679 | unsigned OpNum = 0; | ||||
2680 | Type *PointeeType = nullptr; | ||||
2681 | if (BitCode
| ||||
2682 | Record.size() % 2) | ||||
2683 | PointeeType = getTypeByID(Record[OpNum++]); | ||||
2684 | |||||
2685 | bool InBounds = false; | ||||
2686 | Optional<unsigned> InRangeIndex; | ||||
2687 | if (BitCode
| ||||
2688 | uint64_t Op = Record[OpNum++]; | ||||
2689 | InBounds = Op & 1; | ||||
2690 | InRangeIndex = Op >> 1; | ||||
2691 | } else if (BitCode
| ||||
2692 | InBounds = true; | ||||
2693 | |||||
2694 | SmallVector<Constant*, 16> Elts; | ||||
2695 | Type *Elt0FullTy = nullptr; | ||||
2696 | while (OpNum != Record.size()) { | ||||
2697 | if (!Elt0FullTy) | ||||
2698 | Elt0FullTy = getTypeByID(Record[OpNum]); | ||||
2699 | Type *ElTy = getTypeByID(Record[OpNum++]); | ||||
2700 | if (!ElTy) | ||||
2701 | return error("Invalid record"); | ||||
2702 | Elts.push_back(ValueList.getConstantFwdRef(Record[OpNum++], ElTy)); | ||||
2703 | } | ||||
2704 | |||||
2705 | if (Elts.size() < 1) | ||||
2706 | return error("Invalid gep with no operands"); | ||||
2707 | |||||
2708 | PointerType *OrigPtrTy = cast<PointerType>(Elt0FullTy->getScalarType()); | ||||
| |||||
2709 | if (!PointeeType) | ||||
2710 | PointeeType = OrigPtrTy->getPointerElementType(); | ||||
2711 | else if (!OrigPtrTy->isOpaqueOrPointeeTypeMatches(PointeeType)) | ||||
2712 | return error("Explicit gep operator type does not match pointee type " | ||||
2713 | "of pointer operand"); | ||||
2714 | |||||
2715 | ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end()); | ||||
2716 | V = ConstantExpr::getGetElementPtr(PointeeType, Elts[0], Indices, | ||||
2717 | InBounds, InRangeIndex); | ||||
2718 | break; | ||||
2719 | } | ||||
2720 | case bitc::CST_CODE_CE_SELECT: { // CE_SELECT: [opval#, opval#, opval#] | ||||
2721 | if (Record.size() < 3) | ||||
2722 | return error("Invalid record"); | ||||
2723 | |||||
2724 | DelayedSelectors.push_back( | ||||
2725 | {CurTy, Record[0], Record[1], Record[2], NextCstNo}); | ||||
2726 | (void)ValueList.getConstantFwdRef(NextCstNo, CurTy); | ||||
2727 | ++NextCstNo; | ||||
2728 | continue; | ||||
2729 | } | ||||
2730 | case bitc::CST_CODE_CE_EXTRACTELT | ||||
2731 | : { // CE_EXTRACTELT: [opty, opval, opty, opval] | ||||
2732 | if (Record.size() < 3) | ||||
2733 | return error("Invalid record"); | ||||
2734 | VectorType *OpTy = | ||||
2735 | dyn_cast_or_null<VectorType>(getTypeByID(Record[0])); | ||||
2736 | if (!OpTy) | ||||
2737 | return error("Invalid record"); | ||||
2738 | Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy); | ||||
2739 | Constant *Op1 = nullptr; | ||||
2740 | if (Record.size() == 4) { | ||||
2741 | Type *IdxTy = getTypeByID(Record[2]); | ||||
2742 | if (!IdxTy) | ||||
2743 | return error("Invalid record"); | ||||
2744 | Op1 = ValueList.getConstantFwdRef(Record[3], IdxTy); | ||||
2745 | } else { | ||||
2746 | // Deprecated, but still needed to read old bitcode files. | ||||
2747 | Op1 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context)); | ||||
2748 | } | ||||
2749 | if (!Op1) | ||||
2750 | return error("Invalid record"); | ||||
2751 | V = ConstantExpr::getExtractElement(Op0, Op1); | ||||
2752 | break; | ||||
2753 | } | ||||
2754 | case bitc::CST_CODE_CE_INSERTELT | ||||
2755 | : { // CE_INSERTELT: [opval, opval, opty, opval] | ||||
2756 | VectorType *OpTy = dyn_cast<VectorType>(CurTy); | ||||
2757 | if (Record.size() < 3 || !OpTy) | ||||
2758 | return error("Invalid record"); | ||||
2759 | Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy); | ||||
2760 | Constant *Op1 = ValueList.getConstantFwdRef(Record[1], | ||||
2761 | OpTy->getElementType()); | ||||
2762 | Constant *Op2 = nullptr; | ||||
2763 | if (Record.size() == 4) { | ||||
2764 | Type *IdxTy = getTypeByID(Record[2]); | ||||
2765 | if (!IdxTy) | ||||
2766 | return error("Invalid record"); | ||||
2767 | Op2 = ValueList.getConstantFwdRef(Record[3], IdxTy); | ||||
2768 | } else { | ||||
2769 | // Deprecated, but still needed to read old bitcode files. | ||||
2770 | Op2 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context)); | ||||
2771 | } | ||||
2772 | if (!Op2) | ||||
2773 | return error("Invalid record"); | ||||
2774 | V = ConstantExpr::getInsertElement(Op0, Op1, Op2); | ||||
2775 | break; | ||||
2776 | } | ||||
2777 | case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval] | ||||
2778 | VectorType *OpTy = dyn_cast<VectorType>(CurTy); | ||||
2779 | if (Record.size() < 3 || !OpTy) | ||||
2780 | return error("Invalid record"); | ||||
2781 | DelayedShuffles.push_back( | ||||
2782 | {OpTy, OpTy, Record[0], Record[1], Record[2], NextCstNo}); | ||||
2783 | ++NextCstNo; | ||||
2784 | continue; | ||||
2785 | } | ||||
2786 | case bitc::CST_CODE_CE_SHUFVEC_EX: { // [opty, opval, opval, opval] | ||||
2787 | VectorType *RTy = dyn_cast<VectorType>(CurTy); | ||||
2788 | VectorType *OpTy = | ||||
2789 | dyn_cast_or_null<VectorType>(getTypeByID(Record[0])); | ||||
2790 | if (Record.size() < 4 || !RTy || !OpTy) | ||||
2791 | return error("Invalid record"); | ||||
2792 | DelayedShuffles.push_back( | ||||
2793 | {OpTy, RTy, Record[1], Record[2], Record[3], NextCstNo}); | ||||
2794 | ++NextCstNo; | ||||
2795 | continue; | ||||
2796 | } | ||||
2797 | case bitc::CST_CODE_CE_CMP: { // CE_CMP: [opty, opval, opval, pred] | ||||
2798 | if (Record.size() < 4) | ||||
2799 | return error("Invalid record"); | ||||
2800 | Type *OpTy = getTypeByID(Record[0]); | ||||
2801 | if (!OpTy) | ||||
2802 | return error("Invalid record"); | ||||
2803 | Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy); | ||||
2804 | Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy); | ||||
2805 | |||||
2806 | if (OpTy->isFPOrFPVectorTy()) | ||||
2807 | V = ConstantExpr::getFCmp(Record[3], Op0, Op1); | ||||
2808 | else | ||||
2809 | V = ConstantExpr::getICmp(Record[3], Op0, Op1); | ||||
2810 | break; | ||||
2811 | } | ||||
2812 | // This maintains backward compatibility, pre-asm dialect keywords. | ||||
2813 | // Deprecated, but still needed to read old bitcode files. | ||||
2814 | case bitc::CST_CODE_INLINEASM_OLD: { | ||||
2815 | if (Record.size() < 2) | ||||
2816 | return error("Invalid record"); | ||||
2817 | std::string AsmStr, ConstrStr; | ||||
2818 | bool HasSideEffects = Record[0] & 1; | ||||
2819 | bool IsAlignStack = Record[0] >> 1; | ||||
2820 | unsigned AsmStrSize = Record[1]; | ||||
2821 | if (2+AsmStrSize >= Record.size()) | ||||
2822 | return error("Invalid record"); | ||||
2823 | unsigned ConstStrSize = Record[2+AsmStrSize]; | ||||
2824 | if (3+AsmStrSize+ConstStrSize > Record.size()) | ||||
2825 | return error("Invalid record"); | ||||
2826 | |||||
2827 | for (unsigned i = 0; i != AsmStrSize; ++i) | ||||
2828 | AsmStr += (char)Record[2+i]; | ||||
2829 | for (unsigned i = 0; i != ConstStrSize; ++i) | ||||
2830 | ConstrStr += (char)Record[3+AsmStrSize+i]; | ||||
2831 | UpgradeInlineAsmString(&AsmStr); | ||||
2832 | // FIXME: support upgrading in opaque pointers mode. | ||||
2833 | V = InlineAsm::get(cast<FunctionType>(CurTy->getPointerElementType()), | ||||
2834 | AsmStr, ConstrStr, HasSideEffects, IsAlignStack); | ||||
2835 | break; | ||||
2836 | } | ||||
2837 | // This version adds support for the asm dialect keywords (e.g., | ||||
2838 | // inteldialect). | ||||
2839 | case bitc::CST_CODE_INLINEASM_OLD2: { | ||||
2840 | if (Record.size() < 2) | ||||
2841 | return error("Invalid record"); | ||||
2842 | std::string AsmStr, ConstrStr; | ||||
2843 | bool HasSideEffects = Record[0] & 1; | ||||
2844 | bool IsAlignStack = (Record[0] >> 1) & 1; | ||||
2845 | unsigned AsmDialect = Record[0] >> 2; | ||||
2846 | unsigned AsmStrSize = Record[1]; | ||||
2847 | if (2+AsmStrSize >= Record.size()) | ||||
2848 | return error("Invalid record"); | ||||
2849 | unsigned ConstStrSize = Record[2+AsmStrSize]; | ||||
2850 | if (3+AsmStrSize+ConstStrSize > Record.size()) | ||||
2851 | return error("Invalid record"); | ||||
2852 | |||||
2853 | for (unsigned i = 0; i != AsmStrSize; ++i) | ||||
2854 | AsmStr += (char)Record[2+i]; | ||||
2855 | for (unsigned i = 0; i != ConstStrSize; ++i) | ||||
2856 | ConstrStr += (char)Record[3+AsmStrSize+i]; | ||||
2857 | UpgradeInlineAsmString(&AsmStr); | ||||
2858 | // FIXME: support upgrading in opaque pointers mode. | ||||
2859 | V = InlineAsm::get(cast<FunctionType>(CurTy->getPointerElementType()), | ||||
2860 | AsmStr, ConstrStr, HasSideEffects, IsAlignStack, | ||||
2861 | InlineAsm::AsmDialect(AsmDialect)); | ||||
2862 | break; | ||||
2863 | } | ||||
2864 | // This version adds support for the unwind keyword. | ||||
2865 | case bitc::CST_CODE_INLINEASM_OLD3: { | ||||
2866 | if (Record.size() < 2) | ||||
2867 | return error("Invalid record"); | ||||
2868 | unsigned OpNum = 0; | ||||
2869 | std::string AsmStr, ConstrStr; | ||||
2870 | bool HasSideEffects = Record[OpNum] & 1; | ||||
2871 | bool IsAlignStack = (Record[OpNum] >> 1) & 1; | ||||
2872 | unsigned AsmDialect = (Record[OpNum] >> 2) & 1; | ||||
2873 | bool CanThrow = (Record[OpNum] >> 3) & 1; | ||||
2874 | ++OpNum; | ||||
2875 | unsigned AsmStrSize = Record[OpNum]; | ||||
2876 | ++OpNum; | ||||
2877 | if (OpNum + AsmStrSize >= Record.size()) | ||||
2878 | return error("Invalid record"); | ||||
2879 | unsigned ConstStrSize = Record[OpNum + AsmStrSize]; | ||||
2880 | if (OpNum + 1 + AsmStrSize + ConstStrSize > Record.size()) | ||||
2881 | return error("Invalid record"); | ||||
2882 | |||||
2883 | for (unsigned i = 0; i != AsmStrSize; ++i) | ||||
2884 | AsmStr += (char)Record[OpNum + i]; | ||||
2885 | ++OpNum; | ||||
2886 | for (unsigned i = 0; i != ConstStrSize; ++i) | ||||
2887 | ConstrStr += (char)Record[OpNum + AsmStrSize + i]; | ||||
2888 | UpgradeInlineAsmString(&AsmStr); | ||||
2889 | // FIXME: support upgrading in opaque pointers mode. | ||||
2890 | V = InlineAsm::get(cast<FunctionType>(CurTy->getPointerElementType()), | ||||
2891 | AsmStr, ConstrStr, HasSideEffects, IsAlignStack, | ||||
2892 | InlineAsm::AsmDialect(AsmDialect), CanThrow); | ||||
2893 | break; | ||||
2894 | } | ||||
2895 | // This version adds explicit function type. | ||||
2896 | case bitc::CST_CODE_INLINEASM: { | ||||
2897 | if (Record.size() < 3) | ||||
2898 | return error("Invalid record"); | ||||
2899 | unsigned OpNum = 0; | ||||
2900 | auto *FnTy = dyn_cast_or_null<FunctionType>(getTypeByID(Record[OpNum])); | ||||
2901 | ++OpNum; | ||||
2902 | if (!FnTy) | ||||
2903 | return error("Invalid record"); | ||||
2904 | std::string AsmStr, ConstrStr; | ||||
2905 | bool HasSideEffects = Record[OpNum] & 1; | ||||
2906 | bool IsAlignStack = (Record[OpNum] >> 1) & 1; | ||||
2907 | unsigned AsmDialect = (Record[OpNum] >> 2) & 1; | ||||
2908 | bool CanThrow = (Record[OpNum] >> 3) & 1; | ||||
2909 | ++OpNum; | ||||
2910 | unsigned AsmStrSize = Record[OpNum]; | ||||
2911 | ++OpNum; | ||||
2912 | if (OpNum + AsmStrSize >= Record.size()) | ||||
2913 | return error("Invalid record"); | ||||
2914 | unsigned ConstStrSize = Record[OpNum + AsmStrSize]; | ||||
2915 | if (OpNum + 1 + AsmStrSize + ConstStrSize > Record.size()) | ||||
2916 | return error("Invalid record"); | ||||
2917 | |||||
2918 | for (unsigned i = 0; i != AsmStrSize; ++i) | ||||
2919 | AsmStr += (char)Record[OpNum + i]; | ||||
2920 | ++OpNum; | ||||
2921 | for (unsigned i = 0; i != ConstStrSize; ++i) | ||||
2922 | ConstrStr += (char)Record[OpNum + AsmStrSize + i]; | ||||
2923 | UpgradeInlineAsmString(&AsmStr); | ||||
2924 | V = InlineAsm::get(FnTy, AsmStr, ConstrStr, HasSideEffects, IsAlignStack, | ||||
2925 | InlineAsm::AsmDialect(AsmDialect), CanThrow); | ||||
2926 | break; | ||||
2927 | } | ||||
2928 | case bitc::CST_CODE_BLOCKADDRESS:{ | ||||
2929 | if (Record.size() < 3) | ||||
2930 | return error("Invalid record"); | ||||
2931 | Type *FnTy = getTypeByID(Record[0]); | ||||
2932 | if (!FnTy) | ||||
2933 | return error("Invalid record"); | ||||
2934 | Function *Fn = | ||||
2935 | dyn_cast_or_null<Function>(ValueList.getConstantFwdRef(Record[1],FnTy)); | ||||
2936 | if (!Fn) | ||||
2937 | return error("Invalid record"); | ||||
2938 | |||||
2939 | // If the function is already parsed we can insert the block address right | ||||
2940 | // away. | ||||
2941 | BasicBlock *BB; | ||||
2942 | unsigned BBID = Record[2]; | ||||
2943 | if (!BBID) | ||||
2944 | // Invalid reference to entry block. | ||||
2945 | return error("Invalid ID"); | ||||
2946 | if (!Fn->empty()) { | ||||
2947 | Function::iterator BBI = Fn->begin(), BBE = Fn->end(); | ||||
2948 | for (size_t I = 0, E = BBID; I != E; ++I) { | ||||
2949 | if (BBI == BBE) | ||||
2950 | return error("Invalid ID"); | ||||
2951 | ++BBI; | ||||
2952 | } | ||||
2953 | BB = &*BBI; | ||||
2954 | } else { | ||||
2955 | // Otherwise insert a placeholder and remember it so it can be inserted | ||||
2956 | // when the function is parsed. | ||||
2957 | auto &FwdBBs = BasicBlockFwdRefs[Fn]; | ||||
2958 | if (FwdBBs.empty()) | ||||
2959 | BasicBlockFwdRefQueue.push_back(Fn); | ||||
2960 | if (FwdBBs.size() < BBID + 1) | ||||
2961 | FwdBBs.resize(BBID + 1); | ||||
2962 | if (!FwdBBs[BBID]) | ||||
2963 | FwdBBs[BBID] = BasicBlock::Create(Context); | ||||
2964 | BB = FwdBBs[BBID]; | ||||
2965 | } | ||||
2966 | V = BlockAddress::get(Fn, BB); | ||||
2967 | break; | ||||
2968 | } | ||||
2969 | case bitc::CST_CODE_DSO_LOCAL_EQUIVALENT: { | ||||
2970 | if (Record.size() < 2) | ||||
2971 | return error("Invalid record"); | ||||
2972 | Type *GVTy = getTypeByID(Record[0]); | ||||
2973 | if (!GVTy) | ||||
2974 | return error("Invalid record"); | ||||
2975 | GlobalValue *GV = dyn_cast_or_null<GlobalValue>( | ||||
2976 | ValueList.getConstantFwdRef(Record[1], GVTy)); | ||||
2977 | if (!GV) | ||||
2978 | return error("Invalid record"); | ||||
2979 | |||||
2980 | V = DSOLocalEquivalent::get(GV); | ||||
2981 | break; | ||||
2982 | } | ||||
2983 | case bitc::CST_CODE_NO_CFI_VALUE: { | ||||
2984 | if (Record.size() < 2) | ||||
2985 | return error("Invalid record"); | ||||
2986 | Type *GVTy = getTypeByID(Record[0]); | ||||
2987 | if (!GVTy) | ||||
2988 | return error("Invalid record"); | ||||
2989 | GlobalValue *GV = dyn_cast_or_null<GlobalValue>( | ||||
2990 | ValueList.getConstantFwdRef(Record[1], GVTy)); | ||||
2991 | if (!GV) | ||||
2992 | return error("Invalid record"); | ||||
2993 | V = NoCFIValue::get(GV); | ||||
2994 | break; | ||||
2995 | } | ||||
2996 | } | ||||
2997 | |||||
2998 | ValueList.assignValue(V, NextCstNo); | ||||
2999 | ++NextCstNo; | ||||
3000 | } | ||||
3001 | } | ||||
3002 | |||||
3003 | Error BitcodeReader::parseUseLists() { | ||||
3004 | if (Error Err = Stream.EnterSubBlock(bitc::USELIST_BLOCK_ID)) | ||||
3005 | return Err; | ||||
3006 | |||||
3007 | // Read all the records. | ||||
3008 | SmallVector<uint64_t, 64> Record; | ||||
3009 | |||||
3010 | while (true) { | ||||
3011 | Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks(); | ||||
3012 | if (!MaybeEntry) | ||||
3013 | return MaybeEntry.takeError(); | ||||
3014 | BitstreamEntry Entry = MaybeEntry.get(); | ||||
3015 | |||||
3016 | switch (Entry.Kind) { | ||||
3017 | case BitstreamEntry::SubBlock: // Handled for us already. | ||||
3018 | case BitstreamEntry::Error: | ||||
3019 | return error("Malformed block"); | ||||
3020 | case BitstreamEntry::EndBlock: | ||||
3021 | return Error::success(); | ||||
3022 | case BitstreamEntry::Record: | ||||
3023 | // The interesting case. | ||||
3024 | break; | ||||
3025 | } | ||||
3026 | |||||
3027 | // Read a use list record. | ||||
3028 | Record.clear(); | ||||
3029 | bool IsBB = false; | ||||
3030 | Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record); | ||||
3031 | if (!MaybeRecord) | ||||
3032 | return MaybeRecord.takeError(); | ||||
3033 | switch (MaybeRecord.get()) { | ||||
3034 | default: // Default behavior: unknown type. | ||||
3035 | break; | ||||
3036 | case bitc::USELIST_CODE_BB: | ||||
3037 | IsBB = true; | ||||
3038 | LLVM_FALLTHROUGH[[gnu::fallthrough]]; | ||||
3039 | case bitc::USELIST_CODE_DEFAULT: { | ||||
3040 | unsigned RecordLength = Record.size(); | ||||
3041 | if (RecordLength < 3) | ||||
3042 | // Records should have at least an ID and two indexes. | ||||
3043 | return error("Invalid record"); | ||||
3044 | unsigned ID = Record.pop_back_val(); | ||||
3045 | |||||
3046 | Value *V; | ||||
3047 | if (IsBB) { | ||||
3048 | assert(ID < FunctionBBs.size() && "Basic block not found")(static_cast <bool> (ID < FunctionBBs.size() && "Basic block not found") ? void (0) : __assert_fail ("ID < FunctionBBs.size() && \"Basic block not found\"" , "llvm/lib/Bitcode/Reader/BitcodeReader.cpp", 3048, __extension__ __PRETTY_FUNCTION__)); | ||||
3049 | V = FunctionBBs[ID]; | ||||
3050 | } else | ||||
3051 | V = ValueList[ID]; | ||||
3052 | unsigned NumUses = 0; | ||||
3053 | SmallDenseMap<const Use *, unsigned, 16> Order; | ||||
3054 | for (const Use &U : V->materialized_uses()) { | ||||
3055 | if (++NumUses > Record.size()) | ||||
3056 | break; | ||||
3057 | Order[&U] = Record[NumUses - 1]; | ||||
3058 | } | ||||
3059 | if (Order.size() != Record.size() || NumUses > Record.size()) | ||||
3060 | // Mismatches can happen if the functions are being materialized lazily | ||||
3061 | // (out-of-order), or a value has been upgraded. | ||||
3062 | break; | ||||
3063 | |||||
3064 | V->sortUseList([&](const Use &L, const Use &R) { | ||||
3065 | return Order.lookup(&L) < Order.lookup(&R); | ||||
3066 | }); | ||||
3067 | break; | ||||
3068 | } | ||||
3069 | } | ||||
3070 | } | ||||
3071 | } | ||||
3072 | |||||
3073 | /// When we see the block for metadata, remember where it is and then skip it. | ||||
3074 | /// This lets us lazily deserialize the metadata. | ||||
3075 | Error BitcodeReader::rememberAndSkipMetadata() { | ||||
3076 | // Save the current stream state. | ||||
3077 | uint64_t CurBit = Stream.GetCurrentBitNo(); | ||||
3078 | DeferredMetadataInfo.push_back(CurBit); | ||||
3079 | |||||
3080 | // Skip over the block for now. | ||||
3081 | if (Error Err = Stream.SkipBlock()) | ||||
3082 | return Err; | ||||
3083 | return Error::success(); | ||||
3084 | } | ||||
3085 | |||||
3086 | Error BitcodeReader::materializeMetadata() { | ||||
3087 | for (uint64_t BitPos : DeferredMetadataInfo) { | ||||
3088 | // Move the bit stream to the saved position. | ||||
3089 | if (Error JumpFailed = Stream.JumpToBit(BitPos)) | ||||
3090 | return JumpFailed; | ||||
3091 | if (Error Err = MDLoader->parseModuleMetadata()) | ||||
3092 | return Err; | ||||
3093 | } | ||||
3094 | |||||
3095 | // Upgrade "Linker Options" module flag to "llvm.linker.options" module-level | ||||
3096 | // metadata. Only upgrade if the new option doesn't exist to avoid upgrade | ||||
3097 | // multiple times. | ||||
3098 | if (!TheModule->getNamedMetadata("llvm.linker.options")) { | ||||
3099 | if (Metadata *Val = TheModule->getModuleFlag("Linker Options")) { | ||||
3100 | NamedMDNode *LinkerOpts = | ||||
3101 | TheModule->getOrInsertNamedMetadata("llvm.linker.options"); | ||||
3102 | for (const MDOperand &MDOptions : cast<MDNode>(Val)->operands()) | ||||
3103 | LinkerOpts->addOperand(cast<MDNode>(MDOptions)); | ||||
3104 | } | ||||
3105 | } | ||||
3106 | |||||
3107 | DeferredMetadataInfo.clear(); | ||||
3108 | return Error::success(); | ||||
3109 | } | ||||
3110 | |||||
3111 | void BitcodeReader::setStripDebugInfo() { StripDebugInfo = true; } | ||||
3112 | |||||
3113 | /// When we see the block for a function body, remember where it is and then | ||||
3114 | /// skip it. This lets us lazily deserialize the functions. | ||||
3115 | Error BitcodeReader::rememberAndSkipFunctionBody() { | ||||
3116 | // Get the function we are talking about. | ||||
3117 | if (FunctionsWithBodies.empty()) | ||||
3118 | return error("Insufficient function protos"); | ||||
3119 | |||||
3120 | Function *Fn = FunctionsWithBodies.back(); | ||||
3121 | FunctionsWithBodies.pop_back(); | ||||
3122 | |||||
3123 | // Save the current stream state. | ||||
3124 | uint64_t CurBit = Stream.GetCurrentBitNo(); | ||||
3125 | assert((static_cast <bool> ((DeferredFunctionInfo[Fn] == 0 || DeferredFunctionInfo [Fn] == CurBit) && "Mismatch between VST and scanned function offsets" ) ? void (0) : __assert_fail ("(DeferredFunctionInfo[Fn] == 0 || DeferredFunctionInfo[Fn] == CurBit) && \"Mismatch between VST and scanned function offsets\"" , "llvm/lib/Bitcode/Reader/BitcodeReader.cpp", 3127, __extension__ __PRETTY_FUNCTION__)) | ||||
3126 | (DeferredFunctionInfo[Fn] == 0 || DeferredFunctionInfo[Fn] == CurBit) &&(static_cast <bool> ((DeferredFunctionInfo[Fn] == 0 || DeferredFunctionInfo [Fn] == CurBit) && "Mismatch between VST and scanned function offsets" ) ? void (0) : __assert_fail ("(DeferredFunctionInfo[Fn] == 0 || DeferredFunctionInfo[Fn] == CurBit) && \"Mismatch between VST and scanned function offsets\"" , "llvm/lib/Bitcode/Reader/BitcodeReader.cpp", 3127, __extension__ __PRETTY_FUNCTION__)) | ||||
3127 | "Mismatch between VST and scanned function offsets")(static_cast <bool> ((DeferredFunctionInfo[Fn] == 0 || DeferredFunctionInfo [Fn] == CurBit) && "Mismatch between VST and scanned function offsets" ) ? void (0) : __assert_fail ("(DeferredFunctionInfo[Fn] == 0 || DeferredFunctionInfo[Fn] == CurBit) && \"Mismatch between VST and scanned function offsets\"" , "llvm/lib/Bitcode/Reader/BitcodeReader.cpp", 3127, __extension__ __PRETTY_FUNCTION__)); | ||||
3128 | DeferredFunctionInfo[Fn] = CurBit; | ||||
3129 | |||||
3130 | // Skip over the function block for now. | ||||
3131 | if (Error Err = Stream.SkipBlock()) | ||||
3132 | return Err; | ||||
3133 | return Error::success(); | ||||
3134 | } | ||||
3135 | |||||
3136 | Error BitcodeReader::globalCleanup() { | ||||
3137 | // Patch the initializers for globals and aliases up. | ||||
3138 | if (Error Err = resolveGlobalAndIndirectSymbolInits()) | ||||
3139 | return Err; | ||||
3140 | if (!GlobalInits.empty() || !IndirectSymbolInits.empty()) | ||||
3141 | return error("Malformed global initializer set"); | ||||
3142 | |||||
3143 | // Look for intrinsic functions which need to be upgraded at some point | ||||
3144 | // and functions that need to have their function attributes upgraded. | ||||
3145 | for (Function &F : *TheModule) { | ||||
3146 | MDLoader->upgradeDebugIntrinsics(F); | ||||
3147 | Function *NewFn; | ||||
3148 | if (UpgradeIntrinsicFunction(&F, NewFn)) | ||||
3149 | UpgradedIntrinsics[&F] = NewFn; | ||||
3150 | else if (auto Remangled = Intrinsic::remangleIntrinsicFunction(&F)) | ||||
3151 | // Some types could be renamed during loading if several modules are | ||||
3152 | // loaded in the same LLVMContext (LTO scenario). In this case we should | ||||
3153 | // remangle intrinsics names as well. | ||||
3154 | RemangledIntrinsics[&F] = Remangled.getValue(); | ||||
3155 | // Look for functions that rely on old function attribute behavior. | ||||
3156 | UpgradeFunctionAttributes(F); | ||||
3157 | } | ||||
3158 | |||||
3159 | // Look for global variables which need to be renamed. | ||||
3160 | std::vector<std::pair<GlobalVariable *, GlobalVariable *>> UpgradedVariables; | ||||
3161 | for (GlobalVariable &GV : TheModule->globals()) | ||||
3162 | if (GlobalVariable *Upgraded = UpgradeGlobalVariable(&GV)) | ||||
3163 | UpgradedVariables.emplace_back(&GV, Upgraded); | ||||
3164 | for (auto &Pair : UpgradedVariables) { | ||||
3165 | Pair.first->eraseFromParent(); | ||||
3166 | TheModule->getGlobalList().push_back(Pair.second); | ||||
3167 | } | ||||
3168 | |||||
3169 | // Force deallocation of memory for these vectors to favor the client that | ||||
3170 | // want lazy deserialization. | ||||
3171 | std::vector<std::pair<GlobalVariable *, unsigned>>().swap(GlobalInits); | ||||
3172 | std::vector<std::pair<GlobalValue *, unsigned>>().swap(IndirectSymbolInits); | ||||
3173 | return Error::success(); | ||||
3174 | } | ||||
3175 | |||||
3176 | /// Support for lazy parsing of function bodies. This is required if we | ||||
3177 | /// either have an old bitcode file without a VST forward declaration record, | ||||
3178 | /// or if we have an anonymous function being materialized, since anonymous | ||||
3179 | /// functions do not have a name and are therefore not in the VST. | ||||
3180 | Error BitcodeReader::rememberAndSkipFunctionBodies() { | ||||
3181 | if (Error JumpFailed = Stream.JumpToBit(NextUnreadBit)) | ||||
3182 | return JumpFailed; | ||||
3183 | |||||
3184 | if (Stream.AtEndOfStream()) | ||||
3185 | return error("Could not find function in stream"); | ||||
3186 | |||||
3187 | if (!SeenFirstFunctionBody) | ||||
3188 | return error("Trying to materialize functions before seeing function blocks"); | ||||
3189 | |||||
3190 | // An old bitcode file with the symbol table at the end would have | ||||
3191 | // finished the parse greedily. | ||||
3192 | assert(SeenValueSymbolTable)(static_cast <bool> (SeenValueSymbolTable) ? void (0) : __assert_fail ("SeenValueSymbolTable", "llvm/lib/Bitcode/Reader/BitcodeReader.cpp" , 3192, __extension__ __PRETTY_FUNCTION__)); | ||||
3193 | |||||
3194 | SmallVector<uint64_t, 64> Record; | ||||
3195 | |||||
3196 | while (true) { | ||||
3197 | Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance(); | ||||
3198 | if (!MaybeEntry) | ||||
3199 | return MaybeEntry.takeError(); | ||||
3200 | llvm::BitstreamEntry Entry = MaybeEntry.get(); | ||||
3201 | |||||
3202 | switch (Entry.Kind) { | ||||
3203 | default: | ||||
3204 | return error("Expect SubBlock"); | ||||
3205 | case BitstreamEntry::SubBlock: | ||||
3206 | switch (Entry.ID) { | ||||
3207 | default: | ||||
3208 | return error("Expect function block"); | ||||
3209 | case bitc::FUNCTION_BLOCK_ID: | ||||
3210 | if (Error Err = rememberAndSkipFunctionBody()) | ||||
3211 | return Err; | ||||
3212 | NextUnreadBit = Stream.GetCurrentBitNo(); | ||||
3213 | return Error::success(); | ||||
3214 | } | ||||
3215 | } | ||||
3216 | } | ||||
3217 | } | ||||
3218 | |||||
3219 | Error BitcodeReaderBase::readBlockInfo() { | ||||
3220 | Expected<Optional<BitstreamBlockInfo>> MaybeNewBlockInfo = | ||||
3221 | Stream.ReadBlockInfoBlock(); | ||||
3222 | if (!MaybeNewBlockInfo) | ||||
3223 | return MaybeNewBlockInfo.takeError(); | ||||
3224 | Optional<BitstreamBlockInfo> NewBlockInfo = | ||||
3225 | std::move(MaybeNewBlockInfo.get()); | ||||
3226 | if (!NewBlockInfo) | ||||
3227 | return error("Malformed block"); | ||||
3228 | BlockInfo = std::move(*NewBlockInfo); | ||||
3229 | return Error::success(); | ||||
3230 | } | ||||
3231 | |||||
3232 | Error BitcodeReader::parseComdatRecord(ArrayRef<uint64_t> Record) { | ||||
3233 | // v1: [selection_kind, name] | ||||
3234 | // v2: [strtab_offset, strtab_size, selection_kind] | ||||
3235 | StringRef Name; | ||||
3236 | std::tie(Name, Record) = readNameFromStrtab(Record); | ||||
3237 | |||||
3238 | if (Record.empty()) | ||||
3239 | return error("Invalid record"); | ||||
3240 | Comdat::SelectionKind SK = getDecodedComdatSelectionKind(Record[0]); | ||||
3241 | std::string OldFormatName; | ||||
3242 | if (!UseStrtab) { | ||||
3243 | if (Record.size() < 2) | ||||
3244 | return error("Invalid record"); | ||||
3245 | unsigned ComdatNameSize = Record[1]; | ||||
3246 | if (ComdatNameSize > Record.size() - 2) | ||||
3247 | return error("Comdat name size too large"); | ||||
3248 | OldFormatName.reserve(ComdatNameSize); | ||||
3249 | for (unsigned i = 0; i != ComdatNameSize; ++i) | ||||
3250 | OldFormatName += (char)Record[2 + i]; | ||||
3251 | Name = OldFormatName; | ||||
3252 | } | ||||
3253 | Comdat *C = TheModule->getOrInsertComdat(Name); | ||||
3254 | C->setSelectionKind(SK); | ||||
3255 | ComdatList.push_back(C); | ||||
3256 | return Error::success(); | ||||
3257 | } | ||||
3258 | |||||
3259 | static void inferDSOLocal(GlobalValue *GV) { | ||||
3260 | // infer dso_local from linkage and visibility if it is not encoded. | ||||
3261 | if (GV->hasLocalLinkage() || | ||||
3262 | (!GV->hasDefaultVisibility() && !GV->hasExternalWeakLinkage())) | ||||
3263 | GV->setDSOLocal(true); | ||||
3264 | } | ||||
3265 | |||||
3266 | Error BitcodeReader::parseGlobalVarRecord(ArrayRef<uint64_t> Record) { | ||||
3267 | // v1: [pointer type, isconst, initid, linkage, alignment, section, | ||||
3268 | // visibility, threadlocal, unnamed_addr, externally_initialized, | ||||
3269 | // dllstorageclass, comdat, attributes, preemption specifier, | ||||
3270 | // partition strtab offset, partition strtab size] (name in VST) | ||||
3271 | // v2: [strtab_offset, strtab_size, v1] | ||||
3272 | StringRef Name; | ||||
3273 | std::tie(Name, Record) = readNameFromStrtab(Record); | ||||
3274 | |||||
3275 | if (Record.size() < 6) | ||||
3276 | return error("Invalid record"); | ||||
3277 | Type *Ty = getTypeByID(Record[0]); | ||||
3278 | if (!Ty) | ||||
3279 | return error("Invalid record"); | ||||
3280 | bool isConstant = Record[1] & 1; | ||||
3281 | bool explicitType = Record[1] & 2; | ||||
3282 | unsigned AddressSpace; | ||||
3283 | if (explicitType) { | ||||
3284 | AddressSpace = Record[1] >> 2; | ||||
3285 | } else { | ||||
3286 | if (!Ty->isPointerTy()) | ||||
3287 | return error("Invalid type for value"); | ||||
3288 | AddressSpace = cast<PointerType>(Ty)->getAddressSpace(); | ||||
3289 | Ty = Ty->getPointerElementType(); | ||||
3290 | } | ||||
3291 | |||||
3292 | uint64_t RawLinkage = Record[3]; | ||||
3293 | GlobalValue::LinkageTypes Linkage = getDecodedLinkage(RawLinkage); | ||||
3294 | MaybeAlign Alignment; | ||||
3295 | if (Error Err = parseAlignmentValue(Record[4], Alignment)) | ||||
3296 | return Err; | ||||
3297 | std::string Section; | ||||
3298 | if (Record[5]) { | ||||
3299 | if (Record[5] - 1 >= SectionTable.size()) | ||||
3300 | return error("Invalid ID"); | ||||
3301 | Section = SectionTable[Record[5] - 1]; | ||||
3302 | } | ||||
3303 | GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility; | ||||
3304 | // Local linkage must have default visibility. | ||||
3305 | // auto-upgrade `hidden` and `protected` for old bitcode. | ||||
3306 | if (Record.size() > 6 && !GlobalValue::isLocalLinkage(Linkage)) | ||||
3307 | Visibility = getDecodedVisibility(Record[6]); | ||||
3308 | |||||
3309 | GlobalVariable::ThreadLocalMode TLM = GlobalVariable::NotThreadLocal; | ||||
3310 | if (Record.size() > 7) | ||||
3311 | TLM = getDecodedThreadLocalMode(Record[7]); | ||||
3312 | |||||
3313 | GlobalValue::UnnamedAddr UnnamedAddr = GlobalValue::UnnamedAddr::None; | ||||
3314 | if (Record.size() > 8) | ||||
3315 | UnnamedAddr = getDecodedUnnamedAddrType(Record[8]); | ||||
3316 | |||||
3317 | bool ExternallyInitialized = false; | ||||
3318 | if (Record.size() > 9) | ||||
3319 | ExternallyInitialized = Record[9]; | ||||
3320 | |||||
3321 | GlobalVariable *NewGV = | ||||
3322 | new GlobalVariable(*TheModule, Ty, isConstant, Linkage, nullptr, Name, | ||||
3323 | nullptr, TLM, AddressSpace, ExternallyInitialized); | ||||
3324 | NewGV->setAlignment(Alignment); | ||||
3325 | if (!Section.empty()) | ||||
3326 | NewGV->setSection(Section); | ||||
3327 | NewGV->setVisibility(Visibility); | ||||
3328 | NewGV->setUnnamedAddr(UnnamedAddr); | ||||
3329 | |||||
3330 | if (Record.size() > 10) | ||||
3331 | NewGV->setDLLStorageClass(getDecodedDLLStorageClass(Record[10])); | ||||
3332 | else | ||||
3333 | upgradeDLLImportExportLinkage(NewGV, RawLinkage); | ||||
3334 | |||||
3335 | ValueList.push_back(NewGV); | ||||
3336 | |||||
3337 | // Remember which value to use for the global initializer. | ||||
3338 | if (unsigned InitID = Record[2]) | ||||
3339 | GlobalInits.push_back(std::make_pair(NewGV, InitID - 1)); | ||||
3340 | |||||
3341 | if (Record.size() > 11) { | ||||
3342 | if (unsigned ComdatID = Record[11]) { | ||||
3343 | if (ComdatID > ComdatList.size()) | ||||
3344 | return error("Invalid global variable comdat ID"); | ||||
3345 | NewGV->setComdat(ComdatList[ComdatID - 1]); | ||||
3346 | } | ||||
3347 | } else if (hasImplicitComdat(RawLinkage)) { | ||||
3348 | ImplicitComdatObjects.insert(NewGV); | ||||
3349 | } | ||||
3350 | |||||
3351 | if (Record.size() > 12) { | ||||
3352 | auto AS = getAttributes(Record[12]).getFnAttrs(); | ||||
3353 | NewGV->setAttributes(AS); | ||||
3354 | } | ||||
3355 | |||||
3356 | if (Record.size() > 13) { | ||||
3357 | NewGV->setDSOLocal(getDecodedDSOLocal(Record[13])); | ||||
3358 | } | ||||
3359 | inferDSOLocal(NewGV); | ||||
3360 | |||||
3361 | // Check whether we have enough values to read a partition name. | ||||
3362 | if (Record.size() > 15) | ||||
3363 | NewGV->setPartition(StringRef(Strtab.data() + Record[14], Record[15])); | ||||
3364 | |||||
3365 | return Error::success(); | ||||
3366 | } | ||||
3367 | |||||
3368 | Error BitcodeReader::parseFunctionRecord(ArrayRef<uint64_t> Record) { | ||||
3369 | // v1: [type, callingconv, isproto, linkage, paramattr, alignment, section, | ||||
3370 | // visibility, gc, unnamed_addr, prologuedata, dllstorageclass, comdat, | ||||
3371 | // prefixdata, personalityfn, preemption specifier, addrspace] (name in VST) | ||||
3372 | // v2: [strtab_offset, strtab_size, v1] | ||||
3373 | StringRef Name; | ||||
3374 | std::tie(Name, Record) = readNameFromStrtab(Record); | ||||
3375 | |||||
3376 | if (Record.size() < 8) | ||||
3377 | return error("Invalid record"); | ||||
3378 | Type *FTy = getTypeByID(Record[0]); | ||||
3379 | if (!FTy) | ||||
3380 | return error("Invalid record"); | ||||
3381 | if (auto *PTy = dyn_cast<PointerType>(FTy)) | ||||
3382 | FTy = PTy->getPointerElementType(); | ||||
3383 | |||||
3384 | if (!isa<FunctionType>(FTy)) | ||||
3385 | return error("Invalid type for value"); | ||||
3386 | auto CC = static_cast<CallingConv::ID>(Record[1]); | ||||
3387 | if (CC & ~CallingConv::MaxID) | ||||
3388 | return error("Invalid calling convention ID"); | ||||
3389 | |||||
3390 | unsigned AddrSpace = TheModule->getDataLayout().getProgramAddressSpace(); | ||||
3391 | if (Record.size() > 16) | ||||
3392 | AddrSpace = Record[16]; | ||||
3393 | |||||
3394 | Function *Func = | ||||
3395 | Function::Create(cast<FunctionType>(FTy), GlobalValue::ExternalLinkage, | ||||
3396 | AddrSpace, Name, TheModule); | ||||
3397 | |||||
3398 | assert(Func->getFunctionType() == FTy &&(static_cast <bool> (Func->getFunctionType() == FTy && "Incorrect fully specified type provided for function") ? void (0) : __assert_fail ("Func->getFunctionType() == FTy && \"Incorrect fully specified type provided for function\"" , "llvm/lib/Bitcode/Reader/BitcodeReader.cpp", 3399, __extension__ __PRETTY_FUNCTION__)) | ||||
3399 | "Incorrect fully specified type provided for function")(static_cast <bool> (Func->getFunctionType() == FTy && "Incorrect fully specified type provided for function") ? void (0) : __assert_fail ("Func->getFunctionType() == FTy && \"Incorrect fully specified type provided for function\"" , "llvm/lib/Bitcode/Reader/BitcodeReader.cpp", 3399, __extension__ __PRETTY_FUNCTION__)); | ||||
3400 | FunctionTypes[Func] = cast<FunctionType>(FTy); | ||||
3401 | |||||
3402 | Func->setCallingConv(CC); | ||||
3403 | bool isProto = Record[2]; | ||||
3404 | uint64_t RawLinkage = Record[3]; | ||||
3405 | Func->setLinkage(getDecodedLinkage(RawLinkage)); | ||||
3406 | Func->setAttributes(getAttributes(Record[4])); | ||||
3407 | |||||
3408 | // Upgrade any old-style byval or sret without a type by propagating the | ||||
3409 | // argument's pointee type. There should be no opaque pointers where the byval | ||||
3410 | // type is implicit. | ||||
3411 | for (unsigned i = 0; i != Func->arg_size(); ++i) { | ||||
3412 | for (Attribute::AttrKind Kind : {Attribute::ByVal, Attribute::StructRet, | ||||
3413 | Attribute::InAlloca}) { | ||||
3414 | if (!Func->hasParamAttribute(i, Kind)) | ||||
3415 | continue; | ||||
3416 | |||||
3417 | if (Func->getParamAttribute(i, Kind).getValueAsType()) | ||||
3418 | continue; | ||||
3419 | |||||
3420 | Func->removeParamAttr(i, Kind); | ||||
3421 | |||||
3422 | Type *PTy = cast<FunctionType>(FTy)->getParamType(i); | ||||
3423 | Type *PtrEltTy = PTy->getPointerElementType(); | ||||
3424 | Attribute NewAttr; | ||||
3425 | switch (Kind) { | ||||
3426 | case Attribute::ByVal: | ||||
3427 | NewAttr = Attribute::getWithByValType(Context, PtrEltTy); | ||||
3428 | break; | ||||
3429 | case Attribute::StructRet: | ||||
3430 | NewAttr = Attribute::getWithStructRetType(Context, PtrEltTy); | ||||
3431 | break; | ||||
3432 | case Attribute::InAlloca: | ||||
3433 | NewAttr = Attribute::getWithInAllocaType(Context, PtrEltTy); | ||||
3434 | break; | ||||
3435 | default: | ||||
3436 | llvm_unreachable("not an upgraded type attribute")::llvm::llvm_unreachable_internal("not an upgraded type attribute" , "llvm/lib/Bitcode/Reader/BitcodeReader.cpp", 3436); | ||||
3437 | } | ||||
3438 | |||||
3439 | Func->addParamAttr(i, NewAttr); | ||||
3440 | } | ||||
3441 | } | ||||
3442 | |||||
3443 | MaybeAlign Alignment; | ||||
3444 | if (Error Err = parseAlignmentValue(Record[5], Alignment)) | ||||
3445 | return Err; | ||||
3446 | Func->setAlignment(Alignment); | ||||
3447 | if (Record[6]) { | ||||
3448 | if (Record[6] - 1 >= SectionTable.size()) | ||||
3449 | return error("Invalid ID"); | ||||
3450 | Func->setSection(SectionTable[Record[6] - 1]); | ||||
3451 | } | ||||
3452 | // Local linkage must have default visibility. | ||||
3453 | // auto-upgrade `hidden` and `protected` for old bitcode. | ||||
3454 | if (!Func->hasLocalLinkage()) | ||||
3455 | Func->setVisibility(getDecodedVisibility(Record[7])); | ||||
3456 | if (Record.size() > 8 && Record[8]) { | ||||
3457 | if (Record[8] - 1 >= GCTable.size()) | ||||
3458 | return error("Invalid ID"); | ||||
3459 | Func->setGC(GCTable[Record[8] - 1]); | ||||
3460 | } | ||||
3461 | GlobalValue::UnnamedAddr UnnamedAddr = GlobalValue::UnnamedAddr::None; | ||||
3462 | if (Record.size() > 9) | ||||
3463 | UnnamedAddr = getDecodedUnnamedAddrType(Record[9]); | ||||
3464 | Func->setUnnamedAddr(UnnamedAddr); | ||||
3465 | |||||
3466 | FunctionOperandInfo OperandInfo = {Func, 0, 0, 0}; | ||||
3467 | if (Record.size() > 10) | ||||
3468 | OperandInfo.Prologue = Record[10]; | ||||
3469 | |||||
3470 | if (Record.size() > 11) | ||||
3471 | Func->setDLLStorageClass(getDecodedDLLStorageClass(Record[11])); | ||||
3472 | else | ||||
3473 | upgradeDLLImportExportLinkage(Func, RawLinkage); | ||||
3474 | |||||
3475 | if (Record.size() > 12) { | ||||
3476 | if (unsigned ComdatID = Record[12]) { | ||||
3477 | if (ComdatID > ComdatList.size()) | ||||
3478 | return error("Invalid function comdat ID"); | ||||
3479 | Func->setComdat(ComdatList[ComdatID - 1]); | ||||
3480 | } | ||||
3481 | } else if (hasImplicitComdat(RawLinkage)) { | ||||
3482 | ImplicitComdatObjects.insert(Func); | ||||
3483 | } | ||||
3484 | |||||
3485 | if (Record.size() > 13) | ||||
3486 | OperandInfo.Prefix = Record[13]; | ||||
3487 | |||||
3488 | if (Record.size() > 14) | ||||
3489 | OperandInfo.PersonalityFn = Record[14]; | ||||
3490 | |||||
3491 | if (Record.size() > 15) { | ||||
3492 | Func->setDSOLocal(getDecodedDSOLocal(Record[15])); | ||||
3493 | } | ||||
3494 | inferDSOLocal(Func); | ||||
3495 | |||||
3496 | // Record[16] is the address space number. | ||||
3497 | |||||
3498 | // Check whether we have enough values to read a partition name. Also make | ||||
3499 | // sure Strtab has enough values. | ||||
3500 | if (Record.size() > 18 && Strtab.data() && | ||||
3501 | Record[17] + Record[18] <= Strtab.size()) { | ||||
3502 | Func->setPartition(StringRef(Strtab.data() + Record[17], Record[18])); | ||||
3503 | } | ||||
3504 | |||||
3505 | ValueList.push_back(Func); | ||||
3506 | |||||
3507 | if (OperandInfo.PersonalityFn || OperandInfo.Prefix || OperandInfo.Prologue) | ||||
3508 | FunctionOperands.push_back(OperandInfo); | ||||
3509 | |||||
3510 | // If this is a function with a body, remember the prototype we are | ||||
3511 | // creating now, so that we can match up the body with them later. | ||||
3512 | if (!isProto) { | ||||
3513 | Func->setIsMaterializable(true); | ||||
3514 | FunctionsWithBodies.push_back(Func); | ||||
3515 | DeferredFunctionInfo[Func] = 0; | ||||
3516 | } | ||||
3517 | return Error::success(); | ||||
3518 | } | ||||
3519 | |||||
3520 | Error BitcodeReader::parseGlobalIndirectSymbolRecord( | ||||
3521 | unsigned BitCode, ArrayRef<uint64_t> Record) { | ||||
3522 | // v1 ALIAS_OLD: [alias type, aliasee val#, linkage] (name in VST) | ||||
3523 | // v1 ALIAS: [alias type, addrspace, aliasee val#, linkage, visibility, | ||||
3524 | // dllstorageclass, threadlocal, unnamed_addr, | ||||
3525 | // preemption specifier] (name in VST) | ||||
3526 | // v1 IFUNC: [alias type, addrspace, aliasee val#, linkage, | ||||
3527 | // visibility, dllstorageclass, threadlocal, unnamed_addr, | ||||
3528 | // preemption specifier] (name in VST) | ||||
3529 | // v2: [strtab_offset, strtab_size, v1] | ||||
3530 | StringRef Name; | ||||
3531 | std::tie(Name, Record) = readNameFromStrtab(Record); | ||||
3532 | |||||
3533 | bool NewRecord = BitCode != bitc::MODULE_CODE_ALIAS_OLD; | ||||
3534 | if (Record.size() < (3 + (unsigned)NewRecord)) | ||||
3535 | return error("Invalid record"); | ||||
3536 | unsigned OpNum = 0; | ||||
3537 | Type *Ty = getTypeByID(Record[OpNum++]); | ||||
3538 | if (!Ty) | ||||
3539 | return error("Invalid record"); | ||||
3540 | |||||
3541 | unsigned AddrSpace; | ||||
3542 | if (!NewRecord) { | ||||
3543 | auto *PTy = dyn_cast<PointerType>(Ty); | ||||
3544 | if (!PTy) | ||||
3545 | return error("Invalid type for value"); | ||||
3546 | Ty = PTy->getPointerElementType(); | ||||
3547 | AddrSpace = PTy->getAddressSpace(); | ||||
3548 | } else { | ||||
3549 | AddrSpace = Record[OpNum++]; | ||||
3550 | } | ||||
3551 | |||||
3552 | auto Val = Record[OpNum++]; | ||||
3553 | auto Linkage = Record[OpNum++]; | ||||
3554 | GlobalValue *NewGA; | ||||
3555 | if (BitCode == bitc::MODULE_CODE_ALIAS || | ||||
3556 | BitCode == bitc::MODULE_CODE_ALIAS_OLD) | ||||
3557 | NewGA = GlobalAlias::create(Ty, AddrSpace, getDecodedLinkage(Linkage), Name, | ||||
3558 | TheModule); | ||||
3559 | else | ||||
3560 | NewGA = GlobalIFunc::create(Ty, AddrSpace, getDecodedLinkage(Linkage), Name, | ||||
3561 | nullptr, TheModule); | ||||
3562 | |||||
3563 | // Local linkage must have default visibility. | ||||
3564 | // auto-upgrade `hidden` and `protected` for old bitcode. | ||||
3565 | if (OpNum != Record.size()) { | ||||
3566 | auto VisInd = OpNum++; | ||||
3567 | if (!NewGA->hasLocalLinkage()) | ||||
3568 | NewGA->setVisibility(getDecodedVisibility(Record[VisInd])); | ||||
3569 | } | ||||
3570 | if (BitCode == bitc::MODULE_CODE_ALIAS || | ||||
3571 | BitCode == bitc::MODULE_CODE_ALIAS_OLD) { | ||||
3572 | if (OpNum != Record.size()) | ||||
3573 | NewGA->setDLLStorageClass(getDecodedDLLStorageClass(Record[OpNum++])); | ||||
3574 | else | ||||
3575 | upgradeDLLImportExportLinkage(NewGA, Linkage); | ||||
3576 | if (OpNum != Record.size()) | ||||
3577 | NewGA->setThreadLocalMode(getDecodedThreadLocalMode(Record[OpNum++])); | ||||
3578 | if (OpNum != Record.size()) | ||||
3579 | NewGA->setUnnamedAddr(getDecodedUnnamedAddrType(Record[OpNum++])); | ||||
3580 | } | ||||
3581 | if (OpNum != Record.size()) | ||||
3582 | NewGA->setDSOLocal(getDecodedDSOLocal(Record[OpNum++])); | ||||
3583 | inferDSOLocal(NewGA); | ||||
3584 | |||||
3585 | // Check whether we have enough values to read a partition name. | ||||
3586 | if (OpNum + 1 < Record.size()) { | ||||
3587 | NewGA->setPartition( | ||||
3588 | StringRef(Strtab.data() + Record[OpNum], Record[OpNum + 1])); | ||||
3589 | OpNum += 2; | ||||
3590 | } | ||||
3591 | |||||
3592 | ValueList.push_back(NewGA); | ||||
3593 | IndirectSymbolInits.push_back(std::make_pair(NewGA, Val)); | ||||
3594 | return Error::success(); | ||||
3595 | } | ||||
3596 | |||||
3597 | Error BitcodeReader::parseModule(uint64_t ResumeBit, | ||||
3598 | bool ShouldLazyLoadMetadata, | ||||
3599 | DataLayoutCallbackTy DataLayoutCallback) { | ||||
3600 | if (ResumeBit) { | ||||
3601 | if (Error JumpFailed = Stream.JumpToBit(ResumeBit)) | ||||
3602 | return JumpFailed; | ||||
3603 | } else if (Error Err = Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID)) | ||||
3604 | return Err; | ||||
3605 | |||||
3606 | SmallVector<uint64_t, 64> Record; | ||||
3607 | |||||
3608 | // Parts of bitcode parsing depend on the datalayout. Make sure we | ||||
3609 | // finalize the datalayout before we run any of that code. | ||||
3610 | bool ResolvedDataLayout = false; | ||||
3611 | auto ResolveDataLayout = [&] { | ||||
3612 | if (ResolvedDataLayout) | ||||
3613 | return; | ||||
3614 | |||||
3615 | // datalayout and triple can't be parsed after this point. | ||||
3616 | ResolvedDataLayout = true; | ||||
3617 | |||||
3618 | // Upgrade data layout string. | ||||
3619 | std::string DL = llvm::UpgradeDataLayoutString( | ||||
3620 | TheModule->getDataLayoutStr(), TheModule->getTargetTriple()); | ||||
3621 | TheModule->setDataLayout(DL); | ||||
3622 | |||||
3623 | if (auto LayoutOverride = | ||||
3624 | DataLayoutCallback(TheModule->getTargetTriple())) | ||||
3625 | TheModule->setDataLayout(*LayoutOverride); | ||||
3626 | }; | ||||
3627 | |||||
3628 | // Read all the records for this module. | ||||
3629 | while (true) { | ||||
3630 | Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance(); | ||||
3631 | if (!MaybeEntry) | ||||
3632 | return MaybeEntry.takeError(); | ||||
3633 | llvm::BitstreamEntry Entry = MaybeEntry.get(); | ||||
3634 | |||||
3635 | switch (Entry.Kind) { | ||||
3636 | case BitstreamEntry::Error: | ||||
3637 | return error("Malformed block"); | ||||
3638 | case BitstreamEntry::EndBlock: | ||||
3639 | ResolveDataLayout(); | ||||
3640 | return globalCleanup(); | ||||
3641 | |||||
3642 | case BitstreamEntry::SubBlock: | ||||
3643 | switch (Entry.ID) { | ||||
3644 | default: // Skip unknown content. | ||||
3645 | if (Error Err = Stream.SkipBlock()) | ||||
3646 | return Err; | ||||
3647 | break; | ||||
3648 | case bitc::BLOCKINFO_BLOCK_ID: | ||||
3649 | if (Error Err = readBlockInfo()) | ||||
3650 | return Err; | ||||
3651 | break; | ||||
3652 | case bitc::PARAMATTR_BLOCK_ID: | ||||
3653 | if (Error Err = parseAttributeBlock()) | ||||
3654 | return Err; | ||||
3655 | break; | ||||
3656 | case bitc::PARAMATTR_GROUP_BLOCK_ID: | ||||
3657 | if (Error Err = parseAttributeGroupBlock()) | ||||
3658 | return Err; | ||||
3659 | break; | ||||
3660 | case bitc::TYPE_BLOCK_ID_NEW: | ||||
3661 | if (Error Err = parseTypeTable()) | ||||
3662 | return Err; | ||||
3663 | break; | ||||
3664 | case bitc::VALUE_SYMTAB_BLOCK_ID: | ||||
3665 | if (!SeenValueSymbolTable) { | ||||
3666 | // Either this is an old form VST without function index and an | ||||
3667 | // associated VST forward declaration record (which would have caused | ||||
3668 | // the VST to be jumped to and parsed before it was encountered | ||||
3669 | // normally in the stream), or there were no function blocks to | ||||
3670 | // trigger an earlier parsing of the VST. | ||||
3671 | assert(VSTOffset == 0 || FunctionsWithBodies.empty())(static_cast <bool> (VSTOffset == 0 || FunctionsWithBodies .empty()) ? void (0) : __assert_fail ("VSTOffset == 0 || FunctionsWithBodies.empty()" , "llvm/lib/Bitcode/Reader/BitcodeReader.cpp", 3671, __extension__ __PRETTY_FUNCTION__)); | ||||
3672 | if (Error Err = parseValueSymbolTable()) | ||||
3673 | return Err; | ||||
3674 | SeenValueSymbolTable = true; | ||||
3675 | } else { | ||||
3676 | // We must have had a VST forward declaration record, which caused | ||||
3677 | // the parser to jump to and parse the VST earlier. | ||||
3678 | assert(VSTOffset > 0)(static_cast <bool> (VSTOffset > 0) ? void (0) : __assert_fail ("VSTOffset > 0", "llvm/lib/Bitcode/Reader/BitcodeReader.cpp" , 3678, __extension__ __PRETTY_FUNCTION__)); | ||||
3679 | if (Error Err = Stream.SkipBlock()) | ||||
3680 | return Err; | ||||
3681 | } | ||||
3682 | break; | ||||
3683 | case bitc::CONSTANTS_BLOCK_ID: | ||||
3684 | if (Error Err = parseConstants()) | ||||
3685 | return Err; | ||||
3686 | if (Error Err = resolveGlobalAndIndirectSymbolInits()) | ||||
3687 | return Err; | ||||
3688 | break; | ||||
3689 | case bitc::METADATA_BLOCK_ID: | ||||
3690 | if (ShouldLazyLoadMetadata) { | ||||
3691 | if (Error Err = rememberAndSkipMetadata()) | ||||
3692 | return Err; | ||||
3693 | break; | ||||
3694 | } | ||||
3695 | assert(DeferredMetadataInfo.empty() && "Unexpected deferred metadata")(static_cast <bool> (DeferredMetadataInfo.empty() && "Unexpected deferred metadata") ? void (0) : __assert_fail ( "DeferredMetadataInfo.empty() && \"Unexpected deferred metadata\"" , "llvm/lib/Bitcode/Reader/BitcodeReader.cpp", 3695, __extension__ __PRETTY_FUNCTION__)); | ||||
3696 | if (Error Err = MDLoader->parseModuleMetadata()) | ||||
3697 | return Err; | ||||
3698 | break; | ||||
3699 | case bitc::METADATA_KIND_BLOCK_ID: | ||||
3700 | if (Error Err = MDLoader->parseMetadataKinds()) | ||||
3701 | return Err; | ||||
3702 | break; | ||||
3703 | case bitc::FUNCTION_BLOCK_ID: | ||||
3704 | ResolveDataLayout(); | ||||
3705 | |||||
3706 | // If this is the first function body we've seen, reverse the | ||||
3707 | // FunctionsWithBodies list. | ||||
3708 | if (!SeenFirstFunctionBody) { | ||||
3709 | std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end()); | ||||
3710 | if (Error Err = globalCleanup()) | ||||
3711 | return Err; | ||||
3712 | SeenFirstFunctionBody = true; | ||||
3713 | } | ||||
3714 | |||||
3715 | if (VSTOffset > 0) { | ||||
3716 | // If we have a VST forward declaration record, make sure we | ||||
3717 | // parse the VST now if we haven't already. It is needed to | ||||
3718 | // set up the DeferredFunctionInfo vector for lazy reading. | ||||
3719 | if (!SeenValueSymbolTable) { | ||||
3720 | if (Error Err = BitcodeReader::parseValueSymbolTable(VSTOffset)) | ||||
3721 | return Err; | ||||
3722 | SeenValueSymbolTable = true; | ||||
3723 | // Fall through so that we record the NextUnreadBit below. | ||||
3724 | // This is necessary in case we have an anonymous function that | ||||
3725 | // is later materialized. Since it will not have a VST entry we | ||||
3726 | // need to fall back to the lazy parse to find its offset. | ||||
3727 | } else { | ||||
3728 | // If we have a VST forward declaration record, but have already | ||||
3729 | // parsed the VST (just above, when the first function body was | ||||
3730 | // encountered here), then we are resuming the parse after | ||||
3731 | // materializing functions. The ResumeBit points to the | ||||
3732 | // start of the last function block recorded in the | ||||
3733 | // DeferredFunctionInfo map. Skip it. | ||||
3734 | if (Error Err = Stream.SkipBlock()) | ||||
3735 | return Err; | ||||
3736 | continue; | ||||
3737 | } | ||||
3738 | } | ||||
3739 | |||||
3740 | // Support older bitcode files that did not have the function | ||||
3741 | // index in the VST, nor a VST forward declaration record, as | ||||
3742 | // well as anonymous functions that do not have VST entries. | ||||
3743 | // Build the DeferredFunctionInfo vector on the fly. | ||||
3744 | if (Error Err = rememberAndSkipFunctionBody()) | ||||
3745 | return Err; | ||||
3746 | |||||
3747 | // Suspend parsing when we reach the function bodies. Subsequent | ||||
3748 | // materialization calls will resume it when necessary. If the bitcode | ||||
3749 | // file is old, the symbol table will be at the end instead and will not | ||||
3750 | // have been seen yet. In this case, just finish the parse now. | ||||
3751 | if (SeenValueSymbolTable) { | ||||
3752 | NextUnreadBit = Stream.GetCurrentBitNo(); | ||||
3753 | // After the VST has been parsed, we need to make sure intrinsic name | ||||
3754 | // are auto-upgraded. | ||||
3755 | return globalCleanup(); | ||||
3756 | } | ||||
3757 | break; | ||||
3758 | case bitc::USELIST_BLOCK_ID: | ||||
3759 | if (Error Err = parseUseLists()) | ||||
3760 | return Err; | ||||
3761 | break; | ||||
3762 | case bitc::OPERAND_BUNDLE_TAGS_BLOCK_ID: | ||||
3763 | if (Error Err = parseOperandBundleTags()) | ||||
3764 | return Err; | ||||
3765 | break; | ||||
3766 | case bitc::SYNC_SCOPE_NAMES_BLOCK_ID: | ||||
3767 | if (Error Err = parseSyncScopeNames()) | ||||
3768 | return Err; | ||||
3769 | break; | ||||
3770 | } | ||||
3771 | continue; | ||||
3772 | |||||
3773 | case BitstreamEntry::Record: | ||||
3774 | // The interesting case. | ||||
3775 | break; | ||||
3776 | } | ||||
3777 | |||||
3778 | // Read a record. | ||||
3779 | Expected<unsigned> MaybeBitCode = Stream.readRecord(Entry.ID, Record); | ||||
3780 | if (!MaybeBitCode) | ||||
3781 | return MaybeBitCode.takeError(); | ||||
3782 | switch (unsigned BitCode = MaybeBitCode.get()) { | ||||
3783 | default: break; // Default behavior, ignore unknown content. | ||||
3784 | case bitc::MODULE_CODE_VERSION: { | ||||
3785 | Expected<unsigned> VersionOrErr = parseVersionRecord(Record); | ||||
3786 | if (!VersionOrErr) | ||||
3787 | return VersionOrErr.takeError(); | ||||
3788 | UseRelativeIDs = *VersionOrErr >= 1; | ||||
3789 | break; | ||||
3790 | } | ||||
3791 | case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N] | ||||
3792 | if (ResolvedDataLayout) | ||||
3793 | return error("target triple too late in module"); | ||||
3794 | std::string S; | ||||
3795 | if (convertToString(Record, 0, S)) | ||||
3796 | return error("Invalid record"); | ||||
3797 | TheModule->setTargetTriple(S); | ||||
3798 | break; | ||||
3799 | } | ||||
3800 | case bitc::MODULE_CODE_DATALAYOUT: { // DATALAYOUT: [strchr x N] | ||||
3801 | if (ResolvedDataLayout) | ||||
3802 | return error("datalayout too late in module"); | ||||
3803 | std::string S; | ||||
3804 | if (convertToString(Record, 0, S)) | ||||
3805 | return error("Invalid record"); | ||||
3806 | Expected<DataLayout> MaybeDL = DataLayout::parse(S); | ||||
3807 | if (!MaybeDL) | ||||
3808 | return MaybeDL.takeError(); | ||||
3809 | TheModule->setDataLayout(MaybeDL.get()); | ||||
3810 | break; | ||||
3811 | } | ||||
3812 | case bitc::MODULE_CODE_ASM: { // ASM: [strchr x N] | ||||
3813 | std::string S; | ||||
3814 | if (convertToString(Record, 0, S)) | ||||
3815 | return error("Invalid record"); | ||||
3816 | TheModule->setModuleInlineAsm(S); | ||||
3817 | break; | ||||
3818 | } | ||||
3819 | case bitc::MODULE_CODE_DEPLIB: { // DEPLIB: [strchr x N] | ||||
3820 | // Deprecated, but still needed to read old bitcode files. | ||||
3821 | std::string S; | ||||
3822 | if (convertToString(Record, 0, S)) | ||||
3823 | return error("Invalid record"); | ||||
3824 | // Ignore value. | ||||
3825 | break; | ||||
3826 | } | ||||
3827 | case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N] | ||||
3828 | std::string S; | ||||
3829 | if (convertToString(Record, 0, S)) | ||||
3830 | return error("Invalid record"); | ||||
3831 | SectionTable.push_back(S); | ||||
3832 | break; | ||||
3833 | } | ||||
3834 | case bitc::MODULE_CODE_GCNAME: { // SECTIONNAME: [strchr x N] | ||||
3835 | std::string S; | ||||
3836 | if (convertToString(Record, 0, S)) | ||||
3837 | return error("Invalid record"); | ||||
3838 | GCTable.push_back(S); | ||||
3839 | break; | ||||
3840 | } | ||||
3841 | case bitc::MODULE_CODE_COMDAT: | ||||
3842 | if (Error Err = parseComdatRecord(Record)) | ||||
3843 | return Err; | ||||
3844 | break; | ||||
3845 | // FIXME: BitcodeReader should handle {GLOBALVAR, FUNCTION, ALIAS, IFUNC} | ||||
3846 | // written by ThinLinkBitcodeWriter. See | ||||
3847 | // `ThinLinkBitcodeWriter::writeSimplifiedModuleInfo` for the format of each | ||||
3848 | // record | ||||
3849 | // (https://github.com/llvm/llvm-project/blob/b6a93967d9c11e79802b5e75cec1584d6c8aa472/llvm/lib/Bitcode/Writer/BitcodeWriter.cpp#L4714) | ||||
3850 | case bitc::MODULE_CODE_GLOBALVAR: | ||||
3851 | if (Error Err = parseGlobalVarRecord(Record)) | ||||
3852 | return Err; | ||||
3853 | break; | ||||
3854 | case bitc::MODULE_CODE_FUNCTION: | ||||
3855 | ResolveDataLayout(); | ||||
3856 | if (Error Err = parseFunctionRecord(Record)) | ||||
3857 | return Err; | ||||
3858 | break; | ||||
3859 | case bitc::MODULE_CODE_IFUNC: | ||||
3860 | case bitc::MODULE_CODE_ALIAS: | ||||
3861 | case bitc::MODULE_CODE_ALIAS_OLD: | ||||
3862 | if (Error Err = parseGlobalIndirectSymbolRecord(BitCode, Record)) | ||||
3863 | return Err; | ||||
3864 | break; | ||||
3865 | /// MODULE_CODE_VSTOFFSET: [offset] | ||||
3866 | case bitc::MODULE_CODE_VSTOFFSET: | ||||
3867 | if (Record.empty()) | ||||
3868 | return error("Invalid record"); | ||||
3869 | // Note that we subtract 1 here because the offset is relative to one word | ||||
3870 | // before the start of the identification or module block, which was | ||||
3871 | // historically always the start of the regular bitcode header. | ||||
3872 | VSTOffset = Record[0] - 1; | ||||
3873 | break; | ||||
3874 | /// MODULE_CODE_SOURCE_FILENAME: [namechar x N] | ||||
3875 | case bitc::MODULE_CODE_SOURCE_FILENAME: | ||||
3876 | SmallString<128> ValueName; | ||||
3877 | if (convertToString(Record, 0, ValueName)) | ||||
3878 | return error("Invalid record"); | ||||
3879 | TheModule->setSourceFileName(ValueName); | ||||
3880 | break; | ||||
3881 | } | ||||
3882 | Record.clear(); | ||||
3883 | } | ||||
3884 | } | ||||
3885 | |||||
3886 | Error BitcodeReader::parseBitcodeInto(Module *M, bool ShouldLazyLoadMetadata, | ||||
3887 | bool IsImporting, | ||||
3888 | DataLayoutCallbackTy DataLayoutCallback) { | ||||
3889 | TheModule = M; | ||||
3890 | MDLoader = MetadataLoader(Stream, *M, ValueList, IsImporting, | ||||
3891 | [&](unsigned ID) { return getTypeByID(ID); }); | ||||
3892 | return parseModule(0, ShouldLazyLoadMetadata, DataLayoutCallback); | ||||
3893 | } | ||||
3894 | |||||
3895 | Error BitcodeReader::typeCheckLoadStoreInst(Type *ValType, Type *PtrType) { | ||||
3896 | if (!isa<PointerType>(PtrType)) | ||||
3897 | return error("Load/Store operand is not a pointer type"); | ||||
3898 | |||||
3899 | if (!cast<PointerType>(PtrType)->isOpaqueOrPointeeTypeMatches(ValType)) | ||||
3900 | return error("Explicit load/store type does not match pointee " | ||||
3901 | "type of pointer operand"); | ||||
3902 | if (!PointerType::isLoadableOrStorableType(ValType)) | ||||
3903 | return error("Cannot load/store from pointer"); | ||||
3904 | return Error::success(); | ||||
3905 | } | ||||
3906 | |||||
3907 | void BitcodeReader::propagateAttributeTypes(CallBase *CB, | ||||
3908 | ArrayRef<Type *> ArgsTys) { | ||||
3909 | for (unsigned i = 0; i != CB->arg_size(); ++i) { | ||||
3910 | for (Attribute::AttrKind Kind : {Attribute::ByVal, Attribute::StructRet, | ||||
3911 | Attribute::InAlloca}) { | ||||
3912 | if (!CB->paramHasAttr(i, Kind) || | ||||
3913 | CB->getParamAttr(i, Kind).getValueAsType()) | ||||
3914 | continue; | ||||
3915 | |||||
3916 | CB->removeParamAttr(i, Kind); | ||||
3917 | |||||
3918 | Type *PtrEltTy = ArgsTys[i]->getPointerElementType(); | ||||
3919 | Attribute NewAttr; | ||||
3920 | switch (Kind) { | ||||
3921 | case Attribute::ByVal: | ||||
3922 | NewAttr = Attribute::getWithByValType(Context, PtrEltTy); | ||||
3923 | break; | ||||
3924 | case Attribute::StructRet: | ||||
3925 | NewAttr = Attribute::getWithStructRetType(Context, PtrEltTy); | ||||
3926 | break; | ||||
3927 | case Attribute::InAlloca: | ||||
3928 | NewAttr = Attribute::getWithInAllocaType(Context, PtrEltTy); | ||||
3929 | break; | ||||
3930 | default: | ||||
3931 | llvm_unreachable("not an upgraded type attribute")::llvm::llvm_unreachable_internal("not an upgraded type attribute" , "llvm/lib/Bitcode/Reader/BitcodeReader.cpp", 3931); | ||||
3932 | } | ||||
3933 | |||||
3934 | CB->addParamAttr(i, NewAttr); | ||||
3935 | } | ||||
3936 | } | ||||
3937 | |||||
3938 | if (CB->isInlineAsm()) { | ||||
3939 | const InlineAsm *IA = cast<InlineAsm>(CB->getCalledOperand()); | ||||
3940 | unsigned ArgNo = 0; | ||||
3941 | for (const InlineAsm::ConstraintInfo &CI : IA->ParseConstraints()) { | ||||
3942 | if (!CI.hasArg()) | ||||
3943 | continue; | ||||
3944 | |||||
3945 | if (CI.isIndirect && !CB->getAttributes().getParamElementType(ArgNo)) { | ||||
3946 | Type *ElemTy = ArgsTys[ArgNo]->getPointerElementType(); | ||||
3947 | CB->addParamAttr( | ||||
3948 | ArgNo, Attribute::get(Context, Attribute::ElementType, ElemTy)); | ||||
3949 | } | ||||
3950 | |||||
3951 | ArgNo++; | ||||
3952 | } | ||||
3953 | } | ||||
3954 | |||||
3955 | switch (CB->getIntrinsicID()) { | ||||
3956 | case Intrinsic::preserve_array_access_index: | ||||
3957 | case Intrinsic::preserve_struct_access_index: | ||||
3958 | if (!CB->getAttributes().getParamElementType(0)) { | ||||
3959 | Type *ElTy = ArgsTys[0]->getPointerElementType(); | ||||
3960 | Attribute NewAttr = Attribute::get(Context, Attribute::ElementType, ElTy); | ||||
3961 | CB->addParamAttr(0, NewAttr); | ||||
3962 | } | ||||
3963 | break; | ||||
3964 | default: | ||||
3965 | break; | ||||
3966 | } | ||||
3967 | } | ||||
3968 | |||||
3969 | /// Lazily parse the specified function body block. | ||||
3970 | Error BitcodeReader::parseFunctionBody(Function *F) { | ||||
3971 | if (Error Err = Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID)) | ||||
3972 | return Err; | ||||
3973 | |||||
3974 | // Unexpected unresolved metadata when parsing function. | ||||
3975 | if (MDLoader->hasFwdRefs()) | ||||
3976 | return error("Invalid function metadata: incoming forward references"); | ||||
3977 | |||||
3978 | InstructionList.clear(); | ||||
3979 | unsigned ModuleValueListSize = ValueList.size(); | ||||
3980 | unsigned ModuleMDLoaderSize = MDLoader->size(); | ||||
3981 | |||||
3982 | // Add all the function arguments to the value table. | ||||
3983 | #ifndef NDEBUG | ||||
3984 | unsigned ArgNo = 0; | ||||
3985 | FunctionType *FTy = FunctionTypes[F]; | ||||
3986 | #endif | ||||
3987 | for (Argument &I : F->args()) { | ||||
3988 | assert(I.getType() == FTy->getParamType(ArgNo++) &&(static_cast <bool> (I.getType() == FTy->getParamType (ArgNo++) && "Incorrect fully specified type for Function Argument" ) ? void (0) : __assert_fail ("I.getType() == FTy->getParamType(ArgNo++) && \"Incorrect fully specified type for Function Argument\"" , "llvm/lib/Bitcode/Reader/BitcodeReader.cpp", 3989, __extension__ __PRETTY_FUNCTION__)) | ||||
3989 | "Incorrect fully specified type for Function Argument")(static_cast <bool> (I.getType() == FTy->getParamType (ArgNo++) && "Incorrect fully specified type for Function Argument" ) ? void (0) : __assert_fail ("I.getType() == FTy->getParamType(ArgNo++) && \"Incorrect fully specified type for Function Argument\"" , "llvm/lib/Bitcode/Reader/BitcodeReader.cpp", 3989, __extension__ __PRETTY_FUNCTION__)); | ||||
3990 | ValueList.push_back(&I); | ||||
3991 | } | ||||
3992 | unsigned NextValueNo = ValueList.size(); | ||||
3993 | BasicBlock *CurBB = nullptr; | ||||
3994 | unsigned CurBBNo = 0; | ||||
3995 | |||||
3996 | DebugLoc LastLoc; | ||||
3997 | auto getLastInstruction = [&]() -> Instruction * { | ||||
3998 | if (CurBB && !CurBB->empty()) | ||||
3999 | return &CurBB->back(); | ||||
4000 | else if (CurBBNo && FunctionBBs[CurBBNo - 1] && | ||||
4001 | !FunctionBBs[CurBBNo - 1]->empty()) | ||||
4002 | return &FunctionBBs[CurBBNo - 1]->back(); | ||||
4003 | return nullptr; | ||||
4004 | }; | ||||
4005 | |||||
4006 | std::vector<OperandBundleDef> OperandBundles; | ||||
4007 | |||||
4008 | // Read all the records. | ||||
4009 | SmallVector<uint64_t, 64> Record; | ||||
4010 | |||||
4011 | while (true) { | ||||
4012 | Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance(); | ||||
4013 | if (!MaybeEntry) | ||||
4014 | return MaybeEntry.takeError(); | ||||
4015 | llvm::BitstreamEntry Entry = MaybeEntry.get(); | ||||
4016 | |||||
4017 | switch (Entry.Kind) { | ||||
4018 | case BitstreamEntry::Error: | ||||
4019 | return error("Malformed block"); | ||||
4020 | case BitstreamEntry::EndBlock: | ||||
4021 | goto OutOfRecordLoop; | ||||
4022 | |||||
4023 | case BitstreamEntry::SubBlock: | ||||
4024 | switch (Entry.ID) { | ||||
4025 | default: // Skip unknown content. | ||||
4026 | if (Error Err = Stream.SkipBlock()) | ||||
4027 | return Err; | ||||
4028 | break; | ||||
4029 | case bitc::CONSTANTS_BLOCK_ID: | ||||
4030 | if (Error Err = parseConstants()) | ||||
4031 | return Err; | ||||
4032 | NextValueNo = ValueList.size(); | ||||
4033 | break; | ||||
4034 | case bitc::VALUE_SYMTAB_BLOCK_ID: | ||||
4035 | if (Error Err = parseValueSymbolTable()) | ||||
4036 | return Err; | ||||
4037 | break; | ||||
4038 | case bitc::METADATA_ATTACHMENT_ID: | ||||
4039 | if (Error Err = MDLoader->parseMetadataAttachment(*F, InstructionList)) | ||||
4040 | return Err; | ||||
4041 | break; | ||||
4042 | case bitc::METADATA_BLOCK_ID: | ||||
4043 | assert(DeferredMetadataInfo.empty() &&(static_cast <bool> (DeferredMetadataInfo.empty() && "Must read all module-level metadata before function-level") ? void (0) : __assert_fail ("DeferredMetadataInfo.empty() && \"Must read all module-level metadata before function-level\"" , "llvm/lib/Bitcode/Reader/BitcodeReader.cpp", 4044, __extension__ __PRETTY_FUNCTION__)) | ||||
4044 | "Must read all module-level metadata before function-level")(static_cast <bool> (DeferredMetadataInfo.empty() && "Must read all module-level metadata before function-level") ? void (0) : __assert_fail ("DeferredMetadataInfo.empty() && \"Must read all module-level metadata before function-level\"" , "llvm/lib/Bitcode/Reader/BitcodeReader.cpp", 4044, __extension__ __PRETTY_FUNCTION__)); | ||||
4045 | if (Error Err = MDLoader->parseFunctionMetadata()) | ||||
4046 | return Err; | ||||
4047 | break; | ||||
4048 | case bitc::USELIST_BLOCK_ID: | ||||
4049 | if (Error Err = parseUseLists()) | ||||
4050 | return Err; | ||||
4051 | break; | ||||
4052 | } | ||||
4053 | continue; | ||||
4054 | |||||
4055 | case BitstreamEntry::Record: | ||||
4056 | // The interesting case. | ||||
4057 | break; | ||||
4058 | } | ||||
4059 | |||||
4060 | // Read a record. | ||||
4061 | Record.clear(); | ||||
4062 | Instruction *I = nullptr; | ||||
4063 | Expected<unsigned> MaybeBitCode = Stream.readRecord(Entry.ID, Record); | ||||
4064 | if (!MaybeBitCode) | ||||
4065 | return MaybeBitCode.takeError(); | ||||
4066 | switch (unsigned BitCode = MaybeBitCode.get()) { | ||||
4067 | default: // Default behavior: reject | ||||
4068 | return error("Invalid value"); | ||||
4069 | case bitc::FUNC_CODE_DECLAREBLOCKS: { // DECLAREBLOCKS: [nblocks] | ||||
4070 | if (Record.empty() || Record[0] == 0) | ||||
4071 | return error("Invalid record"); | ||||
4072 | // Create all the basic blocks for the function. | ||||
4073 | FunctionBBs.resize(Record[0]); | ||||
4074 | |||||
4075 | // See if anything took the address of blocks in this function. | ||||
4076 | auto BBFRI = BasicBlockFwdRefs.find(F); | ||||
4077 | if (BBFRI == BasicBlockFwdRefs.end()) { | ||||
4078 | for (BasicBlock *&BB : FunctionBBs) | ||||
4079 | BB = BasicBlock::Create(Context, "", F); | ||||
4080 | } else { | ||||
4081 | auto &BBRefs = BBFRI->second; | ||||
4082 | // Check for invalid basic block references. | ||||
4083 | if (BBRefs.size() > FunctionBBs.size()) | ||||
4084 | return error("Invalid ID"); | ||||
4085 | assert(!BBRefs.empty() && "Unexpected empty array")(static_cast <bool> (!BBRefs.empty() && "Unexpected empty array" ) ? void (0) : __assert_fail ("!BBRefs.empty() && \"Unexpected empty array\"" , "llvm/lib/Bitcode/Reader/BitcodeReader.cpp", 4085, __extension__ __PRETTY_FUNCTION__)); | ||||
4086 | assert(!BBRefs.front() && "Invalid reference to entry block")(static_cast <bool> (!BBRefs.front() && "Invalid reference to entry block" ) ? void (0) : __assert_fail ("!BBRefs.front() && \"Invalid reference to entry block\"" , "llvm/lib/Bitcode/Reader/BitcodeReader.cpp", 4086, __extension__ __PRETTY_FUNCTION__)); | ||||
4087 | for (unsigned I = 0, E = FunctionBBs.size(), RE = BBRefs.size(); I != E; | ||||
4088 | ++I) | ||||
4089 | if (I < RE && BBRefs[I]) { | ||||
4090 | BBRefs[I]->insertInto(F); | ||||
4091 | FunctionBBs[I] = BBRefs[I]; | ||||
4092 | } else { | ||||
4093 | FunctionBBs[I] = BasicBlock::Create(Context, "", F); | ||||
4094 | } | ||||
4095 | |||||
4096 | // Erase from the table. | ||||
4097 | BasicBlockFwdRefs.erase(BBFRI); | ||||
4098 | } | ||||
4099 | |||||
4100 | CurBB = FunctionBBs[0]; | ||||
4101 | continue; | ||||
4102 | } | ||||
4103 | |||||
4104 | case bitc::FUNC_CODE_DEBUG_LOC_AGAIN: // DEBUG_LOC_AGAIN | ||||
4105 | // This record indicates that the last instruction is at the same | ||||
4106 | // location as the previous instruction with a location. | ||||
4107 | I = getLastInstruction(); | ||||
4108 | |||||
4109 | if (!I) | ||||
4110 | return error("Invalid record"); | ||||
4111 | I->setDebugLoc(LastLoc); | ||||
4112 | I = nullptr; | ||||
4113 | continue; | ||||
4114 | |||||
4115 | case bitc::FUNC_CODE_DEBUG_LOC: { // DEBUG_LOC: [line, col, scope, ia] | ||||
4116 | I = getLastInstruction(); | ||||
4117 | if (!I || Record.size() < 4) | ||||
4118 | return error("Invalid record"); | ||||
4119 | |||||
4120 | unsigned Line = Record[0], Col = Record[1]; | ||||
4121 | unsigned ScopeID = Record[2], IAID = Record[3]; | ||||
4122 | bool isImplicitCode = Record.size() == 5 && Record[4]; | ||||
4123 | |||||
4124 | MDNode *Scope = nullptr, *IA = nullptr; | ||||
4125 | if (ScopeID) { | ||||
4126 | Scope = dyn_cast_or_null<MDNode>( | ||||
4127 | MDLoader->getMetadataFwdRefOrLoad(ScopeID - 1)); | ||||
4128 | if (!Scope) | ||||
4129 | return error("Invalid record"); | ||||
4130 | } | ||||
4131 | if (IAID) { | ||||
4132 | IA = dyn_cast_or_null<MDNode>( | ||||
4133 | MDLoader->getMetadataFwdRefOrLoad(IAID - 1)); | ||||
4134 | if (!IA) | ||||
4135 | return error("Invalid record"); | ||||
4136 | } | ||||
4137 | LastLoc = DILocation::get(Scope->getContext(), Line, Col, Scope, IA, | ||||
4138 | isImplicitCode); | ||||
4139 | I->setDebugLoc(LastLoc); | ||||
4140 | I = nullptr; | ||||
4141 | continue; | ||||
4142 | } | ||||
4143 | case bitc::FUNC_CODE_INST_UNOP: { // UNOP: [opval, ty, opcode] | ||||
4144 | unsigned OpNum = 0; | ||||
4145 | Value *LHS; | ||||
4146 | if (getValueTypePair(Record, OpNum, NextValueNo, LHS) || | ||||
4147 | OpNum+1 > Record.size()) | ||||
4148 | return error("Invalid record"); | ||||
4149 | |||||
4150 | int Opc = getDecodedUnaryOpcode(Record[OpNum++], LHS->getType()); | ||||
4151 | if (Opc == -1) | ||||
4152 | return error("Invalid record"); | ||||
4153 | I = UnaryOperator::Create((Instruction::UnaryOps)Opc, LHS); | ||||
4154 | InstructionList.push_back(I); | ||||
4155 | if (OpNum < Record.size()) { | ||||
4156 | if (isa<FPMathOperator>(I)) { | ||||
4157 | FastMathFlags FMF = getDecodedFastMathFlags(Record[OpNum]); | ||||
4158 | if (FMF.any()) | ||||
4159 | I->setFastMathFlags(FMF); | ||||
4160 | } | ||||
4161 | } | ||||
4162 | break; | ||||
4163 | } | ||||
4164 | case bitc::FUNC_CODE_INST_BINOP: { // BINOP: [opval, ty, opval, opcode] | ||||
4165 | unsigned OpNum = 0; | ||||
4166 | Value *LHS, *RHS; | ||||
4167 | if (getValueTypePair(Record, OpNum, NextValueNo, LHS) || | ||||
4168 | popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) || | ||||
4169 | OpNum+1 > Record.size()) | ||||
4170 | return error("Invalid record"); | ||||
4171 | |||||
4172 | int Opc = getDecodedBinaryOpcode(Record[OpNum++], LHS->getType()); | ||||
4173 | if (Opc == -1) | ||||
4174 | return error("Invalid record"); | ||||
4175 | I = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS); | ||||
4176 | InstructionList.push_back(I); | ||||
4177 | if (OpNum < Record.size()) { | ||||
4178 | if (Opc == Instruction::Add || | ||||
4179 | Opc == Instruction::Sub || | ||||
4180 | Opc == Instruction::Mul || | ||||
4181 | Opc == Instruction::Shl) { | ||||
4182 | if (Record[OpNum] & (1 << bitc::OBO_NO_SIGNED_WRAP)) | ||||
4183 | cast<BinaryOperator>(I)->setHasNoSignedWrap(true); | ||||
4184 | if (Record[OpNum] & (1 << bitc::OBO_NO_UNSIGNED_WRAP)) | ||||
4185 | cast<BinaryOperator>(I)->setHasNoUnsignedWrap(true); | ||||
4186 | } else if (Opc == Instruction::SDiv || | ||||
4187 | Opc == Instruction::UDiv || | ||||
4188 | Opc == Instruction::LShr || | ||||
4189 | Opc == Instruction::AShr) { | ||||
4190 | if (Record[OpNum] & (1 << bitc::PEO_EXACT)) | ||||
4191 | cast<BinaryOperator>(I)->setIsExact(true); | ||||
4192 | } else if (isa<FPMathOperator>(I)) { | ||||
4193 | FastMathFlags FMF = getDecodedFastMathFlags(Record[OpNum]); | ||||
4194 | if (FMF.any()) | ||||
4195 | I->setFastMathFlags(FMF); | ||||
4196 | } | ||||
4197 | |||||
4198 | } | ||||
4199 | break; | ||||
4200 | } | ||||
4201 | case bitc::FUNC_CODE_INST_CAST: { // CAST: [opval, opty, destty, castopc] | ||||
4202 | unsigned OpNum = 0; | ||||
4203 | Value *Op; | ||||
4204 | if (getValueTypePair(Record, OpNum, NextValueNo, Op) || | ||||
4205 | OpNum+2 != Record.size()) | ||||
4206 | return error("Invalid record"); | ||||
4207 | |||||
4208 | Type *ResTy = getTypeByID(Record[OpNum]); | ||||
4209 | int Opc = getDecodedCastOpcode(Record[OpNum + 1]); | ||||
4210 | if (Opc == -1 || !ResTy) | ||||
4211 | return error("Invalid record"); | ||||
4212 | Instruction *Temp = nullptr; | ||||
4213 | if ((I = UpgradeBitCastInst(Opc, Op, ResTy, Temp))) { | ||||
4214 | if (Temp) { | ||||
4215 | InstructionList.push_back(Temp); | ||||
4216 | assert(CurBB && "No current BB?")(static_cast <bool> (CurBB && "No current BB?") ? void (0) : __assert_fail ("CurBB && \"No current BB?\"" , "llvm/lib/Bitcode/Reader/BitcodeReader.cpp", 4216, __extension__ __PRETTY_FUNCTION__)); | ||||
4217 | CurBB->getInstList().push_back(Temp); | ||||
4218 | } | ||||
4219 | } else { | ||||
4220 | auto CastOp = (Instruction::CastOps)Opc; | ||||
4221 | if (!CastInst::castIsValid(CastOp, Op, ResTy)) | ||||
4222 | return error("Invalid cast"); | ||||
4223 | I = CastInst::Create(CastOp, Op, ResTy); | ||||
4224 | } | ||||
4225 | InstructionList.push_back(I); | ||||
4226 | break; | ||||
4227 | } | ||||
4228 | case bitc::FUNC_CODE_INST_INBOUNDS_GEP_OLD: | ||||
4229 | case bitc::FUNC_CODE_INST_GEP_OLD: | ||||
4230 | case bitc::FUNC_CODE_INST_GEP: { // GEP: type, [n x operands] | ||||
4231 | unsigned OpNum = 0; | ||||
4232 | |||||
4233 | Type *Ty; | ||||
4234 | bool InBounds; | ||||
4235 | |||||
4236 | if (BitCode == bitc::FUNC_CODE_INST_GEP) { | ||||
4237 | InBounds = Record[OpNum++]; | ||||
4238 | Ty = getTypeByID(Record[OpNum++]); | ||||
4239 | } else { | ||||
4240 | InBounds = BitCode == bitc::FUNC_CODE_INST_INBOUNDS_GEP_OLD; | ||||
4241 | Ty = nullptr; | ||||
4242 | } | ||||
4243 | |||||
4244 | Value *BasePtr; | ||||
4245 | if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr)) | ||||
4246 | return error("Invalid record"); | ||||
4247 | |||||
4248 | if (!Ty) { | ||||
4249 | Ty = BasePtr->getType()->getScalarType()->getPointerElementType(); | ||||
4250 | } else if (!cast<PointerType>(BasePtr->getType()->getScalarType()) | ||||
4251 | ->isOpaqueOrPointeeTypeMatches(Ty)) { | ||||
4252 | return error( | ||||
4253 | "Explicit gep type does not match pointee type of pointer operand"); | ||||
4254 | } | ||||
4255 | |||||
4256 | SmallVector<Value*, 16> GEPIdx; | ||||
4257 | while (OpNum != Record.size()) { | ||||
4258 | Value *Op; | ||||
4259 | if (getValueTypePair(Record, OpNum, NextValueNo, Op)) | ||||
4260 | return error("Invalid record"); | ||||
4261 | GEPIdx.push_back(Op); | ||||
4262 | } | ||||
4263 | |||||
4264 | I = GetElementPtrInst::Create(Ty, BasePtr, GEPIdx); | ||||
4265 | |||||
4266 | InstructionList.push_back(I); | ||||
4267 | if (InBounds) | ||||
4268 | cast<GetElementPtrInst>(I)->setIsInBounds(true); | ||||
4269 | break; | ||||
4270 | } | ||||
4271 | |||||
4272 | case bitc::FUNC_CODE_INST_EXTRACTVAL: { | ||||
4273 | // EXTRACTVAL: [opty, opval, n x indices] | ||||
4274 | unsigned OpNum = 0; | ||||
4275 | Value *Agg; | ||||
4276 | if (getValueTypePair(Record, OpNum, NextValueNo, Agg)) | ||||
4277 | return error("Invalid record"); | ||||
4278 | Type *Ty = Agg->getType(); | ||||
4279 | |||||
4280 | unsigned RecSize = Record.size(); | ||||
4281 | if (OpNum == RecSize) | ||||
4282 | return error("EXTRACTVAL: Invalid instruction with 0 indices"); | ||||
4283 | |||||
4284 | SmallVector<unsigned, 4> EXTRACTVALIdx; | ||||
4285 | for (; OpNum != RecSize; ++OpNum) { | ||||
4286 | bool IsArray = Ty->isArrayTy(); | ||||
4287 | bool IsStruct = Ty->isStructTy(); | ||||
4288 | uint64_t Index = Record[OpNum]; | ||||
4289 | |||||
4290 | if (!IsStruct && !IsArray) | ||||
4291 | return error("EXTRACTVAL: Invalid type"); | ||||
4292 | if ((unsigned)Index != Index) | ||||
4293 | return error("Invalid value"); | ||||
4294 | if (IsStruct && Index >= Ty->getStructNumElements()) | ||||
4295 | return error("EXTRACTVAL: Invalid struct index"); | ||||
4296 | if (IsArray && Index >= Ty->getArrayNumElements()) | ||||
4297 | return error("EXTRACTVAL: Invalid array index"); | ||||
4298 | EXTRACTVALIdx.push_back((unsigned)Index); | ||||
4299 | |||||
4300 | if (IsStruct) | ||||
4301 | Ty = Ty->getStructElementType(Index); | ||||
4302 | else | ||||
4303 | Ty = Ty->getArrayElementType(); | ||||
4304 | } | ||||
4305 | |||||
4306 | I = ExtractValueInst::Create(Agg, EXTRACTVALIdx); | ||||
4307 | InstructionList.push_back(I); | ||||
4308 | break; | ||||
4309 | } | ||||
4310 | |||||
4311 | case bitc::FUNC_CODE_INST_INSERTVAL: { | ||||
4312 | // INSERTVAL: [opty, opval, opty, opval, n x indices] | ||||
4313 | unsigned OpNum = 0; | ||||
4314 | Value *Agg; | ||||
4315 | if (getValueTypePair(Record, OpNum, NextValueNo, Agg)) | ||||
4316 | return error("Invalid record"); | ||||
4317 | Value *Val; | ||||
4318 | if (getValueTypePair(Record, OpNum, NextValueNo, Val)) | ||||
4319 | return error("Invalid record"); | ||||
4320 | |||||
4321 | unsigned RecSize = Record.size(); | ||||
4322 | if (OpNum == RecSize) | ||||
4323 | return error("INSERTVAL: Invalid instruction with 0 indices"); | ||||
4324 | |||||
4325 | SmallVector<unsigned, 4> INSERTVALIdx; | ||||
4326 | Type *CurTy = Agg->getType(); | ||||
4327 | for (; OpNum != RecSize; ++OpNum) { | ||||
4328 | bool IsArray = CurTy->isArrayTy(); | ||||
4329 | bool IsStruct = CurTy->isStructTy(); | ||||
4330 | uint64_t Index = Record[OpNum]; | ||||
4331 | |||||
4332 | if (!IsStruct && !IsArray) | ||||
4333 | return error("INSERTVAL: Invalid type"); | ||||
4334 | if ((unsigned)Index != Index) | ||||
4335 | return error("Invalid value"); | ||||
4336 | if (IsStruct && Index >= CurTy->getStructNumElements()) | ||||
4337 | return error("INSERTVAL: Invalid struct index"); | ||||
4338 | if (IsArray && Index >= CurTy->getArrayNumElements()) | ||||
4339 | return error("INSERTVAL: Invalid array index"); | ||||
4340 | |||||
4341 | INSERTVALIdx.push_back((unsigned)Index); | ||||
4342 | if (IsStruct) | ||||
4343 | CurTy = CurTy->getStructElementType(Index); | ||||
4344 | else | ||||
4345 | CurTy = CurTy->getArrayElementType(); | ||||
4346 | } | ||||
4347 | |||||
4348 | if (CurTy != Val->getType()) | ||||
4349 | return error("Inserted value type doesn't match aggregate type"); | ||||
4350 | |||||
4351 | I = InsertValueInst::Create(Agg, Val, INSERTVALIdx); | ||||
4352 | InstructionList.push_back(I); | ||||
4353 | break; | ||||
4354 | } | ||||
4355 | |||||
4356 | case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval] | ||||
4357 | // obsolete form of select | ||||
4358 | // handles select i1 ... in old bitcode | ||||
4359 | unsigned OpNum = 0; | ||||
4360 | Value *TrueVal, *FalseVal, *Cond; | ||||
4361 | if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) || | ||||
4362 | popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) || | ||||
4363 | popValue(Record, OpNum, NextValueNo, Type::getInt1Ty(Context), Cond)) | ||||
4364 | return error("Invalid record"); | ||||
4365 | |||||
4366 | I = SelectInst::Create(Cond, TrueVal, FalseVal); | ||||
4367 | InstructionList.push_back(I); | ||||
4368 | break; | ||||
4369 | } | ||||
4370 | |||||
4371 | case bitc::FUNC_CODE_INST_VSELECT: {// VSELECT: [ty,opval,opval,predty,pred] | ||||
4372 | // new form of select | ||||
4373 | // handles select i1 or select [N x i1] | ||||
4374 | unsigned OpNum = 0; | ||||
4375 | Value *TrueVal, *FalseVal, *Cond; | ||||
4376 | if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) || | ||||
4377 | popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) || | ||||
4378 | getValueTypePair(Record, OpNum, NextValueNo, Cond)) | ||||
4379 | return error("Invalid record"); | ||||
4380 | |||||
4381 | // select condition can be either i1 or [N x i1] | ||||
4382 | if (VectorType* vector_type = | ||||
4383 | dyn_cast<VectorType>(Cond->getType())) { | ||||
4384 | // expect <n x i1> | ||||
4385 | if (vector_type->getElementType() != Type::getInt1Ty(Context)) | ||||
4386 | return error("Invalid type for value"); | ||||
4387 | } else { | ||||
4388 | // expect i1 | ||||
4389 | if (Cond->getType() != Type::getInt1Ty(Context)) | ||||
4390 | return error("Invalid type for value"); | ||||
4391 | } | ||||
4392 | |||||
4393 | I = SelectInst::Create(Cond, TrueVal, FalseVal); | ||||
4394 | InstructionList.push_back(I); | ||||
4395 | if (OpNum < Record.size() && isa<FPMathOperator>(I)) { | ||||
4396 | FastMathFlags FMF = getDecodedFastMathFlags(Record[OpNum]); | ||||
4397 | if (FMF.any()) | ||||
4398 | I->setFastMathFlags(FMF); | ||||
4399 | } | ||||
4400 | break; | ||||
4401 | } | ||||
4402 | |||||
4403 | case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval] | ||||
4404 | unsigned OpNum = 0; | ||||
4405 | Value *Vec, *Idx; | ||||
4406 | if (getValueTypePair(Record, OpNum, NextValueNo, Vec) || | ||||
4407 | getValueTypePair(Record, OpNum, NextValueNo, Idx)) | ||||
4408 | return error("Invalid record"); | ||||
4409 | if (!Vec->getType()->isVectorTy()) | ||||
4410 | return error("Invalid type for value"); | ||||
4411 | I = ExtractElementInst::Create(Vec, Idx); | ||||
4412 | InstructionList.push_back(I); | ||||
4413 | break; | ||||
4414 | } | ||||
4415 | |||||
4416 | case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval] | ||||
4417 | unsigned OpNum = 0; | ||||
4418 | Value *Vec, *Elt, *Idx; | ||||
4419 | if (getValueTypePair(Record, OpNum, NextValueNo, Vec)) | ||||
4420 | return error("Invalid record"); | ||||
4421 | if (!Vec->getType()->isVectorTy()) | ||||
4422 | return error("Invalid type for value"); | ||||
4423 | if (popValue(Record, OpNum, NextValueNo, | ||||
4424 | cast<VectorType>(Vec->getType())->getElementType(), Elt) || | ||||
4425 | getValueTypePair(Record, OpNum, NextValueNo, Idx)) | ||||
4426 | return error("Invalid record"); | ||||
4427 | I = InsertElementInst::Create(Vec, Elt, Idx); | ||||
4428 | InstructionList.push_back(I); | ||||
4429 | break; | ||||
4430 | } | ||||
4431 | |||||
4432 | case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval] | ||||
4433 | unsigned OpNum = 0; | ||||
4434 | Value *Vec1, *Vec2, *Mask; | ||||
4435 | if (getValueTypePair(Record, OpNum, NextValueNo, Vec1) || | ||||
4436 | popValue(Record, OpNum, NextValueNo, Vec1->getType(), Vec2)) | ||||
4437 | return error("Invalid record"); | ||||
4438 | |||||
4439 | if (getValueTypePair(Record, OpNum, NextValueNo, Mask)) | ||||
4440 | return error("Invalid record"); | ||||
4441 | if (!Vec1->getType()->isVectorTy() || !Vec2->getType()->isVectorTy()) | ||||
4442 | return error("Invalid type for value"); | ||||
4443 | |||||
4444 | I = new ShuffleVectorInst(Vec1, Vec2, Mask); | ||||
4445 | InstructionList.push_back(I); | ||||
4446 | break; | ||||
4447 | } | ||||
4448 | |||||
4449 | case bitc::FUNC_CODE_INST_CMP: // CMP: [opty, opval, opval, pred] | ||||
4450 | // Old form of ICmp/FCmp returning bool | ||||
4451 | // Existed to differentiate between icmp/fcmp and vicmp/vfcmp which were | ||||
4452 | // both legal on vectors but had different behaviour. | ||||
4453 | case bitc::FUNC_CODE_INST_CMP2: { // CMP2: [opty, opval, opval, pred] | ||||
4454 | // FCmp/ICmp returning bool or vector of bool | ||||
4455 | |||||
4456 | unsigned OpNum = 0; | ||||
4457 | Value *LHS, *RHS; | ||||
4458 | if (getValueTypePair(Record, OpNum, NextValueNo, LHS) || | ||||
4459 | popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS)) | ||||
4460 | return error("Invalid record"); | ||||
4461 | |||||
4462 | if (OpNum >= Record.size()) | ||||
4463 | return error( | ||||
4464 | "Invalid record: operand number exceeded available operands"); | ||||
4465 | |||||
4466 | unsigned PredVal = Record[OpNum]; | ||||
4467 | bool IsFP = LHS->getType()->isFPOrFPVectorTy(); | ||||
4468 | FastMathFlags FMF; | ||||
4469 | if (IsFP && Record.size() > OpNum+1) | ||||
4470 | FMF = getDecodedFastMathFlags(Record[++OpNum]); | ||||
4471 | |||||
4472 | if (OpNum+1 != Record.size()) | ||||
4473 | return error("Invalid record"); | ||||
4474 | |||||
4475 | if (LHS->getType()->isFPOrFPVectorTy()) | ||||
4476 | I = new FCmpInst((FCmpInst::Predicate)PredVal, LHS, RHS); | ||||
4477 | else | ||||
4478 | I = new ICmpInst((ICmpInst::Predicate)PredVal, LHS, RHS); | ||||
4479 | |||||
4480 | if (FMF.any()) | ||||
4481 | I->setFastMathFlags(FMF); | ||||
4482 | InstructionList.push_back(I); | ||||
4483 | break; | ||||
4484 | } | ||||
4485 | |||||
4486 | case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>] | ||||
4487 | { | ||||
4488 | unsigned Size = Record.size(); | ||||
4489 | if (Size == 0) { | ||||
4490 | I = ReturnInst::Create(Context); | ||||
4491 | InstructionList.push_back(I); | ||||
4492 | break; | ||||
4493 | } | ||||
4494 | |||||
4495 | unsigned OpNum = 0; | ||||
4496 | Value *Op = nullptr; | ||||
4497 | if (getValueTypePair(Record, OpNum, NextValueNo, Op)) | ||||
4498 | return error("Invalid record"); | ||||
4499 | if (OpNum != Record.size()) | ||||
4500 | return error("Invalid record"); | ||||
4501 | |||||
4502 | I = ReturnInst::Create(Context, Op); | ||||
4503 | InstructionList.push_back(I); | ||||
4504 | break; | ||||
4505 | } | ||||
4506 | case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#] | ||||
4507 | if (Record.size() != 1 && Record.size() != 3) | ||||
4508 | return error("Invalid record"); | ||||
4509 | BasicBlock *TrueDest = getBasicBlock(Record[0]); | ||||
4510 | if (!TrueDest) | ||||
4511 | return error("Invalid record"); | ||||
4512 | |||||
4513 | if (Record.size() == 1) { | ||||
4514 | I = BranchInst::Create(TrueDest); | ||||
4515 | InstructionList.push_back(I); | ||||
4516 | } | ||||
4517 | else { | ||||
4518 | BasicBlock *FalseDest = getBasicBlock(Record[1]); | ||||
4519 | Value *Cond = getValue(Record, 2, NextValueNo, | ||||
4520 | Type::getInt1Ty(Context)); | ||||
4521 | if (!FalseDest || !Cond) | ||||
4522 | return error("Invalid record"); | ||||
4523 | I = BranchInst::Create(TrueDest, FalseDest, Cond); | ||||
4524 | InstructionList.push_back(I); | ||||
4525 | } | ||||
4526 | break; | ||||
4527 | } | ||||
4528 | case bitc::FUNC_CODE_INST_CLEANUPRET: { // CLEANUPRET: [val] or [val,bb#] | ||||
4529 | if (Record.size() != 1 && Record.size() != 2) | ||||
4530 | return error("Invalid record"); | ||||
4531 | unsigned Idx = 0; | ||||
4532 | Value *CleanupPad = | ||||
4533 | getValue(Record, Idx++, NextValueNo, Type::getTokenTy(Context)); | ||||
4534 | if (!CleanupPad) | ||||
4535 | return error("Invalid record"); | ||||
4536 | BasicBlock *UnwindDest = nullptr; | ||||
4537 | if (Record.size() == 2) { | ||||
4538 | UnwindDest = getBasicBlock(Record[Idx++]); | ||||
4539 | if (!UnwindDest) | ||||
4540 | return error("Invalid record"); | ||||
4541 | } | ||||
4542 | |||||
4543 | I = CleanupReturnInst::Create(CleanupPad, UnwindDest); | ||||
4544 | InstructionList.push_back(I); | ||||
4545 | break; | ||||
4546 | } | ||||
4547 | case bitc::FUNC_CODE_INST_CATCHRET: { // CATCHRET: [val,bb#] | ||||
4548 | if (Record.size() != 2) | ||||
4549 | return error("Invalid record"); | ||||
4550 | unsigned Idx = 0; | ||||
4551 | Value *CatchPad = | ||||
4552 | getValue(Record, Idx++, NextValueNo, Type::getTokenTy(Context)); | ||||
4553 | if (!CatchPad) | ||||
4554 | return error("Invalid record"); | ||||
4555 | BasicBlock *BB = getBasicBlock(Record[Idx++]); | ||||
4556 | if (!BB) | ||||
4557 | return error("Invalid record"); | ||||
4558 | |||||
4559 | I = CatchReturnInst::Create(CatchPad, BB); | ||||
4560 | InstructionList.push_back(I); | ||||
4561 | break; | ||||
4562 | } | ||||
4563 | case bitc::FUNC_CODE_INST_CATCHSWITCH: { // CATCHSWITCH: [tok,num,(bb)*,bb?] | ||||
4564 | // We must have, at minimum, the outer scope and the number of arguments. | ||||
4565 | if (Record.size() < 2) | ||||
4566 | return error("Invalid record"); | ||||
4567 | |||||
4568 | unsigned Idx = 0; | ||||
4569 | |||||
4570 | Value *ParentPad = | ||||
4571 | getValue(Record, Idx++, NextValueNo, Type::getTokenTy(Context)); | ||||
4572 | |||||
4573 | unsigned NumHandlers = Record[Idx++]; | ||||
4574 | |||||
4575 | SmallVector<BasicBlock *, 2> Handlers; | ||||
4576 | for (unsigned Op = 0; Op != NumHandlers; ++Op) { | ||||
4577 | BasicBlock *BB = getBasicBlock(Record[Idx++]); | ||||
4578 | if (!BB) | ||||
4579 | return error("Invalid record"); | ||||
4580 | Handlers.push_back(BB); | ||||
4581 | } | ||||
4582 | |||||
4583 | BasicBlock *UnwindDest = nullptr; | ||||
4584 | if (Idx + 1 == Record.size()) { | ||||
4585 | UnwindDest = getBasicBlock(Record[Idx++]); | ||||
4586 | if (!UnwindDest) | ||||
4587 | return error("Invalid record"); | ||||
4588 | } | ||||
4589 | |||||
4590 | if (Record.size() != Idx) | ||||
4591 | return error("Invalid record"); | ||||
4592 | |||||
4593 | auto *CatchSwitch = | ||||
4594 | CatchSwitchInst::Create(ParentPad, UnwindDest, NumHandlers); | ||||
4595 | for (BasicBlock *Handler : Handlers) | ||||
4596 | CatchSwitch->addHandler(Handler); | ||||
4597 | I = CatchSwitch; | ||||
4598 | InstructionList.push_back(I); | ||||
4599 | break; | ||||
4600 | } | ||||
4601 | case bitc::FUNC_CODE_INST_CATCHPAD: | ||||
4602 | case bitc::FUNC_CODE_INST_CLEANUPPAD: { // [tok,num,(ty,val)*] | ||||
4603 | // We must have, at minimum, the outer scope and the number of arguments. | ||||
4604 | if (Record.size() < 2) | ||||
4605 | return error("Invalid record"); | ||||
4606 | |||||
4607 | unsigned Idx = 0; | ||||
4608 | |||||
4609 | Value *ParentPad = | ||||
4610 | getValue(Record, Idx++, NextValueNo, Type::getTokenTy(Context)); | ||||
4611 | |||||
4612 | unsigned NumArgOperands = Record[Idx++]; | ||||
4613 | |||||
4614 | SmallVector<Value *, 2> Args; | ||||
4615 | for (unsigned Op = 0; Op != NumArgOperands; ++Op) { | ||||
4616 | Value *Val; | ||||
4617 | if (getValueTypePair(Record, Idx, NextValueNo, Val)) | ||||
4618 | return error("Invalid record"); | ||||
4619 | Args.push_back(Val); | ||||
4620 | } | ||||
4621 | |||||
4622 | if (Record.size() != Idx) | ||||
4623 | return error("Invalid record"); | ||||
4624 | |||||
4625 | if (BitCode == bitc::FUNC_CODE_INST_CLEANUPPAD) | ||||
4626 | I = CleanupPadInst::Create(ParentPad, Args); | ||||
4627 | else | ||||
4628 | I = CatchPadInst::Create(ParentPad, Args); | ||||
4629 | InstructionList.push_back(I); | ||||
4630 | break; | ||||
4631 | } | ||||
4632 | case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, op0, op1, ...] | ||||
4633 | // Check magic | ||||
4634 | if ((Record[0] >> 16) == SWITCH_INST_MAGIC) { | ||||
4635 | // "New" SwitchInst format with case ranges. The changes to write this | ||||
4636 | // format were reverted but we still recognize bitcode that uses it. | ||||
4637 | // Hopefully someday we will have support for case ranges and can use | ||||
4638 | // this format again. | ||||
4639 | |||||
4640 | Type *OpTy = getTypeByID(Record[1]); | ||||
4641 | unsigned ValueBitWidth = cast<IntegerType>(OpTy)->getBitWidth(); | ||||
4642 | |||||
4643 | Value *Cond = getValue(Record, 2, NextValueNo, OpTy); | ||||
4644 | BasicBlock *Default = getBasicBlock(Record[3]); | ||||
4645 | if (!OpTy || !Cond || !Default) | ||||
4646 | return error("Invalid record"); | ||||
4647 | |||||
4648 | unsigned NumCases = Record[4]; | ||||
4649 | |||||
4650 | SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases); | ||||
4651 | InstructionList.push_back(SI); | ||||
4652 | |||||
4653 | unsigned CurIdx = 5; | ||||
4654 | for (unsigned i = 0; i != NumCases; ++i) { | ||||
4655 | SmallVector<ConstantInt*, 1> CaseVals; | ||||
4656 | unsigned NumItems = Record[CurIdx++]; | ||||
4657 | for (unsigned ci = 0; ci != NumItems; ++ci) { | ||||
4658 | bool isSingleNumber = Record[CurIdx++]; | ||||
4659 | |||||
4660 | APInt Low; | ||||
4661 | unsigned ActiveWords = 1; | ||||
4662 | if (ValueBitWidth > 64) | ||||
4663 | ActiveWords = Record[CurIdx++]; | ||||
4664 | Low = readWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords), | ||||
4665 | ValueBitWidth); | ||||
4666 | CurIdx += ActiveWords; | ||||
4667 | |||||
4668 | if (!isSingleNumber) { | ||||
4669 | ActiveWords = 1; | ||||
4670 | if (ValueBitWidth > 64) | ||||
4671 | ActiveWords = Record[CurIdx++]; | ||||
4672 | APInt High = readWideAPInt( | ||||
4673 | makeArrayRef(&Record[CurIdx], ActiveWords), ValueBitWidth); | ||||
4674 | CurIdx += ActiveWords; | ||||
4675 | |||||
4676 | // FIXME: It is not clear whether values in the range should be | ||||
4677 | // compared as signed or unsigned values. The partially | ||||
4678 | // implemented changes that used this format in the past used | ||||
4679 | // unsigned comparisons. | ||||
4680 | for ( ; Low.ule(High); ++Low) | ||||
4681 | CaseVals.push_back(ConstantInt::get(Context, Low)); | ||||
4682 | } else | ||||
4683 | CaseVals.push_back(ConstantInt::get(Context, Low)); | ||||
4684 | } | ||||
4685 | BasicBlock *DestBB = getBasicBlock(Record[CurIdx++]); | ||||
4686 | for (ConstantInt *Cst : CaseVals) | ||||
4687 | SI->addCase(Cst, DestBB); | ||||
4688 | } | ||||
4689 | I = SI; | ||||
4690 | break; | ||||
4691 | } | ||||
4692 | |||||
4693 | // Old SwitchInst format without case ranges. | ||||
4694 | |||||
4695 | if (Record.size() < 3 || (Record.size() & 1) == 0) | ||||
4696 | return error("Invalid record"); | ||||
4697 | Type *OpTy = getTypeByID(Record[0]); | ||||
4698 | Value *Cond = getValue(Record, 1, NextValueNo, OpTy); | ||||
4699 | BasicBlock *Default = getBasicBlock(Record[2]); | ||||
4700 | if (!OpTy || !Cond || !Default) | ||||
4701 | return error("Invalid record"); | ||||
4702 | unsigned NumCases = (Record.size()-3)/2; | ||||
4703 | SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases); | ||||
4704 | InstructionList.push_back(SI); | ||||
4705 | for (unsigned i = 0, e = NumCases; i != e; ++i) { | ||||
4706 | ConstantInt *CaseVal = | ||||
4707 | dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy)); | ||||
4708 | BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]); | ||||
4709 | if (!CaseVal || !DestBB) { | ||||
4710 | delete SI; | ||||
4711 | return error("Invalid record"); | ||||
4712 | } | ||||
4713 | SI->addCase(CaseVal, DestBB); | ||||
4714 | } | ||||
4715 | I = SI; | ||||
4716 | break; | ||||
4717 | } | ||||
4718 | case bitc::FUNC_CODE_INST_INDIRECTBR: { // INDIRECTBR: [opty, op0, op1, ...] | ||||
4719 | if (Record.size() < 2) | ||||
4720 | return error("Invalid record"); | ||||
4721 | Type *OpTy = getTypeByID(Record[0]); | ||||
4722 | Value *Address = getValue(Record, 1, NextValueNo, OpTy); | ||||
4723 | if (!OpTy || !Address) | ||||
4724 | return error("Invalid record"); | ||||
4725 | unsigned NumDests = Record.size()-2; | ||||
4726 | IndirectBrInst *IBI = IndirectBrInst::Create(Address, NumDests); | ||||
4727 | InstructionList.push_back(IBI); | ||||
4728 | for (unsigned i = 0, e = NumDests; i != e; ++i) { | ||||
4729 | if (BasicBlock *DestBB = getBasicBlock(Record[2+i])) { | ||||
4730 | IBI->addDestination(DestBB); | ||||
4731 | } else { | ||||
4732 | delete IBI; | ||||
4733 | return error("Invalid record"); | ||||
4734 | } | ||||
4735 | } | ||||
4736 | I = IBI; | ||||
4737 | break; | ||||
4738 | } | ||||
4739 | |||||
4740 | case bitc::FUNC_CODE_INST_INVOKE: { | ||||
4741 | // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...] | ||||
4742 | if (Record.size() < 4) | ||||
4743 | return error("Invalid record"); | ||||
4744 | unsigned OpNum = 0; | ||||
4745 | AttributeList PAL = getAttributes(Record[OpNum++]); | ||||
4746 | unsigned CCInfo = Record[OpNum++]; | ||||
4747 | BasicBlock *NormalBB = getBasicBlock(Record[OpNum++]); | ||||
4748 | BasicBlock *UnwindBB = getBasicBlock(Record[OpNum++]); | ||||
4749 | |||||
4750 | FunctionType *FTy = nullptr; | ||||
4751 | if ((CCInfo >> 13) & 1) { | ||||
4752 | FTy = dyn_cast<FunctionType>(getTypeByID(Record[OpNum++])); | ||||
4753 | if (!FTy) | ||||
4754 | return error("Explicit invoke type is not a function type"); | ||||
4755 | } | ||||
4756 | |||||
4757 | Value *Callee; | ||||
4758 | if (getValueTypePair(Record, OpNum, NextValueNo, Callee)) | ||||
4759 | return error("Invalid record"); | ||||
4760 | |||||
4761 | PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType()); | ||||
4762 | if (!CalleeTy) | ||||
4763 | return error("Callee is not a pointer"); | ||||
4764 | if (!FTy) { | ||||
4765 | FTy = | ||||
4766 | dyn_cast<FunctionType>(Callee->getType()->getPointerElementType()); | ||||
4767 | if (!FTy) | ||||
4768 | return error("Callee is not of pointer to function type"); | ||||
4769 | } else if (!CalleeTy->isOpaqueOrPointeeTypeMatches(FTy)) | ||||
4770 | return error("Explicit invoke type does not match pointee type of " | ||||
4771 | "callee operand"); | ||||
4772 | if (Record.size() < FTy->getNumParams() + OpNum) | ||||
4773 | return error("Insufficient operands to call"); | ||||
4774 | |||||
4775 | SmallVector<Value*, 16> Ops; | ||||
4776 | SmallVector<Type *, 16> ArgsTys; | ||||
4777 | for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) { | ||||
4778 | Ops.push_back(getValue(Record, OpNum, NextValueNo, | ||||
4779 | FTy->getParamType(i))); | ||||
4780 | ArgsTys.push_back(FTy->getParamType(i)); | ||||
4781 | if (!Ops.back()) | ||||
4782 | return error("Invalid record"); | ||||
4783 | } | ||||
4784 | |||||
4785 | if (!FTy->isVarArg()) { | ||||
4786 | if (Record.size() != OpNum) | ||||
4787 | return error("Invalid record"); | ||||
4788 | } else { | ||||
4789 | // Read type/value pairs for varargs params. | ||||
4790 | while (OpNum != Record.size()) { | ||||
4791 | Value *Op; | ||||
4792 | if (getValueTypePair(Record, OpNum, NextValueNo, Op)) | ||||
4793 | return error("Invalid record"); | ||||
4794 | Ops.push_back(Op); | ||||
4795 | ArgsTys.push_back(Op->getType()); | ||||
4796 | } | ||||
4797 | } | ||||
4798 | |||||
4799 | I = InvokeInst::Create(FTy, Callee, NormalBB, UnwindBB, Ops, | ||||
4800 | OperandBundles); | ||||
4801 | OperandBundles.clear(); | ||||
4802 | InstructionList.push_back(I); | ||||
4803 | cast<InvokeInst>(I)->setCallingConv( | ||||
4804 | static_cast<CallingConv::ID>(CallingConv::MaxID & CCInfo)); | ||||
4805 | cast<InvokeInst>(I)->setAttributes(PAL); | ||||
4806 | propagateAttributeTypes(cast<CallBase>(I), ArgsTys); | ||||
4807 | |||||
4808 | break; | ||||
4809 | } | ||||
4810 | case bitc::FUNC_CODE_INST_RESUME: { // RESUME: [opval] | ||||
4811 | unsigned Idx = 0; | ||||
4812 | Value *Val = nullptr; | ||||
4813 | if (getValueTypePair(Record, Idx, NextValueNo, Val)) | ||||
4814 | return error("Invalid record"); | ||||
4815 | I = ResumeInst::Create(Val); | ||||
4816 | InstructionList.push_back(I); | ||||
4817 | break; | ||||
4818 | } | ||||
4819 | case bitc::FUNC_CODE_INST_CALLBR: { | ||||
4820 | // CALLBR: [attr, cc, norm, transfs, fty, fnid, args] | ||||
4821 | unsigned OpNum = 0; | ||||
4822 | AttributeList PAL = getAttributes(Record[OpNum++]); | ||||
4823 | unsigned CCInfo = Record[OpNum++]; | ||||
4824 | |||||
4825 | BasicBlock *DefaultDest = getBasicBlock(Record[OpNum++]); | ||||
4826 | unsigned NumIndirectDests = Record[OpNum++]; | ||||
4827 | SmallVector<BasicBlock *, 16> IndirectDests; | ||||
4828 | for (unsigned i = 0, e = NumIndirectDests; i != e; ++i) | ||||
4829 | IndirectDests.push_back(getBasicBlock(Record[OpNum++])); | ||||
4830 | |||||
4831 | FunctionType *FTy = nullptr; | ||||
4832 | if ((CCInfo >> bitc::CALL_EXPLICIT_TYPE) & 1) { | ||||
4833 | FTy = dyn_cast<FunctionType>(getTypeByID(Record[OpNum++])); | ||||
4834 | if (!FTy) | ||||
4835 | return error("Explicit call type is not a function type"); | ||||
4836 | } | ||||
4837 | |||||
4838 | Value *Callee; | ||||
4839 | if (getValueTypePair(Record, OpNum, NextValueNo, Callee)) | ||||
4840 | return error("Invalid record"); | ||||
4841 | |||||
4842 | PointerType *OpTy = dyn_cast<PointerType>(Callee->getType()); | ||||
4843 | if (!OpTy) | ||||
4844 | return error("Callee is not a pointer type"); | ||||
4845 | if (!FTy) { | ||||
4846 | FTy = | ||||
4847 | dyn_cast<FunctionType>(Callee->getType()->getPointerElementType()); | ||||
4848 | if (!FTy) | ||||
4849 | return error("Callee is not of pointer to function type"); | ||||
4850 | } else if (!OpTy->isOpaqueOrPointeeTypeMatches(FTy)) | ||||
4851 | return error("Explicit call type does not match pointee type of " | ||||
4852 | "callee operand"); | ||||
4853 | if (Record.size() < FTy->getNumParams() + OpNum) | ||||
4854 | return error("Insufficient operands to call"); | ||||
4855 | |||||
4856 | SmallVector<Value*, 16> Args; | ||||
4857 | SmallVector<Type *, 16> ArgsTys; | ||||
4858 | // Read the fixed params. | ||||
4859 | for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) { | ||||
4860 | Value *Arg; | ||||
4861 | if (FTy->getParamType(i)->isLabelTy()) | ||||
4862 | Arg = getBasicBlock(Record[OpNum]); | ||||
4863 | else | ||||
4864 | Arg = getValue(Record, OpNum, NextValueNo, FTy->getParamType(i)); | ||||
4865 | if (!Arg) | ||||
4866 | return error("Invalid record"); | ||||
4867 | Args.push_back(Arg); | ||||
4868 | ArgsTys.push_back(Arg->getType()); | ||||
4869 | } | ||||
4870 | |||||
4871 | // Read type/value pairs for varargs params. | ||||
4872 | if (!FTy->isVarArg()) { | ||||
4873 | if (OpNum != Record.size()) | ||||
4874 | return error("Invalid record"); | ||||
4875 | } else { | ||||
4876 | while (OpNum != Record.size()) { | ||||
4877 | Value *Op; | ||||
4878 | if (getValueTypePair(Record, OpNum, NextValueNo, Op)) | ||||
4879 | return error("Invalid record"); | ||||
4880 | Args.push_back(Op); | ||||
4881 | ArgsTys.push_back(Op->getType()); | ||||
4882 | } | ||||
4883 | } | ||||
4884 | |||||
4885 | I = CallBrInst::Create(FTy, Callee, DefaultDest, IndirectDests, Args, | ||||
4886 | OperandBundles); | ||||
4887 | OperandBundles.clear(); | ||||
4888 | InstructionList.push_back(I); | ||||
4889 | cast<CallBrInst>(I)->setCallingConv( | ||||
4890 | static_cast<CallingConv::ID>((0x7ff & CCInfo) >> bitc::CALL_CCONV)); | ||||
4891 | cast<CallBrInst>(I)->setAttributes(PAL); | ||||
4892 | propagateAttributeTypes(cast<CallBase>(I), ArgsTys); | ||||
4893 | break; | ||||
4894 | } | ||||
4895 | case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE | ||||
4896 | I = new UnreachableInst(Context); | ||||
4897 | InstructionList.push_back(I); | ||||
4898 | break; | ||||
4899 | case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...] | ||||
4900 | if (Record.empty()) | ||||
4901 | return error("Invalid record"); | ||||
4902 | // The first record specifies the type. | ||||
4903 | Type *Ty = getTypeByID(Record[0]); | ||||
4904 | if (!Ty) | ||||
4905 | return error("Invalid record"); | ||||
4906 | |||||
4907 | // Phi arguments are pairs of records of [value, basic block]. | ||||
4908 | // There is an optional final record for fast-math-flags if this phi has a | ||||
4909 | // floating-point type. | ||||
4910 | size_t NumArgs = (Record.size() - 1) / 2; | ||||
4911 | PHINode *PN = PHINode::Create(Ty, NumArgs); | ||||
4912 | if ((Record.size() - 1) % 2 == 1 && !isa<FPMathOperator>(PN)) | ||||
4913 | return error("Invalid record"); | ||||
4914 | InstructionList.push_back(PN); | ||||
4915 | |||||
4916 | for (unsigned i = 0; i != NumArgs; i++) { | ||||
4917 | Value *V; | ||||
4918 | // With the new function encoding, it is possible that operands have | ||||
4919 | // negative IDs (for forward references). Use a signed VBR | ||||
4920 | // representation to keep the encoding small. | ||||
4921 | if (UseRelativeIDs) | ||||
4922 | V = getValueSigned(Record, i * 2 + 1, NextValueNo, Ty); | ||||
4923 | else | ||||
4924 | V = getValue(Record, i * 2 + 1, NextValueNo, Ty); | ||||
4925 | BasicBlock *BB = getBasicBlock(Record[i * 2 + 2]); | ||||
4926 | if (!V || !BB) | ||||
4927 | return error("Invalid record"); | ||||
4928 | PN->addIncoming(V, BB); | ||||
4929 | } | ||||
4930 | I = PN; | ||||
4931 | |||||
4932 | // If there are an even number of records, the final record must be FMF. | ||||
4933 | if (Record.size() % 2 == 0) { | ||||
4934 | assert(isa<FPMathOperator>(I) && "Unexpected phi type")(static_cast <bool> (isa<FPMathOperator>(I) && "Unexpected phi type") ? void (0) : __assert_fail ("isa<FPMathOperator>(I) && \"Unexpected phi type\"" , "llvm/lib/Bitcode/Reader/BitcodeReader.cpp", 4934, __extension__ __PRETTY_FUNCTION__)); | ||||
4935 | FastMathFlags FMF = getDecodedFastMathFlags(Record[Record.size() - 1]); | ||||
4936 | if (FMF.any()) | ||||
4937 | I->setFastMathFlags(FMF); | ||||
4938 | } | ||||
4939 | |||||
4940 | break; | ||||
4941 | } | ||||
4942 | |||||
4943 | case bitc::FUNC_CODE_INST_LANDINGPAD: | ||||
4944 | case bitc::FUNC_CODE_INST_LANDINGPAD_OLD: { | ||||
4945 | // LANDINGPAD: [ty, val, val, num, (id0,val0 ...)?] | ||||
4946 | unsigned Idx = 0; | ||||
4947 | if (BitCode == bitc::FUNC_CODE_INST_LANDINGPAD) { | ||||
4948 | if (Record.size() < 3) | ||||
4949 | return error("Invalid record"); | ||||
4950 | } else { | ||||
4951 | assert(BitCode == bitc::FUNC_CODE_INST_LANDINGPAD_OLD)(static_cast <bool> (BitCode == bitc::FUNC_CODE_INST_LANDINGPAD_OLD ) ? void (0) : __assert_fail ("BitCode == bitc::FUNC_CODE_INST_LANDINGPAD_OLD" , "llvm/lib/Bitcode/Reader/BitcodeReader.cpp", 4951, __extension__ __PRETTY_FUNCTION__)); | ||||
4952 | if (Record.size() < 4) | ||||
4953 | return error("Invalid record"); | ||||
4954 | } | ||||
4955 | Type *Ty = getTypeByID(Record[Idx++]); | ||||
4956 | if (!Ty) | ||||
4957 | return error("Invalid record"); | ||||
4958 | if (BitCode == bitc::FUNC_CODE_INST_LANDINGPAD_OLD) { | ||||
4959 | Value *PersFn = nullptr; | ||||
4960 | if (getValueTypePair(Record, Idx, NextValueNo, PersFn)) | ||||
4961 | return error("Invalid record"); | ||||
4962 | |||||
4963 | if (!F->hasPersonalityFn()) | ||||
4964 | F->setPersonalityFn(cast<Constant>(PersFn)); | ||||
4965 | else if (F->getPersonalityFn() != cast<Constant>(PersFn)) | ||||
4966 | return error("Personality function mismatch"); | ||||
4967 | } | ||||
4968 | |||||
4969 | bool IsCleanup = !!Record[Idx++]; | ||||
4970 | unsigned NumClauses = Record[Idx++]; | ||||
4971 | LandingPadInst *LP = LandingPadInst::Create(Ty, NumClauses); | ||||
4972 | LP->setCleanup(IsCleanup); | ||||
4973 | for (unsigned J = 0; J != NumClauses; ++J) { | ||||
4974 | LandingPadInst::ClauseType CT = | ||||
4975 | LandingPadInst::ClauseType(Record[Idx++]); (void)CT; | ||||
4976 | Value *Val; | ||||
4977 | |||||
4978 | if (getValueTypePair(Record, Idx, NextValueNo, Val)) { | ||||
4979 | delete LP; | ||||
4980 | return error("Invalid record"); | ||||
4981 | } | ||||
4982 | |||||
4983 | assert((CT != LandingPadInst::Catch ||(static_cast <bool> ((CT != LandingPadInst::Catch || !isa <ArrayType>(Val->getType())) && "Catch clause has a invalid type!" ) ? void (0) : __assert_fail ("(CT != LandingPadInst::Catch || !isa<ArrayType>(Val->getType())) && \"Catch clause has a invalid type!\"" , "llvm/lib/Bitcode/Reader/BitcodeReader.cpp", 4985, __extension__ __PRETTY_FUNCTION__)) | ||||
4984 | !isa<ArrayType>(Val->getType())) &&(static_cast <bool> ((CT != LandingPadInst::Catch || !isa <ArrayType>(Val->getType())) && "Catch clause has a invalid type!" ) ? void (0) : __assert_fail ("(CT != LandingPadInst::Catch || !isa<ArrayType>(Val->getType())) && \"Catch clause has a invalid type!\"" , "llvm/lib/Bitcode/Reader/BitcodeReader.cpp", 4985, __extension__ __PRETTY_FUNCTION__)) | ||||
4985 | "Catch clause has a invalid type!")(static_cast <bool> ((CT != LandingPadInst::Catch || !isa <ArrayType>(Val->getType())) && "Catch clause has a invalid type!" ) ? void (0) : __assert_fail ("(CT != LandingPadInst::Catch || !isa<ArrayType>(Val->getType())) && \"Catch clause has a invalid type!\"" , "llvm/lib/Bitcode/Reader/BitcodeReader.cpp", 4985, __extension__ __PRETTY_FUNCTION__)); | ||||
4986 | assert((CT != LandingPadInst::Filter ||(static_cast <bool> ((CT != LandingPadInst::Filter || isa <ArrayType>(Val->getType())) && "Filter clause has invalid type!" ) ? void (0) : __assert_fail ("(CT != LandingPadInst::Filter || isa<ArrayType>(Val->getType())) && \"Filter clause has invalid type!\"" , "llvm/lib/Bitcode/Reader/BitcodeReader.cpp", 4988, __extension__ __PRETTY_FUNCTION__)) | ||||
4987 | isa<ArrayType>(Val->getType())) &&(static_cast <bool> ((CT != LandingPadInst::Filter || isa <ArrayType>(Val->getType())) && "Filter clause has invalid type!" ) ? void (0) : __assert_fail ("(CT != LandingPadInst::Filter || isa<ArrayType>(Val->getType())) && \"Filter clause has invalid type!\"" , "llvm/lib/Bitcode/Reader/BitcodeReader.cpp", 4988, __extension__ __PRETTY_FUNCTION__)) | ||||
4988 | "Filter clause has invalid type!")(static_cast <bool> ((CT != LandingPadInst::Filter || isa <ArrayType>(Val->getType())) && "Filter clause has invalid type!" ) ? void (0) : __assert_fail ("(CT != LandingPadInst::Filter || isa<ArrayType>(Val->getType())) && \"Filter clause has invalid type!\"" , "llvm/lib/Bitcode/Reader/BitcodeReader.cpp", 4988, __extension__ __PRETTY_FUNCTION__)); | ||||
4989 | LP->addClause(cast<Constant>(Val)); | ||||
4990 | } | ||||
4991 | |||||
4992 | I = LP; | ||||
4993 | InstructionList.push_back(I); | ||||
4994 | break; | ||||
4995 | } | ||||
4996 | |||||
4997 | case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, opty, op, align] | ||||
4998 | if (Record.size() != 4) | ||||
4999 | return error("Invalid record"); | ||||
5000 | using APV = AllocaPackedValues; | ||||
5001 | const uint64_t Rec = Record[3]; | ||||
5002 | const bool InAlloca = Bitfield::get<APV::UsedWithInAlloca>(Rec); | ||||
5003 | const bool SwiftError = Bitfield::get<APV::SwiftError>(Rec); | ||||
5004 | Type *Ty = getTypeByID(Record[0]); | ||||
5005 | if (!Bitfield::get<APV::ExplicitType>(Rec)) { | ||||
5006 | auto *PTy = dyn_cast_or_null<PointerType>(Ty); | ||||
5007 | if (!PTy) | ||||
5008 | return error("Old-style alloca with a non-pointer type"); | ||||
5009 | Ty = PTy->getPointerElementType(); | ||||
5010 | } | ||||
5011 | Type *OpTy = getTypeByID(Record[1]); | ||||
5012 | Value *Size = getFnValueByID(Record[2], OpTy); | ||||
5013 | MaybeAlign Align; | ||||
5014 | uint64_t AlignExp = | ||||
5015 | Bitfield::get<APV::AlignLower>(Rec) | | ||||
5016 | (Bitfield::get<APV::AlignUpper>(Rec) << APV::AlignLower::Bits); | ||||
5017 | if (Error Err = parseAlignmentValue(AlignExp, Align)) { | ||||
5018 | return Err; | ||||
5019 | } | ||||
5020 | if (!Ty || !Size) | ||||
5021 | return error("Invalid record"); | ||||
5022 | |||||
5023 | // FIXME: Make this an optional field. | ||||
5024 | const DataLayout &DL = TheModule->getDataLayout(); | ||||
5025 | unsigned AS = DL.getAllocaAddrSpace(); | ||||
5026 | |||||
5027 | SmallPtrSet<Type *, 4> Visited; | ||||
5028 | if (!Align && !Ty->isSized(&Visited)) | ||||
5029 | return error("alloca of unsized type"); | ||||
5030 | if (!Align) | ||||
5031 | Align = DL.getPrefTypeAlign(Ty); | ||||
5032 | |||||
5033 | AllocaInst *AI = new AllocaInst(Ty, AS, Size, *Align); | ||||
5034 | AI->setUsedWithInAlloca(InAlloca); | ||||
5035 | AI->setSwiftError(SwiftError); | ||||
5036 | I = AI; | ||||
5037 | InstructionList.push_back(I); | ||||
5038 | break; | ||||
5039 | } | ||||
5040 | case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol] | ||||
5041 | unsigned OpNum = 0; | ||||
5042 | Value *Op; | ||||
5043 | if (getValueTypePair(Record, OpNum, NextValueNo, Op) || | ||||
5044 | (OpNum + 2 != Record.size() && OpNum + 3 != Record.size())) | ||||
5045 | return error("Invalid record"); | ||||
5046 | |||||
5047 | if (!isa<PointerType>(Op->getType())) | ||||
5048 | return error("Load operand is not a pointer type"); | ||||
5049 | |||||
5050 | Type *Ty = nullptr; | ||||
5051 | if (OpNum + 3 == Record.size()) { | ||||
5052 | Ty = getTypeByID(Record[OpNum++]); | ||||
5053 | } else { | ||||
5054 | Ty = Op->getType()->getPointerElementType(); | ||||
5055 | } | ||||
5056 | |||||
5057 | if (Error Err = typeCheckLoadStoreInst(Ty, Op->getType())) | ||||
5058 | return Err; | ||||
5059 | |||||
5060 | MaybeAlign Align; | ||||
5061 | if (Error Err = parseAlignmentValue(Record[OpNum], Align)) | ||||
5062 | return Err; | ||||
5063 | SmallPtrSet<Type *, 4> Visited; | ||||
5064 | if (!Align && !Ty->isSized(&Visited)) | ||||
5065 | return error("load of unsized type"); | ||||
5066 | if (!Align) | ||||
5067 | Align = TheModule->getDataLayout().getABITypeAlign(Ty); | ||||
5068 | I = new LoadInst(Ty, Op, "", Record[OpNum + 1], *Align); | ||||
5069 | InstructionList.push_back(I); | ||||
5070 | break; | ||||
5071 | } | ||||
5072 | case bitc::FUNC_CODE_INST_LOADATOMIC: { | ||||
5073 | // LOADATOMIC: [opty, op, align, vol, ordering, ssid] | ||||
5074 | unsigned OpNum = 0; | ||||
5075 | Value *Op; | ||||
5076 | if (getValueTypePair(Record, OpNum, NextValueNo, Op) || | ||||
5077 | (OpNum + 4 != Record.size() && OpNum + 5 != Record.size())) | ||||
5078 | return error("Invalid record"); | ||||
5079 | |||||
5080 | if (!isa<PointerType>(Op->getType())) | ||||
5081 | return error("Load operand is not a pointer type"); | ||||
5082 | |||||
5083 | Type *Ty = nullptr; | ||||
5084 | if (OpNum + 5 == Record.size()) { | ||||
5085 | Ty = getTypeByID(Record[OpNum++]); | ||||
5086 | } else { | ||||
5087 | Ty = Op->getType()->getPointerElementType(); | ||||
5088 | } | ||||
5089 | |||||
5090 | if (Error Err = typeCheckLoadStoreInst(Ty, Op->getType())) | ||||
5091 | return Err; | ||||
5092 | |||||
5093 | AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]); | ||||
5094 | if (Ordering == AtomicOrdering::NotAtomic || | ||||
5095 | Ordering == AtomicOrdering::Release || | ||||
5096 | Ordering == AtomicOrdering::AcquireRelease) | ||||
5097 | return error("Invalid record"); | ||||
5098 | if (Ordering != AtomicOrdering::NotAtomic && Record[OpNum] == 0) | ||||
5099 | return error("Invalid record"); | ||||
5100 | SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 3]); | ||||
5101 | |||||
5102 | MaybeAlign Align; | ||||
5103 | if (Error Err = parseAlignmentValue(Record[OpNum], Align)) | ||||
5104 | return Err; | ||||
5105 | if (!Align) | ||||
5106 | return error("Alignment missing from atomic load"); | ||||
5107 | I = new LoadInst(Ty, Op, "", Record[OpNum + 1], *Align, Ordering, SSID); | ||||
5108 | InstructionList.push_back(I); | ||||
5109 | break; | ||||
5110 | } | ||||
5111 | case bitc::FUNC_CODE_INST_STORE: | ||||
5112 | case bitc::FUNC_CODE_INST_STORE_OLD: { // STORE2:[ptrty, ptr, val, align, vol] | ||||
5113 | unsigned OpNum = 0; | ||||
5114 | Value *Val, *Ptr; | ||||
5115 | if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) || | ||||
5116 | (BitCode == bitc::FUNC_CODE_INST_STORE | ||||
5117 | ? getValueTypePair(Record, OpNum, NextValueNo, Val) | ||||
5118 | : popValue(Record, OpNum, NextValueNo, | ||||
5119 | Ptr->getType()->getPointerElementType(), Val)) || | ||||
5120 | OpNum + 2 != Record.size()) | ||||
5121 | return error("Invalid record"); | ||||
5122 | |||||
5123 | if (Error Err = typeCheckLoadStoreInst(Val->getType(), Ptr->getType())) | ||||
5124 | return Err; | ||||
5125 | MaybeAlign Align; | ||||
5126 | if (Error Err = parseAlignmentValue(Record[OpNum], Align)) | ||||
5127 | return Err; | ||||
5128 | SmallPtrSet<Type *, 4> Visited; | ||||
5129 | if (!Align && !Val->getType()->isSized(&Visited)) | ||||
5130 | return error("store of unsized type"); | ||||
5131 | if (!Align) | ||||
5132 | Align = TheModule->getDataLayout().getABITypeAlign(Val->getType()); | ||||
5133 | I = new StoreInst(Val, Ptr, Record[OpNum + 1], *Align); | ||||
5134 | InstructionList.push_back(I); | ||||
5135 | break; | ||||
5136 | } | ||||
5137 | case bitc::FUNC_CODE_INST_STOREATOMIC: | ||||
5138 | case bitc::FUNC_CODE_INST_STOREATOMIC_OLD: { | ||||
5139 | // STOREATOMIC: [ptrty, ptr, val, align, vol, ordering, ssid] | ||||
5140 | unsigned OpNum = 0; | ||||
5141 | Value *Val, *Ptr; | ||||
5142 | if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) || | ||||
5143 | !isa<PointerType>(Ptr->getType()) || | ||||
5144 | (BitCode == bitc::FUNC_CODE_INST_STOREATOMIC | ||||
5145 | ? getValueTypePair(Record, OpNum, NextValueNo, Val) | ||||
5146 | : popValue(Record, OpNum, NextValueNo, | ||||
5147 | Ptr->getType()->getPointerElementType(), Val)) || | ||||
5148 | OpNum + 4 != Record.size()) | ||||
5149 | return error("Invalid record"); | ||||
5150 | |||||
5151 | if (Error Err = typeCheckLoadStoreInst(Val->getType(), Ptr->getType())) | ||||
5152 | return Err; | ||||
5153 | AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]); | ||||
5154 | if (Ordering == AtomicOrdering::NotAtomic || | ||||
5155 | Ordering == AtomicOrdering::Acquire || | ||||
5156 | Ordering == AtomicOrdering::AcquireRelease) | ||||
5157 | return error("Invalid record"); | ||||
5158 | SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 3]); | ||||
5159 | if (Ordering != AtomicOrdering::NotAtomic && Record[OpNum] == 0) | ||||
5160 | return error("Invalid record"); | ||||
5161 | |||||
5162 | MaybeAlign Align; | ||||
5163 | if (Error Err = parseAlignmentValue(Record[OpNum], Align)) | ||||
5164 | return Err; | ||||
5165 | if (!Align) | ||||
5166 | return error("Alignment missing from atomic store"); | ||||
5167 | I = new StoreInst(Val, Ptr, Record[OpNum + 1], *Align, Ordering, SSID); | ||||
5168 | InstructionList.push_back(I); | ||||
5169 | break; | ||||
5170 | } | ||||
5171 | case bitc::FUNC_CODE_INST_CMPXCHG_OLD: { | ||||
5172 | // CMPXCHG_OLD: [ptrty, ptr, cmp, val, vol, ordering, synchscope, | ||||
5173 | // failure_ordering?, weak?] | ||||
5174 | const size_t NumRecords = Record.size(); | ||||
5175 | unsigned OpNum = 0; | ||||
5176 | Value *Ptr = nullptr; | ||||
5177 | if (getValueTypePair(Record, OpNum, NextValueNo, Ptr)) | ||||
5178 | return error("Invalid record"); | ||||
5179 | |||||
5180 | if (!isa<PointerType>(Ptr->getType())) | ||||
5181 | return error("Cmpxchg operand is not a pointer type"); | ||||
5182 | |||||
5183 | Value *Cmp = nullptr; | ||||
5184 | if (popValue(Record, OpNum, NextValueNo, | ||||
5185 | cast<PointerType>(Ptr->getType())->getPointerElementType(), | ||||
5186 | Cmp)) | ||||
5187 | return error("Invalid record"); | ||||
5188 | |||||
5189 | Value *New = nullptr; | ||||
5190 | if (popValue(Record, OpNum, NextValueNo, Cmp->getType(), New) || | ||||
5191 | NumRecords < OpNum + 3 || NumRecords > OpNum + 5) | ||||
5192 | return error("Invalid record"); | ||||
5193 | |||||
5194 | const AtomicOrdering SuccessOrdering = | ||||
5195 | getDecodedOrdering(Record[OpNum + 1]); | ||||
5196 | if (SuccessOrdering == AtomicOrdering::NotAtomic || | ||||
5197 | SuccessOrdering == AtomicOrdering::Unordered) | ||||
5198 | return error("Invalid record"); | ||||
5199 | |||||
5200 | const SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 2]); | ||||
5201 | |||||
5202 | if (Error Err = typeCheckLoadStoreInst(Cmp->getType(), Ptr->getType())) | ||||
5203 | return Err; | ||||
5204 | |||||
5205 | const AtomicOrdering FailureOrdering = | ||||
5206 | NumRecords < 7 | ||||
5207 | ? AtomicCmpXchgInst::getStrongestFailureOrdering(SuccessOrdering) | ||||
5208 | : getDecodedOrdering(Record[OpNum + 3]); | ||||
5209 | |||||
5210 | if (FailureOrdering == AtomicOrdering::NotAtomic || | ||||
5211 | FailureOrdering == AtomicOrdering::Unordered) | ||||
5212 | return error("Invalid record"); | ||||
5213 | |||||
5214 | const Align Alignment( | ||||
5215 | TheModule->getDataLayout().getTypeStoreSize(Cmp->getType())); | ||||
5216 | |||||
5217 | I = new AtomicCmpXchgInst(Ptr, Cmp, New, Alignment, SuccessOrdering, | ||||
5218 | FailureOrdering, SSID); | ||||
5219 | cast<AtomicCmpXchgInst>(I)->setVolatile(Record[OpNum]); | ||||
5220 | |||||
5221 | if (NumRecords < 8) { | ||||
5222 | // Before weak cmpxchgs existed, the instruction simply returned the | ||||
5223 | // value loaded from memory, so bitcode files from that era will be | ||||
5224 | // expecting the first component of a modern cmpxchg. | ||||
5225 | CurBB->getInstList().push_back(I); | ||||
5226 | I = ExtractValueInst::Create(I, 0); | ||||
5227 | } else { | ||||
5228 | cast<AtomicCmpXchgInst>(I)->setWeak(Record[OpNum + 4]); | ||||
5229 | } | ||||
5230 | |||||
5231 | InstructionList.push_back(I); | ||||
5232 | break; | ||||
5233 | } | ||||
5234 | case bitc::FUNC_CODE_INST_CMPXCHG: { | ||||
5235 | // CMPXCHG: [ptrty, ptr, cmp, val, vol, success_ordering, synchscope, | ||||
5236 | // failure_ordering, weak, align?] | ||||
5237 | const size_t NumRecords = Record.size(); | ||||
5238 | unsigned OpNum = 0; | ||||
5239 | Value *Ptr = nullptr; | ||||
5240 | if (getValueTypePair(Record, OpNum, NextValueNo, Ptr)) | ||||
5241 | return error("Invalid record"); | ||||
5242 | |||||
5243 | if (!isa<PointerType>(Ptr->getType())) | ||||
5244 | return error("Cmpxchg operand is not a pointer type"); | ||||
5245 | |||||
5246 | Value *Cmp = nullptr; | ||||
5247 | if (getValueTypePair(Record, OpNum, NextValueNo, Cmp)) | ||||
5248 | return error("Invalid record"); | ||||
5249 | |||||
5250 | Value *Val = nullptr; | ||||
5251 | if (popValue(Record, OpNum, NextValueNo, Cmp->getType(), Val)) | ||||
5252 | return error("Invalid record"); | ||||
5253 | |||||
5254 | if (NumRecords < OpNum + 3 || NumRecords > OpNum + 6) | ||||
5255 | return error("Invalid record"); | ||||
5256 | |||||
5257 | const bool IsVol = Record[OpNum]; | ||||
5258 | |||||
5259 | const AtomicOrdering SuccessOrdering = | ||||
5260 | getDecodedOrdering(Record[OpNum + 1]); | ||||
5261 | if (!AtomicCmpXchgInst::isValidSuccessOrdering(SuccessOrdering)) | ||||
5262 | return error("Invalid cmpxchg success ordering"); | ||||
5263 | |||||
5264 | const SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 2]); | ||||
5265 | |||||
5266 | if (Error Err = typeCheckLoadStoreInst(Cmp->getType(), Ptr->getType())) | ||||
5267 | return Err; | ||||
5268 | |||||
5269 | const AtomicOrdering FailureOrdering = | ||||
5270 | getDecodedOrdering(Record[OpNum + 3]); | ||||
5271 | if (!AtomicCmpXchgInst::isValidFailureOrdering(FailureOrdering)) | ||||
5272 | return error("Invalid cmpxchg failure ordering"); | ||||
5273 | |||||
5274 | const bool IsWeak = Record[OpNum + 4]; | ||||
5275 | |||||
5276 | MaybeAlign Alignment; | ||||
5277 | |||||
5278 | if (NumRecords == (OpNum + 6)) { | ||||
5279 | if (Error Err = parseAlignmentValue(Record[OpNum + 5], Alignment)) | ||||
5280 | return Err; | ||||
5281 | } | ||||
5282 | if (!Alignment) | ||||
5283 | Alignment = | ||||
5284 | Align(TheModule->getDataLayout().getTypeStoreSize(Cmp->getType())); | ||||
5285 | |||||
5286 | I = new AtomicCmpXchgInst(Ptr, Cmp, Val, *Alignment, SuccessOrdering, | ||||
5287 | FailureOrdering, SSID); | ||||
5288 | cast<AtomicCmpXchgInst>(I)->setVolatile(IsVol); | ||||
5289 | cast<AtomicCmpXchgInst>(I)->setWeak(IsWeak); | ||||
5290 | |||||
5291 | InstructionList.push_back(I); | ||||
5292 | break; | ||||
5293 | } | ||||
5294 | case bitc::FUNC_CODE_INST_ATOMICRMW_OLD: | ||||
5295 | case bitc::FUNC_CODE_INST_ATOMICRMW: { | ||||
5296 | // ATOMICRMW_OLD: [ptrty, ptr, val, op, vol, ordering, ssid, align?] | ||||
5297 | // ATOMICRMW: [ptrty, ptr, valty, val, op, vol, ordering, ssid, align?] | ||||
5298 | const size_t NumRecords = Record.size(); | ||||
5299 | unsigned OpNum = 0; | ||||
5300 | |||||
5301 | Value *Ptr = nullptr; | ||||
5302 | if (getValueTypePair(Record, OpNum, NextValueNo, Ptr)) | ||||
5303 | return error("Invalid record"); | ||||
5304 | |||||
5305 | if (!isa<PointerType>(Ptr->getType())) | ||||
5306 | return error("Invalid record"); | ||||
5307 | |||||
5308 | Value *Val = nullptr; | ||||
5309 | if (BitCode == bitc::FUNC_CODE_INST_ATOMICRMW_OLD) { | ||||
5310 | if (popValue(Record, OpNum, NextValueNo, | ||||
5311 | cast<PointerType>(Ptr->getType())->getPointerElementType(), | ||||
5312 | Val)) | ||||
5313 | return error("Invalid record"); | ||||
5314 | } else { | ||||
5315 | if (getValueTypePair(Record, OpNum, NextValueNo, Val)) | ||||
5316 | return error("Invalid record"); | ||||
5317 | } | ||||
5318 | |||||
5319 | if (!(NumRecords == (OpNum + 4) || NumRecords == (OpNum + 5))) | ||||
5320 | return error("Invalid record"); | ||||
5321 | |||||
5322 | const AtomicRMWInst::BinOp Operation = | ||||
5323 | getDecodedRMWOperation(Record[OpNum]); | ||||
5324 | if (Operation < AtomicRMWInst::FIRST_BINOP || | ||||
5325 | Operation > AtomicRMWInst::LAST_BINOP) | ||||
5326 | return error("Invalid record"); | ||||
5327 | |||||
5328 | const bool IsVol = Record[OpNum + 1]; | ||||
5329 | |||||
5330 | const AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]); | ||||
5331 | if (Ordering == AtomicOrdering::NotAtomic || | ||||
5332 | Ordering == AtomicOrdering::Unordered) | ||||
5333 | return error("Invalid record"); | ||||
5334 | |||||
5335 | const SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 3]); | ||||
5336 | |||||
5337 | MaybeAlign Alignment; | ||||
5338 | |||||
5339 | if (NumRecords == (OpNum + 5)) { | ||||
5340 | if (Error Err = parseAlignmentValue(Record[OpNum + 4], Alignment)) | ||||
5341 | return Err; | ||||
5342 | } | ||||
5343 | |||||
5344 | if (!Alignment) | ||||
5345 | Alignment = | ||||
5346 | Align(TheModule->getDataLayout().getTypeStoreSize(Val->getType())); | ||||
5347 | |||||
5348 | I = new AtomicRMWInst(Operation, Ptr, Val, *Alignment, Ordering, SSID); | ||||
5349 | cast<AtomicRMWInst>(I)->setVolatile(IsVol); | ||||
5350 | |||||
5351 | InstructionList.push_back(I); | ||||
5352 | break; | ||||
5353 | } | ||||
5354 | case bitc::FUNC_CODE_INST_FENCE: { // FENCE:[ordering, ssid] | ||||
5355 | if (2 != Record.size()) | ||||
5356 | return error("Invalid record"); | ||||
5357 | AtomicOrdering Ordering = getDecodedOrdering(Record[0]); | ||||
5358 | if (Ordering == AtomicOrdering::NotAtomic || | ||||
5359 | Ordering == AtomicOrdering::Unordered || | ||||
5360 | Ordering == AtomicOrdering::Monotonic) | ||||
5361 | return error("Invalid record"); | ||||
5362 | SyncScope::ID SSID = getDecodedSyncScopeID(Record[1]); | ||||
5363 | I = new FenceInst(Context, Ordering, SSID); | ||||
5364 | InstructionList.push_back(I); | ||||
5365 | break; | ||||
5366 | } | ||||
5367 | case bitc::FUNC_CODE_INST_CALL: { | ||||
5368 | // CALL: [paramattrs, cc, fmf, fnty, fnid, arg0, arg1...] | ||||
5369 | if (Record.size() < 3) | ||||
5370 | return error("Invalid record"); | ||||
5371 | |||||
5372 | unsigned OpNum = 0; | ||||
5373 | AttributeList PAL = getAttributes(Record[OpNum++]); | ||||
5374 | unsigned CCInfo = Record[OpNum++]; | ||||
5375 | |||||
5376 | FastMathFlags FMF; | ||||
5377 | if ((CCInfo >> bitc::CALL_FMF) & 1) { | ||||
5378 | FMF = getDecodedFastMathFlags(Record[OpNum++]); | ||||
5379 | if (!FMF.any()) | ||||
5380 | return error("Fast math flags indicator set for call with no FMF"); | ||||
5381 | } | ||||
5382 | |||||
5383 | FunctionType *FTy = nullptr; | ||||
5384 | if ((CCInfo >> bitc::CALL_EXPLICIT_TYPE) & 1) { | ||||
5385 | FTy = dyn_cast<FunctionType>(getTypeByID(Record[OpNum++])); | ||||
5386 | if (!FTy) | ||||
5387 | return error("Explicit call type is not a function type"); | ||||
5388 | } | ||||
5389 | |||||
5390 | Value *Callee; | ||||
5391 | if (getValueTypePair(Record, OpNum, NextValueNo, Callee)) | ||||
5392 | return error("Invalid record"); | ||||
5393 | |||||
5394 | PointerType *OpTy = dyn_cast<PointerType>(Callee->getType()); | ||||
5395 | if (!OpTy) | ||||
5396 | return error("Callee is not a pointer type"); | ||||
5397 | if (!FTy) { | ||||
5398 | FTy = | ||||
5399 | dyn_cast<FunctionType>(Callee->getType()->getPointerElementType()); | ||||
5400 | if (!FTy) | ||||
5401 | return error("Callee is not of pointer to function type"); | ||||
5402 | } else if (!OpTy->isOpaqueOrPointeeTypeMatches(FTy)) | ||||
5403 | return error("Explicit call type does not match pointee type of " | ||||
5404 | "callee operand"); | ||||
5405 | if (Record.size() < FTy->getNumParams() + OpNum) | ||||
5406 | return error("Insufficient operands to call"); | ||||
5407 | |||||
5408 | SmallVector<Value*, 16> Args; | ||||
5409 | SmallVector<Type *, 16> ArgsTys; | ||||
5410 | // Read the fixed params. | ||||
5411 | for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) { | ||||
5412 | if (FTy->getParamType(i)->isLabelTy()) | ||||
5413 | Args.push_back(getBasicBlock(Record[OpNum])); | ||||
5414 | else | ||||
5415 | Args.push_back(getValue(Record, OpNum, NextValueNo, | ||||
5416 | FTy->getParamType(i))); | ||||
5417 | ArgsTys.push_back(FTy->getParamType(i)); | ||||
5418 | if (!Args.back()) | ||||
5419 | return error("Invalid record"); | ||||
5420 | } | ||||
5421 | |||||
5422 | // Read type/value pairs for varargs params. | ||||
5423 | if (!FTy->isVarArg()) { | ||||
5424 | if (OpNum != Record.size()) | ||||
5425 | return error("Invalid record"); | ||||
5426 | } else { | ||||
5427 | while (OpNum != Record.size()) { | ||||
5428 | Value *Op; | ||||
5429 | if (getValueTypePair(Record, OpNum, NextValueNo, Op)) | ||||
5430 | return error("Invalid record"); | ||||
5431 | Args.push_back(Op); | ||||
5432 | ArgsTys.push_back(Op->getType()); | ||||
5433 | } | ||||
5434 | } | ||||
5435 | |||||
5436 | I = CallInst::Create(FTy, Callee, Args, OperandBundles); | ||||
5437 | OperandBundles.clear(); | ||||
5438 | InstructionList.push_back(I); | ||||
5439 | cast<CallInst>(I)->setCallingConv( | ||||
5440 | static_cast<CallingConv::ID>((0x7ff & CCInfo) >> bitc::CALL_CCONV)); | ||||
5441 | CallInst::TailCallKind TCK = CallInst::TCK_None; | ||||
5442 | if (CCInfo & 1 << bitc::CALL_TAIL) | ||||
5443 | TCK = CallInst::TCK_Tail; | ||||
5444 | if (CCInfo & (1 << bitc::CALL_MUSTTAIL)) | ||||
5445 | TCK = CallInst::TCK_MustTail; | ||||
5446 | if (CCInfo & (1 << bitc::CALL_NOTAIL)) | ||||
5447 | TCK = CallInst::TCK_NoTail; | ||||
5448 | cast<CallInst>(I)->setTailCallKind(TCK); | ||||
5449 | cast<CallInst>(I)->setAttributes(PAL); | ||||
5450 | propagateAttributeTypes(cast<CallBase>(I), ArgsTys); | ||||
5451 | if (FMF.any()) { | ||||
5452 | if (!isa<FPMathOperator>(I)) | ||||
5453 | return error("Fast-math-flags specified for call without " | ||||
5454 | "floating-point scalar or vector return type"); | ||||
5455 | I->setFastMathFlags(FMF); | ||||
5456 | } | ||||
5457 | break; | ||||
5458 | } | ||||
5459 | case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty] | ||||
5460 | if (Record.size() < 3) | ||||
5461 | return error("Invalid record"); | ||||
5462 | Type *OpTy = getTypeByID(Record[0]); | ||||
5463 | Value *Op = getValue(Record, 1, NextValueNo, OpTy); | ||||
5464 | Type *ResTy = getTypeByID(Record[2]); | ||||
5465 | if (!OpTy || !Op || !ResTy) | ||||
5466 | return error("Invalid record"); | ||||
5467 | I = new VAArgInst(Op, ResTy); | ||||
5468 | InstructionList.push_back(I); | ||||
5469 | break; | ||||
5470 | } | ||||
5471 | |||||
5472 | case bitc::FUNC_CODE_OPERAND_BUNDLE: { | ||||
5473 | // A call or an invoke can be optionally prefixed with some variable | ||||
5474 | // number of operand bundle blocks. These blocks are read into | ||||
5475 | // OperandBundles and consumed at the next call or invoke instruction. | ||||
5476 | |||||
5477 | if (Record.empty() || Record[0] >= BundleTags.size()) | ||||
5478 | return error("Invalid record"); | ||||
5479 | |||||
5480 | std::vector<Value *> Inputs; | ||||
5481 | |||||
5482 | unsigned OpNum = 1; | ||||
5483 | while (OpNum != Record.size()) { | ||||
5484 | Value *Op; | ||||
5485 | if (getValueTypePair(Record, OpNum, NextValueNo, Op)) | ||||
5486 | return error("Invalid record"); | ||||
5487 | Inputs.push_back(Op); | ||||
5488 | } | ||||
5489 | |||||
5490 | OperandBundles.emplace_back(BundleTags[Record[0]], std::move(Inputs)); | ||||
5491 | continue; | ||||
5492 | } | ||||
5493 | |||||
5494 | case bitc::FUNC_CODE_INST_FREEZE: { // FREEZE: [opty,opval] | ||||
5495 | unsigned OpNum = 0; | ||||
5496 | Value *Op = nullptr; | ||||
5497 | if (getValueTypePair(Record, OpNum, NextValueNo, Op)) | ||||
5498 | return error("Invalid record"); | ||||
5499 | if (OpNum != Record.size()) | ||||
5500 | return error("Invalid record"); | ||||
5501 | |||||
5502 | I = new FreezeInst(Op); | ||||
5503 | InstructionList.push_back(I); | ||||
5504 | break; | ||||
5505 | } | ||||
5506 | } | ||||
5507 | |||||
5508 | // Add instruction to end of current BB. If there is no current BB, reject | ||||
5509 | // this file. | ||||
5510 | if (!CurBB) { | ||||
5511 | I->deleteValue(); | ||||
5512 | return error("Invalid instruction with no BB"); | ||||
5513 | } | ||||
5514 | if (!OperandBundles.empty()) { | ||||
5515 | I->deleteValue(); | ||||
5516 | return error("Operand bundles found with no consumer"); | ||||
5517 | } | ||||
5518 | CurBB->getInstList().push_back(I); | ||||
5519 | |||||
5520 | // If this was a terminator instruction, move to the next block. | ||||
5521 | if (I->isTerminator()) { | ||||
5522 | ++CurBBNo; | ||||
5523 | CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : nullptr; | ||||
5524 | } | ||||
5525 | |||||
5526 | // Non-void values get registered in the value table for future use. | ||||
5527 | if (!I->getType()->isVoidTy()) | ||||
5528 | ValueList.assignValue(I, NextValueNo++); | ||||
5529 | } | ||||
5530 | |||||
5531 | OutOfRecordLoop: | ||||
5532 | |||||
5533 | if (!OperandBundles.empty()) | ||||
5534 | return error("Operand bundles found with no consumer"); | ||||
5535 | |||||
5536 | // Check the function list for unresolved values. | ||||
5537 | if (Argument *A = dyn_cast<Argument>(ValueList.back())) { | ||||
5538 | if (!A->getParent()) { | ||||
5539 | // We found at least one unresolved value. Nuke them all to avoid leaks. | ||||
5540 | for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){ | ||||
5541 | if ((A = dyn_cast_or_null<Argument>(ValueList[i])) && !A->getParent()) { | ||||
5542 | A->replaceAllUsesWith(UndefValue::get(A->getType())); | ||||
5543 | delete A; | ||||
5544 | } | ||||
5545 | } | ||||
5546 | return error("Never resolved value found in function"); | ||||
5547 | } | ||||
5548 | } | ||||
5549 | |||||
5550 | // Unexpected unresolved metadata about to be dropped. | ||||
5551 | if (MDLoader->hasFwdRefs()) | ||||
5552 | return error("Invalid function metadata: outgoing forward refs"); | ||||
5553 | |||||
5554 | // Trim the value list down to the size it was before we parsed this function. | ||||
5555 | ValueList.shrinkTo(ModuleValueListSize); | ||||
5556 | MDLoader->shrinkTo(ModuleMDLoaderSize); | ||||
5557 | std::vector<BasicBlock*>().swap(FunctionBBs); | ||||
5558 | return Error::success(); | ||||
5559 | } | ||||
5560 | |||||
5561 | /// Find the function body in the bitcode stream | ||||
5562 | Error BitcodeReader::findFunctionInStream( | ||||
5563 | Function *F, | ||||
5564 | DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator) { | ||||
5565 | while (DeferredFunctionInfoIterator->second == 0) { | ||||
5566 | // This is the fallback handling for the old format bitcode that | ||||
5567 | // didn't contain the function index in the VST, or when we have | ||||
5568 | // an anonymous function which would not have a VST entry. | ||||
5569 | // Assert that we have one of those two cases. | ||||
5570 | assert(VSTOffset == 0 || !F->hasName())(static_cast <bool> (VSTOffset == 0 || !F->hasName() ) ? void (0) : __assert_fail ("VSTOffset == 0 || !F->hasName()" , "llvm/lib/Bitcode/Reader/BitcodeReader.cpp", 5570, __extension__ __PRETTY_FUNCTION__)); | ||||
5571 | // Parse the next body in the stream and set its position in the | ||||
5572 | // DeferredFunctionInfo map. | ||||
5573 | if (Error Err = rememberAndSkipFunctionBodies()) | ||||
5574 | return Err; | ||||
5575 | } | ||||
5576 | return Error::success(); | ||||
5577 | } | ||||
5578 | |||||
5579 | SyncScope::ID BitcodeReader::getDecodedSyncScopeID(unsigned Val) { | ||||
5580 | if (Val == SyncScope::SingleThread || Val == SyncScope::System) | ||||
5581 | return SyncScope::ID(Val); | ||||
5582 | if (Val >= SSIDs.size()) | ||||
5583 | return SyncScope::System; // Map unknown synchronization scopes to system. | ||||
5584 | return SSIDs[Val]; | ||||
5585 | } | ||||
5586 | |||||
5587 | //===----------------------------------------------------------------------===// | ||||
5588 | // GVMaterializer implementation | ||||
5589 | //===----------------------------------------------------------------------===// | ||||
5590 | |||||
5591 | Error BitcodeReader::materialize(GlobalValue *GV) { | ||||
5592 | Function *F = dyn_cast<Function>(GV); | ||||
5593 | // If it's not a function or is already material, ignore the request. | ||||
5594 | if (!F || !F->isMaterializable()) | ||||
5595 | return Error::success(); | ||||
5596 | |||||
5597 | DenseMap<Function*, uint64_t>::iterator DFII = DeferredFunctionInfo.find(F); | ||||
5598 | assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!")(static_cast <bool> (DFII != DeferredFunctionInfo.end() && "Deferred function not found!") ? void (0) : __assert_fail ("DFII != DeferredFunctionInfo.end() && \"Deferred function not found!\"" , "llvm/lib/Bitcode/Reader/BitcodeReader.cpp", 5598, __extension__ __PRETTY_FUNCTION__)); | ||||
5599 | // If its position is recorded as 0, its body is somewhere in the stream | ||||
5600 | // but we haven't seen it yet. | ||||
5601 | if (DFII->second == 0) | ||||
5602 | if (Error Err = findFunctionInStream(F, DFII)) | ||||
5603 | return Err; | ||||
5604 | |||||
5605 | // Materialize metadata before parsing any function bodies. | ||||
5606 | if (Error Err = materializeMetadata()) | ||||
5607 | return Err; | ||||
5608 | |||||
5609 | // Move the bit stream to the saved position of the deferred function body. | ||||
5610 | if (Error JumpFailed = Stream.JumpToBit(DFII->second)) | ||||
5611 | return JumpFailed; | ||||
5612 | if (Error Err = parseFunctionBody(F)) | ||||
5613 | return Err; | ||||
5614 | F->setIsMaterializable(false); | ||||
5615 | |||||
5616 | if (StripDebugInfo) | ||||
5617 | stripDebugInfo(*F); | ||||
5618 | |||||
5619 | // Upgrade any old intrinsic calls in the function. | ||||
5620 | for (auto &I : UpgradedIntrinsics) { | ||||
5621 | for (User *U : llvm::make_early_inc_range(I.first->materialized_users())) | ||||
5622 | if (CallInst *CI = dyn_cast<CallInst>(U)) | ||||
5623 | UpgradeIntrinsicCall(CI, I.second); | ||||
5624 | } | ||||
5625 | |||||
5626 | // Update calls to the remangled intrinsics | ||||
5627 | for (auto &I : RemangledIntrinsics) | ||||
5628 | for (User *U : llvm::make_early_inc_range(I.first->materialized_users())) | ||||
5629 | // Don't expect any other users than call sites | ||||
5630 | cast<CallBase>(U)->setCalledFunction(I.second); | ||||
5631 | |||||
5632 | // Finish fn->subprogram upgrade for materialized functions. | ||||
5633 | if (DISubprogram *SP = MDLoader->lookupSubprogramForFunction(F)) | ||||
5634 | F->setSubprogram(SP); | ||||
5635 | |||||
5636 | // Check if the TBAA Metadata are valid, otherwise we will need to strip them. | ||||
5637 | if (!MDLoader->isStrippingTBAA()) { | ||||
5638 | for (auto &I : instructions(F)) { | ||||
5639 | MDNode *TBAA = I.getMetadata(LLVMContext::MD_tbaa); | ||||
5640 | if (!TBAA || TBAAVerifyHelper.visitTBAAMetadata(I, TBAA)) | ||||
5641 | continue; | ||||
5642 | MDLoader->setStripTBAA(true); | ||||
5643 | stripTBAA(F->getParent()); | ||||
5644 | } | ||||
5645 | } | ||||
5646 | |||||
5647 | for (auto &I : instructions(F)) { | ||||
5648 | // "Upgrade" older incorrect branch weights by dropping them. | ||||
5649 | if (auto *MD = I.getMetadata(LLVMContext::MD_prof)) { | ||||
5650 | if (MD->getOperand(0) != nullptr && isa<MDString>(MD->getOperand(0))) { | ||||
5651 | MDString *MDS = cast<MDString>(MD->getOperand(0)); | ||||
5652 | StringRef ProfName = MDS->getString(); | ||||
5653 | // Check consistency of !prof branch_weights metadata. | ||||
5654 | if (!ProfName.equals("branch_weights")) | ||||
5655 | continue; | ||||
5656 | unsigned ExpectedNumOperands = 0; | ||||
5657 | if (BranchInst *BI = dyn_cast<BranchInst>(&I)) | ||||
5658 | ExpectedNumOperands = BI->getNumSuccessors(); | ||||
5659 | else if (SwitchInst *SI = dyn_cast<SwitchInst>(&I)) | ||||
5660 | ExpectedNumOperands = SI->getNumSuccessors(); | ||||
5661 | else if (isa<CallInst>(&I)) | ||||
5662 | ExpectedNumOperands = 1; | ||||
5663 | else if (IndirectBrInst *IBI = dyn_cast<IndirectBrInst>(&I)) | ||||
5664 | ExpectedNumOperands = IBI->getNumDestinations(); | ||||
5665 | else if (isa<SelectInst>(&I)) | ||||
5666 | ExpectedNumOperands = 2; | ||||
5667 | else | ||||
5668 | continue; // ignore and continue. | ||||
5669 | |||||
5670 | // If branch weight doesn't match, just strip branch weight. | ||||
5671 | if (MD->getNumOperands() != 1 + ExpectedNumOperands) | ||||
5672 | I.setMetadata(LLVMContext::MD_prof, nullptr); | ||||
5673 | } | ||||
5674 | } | ||||
5675 | |||||
5676 | // Remove incompatible attributes on function calls. | ||||
5677 | if (auto *CI = dyn_cast<CallBase>(&I)) { | ||||
5678 | CI->removeRetAttrs(AttributeFuncs::typeIncompatible( | ||||
5679 | CI->getFunctionType()->getReturnType())); | ||||
5680 | |||||
5681 | for (unsigned ArgNo = 0; ArgNo < CI->arg_size(); ++ArgNo) | ||||
5682 | CI->removeParamAttrs(ArgNo, AttributeFuncs::typeIncompatible( | ||||
5683 | CI->getArgOperand(ArgNo)->getType())); | ||||
5684 | } | ||||
5685 | } | ||||
5686 | |||||
5687 | // Look for functions that rely on old function attribute behavior. | ||||
5688 | UpgradeFunctionAttributes(*F); | ||||
5689 | |||||
5690 | // Bring in any functions that this function forward-referenced via | ||||
5691 | // blockaddresses. | ||||
5692 | return materializeForwardReferencedFunctions(); | ||||
5693 | } | ||||
5694 | |||||
5695 | Error BitcodeReader::materializeModule() { | ||||
5696 | if (Error Err = materializeMetadata()) | ||||
5697 | return Err; | ||||
5698 | |||||
5699 | // Promise to materialize all forward references. | ||||
5700 | WillMaterializeAllForwardRefs = true; | ||||
5701 | |||||
5702 | // Iterate over the module, deserializing any functions that are still on | ||||
5703 | // disk. | ||||
5704 | for (Function &F : *TheModule) { | ||||
5705 | if (Error Err = materialize(&F)) | ||||
5706 | return Err; | ||||
5707 | } | ||||
5708 | // At this point, if there are any function bodies, parse the rest of | ||||
5709 | // the bits in the module past the last function block we have recorded | ||||
5710 | // through either lazy scanning or the VST. | ||||
5711 | if (LastFunctionBlockBit || NextUnreadBit) | ||||
5712 | if (Error Err = parseModule(LastFunctionBlockBit > NextUnreadBit | ||||
5713 | ? LastFunctionBlockBit | ||||
5714 | : NextUnreadBit)) | ||||
5715 | return Err; | ||||
5716 | |||||
5717 | // Check that all block address forward references got resolved (as we | ||||
5718 | // promised above). | ||||
5719 | if (!BasicBlockFwdRefs.empty()) | ||||
5720 | return error("Never resolved function from blockaddress"); | ||||
5721 | |||||
5722 | // Upgrade any intrinsic calls that slipped through (should not happen!) and | ||||
5723 | // delete the old functions to clean up. We can't do this unless the entire | ||||
5724 | // module is materialized because there could always be another function body | ||||
5725 | // with calls to the old function. | ||||
5726 | for (auto &I : UpgradedIntrinsics) { | ||||
5727 | for (auto *U : I.first->users()) { | ||||
5728 | if (CallInst *CI = dyn_cast<CallInst>(U)) | ||||
5729 | UpgradeIntrinsicCall(CI, I.second); | ||||
5730 | } | ||||
5731 | if (!I.first->use_empty()) | ||||
5732 | I.first->replaceAllUsesWith(I.second); | ||||
5733 | I.first->eraseFromParent(); | ||||
5734 | } | ||||
5735 | UpgradedIntrinsics.clear(); | ||||
5736 | // Do the same for remangled intrinsics | ||||
5737 | for (auto &I : RemangledIntrinsics) { | ||||
5738 | I.first->replaceAllUsesWith(I.second); | ||||
5739 | I.first->eraseFromParent(); | ||||
5740 | } | ||||
5741 | RemangledIntrinsics.clear(); | ||||
5742 | |||||
5743 | UpgradeDebugInfo(*TheModule); | ||||
5744 | |||||
5745 | UpgradeModuleFlags(*TheModule); | ||||
5746 | |||||
5747 | UpgradeARCRuntime(*TheModule); | ||||
5748 | |||||
5749 | return Error::success(); | ||||
5750 | } | ||||
5751 | |||||
5752 | std::vector<StructType *> BitcodeReader::getIdentifiedStructTypes() const { | ||||
5753 | return IdentifiedStructTypes; | ||||
5754 | } | ||||
5755 | |||||
5756 | ModuleSummaryIndexBitcodeReader::ModuleSummaryIndexBitcodeReader( | ||||
5757 | BitstreamCursor Cursor, StringRef Strtab, ModuleSummaryIndex &TheIndex, | ||||
5758 | StringRef ModulePath, unsigned ModuleId) | ||||
5759 | : BitcodeReaderBase(std::move(Cursor), Strtab), TheIndex(TheIndex), | ||||
5760 | ModulePath(ModulePath), ModuleId(ModuleId) {} | ||||
5761 | |||||
5762 | void ModuleSummaryIndexBitcodeReader::addThisModule() { | ||||
5763 | TheIndex.addModule(ModulePath, ModuleId); | ||||
5764 | } | ||||
5765 | |||||
5766 | ModuleSummaryIndex::ModuleInfo * | ||||
5767 | ModuleSummaryIndexBitcodeReader::getThisModule() { | ||||
5768 | return TheIndex.getModule(ModulePath); | ||||
5769 | } | ||||
5770 | |||||
5771 | std::pair<ValueInfo, GlobalValue::GUID> | ||||
5772 | ModuleSummaryIndexBitcodeReader::getValueInfoFromValueId(unsigned ValueId) { | ||||
5773 | auto VGI = ValueIdToValueInfoMap[ValueId]; | ||||
5774 | assert(VGI.first)(static_cast <bool> (VGI.first) ? void (0) : __assert_fail ("VGI.first", "llvm/lib/Bitcode/Reader/BitcodeReader.cpp", 5774 , __extension__ __PRETTY_FUNCTION__)); | ||||
5775 | return VGI; | ||||
5776 | } | ||||
5777 | |||||
5778 | void ModuleSummaryIndexBitcodeReader::setValueGUID( | ||||
5779 | uint64_t ValueID, StringRef ValueName, GlobalValue::LinkageTypes Linkage, | ||||
5780 | StringRef SourceFileName) { | ||||
5781 | std::string GlobalId = | ||||
5782 | GlobalValue::getGlobalIdentifier(ValueName, Linkage, SourceFileName); | ||||
5783 | auto ValueGUID = GlobalValue::getGUID(GlobalId); | ||||
5784 | auto OriginalNameID = ValueGUID; | ||||
5785 | if (GlobalValue::isLocalLinkage(Linkage)) | ||||
5786 | OriginalNameID = GlobalValue::getGUID(ValueName); | ||||
5787 | if (PrintSummaryGUIDs) | ||||
5788 | dbgs() << "GUID " << ValueGUID << "(" << OriginalNameID << ") is " | ||||
5789 | << ValueName << "\n"; | ||||
5790 | |||||
5791 | // UseStrtab is false for legacy summary formats and value names are | ||||
5792 | // created on stack. In that case we save the name in a string saver in | ||||
5793 | // the index so that the value name can be recorded. | ||||
5794 | ValueIdToValueInfoMap[ValueID] = std::make_pair( | ||||
5795 | TheIndex.getOrInsertValueInfo( | ||||
5796 | ValueGUID, | ||||
5797 | UseStrtab ? ValueName : TheIndex.saveString(ValueName)), | ||||
5798 | OriginalNameID); | ||||
5799 | } | ||||
5800 | |||||
5801 | // Specialized value symbol table parser used when reading module index | ||||
5802 | // blocks where we don't actually create global values. The parsed information | ||||
5803 | // is saved in the bitcode reader for use when later parsing summaries. | ||||
5804 | Error ModuleSummaryIndexBitcodeReader::parseValueSymbolTable( | ||||
5805 | uint64_t Offset, | ||||
5806 | DenseMap<unsigned, GlobalValue::LinkageTypes> &ValueIdToLinkageMap) { | ||||
5807 | // With a strtab the VST is not required to parse the summary. | ||||
5808 | if (UseStrtab) | ||||
5809 | return Error::success(); | ||||
5810 | |||||
5811 | assert(Offset > 0 && "Expected non-zero VST offset")(static_cast <bool> (Offset > 0 && "Expected non-zero VST offset" ) ? void (0) : __assert_fail ("Offset > 0 && \"Expected non-zero VST offset\"" , "llvm/lib/Bitcode/Reader/BitcodeReader.cpp", 5811, __extension__ __PRETTY_FUNCTION__)); | ||||
5812 | Expected<uint64_t> MaybeCurrentBit = jumpToValueSymbolTable(Offset, Stream); | ||||
5813 | if (!MaybeCurrentBit) | ||||
5814 | return MaybeCurrentBit.takeError(); | ||||
5815 | uint64_t CurrentBit = MaybeCurrentBit.get(); | ||||
5816 | |||||
5817 | if (Error Err = Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID)) | ||||
5818 | return Err; | ||||
5819 | |||||
5820 | SmallVector<uint64_t, 64> Record; | ||||
5821 | |||||
5822 | // Read all the records for this value table. | ||||
5823 | SmallString<128> ValueName; | ||||
5824 | |||||
5825 | while (true) { | ||||
5826 | Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks(); | ||||
5827 | if (!MaybeEntry) | ||||
5828 | return MaybeEntry.takeError(); | ||||
5829 | BitstreamEntry Entry = MaybeEntry.get(); | ||||
5830 | |||||
5831 | switch (Entry.Kind) { | ||||
5832 | case BitstreamEntry::SubBlock: // Handled for us already. | ||||
5833 | case BitstreamEntry::Error: | ||||
5834 | return error("Malformed block"); | ||||
5835 | case BitstreamEntry::EndBlock: | ||||
5836 | // Done parsing VST, jump back to wherever we came from. | ||||
5837 | if (Error JumpFailed = Stream.JumpToBit(CurrentBit)) | ||||
5838 | return JumpFailed; | ||||
5839 | return Error::success(); | ||||
5840 | case BitstreamEntry::Record: | ||||
5841 | // The interesting case. | ||||
5842 | break; | ||||
5843 | } | ||||
5844 | |||||
5845 | // Read a record. | ||||
5846 | Record.clear(); | ||||
5847 | Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record); | ||||
5848 | if (!MaybeRecord) | ||||
5849 | return MaybeRecord.takeError(); | ||||
5850 | switch (MaybeRecord.get()) { | ||||
5851 | default: // Default behavior: ignore (e.g. VST_CODE_BBENTRY records). | ||||
5852 | break; | ||||
5853 | case bitc::VST_CODE_ENTRY: { // VST_CODE_ENTRY: [valueid, namechar x N] | ||||
5854 | if (convertToString(Record, 1, ValueName)) | ||||
5855 | return error("Invalid record"); | ||||
5856 | unsigned ValueID = Record[0]; | ||||
5857 | assert(!SourceFileName.empty())(static_cast <bool> (!SourceFileName.empty()) ? void (0 ) : __assert_fail ("!SourceFileName.empty()", "llvm/lib/Bitcode/Reader/BitcodeReader.cpp" , 5857, __extension__ __PRETTY_FUNCTION__)); | ||||
5858 | auto VLI = ValueIdToLinkageMap.find(ValueID); | ||||
5859 | assert(VLI != ValueIdToLinkageMap.end() &&(static_cast <bool> (VLI != ValueIdToLinkageMap.end() && "No linkage found for VST entry?") ? void (0) : __assert_fail ("VLI != ValueIdToLinkageMap.end() && \"No linkage found for VST entry?\"" , "llvm/lib/Bitcode/Reader/BitcodeReader.cpp", 5860, __extension__ __PRETTY_FUNCTION__)) | ||||
5860 | "No linkage found for VST entry?")(static_cast <bool> (VLI != ValueIdToLinkageMap.end() && "No linkage found for VST entry?") ? void (0) : __assert_fail ("VLI != ValueIdToLinkageMap.end() && \"No linkage found for VST entry?\"" , "llvm/lib/Bitcode/Reader/BitcodeReader.cpp", 5860, __extension__ __PRETTY_FUNCTION__)); | ||||
5861 | auto Linkage = VLI->second; | ||||
5862 | setValueGUID(ValueID, ValueName, Linkage, SourceFileName); | ||||
5863 | ValueName.clear(); | ||||
5864 | break; | ||||
5865 | } | ||||
5866 | case bitc::VST_CODE_FNENTRY: { | ||||
5867 | // VST_CODE_FNENTRY: [valueid, offset, namechar x N] | ||||
5868 | if (convertToString(Record, 2, ValueName)) | ||||
5869 | return error("Invalid record"); | ||||
5870 | unsigned ValueID = Record[0]; | ||||
5871 | assert(!SourceFileName.empty())(static_cast <bool> (!SourceFileName.empty()) ? void (0 ) : __assert_fail ("!SourceFileName.empty()", "llvm/lib/Bitcode/Reader/BitcodeReader.cpp" , 5871, __extension__ __PRETTY_FUNCTION__)); | ||||
5872 | auto VLI = ValueIdToLinkageMap.find(ValueID); | ||||
5873 | assert(VLI != ValueIdToLinkageMap.end() &&(static_cast <bool> (VLI != ValueIdToLinkageMap.end() && "No linkage found for VST entry?") ? void (0) : __assert_fail ("VLI != ValueIdToLinkageMap.end() && \"No linkage found for VST entry?\"" , "llvm/lib/Bitcode/Reader/BitcodeReader.cpp", 5874, __extension__ __PRETTY_FUNCTION__)) | ||||
5874 | "No linkage found for VST entry?")(static_cast <bool> (VLI != ValueIdToLinkageMap.end() && "No linkage found for VST entry?") ? void (0) : __assert_fail ("VLI != ValueIdToLinkageMap.end() && \"No linkage found for VST entry?\"" , "llvm/lib/Bitcode/Reader/BitcodeReader.cpp", 5874, __extension__ __PRETTY_FUNCTION__)); | ||||
5875 | auto Linkage = VLI->second; | ||||
5876 | setValueGUID(ValueID, ValueName, Linkage, SourceFileName); | ||||
5877 | ValueName.clear(); | ||||
5878 | break; | ||||
5879 | } | ||||
5880 | case bitc::VST_CODE_COMBINED_ENTRY: { | ||||
5881 | // VST_CODE_COMBINED_ENTRY: [valueid, refguid] | ||||
5882 | unsigned ValueID = Record[0]; | ||||
5883 | GlobalValue::GUID RefGUID = Record[1]; | ||||
5884 | // The "original name", which is the second value of the pair will be | ||||
5885 | // overriden later by a FS_COMBINED_ORIGINAL_NAME in the combined index. | ||||
5886 | ValueIdToValueInfoMap[ValueID] = | ||||
5887 | std::make_pair(TheIndex.getOrInsertValueInfo(RefGUID), RefGUID); | ||||
5888 | break; | ||||
5889 | } | ||||
5890 | } | ||||
5891 | } | ||||
5892 | } | ||||
5893 | |||||
5894 | // Parse just the blocks needed for building the index out of the module. | ||||
5895 | // At the end of this routine the module Index is populated with a map | ||||
5896 | // from global value id to GlobalValueSummary objects. | ||||
5897 | Error ModuleSummaryIndexBitcodeReader::parseModule() { | ||||
5898 | if (Error Err = Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID)) | ||||
5899 | return Err; | ||||
5900 | |||||
5901 | SmallVector<uint64_t, 64> Record; | ||||
5902 | DenseMap<unsigned, GlobalValue::LinkageTypes> ValueIdToLinkageMap; | ||||
5903 | unsigned ValueId = 0; | ||||
5904 | |||||
5905 | // Read the index for this module. | ||||
5906 | while (true) { | ||||
5907 | Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance(); | ||||
5908 | if (!MaybeEntry) | ||||
5909 | return MaybeEntry.takeError(); | ||||
5910 | llvm::BitstreamEntry Entry = MaybeEntry.get(); | ||||
5911 | |||||
5912 | switch (Entry.Kind) { | ||||
5913 | case BitstreamEntry::Error: | ||||
5914 | return error("Malformed block"); | ||||
5915 | case BitstreamEntry::EndBlock: | ||||
5916 | return Error::success(); | ||||
5917 | |||||
5918 | case BitstreamEntry::SubBlock: | ||||
5919 | switch (Entry.ID) { | ||||
5920 | default: // Skip unknown content. | ||||
5921 | if (Error Err = Stream.SkipBlock()) | ||||
5922 | return Err; | ||||
5923 | break; | ||||
5924 | case bitc::BLOCKINFO_BLOCK_ID: | ||||
5925 | // Need to parse these to get abbrev ids (e.g. for VST) | ||||
5926 | if (Error Err = readBlockInfo()) | ||||
5927 | return Err; | ||||
5928 | break; | ||||
5929 | case bitc::VALUE_SYMTAB_BLOCK_ID: | ||||
5930 | // Should have been parsed earlier via VSTOffset, unless there | ||||
5931 | // is no summary section. | ||||
5932 | assert(((SeenValueSymbolTable && VSTOffset > 0) ||(static_cast <bool> (((SeenValueSymbolTable && VSTOffset > 0) || !SeenGlobalValSummary) && "Expected early VST parse via VSTOffset record" ) ? void (0) : __assert_fail ("((SeenValueSymbolTable && VSTOffset > 0) || !SeenGlobalValSummary) && \"Expected early VST parse via VSTOffset record\"" , "llvm/lib/Bitcode/Reader/BitcodeReader.cpp", 5934, __extension__ __PRETTY_FUNCTION__)) | ||||
5933 | !SeenGlobalValSummary) &&(static_cast <bool> (((SeenValueSymbolTable && VSTOffset > 0) || !SeenGlobalValSummary) && "Expected early VST parse via VSTOffset record" ) ? void (0) : __assert_fail ("((SeenValueSymbolTable && VSTOffset > 0) || !SeenGlobalValSummary) && \"Expected early VST parse via VSTOffset record\"" , "llvm/lib/Bitcode/Reader/BitcodeReader.cpp", 5934, __extension__ __PRETTY_FUNCTION__)) | ||||
5934 | "Expected early VST parse via VSTOffset record")(static_cast <bool> (((SeenValueSymbolTable && VSTOffset > 0) || !SeenGlobalValSummary) && "Expected early VST parse via VSTOffset record" ) ? void (0) : __assert_fail ("((SeenValueSymbolTable && VSTOffset > 0) || !SeenGlobalValSummary) && \"Expected early VST parse via VSTOffset record\"" , "llvm/lib/Bitcode/Reader/BitcodeReader.cpp", 5934, __extension__ __PRETTY_FUNCTION__)); | ||||
5935 | if (Error Err = Stream.SkipBlock()) | ||||
5936 | return Err; | ||||
5937 | break; | ||||
5938 | case bitc::GLOBALVAL_SUMMARY_BLOCK_ID: | ||||
5939 | case bitc::FULL_LTO_GLOBALVAL_SUMMARY_BLOCK_ID: | ||||
5940 | // Add the module if it is a per-module index (has a source file name). | ||||
5941 | if (!SourceFileName.empty()) | ||||
5942 | addThisModule(); | ||||
5943 | assert(!SeenValueSymbolTable &&(static_cast <bool> (!SeenValueSymbolTable && "Already read VST when parsing summary block?" ) ? void (0) : __assert_fail ("!SeenValueSymbolTable && \"Already read VST when parsing summary block?\"" , "llvm/lib/Bitcode/Reader/BitcodeReader.cpp", 5944, __extension__ __PRETTY_FUNCTION__)) | ||||
5944 | "Already read VST when parsing summary block?")(static_cast <bool> (!SeenValueSymbolTable && "Already read VST when parsing summary block?" ) ? void (0) : __assert_fail ("!SeenValueSymbolTable && \"Already read VST when parsing summary block?\"" , "llvm/lib/Bitcode/Reader/BitcodeReader.cpp", 5944, __extension__ __PRETTY_FUNCTION__)); | ||||
5945 | // We might not have a VST if there were no values in the | ||||
5946 | // summary. An empty summary block generated when we are | ||||
5947 | // performing ThinLTO compiles so we don't later invoke | ||||
5948 | // the regular LTO process on them. | ||||
5949 | if (VSTOffset > 0) { | ||||
5950 | if (Error Err = parseValueSymbolTable(VSTOffset, ValueIdToLinkageMap)) | ||||
5951 | return Err; | ||||
5952 | SeenValueSymbolTable = true; | ||||
5953 | } | ||||
5954 | SeenGlobalValSummary = true; | ||||
5955 | if (Error Err = parseEntireSummary(Entry.ID)) | ||||
5956 | return Err; | ||||
5957 | break; | ||||
5958 | case bitc::MODULE_STRTAB_BLOCK_ID: | ||||
5959 | if (Error Err = parseModuleStringTable()) | ||||
5960 | return Err; | ||||
5961 | break; | ||||
5962 | } | ||||
5963 | continue; | ||||
5964 | |||||
5965 | case BitstreamEntry::Record: { | ||||
5966 | Record.clear(); | ||||
5967 | Expected<unsigned> MaybeBitCode = Stream.readRecord(Entry.ID, Record); | ||||
5968 | if (!MaybeBitCode) | ||||
5969 | return MaybeBitCode.takeError(); | ||||
5970 | switch (MaybeBitCode.get()) { | ||||
5971 | default: | ||||
5972 | break; // Default behavior, ignore unknown content. | ||||
5973 | case bitc::MODULE_CODE_VERSION: { | ||||
5974 | if (Error Err = parseVersionRecord(Record).takeError()) | ||||
5975 | return Err; | ||||
5976 | break; | ||||
5977 | } | ||||
5978 | /// MODULE_CODE_SOURCE_FILENAME: [namechar x N] | ||||
5979 | case bitc::MODULE_CODE_SOURCE_FILENAME: { | ||||
5980 | SmallString<128> ValueName; | ||||
5981 | if (convertToString(Record, 0, ValueName)) | ||||
5982 | return error("Invalid record"); | ||||
5983 | SourceFileName = ValueName.c_str(); | ||||
5984 | break; | ||||
5985 | } | ||||
5986 | /// MODULE_CODE_HASH: [5*i32] | ||||
5987 | case bitc::MODULE_CODE_HASH: { | ||||
5988 | if (Record.size() != 5) | ||||
5989 | return error("Invalid hash length " + Twine(Record.size()).str()); | ||||
5990 | auto &Hash = getThisModule()->second.second; | ||||
5991 | int Pos = 0; | ||||
5992 | for (auto &Val : Record) { | ||||
5993 | assert(!(Val >> 32) && "Unexpected high bits set")(static_cast <bool> (!(Val >> 32) && "Unexpected high bits set" ) ? void (0) : __assert_fail ("!(Val >> 32) && \"Unexpected high bits set\"" , "llvm/lib/Bitcode/Reader/BitcodeReader.cpp", 5993, __extension__ __PRETTY_FUNCTION__)); | ||||
5994 | Hash[Pos++] = Val; | ||||
5995 | } | ||||
5996 | break; | ||||
5997 | } | ||||
5998 | /// MODULE_CODE_VSTOFFSET: [offset] | ||||
5999 | case bitc::MODULE_CODE_VSTOFFSET: | ||||
6000 | if (Record.empty()) | ||||
6001 | return error("Invalid record"); | ||||
6002 | // Note that we subtract 1 here because the offset is relative to one | ||||
6003 | // word before the start of the identification or module block, which | ||||
6004 | // was historically always the start of the regular bitcode header. | ||||
6005 | VSTOffset = Record[0] - 1; | ||||
6006 | break; | ||||
6007 | // v1 GLOBALVAR: [pointer type, isconst, initid, linkage, ...] | ||||
6008 | // v1 FUNCTION: [type, callingconv, isproto, linkage, ...] | ||||
6009 | // v1 ALIAS: [alias type, addrspace, aliasee val#, linkage, ...] | ||||
6010 | // v2: [strtab offset, strtab size, v1] | ||||
6011 | case bitc::MODULE_CODE_GLOBALVAR: | ||||
6012 | case bitc::MODULE_CODE_FUNCTION: | ||||
6013 | case bitc::MODULE_CODE_ALIAS: { | ||||
6014 | StringRef Name; | ||||
6015 | ArrayRef<uint64_t> GVRecord; | ||||
6016 | std::tie(Name, GVRecord) = readNameFromStrtab(Record); | ||||
6017 | if (GVRecord.size() <= 3) | ||||
6018 | return error("Invalid record"); | ||||
6019 | uint64_t RawLinkage = GVRecord[3]; | ||||
6020 | GlobalValue::LinkageTypes Linkage = getDecodedLinkage(RawLinkage); | ||||
6021 | if (!UseStrtab) { | ||||
6022 | ValueIdToLinkageMap[ValueId++] = Linkage; | ||||
6023 | break; | ||||
6024 | } | ||||
6025 | |||||
6026 | setValueGUID(ValueId++, Name, Linkage, SourceFileName); | ||||
6027 | break; | ||||
6028 | } | ||||
6029 | } | ||||
6030 | } | ||||
6031 | continue; | ||||
6032 | } | ||||
6033 | } | ||||
6034 | } | ||||
6035 | |||||
6036 | std::vector<ValueInfo> | ||||
6037 | ModuleSummaryIndexBitcodeReader::makeRefList(ArrayRef<uint64_t> Record) { | ||||
6038 | std::vector<ValueInfo> Ret; | ||||
6039 | Ret.reserve(Record.size()); | ||||
6040 | for (uint64_t RefValueId : Record) | ||||
6041 | Ret.push_back(getValueInfoFromValueId(RefValueId).first); | ||||
6042 | return Ret; | ||||
6043 | } | ||||
6044 | |||||
6045 | std::vector<FunctionSummary::EdgeTy> | ||||
6046 | ModuleSummaryIndexBitcodeReader::makeCallList(ArrayRef<uint64_t> Record, | ||||
6047 | bool IsOldProfileFormat, | ||||
6048 | bool HasProfile, bool HasRelBF) { | ||||
6049 | std::vector<FunctionSummary::EdgeTy> Ret; | ||||
6050 | Ret.reserve(Record.size()); | ||||
6051 | for (unsigned I = 0, E = Record.size(); I != E; ++I) { | ||||
6052 | CalleeInfo::HotnessType Hotness = CalleeInfo::HotnessType::Unknown; | ||||
6053 | uint64_t RelBF = 0; | ||||
6054 | ValueInfo Callee = getValueInfoFromValueId(Record[I]).first; | ||||
6055 | if (IsOldProfileFormat) { | ||||
6056 | I += 1; // Skip old callsitecount field | ||||
6057 | if (HasProfile) | ||||
6058 | I += 1; // Skip old profilecount field | ||||
6059 | } else if (HasProfile) | ||||
6060 | Hotness = static_cast<CalleeInfo::HotnessType>(Record[++I]); | ||||
6061 | else if (HasRelBF) | ||||
6062 | RelBF = Record[++I]; | ||||
6063 | Ret.push_back(FunctionSummary::EdgeTy{Callee, CalleeInfo(Hotness, RelBF)}); | ||||
6064 | } | ||||
6065 | return Ret; | ||||
6066 | } | ||||
6067 | |||||
6068 | static void | ||||
6069 | parseWholeProgramDevirtResolutionByArg(ArrayRef<uint64_t> Record, size_t &Slot, | ||||
6070 | WholeProgramDevirtResolution &Wpd) { | ||||
6071 | uint64_t ArgNum = Record[Slot++]; | ||||
6072 | WholeProgramDevirtResolution::ByArg &B = | ||||
6073 | Wpd.ResByArg[{Record.begin() + Slot, Record.begin() + Slot + ArgNum}]; | ||||
6074 | Slot += ArgNum; | ||||
6075 | |||||
6076 | B.TheKind = | ||||
6077 | static_cast<WholeProgramDevirtResolution::ByArg::Kind>(Record[Slot++]); | ||||
6078 | B.Info = Record[Slot++]; | ||||
6079 | B.Byte = Record[Slot++]; | ||||
6080 | B.Bit = Record[Slot++]; | ||||
6081 | } | ||||
6082 | |||||
6083 | static void parseWholeProgramDevirtResolution(ArrayRef<uint64_t> Record, | ||||
6084 | StringRef Strtab, size_t &Slot, | ||||
6085 | TypeIdSummary &TypeId) { | ||||
6086 | uint64_t Id = Record[Slot++]; | ||||
6087 | WholeProgramDevirtResolution &Wpd = TypeId.WPDRes[Id]; | ||||
6088 | |||||
6089 | Wpd.TheKind = static_cast<WholeProgramDevirtResolution::Kind>(Record[Slot++]); | ||||
6090 | Wpd.SingleImplName = {Strtab.data() + Record[Slot], | ||||
6091 | static_cast<size_t>(Record[Slot + 1])}; | ||||
6092 | Slot += 2; | ||||
6093 | |||||
6094 | uint64_t ResByArgNum = Record[Slot++]; | ||||
6095 | for (uint64_t I = 0; I != ResByArgNum; ++I) | ||||
6096 | parseWholeProgramDevirtResolutionByArg(Record, Slot, Wpd); | ||||
6097 | } | ||||
6098 | |||||
6099 | static void parseTypeIdSummaryRecord(ArrayRef<uint64_t> Record, | ||||
6100 | StringRef Strtab, | ||||
6101 | ModuleSummaryIndex &TheIndex) { | ||||
6102 | size_t Slot = 0; | ||||
6103 | TypeIdSummary &TypeId = TheIndex.getOrInsertTypeIdSummary( | ||||
6104 | {Strtab.data() + Record[Slot], static_cast<size_t>(Record[Slot + 1])}); | ||||
6105 | Slot += 2; | ||||
6106 | |||||
6107 | TypeId.TTRes.TheKind = static_cast<TypeTestResolution::Kind>(Record[Slot++]); | ||||
6108 | TypeId.TTRes.SizeM1BitWidth = Record[Slot++]; | ||||
6109 | TypeId.TTRes.AlignLog2 = Record[Slot++]; | ||||
6110 | TypeId.TTRes.SizeM1 = Record[Slot++]; | ||||
6111 | TypeId.TTRes.BitMask = Record[Slot++]; | ||||
6112 | TypeId.TTRes.InlineBits = Record[Slot++]; | ||||
6113 | |||||
6114 | while (Slot < Record.size()) | ||||
6115 | parseWholeProgramDevirtResolution(Record, Strtab, Slot, TypeId); | ||||
6116 | } | ||||
6117 | |||||
6118 | std::vector<FunctionSummary::ParamAccess> | ||||
6119 | ModuleSummaryIndexBitcodeReader::parseParamAccesses(ArrayRef<uint64_t> Record) { | ||||
6120 | auto ReadRange = [&]() { | ||||
6121 | APInt Lower(FunctionSummary::ParamAccess::RangeWidth, | ||||
6122 | BitcodeReader::decodeSignRotatedValue(Record.front())); | ||||
6123 | Record = Record.drop_front(); | ||||
6124 | APInt Upper(FunctionSummary::ParamAccess::RangeWidth, | ||||
6125 | BitcodeReader::decodeSignRotatedValue(Record.front())); | ||||
6126 | Record = Record.drop_front(); | ||||
6127 | ConstantRange Range{Lower, Upper}; | ||||
6128 | assert(!Range.isFullSet())(static_cast <bool> (!Range.isFullSet()) ? void (0) : __assert_fail ("!Range.isFullSet()", "llvm/lib/Bitcode/Reader/BitcodeReader.cpp" , 6128, __extension__ __PRETTY_FUNCTION__)); | ||||
6129 | assert(!Range.isUpperSignWrapped())(static_cast <bool> (!Range.isUpperSignWrapped()) ? void (0) : __assert_fail ("!Range.isUpperSignWrapped()", "llvm/lib/Bitcode/Reader/BitcodeReader.cpp" , 6129, __extension__ __PRETTY_FUNCTION__)); | ||||
6130 | return Range; | ||||
6131 | }; | ||||
6132 | |||||
6133 | std::vector<FunctionSummary::ParamAccess> PendingParamAccesses; | ||||
6134 | while (!Record.empty()) { | ||||
6135 | PendingParamAccesses.emplace_back(); | ||||
6136 | FunctionSummary::ParamAccess &ParamAccess = PendingParamAccesses.back(); | ||||
6137 | ParamAccess.ParamNo = Record.front(); | ||||
6138 | Record = Record.drop_front(); | ||||
6139 | ParamAccess.Use = ReadRange(); | ||||
6140 | ParamAccess.Calls.resize(Record.front()); | ||||
6141 | Record = Record.drop_front(); | ||||
6142 | for (auto &Call : ParamAccess.Calls) { | ||||
6143 | Call.ParamNo = Record.front(); | ||||
6144 | Record = Record.drop_front(); | ||||
6145 | Call.Callee = getValueInfoFromValueId(Record.front()).first; | ||||
6146 | Record = Record.drop_front(); | ||||
6147 | Call.Offsets = ReadRange(); | ||||
6148 | } | ||||
6149 | } | ||||
6150 | return PendingParamAccesses; | ||||
6151 | } | ||||
6152 | |||||
6153 | void ModuleSummaryIndexBitcodeReader::parseTypeIdCompatibleVtableInfo( | ||||
6154 | ArrayRef<uint64_t> Record, size_t &Slot, | ||||
6155 | TypeIdCompatibleVtableInfo &TypeId) { | ||||
6156 | uint64_t Offset = Record[Slot++]; | ||||
6157 | ValueInfo Callee = getValueInfoFromValueId(Record[Slot++]).first; | ||||
6158 | TypeId.push_back({Offset, Callee}); | ||||
6159 | } | ||||
6160 | |||||
6161 | void ModuleSummaryIndexBitcodeReader::parseTypeIdCompatibleVtableSummaryRecord( | ||||
6162 | ArrayRef<uint64_t> Record) { | ||||
6163 | size_t Slot = 0; | ||||
6164 | TypeIdCompatibleVtableInfo &TypeId = | ||||
6165 | TheIndex.getOrInsertTypeIdCompatibleVtableSummary( | ||||
6166 | {Strtab.data() + Record[Slot], | ||||
6167 | static_cast<size_t>(Record[Slot + 1])}); | ||||
6168 | Slot += 2; | ||||
6169 | |||||
6170 | while (Slot < Record.size()) | ||||
6171 | parseTypeIdCompatibleVtableInfo(Record, Slot, TypeId); | ||||
6172 | } | ||||
6173 | |||||
6174 | static void setSpecialRefs(std::vector<ValueInfo> &Refs, unsigned ROCnt, | ||||
6175 | unsigned WOCnt) { | ||||
6176 | // Readonly and writeonly refs are in the end of the refs list. | ||||
6177 | assert(ROCnt + WOCnt <= Refs.size())(static_cast <bool> (ROCnt + WOCnt <= Refs.size()) ? void (0) : __assert_fail ("ROCnt + WOCnt <= Refs.size()", "llvm/lib/Bitcode/Reader/BitcodeReader.cpp", 6177, __extension__ __PRETTY_FUNCTION__)); | ||||
6178 | unsigned FirstWORef = Refs.size() - WOCnt; | ||||
6179 | unsigned RefNo = FirstWORef - ROCnt; | ||||
6180 | for (; RefNo < FirstWORef; ++RefNo) | ||||
6181 | Refs[RefNo].setReadOnly(); | ||||
6182 | for (; RefNo < Refs.size(); ++RefNo) | ||||
6183 | Refs[RefNo].setWriteOnly(); | ||||
6184 | } | ||||
6185 | |||||
6186 | // Eagerly parse the entire summary block. This populates the GlobalValueSummary | ||||
6187 | // objects in the index. | ||||
6188 | Error ModuleSummaryIndexBitcodeReader::parseEntireSummary(unsigned ID) { | ||||
6189 | if (Error Err = Stream.EnterSubBlock(ID)) | ||||
6190 | return Err; | ||||
6191 | SmallVector<uint64_t, 64> Record; | ||||
6192 | |||||
6193 | // Parse version | ||||
6194 | { | ||||
6195 | Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks(); | ||||
6196 | if (!MaybeEntry) | ||||
6197 | return MaybeEntry.takeError(); | ||||
6198 | BitstreamEntry Entry = MaybeEntry.get(); | ||||
6199 | |||||
6200 | if (Entry.Kind != BitstreamEntry::Record) | ||||
6201 | return error("Invalid Summary Block: record for version expected"); | ||||
6202 | Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record); | ||||
6203 | if (!MaybeRecord) | ||||
6204 | return MaybeRecord.takeError(); | ||||
6205 | if (MaybeRecord.get() != bitc::FS_VERSION) | ||||
6206 | return error("Invalid Summary Block: version expected"); | ||||
6207 | } | ||||
6208 | const uint64_t Version = Record[0]; | ||||
6209 | const bool IsOldProfileFormat = Version == 1; | ||||
6210 | if (Version < 1 || Version > ModuleSummaryIndex::BitcodeSummaryVersion) | ||||
6211 | return error("Invalid summary version " + Twine(Version) + | ||||
6212 | ". Version should be in the range [1-" + | ||||
6213 | Twine(ModuleSummaryIndex::BitcodeSummaryVersion) + | ||||
6214 | "]."); | ||||
6215 | Record.clear(); | ||||
6216 | |||||
6217 | // Keep around the last seen summary to be used when we see an optional | ||||
6218 | // "OriginalName" attachement. | ||||
6219 | GlobalValueSummary *LastSeenSummary = nullptr; | ||||
6220 | GlobalValue::GUID LastSeenGUID = 0; | ||||
6221 | |||||
6222 | // We can expect to see any number of type ID information records before | ||||
6223 | // each function summary records; these variables store the information | ||||
6224 | // collected so far so that it can be used to create the summary object. | ||||
6225 | std::vector<GlobalValue::GUID> PendingTypeTests; | ||||
6226 | std::vector<FunctionSummary::VFuncId> PendingTypeTestAssumeVCalls, | ||||
6227 | PendingTypeCheckedLoadVCalls; | ||||
6228 | std::vector<FunctionSummary::ConstVCall> PendingTypeTestAssumeConstVCalls, | ||||
6229 | PendingTypeCheckedLoadConstVCalls; | ||||
6230 | std::vector<FunctionSummary::ParamAccess> PendingParamAccesses; | ||||
6231 | |||||
6232 | while (true) { | ||||
6233 | Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks(); | ||||
6234 | if (!MaybeEntry) | ||||
6235 | return MaybeEntry.takeError(); | ||||
6236 | BitstreamEntry Entry = MaybeEntry.get(); | ||||
6237 | |||||
6238 | switch (Entry.Kind) { | ||||
6239 | case BitstreamEntry::SubBlock: // Handled for us already. | ||||
6240 | case BitstreamEntry::Error: | ||||
6241 | return error("Malformed block"); | ||||
6242 | case BitstreamEntry::EndBlock: | ||||
6243 | return Error::success(); | ||||
6244 | case BitstreamEntry::Record: | ||||
6245 | // The interesting case. | ||||
6246 | break; | ||||
6247 | } | ||||
6248 | |||||
6249 | // Read a record. The record format depends on whether this | ||||
6250 | // is a per-module index or a combined index file. In the per-module | ||||
6251 | // case the records contain the associated value's ID for correlation | ||||
6252 | // with VST entries. In the combined index the correlation is done | ||||
6253 | // via the bitcode offset of the summary records (which were saved | ||||
6254 | // in the combined index VST entries). The records also contain | ||||
6255 | // information used for ThinLTO renaming and importing. | ||||
6256 | Record.clear(); | ||||
6257 | Expected<unsigned> MaybeBitCode = Stream.readRecord(Entry.ID, Record); | ||||
6258 | if (!MaybeBitCode) | ||||
6259 | return MaybeBitCode.takeError(); | ||||
6260 | switch (unsigned BitCode = MaybeBitCode.get()) { | ||||
6261 | default: // Default behavior: ignore. | ||||
6262 | break; | ||||
6263 | case bitc::FS_FLAGS: { // [flags] | ||||
6264 | TheIndex.setFlags(Record[0]); | ||||
6265 | break; | ||||
6266 | } | ||||
6267 | case bitc::FS_VALUE_GUID: { // [valueid, refguid] | ||||
6268 | uint64_t ValueID = Record[0]; | ||||
6269 | GlobalValue::GUID RefGUID = Record[1]; | ||||
6270 | ValueIdToValueInfoMap[ValueID] = | ||||
6271 | std::make_pair(TheIndex.getOrInsertValueInfo(RefGUID), RefGUID); | ||||
6272 | break; | ||||
6273 | } | ||||
6274 | // FS_PERMODULE: [valueid, flags, instcount, fflags, numrefs, | ||||
6275 | // numrefs x valueid, n x (valueid)] | ||||
6276 | // FS_PERMODULE_PROFILE: [valueid, flags, instcount, fflags, numrefs, | ||||
6277 | // numrefs x valueid, | ||||
6278 | // n x (valueid, hotness)] | ||||
6279 | // FS_PERMODULE_RELBF: [valueid, flags, instcount, fflags, numrefs, | ||||
6280 | // numrefs x valueid, | ||||
6281 | // n x (valueid, relblockfreq)] | ||||
6282 | case bitc::FS_PERMODULE: | ||||
6283 | case bitc::FS_PERMODULE_RELBF: | ||||
6284 | case bitc::FS_PERMODULE_PROFILE: { | ||||
6285 | unsigned ValueID = Record[0]; | ||||
6286 | uint64_t RawFlags = Record[1]; | ||||
6287 | unsigned InstCount = Record[2]; | ||||
6288 | uint64_t RawFunFlags = 0; | ||||
6289 | unsigned NumRefs = Record[3]; | ||||
6290 | unsigned NumRORefs = 0, NumWORefs = 0; | ||||
6291 | int RefListStartIndex = 4; | ||||
6292 | if (Version >= 4) { | ||||
6293 | RawFunFlags = Record[3]; | ||||
6294 | NumRefs = Record[4]; | ||||
6295 | RefListStartIndex = 5; | ||||
6296 | if (Version >= 5) { | ||||
6297 | NumRORefs = Record[5]; | ||||
6298 | RefListStartIndex = 6; | ||||
6299 | if (Version >= 7) { | ||||
6300 | NumWORefs = Record[6]; | ||||
6301 | RefListStartIndex = 7; | ||||
6302 | } | ||||
6303 | } | ||||
6304 | } | ||||
6305 | |||||
6306 | auto Flags = getDecodedGVSummaryFlags(RawFlags, Version); | ||||
6307 | // The module path string ref set in the summary must be owned by the | ||||
6308 | // index's module string table. Since we don't have a module path | ||||
6309 | // string table section in the per-module index, we create a single | ||||
6310 | // module path string table entry with an empty (0) ID to take | ||||
6311 | // ownership. | ||||
6312 | int CallGraphEdgeStartIndex = RefListStartIndex + NumRefs; | ||||
6313 | assert(Record.size() >= RefListStartIndex + NumRefs &&(static_cast <bool> (Record.size() >= RefListStartIndex + NumRefs && "Record size inconsistent with number of references" ) ? void (0) : __assert_fail ("Record.size() >= RefListStartIndex + NumRefs && \"Record size inconsistent with number of references\"" , "llvm/lib/Bitcode/Reader/BitcodeReader.cpp", 6314, __extension__ __PRETTY_FUNCTION__)) | ||||
6314 | "Record size inconsistent with number of references")(static_cast <bool> (Record.size() >= RefListStartIndex + NumRefs && "Record size inconsistent with number of references" ) ? void (0) : __assert_fail ("Record.size() >= RefListStartIndex + NumRefs && \"Record size inconsistent with number of references\"" , "llvm/lib/Bitcode/Reader/BitcodeReader.cpp", 6314, __extension__ __PRETTY_FUNCTION__)); | ||||
6315 | std::vector<ValueInfo> Refs = makeRefList( | ||||
6316 | ArrayRef<uint64_t>(Record).slice(RefListStartIndex, NumRefs)); | ||||
6317 | bool HasProfile = (BitCode == bitc::FS_PERMODULE_PROFILE); | ||||
6318 | bool HasRelBF = (BitCode == bitc::FS_PERMODULE_RELBF); | ||||
6319 | std::vector<FunctionSummary::EdgeTy> Calls = makeCallList( | ||||
6320 | ArrayRef<uint64_t>(Record).slice(CallGraphEdgeStartIndex), | ||||
6321 | IsOldProfileFormat, HasProfile, HasRelBF); | ||||
6322 | setSpecialRefs(Refs, NumRORefs, NumWORefs); | ||||
6323 | auto FS = std::make_unique<FunctionSummary>( | ||||
6324 | Flags, InstCount, getDecodedFFlags(RawFunFlags), /*EntryCount=*/0, | ||||
6325 | std::move(Refs), std::move(Calls), std::move(PendingTypeTests), | ||||
6326 | std::move(PendingTypeTestAssumeVCalls), | ||||
6327 | std::move(PendingTypeCheckedLoadVCalls), | ||||
6328 | std::move(PendingTypeTestAssumeConstVCalls), | ||||
6329 | std::move(PendingTypeCheckedLoadConstVCalls), | ||||
6330 | std::move(PendingParamAccesses)); | ||||
6331 | auto VIAndOriginalGUID = getValueInfoFromValueId(ValueID); | ||||
6332 | FS->setModulePath(getThisModule()->first()); | ||||
6333 | FS->setOriginalName(VIAndOriginalGUID.second); | ||||
6334 | TheIndex.addGlobalValueSummary(VIAndOriginalGUID.first, std::move(FS)); | ||||
6335 | break; | ||||
6336 | } | ||||
6337 | // FS_ALIAS: [valueid, flags, valueid] | ||||
6338 | // Aliases must be emitted (and parsed) after all FS_PERMODULE entries, as | ||||
6339 | // they expect all aliasee summaries to be available. | ||||
6340 | case bitc::FS_ALIAS: { | ||||
6341 | unsigned ValueID = Record[0]; | ||||
6342 | uint64_t RawFlags = Record[1]; | ||||
6343 | unsigned AliaseeID = Record[2]; | ||||
6344 | auto Flags = getDecodedGVSummaryFlags(RawFlags, Version); | ||||
6345 | auto AS = std::make_unique<AliasSummary>(Flags); | ||||
6346 | // The module path string ref set in the summary must be owned by the | ||||
6347 | // index's module string table. Since we don't have a module path | ||||
6348 | // string table section in the per-module index, we create a single | ||||
6349 | // module path string table entry with an empty (0) ID to take | ||||
6350 | // ownership. | ||||
6351 | AS->setModulePath(getThisModule()->first()); | ||||
6352 | |||||
6353 | auto AliaseeVI = getValueInfoFromValueId(AliaseeID).first; | ||||
6354 | auto AliaseeInModule = TheIndex.findSummaryInModule(AliaseeVI, ModulePath); | ||||
6355 | if (!AliaseeInModule) | ||||
6356 | return error("Alias expects aliasee summary to be parsed"); | ||||
6357 | AS->setAliasee(AliaseeVI, AliaseeInModule); | ||||
6358 | |||||
6359 | auto GUID = getValueInfoFromValueId(ValueID); | ||||
6360 | AS->setOriginalName(GUID.second); | ||||
6361 | TheIndex.addGlobalValueSummary(GUID.first, std::move(AS)); | ||||
6362 | break; | ||||
6363 | } | ||||
6364 | // FS_PERMODULE_GLOBALVAR_INIT_REFS: [valueid, flags, varflags, n x valueid] | ||||
6365 | case bitc::FS_PERMODULE_GLOBALVAR_INIT_REFS: { | ||||
6366 | unsigned ValueID = Record[0]; | ||||
6367 | uint64_t RawFlags = Record[1]; | ||||
6368 | unsigned RefArrayStart = 2; | ||||
6369 | GlobalVarSummary::GVarFlags GVF(/* ReadOnly */ false, | ||||
6370 | /* WriteOnly */ false, | ||||
6371 | /* Constant */ false, | ||||
6372 | GlobalObject::VCallVisibilityPublic); | ||||
6373 | auto Flags = getDecodedGVSummaryFlags(RawFlags, Version); | ||||
6374 | if (Version >= 5) { | ||||
6375 | GVF = getDecodedGVarFlags(Record[2]); | ||||
6376 | RefArrayStart = 3; | ||||
6377 | } | ||||
6378 | std::vector<ValueInfo> Refs = | ||||
6379 | makeRefList(ArrayRef<uint64_t>(Record).slice(RefArrayStart)); | ||||
6380 | auto FS = | ||||
6381 | std::make_unique<GlobalVarSummary>(Flags, GVF, std::move(Refs)); | ||||
6382 | FS->setModulePath(getThisModule()->first()); | ||||
6383 | auto GUID = getValueInfoFromValueId(ValueID); | ||||
6384 | FS->setOriginalName(GUID.second); | ||||
6385 | TheIndex.addGlobalValueSummary(GUID.first, std::move(FS)); | ||||
6386 | break; | ||||
6387 | } | ||||
6388 | // FS_PERMODULE_VTABLE_GLOBALVAR_INIT_REFS: [valueid, flags, varflags, | ||||
6389 | // numrefs, numrefs x valueid, | ||||
6390 | // n x (valueid, offset)] | ||||
6391 | case bitc::FS_PERMODULE_VTABLE_GLOBALVAR_INIT_REFS: { | ||||
6392 | unsigned ValueID = Record[0]; | ||||
6393 | uint64_t RawFlags = Record[1]; | ||||
6394 | GlobalVarSummary::GVarFlags GVF = getDecodedGVarFlags(Record[2]); | ||||
6395 | unsigned NumRefs = Record[3]; | ||||
6396 | unsigned RefListStartIndex = 4; | ||||
6397 | unsigned VTableListStartIndex = RefListStartIndex + NumRefs; | ||||
6398 | auto Flags = getDecodedGVSummaryFlags(RawFlags, Version); | ||||
6399 | std::vector<ValueInfo> Refs = makeRefList( | ||||
6400 | ArrayRef<uint64_t>(Record).slice(RefListStartIndex, NumRefs)); | ||||
6401 | VTableFuncList VTableFuncs; | ||||
6402 | for (unsigned I = VTableListStartIndex, E = Record.size(); I != E; ++I) { | ||||
6403 | ValueInfo Callee = getValueInfoFromValueId(Record[I]).first; | ||||
6404 | uint64_t Offset = Record[++I]; | ||||
6405 | VTableFuncs.push_back({Callee, Offset}); | ||||
6406 | } | ||||
6407 | auto VS = | ||||
6408 | std::make_unique<GlobalVarSummary>(Flags, GVF, std::move(Refs)); | ||||
6409 | VS->setModulePath(getThisModule()->first()); | ||||
6410 | VS->setVTableFuncs(VTableFuncs); | ||||
6411 | auto GUID = getValueInfoFromValueId(ValueID); | ||||
6412 | VS->setOriginalName(GUID.second); | ||||
6413 | TheIndex.addGlobalValueSummary(GUID.first, std::move(VS)); | ||||
6414 | break; | ||||
6415 | } | ||||
6416 | // FS_COMBINED: [valueid, modid, flags, instcount, fflags, numrefs, | ||||
6417 | // numrefs x valueid, n x (valueid)] | ||||
6418 | // FS_COMBINED_PROFILE: [valueid, modid, flags, instcount, fflags, numrefs, | ||||
6419 | // numrefs x valueid, n x (valueid, hotness)] | ||||
6420 | case bitc::FS_COMBINED: | ||||
6421 | case bitc::FS_COMBINED_PROFILE: { | ||||
6422 | unsigned ValueID = Record[0]; | ||||
6423 | uint64_t ModuleId = Record[1]; | ||||
6424 | uint64_t RawFlags = Record[2]; | ||||
6425 | unsigned InstCount = Record[3]; | ||||
6426 | uint64_t RawFunFlags = 0; | ||||
6427 | uint64_t EntryCount = 0; | ||||
6428 | unsigned NumRefs = Record[4]; | ||||
6429 | unsigned NumRORefs = 0, NumWORefs = 0; | ||||
6430 | int RefListStartIndex = 5; | ||||
6431 | |||||
6432 | if (Version >= 4) { | ||||
6433 | RawFunFlags = Record[4]; | ||||
6434 | RefListStartIndex = 6; | ||||
6435 | size_t NumRefsIndex = 5; | ||||
6436 | if (Version >= 5) { | ||||
6437 | unsigned NumRORefsOffset = 1; | ||||
6438 | RefListStartIndex = 7; | ||||
6439 | if (Version >= 6) { | ||||
6440 | NumRefsIndex = 6; | ||||
6441 | EntryCount = Record[5]; | ||||
6442 | RefListStartIndex = 8; | ||||
6443 | if (Version >= 7) { | ||||
6444 | RefListStartIndex = 9; | ||||
6445 | NumWORefs = Record[8]; | ||||
6446 | NumRORefsOffset = 2; | ||||
6447 | } | ||||
6448 | } | ||||
6449 | NumRORefs = Record[RefListStartIndex - NumRORefsOffset]; | ||||
6450 | } | ||||
6451 | NumRefs = Record[NumRefsIndex]; | ||||
6452 | } | ||||
6453 | |||||
6454 | auto Flags = getDecodedGVSummaryFlags(RawFlags, Version); | ||||
6455 | int CallGraphEdgeStartIndex = RefListStartIndex + NumRefs; | ||||
6456 | assert(Record.size() >= RefListStartIndex + NumRefs &&(static_cast <bool> (Record.size() >= RefListStartIndex + NumRefs && "Record size inconsistent with number of references" ) ? void (0) : __assert_fail ("Record.size() >= RefListStartIndex + NumRefs && \"Record size inconsistent with number of references\"" , "llvm/lib/Bitcode/Reader/BitcodeReader.cpp", 6457, __extension__ __PRETTY_FUNCTION__)) | ||||
6457 | "Record size inconsistent with number of references")(static_cast <bool> (Record.size() >= RefListStartIndex + NumRefs && "Record size inconsistent with number of references" ) ? void (0) : __assert_fail ("Record.size() >= RefListStartIndex + NumRefs && \"Record size inconsistent with number of references\"" , "llvm/lib/Bitcode/Reader/BitcodeReader.cpp", 6457, __extension__ __PRETTY_FUNCTION__)); | ||||
6458 | std::vector<ValueInfo> Refs = makeRefList( | ||||
6459 | ArrayRef<uint64_t>(Record).slice(RefListStartIndex, NumRefs)); | ||||
6460 | bool HasProfile = (BitCode == bitc::FS_COMBINED_PROFILE); | ||||
6461 | std::vector<FunctionSummary::EdgeTy> Edges = makeCallList( | ||||
6462 | ArrayRef<uint64_t>(Record).slice(CallGraphEdgeStartIndex), | ||||
6463 | IsOldProfileFormat, HasProfile, false); | ||||
6464 | ValueInfo VI = getValueInfoFromValueId(ValueID).first; | ||||
6465 | setSpecialRefs(Refs, NumRORefs, NumWORefs); | ||||
6466 | auto FS = std::make_unique<FunctionSummary>( | ||||
6467 | Flags, InstCount, getDecodedFFlags(RawFunFlags), EntryCount, | ||||
6468 | std::move(Refs), std::move(Edges), std::move(PendingTypeTests), | ||||
6469 | std::move(PendingTypeTestAssumeVCalls), | ||||
6470 | std::move(PendingTypeCheckedLoadVCalls), | ||||
6471 | std::move(PendingTypeTestAssumeConstVCalls), | ||||
6472 | std::move(PendingTypeCheckedLoadConstVCalls), | ||||
6473 | std::move(PendingParamAccesses)); | ||||
6474 | LastSeenSummary = FS.get(); | ||||
6475 | LastSeenGUID = VI.getGUID(); | ||||
6476 | FS->setModulePath(ModuleIdMap[ModuleId]); | ||||
6477 | TheIndex.addGlobalValueSummary(VI, std::move(FS)); | ||||
6478 | break; | ||||
6479 | } | ||||
6480 | // FS_COMBINED_ALIAS: [valueid, modid, flags, valueid] | ||||
6481 | // Aliases must be emitted (and parsed) after all FS_COMBINED entries, as | ||||
6482 | // they expect all aliasee summaries to be available. | ||||
6483 | case bitc::FS_COMBINED_ALIAS: { | ||||
6484 | unsigned ValueID = Record[0]; | ||||
6485 | uint64_t ModuleId = Record[1]; | ||||
6486 | uint64_t RawFlags = Record[2]; | ||||
6487 | unsigned AliaseeValueId = Record[3]; | ||||
6488 | auto Flags = getDecodedGVSummaryFlags(RawFlags, Version); | ||||
6489 | auto AS = std::make_unique<AliasSummary>(Flags); | ||||
6490 | LastSeenSummary = AS.get(); | ||||
6491 | AS->setModulePath(ModuleIdMap[ModuleId]); | ||||
6492 | |||||
6493 | auto AliaseeVI = getValueInfoFromValueId(AliaseeValueId).first; | ||||
6494 | auto AliaseeInModule = TheIndex.findSummaryInModule(AliaseeVI, AS->modulePath()); | ||||
6495 | AS->setAliasee(AliaseeVI, AliaseeInModule); | ||||
6496 | |||||
6497 | ValueInfo VI = getValueInfoFromValueId(ValueID).first; | ||||
6498 | LastSeenGUID = VI.getGUID(); | ||||
6499 | TheIndex.addGlobalValueSummary(VI, std::move(AS)); | ||||
6500 | break; | ||||
6501 | } | ||||
6502 | // FS_COMBINED_GLOBALVAR_INIT_REFS: [valueid, modid, flags, n x valueid] | ||||
6503 | case bitc::FS_COMBINED_GLOBALVAR_INIT_REFS: { | ||||
6504 | unsigned ValueID = Record[0]; | ||||
6505 | uint64_t ModuleId = Record[1]; | ||||
6506 | uint64_t RawFlags = Record[2]; | ||||
6507 | unsigned RefArrayStart = 3; | ||||
6508 | GlobalVarSummary::GVarFlags GVF(/* ReadOnly */ false, | ||||
6509 | /* WriteOnly */ false, | ||||
6510 | /* Constant */ false, | ||||
6511 | GlobalObject::VCallVisibilityPublic); | ||||
6512 | auto Flags = getDecodedGVSummaryFlags(RawFlags, Version); | ||||
6513 | if (Version >= 5) { | ||||
6514 | GVF = getDecodedGVarFlags(Record[3]); | ||||
6515 | RefArrayStart = 4; | ||||
6516 | } | ||||
6517 | std::vector<ValueInfo> Refs = | ||||
6518 | makeRefList(ArrayRef<uint64_t>(Record).slice(RefArrayStart)); | ||||
6519 | auto FS = | ||||
6520 | std::make_unique<GlobalVarSummary>(Flags, GVF, std::move(Refs)); | ||||
6521 | LastSeenSummary = FS.get(); | ||||
6522 | FS->setModulePath(ModuleIdMap[ModuleId]); | ||||
6523 | ValueInfo VI = getValueInfoFromValueId(ValueID).first; | ||||
6524 | LastSeenGUID = VI.getGUID(); | ||||
6525 | TheIndex.addGlobalValueSummary(VI, std::move(FS)); | ||||
6526 | break; | ||||
6527 | } | ||||
6528 | // FS_COMBINED_ORIGINAL_NAME: [original_name] | ||||
6529 | case bitc::FS_COMBINED_ORIGINAL_NAME: { | ||||
6530 | uint64_t OriginalName = Record[0]; | ||||
6531 | if (!LastSeenSummary) | ||||
6532 | return error("Name attachment that does not follow a combined record"); | ||||
6533 | LastSeenSummary->setOriginalName(OriginalName); | ||||
6534 | TheIndex.addOriginalName(LastSeenGUID, OriginalName); | ||||
6535 | // Reset the LastSeenSummary | ||||
6536 | LastSeenSummary = nullptr; | ||||
6537 | LastSeenGUID = 0; | ||||
6538 | break; | ||||
6539 | } | ||||
6540 | case bitc::FS_TYPE_TESTS: | ||||
6541 | assert(PendingTypeTests.empty())(static_cast <bool> (PendingTypeTests.empty()) ? void ( 0) : __assert_fail ("PendingTypeTests.empty()", "llvm/lib/Bitcode/Reader/BitcodeReader.cpp" , 6541, __extension__ __PRETTY_FUNCTION__)); | ||||
6542 | llvm::append_range(PendingTypeTests, Record); | ||||
6543 | break; | ||||
6544 | |||||
6545 | case bitc::FS_TYPE_TEST_ASSUME_VCALLS: | ||||
6546 | assert(PendingTypeTestAssumeVCalls.empty())(static_cast <bool> (PendingTypeTestAssumeVCalls.empty( )) ? void (0) : __assert_fail ("PendingTypeTestAssumeVCalls.empty()" , "llvm/lib/Bitcode/Reader/BitcodeReader.cpp", 6546, __extension__ __PRETTY_FUNCTION__)); | ||||
6547 | for (unsigned I = 0; I != Record.size(); I += 2) | ||||
6548 | PendingTypeTestAssumeVCalls.push_back({Record[I], Record[I+1]}); | ||||
6549 | break; | ||||
6550 | |||||
6551 | case bitc::FS_TYPE_CHECKED_LOAD_VCALLS: | ||||
6552 | assert(PendingTypeCheckedLoadVCalls.empty())(static_cast <bool> (PendingTypeCheckedLoadVCalls.empty ()) ? void (0) : __assert_fail ("PendingTypeCheckedLoadVCalls.empty()" , "llvm/lib/Bitcode/Reader/BitcodeReader.cpp", 6552, __extension__ __PRETTY_FUNCTION__)); | ||||
6553 | for (unsigned I = 0; I != Record.size(); I += 2) | ||||
6554 | PendingTypeCheckedLoadVCalls.push_back({Record[I], Record[I+1]}); | ||||
6555 | break; | ||||
6556 | |||||
6557 | case bitc::FS_TYPE_TEST_ASSUME_CONST_VCALL: | ||||
6558 | PendingTypeTestAssumeConstVCalls.push_back( | ||||
6559 | {{Record[0], Record[1]}, {Record.begin() + 2, Record.end()}}); | ||||
6560 | break; | ||||
6561 | |||||
6562 | case bitc::FS_TYPE_CHECKED_LOAD_CONST_VCALL: | ||||
6563 | PendingTypeCheckedLoadConstVCalls.push_back( | ||||
6564 | {{Record[0], Record[1]}, {Record.begin() + 2, Record.end()}}); | ||||
6565 | break; | ||||
6566 | |||||
6567 | case bitc::FS_CFI_FUNCTION_DEFS: { | ||||
6568 | std::set<std::string> &CfiFunctionDefs = TheIndex.cfiFunctionDefs(); | ||||
6569 | for (unsigned I = 0; I != Record.size(); I += 2) | ||||
6570 | CfiFunctionDefs.insert( | ||||
6571 | {Strtab.data() + Record[I], static_cast<size_t>(Record[I + 1])}); | ||||
6572 | break; | ||||
6573 | } | ||||
6574 | |||||
6575 | case bitc::FS_CFI_FUNCTION_DECLS: { | ||||
6576 | std::set<std::string> &CfiFunctionDecls = TheIndex.cfiFunctionDecls(); | ||||
6577 | for (unsigned I = 0; I != Record.size(); I += 2) | ||||
6578 | CfiFunctionDecls.insert( | ||||
6579 | {Strtab.data() + Record[I], static_cast<size_t>(Record[I + 1])}); | ||||
6580 | break; | ||||
6581 | } | ||||
6582 | |||||
6583 | case bitc::FS_TYPE_ID: | ||||
6584 | parseTypeIdSummaryRecord(Record, Strtab, TheIndex); | ||||
6585 | break; | ||||
6586 | |||||
6587 | case bitc::FS_TYPE_ID_METADATA: | ||||
6588 | parseTypeIdCompatibleVtableSummaryRecord(Record); | ||||
6589 | break; | ||||
6590 | |||||
6591 | case bitc::FS_BLOCK_COUNT: | ||||
6592 | TheIndex.addBlockCount(Record[0]); | ||||
6593 | break; | ||||
6594 | |||||
6595 | case bitc::FS_PARAM_ACCESS: { | ||||
6596 | PendingParamAccesses = parseParamAccesses(Record); | ||||
6597 | break; | ||||
6598 | } | ||||
6599 | } | ||||
6600 | } | ||||
6601 | llvm_unreachable("Exit infinite loop")::llvm::llvm_unreachable_internal("Exit infinite loop", "llvm/lib/Bitcode/Reader/BitcodeReader.cpp" , 6601); | ||||
6602 | } | ||||
6603 | |||||
6604 | // Parse the module string table block into the Index. | ||||
6605 | // This populates the ModulePathStringTable map in the index. | ||||
6606 | Error ModuleSummaryIndexBitcodeReader::parseModuleStringTable() { | ||||
6607 | if (Error Err = Stream.EnterSubBlock(bitc::MODULE_STRTAB_BLOCK_ID)) | ||||
6608 | return Err; | ||||
6609 | |||||
6610 | SmallVector<uint64_t, 64> Record; | ||||
6611 | |||||
6612 | SmallString<128> ModulePath; | ||||
6613 | ModuleSummaryIndex::ModuleInfo *LastSeenModule = nullptr; | ||||
6614 | |||||
6615 | while (true) { | ||||
6616 | Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks(); | ||||
6617 | if (!MaybeEntry) | ||||
6618 | return MaybeEntry.takeError(); | ||||
6619 | BitstreamEntry Entry = MaybeEntry.get(); | ||||
6620 | |||||
6621 | switch (Entry.Kind) { | ||||
6622 | case BitstreamEntry::SubBlock: // Handled for us already. | ||||
6623 | case BitstreamEntry::Error: | ||||
6624 | return error("Malformed block"); | ||||
6625 | case BitstreamEntry::EndBlock: | ||||
6626 | return Error::success(); | ||||
6627 | case BitstreamEntry::Record: | ||||
6628 | // The interesting case. | ||||
6629 | break; | ||||
6630 | } | ||||
6631 | |||||
6632 | Record.clear(); | ||||
6633 | Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record); | ||||
6634 | if (!MaybeRecord) | ||||
6635 | return MaybeRecord.takeError(); | ||||
6636 | switch (MaybeRecord.get()) { | ||||
6637 | default: // Default behavior: ignore. | ||||
6638 | break; | ||||
6639 | case bitc::MST_CODE_ENTRY: { | ||||
6640 | // MST_ENTRY: [modid, namechar x N] | ||||
6641 | uint64_t ModuleId = Record[0]; | ||||
6642 | |||||
6643 | if (convertToString(Record, 1, ModulePath)) | ||||
6644 | return error("Invalid record"); | ||||
6645 | |||||
6646 | LastSeenModule = TheIndex.addModule(ModulePath, ModuleId); | ||||
6647 | ModuleIdMap[ModuleId] = LastSeenModule->first(); | ||||
6648 | |||||
6649 | ModulePath.clear(); | ||||
6650 | break; | ||||
6651 | } | ||||
6652 | /// MST_CODE_HASH: [5*i32] | ||||
6653 | case bitc::MST_CODE_HASH: { | ||||
6654 | if (Record.size() != 5) | ||||
6655 | return error("Invalid hash length " + Twine(Record.size()).str()); | ||||
6656 | if (!LastSeenModule) | ||||
6657 | return error("Invalid hash that does not follow a module path"); | ||||
6658 | int Pos = 0; | ||||
6659 | for (auto &Val : Record) { | ||||
6660 | assert(!(Val >> 32) && "Unexpected high bits set")(static_cast <bool> (!(Val >> 32) && "Unexpected high bits set" ) ? void (0) : __assert_fail ("!(Val >> 32) && \"Unexpected high bits set\"" , "llvm/lib/Bitcode/Reader/BitcodeReader.cpp", 6660, __extension__ __PRETTY_FUNCTION__)); | ||||
6661 | LastSeenModule->second.second[Pos++] = Val; | ||||
6662 | } | ||||
6663 | // Reset LastSeenModule to avoid overriding the hash unexpectedly. | ||||
6664 | LastSeenModule = nullptr; | ||||
6665 | break; | ||||
6666 | } | ||||
6667 | } | ||||
6668 | } | ||||
6669 | llvm_unreachable("Exit infinite loop")::llvm::llvm_unreachable_internal("Exit infinite loop", "llvm/lib/Bitcode/Reader/BitcodeReader.cpp" , 6669); | ||||
6670 | } | ||||
6671 | |||||
6672 | namespace { | ||||
6673 | |||||
6674 | // FIXME: This class is only here to support the transition to llvm::Error. It | ||||
6675 | // will be removed once this transition is complete. Clients should prefer to | ||||
6676 | // deal with the Error value directly, rather than converting to error_code. | ||||
6677 | class BitcodeErrorCategoryType : public std::error_category { | ||||
6678 | const char *name() const noexcept override { | ||||
6679 | return "llvm.bitcode"; | ||||
6680 | } | ||||
6681 | |||||
6682 | std::string message(int IE) const override { | ||||
6683 | BitcodeError E = static_cast<BitcodeError>(IE); | ||||
6684 | switch (E) { | ||||
6685 | case BitcodeError::CorruptedBitcode: | ||||
6686 | return "Corrupted bitcode"; | ||||
6687 | } | ||||
6688 | llvm_unreachable("Unknown error type!")::llvm::llvm_unreachable_internal("Unknown error type!", "llvm/lib/Bitcode/Reader/BitcodeReader.cpp" , 6688); | ||||
6689 | } | ||||
6690 | }; | ||||
6691 | |||||
6692 | } // end anonymous namespace | ||||
6693 | |||||
6694 | static ManagedStatic<BitcodeErrorCategoryType> ErrorCategory; | ||||
6695 | |||||
6696 | const std::error_category &llvm::BitcodeErrorCategory() { | ||||
6697 | return *ErrorCategory; | ||||
6698 | } | ||||
6699 | |||||
6700 | static Expected<StringRef> readBlobInRecord(BitstreamCursor &Stream, | ||||
6701 | unsigned Block, unsigned RecordID) { | ||||
6702 | if (Error Err = Stream.EnterSubBlock(Block)) | ||||
6703 | return std::move(Err); | ||||
6704 | |||||
6705 | StringRef Strtab; | ||||
6706 | while (true) { | ||||
6707 | Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance(); | ||||
6708 | if (!MaybeEntry) | ||||
6709 | return MaybeEntry.takeError(); | ||||
6710 | llvm::BitstreamEntry Entry = MaybeEntry.get(); | ||||
6711 | |||||
6712 | switch (Entry.Kind) { | ||||
6713 | case BitstreamEntry::EndBlock: | ||||
6714 | return Strtab; | ||||
6715 | |||||
6716 | case BitstreamEntry::Error: | ||||
6717 | return error("Malformed block"); | ||||
6718 | |||||
6719 | case BitstreamEntry::SubBlock: | ||||
6720 | if (Error Err = Stream.SkipBlock()) | ||||
6721 | return std::move(Err); | ||||
6722 | break; | ||||
6723 | |||||
6724 | case BitstreamEntry::Record: | ||||
6725 | StringRef Blob; | ||||
6726 | SmallVector<uint64_t, 1> Record; | ||||
6727 | Expected<unsigned> MaybeRecord = | ||||
6728 | Stream.readRecord(Entry.ID, Record, &Blob); | ||||
6729 | if (!MaybeRecord) | ||||
6730 | return MaybeRecord.takeError(); | ||||
6731 | if (MaybeRecord.get() == RecordID) | ||||
6732 | Strtab = Blob; | ||||
6733 | break; | ||||
6734 | } | ||||
6735 | } | ||||
6736 | } | ||||
6737 | |||||
6738 | //===----------------------------------------------------------------------===// | ||||
6739 | // External interface | ||||
6740 | //===----------------------------------------------------------------------===// | ||||
6741 | |||||
6742 | Expected<std::vector<BitcodeModule>> | ||||
6743 | llvm::getBitcodeModuleList(MemoryBufferRef Buffer) { | ||||
6744 | auto FOrErr = getBitcodeFileContents(Buffer); | ||||
6745 | if (!FOrErr) | ||||
6746 | return FOrErr.takeError(); | ||||
6747 | return std::move(FOrErr->Mods); | ||||
6748 | } | ||||
6749 | |||||
6750 | Expected<BitcodeFileContents> | ||||
6751 | llvm::getBitcodeFileContents(MemoryBufferRef Buffer) { | ||||
6752 | Expected<BitstreamCursor> StreamOrErr = initStream(Buffer); | ||||
6753 | if (!StreamOrErr) | ||||
6754 | return StreamOrErr.takeError(); | ||||
6755 | BitstreamCursor &Stream = *StreamOrErr; | ||||
6756 | |||||
6757 | BitcodeFileContents F; | ||||
6758 | while (true) { | ||||
6759 | uint64_t BCBegin = Stream.getCurrentByteNo(); | ||||
6760 | |||||
6761 | // We may be consuming bitcode from a client that leaves garbage at the end | ||||
6762 | // of the bitcode stream (e.g. Apple's ar tool). If we are close enough to | ||||
6763 | // the end that there cannot possibly be another module, stop looking. | ||||
6764 | if (BCBegin + 8 >= Stream.getBitcodeBytes().size()) | ||||
6765 | return F; | ||||
6766 | |||||
6767 | Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance(); | ||||
6768 | if (!MaybeEntry) | ||||
6769 | return MaybeEntry.takeError(); | ||||
6770 | llvm::BitstreamEntry Entry = MaybeEntry.get(); | ||||
6771 | |||||
6772 | switch (Entry.Kind) { | ||||
6773 | case BitstreamEntry::EndBlock: | ||||
6774 | case BitstreamEntry::Error: | ||||
6775 | return error("Malformed block"); | ||||
6776 | |||||
6777 | case BitstreamEntry::SubBlock: { | ||||
6778 | uint64_t IdentificationBit = -1ull; | ||||
6779 | if (Entry.ID == bitc::IDENTIFICATION_BLOCK_ID) { | ||||
6780 | IdentificationBit = Stream.GetCurrentBitNo() - BCBegin * 8; | ||||
6781 | if (Error Err = Stream.SkipBlock()) | ||||
6782 | return std::move(Err); | ||||
6783 | |||||
6784 | { | ||||
6785 | Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance(); | ||||
6786 | if (!MaybeEntry) | ||||
6787 | return MaybeEntry.takeError(); | ||||
6788 | Entry = MaybeEntry.get(); | ||||
6789 | } | ||||
6790 | |||||
6791 | if (Entry.Kind != BitstreamEntry::SubBlock || | ||||
6792 | Entry.ID != bitc::MODULE_BLOCK_ID) | ||||
6793 | return error("Malformed block"); | ||||
6794 | } | ||||
6795 | |||||
6796 | if (Entry.ID == bitc::MODULE_BLOCK_ID) { | ||||
6797 | uint64_t ModuleBit = Stream.GetCurrentBitNo() - BCBegin * 8; | ||||
6798 | if (Error Err = Stream.SkipBlock()) | ||||
6799 | return std::move(Err); | ||||
6800 | |||||
6801 | F.Mods.push_back({Stream.getBitcodeBytes().slice( | ||||
6802 | BCBegin, Stream.getCurrentByteNo() - BCBegin), | ||||
6803 | Buffer.getBufferIdentifier(), IdentificationBit, | ||||
6804 | ModuleBit}); | ||||
6805 | continue; | ||||
6806 | } | ||||
6807 | |||||
6808 | if (Entry.ID == bitc::STRTAB_BLOCK_ID) { | ||||
6809 | Expected<StringRef> Strtab = | ||||
6810 | readBlobInRecord(Stream, bitc::STRTAB_BLOCK_ID, bitc::STRTAB_BLOB); | ||||
6811 | if (!Strtab) | ||||
6812 | return Strtab.takeError(); | ||||
6813 | // This string table is used by every preceding bitcode module that does | ||||
6814 | // not have its own string table. A bitcode file may have multiple | ||||
6815 | // string tables if it was created by binary concatenation, for example | ||||
6816 | // with "llvm-cat -b". | ||||
6817 | for (BitcodeModule &I : llvm::reverse(F.Mods)) { | ||||
6818 | if (!I.Strtab.empty()) | ||||
6819 | break; | ||||
6820 | I.Strtab = *Strtab; | ||||
6821 | } | ||||
6822 | // Similarly, the string table is used by every preceding symbol table; | ||||
6823 | // normally there will be just one unless the bitcode file was created | ||||
6824 | // by binary concatenation. | ||||
6825 | if (!F.Symtab.empty() && F.StrtabForSymtab.empty()) | ||||
6826 | F.StrtabForSymtab = *Strtab; | ||||
6827 | continue; | ||||
6828 | } | ||||
6829 | |||||
6830 | if (Entry.ID == bitc::SYMTAB_BLOCK_ID) { | ||||
6831 | Expected<StringRef> SymtabOrErr = | ||||
6832 | readBlobInRecord(Stream, bitc::SYMTAB_BLOCK_ID, bitc::SYMTAB_BLOB); | ||||
6833 | if (!SymtabOrErr) | ||||
6834 | return SymtabOrErr.takeError(); | ||||
6835 | |||||
6836 | // We can expect the bitcode file to have multiple symbol tables if it | ||||
6837 | // was created by binary concatenation. In that case we silently | ||||
6838 | // ignore any subsequent symbol tables, which is fine because this is a | ||||
6839 | // low level function. The client is expected to notice that the number | ||||
6840 | // of modules in the symbol table does not match the number of modules | ||||
6841 | // in the input file and regenerate the symbol table. | ||||
6842 | if (F.Symtab.empty()) | ||||
6843 | F.Symtab = *SymtabOrErr; | ||||
6844 | continue; | ||||
6845 | } | ||||
6846 | |||||
6847 | if (Error Err = Stream.SkipBlock()) | ||||
6848 | return std::move(Err); | ||||
6849 | continue; | ||||
6850 | } | ||||
6851 | case BitstreamEntry::Record: | ||||
6852 | if (Error E = Stream.skipRecord(Entry.ID).takeError()) | ||||
6853 | return std::move(E); | ||||
6854 | continue; | ||||
6855 | } | ||||
6856 | } | ||||
6857 | } | ||||
6858 | |||||
6859 | /// Get a lazy one-at-time loading module from bitcode. | ||||
6860 | /// | ||||
6861 | /// This isn't always used in a lazy context. In particular, it's also used by | ||||
6862 | /// \a parseModule(). If this is truly lazy, then we need to eagerly pull | ||||
6863 | /// in forward-referenced functions from block address references. | ||||
6864 | /// | ||||
6865 | /// \param[in] MaterializeAll Set to \c true if we should materialize | ||||
6866 | /// everything. | ||||
6867 | Expected<std::unique_ptr<Module>> | ||||
6868 | BitcodeModule::getModuleImpl(LLVMContext &Context, bool MaterializeAll, | ||||
6869 | bool ShouldLazyLoadMetadata, bool IsImporting, | ||||
6870 | DataLayoutCallbackTy DataLayoutCallback) { | ||||
6871 | BitstreamCursor Stream(Buffer); | ||||
6872 | |||||
6873 | std::string ProducerIdentification; | ||||
6874 | if (IdentificationBit != -1ull) { | ||||
6875 | if (Error JumpFailed = Stream.JumpToBit(IdentificationBit)) | ||||
6876 | return std::move(JumpFailed); | ||||
6877 | if (Error E = | ||||
6878 | readIdentificationBlock(Stream).moveInto(ProducerIdentification)) | ||||
6879 | return std::move(E); | ||||
6880 | } | ||||
6881 | |||||
6882 | if (Error JumpFailed = Stream.JumpToBit(ModuleBit)) | ||||
6883 | return std::move(JumpFailed); | ||||
6884 | auto *R = new BitcodeReader(std::move(Stream), Strtab, ProducerIdentification, | ||||
6885 | Context); | ||||
6886 | |||||
6887 | std::unique_ptr<Module> M = | ||||
6888 | std::make_unique<Module>(ModuleIdentifier, Context); | ||||
6889 | M->setMaterializer(R); | ||||
6890 | |||||
6891 | // Delay parsing Metadata if ShouldLazyLoadMetadata is true. | ||||
6892 | if (Error Err = R->parseBitcodeInto(M.get(), ShouldLazyLoadMetadata, | ||||
6893 | IsImporting, DataLayoutCallback)) | ||||
6894 | return std::move(Err); | ||||
6895 | |||||
6896 | if (MaterializeAll) { | ||||
6897 | // Read in the entire module, and destroy the BitcodeReader. | ||||
6898 | if (Error Err = M->materializeAll()) | ||||
6899 | return std::move(Err); | ||||
6900 | } else { | ||||
6901 | // Resolve forward references from blockaddresses. | ||||
6902 | if (Error Err = R->materializeForwardReferencedFunctions()) | ||||
6903 | return std::move(Err); | ||||
6904 | } | ||||
6905 | return std::move(M); | ||||
6906 | } | ||||
6907 | |||||
6908 | Expected<std::unique_ptr<Module>> | ||||
6909 | BitcodeModule::getLazyModule(LLVMContext &Context, bool ShouldLazyLoadMetadata, | ||||
6910 | bool IsImporting) { | ||||
6911 | return getModuleImpl(Context, false, ShouldLazyLoadMetadata, IsImporting, | ||||
6912 | [](StringRef) { return None; }); | ||||
6913 | } | ||||
6914 | |||||
6915 | // Parse the specified bitcode buffer and merge the index into CombinedIndex. | ||||
6916 | // We don't use ModuleIdentifier here because the client may need to control the | ||||
6917 | // module path used in the combined summary (e.g. when reading summaries for | ||||
6918 | // regular LTO modules). | ||||
6919 | Error BitcodeModule::readSummary(ModuleSummaryIndex &CombinedIndex, | ||||
6920 | StringRef ModulePath, uint64_t ModuleId) { | ||||
6921 | BitstreamCursor Stream(Buffer); | ||||
6922 | if (Error JumpFailed = Stream.JumpToBit(ModuleBit)) | ||||
6923 | return JumpFailed; | ||||
6924 | |||||
6925 | ModuleSummaryIndexBitcodeReader R(std::move(Stream), Strtab, CombinedIndex, | ||||
6926 | ModulePath, ModuleId); | ||||
6927 | return R.parseModule(); | ||||
6928 | } | ||||
6929 | |||||
6930 | // Parse the specified bitcode buffer, returning the function info index. | ||||
6931 | Expected<std::unique_ptr<ModuleSummaryIndex>> BitcodeModule::getSummary() { | ||||
6932 | BitstreamCursor Stream(Buffer); | ||||
6933 | if (Error JumpFailed = Stream.JumpToBit(ModuleBit)) | ||||
6934 | return std::move(JumpFailed); | ||||
6935 | |||||
6936 | auto Index = std::make_unique<ModuleSummaryIndex>(/*HaveGVs=*/false); | ||||
6937 | ModuleSummaryIndexBitcodeReader R(std::move(Stream), Strtab, *Index, | ||||
6938 | ModuleIdentifier, 0); | ||||
6939 | |||||
6940 | if (Error Err = R.parseModule()) | ||||
6941 | return std::move(Err); | ||||
6942 | |||||
6943 | return std::move(Index); | ||||
6944 | } | ||||
6945 | |||||
6946 | static Expected<bool> getEnableSplitLTOUnitFlag(BitstreamCursor &Stream, | ||||
6947 | unsigned ID) { | ||||
6948 | if (Error Err = Stream.EnterSubBlock(ID)) | ||||
6949 | return std::move(Err); | ||||
6950 | SmallVector<uint64_t, 64> Record; | ||||
6951 | |||||
6952 | while (true) { | ||||
6953 | BitstreamEntry Entry; | ||||
6954 | if (Error E = Stream.advanceSkippingSubblocks().moveInto(Entry)) | ||||
6955 | return std::move(E); | ||||
6956 | |||||
6957 | switch (Entry.Kind) { | ||||
6958 | case BitstreamEntry::SubBlock: // Handled for us already. | ||||
6959 | case BitstreamEntry::Error: | ||||
6960 | return error("Malformed block"); | ||||
6961 | case BitstreamEntry::EndBlock: | ||||
6962 | // If no flags record found, conservatively return true to mimic | ||||
6963 | // behavior before this flag was added. | ||||
6964 | return true; | ||||
6965 | case BitstreamEntry::Record: | ||||
6966 | // The interesting case. | ||||
6967 | break; | ||||
6968 | } | ||||
6969 | |||||
6970 | // Look for the FS_FLAGS record. | ||||
6971 | Record.clear(); | ||||
6972 | Expected<unsigned> MaybeBitCode = Stream.readRecord(Entry.ID, Record); | ||||
6973 | if (!MaybeBitCode) | ||||
6974 | return MaybeBitCode.takeError(); | ||||
6975 | switch (MaybeBitCode.get()) { | ||||
6976 | default: // Default behavior: ignore. | ||||
6977 | break; | ||||
6978 | case bitc::FS_FLAGS: { // [flags] | ||||
6979 | uint64_t Flags = Record[0]; | ||||
6980 | // Scan flags. | ||||
6981 | assert(Flags <= 0x7f && "Unexpected bits in flag")(static_cast <bool> (Flags <= 0x7f && "Unexpected bits in flag" ) ? void (0) : __assert_fail ("Flags <= 0x7f && \"Unexpected bits in flag\"" , "llvm/lib/Bitcode/Reader/BitcodeReader.cpp", 6981, __extension__ __PRETTY_FUNCTION__)); | ||||
6982 | |||||
6983 | return Flags & 0x8; | ||||
6984 | } | ||||
6985 | } | ||||
6986 | } | ||||
6987 | llvm_unreachable("Exit infinite loop")::llvm::llvm_unreachable_internal("Exit infinite loop", "llvm/lib/Bitcode/Reader/BitcodeReader.cpp" , 6987); | ||||
6988 | } | ||||
6989 | |||||
6990 | // Check if the given bitcode buffer contains a global value summary block. | ||||
6991 | Expected<BitcodeLTOInfo> BitcodeModule::getLTOInfo() { | ||||
6992 | BitstreamCursor Stream(Buffer); | ||||
6993 | if (Error JumpFailed = Stream.JumpToBit(ModuleBit)) | ||||
6994 | return std::move(JumpFailed); | ||||
6995 | |||||
6996 | if (Error Err = Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID)) | ||||
6997 | return std::move(Err); | ||||
6998 | |||||
6999 | while (true) { | ||||
7000 | llvm::BitstreamEntry Entry; | ||||
7001 | if (Error E = Stream.advance().moveInto(Entry)) | ||||
7002 | return std::move(E); | ||||
7003 | |||||
7004 | switch (Entry.Kind) { | ||||
7005 | case BitstreamEntry::Error: | ||||
7006 | return error("Malformed block"); | ||||
7007 | case BitstreamEntry::EndBlock: | ||||
7008 | return BitcodeLTOInfo{/*IsThinLTO=*/false, /*HasSummary=*/false, | ||||
7009 | /*EnableSplitLTOUnit=*/false}; | ||||
7010 | |||||
7011 | case BitstreamEntry::SubBlock: | ||||
7012 | if (Entry.ID == bitc::GLOBALVAL_SUMMARY_BLOCK_ID) { | ||||
7013 | Expected<bool> EnableSplitLTOUnit = | ||||
7014 | getEnableSplitLTOUnitFlag(Stream, Entry.ID); | ||||
7015 | if (!EnableSplitLTOUnit) | ||||
7016 | return EnableSplitLTOUnit.takeError(); | ||||
7017 | return BitcodeLTOInfo{/*IsThinLTO=*/true, /*HasSummary=*/true, | ||||
7018 | *EnableSplitLTOUnit}; | ||||
7019 | } | ||||
7020 | |||||
7021 | if (Entry.ID == bitc::FULL_LTO_GLOBALVAL_SUMMARY_BLOCK_ID) { | ||||
7022 | Expected<bool> EnableSplitLTOUnit = | ||||
7023 | getEnableSplitLTOUnitFlag(Stream, Entry.ID); | ||||
7024 | if (!EnableSplitLTOUnit) | ||||
7025 | return EnableSplitLTOUnit.takeError(); | ||||
7026 | return BitcodeLTOInfo{/*IsThinLTO=*/false, /*HasSummary=*/true, | ||||
7027 | *EnableSplitLTOUnit}; | ||||
7028 | } | ||||
7029 | |||||
7030 | // Ignore other sub-blocks. | ||||
7031 | if (Error Err = Stream.SkipBlock()) | ||||
7032 | return std::move(Err); | ||||
7033 | continue; | ||||
7034 | |||||
7035 | case BitstreamEntry::Record: | ||||
7036 | if (Expected<unsigned> StreamFailed = Stream.skipRecord(Entry.ID)) | ||||
7037 | continue; | ||||
7038 | else | ||||
7039 | return StreamFailed.takeError(); | ||||
7040 | } | ||||
7041 | } | ||||
7042 | } | ||||
7043 | |||||
7044 | static Expected<BitcodeModule> getSingleModule(MemoryBufferRef Buffer) { | ||||
7045 | Expected<std::vector<BitcodeModule>> MsOrErr = getBitcodeModuleList(Buffer); | ||||
7046 | if (!MsOrErr) | ||||
7047 | return MsOrErr.takeError(); | ||||
7048 | |||||
7049 | if (MsOrErr->size() != 1) | ||||
7050 | return error("Expected a single module"); | ||||
7051 | |||||
7052 | return (*MsOrErr)[0]; | ||||
7053 | } | ||||
7054 | |||||
7055 | Expected<std::unique_ptr<Module>> | ||||
7056 | llvm::getLazyBitcodeModule(MemoryBufferRef Buffer, LLVMContext &Context, | ||||
7057 | bool ShouldLazyLoadMetadata, bool IsImporting) { | ||||
7058 | Expected<BitcodeModule> BM = getSingleModule(Buffer); | ||||
7059 | if (!BM) | ||||
7060 | return BM.takeError(); | ||||
7061 | |||||
7062 | return BM->getLazyModule(Context, ShouldLazyLoadMetadata, IsImporting); | ||||
7063 | } | ||||
7064 | |||||
7065 | Expected<std::unique_ptr<Module>> llvm::getOwningLazyBitcodeModule( | ||||
7066 | std::unique_ptr<MemoryBuffer> &&Buffer, LLVMContext &Context, | ||||
7067 | bool ShouldLazyLoadMetadata, bool IsImporting) { | ||||
7068 | auto MOrErr = getLazyBitcodeModule(*Buffer, Context, ShouldLazyLoadMetadata, | ||||
7069 | IsImporting); | ||||
7070 | if (MOrErr) | ||||
7071 | (*MOrErr)->setOwnedMemoryBuffer(std::move(Buffer)); | ||||
7072 | return MOrErr; | ||||
7073 | } | ||||
7074 | |||||
7075 | Expected<std::unique_ptr<Module>> | ||||
7076 | BitcodeModule::parseModule(LLVMContext &Context, | ||||
7077 | DataLayoutCallbackTy DataLayoutCallback) { | ||||
7078 | return getModuleImpl(Context, true, false, false, DataLayoutCallback); | ||||
7079 | // TODO: Restore the use-lists to the in-memory state when the bitcode was | ||||
7080 | // written. We must defer until the Module has been fully materialized. | ||||
7081 | } | ||||
7082 | |||||
7083 | Expected<std::unique_ptr<Module>> | ||||
7084 | llvm::parseBitcodeFile(MemoryBufferRef Buffer, LLVMContext &Context, | ||||
7085 | DataLayoutCallbackTy DataLayoutCallback) { | ||||
7086 | Expected<BitcodeModule> BM = getSingleModule(Buffer); | ||||
7087 | if (!BM) | ||||
7088 | return BM.takeError(); | ||||
7089 | |||||
7090 | return BM->parseModule(Context, DataLayoutCallback); | ||||
7091 | } | ||||
7092 | |||||
7093 | Expected<std::string> llvm::getBitcodeTargetTriple(MemoryBufferRef Buffer) { | ||||
7094 | Expected<BitstreamCursor> StreamOrErr = initStream(Buffer); | ||||
7095 | if (!StreamOrErr) | ||||
7096 | return StreamOrErr.takeError(); | ||||
7097 | |||||
7098 | return readTriple(*StreamOrErr); | ||||
7099 | } | ||||
7100 | |||||
7101 | Expected<bool> llvm::isBitcodeContainingObjCCategory(MemoryBufferRef Buffer) { | ||||
7102 | Expected<BitstreamCursor> StreamOrErr = initStream(Buffer); | ||||
7103 | if (!StreamOrErr) | ||||
7104 | return StreamOrErr.takeError(); | ||||
7105 | |||||
7106 | return hasObjCCategory(*StreamOrErr); | ||||
7107 | } | ||||
7108 | |||||
7109 | Expected<std::string> llvm::getBitcodeProducerString(MemoryBufferRef Buffer) { | ||||
7110 | Expected<BitstreamCursor> StreamOrErr = initStream(Buffer); | ||||
7111 | if (!StreamOrErr) | ||||
7112 | return StreamOrErr.takeError(); | ||||
7113 | |||||
7114 | return readIdentificationCode(*StreamOrErr); | ||||
7115 | } | ||||
7116 | |||||
7117 | Error llvm::readModuleSummaryIndex(MemoryBufferRef Buffer, | ||||
7118 | ModuleSummaryIndex &CombinedIndex, | ||||
7119 | uint64_t ModuleId) { | ||||
7120 | Expected<BitcodeModule> BM = getSingleModule(Buffer); | ||||
7121 | if (!BM) | ||||
7122 | return BM.takeError(); | ||||
7123 | |||||
7124 | return BM->readSummary(CombinedIndex, BM->getModuleIdentifier(), ModuleId); | ||||
7125 | } | ||||
7126 | |||||
7127 | Expected<std::unique_ptr<ModuleSummaryIndex>> | ||||
7128 | llvm::getModuleSummaryIndex(MemoryBufferRef Buffer) { | ||||
7129 | Expected<BitcodeModule> BM = getSingleModule(Buffer); | ||||
7130 | if (!BM) | ||||
7131 | return BM.takeError(); | ||||
7132 | |||||
7133 | return BM->getSummary(); | ||||
7134 | } | ||||
7135 | |||||
7136 | Expected<BitcodeLTOInfo> llvm::getBitcodeLTOInfo(MemoryBufferRef Buffer) { | ||||
7137 | Expected<BitcodeModule> BM = getSingleModule(Buffer); | ||||
7138 | if (!BM) | ||||
7139 | return BM.takeError(); | ||||
7140 | |||||
7141 | return BM->getLTOInfo(); | ||||
7142 | } | ||||
7143 | |||||
7144 | Expected<std::unique_ptr<ModuleSummaryIndex>> | ||||
7145 | llvm::getModuleSummaryIndexForFile(StringRef Path, | ||||
7146 | bool IgnoreEmptyThinLTOIndexFile) { | ||||
7147 | ErrorOr<std::unique_ptr<MemoryBuffer>> FileOrErr = | ||||
7148 | MemoryBuffer::getFileOrSTDIN(Path); | ||||
7149 | if (!FileOrErr) | ||||
7150 | return errorCodeToError(FileOrErr.getError()); | ||||
7151 | if (IgnoreEmptyThinLTOIndexFile && !(*FileOrErr)->getBufferSize()) | ||||
7152 | return nullptr; | ||||
7153 | return getModuleSummaryIndex(**FileOrErr); | ||||
7154 | } |
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/SmallVector.h" |
18 | #include "llvm/ADT/StringExtras.h" |
19 | #include "llvm/ADT/Twine.h" |
20 | #include "llvm/Config/abi-breaking.h" |
21 | #include "llvm/Support/AlignOf.h" |
22 | #include "llvm/Support/Compiler.h" |
23 | #include "llvm/Support/Debug.h" |
24 | #include "llvm/Support/ErrorHandling.h" |
25 | #include "llvm/Support/ErrorOr.h" |
26 | #include "llvm/Support/Format.h" |
27 | #include "llvm/Support/raw_ostream.h" |
28 | #include <cassert> |
29 | #include <cstdint> |
30 | #include <cstdlib> |
31 | #include <functional> |
32 | #include <memory> |
33 | #include <new> |
34 | #include <string> |
35 | #include <system_error> |
36 | #include <type_traits> |
37 | #include <utility> |
38 | #include <vector> |
39 | |
40 | namespace llvm { |
41 | |
42 | class ErrorSuccess; |
43 | |
44 | /// Base class for error info classes. Do not extend this directly: Extend |
45 | /// the ErrorInfo template subclass instead. |
46 | class ErrorInfoBase { |
47 | public: |
48 | virtual ~ErrorInfoBase() = default; |
49 | |
50 | /// Print an error message to an output stream. |
51 | virtual void log(raw_ostream &OS) const = 0; |
52 | |
53 | /// Return the error message as a string. |
54 | virtual std::string message() const { |
55 | std::string Msg; |
56 | raw_string_ostream OS(Msg); |
57 | log(OS); |
58 | return OS.str(); |
59 | } |
60 | |
61 | /// Convert this error to a std::error_code. |
62 | /// |
63 | /// This is a temporary crutch to enable interaction with code still |
64 | /// using std::error_code. It will be removed in the future. |
65 | virtual std::error_code convertToErrorCode() const = 0; |
66 | |
67 | // Returns the class ID for this type. |
68 | static const void *classID() { return &ID; } |
69 | |
70 | // Returns the class ID for the dynamic type of this ErrorInfoBase instance. |
71 | virtual const void *dynamicClassID() const = 0; |
72 | |
73 | // Check whether this instance is a subclass of the class identified by |
74 | // ClassID. |
75 | virtual bool isA(const void *const ClassID) const { |
76 | return ClassID == classID(); |
77 | } |
78 | |
79 | // Check whether this instance is a subclass of ErrorInfoT. |
80 | template <typename ErrorInfoT> bool isA() const { |
81 | return isA(ErrorInfoT::classID()); |
82 | } |
83 | |
84 | private: |
85 | virtual void anchor(); |
86 | |
87 | static char ID; |
88 | }; |
89 | |
90 | /// Lightweight error class with error context and mandatory checking. |
91 | /// |
92 | /// Instances of this class wrap a ErrorInfoBase pointer. Failure states |
93 | /// are represented by setting the pointer to a ErrorInfoBase subclass |
94 | /// instance containing information describing the failure. Success is |
95 | /// represented by a null pointer value. |
96 | /// |
97 | /// Instances of Error also contains a 'Checked' flag, which must be set |
98 | /// before the destructor is called, otherwise the destructor will trigger a |
99 | /// runtime error. This enforces at runtime the requirement that all Error |
100 | /// instances be checked or returned to the caller. |
101 | /// |
102 | /// There are two ways to set the checked flag, depending on what state the |
103 | /// Error instance is in. For Error instances indicating success, it |
104 | /// is sufficient to invoke the boolean conversion operator. E.g.: |
105 | /// |
106 | /// @code{.cpp} |
107 | /// Error foo(<...>); |
108 | /// |
109 | /// if (auto E = foo(<...>)) |
110 | /// return E; // <- Return E if it is in the error state. |
111 | /// // We have verified that E was in the success state. It can now be safely |
112 | /// // destroyed. |
113 | /// @endcode |
114 | /// |
115 | /// A success value *can not* be dropped. For example, just calling 'foo(<...>)' |
116 | /// without testing the return value will raise a runtime error, even if foo |
117 | /// returns success. |
118 | /// |
119 | /// For Error instances representing failure, you must use either the |
120 | /// handleErrors or handleAllErrors function with a typed handler. E.g.: |
121 | /// |
122 | /// @code{.cpp} |
123 | /// class MyErrorInfo : public ErrorInfo<MyErrorInfo> { |
124 | /// // Custom error info. |
125 | /// }; |
126 | /// |
127 | /// Error foo(<...>) { return make_error<MyErrorInfo>(...); } |
128 | /// |
129 | /// auto E = foo(<...>); // <- foo returns failure with MyErrorInfo. |
130 | /// auto NewE = |
131 | /// handleErrors(E, |
132 | /// [](const MyErrorInfo &M) { |
133 | /// // Deal with the error. |
134 | /// }, |
135 | /// [](std::unique_ptr<OtherError> M) -> Error { |
136 | /// if (canHandle(*M)) { |
137 | /// // handle error. |
138 | /// return Error::success(); |
139 | /// } |
140 | /// // Couldn't handle this error instance. Pass it up the stack. |
141 | /// return Error(std::move(M)); |
142 | /// ); |
143 | /// // Note - we must check or return NewE in case any of the handlers |
144 | /// // returned a new error. |
145 | /// @endcode |
146 | /// |
147 | /// The handleAllErrors function is identical to handleErrors, except |
148 | /// that it has a void return type, and requires all errors to be handled and |
149 | /// no new errors be returned. It prevents errors (assuming they can all be |
150 | /// handled) from having to be bubbled all the way to the top-level. |
151 | /// |
152 | /// *All* Error instances must be checked before destruction, even if |
153 | /// they're moved-assigned or constructed from Success values that have already |
154 | /// been checked. This enforces checking through all levels of the call stack. |
155 | class LLVM_NODISCARD[[clang::warn_unused_result]] Error { |
156 | // ErrorList needs to be able to yank ErrorInfoBase pointers out of Errors |
157 | // to add to the error list. It can't rely on handleErrors for this, since |
158 | // handleErrors does not support ErrorList handlers. |
159 | friend class ErrorList; |
160 | |
161 | // handleErrors needs to be able to set the Checked flag. |
162 | template <typename... HandlerTs> |
163 | friend Error handleErrors(Error E, HandlerTs &&... Handlers); |
164 | |
165 | // Expected<T> needs to be able to steal the payload when constructed from an |
166 | // error. |
167 | template <typename T> friend class Expected; |
168 | |
169 | // wrap needs to be able to steal the payload. |
170 | friend LLVMErrorRef wrap(Error); |
171 | |
172 | protected: |
173 | /// Create a success value. Prefer using 'Error::success()' for readability |
174 | Error() { |
175 | setPtr(nullptr); |
176 | setChecked(false); |
177 | } |
178 | |
179 | public: |
180 | /// Create a success value. |
181 | static ErrorSuccess success(); |
182 | |
183 | // Errors are not copy-constructable. |
184 | Error(const Error &Other) = delete; |
185 | |
186 | /// Move-construct an error value. The newly constructed error is considered |
187 | /// unchecked, even if the source error had been checked. The original error |
188 | /// becomes a checked Success value, regardless of its original state. |
189 | Error(Error &&Other) { |
190 | setChecked(true); |
191 | *this = std::move(Other); |
192 | } |
193 | |
194 | /// Create an error value. Prefer using the 'make_error' function, but |
195 | /// this constructor can be useful when "re-throwing" errors from handlers. |
196 | Error(std::unique_ptr<ErrorInfoBase> Payload) { |
197 | setPtr(Payload.release()); |
198 | setChecked(false); |
199 | } |
200 | |
201 | // Errors are not copy-assignable. |
202 | Error &operator=(const Error &Other) = delete; |
203 | |
204 | /// Move-assign an error value. The current error must represent success, you |
205 | /// you cannot overwrite an unhandled error. The current error is then |
206 | /// considered unchecked. The source error becomes a checked success value, |
207 | /// regardless of its original state. |
208 | Error &operator=(Error &&Other) { |
209 | // Don't allow overwriting of unchecked values. |
210 | assertIsChecked(); |
211 | setPtr(Other.getPtr()); |
212 | |
213 | // This Error is unchecked, even if the source error was checked. |
214 | setChecked(false); |
215 | |
216 | // Null out Other's payload and set its checked bit. |
217 | Other.setPtr(nullptr); |
218 | Other.setChecked(true); |
219 | |
220 | return *this; |
221 | } |
222 | |
223 | /// Destroy a Error. Fails with a call to abort() if the error is |
224 | /// unchecked. |
225 | ~Error() { |
226 | assertIsChecked(); |
227 | delete getPtr(); |
228 | } |
229 | |
230 | /// Bool conversion. Returns true if this Error is in a failure state, |
231 | /// and false if it is in an accept state. If the error is in a Success state |
232 | /// it will be considered checked. |
233 | explicit operator bool() { |
234 | setChecked(getPtr() == nullptr); |
235 | return getPtr() != nullptr; |
236 | } |
237 | |
238 | /// Check whether one error is a subclass of another. |
239 | template <typename ErrT> bool isA() const { |
240 | return getPtr() && getPtr()->isA(ErrT::classID()); |
241 | } |
242 | |
243 | /// Returns the dynamic class id of this error, or null if this is a success |
244 | /// value. |
245 | const void* dynamicClassID() const { |
246 | if (!getPtr()) |
247 | return nullptr; |
248 | return getPtr()->dynamicClassID(); |
249 | } |
250 | |
251 | private: |
252 | #if LLVM_ENABLE_ABI_BREAKING_CHECKS1 |
253 | // assertIsChecked() happens very frequently, but under normal circumstances |
254 | // is supposed to be a no-op. So we want it to be inlined, but having a bunch |
255 | // of debug prints can cause the function to be too large for inlining. So |
256 | // it's important that we define this function out of line so that it can't be |
257 | // inlined. |
258 | [[noreturn]] void fatalUncheckedError() const; |
259 | #endif |
260 | |
261 | void assertIsChecked() { |
262 | #if LLVM_ENABLE_ABI_BREAKING_CHECKS1 |
263 | if (LLVM_UNLIKELY(!getChecked() || getPtr())__builtin_expect((bool)(!getChecked() || getPtr()), false)) |
264 | fatalUncheckedError(); |
265 | #endif |
266 | } |
267 | |
268 | ErrorInfoBase *getPtr() const { |
269 | #if LLVM_ENABLE_ABI_BREAKING_CHECKS1 |
270 | return reinterpret_cast<ErrorInfoBase*>( |
271 | reinterpret_cast<uintptr_t>(Payload) & |
272 | ~static_cast<uintptr_t>(0x1)); |
273 | #else |
274 | return Payload; |
275 | #endif |
276 | } |
277 | |
278 | void setPtr(ErrorInfoBase *EI) { |
279 | #if LLVM_ENABLE_ABI_BREAKING_CHECKS1 |
280 | Payload = reinterpret_cast<ErrorInfoBase*>( |
281 | (reinterpret_cast<uintptr_t>(EI) & |
282 | ~static_cast<uintptr_t>(0x1)) | |
283 | (reinterpret_cast<uintptr_t>(Payload) & 0x1)); |
284 | #else |
285 | Payload = EI; |
286 | #endif |
287 | } |
288 | |
289 | bool getChecked() const { |
290 | #if LLVM_ENABLE_ABI_BREAKING_CHECKS1 |
291 | return (reinterpret_cast<uintptr_t>(Payload) & 0x1) == 0; |
292 | #else |
293 | return true; |
294 | #endif |
295 | } |
296 | |
297 | void setChecked(bool V) { |
298 | #if LLVM_ENABLE_ABI_BREAKING_CHECKS1 |
299 | Payload = reinterpret_cast<ErrorInfoBase*>( |
300 | (reinterpret_cast<uintptr_t>(Payload) & |
301 | ~static_cast<uintptr_t>(0x1)) | |
302 | (V ? 0 : 1)); |
303 | #endif |
304 | } |
305 | |
306 | std::unique_ptr<ErrorInfoBase> takePayload() { |
307 | std::unique_ptr<ErrorInfoBase> Tmp(getPtr()); |
308 | setPtr(nullptr); |
309 | setChecked(true); |
310 | return Tmp; |
311 | } |
312 | |
313 | friend raw_ostream &operator<<(raw_ostream &OS, const Error &E) { |
314 | if (auto *P = E.getPtr()) |
315 | P->log(OS); |
316 | else |
317 | OS << "success"; |
318 | return OS; |
319 | } |
320 | |
321 | ErrorInfoBase *Payload = nullptr; |
322 | }; |
323 | |
324 | /// Subclass of Error for the sole purpose of identifying the success path in |
325 | /// the type system. This allows to catch invalid conversion to Expected<T> at |
326 | /// compile time. |
327 | class ErrorSuccess final : public Error {}; |
328 | |
329 | inline ErrorSuccess Error::success() { return ErrorSuccess(); } |
330 | |
331 | /// Make a Error instance representing failure using the given error info |
332 | /// type. |
333 | template <typename ErrT, typename... ArgTs> Error make_error(ArgTs &&... Args) { |
334 | return Error(std::make_unique<ErrT>(std::forward<ArgTs>(Args)...)); |
335 | } |
336 | |
337 | /// Base class for user error types. Users should declare their error types |
338 | /// like: |
339 | /// |
340 | /// class MyError : public ErrorInfo<MyError> { |
341 | /// .... |
342 | /// }; |
343 | /// |
344 | /// This class provides an implementation of the ErrorInfoBase::kind |
345 | /// method, which is used by the Error RTTI system. |
346 | template <typename ThisErrT, typename ParentErrT = ErrorInfoBase> |
347 | class ErrorInfo : public ParentErrT { |
348 | public: |
349 | using ParentErrT::ParentErrT; // inherit constructors |
350 | |
351 | static const void *classID() { return &ThisErrT::ID; } |
352 | |
353 | const void *dynamicClassID() const override { return &ThisErrT::ID; } |
354 | |
355 | bool isA(const void *const ClassID) const override { |
356 | return ClassID == classID() || ParentErrT::isA(ClassID); |
357 | } |
358 | }; |
359 | |
360 | /// Special ErrorInfo subclass representing a list of ErrorInfos. |
361 | /// Instances of this class are constructed by joinError. |
362 | class ErrorList final : public ErrorInfo<ErrorList> { |
363 | // handleErrors needs to be able to iterate the payload list of an |
364 | // ErrorList. |
365 | template <typename... HandlerTs> |
366 | friend Error handleErrors(Error E, HandlerTs &&... Handlers); |
367 | |
368 | // joinErrors is implemented in terms of join. |
369 | friend Error joinErrors(Error, Error); |
370 | |
371 | public: |
372 | void log(raw_ostream &OS) const override { |
373 | OS << "Multiple errors:\n"; |
374 | for (const auto &ErrPayload : Payloads) { |
375 | ErrPayload->log(OS); |
376 | OS << "\n"; |
377 | } |
378 | } |
379 | |
380 | std::error_code convertToErrorCode() const override; |
381 | |
382 | // Used by ErrorInfo::classID. |
383 | static char ID; |
384 | |
385 | private: |
386 | ErrorList(std::unique_ptr<ErrorInfoBase> Payload1, |
387 | std::unique_ptr<ErrorInfoBase> Payload2) { |
388 | assert(!Payload1->isA<ErrorList>() && !Payload2->isA<ErrorList>() &&(static_cast <bool> (!Payload1->isA<ErrorList> () && !Payload2->isA<ErrorList>() && "ErrorList constructor payloads should be singleton errors") ? void (0) : __assert_fail ("!Payload1->isA<ErrorList>() && !Payload2->isA<ErrorList>() && \"ErrorList constructor payloads should be singleton errors\"" , "llvm/include/llvm/Support/Error.h", 389, __extension__ __PRETTY_FUNCTION__ )) |
389 | "ErrorList constructor payloads should be singleton errors")(static_cast <bool> (!Payload1->isA<ErrorList> () && !Payload2->isA<ErrorList>() && "ErrorList constructor payloads should be singleton errors") ? void (0) : __assert_fail ("!Payload1->isA<ErrorList>() && !Payload2->isA<ErrorList>() && \"ErrorList constructor payloads should be singleton errors\"" , "llvm/include/llvm/Support/Error.h", 389, __extension__ __PRETTY_FUNCTION__ )); |
390 | Payloads.push_back(std::move(Payload1)); |
391 | Payloads.push_back(std::move(Payload2)); |
392 | } |
393 | |
394 | static Error join(Error E1, Error E2) { |
395 | if (!E1) |
396 | return E2; |
397 | if (!E2) |
398 | return E1; |
399 | if (E1.isA<ErrorList>()) { |
400 | auto &E1List = static_cast<ErrorList &>(*E1.getPtr()); |
401 | if (E2.isA<ErrorList>()) { |
402 | auto E2Payload = E2.takePayload(); |
403 | auto &E2List = static_cast<ErrorList &>(*E2Payload); |
404 | for (auto &Payload : E2List.Payloads) |
405 | E1List.Payloads.push_back(std::move(Payload)); |
406 | } else |
407 | E1List.Payloads.push_back(E2.takePayload()); |
408 | |
409 | return E1; |
410 | } |
411 | if (E2.isA<ErrorList>()) { |
412 | auto &E2List = static_cast<ErrorList &>(*E2.getPtr()); |
413 | E2List.Payloads.insert(E2List.Payloads.begin(), E1.takePayload()); |
414 | return E2; |
415 | } |
416 | return Error(std::unique_ptr<ErrorList>( |
417 | new ErrorList(E1.takePayload(), E2.takePayload()))); |
418 | } |
419 | |
420 | std::vector<std::unique_ptr<ErrorInfoBase>> Payloads; |
421 | }; |
422 | |
423 | /// Concatenate errors. The resulting Error is unchecked, and contains the |
424 | /// ErrorInfo(s), if any, contained in E1, followed by the |
425 | /// ErrorInfo(s), if any, contained in E2. |
426 | inline Error joinErrors(Error E1, Error E2) { |
427 | return ErrorList::join(std::move(E1), std::move(E2)); |
428 | } |
429 | |
430 | /// Tagged union holding either a T or a Error. |
431 | /// |
432 | /// This class parallels ErrorOr, but replaces error_code with Error. Since |
433 | /// Error cannot be copied, this class replaces getError() with |
434 | /// takeError(). It also adds an bool errorIsA<ErrT>() method for testing the |
435 | /// error class type. |
436 | /// |
437 | /// Example usage of 'Expected<T>' as a function return type: |
438 | /// |
439 | /// @code{.cpp} |
440 | /// Expected<int> myDivide(int A, int B) { |
441 | /// if (B == 0) { |
442 | /// // return an Error |
443 | /// return createStringError(inconvertibleErrorCode(), |
444 | /// "B must not be zero!"); |
445 | /// } |
446 | /// // return an integer |
447 | /// return A / B; |
448 | /// } |
449 | /// @endcode |
450 | /// |
451 | /// Checking the results of to a function returning 'Expected<T>': |
452 | /// @code{.cpp} |
453 | /// if (auto E = Result.takeError()) { |
454 | /// // We must consume the error. Typically one of: |
455 | /// // - return the error to our caller |
456 | /// // - toString(), when logging |
457 | /// // - consumeError(), to silently swallow the error |
458 | /// // - handleErrors(), to distinguish error types |
459 | /// errs() << "Problem with division " << toString(std::move(E)) << "\n"; |
460 | /// return; |
461 | /// } |
462 | /// // use the result |
463 | /// outs() << "The answer is " << *Result << "\n"; |
464 | /// @endcode |
465 | /// |
466 | /// For unit-testing a function returning an 'Expceted<T>', see the |
467 | /// 'EXPECT_THAT_EXPECTED' macros in llvm/Testing/Support/Error.h |
468 | |
469 | template <class T> class LLVM_NODISCARD[[clang::warn_unused_result]] Expected { |
470 | template <class T1> friend class ExpectedAsOutParameter; |
471 | template <class OtherT> friend class Expected; |
472 | |
473 | static constexpr bool isRef = std::is_reference<T>::value; |
474 | |
475 | using wrap = std::reference_wrapper<std::remove_reference_t<T>>; |
476 | |
477 | using error_type = std::unique_ptr<ErrorInfoBase>; |
478 | |
479 | public: |
480 | using storage_type = std::conditional_t<isRef, wrap, T>; |
481 | using value_type = T; |
482 | |
483 | private: |
484 | using reference = std::remove_reference_t<T> &; |
485 | using const_reference = const std::remove_reference_t<T> &; |
486 | using pointer = std::remove_reference_t<T> *; |
487 | using const_pointer = const std::remove_reference_t<T> *; |
488 | |
489 | public: |
490 | /// Create an Expected<T> error value from the given Error. |
491 | Expected(Error Err) |
492 | : HasError(true) |
493 | #if LLVM_ENABLE_ABI_BREAKING_CHECKS1 |
494 | // Expected is unchecked upon construction in Debug builds. |
495 | , Unchecked(true) |
496 | #endif |
497 | { |
498 | assert(Err && "Cannot create Expected<T> from Error success value.")(static_cast <bool> (Err && "Cannot create Expected<T> from Error success value." ) ? void (0) : __assert_fail ("Err && \"Cannot create Expected<T> from Error success value.\"" , "llvm/include/llvm/Support/Error.h", 498, __extension__ __PRETTY_FUNCTION__ )); |
499 | new (getErrorStorage()) error_type(Err.takePayload()); |
500 | } |
501 | |
502 | /// Forbid to convert from Error::success() implicitly, this avoids having |
503 | /// Expected<T> foo() { return Error::success(); } which compiles otherwise |
504 | /// but triggers the assertion above. |
505 | Expected(ErrorSuccess) = delete; |
506 | |
507 | /// Create an Expected<T> success value from the given OtherT value, which |
508 | /// must be convertible to T. |
509 | template <typename OtherT> |
510 | Expected(OtherT &&Val, |
511 | std::enable_if_t<std::is_convertible<OtherT, T>::value> * = nullptr) |
512 | : HasError(false) |
513 | #if LLVM_ENABLE_ABI_BREAKING_CHECKS1 |
514 | // Expected is unchecked upon construction in Debug builds. |
515 | , |
516 | Unchecked(true) |
517 | #endif |
518 | { |
519 | new (getStorage()) storage_type(std::forward<OtherT>(Val)); |
520 | } |
521 | |
522 | /// Move construct an Expected<T> value. |
523 | Expected(Expected &&Other) { moveConstruct(std::move(Other)); } |
524 | |
525 | /// Move construct an Expected<T> value from an Expected<OtherT>, where OtherT |
526 | /// must be convertible to T. |
527 | template <class OtherT> |
528 | Expected( |
529 | Expected<OtherT> &&Other, |
530 | std::enable_if_t<std::is_convertible<OtherT, T>::value> * = nullptr) { |
531 | moveConstruct(std::move(Other)); |
532 | } |
533 | |
534 | /// Move construct an Expected<T> value from an Expected<OtherT>, where OtherT |
535 | /// isn't convertible to T. |
536 | template <class OtherT> |
537 | explicit Expected( |
538 | Expected<OtherT> &&Other, |
539 | std::enable_if_t<!std::is_convertible<OtherT, T>::value> * = nullptr) { |
540 | moveConstruct(std::move(Other)); |
541 | } |
542 | |
543 | /// Move-assign from another Expected<T>. |
544 | Expected &operator=(Expected &&Other) { |
545 | moveAssign(std::move(Other)); |
546 | return *this; |
547 | } |
548 | |
549 | /// Destroy an Expected<T>. |
550 | ~Expected() { |
551 | assertIsChecked(); |
552 | if (!HasError) |
553 | getStorage()->~storage_type(); |
554 | else |
555 | getErrorStorage()->~error_type(); |
556 | } |
557 | |
558 | /// Return false if there is an error. |
559 | explicit operator bool() { |
560 | #if LLVM_ENABLE_ABI_BREAKING_CHECKS1 |
561 | Unchecked = HasError; |
562 | #endif |
563 | return !HasError; |
564 | } |
565 | |
566 | /// Returns a reference to the stored T value. |
567 | reference get() { |
568 | assertIsChecked(); |
569 | return *getStorage(); |
570 | } |
571 | |
572 | /// Returns a const reference to the stored T value. |
573 | const_reference get() const { |
574 | assertIsChecked(); |
575 | return const_cast<Expected<T> *>(this)->get(); |
576 | } |
577 | |
578 | /// Returns \a takeError() after moving the held T (if any) into \p V. |
579 | template <class OtherT> |
580 | Error moveInto(OtherT &Value, |
581 | std::enable_if_t<std::is_assignable<OtherT &, T &&>::value> * = |
582 | nullptr) && { |
583 | if (*this) |
584 | Value = std::move(get()); |
585 | return takeError(); |
586 | } |
587 | |
588 | /// Check that this Expected<T> is an error of type ErrT. |
589 | template <typename ErrT> bool errorIsA() const { |
590 | return HasError && (*getErrorStorage())->template isA<ErrT>(); |
591 | } |
592 | |
593 | /// Take ownership of the stored error. |
594 | /// After calling this the Expected<T> is in an indeterminate state that can |
595 | /// only be safely destructed. No further calls (beside the destructor) should |
596 | /// be made on the Expected<T> value. |
597 | Error takeError() { |
598 | #if LLVM_ENABLE_ABI_BREAKING_CHECKS1 |
599 | Unchecked = false; |
600 | #endif |
601 | return HasError ? Error(std::move(*getErrorStorage())) : Error::success(); |
602 | } |
603 | |
604 | /// Returns a pointer to the stored T value. |
605 | pointer operator->() { |
606 | assertIsChecked(); |
607 | return toPointer(getStorage()); |
608 | } |
609 | |
610 | /// Returns a const pointer to the stored T value. |
611 | const_pointer operator->() const { |
612 | assertIsChecked(); |
613 | return toPointer(getStorage()); |
614 | } |
615 | |
616 | /// Returns a reference to the stored T value. |
617 | reference operator*() { |
618 | assertIsChecked(); |
619 | return *getStorage(); |
620 | } |
621 | |
622 | /// Returns a const reference to the stored T value. |
623 | const_reference operator*() const { |
624 | assertIsChecked(); |
625 | return *getStorage(); |
626 | } |
627 | |
628 | private: |
629 | template <class T1> |
630 | static bool compareThisIfSameType(const T1 &a, const T1 &b) { |
631 | return &a == &b; |
632 | } |
633 | |
634 | template <class T1, class T2> |
635 | static bool compareThisIfSameType(const T1 &, const T2 &) { |
636 | return false; |
637 | } |
638 | |
639 | template <class OtherT> void moveConstruct(Expected<OtherT> &&Other) { |
640 | HasError = Other.HasError; |
641 | #if LLVM_ENABLE_ABI_BREAKING_CHECKS1 |
642 | Unchecked = true; |
643 | Other.Unchecked = false; |
644 | #endif |
645 | |
646 | if (!HasError) |
647 | new (getStorage()) storage_type(std::move(*Other.getStorage())); |
648 | else |
649 | new (getErrorStorage()) error_type(std::move(*Other.getErrorStorage())); |
650 | } |
651 | |
652 | template <class OtherT> void moveAssign(Expected<OtherT> &&Other) { |
653 | assertIsChecked(); |
654 | |
655 | if (compareThisIfSameType(*this, Other)) |
656 | return; |
657 | |
658 | this->~Expected(); |
659 | new (this) Expected(std::move(Other)); |
660 | } |
661 | |
662 | pointer toPointer(pointer Val) { return Val; } |
663 | |
664 | const_pointer toPointer(const_pointer Val) const { return Val; } |
665 | |
666 | pointer toPointer(wrap *Val) { return &Val->get(); } |
667 | |
668 | const_pointer toPointer(const wrap *Val) const { return &Val->get(); } |
669 | |
670 | storage_type *getStorage() { |
671 | assert(!HasError && "Cannot get value when an error exists!")(static_cast <bool> (!HasError && "Cannot get value when an error exists!" ) ? void (0) : __assert_fail ("!HasError && \"Cannot get value when an error exists!\"" , "llvm/include/llvm/Support/Error.h", 671, __extension__ __PRETTY_FUNCTION__ )); |
672 | return reinterpret_cast<storage_type *>(&TStorage); |
673 | } |
674 | |
675 | const storage_type *getStorage() const { |
676 | assert(!HasError && "Cannot get value when an error exists!")(static_cast <bool> (!HasError && "Cannot get value when an error exists!" ) ? void (0) : __assert_fail ("!HasError && \"Cannot get value when an error exists!\"" , "llvm/include/llvm/Support/Error.h", 676, __extension__ __PRETTY_FUNCTION__ )); |
677 | return reinterpret_cast<const storage_type *>(&TStorage); |
678 | } |
679 | |
680 | error_type *getErrorStorage() { |
681 | assert(HasError && "Cannot get error when a value exists!")(static_cast <bool> (HasError && "Cannot get error when a value exists!" ) ? void (0) : __assert_fail ("HasError && \"Cannot get error when a value exists!\"" , "llvm/include/llvm/Support/Error.h", 681, __extension__ __PRETTY_FUNCTION__ )); |
682 | return reinterpret_cast<error_type *>(&ErrorStorage); |
683 | } |
684 | |
685 | const error_type *getErrorStorage() const { |
686 | assert(HasError && "Cannot get error when a value exists!")(static_cast <bool> (HasError && "Cannot get error when a value exists!" ) ? void (0) : __assert_fail ("HasError && \"Cannot get error when a value exists!\"" , "llvm/include/llvm/Support/Error.h", 686, __extension__ __PRETTY_FUNCTION__ )); |
687 | return reinterpret_cast<const error_type *>(&ErrorStorage); |
688 | } |
689 | |
690 | // Used by ExpectedAsOutParameter to reset the checked flag. |
691 | void setUnchecked() { |
692 | #if LLVM_ENABLE_ABI_BREAKING_CHECKS1 |
693 | Unchecked = true; |
694 | #endif |
695 | } |
696 | |
697 | #if LLVM_ENABLE_ABI_BREAKING_CHECKS1 |
698 | [[noreturn]] LLVM_ATTRIBUTE_NOINLINE__attribute__((noinline)) void fatalUncheckedExpected() const { |
699 | dbgs() << "Expected<T> must be checked before access or destruction.\n"; |
700 | if (HasError) { |
701 | dbgs() << "Unchecked Expected<T> contained error:\n"; |
702 | (*getErrorStorage())->log(dbgs()); |
703 | } else |
704 | dbgs() << "Expected<T> value was in success state. (Note: Expected<T> " |
705 | "values in success mode must still be checked prior to being " |
706 | "destroyed).\n"; |
707 | abort(); |
708 | } |
709 | #endif |
710 | |
711 | void assertIsChecked() const { |
712 | #if LLVM_ENABLE_ABI_BREAKING_CHECKS1 |
713 | if (LLVM_UNLIKELY(Unchecked)__builtin_expect((bool)(Unchecked), false)) |
714 | fatalUncheckedExpected(); |
715 | #endif |
716 | } |
717 | |
718 | union { |
719 | AlignedCharArrayUnion<storage_type> TStorage; |
720 | AlignedCharArrayUnion<error_type> ErrorStorage; |
721 | }; |
722 | bool HasError : 1; |
723 | #if LLVM_ENABLE_ABI_BREAKING_CHECKS1 |
724 | bool Unchecked : 1; |
725 | #endif |
726 | }; |
727 | |
728 | /// Report a serious error, calling any installed error handler. See |
729 | /// ErrorHandling.h. |
730 | [[noreturn]] void report_fatal_error(Error Err, bool gen_crash_diag = true); |
731 | |
732 | /// Report a fatal error if Err is a failure value. |
733 | /// |
734 | /// This function can be used to wrap calls to fallible functions ONLY when it |
735 | /// is known that the Error will always be a success value. E.g. |
736 | /// |
737 | /// @code{.cpp} |
738 | /// // foo only attempts the fallible operation if DoFallibleOperation is |
739 | /// // true. If DoFallibleOperation is false then foo always returns |
740 | /// // Error::success(). |
741 | /// Error foo(bool DoFallibleOperation); |
742 | /// |
743 | /// cantFail(foo(false)); |
744 | /// @endcode |
745 | inline void cantFail(Error Err, const char *Msg = nullptr) { |
746 | if (Err) { |
747 | if (!Msg) |
748 | Msg = "Failure value returned from cantFail wrapped call"; |
749 | #ifndef NDEBUG |
750 | std::string Str; |
751 | raw_string_ostream OS(Str); |
752 | OS << Msg << "\n" << Err; |
753 | Msg = OS.str().c_str(); |
754 | #endif |
755 | llvm_unreachable(Msg)::llvm::llvm_unreachable_internal(Msg, "llvm/include/llvm/Support/Error.h" , 755); |
756 | } |
757 | } |
758 | |
759 | /// Report a fatal error if ValOrErr is a failure value, otherwise unwraps and |
760 | /// returns the contained value. |
761 | /// |
762 | /// This function can be used to wrap calls to fallible functions ONLY when it |
763 | /// is known that the Error will always be a success value. E.g. |
764 | /// |
765 | /// @code{.cpp} |
766 | /// // foo only attempts the fallible operation if DoFallibleOperation is |
767 | /// // true. If DoFallibleOperation is false then foo always returns an int. |
768 | /// Expected<int> foo(bool DoFallibleOperation); |
769 | /// |
770 | /// int X = cantFail(foo(false)); |
771 | /// @endcode |
772 | template <typename T> |
773 | T cantFail(Expected<T> ValOrErr, const char *Msg = nullptr) { |
774 | if (ValOrErr) |
775 | return std::move(*ValOrErr); |
776 | else { |
777 | if (!Msg) |
778 | Msg = "Failure value returned from cantFail wrapped call"; |
779 | #ifndef NDEBUG |
780 | std::string Str; |
781 | raw_string_ostream OS(Str); |
782 | auto E = ValOrErr.takeError(); |
783 | OS << Msg << "\n" << E; |
784 | Msg = OS.str().c_str(); |
785 | #endif |
786 | llvm_unreachable(Msg)::llvm::llvm_unreachable_internal(Msg, "llvm/include/llvm/Support/Error.h" , 786); |
787 | } |
788 | } |
789 | |
790 | /// Report a fatal error if ValOrErr is a failure value, otherwise unwraps and |
791 | /// returns the contained reference. |
792 | /// |
793 | /// This function can be used to wrap calls to fallible functions ONLY when it |
794 | /// is known that the Error will always be a success value. E.g. |
795 | /// |
796 | /// @code{.cpp} |
797 | /// // foo only attempts the fallible operation if DoFallibleOperation is |
798 | /// // true. If DoFallibleOperation is false then foo always returns a Bar&. |
799 | /// Expected<Bar&> foo(bool DoFallibleOperation); |
800 | /// |
801 | /// Bar &X = cantFail(foo(false)); |
802 | /// @endcode |
803 | template <typename T> |
804 | T& cantFail(Expected<T&> ValOrErr, const char *Msg = nullptr) { |
805 | if (ValOrErr) |
806 | return *ValOrErr; |
807 | else { |
808 | if (!Msg) |
809 | Msg = "Failure value returned from cantFail wrapped call"; |
810 | #ifndef NDEBUG |
811 | std::string Str; |
812 | raw_string_ostream OS(Str); |
813 | auto E = ValOrErr.takeError(); |
814 | OS << Msg << "\n" << E; |
815 | Msg = OS.str().c_str(); |
816 | #endif |
817 | llvm_unreachable(Msg)::llvm::llvm_unreachable_internal(Msg, "llvm/include/llvm/Support/Error.h" , 817); |
818 | } |
819 | } |
820 | |
821 | /// Helper for testing applicability of, and applying, handlers for |
822 | /// ErrorInfo types. |
823 | template <typename HandlerT> |
824 | class ErrorHandlerTraits |
825 | : public ErrorHandlerTraits<decltype( |
826 | &std::remove_reference<HandlerT>::type::operator())> {}; |
827 | |
828 | // Specialization functions of the form 'Error (const ErrT&)'. |
829 | template <typename ErrT> class ErrorHandlerTraits<Error (&)(ErrT &)> { |
830 | public: |
831 | static bool appliesTo(const ErrorInfoBase &E) { |
832 | return E.template isA<ErrT>(); |
833 | } |
834 | |
835 | template <typename HandlerT> |
836 | static Error apply(HandlerT &&H, std::unique_ptr<ErrorInfoBase> E) { |
837 | assert(appliesTo(*E) && "Applying incorrect handler")(static_cast <bool> (appliesTo(*E) && "Applying incorrect handler" ) ? void (0) : __assert_fail ("appliesTo(*E) && \"Applying incorrect handler\"" , "llvm/include/llvm/Support/Error.h", 837, __extension__ __PRETTY_FUNCTION__ )); |
838 | return H(static_cast<ErrT &>(*E)); |
839 | } |
840 | }; |
841 | |
842 | // Specialization functions of the form 'void (const ErrT&)'. |
843 | template <typename ErrT> class ErrorHandlerTraits<void (&)(ErrT &)> { |
844 | public: |
845 | static bool appliesTo(const ErrorInfoBase &E) { |
846 | return E.template isA<ErrT>(); |
847 | } |
848 | |
849 | template <typename HandlerT> |
850 | static Error apply(HandlerT &&H, std::unique_ptr<ErrorInfoBase> E) { |
851 | assert(appliesTo(*E) && "Applying incorrect handler")(static_cast <bool> (appliesTo(*E) && "Applying incorrect handler" ) ? void (0) : __assert_fail ("appliesTo(*E) && \"Applying incorrect handler\"" , "llvm/include/llvm/Support/Error.h", 851, __extension__ __PRETTY_FUNCTION__ )); |
852 | H(static_cast<ErrT &>(*E)); |
853 | return Error::success(); |
854 | } |
855 | }; |
856 | |
857 | /// Specialization for functions of the form 'Error (std::unique_ptr<ErrT>)'. |
858 | template <typename ErrT> |
859 | class ErrorHandlerTraits<Error (&)(std::unique_ptr<ErrT>)> { |
860 | public: |
861 | static bool appliesTo(const ErrorInfoBase &E) { |
862 | return E.template isA<ErrT>(); |
863 | } |
864 | |
865 | template <typename HandlerT> |
866 | static Error apply(HandlerT &&H, std::unique_ptr<ErrorInfoBase> E) { |
867 | assert(appliesTo(*E) && "Applying incorrect handler")(static_cast <bool> (appliesTo(*E) && "Applying incorrect handler" ) ? void (0) : __assert_fail ("appliesTo(*E) && \"Applying incorrect handler\"" , "llvm/include/llvm/Support/Error.h", 867, __extension__ __PRETTY_FUNCTION__ )); |
868 | std::unique_ptr<ErrT> SubE(static_cast<ErrT *>(E.release())); |
869 | return H(std::move(SubE)); |
870 | } |
871 | }; |
872 | |
873 | /// Specialization for functions of the form 'void (std::unique_ptr<ErrT>)'. |
874 | template <typename ErrT> |
875 | class ErrorHandlerTraits<void (&)(std::unique_ptr<ErrT>)> { |
876 | public: |
877 | static bool appliesTo(const ErrorInfoBase &E) { |
878 | return E.template isA<ErrT>(); |
879 | } |
880 | |
881 | template <typename HandlerT> |
882 | static Error apply(HandlerT &&H, std::unique_ptr<ErrorInfoBase> E) { |
883 | assert(appliesTo(*E) && "Applying incorrect handler")(static_cast <bool> (appliesTo(*E) && "Applying incorrect handler" ) ? void (0) : __assert_fail ("appliesTo(*E) && \"Applying incorrect handler\"" , "llvm/include/llvm/Support/Error.h", 883, __extension__ __PRETTY_FUNCTION__ )); |
884 | std::unique_ptr<ErrT> SubE(static_cast<ErrT *>(E.release())); |
885 | H(std::move(SubE)); |
886 | return Error::success(); |
887 | } |
888 | }; |
889 | |
890 | // Specialization for member functions of the form 'RetT (const ErrT&)'. |
891 | template <typename C, typename RetT, typename ErrT> |
892 | class ErrorHandlerTraits<RetT (C::*)(ErrT &)> |
893 | : public ErrorHandlerTraits<RetT (&)(ErrT &)> {}; |
894 | |
895 | // Specialization for member functions of the form 'RetT (const ErrT&) const'. |
896 | template <typename C, typename RetT, typename ErrT> |
897 | class ErrorHandlerTraits<RetT (C::*)(ErrT &) const> |
898 | : public ErrorHandlerTraits<RetT (&)(ErrT &)> {}; |
899 | |
900 | // Specialization for member functions of the form 'RetT (const ErrT&)'. |
901 | template <typename C, typename RetT, typename ErrT> |
902 | class ErrorHandlerTraits<RetT (C::*)(const ErrT &)> |
903 | : public ErrorHandlerTraits<RetT (&)(ErrT &)> {}; |
904 | |
905 | // Specialization for member functions of the form 'RetT (const ErrT&) const'. |
906 | template <typename C, typename RetT, typename ErrT> |
907 | class ErrorHandlerTraits<RetT (C::*)(const ErrT &) const> |
908 | : public ErrorHandlerTraits<RetT (&)(ErrT &)> {}; |
909 | |
910 | /// Specialization for member functions of the form |
911 | /// 'RetT (std::unique_ptr<ErrT>)'. |
912 | template <typename C, typename RetT, typename ErrT> |
913 | class ErrorHandlerTraits<RetT (C::*)(std::unique_ptr<ErrT>)> |
914 | : public ErrorHandlerTraits<RetT (&)(std::unique_ptr<ErrT>)> {}; |
915 | |
916 | /// Specialization for member functions of the form |
917 | /// 'RetT (std::unique_ptr<ErrT>) const'. |
918 | template <typename C, typename RetT, typename ErrT> |
919 | class ErrorHandlerTraits<RetT (C::*)(std::unique_ptr<ErrT>) const> |
920 | : public ErrorHandlerTraits<RetT (&)(std::unique_ptr<ErrT>)> {}; |
921 | |
922 | inline Error handleErrorImpl(std::unique_ptr<ErrorInfoBase> Payload) { |
923 | return Error(std::move(Payload)); |
924 | } |
925 | |
926 | template <typename HandlerT, typename... HandlerTs> |
927 | Error handleErrorImpl(std::unique_ptr<ErrorInfoBase> Payload, |
928 | HandlerT &&Handler, HandlerTs &&... Handlers) { |
929 | if (ErrorHandlerTraits<HandlerT>::appliesTo(*Payload)) |
930 | return ErrorHandlerTraits<HandlerT>::apply(std::forward<HandlerT>(Handler), |
931 | std::move(Payload)); |
932 | return handleErrorImpl(std::move(Payload), |
933 | std::forward<HandlerTs>(Handlers)...); |
934 | } |
935 | |
936 | /// Pass the ErrorInfo(s) contained in E to their respective handlers. Any |
937 | /// unhandled errors (or Errors returned by handlers) are re-concatenated and |
938 | /// returned. |
939 | /// Because this function returns an error, its result must also be checked |
940 | /// or returned. If you intend to handle all errors use handleAllErrors |
941 | /// (which returns void, and will abort() on unhandled errors) instead. |
942 | template <typename... HandlerTs> |
943 | Error handleErrors(Error E, HandlerTs &&... Hs) { |
944 | if (!E) |
945 | return Error::success(); |
946 | |
947 | std::unique_ptr<ErrorInfoBase> Payload = E.takePayload(); |
948 | |
949 | if (Payload->isA<ErrorList>()) { |
950 | ErrorList &List = static_cast<ErrorList &>(*Payload); |
951 | Error R; |
952 | for (auto &P : List.Payloads) |
953 | R = ErrorList::join( |
954 | std::move(R), |
955 | handleErrorImpl(std::move(P), std::forward<HandlerTs>(Hs)...)); |
956 | return R; |
957 | } |
958 | |
959 | return handleErrorImpl(std::move(Payload), std::forward<HandlerTs>(Hs)...); |
960 | } |
961 | |
962 | /// Behaves the same as handleErrors, except that by contract all errors |
963 | /// *must* be handled by the given handlers (i.e. there must be no remaining |
964 | /// errors after running the handlers, or llvm_unreachable is called). |
965 | template <typename... HandlerTs> |
966 | void handleAllErrors(Error E, HandlerTs &&... Handlers) { |
967 | cantFail(handleErrors(std::move(E), std::forward<HandlerTs>(Handlers)...)); |
968 | } |
969 | |
970 | /// Check that E is a non-error, then drop it. |
971 | /// If E is an error, llvm_unreachable will be called. |
972 | inline void handleAllErrors(Error E) { |
973 | cantFail(std::move(E)); |
974 | } |
975 | |
976 | /// Handle any errors (if present) in an Expected<T>, then try a recovery path. |
977 | /// |
978 | /// If the incoming value is a success value it is returned unmodified. If it |
979 | /// is a failure value then it the contained error is passed to handleErrors. |
980 | /// If handleErrors is able to handle the error then the RecoveryPath functor |
981 | /// is called to supply the final result. If handleErrors is not able to |
982 | /// handle all errors then the unhandled errors are returned. |
983 | /// |
984 | /// This utility enables the follow pattern: |
985 | /// |
986 | /// @code{.cpp} |
987 | /// enum FooStrategy { Aggressive, Conservative }; |
988 | /// Expected<Foo> foo(FooStrategy S); |
989 | /// |
990 | /// auto ResultOrErr = |
991 | /// handleExpected( |
992 | /// foo(Aggressive), |
993 | /// []() { return foo(Conservative); }, |
994 | /// [](AggressiveStrategyError&) { |
995 | /// // Implicitly conusme this - we'll recover by using a conservative |
996 | /// // strategy. |
997 | /// }); |
998 | /// |
999 | /// @endcode |
1000 | template <typename T, typename RecoveryFtor, typename... HandlerTs> |
1001 | Expected<T> handleExpected(Expected<T> ValOrErr, RecoveryFtor &&RecoveryPath, |
1002 | HandlerTs &&... Handlers) { |
1003 | if (ValOrErr) |
1004 | return ValOrErr; |
1005 | |
1006 | if (auto Err = handleErrors(ValOrErr.takeError(), |
1007 | std::forward<HandlerTs>(Handlers)...)) |
1008 | return std::move(Err); |
1009 | |
1010 | return RecoveryPath(); |
1011 | } |
1012 | |
1013 | /// Log all errors (if any) in E to OS. If there are any errors, ErrorBanner |
1014 | /// will be printed before the first one is logged. A newline will be printed |
1015 | /// after each error. |
1016 | /// |
1017 | /// This function is compatible with the helpers from Support/WithColor.h. You |
1018 | /// can pass any of them as the OS. Please consider using them instead of |
1019 | /// including 'error: ' in the ErrorBanner. |
1020 | /// |
1021 | /// This is useful in the base level of your program to allow clean termination |
1022 | /// (allowing clean deallocation of resources, etc.), while reporting error |
1023 | /// information to the user. |
1024 | void logAllUnhandledErrors(Error E, raw_ostream &OS, Twine ErrorBanner = {}); |
1025 | |
1026 | /// Write all error messages (if any) in E to a string. The newline character |
1027 | /// is used to separate error messages. |
1028 | inline std::string toString(Error E) { |
1029 | SmallVector<std::string, 2> Errors; |
1030 | handleAllErrors(std::move(E), [&Errors](const ErrorInfoBase &EI) { |
1031 | Errors.push_back(EI.message()); |
1032 | }); |
1033 | return join(Errors.begin(), Errors.end(), "\n"); |
1034 | } |
1035 | |
1036 | /// Consume a Error without doing anything. This method should be used |
1037 | /// only where an error can be considered a reasonable and expected return |
1038 | /// value. |
1039 | /// |
1040 | /// Uses of this method are potentially indicative of design problems: If it's |
1041 | /// legitimate to do nothing while processing an "error", the error-producer |
1042 | /// might be more clearly refactored to return an Optional<T>. |
1043 | inline void consumeError(Error Err) { |
1044 | handleAllErrors(std::move(Err), [](const ErrorInfoBase &) {}); |
1045 | } |
1046 | |
1047 | /// Convert an Expected to an Optional without doing anything. This method |
1048 | /// should be used only where an error can be considered a reasonable and |
1049 | /// expected return value. |
1050 | /// |
1051 | /// Uses of this method are potentially indicative of problems: perhaps the |
1052 | /// error should be propagated further, or the error-producer should just |
1053 | /// return an Optional in the first place. |
1054 | template <typename T> Optional<T> expectedToOptional(Expected<T> &&E) { |
1055 | if (E) |
1056 | return std::move(*E); |
1057 | consumeError(E.takeError()); |
1058 | return None; |
1059 | } |
1060 | |
1061 | /// Helper for converting an Error to a bool. |
1062 | /// |
1063 | /// This method returns true if Err is in an error state, or false if it is |
1064 | /// in a success state. Puts Err in a checked state in both cases (unlike |
1065 | /// Error::operator bool(), which only does this for success states). |
1066 | inline bool errorToBool(Error Err) { |
1067 | bool IsError = static_cast<bool>(Err); |
1068 | if (IsError) |
1069 | consumeError(std::move(Err)); |
1070 | return IsError; |
1071 | } |
1072 | |
1073 | /// Helper for Errors used as out-parameters. |
1074 | /// |
1075 | /// This helper is for use with the Error-as-out-parameter idiom, where an error |
1076 | /// is passed to a function or method by reference, rather than being returned. |
1077 | /// In such cases it is helpful to set the checked bit on entry to the function |
1078 | /// so that the error can be written to (unchecked Errors abort on assignment) |
1079 | /// and clear the checked bit on exit so that clients cannot accidentally forget |
1080 | /// to check the result. This helper performs these actions automatically using |
1081 | /// RAII: |
1082 | /// |
1083 | /// @code{.cpp} |
1084 | /// Result foo(Error &Err) { |
1085 | /// ErrorAsOutParameter ErrAsOutParam(&Err); // 'Checked' flag set |
1086 | /// // <body of foo> |
1087 | /// // <- 'Checked' flag auto-cleared when ErrAsOutParam is destructed. |
1088 | /// } |
1089 | /// @endcode |
1090 | /// |
1091 | /// ErrorAsOutParameter takes an Error* rather than Error& so that it can be |
1092 | /// used with optional Errors (Error pointers that are allowed to be null). If |
1093 | /// ErrorAsOutParameter took an Error reference, an instance would have to be |
1094 | /// created inside every condition that verified that Error was non-null. By |
1095 | /// taking an Error pointer we can just create one instance at the top of the |
1096 | /// function. |
1097 | class ErrorAsOutParameter { |
1098 | public: |
1099 | ErrorAsOutParameter(Error *Err) : Err(Err) { |
1100 | // Raise the checked bit if Err is success. |
1101 | if (Err) |
1102 | (void)!!*Err; |
1103 | } |
1104 | |
1105 | ~ErrorAsOutParameter() { |
1106 | // Clear the checked bit. |
1107 | if (Err && !*Err) |
1108 | *Err = Error::success(); |
1109 | } |
1110 | |
1111 | private: |
1112 | Error *Err; |
1113 | }; |
1114 | |
1115 | /// Helper for Expected<T>s used as out-parameters. |
1116 | /// |
1117 | /// See ErrorAsOutParameter. |
1118 | template <typename T> |
1119 | class ExpectedAsOutParameter { |
1120 | public: |
1121 | ExpectedAsOutParameter(Expected<T> *ValOrErr) |
1122 | : ValOrErr(ValOrErr) { |
1123 | if (ValOrErr) |
1124 | (void)!!*ValOrErr; |
1125 | } |
1126 | |
1127 | ~ExpectedAsOutParameter() { |
1128 | if (ValOrErr) |
1129 | ValOrErr->setUnchecked(); |
1130 | } |
1131 | |
1132 | private: |
1133 | Expected<T> *ValOrErr; |
1134 | }; |
1135 | |
1136 | /// This class wraps a std::error_code in a Error. |
1137 | /// |
1138 | /// This is useful if you're writing an interface that returns a Error |
1139 | /// (or Expected) and you want to call code that still returns |
1140 | /// std::error_codes. |
1141 | class ECError : public ErrorInfo<ECError> { |
1142 | friend Error errorCodeToError(std::error_code); |
1143 | |
1144 | virtual void anchor() override; |
1145 | |
1146 | public: |
1147 | void setErrorCode(std::error_code EC) { this->EC = EC; } |
1148 | std::error_code convertToErrorCode() const override { return EC; } |
1149 | void log(raw_ostream &OS) const override { OS << EC.message(); } |
1150 | |
1151 | // Used by ErrorInfo::classID. |
1152 | static char ID; |
1153 | |
1154 | protected: |
1155 | ECError() = default; |
1156 | ECError(std::error_code EC) : EC(EC) {} |
1157 | |
1158 | std::error_code EC; |
1159 | }; |
1160 | |
1161 | /// The value returned by this function can be returned from convertToErrorCode |
1162 | /// for Error values where no sensible translation to std::error_code exists. |
1163 | /// It should only be used in this situation, and should never be used where a |
1164 | /// sensible conversion to std::error_code is available, as attempts to convert |
1165 | /// to/from this error will result in a fatal error. (i.e. it is a programmatic |
1166 | /// error to try to convert such a value). |
1167 | std::error_code inconvertibleErrorCode(); |
1168 | |
1169 | /// Helper for converting an std::error_code to a Error. |
1170 | Error errorCodeToError(std::error_code EC); |
1171 | |
1172 | /// Helper for converting an ECError to a std::error_code. |
1173 | /// |
1174 | /// This method requires that Err be Error() or an ECError, otherwise it |
1175 | /// will trigger a call to abort(). |
1176 | std::error_code errorToErrorCode(Error Err); |
1177 | |
1178 | /// Convert an ErrorOr<T> to an Expected<T>. |
1179 | template <typename T> Expected<T> errorOrToExpected(ErrorOr<T> &&EO) { |
1180 | if (auto EC = EO.getError()) |
1181 | return errorCodeToError(EC); |
1182 | return std::move(*EO); |
1183 | } |
1184 | |
1185 | /// Convert an Expected<T> to an ErrorOr<T>. |
1186 | template <typename T> ErrorOr<T> expectedToErrorOr(Expected<T> &&E) { |
1187 | if (auto Err = E.takeError()) |
1188 | return errorToErrorCode(std::move(Err)); |
1189 | return std::move(*E); |
1190 | } |
1191 | |
1192 | /// This class wraps a string in an Error. |
1193 | /// |
1194 | /// StringError is useful in cases where the client is not expected to be able |
1195 | /// to consume the specific error message programmatically (for example, if the |
1196 | /// error message is to be presented to the user). |
1197 | /// |
1198 | /// StringError can also be used when additional information is to be printed |
1199 | /// along with a error_code message. Depending on the constructor called, this |
1200 | /// class can either display: |
1201 | /// 1. the error_code message (ECError behavior) |
1202 | /// 2. a string |
1203 | /// 3. the error_code message and a string |
1204 | /// |
1205 | /// These behaviors are useful when subtyping is required; for example, when a |
1206 | /// specific library needs an explicit error type. In the example below, |
1207 | /// PDBError is derived from StringError: |
1208 | /// |
1209 | /// @code{.cpp} |
1210 | /// Expected<int> foo() { |
1211 | /// return llvm::make_error<PDBError>(pdb_error_code::dia_failed_loading, |
1212 | /// "Additional information"); |
1213 | /// } |
1214 | /// @endcode |
1215 | /// |
1216 | class StringError : public ErrorInfo<StringError> { |
1217 | public: |
1218 | static char ID; |
1219 | |
1220 | // Prints EC + S and converts to EC |
1221 | StringError(std::error_code EC, const Twine &S = Twine()); |
1222 | |
1223 | // Prints S and converts to EC |
1224 | StringError(const Twine &S, std::error_code EC); |
1225 | |
1226 | void log(raw_ostream &OS) const override; |
1227 | std::error_code convertToErrorCode() const override; |
1228 | |
1229 | const std::string &getMessage() const { return Msg; } |
1230 | |
1231 | private: |
1232 | std::string Msg; |
1233 | std::error_code EC; |
1234 | const bool PrintMsgOnly = false; |
1235 | }; |
1236 | |
1237 | /// Create formatted StringError object. |
1238 | template <typename... Ts> |
1239 | inline Error createStringError(std::error_code EC, char const *Fmt, |
1240 | const Ts &... Vals) { |
1241 | std::string Buffer; |
1242 | raw_string_ostream Stream(Buffer); |
1243 | Stream << format(Fmt, Vals...); |
1244 | return make_error<StringError>(Stream.str(), EC); |
1245 | } |
1246 | |
1247 | Error createStringError(std::error_code EC, char const *Msg); |
1248 | |
1249 | inline Error createStringError(std::error_code EC, const Twine &S) { |
1250 | return createStringError(EC, S.str().c_str()); |
1251 | } |
1252 | |
1253 | template <typename... Ts> |
1254 | inline Error createStringError(std::errc EC, char const *Fmt, |
1255 | const Ts &... Vals) { |
1256 | return createStringError(std::make_error_code(EC), Fmt, Vals...); |
1257 | } |
1258 | |
1259 | /// This class wraps a filename and another Error. |
1260 | /// |
1261 | /// In some cases, an error needs to live along a 'source' name, in order to |
1262 | /// show more detailed information to the user. |
1263 | class FileError final : public ErrorInfo<FileError> { |
1264 | |
1265 | friend Error createFileError(const Twine &, Error); |
1266 | friend Error createFileError(const Twine &, size_t, Error); |
1267 | |
1268 | public: |
1269 | void log(raw_ostream &OS) const override { |
1270 | assert(Err && "Trying to log after takeError().")(static_cast <bool> (Err && "Trying to log after takeError()." ) ? void (0) : __assert_fail ("Err && \"Trying to log after takeError().\"" , "llvm/include/llvm/Support/Error.h", 1270, __extension__ __PRETTY_FUNCTION__ )); |
1271 | OS << "'" << FileName << "': "; |
1272 | if (Line.hasValue()) |
1273 | OS << "line " << Line.getValue() << ": "; |
1274 | Err->log(OS); |
1275 | } |
1276 | |
1277 | std::string messageWithoutFileInfo() const { |
1278 | std::string Msg; |
1279 | raw_string_ostream OS(Msg); |
1280 | Err->log(OS); |
1281 | return OS.str(); |
1282 | } |
1283 | |
1284 | StringRef getFileName() { return FileName; } |
1285 | |
1286 | Error takeError() { return Error(std::move(Err)); } |
1287 | |
1288 | std::error_code convertToErrorCode() const override; |
1289 | |
1290 | // Used by ErrorInfo::classID. |
1291 | static char ID; |
1292 | |
1293 | private: |
1294 | FileError(const Twine &F, Optional<size_t> LineNum, |
1295 | std::unique_ptr<ErrorInfoBase> E) { |
1296 | assert(E && "Cannot create FileError from Error success value.")(static_cast <bool> (E && "Cannot create FileError from Error success value." ) ? void (0) : __assert_fail ("E && \"Cannot create FileError from Error success value.\"" , "llvm/include/llvm/Support/Error.h", 1296, __extension__ __PRETTY_FUNCTION__ )); |
1297 | FileName = F.str(); |
1298 | Err = std::move(E); |
1299 | Line = std::move(LineNum); |
1300 | } |
1301 | |
1302 | static Error build(const Twine &F, Optional<size_t> Line, Error E) { |
1303 | std::unique_ptr<ErrorInfoBase> Payload; |
1304 | handleAllErrors(std::move(E), |
1305 | [&](std::unique_ptr<ErrorInfoBase> EIB) -> Error { |
1306 | Payload = std::move(EIB); |
1307 | return Error::success(); |
1308 | }); |
1309 | return Error( |
1310 | std::unique_ptr<FileError>(new FileError(F, Line, std::move(Payload)))); |
1311 | } |
1312 | |
1313 | std::string FileName; |
1314 | Optional<size_t> Line; |
1315 | std::unique_ptr<ErrorInfoBase> Err; |
1316 | }; |
1317 | |
1318 | /// Concatenate a source file path and/or name with an Error. The resulting |
1319 | /// Error is unchecked. |
1320 | inline Error createFileError(const Twine &F, Error E) { |
1321 | return FileError::build(F, Optional<size_t>(), std::move(E)); |
1322 | } |
1323 | |
1324 | /// Concatenate a source file path and/or name with line number and an Error. |
1325 | /// The resulting Error is unchecked. |
1326 | inline Error createFileError(const Twine &F, size_t Line, Error E) { |
1327 | return FileError::build(F, Optional<size_t>(Line), std::move(E)); |
1328 | } |
1329 | |
1330 | /// Concatenate a source file path and/or name with a std::error_code |
1331 | /// to form an Error object. |
1332 | inline Error createFileError(const Twine &F, std::error_code EC) { |
1333 | return createFileError(F, errorCodeToError(EC)); |
1334 | } |
1335 | |
1336 | /// Concatenate a source file path and/or name with line number and |
1337 | /// std::error_code to form an Error object. |
1338 | inline Error createFileError(const Twine &F, size_t Line, std::error_code EC) { |
1339 | return createFileError(F, Line, errorCodeToError(EC)); |
1340 | } |
1341 | |
1342 | Error createFileError(const Twine &F, ErrorSuccess) = delete; |
1343 | |
1344 | /// Helper for check-and-exit error handling. |
1345 | /// |
1346 | /// For tool use only. NOT FOR USE IN LIBRARY CODE. |
1347 | /// |
1348 | class ExitOnError { |
1349 | public: |
1350 | /// Create an error on exit helper. |
1351 | ExitOnError(std::string Banner = "", int DefaultErrorExitCode = 1) |
1352 | : Banner(std::move(Banner)), |
1353 | GetExitCode([=](const Error &) { return DefaultErrorExitCode; }) {} |
1354 | |
1355 | /// Set the banner string for any errors caught by operator(). |
1356 | void setBanner(std::string Banner) { this->Banner = std::move(Banner); } |
1357 | |
1358 | /// Set the exit-code mapper function. |
1359 | void setExitCodeMapper(std::function<int(const Error &)> GetExitCode) { |
1360 | this->GetExitCode = std::move(GetExitCode); |
1361 | } |
1362 | |
1363 | /// Check Err. If it's in a failure state log the error(s) and exit. |
1364 | void operator()(Error Err) const { checkError(std::move(Err)); } |
1365 | |
1366 | /// Check E. If it's in a success state then return the contained value. If |
1367 | /// it's in a failure state log the error(s) and exit. |
1368 | template <typename T> T operator()(Expected<T> &&E) const { |
1369 | checkError(E.takeError()); |
1370 | return std::move(*E); |
1371 | } |
1372 | |
1373 | /// Check E. If it's in a success state then return the contained reference. If |
1374 | /// it's in a failure state log the error(s) and exit. |
1375 | template <typename T> T& operator()(Expected<T&> &&E) const { |
1376 | checkError(E.takeError()); |
1377 | return *E; |
1378 | } |
1379 | |
1380 | private: |
1381 | void checkError(Error Err) const { |
1382 | if (Err) { |
1383 | int ExitCode = GetExitCode(Err); |
1384 | logAllUnhandledErrors(std::move(Err), errs(), Banner); |
1385 | exit(ExitCode); |
1386 | } |
1387 | } |
1388 | |
1389 | std::string Banner; |
1390 | std::function<int(const Error &)> GetExitCode; |
1391 | }; |
1392 | |
1393 | /// Conversion from Error to LLVMErrorRef for C error bindings. |
1394 | inline LLVMErrorRef wrap(Error Err) { |
1395 | return reinterpret_cast<LLVMErrorRef>(Err.takePayload().release()); |
1396 | } |
1397 | |
1398 | /// Conversion from LLVMErrorRef to Error for C error bindings. |
1399 | inline Error unwrap(LLVMErrorRef ErrRef) { |
1400 | return Error(std::unique_ptr<ErrorInfoBase>( |
1401 | reinterpret_cast<ErrorInfoBase *>(ErrRef))); |
1402 | } |
1403 | |
1404 | } // end namespace llvm |
1405 | |
1406 | #endif // LLVM_SUPPORT_ERROR_H |