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/Bitcode/BitstreamReader.h"
31 #include "llvm/ADT/Optional.h"
32 #include "llvm/Bitcode/LLVMBitCodes.h"
33 #include "llvm/Bitcode/ReaderWriter.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/MathExtras.h"
39 #include "llvm/Support/MemoryBuffer.h"
40 #include "llvm/Support/PrettyStackTrace.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 BitstreamReader &StreamFile,
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 BitstreamReader::BlockInfo *Info =
98 StreamFile.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::MODULE_BLOCK_ID: return "MODULE_BLOCK";
109 case bitc::PARAMATTR_BLOCK_ID: return "PARAMATTR_BLOCK";
110 case bitc::PARAMATTR_GROUP_BLOCK_ID: return "PARAMATTR_GROUP_BLOCK_ID";
111 case bitc::TYPE_BLOCK_ID_NEW: return "TYPE_BLOCK_ID";
112 case bitc::CONSTANTS_BLOCK_ID: return "CONSTANTS_BLOCK";
113 case bitc::FUNCTION_BLOCK_ID: return "FUNCTION_BLOCK";
114 case bitc::VALUE_SYMTAB_BLOCK_ID: return "VALUE_SYMTAB";
115 case bitc::METADATA_BLOCK_ID: return "METADATA_BLOCK";
116 case bitc::METADATA_ATTACHMENT_ID: return "METADATA_ATTACHMENT_BLOCK";
117 case bitc::USELIST_BLOCK_ID: return "USELIST_BLOCK_ID";
118 case bitc::FUNCTION_SUMMARY_BLOCK_ID:
119 return "FUNCTION_SUMMARY_BLOCK";
120 case bitc::MODULE_STRTAB_BLOCK_ID: return "MODULE_STRTAB_BLOCK";
124 /// GetCodeName - Return a symbolic code name if known, otherwise return
126 static const char *GetCodeName(unsigned CodeID, unsigned BlockID,
127 const BitstreamReader &StreamFile,
128 CurStreamTypeType CurStreamType) {
129 // Standard blocks for all bitcode files.
130 if (BlockID < bitc::FIRST_APPLICATION_BLOCKID) {
131 if (BlockID == bitc::BLOCKINFO_BLOCK_ID) {
133 default: return nullptr;
134 case bitc::BLOCKINFO_CODE_SETBID: return "SETBID";
135 case bitc::BLOCKINFO_CODE_BLOCKNAME: return "BLOCKNAME";
136 case bitc::BLOCKINFO_CODE_SETRECORDNAME: return "SETRECORDNAME";
142 // Check to see if we have a blockinfo record for this record, with a name.
143 if (const BitstreamReader::BlockInfo *Info =
144 StreamFile.getBlockInfo(BlockID)) {
145 for (unsigned i = 0, e = Info->RecordNames.size(); i != e; ++i)
146 if (Info->RecordNames[i].first == CodeID)
147 return Info->RecordNames[i].second.c_str();
151 if (CurStreamType != LLVMIRBitstream) return nullptr;
153 #define STRINGIFY_CODE(PREFIX, CODE) \
154 case bitc::PREFIX##_##CODE: \
157 default: return nullptr;
158 case bitc::MODULE_BLOCK_ID:
160 default: return nullptr;
161 STRINGIFY_CODE(MODULE_CODE, VERSION)
162 STRINGIFY_CODE(MODULE_CODE, TRIPLE)
163 STRINGIFY_CODE(MODULE_CODE, DATALAYOUT)
164 STRINGIFY_CODE(MODULE_CODE, ASM)
165 STRINGIFY_CODE(MODULE_CODE, SECTIONNAME)
166 STRINGIFY_CODE(MODULE_CODE, DEPLIB) // FIXME: Remove in 4.0
167 STRINGIFY_CODE(MODULE_CODE, GLOBALVAR)
168 STRINGIFY_CODE(MODULE_CODE, FUNCTION)
169 STRINGIFY_CODE(MODULE_CODE, ALIAS)
170 STRINGIFY_CODE(MODULE_CODE, PURGEVALS)
171 STRINGIFY_CODE(MODULE_CODE, GCNAME)
172 STRINGIFY_CODE(MODULE_CODE, VSTOFFSET)
174 case bitc::PARAMATTR_BLOCK_ID:
176 default: return nullptr;
177 // FIXME: Should these be different?
178 case bitc::PARAMATTR_CODE_ENTRY_OLD: return "ENTRY";
179 case bitc::PARAMATTR_CODE_ENTRY: return "ENTRY";
180 case bitc::PARAMATTR_GRP_CODE_ENTRY: return "ENTRY";
182 case bitc::TYPE_BLOCK_ID_NEW:
184 default: return nullptr;
185 STRINGIFY_CODE(TYPE_CODE, NUMENTRY)
186 STRINGIFY_CODE(TYPE_CODE, VOID)
187 STRINGIFY_CODE(TYPE_CODE, FLOAT)
188 STRINGIFY_CODE(TYPE_CODE, DOUBLE)
189 STRINGIFY_CODE(TYPE_CODE, LABEL)
190 STRINGIFY_CODE(TYPE_CODE, OPAQUE)
191 STRINGIFY_CODE(TYPE_CODE, INTEGER)
192 STRINGIFY_CODE(TYPE_CODE, POINTER)
193 STRINGIFY_CODE(TYPE_CODE, ARRAY)
194 STRINGIFY_CODE(TYPE_CODE, VECTOR)
195 STRINGIFY_CODE(TYPE_CODE, X86_FP80)
196 STRINGIFY_CODE(TYPE_CODE, FP128)
197 STRINGIFY_CODE(TYPE_CODE, PPC_FP128)
198 STRINGIFY_CODE(TYPE_CODE, METADATA)
199 STRINGIFY_CODE(TYPE_CODE, STRUCT_ANON)
200 STRINGIFY_CODE(TYPE_CODE, STRUCT_NAME)
201 STRINGIFY_CODE(TYPE_CODE, STRUCT_NAMED)
202 STRINGIFY_CODE(TYPE_CODE, FUNCTION)
205 case bitc::CONSTANTS_BLOCK_ID:
207 default: return nullptr;
208 STRINGIFY_CODE(CST_CODE, SETTYPE)
209 STRINGIFY_CODE(CST_CODE, NULL)
210 STRINGIFY_CODE(CST_CODE, UNDEF)
211 STRINGIFY_CODE(CST_CODE, INTEGER)
212 STRINGIFY_CODE(CST_CODE, WIDE_INTEGER)
213 STRINGIFY_CODE(CST_CODE, FLOAT)
214 STRINGIFY_CODE(CST_CODE, AGGREGATE)
215 STRINGIFY_CODE(CST_CODE, STRING)
216 STRINGIFY_CODE(CST_CODE, CSTRING)
217 STRINGIFY_CODE(CST_CODE, CE_BINOP)
218 STRINGIFY_CODE(CST_CODE, CE_CAST)
219 STRINGIFY_CODE(CST_CODE, CE_GEP)
220 STRINGIFY_CODE(CST_CODE, CE_INBOUNDS_GEP)
221 STRINGIFY_CODE(CST_CODE, CE_SELECT)
222 STRINGIFY_CODE(CST_CODE, CE_EXTRACTELT)
223 STRINGIFY_CODE(CST_CODE, CE_INSERTELT)
224 STRINGIFY_CODE(CST_CODE, CE_SHUFFLEVEC)
225 STRINGIFY_CODE(CST_CODE, CE_CMP)
226 STRINGIFY_CODE(CST_CODE, INLINEASM)
227 STRINGIFY_CODE(CST_CODE, CE_SHUFVEC_EX)
228 case bitc::CST_CODE_BLOCKADDRESS: return "CST_CODE_BLOCKADDRESS";
229 STRINGIFY_CODE(CST_CODE, DATA)
231 case bitc::FUNCTION_BLOCK_ID:
233 default: return nullptr;
234 STRINGIFY_CODE(FUNC_CODE, DECLAREBLOCKS)
235 STRINGIFY_CODE(FUNC_CODE, INST_BINOP)
236 STRINGIFY_CODE(FUNC_CODE, INST_CAST)
237 STRINGIFY_CODE(FUNC_CODE, INST_GEP_OLD)
238 STRINGIFY_CODE(FUNC_CODE, INST_INBOUNDS_GEP_OLD)
239 STRINGIFY_CODE(FUNC_CODE, INST_SELECT)
240 STRINGIFY_CODE(FUNC_CODE, INST_EXTRACTELT)
241 STRINGIFY_CODE(FUNC_CODE, INST_INSERTELT)
242 STRINGIFY_CODE(FUNC_CODE, INST_SHUFFLEVEC)
243 STRINGIFY_CODE(FUNC_CODE, INST_CMP)
244 STRINGIFY_CODE(FUNC_CODE, INST_RET)
245 STRINGIFY_CODE(FUNC_CODE, INST_BR)
246 STRINGIFY_CODE(FUNC_CODE, INST_SWITCH)
247 STRINGIFY_CODE(FUNC_CODE, INST_INVOKE)
248 STRINGIFY_CODE(FUNC_CODE, INST_UNREACHABLE)
249 STRINGIFY_CODE(FUNC_CODE, INST_CLEANUPRET)
250 STRINGIFY_CODE(FUNC_CODE, INST_CATCHRET)
251 STRINGIFY_CODE(FUNC_CODE, INST_CATCHPAD)
252 STRINGIFY_CODE(FUNC_CODE, INST_CLEANUPENDPAD)
253 STRINGIFY_CODE(FUNC_CODE, INST_CATCHENDPAD)
254 STRINGIFY_CODE(FUNC_CODE, INST_TERMINATEPAD)
255 STRINGIFY_CODE(FUNC_CODE, INST_PHI)
256 STRINGIFY_CODE(FUNC_CODE, INST_ALLOCA)
257 STRINGIFY_CODE(FUNC_CODE, INST_LOAD)
258 STRINGIFY_CODE(FUNC_CODE, INST_VAARG)
259 STRINGIFY_CODE(FUNC_CODE, INST_STORE)
260 STRINGIFY_CODE(FUNC_CODE, INST_EXTRACTVAL)
261 STRINGIFY_CODE(FUNC_CODE, INST_INSERTVAL)
262 STRINGIFY_CODE(FUNC_CODE, INST_CMP2)
263 STRINGIFY_CODE(FUNC_CODE, INST_VSELECT)
264 STRINGIFY_CODE(FUNC_CODE, DEBUG_LOC_AGAIN)
265 STRINGIFY_CODE(FUNC_CODE, INST_CALL)
266 STRINGIFY_CODE(FUNC_CODE, DEBUG_LOC)
267 STRINGIFY_CODE(FUNC_CODE, INST_GEP)
269 case bitc::VALUE_SYMTAB_BLOCK_ID:
271 default: return nullptr;
272 STRINGIFY_CODE(VST_CODE, ENTRY)
273 STRINGIFY_CODE(VST_CODE, BBENTRY)
274 STRINGIFY_CODE(VST_CODE, FNENTRY)
275 STRINGIFY_CODE(VST_CODE, COMBINED_FNENTRY)
277 case bitc::MODULE_STRTAB_BLOCK_ID:
279 default: return nullptr;
280 STRINGIFY_CODE(MST_CODE, ENTRY)
282 case bitc::FUNCTION_SUMMARY_BLOCK_ID:
284 default: return nullptr;
285 STRINGIFY_CODE(FS_CODE, PERMODULE_ENTRY)
286 STRINGIFY_CODE(FS_CODE, COMBINED_ENTRY)
288 case bitc::METADATA_ATTACHMENT_ID:
290 default:return nullptr;
291 STRINGIFY_CODE(METADATA, ATTACHMENT)
293 case bitc::METADATA_BLOCK_ID:
295 default:return nullptr;
296 STRINGIFY_CODE(METADATA, STRING)
297 STRINGIFY_CODE(METADATA, NAME)
298 STRINGIFY_CODE(METADATA, KIND)
299 STRINGIFY_CODE(METADATA, NODE)
300 STRINGIFY_CODE(METADATA, VALUE)
301 STRINGIFY_CODE(METADATA, OLD_NODE)
302 STRINGIFY_CODE(METADATA, OLD_FN_NODE)
303 STRINGIFY_CODE(METADATA, NAMED_NODE)
304 STRINGIFY_CODE(METADATA, DISTINCT_NODE)
305 STRINGIFY_CODE(METADATA, LOCATION)
306 STRINGIFY_CODE(METADATA, GENERIC_DEBUG)
307 STRINGIFY_CODE(METADATA, SUBRANGE)
308 STRINGIFY_CODE(METADATA, ENUMERATOR)
309 STRINGIFY_CODE(METADATA, BASIC_TYPE)
310 STRINGIFY_CODE(METADATA, FILE)
311 STRINGIFY_CODE(METADATA, DERIVED_TYPE)
312 STRINGIFY_CODE(METADATA, COMPOSITE_TYPE)
313 STRINGIFY_CODE(METADATA, SUBROUTINE_TYPE)
314 STRINGIFY_CODE(METADATA, COMPILE_UNIT)
315 STRINGIFY_CODE(METADATA, SUBPROGRAM)
316 STRINGIFY_CODE(METADATA, LEXICAL_BLOCK)
317 STRINGIFY_CODE(METADATA, LEXICAL_BLOCK_FILE)
318 STRINGIFY_CODE(METADATA, NAMESPACE)
319 STRINGIFY_CODE(METADATA, TEMPLATE_TYPE)
320 STRINGIFY_CODE(METADATA, TEMPLATE_VALUE)
321 STRINGIFY_CODE(METADATA, GLOBAL_VAR)
322 STRINGIFY_CODE(METADATA, LOCAL_VAR)
323 STRINGIFY_CODE(METADATA, EXPRESSION)
324 STRINGIFY_CODE(METADATA, OBJC_PROPERTY)
325 STRINGIFY_CODE(METADATA, IMPORTED_ENTITY)
326 STRINGIFY_CODE(METADATA, MODULE)
328 case bitc::USELIST_BLOCK_ID:
330 default:return nullptr;
331 case bitc::USELIST_CODE_DEFAULT: return "USELIST_CODE_DEFAULT";
332 case bitc::USELIST_CODE_BB: return "USELIST_CODE_BB";
335 #undef STRINGIFY_CODE
338 struct PerRecordStats {
339 /// The number of times this record code has been seen.
340 unsigned NumInstances;
341 /// The number of times this record code has been seen abbreviated.
343 /// The total number of bits used for this record on disk.
345 /// The number of bits that would have been used if no abbrevs were used.
346 uint64_t UnabbrevBits;
347 /// The number of bits that would be used if "good" abbreviations were used.
348 uint64_t GoodAbbrevBits;
351 : NumInstances(0), NumAbbrev(0), TotalBits(0), UnabbrevBits(0),
355 struct PerBlockIDStats {
356 /// NumInstances - This the number of times this block ID has been seen.
357 unsigned NumInstances;
359 /// NumBits - The total size in bits of all of these blocks.
362 /// NumSubBlocks - The total number of blocks these blocks contain.
363 unsigned NumSubBlocks;
365 /// NumAbbrevs - The total number of abbreviations.
368 /// NumRecords - The total number of records these blocks contain, and the
369 /// number that are abbreviated.
370 unsigned NumRecords, NumAbbreviatedRecords;
372 /// CodeFreq - Keep track of the number of times we see each code.
373 std::vector<PerRecordStats> CodeFreq;
376 : NumInstances(0), NumBits(0),
377 NumSubBlocks(0), NumAbbrevs(0), NumRecords(0), NumAbbreviatedRecords(0) {}
380 static std::map<unsigned, PerBlockIDStats> BlockIDStats;
384 /// Error - All bitcode analysis errors go through this function, making this a
385 /// good place to breakpoint if debugging.
386 static bool Error(const Twine &Err) {
387 errs() << Err << "\n";
391 static unsigned computeVBR6Bits(uint64_t Val) {
399 static void addBlobSize(uint64_t &Bits, StringRef Blob) {
400 // Blob size is always VBR6.
401 Bits += computeVBR6Bits(Blob.size());
403 // Blob is always 32-bit aligned, and padded to a multiple of 32 bits.
404 RoundUpToAlignment(Bits, 32);
405 Bits += Blob.size() * 8;
406 RoundUpToAlignment(Bits, 32);
409 /// \brief Compute the number of bits that would be used by the record if it
410 /// were unabbreviated.
411 static uint64_t computeUnabbrevBits(unsigned AbbrevIDWidth, unsigned Code,
412 ArrayRef<uint64_t> Record, StringRef Blob) {
414 AbbrevIDWidth + computeVBR6Bits(Code) + computeVBR6Bits(Record.size());
415 // Use VBR6 for all fields.
416 for (uint64_t Val : Record)
417 Bits += computeVBR6Bits(Val);
418 // Assume Blob representation for the blob, even though a Blob cannot
421 addBlobSize(Bits, Blob);
425 /// \brief Compute the number of bits that would be used by the record if a
426 /// "good" abbreviation were used. We use an extremely simple heuristic for
427 /// "good"ness: pick the best abbrev that uses a Literal for the record code,
428 /// a normal Blob field for the blob (if present), and a minimal-width Fixed
429 /// field for everything else.
430 static uint64_t computeGoodAbbrevBits(unsigned AbbrevIDWidth, unsigned Code,
431 ArrayRef<uint64_t> Record,
433 uint64_t Bits = AbbrevIDWidth;
434 // Use Fixed for all fields (other than the record code).
435 for (uint64_t Val : Record)
436 Bits += 64 - llvm::countLeadingZeros(Val);
437 // Assume Blob representation for the blob.
439 addBlobSize(Bits, Blob);
443 /// ParseBlock - Read a block, updating statistics, etc.
444 static bool ParseBlock(BitstreamCursor &Stream, unsigned BlockID,
445 unsigned IndentLevel, CurStreamTypeType CurStreamType) {
446 std::string Indent(IndentLevel*2, ' ');
447 uint64_t BlockBitStart = Stream.GetCurrentBitNo();
449 // Get the statistics for this BlockID.
450 PerBlockIDStats &BlockStats = BlockIDStats[BlockID];
452 BlockStats.NumInstances++;
454 // BLOCKINFO is a special part of the stream.
455 if (BlockID == bitc::BLOCKINFO_BLOCK_ID) {
456 if (Dump) outs() << Indent << "<BLOCKINFO_BLOCK/>\n";
457 if (Stream.ReadBlockInfoBlock())
458 return Error("Malformed BlockInfoBlock");
459 uint64_t BlockBitEnd = Stream.GetCurrentBitNo();
460 BlockStats.NumBits += BlockBitEnd-BlockBitStart;
464 unsigned NumWords = 0;
465 if (Stream.EnterSubBlock(BlockID, &NumWords))
466 return Error("Malformed block record");
468 const char *BlockName = nullptr;
470 outs() << Indent << "<";
471 if ((BlockName = GetBlockName(BlockID, *Stream.getBitStreamReader(),
475 outs() << "UnknownBlock" << BlockID;
477 if (NonSymbolic && BlockName)
478 outs() << " BlockID=" << BlockID;
480 outs() << " NumWords=" << NumWords
481 << " BlockCodeSize=" << Stream.getAbbrevIDWidth() << ">\n";
484 SmallVector<uint64_t, 64> Record;
486 // Read all the records for this block.
488 if (Stream.AtEndOfStream())
489 return Error("Premature end of bitstream");
491 uint64_t RecordStartBit = Stream.GetCurrentBitNo();
493 BitstreamEntry Entry =
494 Stream.advance(BitstreamCursor::AF_DontAutoprocessAbbrevs);
496 switch (Entry.Kind) {
497 case BitstreamEntry::Error:
498 return Error("malformed bitcode file");
499 case BitstreamEntry::EndBlock: {
500 uint64_t BlockBitEnd = Stream.GetCurrentBitNo();
501 BlockStats.NumBits += BlockBitEnd-BlockBitStart;
503 outs() << Indent << "</";
505 outs() << BlockName << ">\n";
507 outs() << "UnknownBlock" << BlockID << ">\n";
512 case BitstreamEntry::SubBlock: {
513 uint64_t SubBlockBitStart = Stream.GetCurrentBitNo();
514 if (ParseBlock(Stream, Entry.ID, IndentLevel+1, CurStreamType))
516 ++BlockStats.NumSubBlocks;
517 uint64_t SubBlockBitEnd = Stream.GetCurrentBitNo();
519 // Don't include subblock sizes in the size of this block.
520 BlockBitStart += SubBlockBitEnd-SubBlockBitStart;
523 case BitstreamEntry::Record:
524 // The interesting case.
528 if (Entry.ID == bitc::DEFINE_ABBREV) {
529 Stream.ReadAbbrevRecord();
530 ++BlockStats.NumAbbrevs;
536 ++BlockStats.NumRecords;
539 unsigned Code = Stream.readRecord(Entry.ID, Record, &Blob);
541 // Increment the # occurrences of this code.
542 if (BlockStats.CodeFreq.size() <= Code)
543 BlockStats.CodeFreq.resize(Code+1);
544 BlockStats.CodeFreq[Code].NumInstances++;
545 BlockStats.CodeFreq[Code].TotalBits +=
546 Stream.GetCurrentBitNo()-RecordStartBit;
547 BlockStats.CodeFreq[Code].UnabbrevBits +=
548 computeUnabbrevBits(Stream.getAbbrevIDWidth(), Code, Record, Blob);
549 BlockStats.CodeFreq[Code].GoodAbbrevBits +=
550 computeGoodAbbrevBits(Stream.getAbbrevIDWidth(), Code, Record, Blob);
551 if (Entry.ID != bitc::UNABBREV_RECORD) {
552 BlockStats.CodeFreq[Code].NumAbbrev++;
553 ++BlockStats.NumAbbreviatedRecords;
557 outs() << Indent << " <";
558 if (const char *CodeName =
559 GetCodeName(Code, BlockID, *Stream.getBitStreamReader(),
563 outs() << "UnknownCode" << Code;
565 GetCodeName(Code, BlockID, *Stream.getBitStreamReader(),
567 outs() << " codeid=" << Code;
568 const BitCodeAbbrev *Abbv = nullptr;
569 if (Entry.ID != bitc::UNABBREV_RECORD) {
570 Abbv = Stream.getAbbrev(Entry.ID);
571 outs() << " abbrevid=" << Entry.ID;
574 for (unsigned i = 0, e = Record.size(); i != e; ++i)
575 outs() << " op" << i << "=" << (int64_t)Record[i];
580 for (unsigned i = 1, e = Abbv->getNumOperandInfos(); i != e; ++i) {
581 const BitCodeAbbrevOp &Op = Abbv->getOperandInfo(i);
582 if (!Op.isEncoding() || Op.getEncoding() != BitCodeAbbrevOp::Array)
584 assert(i + 2 == e && "Array op not second to last");
586 bool ArrayIsPrintable = true;
587 for (unsigned j = i - 1, je = Record.size(); j != je; ++j) {
588 if (!isprint(static_cast<unsigned char>(Record[j]))) {
589 ArrayIsPrintable = false;
592 Str += (char)Record[j];
594 if (ArrayIsPrintable) outs() << " record string = '" << Str << "'";
600 outs() << " blob data = ";
601 if (ShowBinaryBlobs) {
603 outs().write_escaped(Blob, /*hex=*/true) << "'";
605 bool BlobIsPrintable = true;
606 for (unsigned i = 0, e = Blob.size(); i != e; ++i)
607 if (!isprint(static_cast<unsigned char>(Blob[i]))) {
608 BlobIsPrintable = false;
613 outs() << "'" << Blob << "'";
615 outs() << "unprintable, " << Blob.size() << " bytes.";
624 static void PrintSize(double Bits) {
625 outs() << format("%.2f/%.2fB/%luW", Bits, Bits/8,(unsigned long)(Bits/32));
627 static void PrintSize(uint64_t Bits) {
628 outs() << format("%lub/%.2fB/%luW", (unsigned long)Bits,
629 (double)Bits/8, (unsigned long)(Bits/32));
632 static bool openBitcodeFile(StringRef Path,
633 std::unique_ptr<MemoryBuffer> &MemBuf,
634 BitstreamReader &StreamFile,
635 BitstreamCursor &Stream,
636 CurStreamTypeType &CurStreamType) {
637 // Read the input file.
638 ErrorOr<std::unique_ptr<MemoryBuffer>> MemBufOrErr =
639 MemoryBuffer::getFileOrSTDIN(Path);
640 if (std::error_code EC = MemBufOrErr.getError())
641 return Error(Twine("Error reading '") + Path + "': " + EC.message());
642 MemBuf = std::move(MemBufOrErr.get());
644 if (MemBuf->getBufferSize() & 3)
645 return Error("Bitcode stream should be a multiple of 4 bytes in length");
647 const unsigned char *BufPtr = (const unsigned char *)MemBuf->getBufferStart();
648 const unsigned char *EndBufPtr = BufPtr + MemBuf->getBufferSize();
650 // If we have a wrapper header, parse it and ignore the non-bc file contents.
651 // The magic number is 0x0B17C0DE stored in little endian.
652 if (isBitcodeWrapper(BufPtr, EndBufPtr))
653 if (SkipBitcodeWrapperHeader(BufPtr, EndBufPtr, true))
654 return Error("Invalid bitcode wrapper header");
656 StreamFile = BitstreamReader(BufPtr, EndBufPtr);
657 Stream = BitstreamCursor(StreamFile);
658 StreamFile.CollectBlockInfoNames();
660 // Read the stream signature.
662 Signature[0] = Stream.Read(8);
663 Signature[1] = Stream.Read(8);
664 Signature[2] = Stream.Read(4);
665 Signature[3] = Stream.Read(4);
666 Signature[4] = Stream.Read(4);
667 Signature[5] = Stream.Read(4);
669 // Autodetect the file contents, if it is one we know.
670 CurStreamType = UnknownBitstream;
671 if (Signature[0] == 'B' && Signature[1] == 'C' &&
672 Signature[2] == 0x0 && Signature[3] == 0xC &&
673 Signature[4] == 0xE && Signature[5] == 0xD)
674 CurStreamType = LLVMIRBitstream;
679 /// AnalyzeBitcode - Analyze the bitcode file specified by InputFilename.
680 static int AnalyzeBitcode() {
681 std::unique_ptr<MemoryBuffer> StreamBuffer;
682 BitstreamReader StreamFile;
683 BitstreamCursor Stream;
684 CurStreamTypeType CurStreamType;
685 if (openBitcodeFile(InputFilename, StreamBuffer, StreamFile, Stream,
689 // Read block info from BlockInfoFilename, if specified.
690 // The block info must be a top-level block.
691 if (!BlockInfoFilename.empty()) {
692 std::unique_ptr<MemoryBuffer> BlockInfoBuffer;
693 BitstreamReader BlockInfoFile;
694 BitstreamCursor BlockInfoCursor;
695 CurStreamTypeType BlockInfoStreamType;
696 if (openBitcodeFile(BlockInfoFilename, BlockInfoBuffer, BlockInfoFile,
697 BlockInfoCursor, BlockInfoStreamType))
700 while (!BlockInfoCursor.AtEndOfStream()) {
701 unsigned Code = BlockInfoCursor.ReadCode();
702 if (Code != bitc::ENTER_SUBBLOCK)
703 return Error("Invalid record at top-level in block info file");
705 unsigned BlockID = BlockInfoCursor.ReadSubBlockID();
706 if (BlockID == bitc::BLOCKINFO_BLOCK_ID) {
707 if (BlockInfoCursor.ReadBlockInfoBlock())
708 return Error("Malformed BlockInfoBlock in block info file");
712 BlockInfoCursor.SkipBlock();
715 StreamFile.takeBlockInfo(std::move(BlockInfoFile));
718 unsigned NumTopBlocks = 0;
720 // Parse the top-level structure. We only allow blocks at the top-level.
721 while (!Stream.AtEndOfStream()) {
722 unsigned Code = Stream.ReadCode();
723 if (Code != bitc::ENTER_SUBBLOCK)
724 return Error("Invalid record at top-level");
726 unsigned BlockID = Stream.ReadSubBlockID();
728 if (ParseBlock(Stream, BlockID, 0, CurStreamType))
733 if (Dump) outs() << "\n\n";
735 uint64_t BufferSizeBits = StreamFile.getBitcodeBytes().getExtent() * CHAR_BIT;
736 // Print a summary of the read file.
737 outs() << "Summary of " << InputFilename << ":\n";
738 outs() << " Total size: ";
739 PrintSize(BufferSizeBits);
741 outs() << " Stream type: ";
742 switch (CurStreamType) {
743 case UnknownBitstream: outs() << "unknown\n"; break;
744 case LLVMIRBitstream: outs() << "LLVM IR\n"; break;
746 outs() << " # Toplevel Blocks: " << NumTopBlocks << "\n";
749 // Emit per-block stats.
750 outs() << "Per-block Summary:\n";
751 for (std::map<unsigned, PerBlockIDStats>::iterator I = BlockIDStats.begin(),
752 E = BlockIDStats.end(); I != E; ++I) {
753 outs() << " Block ID #" << I->first;
754 if (const char *BlockName = GetBlockName(I->first, StreamFile,
756 outs() << " (" << BlockName << ")";
759 const PerBlockIDStats &Stats = I->second;
760 outs() << " Num Instances: " << Stats.NumInstances << "\n";
761 outs() << " Total Size: ";
762 PrintSize(Stats.NumBits);
764 double pct = (Stats.NumBits * 100.0) / BufferSizeBits;
765 outs() << " Percent of file: " << format("%2.4f%%", pct) << "\n";
766 if (Stats.NumInstances > 1) {
767 outs() << " Average Size: ";
768 PrintSize(Stats.NumBits/(double)Stats.NumInstances);
770 outs() << " Tot/Avg SubBlocks: " << Stats.NumSubBlocks << "/"
771 << Stats.NumSubBlocks/(double)Stats.NumInstances << "\n";
772 outs() << " Tot/Avg Abbrevs: " << Stats.NumAbbrevs << "/"
773 << Stats.NumAbbrevs/(double)Stats.NumInstances << "\n";
774 outs() << " Tot/Avg Records: " << Stats.NumRecords << "/"
775 << Stats.NumRecords/(double)Stats.NumInstances << "\n";
777 outs() << " Num SubBlocks: " << Stats.NumSubBlocks << "\n";
778 outs() << " Num Abbrevs: " << Stats.NumAbbrevs << "\n";
779 outs() << " Num Records: " << Stats.NumRecords << "\n";
781 if (Stats.NumRecords) {
782 double pct = (Stats.NumAbbreviatedRecords * 100.0) / Stats.NumRecords;
783 outs() << " Percent Abbrevs: " << format("%2.4f%%", pct) << "\n";
787 // Print a histogram of the codes we see.
788 if (!NoHistogram && !Stats.CodeFreq.empty()) {
789 std::vector<std::pair<uint64_t, unsigned> > FreqPairs; // <bits,code>
790 for (unsigned i = 0, e = Stats.CodeFreq.size(); i != e; ++i)
791 if (unsigned Freq = Stats.CodeFreq[i].TotalBits)
792 FreqPairs.push_back(std::make_pair(Freq, i));
793 std::stable_sort(FreqPairs.begin(), FreqPairs.end());
794 std::reverse(FreqPairs.begin(), FreqPairs.end());
796 outs() << "\tRecord Histogram:\n";
797 outs() << "\t\t Count # Bits % Abv % Cmp (cur/best) Record Kind\n";
798 for (unsigned i = 0, e = FreqPairs.size(); i != e; ++i) {
799 const PerRecordStats &RecStats = Stats.CodeFreq[FreqPairs[i].second];
801 outs() << format("\t\t%7d %9lu ",
802 RecStats.NumInstances,
803 (unsigned long)RecStats.TotalBits);
805 if (RecStats.NumAbbrev)
808 (double)RecStats.NumAbbrev/RecStats.NumInstances*100);
812 if (RecStats.UnabbrevBits)
815 (double)RecStats.TotalBits / RecStats.UnabbrevBits * 100,
816 (double)RecStats.GoodAbbrevBits / RecStats.UnabbrevBits * 100);
820 if (const char *CodeName =
821 GetCodeName(FreqPairs[i].second, I->first, StreamFile,
823 outs() << CodeName << "\n";
825 outs() << "UnknownCode" << FreqPairs[i].second << "\n";
835 int main(int argc, char **argv) {
836 // Print a stack trace if we signal out.
837 sys::PrintStackTraceOnErrorSignal();
838 PrettyStackTraceProgram X(argc, argv);
839 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
840 cl::ParseCommandLineOptions(argc, argv, "llvm-bcanalyzer file analyzer\n");
842 return AnalyzeBitcode();