1 //===-- llvm-bcanalyzer.cpp - Bitcode Analyzer --------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This tool may be invoked in the following manner:
11 // llvm-bcanalyzer [options] - Read LLVM bitcode from stdin
12 // llvm-bcanalyzer [options] x.bc - Read LLVM bitcode from the x.bc file
15 // --help - Output information about command line switches
16 // --dump - Dump low-level bitcode structure in readable format
18 // This tool provides analytical information about a bitcode file. It is
19 // intended as an aid to developers of bitcode reading and writing software. It
20 // produces on std::out a summary of the bitcode file that shows various
21 // statistics about the contents of the file. By default this information is
22 // detailed and contains information about individual bitcode blocks and the
23 // functions in the module.
24 // The tool is also able to print a bitcode file in a straight forward text
25 // format that shows the containment and relationships of the information in
26 // the bitcode file (-dump option).
28 //===----------------------------------------------------------------------===//
30 #include "llvm/ADT/StringExtras.h"
31 #include "llvm/Bitcode/BitcodeReader.h"
32 #include "llvm/Bitcode/BitstreamReader.h"
33 #include "llvm/Bitcode/LLVMBitCodes.h"
34 #include "llvm/IR/Verifier.h"
35 #include "llvm/Support/CommandLine.h"
36 #include "llvm/Support/Format.h"
37 #include "llvm/Support/ManagedStatic.h"
38 #include "llvm/Support/MemoryBuffer.h"
39 #include "llvm/Support/PrettyStackTrace.h"
40 #include "llvm/Support/SHA1.h"
41 #include "llvm/Support/Signals.h"
42 #include "llvm/Support/raw_ostream.h"
46 #include <system_error>
49 static cl::opt<std::string>
50 InputFilename(cl::Positional, cl::desc("<input bitcode>"), cl::init("-"));
52 static cl::opt<bool> Dump("dump", cl::desc("Dump low level bitcode trace"));
54 //===----------------------------------------------------------------------===//
55 // Bitcode specific analysis.
56 //===----------------------------------------------------------------------===//
58 static cl::opt<bool> NoHistogram("disable-histogram",
59 cl::desc("Do not print per-code histogram"));
62 NonSymbolic("non-symbolic",
63 cl::desc("Emit numeric info in dump even if"
64 " symbolic info is available"));
66 static cl::opt<std::string>
67 BlockInfoFilename("block-info",
68 cl::desc("Use the BLOCK_INFO from the given file"));
71 ShowBinaryBlobs("show-binary-blobs",
72 cl::desc("Print binary blobs using hex escapes"));
76 /// CurStreamTypeType - A type for CurStreamType
77 enum CurStreamTypeType {
84 /// GetBlockName - Return a symbolic block name if known, otherwise return
86 static const char *GetBlockName(unsigned BlockID,
87 const BitstreamBlockInfo &BlockInfo,
88 CurStreamTypeType CurStreamType) {
89 // Standard blocks for all bitcode files.
90 if (BlockID < bitc::FIRST_APPLICATION_BLOCKID) {
91 if (BlockID == bitc::BLOCKINFO_BLOCK_ID)
92 return "BLOCKINFO_BLOCK";
96 // Check to see if we have a blockinfo record for this block, with a name.
97 if (const BitstreamBlockInfo::BlockInfo *Info =
98 BlockInfo.getBlockInfo(BlockID)) {
99 if (!Info->Name.empty())
100 return Info->Name.c_str();
104 if (CurStreamType != LLVMIRBitstream) return nullptr;
107 default: return nullptr;
108 case bitc::OPERAND_BUNDLE_TAGS_BLOCK_ID: return "OPERAND_BUNDLE_TAGS_BLOCK";
109 case bitc::MODULE_BLOCK_ID: return "MODULE_BLOCK";
110 case bitc::PARAMATTR_BLOCK_ID: return "PARAMATTR_BLOCK";
111 case bitc::PARAMATTR_GROUP_BLOCK_ID: return "PARAMATTR_GROUP_BLOCK_ID";
112 case bitc::TYPE_BLOCK_ID_NEW: return "TYPE_BLOCK_ID";
113 case bitc::CONSTANTS_BLOCK_ID: return "CONSTANTS_BLOCK";
114 case bitc::FUNCTION_BLOCK_ID: return "FUNCTION_BLOCK";
115 case bitc::IDENTIFICATION_BLOCK_ID:
116 return "IDENTIFICATION_BLOCK_ID";
117 case bitc::VALUE_SYMTAB_BLOCK_ID: return "VALUE_SYMTAB";
118 case bitc::METADATA_BLOCK_ID: return "METADATA_BLOCK";
119 case bitc::METADATA_KIND_BLOCK_ID: return "METADATA_KIND_BLOCK";
120 case bitc::METADATA_ATTACHMENT_ID: return "METADATA_ATTACHMENT_BLOCK";
121 case bitc::USELIST_BLOCK_ID: return "USELIST_BLOCK_ID";
122 case bitc::GLOBALVAL_SUMMARY_BLOCK_ID:
123 return "GLOBALVAL_SUMMARY_BLOCK";
124 case bitc::MODULE_STRTAB_BLOCK_ID: return "MODULE_STRTAB_BLOCK";
128 /// GetCodeName - Return a symbolic code name if known, otherwise return
130 static const char *GetCodeName(unsigned CodeID, unsigned BlockID,
131 const BitstreamBlockInfo &BlockInfo,
132 CurStreamTypeType CurStreamType) {
133 // Standard blocks for all bitcode files.
134 if (BlockID < bitc::FIRST_APPLICATION_BLOCKID) {
135 if (BlockID == bitc::BLOCKINFO_BLOCK_ID) {
137 default: return nullptr;
138 case bitc::BLOCKINFO_CODE_SETBID: return "SETBID";
139 case bitc::BLOCKINFO_CODE_BLOCKNAME: return "BLOCKNAME";
140 case bitc::BLOCKINFO_CODE_SETRECORDNAME: return "SETRECORDNAME";
146 // Check to see if we have a blockinfo record for this record, with a name.
147 if (const BitstreamBlockInfo::BlockInfo *Info =
148 BlockInfo.getBlockInfo(BlockID)) {
149 for (unsigned i = 0, e = Info->RecordNames.size(); i != e; ++i)
150 if (Info->RecordNames[i].first == CodeID)
151 return Info->RecordNames[i].second.c_str();
155 if (CurStreamType != LLVMIRBitstream) return nullptr;
157 #define STRINGIFY_CODE(PREFIX, CODE) \
158 case bitc::PREFIX##_##CODE: \
161 default: return nullptr;
162 case bitc::MODULE_BLOCK_ID:
164 default: return nullptr;
165 STRINGIFY_CODE(MODULE_CODE, VERSION)
166 STRINGIFY_CODE(MODULE_CODE, TRIPLE)
167 STRINGIFY_CODE(MODULE_CODE, DATALAYOUT)
168 STRINGIFY_CODE(MODULE_CODE, ASM)
169 STRINGIFY_CODE(MODULE_CODE, SECTIONNAME)
170 STRINGIFY_CODE(MODULE_CODE, DEPLIB) // FIXME: Remove in 4.0
171 STRINGIFY_CODE(MODULE_CODE, GLOBALVAR)
172 STRINGIFY_CODE(MODULE_CODE, FUNCTION)
173 STRINGIFY_CODE(MODULE_CODE, ALIAS)
174 STRINGIFY_CODE(MODULE_CODE, PURGEVALS)
175 STRINGIFY_CODE(MODULE_CODE, GCNAME)
176 STRINGIFY_CODE(MODULE_CODE, VSTOFFSET)
177 STRINGIFY_CODE(MODULE_CODE, METADATA_VALUES_UNUSED)
178 STRINGIFY_CODE(MODULE_CODE, SOURCE_FILENAME)
179 STRINGIFY_CODE(MODULE_CODE, HASH)
181 case bitc::IDENTIFICATION_BLOCK_ID:
185 STRINGIFY_CODE(IDENTIFICATION_CODE, STRING)
186 STRINGIFY_CODE(IDENTIFICATION_CODE, EPOCH)
188 case bitc::PARAMATTR_BLOCK_ID:
190 default: return nullptr;
191 // FIXME: Should these be different?
192 case bitc::PARAMATTR_CODE_ENTRY_OLD: return "ENTRY";
193 case bitc::PARAMATTR_CODE_ENTRY: return "ENTRY";
195 case bitc::PARAMATTR_GROUP_BLOCK_ID:
197 default: return nullptr;
198 case bitc::PARAMATTR_GRP_CODE_ENTRY: return "ENTRY";
200 case bitc::TYPE_BLOCK_ID_NEW:
202 default: return nullptr;
203 STRINGIFY_CODE(TYPE_CODE, NUMENTRY)
204 STRINGIFY_CODE(TYPE_CODE, VOID)
205 STRINGIFY_CODE(TYPE_CODE, FLOAT)
206 STRINGIFY_CODE(TYPE_CODE, DOUBLE)
207 STRINGIFY_CODE(TYPE_CODE, LABEL)
208 STRINGIFY_CODE(TYPE_CODE, OPAQUE)
209 STRINGIFY_CODE(TYPE_CODE, INTEGER)
210 STRINGIFY_CODE(TYPE_CODE, POINTER)
211 STRINGIFY_CODE(TYPE_CODE, ARRAY)
212 STRINGIFY_CODE(TYPE_CODE, VECTOR)
213 STRINGIFY_CODE(TYPE_CODE, X86_FP80)
214 STRINGIFY_CODE(TYPE_CODE, FP128)
215 STRINGIFY_CODE(TYPE_CODE, PPC_FP128)
216 STRINGIFY_CODE(TYPE_CODE, METADATA)
217 STRINGIFY_CODE(TYPE_CODE, STRUCT_ANON)
218 STRINGIFY_CODE(TYPE_CODE, STRUCT_NAME)
219 STRINGIFY_CODE(TYPE_CODE, STRUCT_NAMED)
220 STRINGIFY_CODE(TYPE_CODE, FUNCTION)
223 case bitc::CONSTANTS_BLOCK_ID:
225 default: return nullptr;
226 STRINGIFY_CODE(CST_CODE, SETTYPE)
227 STRINGIFY_CODE(CST_CODE, NULL)
228 STRINGIFY_CODE(CST_CODE, UNDEF)
229 STRINGIFY_CODE(CST_CODE, INTEGER)
230 STRINGIFY_CODE(CST_CODE, WIDE_INTEGER)
231 STRINGIFY_CODE(CST_CODE, FLOAT)
232 STRINGIFY_CODE(CST_CODE, AGGREGATE)
233 STRINGIFY_CODE(CST_CODE, STRING)
234 STRINGIFY_CODE(CST_CODE, CSTRING)
235 STRINGIFY_CODE(CST_CODE, CE_BINOP)
236 STRINGIFY_CODE(CST_CODE, CE_CAST)
237 STRINGIFY_CODE(CST_CODE, CE_GEP)
238 STRINGIFY_CODE(CST_CODE, CE_INBOUNDS_GEP)
239 STRINGIFY_CODE(CST_CODE, CE_SELECT)
240 STRINGIFY_CODE(CST_CODE, CE_EXTRACTELT)
241 STRINGIFY_CODE(CST_CODE, CE_INSERTELT)
242 STRINGIFY_CODE(CST_CODE, CE_SHUFFLEVEC)
243 STRINGIFY_CODE(CST_CODE, CE_CMP)
244 STRINGIFY_CODE(CST_CODE, INLINEASM)
245 STRINGIFY_CODE(CST_CODE, CE_SHUFVEC_EX)
246 case bitc::CST_CODE_BLOCKADDRESS: return "CST_CODE_BLOCKADDRESS";
247 STRINGIFY_CODE(CST_CODE, DATA)
249 case bitc::FUNCTION_BLOCK_ID:
251 default: return nullptr;
252 STRINGIFY_CODE(FUNC_CODE, DECLAREBLOCKS)
253 STRINGIFY_CODE(FUNC_CODE, INST_BINOP)
254 STRINGIFY_CODE(FUNC_CODE, INST_CAST)
255 STRINGIFY_CODE(FUNC_CODE, INST_GEP_OLD)
256 STRINGIFY_CODE(FUNC_CODE, INST_INBOUNDS_GEP_OLD)
257 STRINGIFY_CODE(FUNC_CODE, INST_SELECT)
258 STRINGIFY_CODE(FUNC_CODE, INST_EXTRACTELT)
259 STRINGIFY_CODE(FUNC_CODE, INST_INSERTELT)
260 STRINGIFY_CODE(FUNC_CODE, INST_SHUFFLEVEC)
261 STRINGIFY_CODE(FUNC_CODE, INST_CMP)
262 STRINGIFY_CODE(FUNC_CODE, INST_RET)
263 STRINGIFY_CODE(FUNC_CODE, INST_BR)
264 STRINGIFY_CODE(FUNC_CODE, INST_SWITCH)
265 STRINGIFY_CODE(FUNC_CODE, INST_INVOKE)
266 STRINGIFY_CODE(FUNC_CODE, INST_UNREACHABLE)
267 STRINGIFY_CODE(FUNC_CODE, INST_CLEANUPRET)
268 STRINGIFY_CODE(FUNC_CODE, INST_CATCHRET)
269 STRINGIFY_CODE(FUNC_CODE, INST_CATCHPAD)
270 STRINGIFY_CODE(FUNC_CODE, INST_PHI)
271 STRINGIFY_CODE(FUNC_CODE, INST_ALLOCA)
272 STRINGIFY_CODE(FUNC_CODE, INST_LOAD)
273 STRINGIFY_CODE(FUNC_CODE, INST_VAARG)
274 STRINGIFY_CODE(FUNC_CODE, INST_STORE)
275 STRINGIFY_CODE(FUNC_CODE, INST_EXTRACTVAL)
276 STRINGIFY_CODE(FUNC_CODE, INST_INSERTVAL)
277 STRINGIFY_CODE(FUNC_CODE, INST_CMP2)
278 STRINGIFY_CODE(FUNC_CODE, INST_VSELECT)
279 STRINGIFY_CODE(FUNC_CODE, DEBUG_LOC_AGAIN)
280 STRINGIFY_CODE(FUNC_CODE, INST_CALL)
281 STRINGIFY_CODE(FUNC_CODE, DEBUG_LOC)
282 STRINGIFY_CODE(FUNC_CODE, INST_GEP)
283 STRINGIFY_CODE(FUNC_CODE, OPERAND_BUNDLE)
285 case bitc::VALUE_SYMTAB_BLOCK_ID:
287 default: return nullptr;
288 STRINGIFY_CODE(VST_CODE, ENTRY)
289 STRINGIFY_CODE(VST_CODE, BBENTRY)
290 STRINGIFY_CODE(VST_CODE, FNENTRY)
291 STRINGIFY_CODE(VST_CODE, COMBINED_ENTRY)
293 case bitc::MODULE_STRTAB_BLOCK_ID:
297 STRINGIFY_CODE(MST_CODE, ENTRY)
298 STRINGIFY_CODE(MST_CODE, HASH)
300 case bitc::GLOBALVAL_SUMMARY_BLOCK_ID:
304 STRINGIFY_CODE(FS, PERMODULE)
305 STRINGIFY_CODE(FS, PERMODULE_PROFILE)
306 STRINGIFY_CODE(FS, PERMODULE_GLOBALVAR_INIT_REFS)
307 STRINGIFY_CODE(FS, COMBINED)
308 STRINGIFY_CODE(FS, COMBINED_PROFILE)
309 STRINGIFY_CODE(FS, COMBINED_GLOBALVAR_INIT_REFS)
310 STRINGIFY_CODE(FS, ALIAS)
311 STRINGIFY_CODE(FS, COMBINED_ALIAS)
312 STRINGIFY_CODE(FS, COMBINED_ORIGINAL_NAME)
313 STRINGIFY_CODE(FS, VERSION)
314 STRINGIFY_CODE(FS, TYPE_TESTS)
316 case bitc::METADATA_ATTACHMENT_ID:
318 default:return nullptr;
319 STRINGIFY_CODE(METADATA, ATTACHMENT)
321 case bitc::METADATA_BLOCK_ID:
323 default:return nullptr;
324 STRINGIFY_CODE(METADATA, STRING_OLD)
325 STRINGIFY_CODE(METADATA, VALUE)
326 STRINGIFY_CODE(METADATA, NODE)
327 STRINGIFY_CODE(METADATA, NAME)
328 STRINGIFY_CODE(METADATA, DISTINCT_NODE)
329 STRINGIFY_CODE(METADATA, KIND) // Older bitcode has it in a MODULE_BLOCK
330 STRINGIFY_CODE(METADATA, LOCATION)
331 STRINGIFY_CODE(METADATA, OLD_NODE)
332 STRINGIFY_CODE(METADATA, OLD_FN_NODE)
333 STRINGIFY_CODE(METADATA, NAMED_NODE)
334 STRINGIFY_CODE(METADATA, GENERIC_DEBUG)
335 STRINGIFY_CODE(METADATA, SUBRANGE)
336 STRINGIFY_CODE(METADATA, ENUMERATOR)
337 STRINGIFY_CODE(METADATA, BASIC_TYPE)
338 STRINGIFY_CODE(METADATA, FILE)
339 STRINGIFY_CODE(METADATA, DERIVED_TYPE)
340 STRINGIFY_CODE(METADATA, COMPOSITE_TYPE)
341 STRINGIFY_CODE(METADATA, SUBROUTINE_TYPE)
342 STRINGIFY_CODE(METADATA, COMPILE_UNIT)
343 STRINGIFY_CODE(METADATA, SUBPROGRAM)
344 STRINGIFY_CODE(METADATA, LEXICAL_BLOCK)
345 STRINGIFY_CODE(METADATA, LEXICAL_BLOCK_FILE)
346 STRINGIFY_CODE(METADATA, NAMESPACE)
347 STRINGIFY_CODE(METADATA, TEMPLATE_TYPE)
348 STRINGIFY_CODE(METADATA, TEMPLATE_VALUE)
349 STRINGIFY_CODE(METADATA, GLOBAL_VAR)
350 STRINGIFY_CODE(METADATA, LOCAL_VAR)
351 STRINGIFY_CODE(METADATA, EXPRESSION)
352 STRINGIFY_CODE(METADATA, OBJC_PROPERTY)
353 STRINGIFY_CODE(METADATA, IMPORTED_ENTITY)
354 STRINGIFY_CODE(METADATA, MODULE)
355 STRINGIFY_CODE(METADATA, MACRO)
356 STRINGIFY_CODE(METADATA, MACRO_FILE)
357 STRINGIFY_CODE(METADATA, STRINGS)
358 STRINGIFY_CODE(METADATA, GLOBAL_DECL_ATTACHMENT)
359 STRINGIFY_CODE(METADATA, GLOBAL_VAR_EXPR)
360 STRINGIFY_CODE(METADATA, INDEX_OFFSET)
361 STRINGIFY_CODE(METADATA, INDEX)
363 case bitc::METADATA_KIND_BLOCK_ID:
367 STRINGIFY_CODE(METADATA, KIND)
369 case bitc::USELIST_BLOCK_ID:
371 default:return nullptr;
372 case bitc::USELIST_CODE_DEFAULT: return "USELIST_CODE_DEFAULT";
373 case bitc::USELIST_CODE_BB: return "USELIST_CODE_BB";
376 case bitc::OPERAND_BUNDLE_TAGS_BLOCK_ID:
378 default: return nullptr;
379 case bitc::OPERAND_BUNDLE_TAG: return "OPERAND_BUNDLE_TAG";
382 #undef STRINGIFY_CODE
385 struct PerRecordStats {
386 unsigned NumInstances;
390 PerRecordStats() : NumInstances(0), NumAbbrev(0), TotalBits(0) {}
393 struct PerBlockIDStats {
394 /// NumInstances - This the number of times this block ID has been seen.
395 unsigned NumInstances;
397 /// NumBits - The total size in bits of all of these blocks.
400 /// NumSubBlocks - The total number of blocks these blocks contain.
401 unsigned NumSubBlocks;
403 /// NumAbbrevs - The total number of abbreviations.
406 /// NumRecords - The total number of records these blocks contain, and the
407 /// number that are abbreviated.
408 unsigned NumRecords, NumAbbreviatedRecords;
410 /// CodeFreq - Keep track of the number of times we see each code.
411 std::vector<PerRecordStats> CodeFreq;
414 : NumInstances(0), NumBits(0),
415 NumSubBlocks(0), NumAbbrevs(0), NumRecords(0), NumAbbreviatedRecords(0) {}
418 static std::map<unsigned, PerBlockIDStats> BlockIDStats;
422 /// ReportError - All bitcode analysis errors go through this function, making this a
423 /// good place to breakpoint if debugging.
424 static bool ReportError(const Twine &Err) {
425 errs() << Err << "\n";
429 static bool decodeMetadataStringsBlob(StringRef Indent,
430 ArrayRef<uint64_t> Record,
435 if (Record.size() != 2)
438 unsigned NumStrings = Record[0];
439 unsigned StringsOffset = Record[1];
440 outs() << " num-strings = " << NumStrings << " {\n";
442 StringRef Lengths = Blob.slice(0, StringsOffset);
443 SimpleBitstreamCursor R(Lengths);
444 StringRef Strings = Blob.drop_front(StringsOffset);
446 if (R.AtEndOfStream())
447 return ReportError("bad length");
449 unsigned Size = R.ReadVBR(6);
450 if (Strings.size() < Size)
451 return ReportError("truncated chars");
453 outs() << Indent << " '";
454 outs().write_escaped(Strings.slice(0, Size), /*hex=*/true);
456 Strings = Strings.drop_front(Size);
457 } while (--NumStrings);
459 outs() << Indent << " }";
463 static bool decodeBlob(unsigned Code, unsigned BlockID, StringRef Indent,
464 ArrayRef<uint64_t> Record, StringRef Blob) {
465 if (BlockID != bitc::METADATA_BLOCK_ID)
467 if (Code != bitc::METADATA_STRINGS)
470 return decodeMetadataStringsBlob(Indent, Record, Blob);
473 /// ParseBlock - Read a block, updating statistics, etc.
474 static bool ParseBlock(BitstreamCursor &Stream, BitstreamBlockInfo &BlockInfo,
475 unsigned BlockID, unsigned IndentLevel,
476 CurStreamTypeType CurStreamType) {
477 std::string Indent(IndentLevel*2, ' ');
478 uint64_t BlockBitStart = Stream.GetCurrentBitNo();
480 // Get the statistics for this BlockID.
481 PerBlockIDStats &BlockStats = BlockIDStats[BlockID];
483 BlockStats.NumInstances++;
485 // BLOCKINFO is a special part of the stream.
486 bool DumpRecords = Dump;
487 if (BlockID == bitc::BLOCKINFO_BLOCK_ID) {
488 if (Dump) outs() << Indent << "<BLOCKINFO_BLOCK/>\n";
489 Optional<BitstreamBlockInfo> NewBlockInfo =
490 Stream.ReadBlockInfoBlock(/*ReadBlockInfoNames=*/true);
492 return ReportError("Malformed BlockInfoBlock");
493 BlockInfo = std::move(*NewBlockInfo);
494 Stream.JumpToBit(BlockBitStart);
495 // It's not really interesting to dump the contents of the blockinfo block.
499 unsigned NumWords = 0;
500 if (Stream.EnterSubBlock(BlockID, &NumWords))
501 return ReportError("Malformed block record");
503 // Keep it for later, when we see a MODULE_HASH record
504 uint64_t BlockEntryPos = Stream.getCurrentByteNo();
506 const char *BlockName = nullptr;
508 outs() << Indent << "<";
509 if ((BlockName = GetBlockName(BlockID, BlockInfo, CurStreamType)))
512 outs() << "UnknownBlock" << BlockID;
514 if (NonSymbolic && BlockName)
515 outs() << " BlockID=" << BlockID;
517 outs() << " NumWords=" << NumWords
518 << " BlockCodeSize=" << Stream.getAbbrevIDWidth() << ">\n";
521 SmallVector<uint64_t, 64> Record;
523 // Keep the offset to the metadata index if seen.
524 uint64_t MetadataIndexOffset = 0;
526 // Read all the records for this block.
528 if (Stream.AtEndOfStream())
529 return ReportError("Premature end of bitstream");
531 uint64_t RecordStartBit = Stream.GetCurrentBitNo();
533 BitstreamEntry Entry =
534 Stream.advance(BitstreamCursor::AF_DontAutoprocessAbbrevs);
536 switch (Entry.Kind) {
537 case BitstreamEntry::Error:
538 return ReportError("malformed bitcode file");
539 case BitstreamEntry::EndBlock: {
540 uint64_t BlockBitEnd = Stream.GetCurrentBitNo();
541 BlockStats.NumBits += BlockBitEnd-BlockBitStart;
543 outs() << Indent << "</";
545 outs() << BlockName << ">\n";
547 outs() << "UnknownBlock" << BlockID << ">\n";
552 case BitstreamEntry::SubBlock: {
553 uint64_t SubBlockBitStart = Stream.GetCurrentBitNo();
554 if (ParseBlock(Stream, BlockInfo, Entry.ID, IndentLevel + 1,
557 ++BlockStats.NumSubBlocks;
558 uint64_t SubBlockBitEnd = Stream.GetCurrentBitNo();
560 // Don't include subblock sizes in the size of this block.
561 BlockBitStart += SubBlockBitEnd-SubBlockBitStart;
564 case BitstreamEntry::Record:
565 // The interesting case.
569 if (Entry.ID == bitc::DEFINE_ABBREV) {
570 Stream.ReadAbbrevRecord();
571 ++BlockStats.NumAbbrevs;
577 ++BlockStats.NumRecords;
580 unsigned CurrentRecordPos = Stream.GetCurrentBitNo();
581 unsigned Code = Stream.readRecord(Entry.ID, Record, &Blob);
583 // Increment the # occurrences of this code.
584 if (BlockStats.CodeFreq.size() <= Code)
585 BlockStats.CodeFreq.resize(Code+1);
586 BlockStats.CodeFreq[Code].NumInstances++;
587 BlockStats.CodeFreq[Code].TotalBits +=
588 Stream.GetCurrentBitNo()-RecordStartBit;
589 if (Entry.ID != bitc::UNABBREV_RECORD) {
590 BlockStats.CodeFreq[Code].NumAbbrev++;
591 ++BlockStats.NumAbbreviatedRecords;
595 outs() << Indent << " <";
596 if (const char *CodeName =
597 GetCodeName(Code, BlockID, BlockInfo, CurStreamType))
600 outs() << "UnknownCode" << Code;
601 if (NonSymbolic && GetCodeName(Code, BlockID, BlockInfo, CurStreamType))
602 outs() << " codeid=" << Code;
603 const BitCodeAbbrev *Abbv = nullptr;
604 if (Entry.ID != bitc::UNABBREV_RECORD) {
605 Abbv = Stream.getAbbrev(Entry.ID);
606 outs() << " abbrevid=" << Entry.ID;
609 for (unsigned i = 0, e = Record.size(); i != e; ++i)
610 outs() << " op" << i << "=" << (int64_t)Record[i];
612 // If we found a metadata index, let's verify that we had an offset before
613 // and validate its forward reference offset was correct!
614 if (BlockID == bitc::METADATA_BLOCK_ID) {
615 if (Code == bitc::METADATA_INDEX_OFFSET) {
616 if (Record.size() != 2)
617 outs() << "(Invalid record)";
619 auto Offset = Record[0] + (Record[1] << 32);
620 MetadataIndexOffset = Stream.GetCurrentBitNo() + Offset;
623 if (Code == bitc::METADATA_INDEX) {
624 outs() << " (offset ";
625 if (MetadataIndexOffset == RecordStartBit)
628 outs() << "mismatch: " << MetadataIndexOffset << " vs "
629 << RecordStartBit << ")";
633 // If we found a module hash, let's verify that it matches!
634 if (BlockID == bitc::MODULE_BLOCK_ID && Code == bitc::MODULE_CODE_HASH) {
635 if (Record.size() != 5)
636 outs() << " (invalid)";
638 // Recompute the hash and compare it to the one in the bitcode
642 int BlockSize = (CurrentRecordPos / 8) - BlockEntryPos;
643 auto Ptr = Stream.getPointerToByte(BlockEntryPos, BlockSize);
644 Hasher.update(ArrayRef<uint8_t>(Ptr, BlockSize));
645 Hash = Hasher.result();
647 SmallString<20> RecordedHash;
648 RecordedHash.resize(20);
650 for (auto &Val : Record) {
651 assert(!(Val >> 32) && "Unexpected high bits set");
652 RecordedHash[Pos++] = (Val >> 24) & 0xFF;
653 RecordedHash[Pos++] = (Val >> 16) & 0xFF;
654 RecordedHash[Pos++] = (Val >> 8) & 0xFF;
655 RecordedHash[Pos++] = (Val >> 0) & 0xFF;
657 if (Hash == RecordedHash)
658 outs() << " (match)";
660 outs() << " (!mismatch!)";
667 for (unsigned i = 1, e = Abbv->getNumOperandInfos(); i != e; ++i) {
668 const BitCodeAbbrevOp &Op = Abbv->getOperandInfo(i);
669 if (!Op.isEncoding() || Op.getEncoding() != BitCodeAbbrevOp::Array)
671 assert(i + 2 == e && "Array op not second to last");
673 bool ArrayIsPrintable = true;
674 for (unsigned j = i - 1, je = Record.size(); j != je; ++j) {
675 if (!isprint(static_cast<unsigned char>(Record[j]))) {
676 ArrayIsPrintable = false;
679 Str += (char)Record[j];
681 if (ArrayIsPrintable)
682 outs() << " record string = '" << Str << "'";
687 if (Blob.data() && decodeBlob(Code, BlockID, Indent, Record, Blob)) {
688 outs() << " blob data = ";
689 if (ShowBinaryBlobs) {
691 outs().write_escaped(Blob, /*hex=*/true) << "'";
693 bool BlobIsPrintable = true;
694 for (unsigned i = 0, e = Blob.size(); i != e; ++i)
695 if (!isprint(static_cast<unsigned char>(Blob[i]))) {
696 BlobIsPrintable = false;
701 outs() << "'" << Blob << "'";
703 outs() << "unprintable, " << Blob.size() << " bytes.";
710 // Make sure that we can skip the current record.
711 Stream.JumpToBit(CurrentRecordPos);
712 Stream.skipRecord(Entry.ID);
716 static void PrintSize(double Bits) {
717 outs() << format("%.2f/%.2fB/%luW", Bits, Bits/8,(unsigned long)(Bits/32));
719 static void PrintSize(uint64_t Bits) {
720 outs() << format("%lub/%.2fB/%luW", (unsigned long)Bits,
721 (double)Bits/8, (unsigned long)(Bits/32));
724 static bool openBitcodeFile(StringRef Path,
725 std::unique_ptr<MemoryBuffer> &MemBuf,
726 BitstreamCursor &Stream,
727 CurStreamTypeType &CurStreamType) {
728 // Read the input file.
729 ErrorOr<std::unique_ptr<MemoryBuffer>> MemBufOrErr =
730 MemoryBuffer::getFileOrSTDIN(Path);
731 if (std::error_code EC = MemBufOrErr.getError())
732 return ReportError(Twine("ReportError reading '") + Path + "': " + EC.message());
733 MemBuf = std::move(MemBufOrErr.get());
735 if (MemBuf->getBufferSize() & 3)
736 return ReportError("Bitcode stream should be a multiple of 4 bytes in length");
738 const unsigned char *BufPtr = (const unsigned char *)MemBuf->getBufferStart();
739 const unsigned char *EndBufPtr = BufPtr + MemBuf->getBufferSize();
741 // If we have a wrapper header, parse it and ignore the non-bc file contents.
742 // The magic number is 0x0B17C0DE stored in little endian.
743 if (isBitcodeWrapper(BufPtr, EndBufPtr)) {
744 if (MemBuf->getBufferSize() < BWH_HeaderSize)
745 return ReportError("Invalid bitcode wrapper header");
748 unsigned Magic = support::endian::read32le(&BufPtr[BWH_MagicField]);
749 unsigned Version = support::endian::read32le(&BufPtr[BWH_VersionField]);
750 unsigned Offset = support::endian::read32le(&BufPtr[BWH_OffsetField]);
751 unsigned Size = support::endian::read32le(&BufPtr[BWH_SizeField]);
752 unsigned CPUType = support::endian::read32le(&BufPtr[BWH_CPUTypeField]);
754 outs() << "<BITCODE_WRAPPER_HEADER"
755 << " Magic=" << format_hex(Magic, 10)
756 << " Version=" << format_hex(Version, 10)
757 << " Offset=" << format_hex(Offset, 10)
758 << " Size=" << format_hex(Size, 10)
759 << " CPUType=" << format_hex(CPUType, 10) << "/>\n";
762 if (SkipBitcodeWrapperHeader(BufPtr, EndBufPtr, true))
763 return ReportError("Invalid bitcode wrapper header");
766 Stream = BitstreamCursor(ArrayRef<uint8_t>(BufPtr, EndBufPtr));
768 // Read the stream signature.
770 Signature[0] = Stream.Read(8);
771 Signature[1] = Stream.Read(8);
772 Signature[2] = Stream.Read(4);
773 Signature[3] = Stream.Read(4);
774 Signature[4] = Stream.Read(4);
775 Signature[5] = Stream.Read(4);
777 // Autodetect the file contents, if it is one we know.
778 CurStreamType = UnknownBitstream;
779 if (Signature[0] == 'B' && Signature[1] == 'C' &&
780 Signature[2] == 0x0 && Signature[3] == 0xC &&
781 Signature[4] == 0xE && Signature[5] == 0xD)
782 CurStreamType = LLVMIRBitstream;
787 /// AnalyzeBitcode - Analyze the bitcode file specified by InputFilename.
788 static int AnalyzeBitcode() {
789 std::unique_ptr<MemoryBuffer> StreamBuffer;
790 BitstreamCursor Stream;
791 BitstreamBlockInfo BlockInfo;
792 CurStreamTypeType CurStreamType;
793 if (openBitcodeFile(InputFilename, StreamBuffer, Stream, CurStreamType))
795 Stream.setBlockInfo(&BlockInfo);
797 // Read block info from BlockInfoFilename, if specified.
798 // The block info must be a top-level block.
799 if (!BlockInfoFilename.empty()) {
800 std::unique_ptr<MemoryBuffer> BlockInfoBuffer;
801 BitstreamCursor BlockInfoCursor;
802 CurStreamTypeType BlockInfoStreamType;
803 if (openBitcodeFile(BlockInfoFilename, BlockInfoBuffer, BlockInfoCursor,
804 BlockInfoStreamType))
807 while (!BlockInfoCursor.AtEndOfStream()) {
808 unsigned Code = BlockInfoCursor.ReadCode();
809 if (Code != bitc::ENTER_SUBBLOCK)
810 return ReportError("Invalid record at top-level in block info file");
812 unsigned BlockID = BlockInfoCursor.ReadSubBlockID();
813 if (BlockID == bitc::BLOCKINFO_BLOCK_ID) {
814 Optional<BitstreamBlockInfo> NewBlockInfo =
815 BlockInfoCursor.ReadBlockInfoBlock(/*ReadBlockInfoNames=*/true);
817 return ReportError("Malformed BlockInfoBlock in block info file");
818 BlockInfo = std::move(*NewBlockInfo);
822 BlockInfoCursor.SkipBlock();
826 unsigned NumTopBlocks = 0;
828 // Parse the top-level structure. We only allow blocks at the top-level.
829 while (!Stream.AtEndOfStream()) {
830 unsigned Code = Stream.ReadCode();
831 if (Code != bitc::ENTER_SUBBLOCK)
832 return ReportError("Invalid record at top-level");
834 unsigned BlockID = Stream.ReadSubBlockID();
836 if (ParseBlock(Stream, BlockInfo, BlockID, 0, CurStreamType))
841 if (Dump) outs() << "\n\n";
843 uint64_t BufferSizeBits = Stream.getBitcodeBytes().size() * CHAR_BIT;
844 // Print a summary of the read file.
845 outs() << "Summary of " << InputFilename << ":\n";
846 outs() << " Total size: ";
847 PrintSize(BufferSizeBits);
849 outs() << " Stream type: ";
850 switch (CurStreamType) {
851 case UnknownBitstream: outs() << "unknown\n"; break;
852 case LLVMIRBitstream: outs() << "LLVM IR\n"; break;
854 outs() << " # Toplevel Blocks: " << NumTopBlocks << "\n";
857 // Emit per-block stats.
858 outs() << "Per-block Summary:\n";
859 for (std::map<unsigned, PerBlockIDStats>::iterator I = BlockIDStats.begin(),
860 E = BlockIDStats.end(); I != E; ++I) {
861 outs() << " Block ID #" << I->first;
862 if (const char *BlockName =
863 GetBlockName(I->first, BlockInfo, CurStreamType))
864 outs() << " (" << BlockName << ")";
867 const PerBlockIDStats &Stats = I->second;
868 outs() << " Num Instances: " << Stats.NumInstances << "\n";
869 outs() << " Total Size: ";
870 PrintSize(Stats.NumBits);
872 double pct = (Stats.NumBits * 100.0) / BufferSizeBits;
873 outs() << " Percent of file: " << format("%2.4f%%", pct) << "\n";
874 if (Stats.NumInstances > 1) {
875 outs() << " Average Size: ";
876 PrintSize(Stats.NumBits/(double)Stats.NumInstances);
878 outs() << " Tot/Avg SubBlocks: " << Stats.NumSubBlocks << "/"
879 << Stats.NumSubBlocks/(double)Stats.NumInstances << "\n";
880 outs() << " Tot/Avg Abbrevs: " << Stats.NumAbbrevs << "/"
881 << Stats.NumAbbrevs/(double)Stats.NumInstances << "\n";
882 outs() << " Tot/Avg Records: " << Stats.NumRecords << "/"
883 << Stats.NumRecords/(double)Stats.NumInstances << "\n";
885 outs() << " Num SubBlocks: " << Stats.NumSubBlocks << "\n";
886 outs() << " Num Abbrevs: " << Stats.NumAbbrevs << "\n";
887 outs() << " Num Records: " << Stats.NumRecords << "\n";
889 if (Stats.NumRecords) {
890 double pct = (Stats.NumAbbreviatedRecords * 100.0) / Stats.NumRecords;
891 outs() << " Percent Abbrevs: " << format("%2.4f%%", pct) << "\n";
895 // Print a histogram of the codes we see.
896 if (!NoHistogram && !Stats.CodeFreq.empty()) {
897 std::vector<std::pair<unsigned, unsigned> > FreqPairs; // <freq,code>
898 for (unsigned i = 0, e = Stats.CodeFreq.size(); i != e; ++i)
899 if (unsigned Freq = Stats.CodeFreq[i].NumInstances)
900 FreqPairs.push_back(std::make_pair(Freq, i));
901 std::stable_sort(FreqPairs.begin(), FreqPairs.end());
902 std::reverse(FreqPairs.begin(), FreqPairs.end());
904 outs() << "\tRecord Histogram:\n";
905 outs() << "\t\t Count # Bits b/Rec % Abv Record Kind\n";
906 for (unsigned i = 0, e = FreqPairs.size(); i != e; ++i) {
907 const PerRecordStats &RecStats = Stats.CodeFreq[FreqPairs[i].second];
909 outs() << format("\t\t%7d %9lu",
910 RecStats.NumInstances,
911 (unsigned long)RecStats.TotalBits);
913 if (RecStats.NumInstances > 1)
914 outs() << format(" %9.1f",
915 (double)RecStats.TotalBits/RecStats.NumInstances);
919 if (RecStats.NumAbbrev)
922 (double)RecStats.NumAbbrev/RecStats.NumInstances*100);
927 if (const char *CodeName = GetCodeName(FreqPairs[i].second, I->first,
928 BlockInfo, CurStreamType))
929 outs() << CodeName << "\n";
931 outs() << "UnknownCode" << FreqPairs[i].second << "\n";
941 int main(int argc, char **argv) {
942 // Print a stack trace if we signal out.
943 sys::PrintStackTraceOnErrorSignal(argv[0]);
944 PrettyStackTraceProgram X(argc, argv);
945 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
946 cl::ParseCommandLineOptions(argc, argv, "llvm-bcanalyzer file analyzer\n");
948 return AnalyzeBitcode();