1//===- BitcodeAnalyzer.cpp - Internal BitcodeAnalyzer 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/BitcodeAnalyzer.h"
10#include "llvm/Bitcode/BitcodeReader.h"
11#include "llvm/Bitcode/LLVMBitCodes.h"
12#include "llvm/Bitstream/BitCodes.h"
13#include "llvm/Bitstream/BitstreamReader.h"
14#include "llvm/Support/Format.h"
15#include "llvm/Support/SHA1.h"
16#include <optional>
17
18using namespace llvm;
19
20static Error reportError(StringRef Message) {
21 return createStringError(EC: std::errc::illegal_byte_sequence, Fmt: Message.data());
22}
23
24/// Return a symbolic block name if known, otherwise return null.
25static std::optional<const char *>
26GetBlockName(unsigned BlockID, const BitstreamBlockInfo &BlockInfo,
27 CurStreamTypeType CurStreamType) {
28 // Standard blocks for all bitcode files.
29 if (BlockID < bitc::FIRST_APPLICATION_BLOCKID) {
30 if (BlockID == bitc::BLOCKINFO_BLOCK_ID)
31 return "BLOCKINFO_BLOCK";
32 return std::nullopt;
33 }
34
35 // Check to see if we have a blockinfo record for this block, with a name.
36 if (const BitstreamBlockInfo::BlockInfo *Info =
37 BlockInfo.getBlockInfo(BlockID)) {
38 if (!Info->Name.empty())
39 return Info->Name.c_str();
40 }
41
42 if (CurStreamType != LLVMIRBitstream)
43 return std::nullopt;
44
45 switch (BlockID) {
46 default:
47 return std::nullopt;
48 case bitc::OPERAND_BUNDLE_TAGS_BLOCK_ID:
49 return "OPERAND_BUNDLE_TAGS_BLOCK";
50 case bitc::MODULE_BLOCK_ID:
51 return "MODULE_BLOCK";
52 case bitc::PARAMATTR_BLOCK_ID:
53 return "PARAMATTR_BLOCK";
54 case bitc::PARAMATTR_GROUP_BLOCK_ID:
55 return "PARAMATTR_GROUP_BLOCK_ID";
56 case bitc::TYPE_BLOCK_ID_NEW:
57 return "TYPE_BLOCK_ID";
58 case bitc::CONSTANTS_BLOCK_ID:
59 return "CONSTANTS_BLOCK";
60 case bitc::FUNCTION_BLOCK_ID:
61 return "FUNCTION_BLOCK";
62 case bitc::IDENTIFICATION_BLOCK_ID:
63 return "IDENTIFICATION_BLOCK_ID";
64 case bitc::VALUE_SYMTAB_BLOCK_ID:
65 return "VALUE_SYMTAB";
66 case bitc::METADATA_BLOCK_ID:
67 return "METADATA_BLOCK";
68 case bitc::METADATA_KIND_BLOCK_ID:
69 return "METADATA_KIND_BLOCK";
70 case bitc::METADATA_ATTACHMENT_ID:
71 return "METADATA_ATTACHMENT_BLOCK";
72 case bitc::USELIST_BLOCK_ID:
73 return "USELIST_BLOCK_ID";
74 case bitc::GLOBALVAL_SUMMARY_BLOCK_ID:
75 return "GLOBALVAL_SUMMARY_BLOCK";
76 case bitc::FULL_LTO_GLOBALVAL_SUMMARY_BLOCK_ID:
77 return "FULL_LTO_GLOBALVAL_SUMMARY_BLOCK";
78 case bitc::MODULE_STRTAB_BLOCK_ID:
79 return "MODULE_STRTAB_BLOCK";
80 case bitc::STRTAB_BLOCK_ID:
81 return "STRTAB_BLOCK";
82 case bitc::SYMTAB_BLOCK_ID:
83 return "SYMTAB_BLOCK";
84 }
85}
86
87/// Return a symbolic code name if known, otherwise return null.
88static std::optional<const char *>
89GetCodeName(unsigned CodeID, unsigned BlockID,
90 const BitstreamBlockInfo &BlockInfo,
91 CurStreamTypeType CurStreamType) {
92 // Standard blocks for all bitcode files.
93 if (BlockID < bitc::FIRST_APPLICATION_BLOCKID) {
94 if (BlockID == bitc::BLOCKINFO_BLOCK_ID) {
95 switch (CodeID) {
96 default:
97 return std::nullopt;
98 case bitc::BLOCKINFO_CODE_SETBID:
99 return "SETBID";
100 case bitc::BLOCKINFO_CODE_BLOCKNAME:
101 return "BLOCKNAME";
102 case bitc::BLOCKINFO_CODE_SETRECORDNAME:
103 return "SETRECORDNAME";
104 }
105 }
106 return std::nullopt;
107 }
108
109 // Check to see if we have a blockinfo record for this record, with a name.
110 if (const BitstreamBlockInfo::BlockInfo *Info =
111 BlockInfo.getBlockInfo(BlockID)) {
112 for (const std::pair<unsigned, std::string> &RN : Info->RecordNames)
113 if (RN.first == CodeID)
114 return RN.second.c_str();
115 }
116
117 if (CurStreamType != LLVMIRBitstream)
118 return std::nullopt;
119
120#define STRINGIFY_CODE(PREFIX, CODE) \
121 case bitc::PREFIX##_##CODE: \
122 return #CODE;
123 switch (BlockID) {
124 default:
125 return std::nullopt;
126 case bitc::MODULE_BLOCK_ID:
127 switch (CodeID) {
128 default:
129 return std::nullopt;
130 STRINGIFY_CODE(MODULE_CODE, VERSION)
131 STRINGIFY_CODE(MODULE_CODE, TRIPLE)
132 STRINGIFY_CODE(MODULE_CODE, DATALAYOUT)
133 STRINGIFY_CODE(MODULE_CODE, ASM)
134 STRINGIFY_CODE(MODULE_CODE, SECTIONNAME)
135 STRINGIFY_CODE(MODULE_CODE, DEPLIB) // Deprecated, present in old bitcode
136 STRINGIFY_CODE(MODULE_CODE, GLOBALVAR)
137 STRINGIFY_CODE(MODULE_CODE, FUNCTION)
138 STRINGIFY_CODE(MODULE_CODE, ALIAS)
139 STRINGIFY_CODE(MODULE_CODE, GCNAME)
140 STRINGIFY_CODE(MODULE_CODE, COMDAT)
141 STRINGIFY_CODE(MODULE_CODE, VSTOFFSET)
142 STRINGIFY_CODE(MODULE_CODE, METADATA_VALUES_UNUSED)
143 STRINGIFY_CODE(MODULE_CODE, SOURCE_FILENAME)
144 STRINGIFY_CODE(MODULE_CODE, HASH)
145 STRINGIFY_CODE(MODULE_CODE, GUIDLIST)
146 }
147 case bitc::IDENTIFICATION_BLOCK_ID:
148 switch (CodeID) {
149 default:
150 return std::nullopt;
151 STRINGIFY_CODE(IDENTIFICATION_CODE, STRING)
152 STRINGIFY_CODE(IDENTIFICATION_CODE, EPOCH)
153 }
154 case bitc::PARAMATTR_BLOCK_ID:
155 switch (CodeID) {
156 default:
157 return std::nullopt;
158 // FIXME: Should these be different?
159 case bitc::PARAMATTR_CODE_ENTRY_OLD:
160 return "ENTRY";
161 case bitc::PARAMATTR_CODE_ENTRY:
162 return "ENTRY";
163 }
164 case bitc::PARAMATTR_GROUP_BLOCK_ID:
165 switch (CodeID) {
166 default:
167 return std::nullopt;
168 case bitc::PARAMATTR_GRP_CODE_ENTRY:
169 return "ENTRY";
170 }
171 case bitc::TYPE_BLOCK_ID_NEW:
172 switch (CodeID) {
173 default:
174 return std::nullopt;
175 STRINGIFY_CODE(TYPE_CODE, NUMENTRY)
176 STRINGIFY_CODE(TYPE_CODE, VOID)
177 STRINGIFY_CODE(TYPE_CODE, FLOAT)
178 STRINGIFY_CODE(TYPE_CODE, DOUBLE)
179 STRINGIFY_CODE(TYPE_CODE, LABEL)
180 STRINGIFY_CODE(TYPE_CODE, OPAQUE)
181 STRINGIFY_CODE(TYPE_CODE, INTEGER)
182 STRINGIFY_CODE(TYPE_CODE, POINTER)
183 STRINGIFY_CODE(TYPE_CODE, HALF)
184 STRINGIFY_CODE(TYPE_CODE, ARRAY)
185 STRINGIFY_CODE(TYPE_CODE, VECTOR)
186 STRINGIFY_CODE(TYPE_CODE, X86_FP80)
187 STRINGIFY_CODE(TYPE_CODE, FP128)
188 STRINGIFY_CODE(TYPE_CODE, PPC_FP128)
189 STRINGIFY_CODE(TYPE_CODE, METADATA)
190 STRINGIFY_CODE(TYPE_CODE, X86_MMX)
191 STRINGIFY_CODE(TYPE_CODE, STRUCT_ANON)
192 STRINGIFY_CODE(TYPE_CODE, STRUCT_NAME)
193 STRINGIFY_CODE(TYPE_CODE, STRUCT_NAMED)
194 STRINGIFY_CODE(TYPE_CODE, FUNCTION)
195 STRINGIFY_CODE(TYPE_CODE, TOKEN)
196 STRINGIFY_CODE(TYPE_CODE, BFLOAT)
197 }
198
199 case bitc::CONSTANTS_BLOCK_ID:
200 switch (CodeID) {
201 default:
202 return std::nullopt;
203 STRINGIFY_CODE(CST_CODE, SETTYPE)
204 STRINGIFY_CODE(CST_CODE, NULL)
205 STRINGIFY_CODE(CST_CODE, UNDEF)
206 STRINGIFY_CODE(CST_CODE, INTEGER)
207 STRINGIFY_CODE(CST_CODE, WIDE_INTEGER)
208 STRINGIFY_CODE(CST_CODE, FLOAT)
209 STRINGIFY_CODE(CST_CODE, AGGREGATE)
210 STRINGIFY_CODE(CST_CODE, STRING)
211 STRINGIFY_CODE(CST_CODE, CSTRING)
212 STRINGIFY_CODE(CST_CODE, CE_BINOP)
213 STRINGIFY_CODE(CST_CODE, CE_CAST)
214 STRINGIFY_CODE(CST_CODE, CE_GEP)
215 STRINGIFY_CODE(CST_CODE, CE_INBOUNDS_GEP)
216 STRINGIFY_CODE(CST_CODE, CE_SELECT)
217 STRINGIFY_CODE(CST_CODE, CE_EXTRACTELT)
218 STRINGIFY_CODE(CST_CODE, CE_INSERTELT)
219 STRINGIFY_CODE(CST_CODE, CE_SHUFFLEVEC)
220 STRINGIFY_CODE(CST_CODE, CE_CMP)
221 STRINGIFY_CODE(CST_CODE, INLINEASM)
222 STRINGIFY_CODE(CST_CODE, CE_SHUFVEC_EX)
223 STRINGIFY_CODE(CST_CODE, CE_UNOP)
224 STRINGIFY_CODE(CST_CODE, DSO_LOCAL_EQUIVALENT)
225 STRINGIFY_CODE(CST_CODE, NO_CFI_VALUE)
226 STRINGIFY_CODE(CST_CODE, PTRAUTH)
227 case bitc::CST_CODE_BLOCKADDRESS:
228 return "CST_CODE_BLOCKADDRESS";
229 STRINGIFY_CODE(CST_CODE, DATA)
230 }
231 case bitc::FUNCTION_BLOCK_ID:
232 switch (CodeID) {
233 default:
234 return std::nullopt;
235 STRINGIFY_CODE(FUNC_CODE, DECLAREBLOCKS)
236 STRINGIFY_CODE(FUNC_CODE, INST_BINOP)
237 STRINGIFY_CODE(FUNC_CODE, INST_CAST)
238 STRINGIFY_CODE(FUNC_CODE, INST_GEP_OLD)
239 STRINGIFY_CODE(FUNC_CODE, INST_INBOUNDS_GEP_OLD)
240 STRINGIFY_CODE(FUNC_CODE, INST_SELECT)
241 STRINGIFY_CODE(FUNC_CODE, INST_EXTRACTELT)
242 STRINGIFY_CODE(FUNC_CODE, INST_INSERTELT)
243 STRINGIFY_CODE(FUNC_CODE, INST_SHUFFLEVEC)
244 STRINGIFY_CODE(FUNC_CODE, INST_CMP)
245 STRINGIFY_CODE(FUNC_CODE, INST_RET)
246 STRINGIFY_CODE(FUNC_CODE, INST_BR)
247 STRINGIFY_CODE(FUNC_CODE, INST_SWITCH)
248 STRINGIFY_CODE(FUNC_CODE, INST_INVOKE)
249 STRINGIFY_CODE(FUNC_CODE, INST_UNOP)
250 STRINGIFY_CODE(FUNC_CODE, INST_UNREACHABLE)
251 STRINGIFY_CODE(FUNC_CODE, INST_CLEANUPRET)
252 STRINGIFY_CODE(FUNC_CODE, INST_CATCHRET)
253 STRINGIFY_CODE(FUNC_CODE, INST_CATCHPAD)
254 STRINGIFY_CODE(FUNC_CODE, INST_PHI)
255 STRINGIFY_CODE(FUNC_CODE, INST_ALLOCA)
256 STRINGIFY_CODE(FUNC_CODE, INST_LOAD)
257 STRINGIFY_CODE(FUNC_CODE, INST_VAARG)
258 STRINGIFY_CODE(FUNC_CODE, INST_STORE)
259 STRINGIFY_CODE(FUNC_CODE, INST_EXTRACTVAL)
260 STRINGIFY_CODE(FUNC_CODE, INST_INSERTVAL)
261 STRINGIFY_CODE(FUNC_CODE, INST_CMP2)
262 STRINGIFY_CODE(FUNC_CODE, INST_VSELECT)
263 STRINGIFY_CODE(FUNC_CODE, DEBUG_LOC_AGAIN)
264 STRINGIFY_CODE(FUNC_CODE, INST_CALL)
265 STRINGIFY_CODE(FUNC_CODE, DEBUG_LOC)
266 STRINGIFY_CODE(FUNC_CODE, INST_GEP)
267 STRINGIFY_CODE(FUNC_CODE, OPERAND_BUNDLE)
268 STRINGIFY_CODE(FUNC_CODE, INST_FENCE)
269 STRINGIFY_CODE(FUNC_CODE, INST_ATOMICRMW)
270 STRINGIFY_CODE(FUNC_CODE, INST_LOADATOMIC)
271 STRINGIFY_CODE(FUNC_CODE, INST_STOREATOMIC)
272 STRINGIFY_CODE(FUNC_CODE, INST_CMPXCHG)
273 STRINGIFY_CODE(FUNC_CODE, INST_CALLBR)
274 STRINGIFY_CODE(FUNC_CODE, BLOCKADDR_USERS)
275 STRINGIFY_CODE(FUNC_CODE, DEBUG_RECORD_DECLARE)
276 STRINGIFY_CODE(FUNC_CODE, DEBUG_RECORD_DECLARE_VALUE)
277 STRINGIFY_CODE(FUNC_CODE, DEBUG_RECORD_VALUE)
278 STRINGIFY_CODE(FUNC_CODE, DEBUG_RECORD_ASSIGN)
279 STRINGIFY_CODE(FUNC_CODE, DEBUG_RECORD_VALUE_SIMPLE)
280 STRINGIFY_CODE(FUNC_CODE, DEBUG_RECORD_LABEL)
281 }
282 case bitc::VALUE_SYMTAB_BLOCK_ID:
283 switch (CodeID) {
284 default:
285 return std::nullopt;
286 STRINGIFY_CODE(VST_CODE, ENTRY)
287 STRINGIFY_CODE(VST_CODE, BBENTRY)
288 STRINGIFY_CODE(VST_CODE, FNENTRY)
289 STRINGIFY_CODE(VST_CODE, COMBINED_ENTRY)
290 }
291 case bitc::MODULE_STRTAB_BLOCK_ID:
292 switch (CodeID) {
293 default:
294 return std::nullopt;
295 STRINGIFY_CODE(MST_CODE, ENTRY)
296 STRINGIFY_CODE(MST_CODE, HASH)
297 }
298 case bitc::GLOBALVAL_SUMMARY_BLOCK_ID:
299 case bitc::FULL_LTO_GLOBALVAL_SUMMARY_BLOCK_ID:
300 switch (CodeID) {
301 default:
302 return std::nullopt;
303 STRINGIFY_CODE(FS, PERMODULE)
304 STRINGIFY_CODE(FS, PERMODULE_PROFILE)
305 STRINGIFY_CODE(FS, PERMODULE_RELBF)
306 STRINGIFY_CODE(FS, PERMODULE_GLOBALVAR_INIT_REFS)
307 STRINGIFY_CODE(FS, PERMODULE_VTABLE_GLOBALVAR_INIT_REFS)
308 STRINGIFY_CODE(FS, COMBINED)
309 STRINGIFY_CODE(FS, COMBINED_PROFILE)
310 STRINGIFY_CODE(FS, COMBINED_GLOBALVAR_INIT_REFS)
311 STRINGIFY_CODE(FS, ALIAS)
312 STRINGIFY_CODE(FS, COMBINED_ALIAS)
313 STRINGIFY_CODE(FS, COMBINED_ORIGINAL_NAME)
314 STRINGIFY_CODE(FS, VERSION)
315 STRINGIFY_CODE(FS, FLAGS)
316 STRINGIFY_CODE(FS, TYPE_TESTS)
317 STRINGIFY_CODE(FS, TYPE_TEST_ASSUME_VCALLS)
318 STRINGIFY_CODE(FS, TYPE_CHECKED_LOAD_VCALLS)
319 STRINGIFY_CODE(FS, TYPE_TEST_ASSUME_CONST_VCALL)
320 STRINGIFY_CODE(FS, TYPE_CHECKED_LOAD_CONST_VCALL)
321 STRINGIFY_CODE(FS, VALUE_GUID)
322 STRINGIFY_CODE(FS, CFI_FUNCTION_DEFS)
323 STRINGIFY_CODE(FS, CFI_FUNCTION_DECLS)
324 STRINGIFY_CODE(FS, TYPE_ID)
325 STRINGIFY_CODE(FS, TYPE_ID_METADATA)
326 STRINGIFY_CODE(FS, BLOCK_COUNT)
327 STRINGIFY_CODE(FS, PARAM_ACCESS)
328 STRINGIFY_CODE(FS, PERMODULE_CALLSITE_INFO)
329 STRINGIFY_CODE(FS, PERMODULE_ALLOC_INFO)
330 STRINGIFY_CODE(FS, COMBINED_CALLSITE_INFO)
331 STRINGIFY_CODE(FS, COMBINED_ALLOC_INFO)
332 STRINGIFY_CODE(FS, STACK_IDS)
333 STRINGIFY_CODE(FS, ALLOC_CONTEXT_IDS)
334 STRINGIFY_CODE(FS, CONTEXT_RADIX_TREE_ARRAY)
335 STRINGIFY_CODE(FS, COMBINED_ALLOC_INFO_NO_CONTEXT)
336 }
337 case bitc::METADATA_ATTACHMENT_ID:
338 switch (CodeID) {
339 default:
340 return std::nullopt;
341 STRINGIFY_CODE(METADATA, ATTACHMENT)
342 }
343 case bitc::METADATA_BLOCK_ID:
344 switch (CodeID) {
345 default:
346 return std::nullopt;
347 STRINGIFY_CODE(METADATA, STRING_OLD)
348 STRINGIFY_CODE(METADATA, VALUE)
349 STRINGIFY_CODE(METADATA, NODE)
350 STRINGIFY_CODE(METADATA, NAME)
351 STRINGIFY_CODE(METADATA, DISTINCT_NODE)
352 STRINGIFY_CODE(METADATA, KIND) // Older bitcode has it in a MODULE_BLOCK
353 STRINGIFY_CODE(METADATA, LOCATION)
354 STRINGIFY_CODE(METADATA, OLD_NODE)
355 STRINGIFY_CODE(METADATA, OLD_FN_NODE)
356 STRINGIFY_CODE(METADATA, NAMED_NODE)
357 STRINGIFY_CODE(METADATA, GENERIC_DEBUG)
358 STRINGIFY_CODE(METADATA, SUBRANGE)
359 STRINGIFY_CODE(METADATA, ENUMERATOR)
360 STRINGIFY_CODE(METADATA, BASIC_TYPE)
361 STRINGIFY_CODE(METADATA, FILE)
362 STRINGIFY_CODE(METADATA, DERIVED_TYPE)
363 STRINGIFY_CODE(METADATA, COMPOSITE_TYPE)
364 STRINGIFY_CODE(METADATA, SUBROUTINE_TYPE)
365 STRINGIFY_CODE(METADATA, COMPILE_UNIT)
366 STRINGIFY_CODE(METADATA, SUBPROGRAM)
367 STRINGIFY_CODE(METADATA, LEXICAL_BLOCK)
368 STRINGIFY_CODE(METADATA, LEXICAL_BLOCK_FILE)
369 STRINGIFY_CODE(METADATA, NAMESPACE)
370 STRINGIFY_CODE(METADATA, TEMPLATE_TYPE)
371 STRINGIFY_CODE(METADATA, TEMPLATE_VALUE)
372 STRINGIFY_CODE(METADATA, GLOBAL_VAR)
373 STRINGIFY_CODE(METADATA, LOCAL_VAR)
374 STRINGIFY_CODE(METADATA, EXPRESSION)
375 STRINGIFY_CODE(METADATA, OBJC_PROPERTY)
376 STRINGIFY_CODE(METADATA, IMPORTED_ENTITY)
377 STRINGIFY_CODE(METADATA, MODULE)
378 STRINGIFY_CODE(METADATA, MACRO)
379 STRINGIFY_CODE(METADATA, MACRO_FILE)
380 STRINGIFY_CODE(METADATA, STRINGS)
381 STRINGIFY_CODE(METADATA, GLOBAL_DECL_ATTACHMENT)
382 STRINGIFY_CODE(METADATA, GLOBAL_VAR_EXPR)
383 STRINGIFY_CODE(METADATA, INDEX_OFFSET)
384 STRINGIFY_CODE(METADATA, INDEX)
385 STRINGIFY_CODE(METADATA, ARG_LIST)
386 }
387 case bitc::METADATA_KIND_BLOCK_ID:
388 switch (CodeID) {
389 default:
390 return std::nullopt;
391 STRINGIFY_CODE(METADATA, KIND)
392 }
393 case bitc::USELIST_BLOCK_ID:
394 switch (CodeID) {
395 default:
396 return std::nullopt;
397 case bitc::USELIST_CODE_DEFAULT:
398 return "USELIST_CODE_DEFAULT";
399 case bitc::USELIST_CODE_BB:
400 return "USELIST_CODE_BB";
401 }
402
403 case bitc::OPERAND_BUNDLE_TAGS_BLOCK_ID:
404 switch (CodeID) {
405 default:
406 return std::nullopt;
407 case bitc::OPERAND_BUNDLE_TAG:
408 return "OPERAND_BUNDLE_TAG";
409 }
410 case bitc::STRTAB_BLOCK_ID:
411 switch (CodeID) {
412 default:
413 return std::nullopt;
414 case bitc::STRTAB_BLOB:
415 return "BLOB";
416 }
417 case bitc::SYMTAB_BLOCK_ID:
418 switch (CodeID) {
419 default:
420 return std::nullopt;
421 case bitc::SYMTAB_BLOB:
422 return "BLOB";
423 }
424 }
425#undef STRINGIFY_CODE
426}
427
428static void printSize(raw_ostream &OS, double Bits) {
429 OS << format(Fmt: "%.2f/%.2fB/%luW", Vals: Bits, Vals: Bits / 8, Vals: (unsigned long)(Bits / 32));
430}
431static void printSize(raw_ostream &OS, uint64_t Bits) {
432 OS << format(Fmt: "%lub/%.2fB/%luW", Vals: (unsigned long)Bits, Vals: (double)Bits / 8,
433 Vals: (unsigned long)(Bits / 32));
434}
435
436static Expected<CurStreamTypeType> ReadSignature(BitstreamCursor &Stream) {
437 auto tryRead = [&Stream](char &Dest, size_t size) -> Error {
438 if (Expected<SimpleBitstreamCursor::word_t> MaybeWord = Stream.Read(NumBits: size))
439 Dest = MaybeWord.get();
440 else
441 return MaybeWord.takeError();
442 return Error::success();
443 };
444
445 char Signature[6];
446 if (Error Err = tryRead(Signature[0], 8))
447 return std::move(Err);
448 if (Error Err = tryRead(Signature[1], 8))
449 return std::move(Err);
450
451 // Autodetect the file contents, if it is one we know.
452 if (Signature[0] == 'C' && Signature[1] == 'P') {
453 if (Error Err = tryRead(Signature[2], 8))
454 return std::move(Err);
455 if (Error Err = tryRead(Signature[3], 8))
456 return std::move(Err);
457 if (Signature[2] == 'C' && Signature[3] == 'H')
458 return ClangSerializedASTBitstream;
459 } else if (Signature[0] == 'D' && Signature[1] == 'I') {
460 if (Error Err = tryRead(Signature[2], 8))
461 return std::move(Err);
462 if (Error Err = tryRead(Signature[3], 8))
463 return std::move(Err);
464 if (Signature[2] == 'A' && Signature[3] == 'G')
465 return ClangSerializedDiagnosticsBitstream;
466 } else if (Signature[0] == 'R' && Signature[1] == 'M') {
467 if (Error Err = tryRead(Signature[2], 8))
468 return std::move(Err);
469 if (Error Err = tryRead(Signature[3], 8))
470 return std::move(Err);
471 if (Signature[2] == 'R' && Signature[3] == 'K')
472 return LLVMBitstreamRemarks;
473 } else {
474 if (Error Err = tryRead(Signature[2], 4))
475 return std::move(Err);
476 if (Error Err = tryRead(Signature[3], 4))
477 return std::move(Err);
478 if (Error Err = tryRead(Signature[4], 4))
479 return std::move(Err);
480 if (Error Err = tryRead(Signature[5], 4))
481 return std::move(Err);
482 if (Signature[0] == 'B' && Signature[1] == 'C' && Signature[2] == 0x0 &&
483 Signature[3] == 0xC && Signature[4] == 0xE && Signature[5] == 0xD)
484 return LLVMIRBitstream;
485 }
486 return UnknownBitstream;
487}
488
489static Expected<CurStreamTypeType> analyzeHeader(std::optional<BCDumpOptions> O,
490 BitstreamCursor &Stream) {
491 ArrayRef<uint8_t> Bytes = Stream.getBitcodeBytes();
492 const unsigned char *BufPtr = (const unsigned char *)Bytes.data();
493 const unsigned char *EndBufPtr = BufPtr + Bytes.size();
494
495 // If we have a wrapper header, parse it and ignore the non-bc file
496 // contents. The magic number is 0x0B17C0DE stored in little endian.
497 if (isBitcodeWrapper(BufPtr, BufEnd: EndBufPtr)) {
498 if (Bytes.size() < BWH_HeaderSize)
499 return reportError(Message: "Invalid bitcode wrapper header");
500
501 if (O) {
502 unsigned Magic = support::endian::read32le(P: &BufPtr[BWH_MagicField]);
503 unsigned Version = support::endian::read32le(P: &BufPtr[BWH_VersionField]);
504 unsigned Offset = support::endian::read32le(P: &BufPtr[BWH_OffsetField]);
505 unsigned Size = support::endian::read32le(P: &BufPtr[BWH_SizeField]);
506 unsigned CPUType = support::endian::read32le(P: &BufPtr[BWH_CPUTypeField]);
507
508 O->OS << "<BITCODE_WRAPPER_HEADER"
509 << " Magic=" << format_hex(N: Magic, Width: 10)
510 << " Version=" << format_hex(N: Version, Width: 10)
511 << " Offset=" << format_hex(N: Offset, Width: 10)
512 << " Size=" << format_hex(N: Size, Width: 10)
513 << " CPUType=" << format_hex(N: CPUType, Width: 10) << "/>\n";
514 }
515
516 if (SkipBitcodeWrapperHeader(BufPtr, BufEnd&: EndBufPtr, VerifyBufferSize: true))
517 return reportError(Message: "Invalid bitcode wrapper header");
518 }
519
520 // Use the cursor modified by skipping the wrapper header.
521 Stream = BitstreamCursor(ArrayRef<uint8_t>(BufPtr, EndBufPtr));
522
523 return ReadSignature(Stream);
524}
525
526static bool canDecodeBlob(unsigned Code, unsigned BlockID) {
527 return BlockID == bitc::METADATA_BLOCK_ID && Code == bitc::METADATA_STRINGS;
528}
529
530Error BitcodeAnalyzer::decodeMetadataStringsBlob(StringRef Indent,
531 ArrayRef<uint64_t> Record,
532 StringRef Blob,
533 raw_ostream &OS) {
534 if (Blob.empty())
535 return reportError(Message: "Cannot decode empty blob.");
536
537 if (Record.size() != 2)
538 return reportError(
539 Message: "Decoding metadata strings blob needs two record entries.");
540
541 unsigned NumStrings = Record[0];
542 unsigned StringsOffset = Record[1];
543 OS << " num-strings = " << NumStrings << " {\n";
544
545 StringRef Lengths = Blob.slice(Start: 0, End: StringsOffset);
546 SimpleBitstreamCursor R(Lengths);
547 StringRef Strings = Blob.drop_front(N: StringsOffset);
548 do {
549 if (R.AtEndOfStream())
550 return reportError(Message: "bad length");
551
552 uint32_t Size;
553 if (Error E = R.ReadVBR(NumBits: 6).moveInto(Value&: Size))
554 return E;
555 if (Strings.size() < Size)
556 return reportError(Message: "truncated chars");
557
558 OS << Indent << " '";
559 OS.write_escaped(Str: Strings.slice(Start: 0, End: Size), /*hex=*/UseHexEscapes: true);
560 OS << "'\n";
561 Strings = Strings.drop_front(N: Size);
562 } while (--NumStrings);
563
564 OS << Indent << " }";
565 return Error::success();
566}
567
568BitcodeAnalyzer::BitcodeAnalyzer(StringRef Buffer,
569 std::optional<StringRef> BlockInfoBuffer)
570 : Stream(Buffer) {
571 if (BlockInfoBuffer)
572 BlockInfoStream.emplace(args&: *BlockInfoBuffer);
573}
574
575Error BitcodeAnalyzer::analyze(std::optional<BCDumpOptions> O,
576 std::optional<StringRef> CheckHash) {
577 if (Error E = analyzeHeader(O, Stream).moveInto(Value&: CurStreamType))
578 return E;
579
580 Stream.setBlockInfo(&BlockInfo);
581
582 // Read block info from BlockInfoStream, if specified.
583 // The block info must be a top-level block.
584 if (BlockInfoStream) {
585 BitstreamCursor BlockInfoCursor(*BlockInfoStream);
586 if (Error E = analyzeHeader(O, Stream&: BlockInfoCursor).takeError())
587 return E;
588
589 while (!BlockInfoCursor.AtEndOfStream()) {
590 Expected<unsigned> MaybeCode = BlockInfoCursor.ReadCode();
591 if (!MaybeCode)
592 return MaybeCode.takeError();
593 if (MaybeCode.get() != bitc::ENTER_SUBBLOCK)
594 return reportError(Message: "Invalid record at top-level in block info file");
595
596 Expected<unsigned> MaybeBlockID = BlockInfoCursor.ReadSubBlockID();
597 if (!MaybeBlockID)
598 return MaybeBlockID.takeError();
599 if (MaybeBlockID.get() == bitc::BLOCKINFO_BLOCK_ID) {
600 std::optional<BitstreamBlockInfo> NewBlockInfo;
601 if (Error E =
602 BlockInfoCursor.ReadBlockInfoBlock(/*ReadBlockInfoNames=*/true)
603 .moveInto(Value&: NewBlockInfo))
604 return E;
605 if (!NewBlockInfo)
606 return reportError(Message: "Malformed BlockInfoBlock in block info file");
607 BlockInfo = std::move(*NewBlockInfo);
608 break;
609 }
610
611 if (Error Err = BlockInfoCursor.SkipBlock())
612 return Err;
613 }
614 }
615
616 // Parse the top-level structure. We only allow blocks at the top-level.
617 while (!Stream.AtEndOfStream()) {
618 Expected<unsigned> MaybeCode = Stream.ReadCode();
619 if (!MaybeCode)
620 return MaybeCode.takeError();
621 if (MaybeCode.get() != bitc::ENTER_SUBBLOCK)
622 return reportError(Message: "Invalid record at top-level");
623
624 Expected<unsigned> MaybeBlockID = Stream.ReadSubBlockID();
625 if (!MaybeBlockID)
626 return MaybeBlockID.takeError();
627
628 if (Error E = parseBlock(BlockID: MaybeBlockID.get(), IndentLevel: 0, O, CheckHash))
629 return E;
630 ++NumTopBlocks;
631 }
632
633 return Error::success();
634}
635
636void BitcodeAnalyzer::printStats(BCDumpOptions O,
637 std::optional<StringRef> Filename) {
638 uint64_t BufferSizeBits = Stream.getBitcodeBytes().size() * CHAR_BIT;
639 // Print a summary of the read file.
640 O.OS << "Summary ";
641 if (Filename)
642 O.OS << "of " << Filename->data() << ":\n";
643 O.OS << " Total size: ";
644 printSize(OS&: O.OS, Bits: BufferSizeBits);
645 O.OS << "\n";
646 O.OS << " Stream type: ";
647 switch (CurStreamType) {
648 case UnknownBitstream:
649 O.OS << "unknown\n";
650 break;
651 case LLVMIRBitstream:
652 O.OS << "LLVM IR\n";
653 break;
654 case ClangSerializedASTBitstream:
655 O.OS << "Clang Serialized AST\n";
656 break;
657 case ClangSerializedDiagnosticsBitstream:
658 O.OS << "Clang Serialized Diagnostics\n";
659 break;
660 case LLVMBitstreamRemarks:
661 O.OS << "LLVM Remarks\n";
662 break;
663 }
664 O.OS << " # Toplevel Blocks: " << NumTopBlocks << "\n";
665 O.OS << "\n";
666
667 // Emit per-block stats.
668 O.OS << "Per-block Summary:\n";
669 for (const auto &Stat : BlockIDStats) {
670 O.OS << " Block ID #" << Stat.first;
671 if (std::optional<const char *> BlockName =
672 GetBlockName(BlockID: Stat.first, BlockInfo, CurStreamType))
673 O.OS << " (" << *BlockName << ")";
674 O.OS << ":\n";
675
676 const PerBlockIDStats &Stats = Stat.second;
677 O.OS << " Num Instances: " << Stats.NumInstances << "\n";
678 O.OS << " Total Size: ";
679 printSize(OS&: O.OS, Bits: Stats.NumBits);
680 O.OS << "\n";
681 double pct = (Stats.NumBits * 100.0) / BufferSizeBits;
682 O.OS << " Percent of file: " << format(Fmt: "%2.4f%%", Vals: pct) << "\n";
683 if (Stats.NumInstances > 1) {
684 O.OS << " Average Size: ";
685 printSize(OS&: O.OS, Bits: Stats.NumBits / (double)Stats.NumInstances);
686 O.OS << "\n";
687 O.OS << " Tot/Avg SubBlocks: " << Stats.NumSubBlocks << "/"
688 << Stats.NumSubBlocks / (double)Stats.NumInstances << "\n";
689 O.OS << " Tot/Avg Abbrevs: " << Stats.NumAbbrevs << "/"
690 << Stats.NumAbbrevs / (double)Stats.NumInstances << "\n";
691 O.OS << " Tot/Avg Records: " << Stats.NumRecords << "/"
692 << Stats.NumRecords / (double)Stats.NumInstances << "\n";
693 } else {
694 O.OS << " Num SubBlocks: " << Stats.NumSubBlocks << "\n";
695 O.OS << " Num Abbrevs: " << Stats.NumAbbrevs << "\n";
696 O.OS << " Num Records: " << Stats.NumRecords << "\n";
697 }
698 if (Stats.NumRecords) {
699 double pct = (Stats.NumAbbreviatedRecords * 100.0) / Stats.NumRecords;
700 O.OS << " Percent Abbrevs: " << format(Fmt: "%2.4f%%", Vals: pct) << "\n";
701 }
702 O.OS << "\n";
703
704 // Print a histogram of the codes we see.
705 if (O.Histogram && !Stats.CodeFreq.empty()) {
706 std::vector<std::pair<unsigned, unsigned>> FreqPairs; // <freq,code>
707 for (unsigned i = 0, e = Stats.CodeFreq.size(); i != e; ++i)
708 if (unsigned Freq = Stats.CodeFreq[i].NumInstances)
709 FreqPairs.push_back(x: std::make_pair(x&: Freq, y&: i));
710 llvm::stable_sort(Range&: FreqPairs);
711 std::reverse(first: FreqPairs.begin(), last: FreqPairs.end());
712
713 O.OS << "\tRecord Histogram:\n";
714 O.OS << "\t\t Count # Bits b/Rec % Abv Record Kind\n";
715 for (const auto &FreqPair : FreqPairs) {
716 const PerRecordStats &RecStats = Stats.CodeFreq[FreqPair.second];
717
718 O.OS << format(Fmt: "\t\t%7d %9lu", Vals: RecStats.NumInstances,
719 Vals: (unsigned long)RecStats.TotalBits);
720
721 if (RecStats.NumInstances > 1)
722 O.OS << format(Fmt: " %9.1f",
723 Vals: (double)RecStats.TotalBits / RecStats.NumInstances);
724 else
725 O.OS << " ";
726
727 if (RecStats.NumAbbrev)
728 O.OS << format(Fmt: " %7.2f", Vals: (double)RecStats.NumAbbrev /
729 RecStats.NumInstances * 100);
730 else
731 O.OS << " ";
732
733 O.OS << " ";
734 if (std::optional<const char *> CodeName = GetCodeName(
735 CodeID: FreqPair.second, BlockID: Stat.first, BlockInfo, CurStreamType))
736 O.OS << *CodeName << "\n";
737 else
738 O.OS << "UnknownCode" << FreqPair.second << "\n";
739 }
740 O.OS << "\n";
741 }
742 }
743}
744
745Error BitcodeAnalyzer::parseBlock(unsigned BlockID, unsigned IndentLevel,
746 std::optional<BCDumpOptions> O,
747 std::optional<StringRef> CheckHash) {
748 std::string Indent(IndentLevel * 2, ' ');
749 uint64_t BlockBitStart = Stream.GetCurrentBitNo();
750
751 // Get the statistics for this BlockID.
752 PerBlockIDStats &BlockStats = BlockIDStats[BlockID];
753
754 BlockStats.NumInstances++;
755
756 // BLOCKINFO is a special part of the stream.
757 bool DumpRecords = O.has_value();
758 if (BlockID == bitc::BLOCKINFO_BLOCK_ID) {
759 if (O && !O->DumpBlockinfo)
760 O->OS << Indent << "<BLOCKINFO_BLOCK/>\n";
761 std::optional<BitstreamBlockInfo> NewBlockInfo;
762 if (Error E = Stream.ReadBlockInfoBlock(/*ReadBlockInfoNames=*/true)
763 .moveInto(Value&: NewBlockInfo))
764 return E;
765 if (!NewBlockInfo)
766 return reportError(Message: "Malformed BlockInfoBlock");
767 BlockInfo = std::move(*NewBlockInfo);
768 if (Error Err = Stream.JumpToBit(BitNo: BlockBitStart))
769 return Err;
770 // It's not really interesting to dump the contents of the blockinfo
771 // block, so only do it if the user explicitly requests it.
772 DumpRecords = O && O->DumpBlockinfo;
773 }
774
775 unsigned NumWords = 0;
776 if (Error Err = Stream.EnterSubBlock(BlockID, NumWordsP: &NumWords))
777 return Err;
778
779 // Keep it for later, when we see a MODULE_HASH record
780 uint64_t BlockEntryPos = Stream.getCurrentByteNo();
781
782 std::optional<const char *> BlockName;
783 if (DumpRecords) {
784 O->OS << Indent << "<";
785 if ((BlockName = GetBlockName(BlockID, BlockInfo, CurStreamType)))
786 O->OS << *BlockName;
787 else
788 O->OS << "UnknownBlock" << BlockID;
789
790 if (!O->Symbolic && BlockName)
791 O->OS << " BlockID=" << BlockID;
792
793 O->OS << " NumWords=" << NumWords
794 << " BlockCodeSize=" << Stream.getAbbrevIDWidth() << ">\n";
795 }
796
797 SmallVector<uint64_t, 64> Record;
798
799 // Keep the offset to the metadata index if seen.
800 uint64_t MetadataIndexOffset = 0;
801
802 // Read all the records for this block.
803 while (true) {
804 if (Stream.AtEndOfStream())
805 return reportError(Message: "Premature end of bitstream");
806
807 uint64_t RecordStartBit = Stream.GetCurrentBitNo();
808
809 BitstreamEntry Entry;
810 if (Error E = Stream.advance(Flags: BitstreamCursor::AF_DontAutoprocessAbbrevs)
811 .moveInto(Value&: Entry))
812 return E;
813
814 switch (Entry.Kind) {
815 case BitstreamEntry::Error:
816 return reportError(Message: "malformed bitcode file");
817 case BitstreamEntry::EndBlock: {
818 uint64_t BlockBitEnd = Stream.GetCurrentBitNo();
819 BlockStats.NumBits += BlockBitEnd - BlockBitStart;
820 if (DumpRecords) {
821 O->OS << Indent << "</";
822 if (BlockName)
823 O->OS << *BlockName << ">\n";
824 else
825 O->OS << "UnknownBlock" << BlockID << ">\n";
826 }
827 return Error::success();
828 }
829
830 case BitstreamEntry::SubBlock: {
831 uint64_t SubBlockBitStart = Stream.GetCurrentBitNo();
832 if (Error E = parseBlock(BlockID: Entry.ID, IndentLevel: IndentLevel + 1, O, CheckHash))
833 return E;
834 ++BlockStats.NumSubBlocks;
835 uint64_t SubBlockBitEnd = Stream.GetCurrentBitNo();
836
837 // Don't include subblock sizes in the size of this block.
838 BlockBitStart += SubBlockBitEnd - SubBlockBitStart;
839 continue;
840 }
841 case BitstreamEntry::Record:
842 // The interesting case.
843 break;
844 }
845
846 if (Entry.ID == bitc::DEFINE_ABBREV) {
847 if (Error Err = Stream.ReadAbbrevRecord())
848 return Err;
849 ++BlockStats.NumAbbrevs;
850 continue;
851 }
852
853 Record.clear();
854
855 ++BlockStats.NumRecords;
856
857 StringRef Blob;
858 uint64_t CurrentRecordPos = Stream.GetCurrentBitNo();
859 unsigned Code;
860 if (Error E = Stream.readRecord(AbbrevID: Entry.ID, Vals&: Record, Blob: &Blob).moveInto(Value&: Code))
861 return E;
862
863 // Increment the # occurrences of this code.
864 if (BlockStats.CodeFreq.size() <= Code)
865 BlockStats.CodeFreq.resize(new_size: Code + 1);
866 BlockStats.CodeFreq[Code].NumInstances++;
867 BlockStats.CodeFreq[Code].TotalBits +=
868 Stream.GetCurrentBitNo() - RecordStartBit;
869 if (Entry.ID != bitc::UNABBREV_RECORD) {
870 BlockStats.CodeFreq[Code].NumAbbrev++;
871 ++BlockStats.NumAbbreviatedRecords;
872 }
873
874 if (DumpRecords) {
875 O->OS << Indent << " <";
876 std::optional<const char *> CodeName =
877 GetCodeName(CodeID: Code, BlockID, BlockInfo, CurStreamType);
878 if (CodeName)
879 O->OS << *CodeName;
880 else
881 O->OS << "UnknownCode" << Code;
882 if (!O->Symbolic && CodeName)
883 O->OS << " codeid=" << Code;
884 const BitCodeAbbrev *Abbv = nullptr;
885 if (Entry.ID != bitc::UNABBREV_RECORD) {
886 Expected<const BitCodeAbbrev *> MaybeAbbv = Stream.getAbbrev(AbbrevID: Entry.ID);
887 if (!MaybeAbbv)
888 return MaybeAbbv.takeError();
889 Abbv = MaybeAbbv.get();
890 O->OS << " abbrevid=" << Entry.ID;
891 }
892
893 for (unsigned i = 0, e = Record.size(); i != e; ++i)
894 O->OS << " op" << i << "=" << (int64_t)Record[i];
895
896 // If we found a metadata index, let's verify that we had an offset
897 // before and validate its forward reference offset was correct!
898 if (BlockID == bitc::METADATA_BLOCK_ID) {
899 if (Code == bitc::METADATA_INDEX_OFFSET) {
900 if (Record.size() != 2)
901 O->OS << "(Invalid record)";
902 else {
903 auto Offset = Record[0] + (Record[1] << 32);
904 MetadataIndexOffset = Stream.GetCurrentBitNo() + Offset;
905 }
906 }
907 if (Code == bitc::METADATA_INDEX) {
908 O->OS << " (offset ";
909 if (MetadataIndexOffset == RecordStartBit)
910 O->OS << "match)";
911 else
912 O->OS << "mismatch: " << MetadataIndexOffset << " vs "
913 << RecordStartBit << ")";
914 }
915 }
916
917 // If we found a module hash, let's verify that it matches!
918 if (BlockID == bitc::MODULE_BLOCK_ID && Code == bitc::MODULE_CODE_HASH &&
919 CheckHash) {
920 if (Record.size() != 5)
921 O->OS << " (invalid)";
922 else {
923 // Recompute the hash and compare it to the one in the bitcode
924 SHA1 Hasher;
925 std::array<uint8_t, 20> Hash;
926 Hasher.update(Str: *CheckHash);
927 {
928 int BlockSize = (CurrentRecordPos / 8) - BlockEntryPos;
929 auto Ptr = Stream.getPointerToByte(ByteNo: BlockEntryPos, NumBytes: BlockSize);
930 Hasher.update(Data: ArrayRef<uint8_t>(Ptr, BlockSize));
931 Hash = Hasher.result();
932 }
933 std::array<uint8_t, 20> RecordedHash;
934 int Pos = 0;
935 for (auto &Val : Record) {
936 assert(!(Val >> 32) && "Unexpected high bits set");
937 support::endian::write32be(P: &RecordedHash[Pos], V: Val);
938 Pos += 4;
939 }
940 if (Hash == RecordedHash)
941 O->OS << " (match)";
942 else
943 O->OS << " (!mismatch!)";
944 }
945 }
946
947 O->OS << "/>";
948
949 if (Abbv) {
950 for (unsigned i = 1, e = Abbv->getNumOperandInfos(); i != e; ++i) {
951 const BitCodeAbbrevOp &Op = Abbv->getOperandInfo(N: i);
952 if (!Op.isEncoding() || Op.getEncoding() != BitCodeAbbrevOp::Array)
953 continue;
954 assert(i + 2 == e && "Array op not second to last");
955 std::string Str;
956 bool ArrayIsPrintable = true;
957 for (unsigned j = i - 1, je = Record.size(); j != je; ++j) {
958 if (!isPrint(C: static_cast<unsigned char>(Record[j]))) {
959 ArrayIsPrintable = false;
960 break;
961 }
962 Str += (char)Record[j];
963 }
964 if (ArrayIsPrintable)
965 O->OS << " record string = '" << Str << "'";
966 break;
967 }
968 }
969
970 if (Blob.data()) {
971 if (canDecodeBlob(Code, BlockID)) {
972 if (Error E = decodeMetadataStringsBlob(Indent, Record, Blob, OS&: O->OS))
973 return E;
974 } else {
975 O->OS << " blob data = ";
976 if (O->ShowBinaryBlobs) {
977 O->OS << "'";
978 O->OS.write_escaped(Str: Blob, /*hex=*/UseHexEscapes: true) << "'";
979 } else {
980 bool BlobIsPrintable = true;
981 for (char C : Blob)
982 if (!isPrint(C: static_cast<unsigned char>(C))) {
983 BlobIsPrintable = false;
984 break;
985 }
986
987 if (BlobIsPrintable)
988 O->OS << "'" << Blob << "'";
989 else
990 O->OS << "unprintable, " << Blob.size() << " bytes.";
991 }
992 }
993 }
994
995 O->OS << "\n";
996 }
997
998 // Make sure that we can skip the current record.
999 if (Error Err = Stream.JumpToBit(BitNo: CurrentRecordPos))
1000 return Err;
1001 if (Expected<unsigned> Skipped = Stream.skipRecord(AbbrevID: Entry.ID))
1002 ; // Do nothing.
1003 else
1004 return Skipped.takeError();
1005 }
1006}
1007
1008