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/MemoryBuffer.h"
39 #include "llvm/Support/PrettyStackTrace.h"
40 #include "llvm/Support/Signals.h"
41 #include "llvm/Support/raw_ostream.h"
45 #include <system_error>
48 static cl::opt<std::string>
49 InputFilename(cl::Positional, cl::desc("<input bitcode>"), cl::init("-"));
51 static cl::opt<bool> Dump("dump", cl::desc("Dump low level bitcode trace"));
53 //===----------------------------------------------------------------------===//
54 // Bitcode specific analysis.
55 //===----------------------------------------------------------------------===//
57 static cl::opt<bool> NoHistogram("disable-histogram",
58 cl::desc("Do not print per-code histogram"));
61 NonSymbolic("non-symbolic",
62 cl::desc("Emit numeric info in dump even if"
63 " symbolic info is available"));
65 static cl::opt<std::string>
66 BlockInfoFilename("block-info",
67 cl::desc("Use the BLOCK_INFO from the given file"));
70 ShowBinaryBlobs("show-binary-blobs",
71 cl::desc("Print binary blobs using hex escapes"));
75 /// CurStreamTypeType - A type for CurStreamType
76 enum CurStreamTypeType {
83 /// GetBlockName - Return a symbolic block name if known, otherwise return
85 static const char *GetBlockName(unsigned BlockID,
86 const BitstreamReader &StreamFile,
87 CurStreamTypeType CurStreamType) {
88 // Standard blocks for all bitcode files.
89 if (BlockID < bitc::FIRST_APPLICATION_BLOCKID) {
90 if (BlockID == bitc::BLOCKINFO_BLOCK_ID)
91 return "BLOCKINFO_BLOCK";
95 // Check to see if we have a blockinfo record for this block, with a name.
96 if (const BitstreamReader::BlockInfo *Info =
97 StreamFile.getBlockInfo(BlockID)) {
98 if (!Info->Name.empty())
99 return Info->Name.c_str();
103 if (CurStreamType != LLVMIRBitstream) return nullptr;
106 default: return nullptr;
107 case bitc::MODULE_BLOCK_ID: return "MODULE_BLOCK";
108 case bitc::PARAMATTR_BLOCK_ID: return "PARAMATTR_BLOCK";
109 case bitc::PARAMATTR_GROUP_BLOCK_ID: return "PARAMATTR_GROUP_BLOCK_ID";
110 case bitc::TYPE_BLOCK_ID_NEW: return "TYPE_BLOCK_ID";
111 case bitc::CONSTANTS_BLOCK_ID: return "CONSTANTS_BLOCK";
112 case bitc::FUNCTION_BLOCK_ID: return "FUNCTION_BLOCK";
113 case bitc::VALUE_SYMTAB_BLOCK_ID: return "VALUE_SYMTAB";
114 case bitc::METADATA_BLOCK_ID: return "METADATA_BLOCK";
115 case bitc::METADATA_ATTACHMENT_ID: return "METADATA_ATTACHMENT_BLOCK";
116 case bitc::USELIST_BLOCK_ID: return "USELIST_BLOCK_ID";
120 /// GetCodeName - Return a symbolic code name if known, otherwise return
122 static const char *GetCodeName(unsigned CodeID, unsigned BlockID,
123 const BitstreamReader &StreamFile,
124 CurStreamTypeType CurStreamType) {
125 // Standard blocks for all bitcode files.
126 if (BlockID < bitc::FIRST_APPLICATION_BLOCKID) {
127 if (BlockID == bitc::BLOCKINFO_BLOCK_ID) {
129 default: return nullptr;
130 case bitc::BLOCKINFO_CODE_SETBID: return "SETBID";
131 case bitc::BLOCKINFO_CODE_BLOCKNAME: return "BLOCKNAME";
132 case bitc::BLOCKINFO_CODE_SETRECORDNAME: return "SETRECORDNAME";
138 // Check to see if we have a blockinfo record for this record, with a name.
139 if (const BitstreamReader::BlockInfo *Info =
140 StreamFile.getBlockInfo(BlockID)) {
141 for (unsigned i = 0, e = Info->RecordNames.size(); i != e; ++i)
142 if (Info->RecordNames[i].first == CodeID)
143 return Info->RecordNames[i].second.c_str();
147 if (CurStreamType != LLVMIRBitstream) return nullptr;
149 #define STRINGIFY_CODE(PREFIX, CODE) \
150 case bitc::PREFIX##_##CODE: \
153 default: return nullptr;
154 case bitc::MODULE_BLOCK_ID:
156 default: return nullptr;
157 STRINGIFY_CODE(MODULE_CODE, VERSION)
158 STRINGIFY_CODE(MODULE_CODE, TRIPLE)
159 STRINGIFY_CODE(MODULE_CODE, DATALAYOUT)
160 STRINGIFY_CODE(MODULE_CODE, ASM)
161 STRINGIFY_CODE(MODULE_CODE, SECTIONNAME)
162 STRINGIFY_CODE(MODULE_CODE, DEPLIB) // FIXME: Remove in 4.0
163 STRINGIFY_CODE(MODULE_CODE, GLOBALVAR)
164 STRINGIFY_CODE(MODULE_CODE, FUNCTION)
165 STRINGIFY_CODE(MODULE_CODE, ALIAS)
166 STRINGIFY_CODE(MODULE_CODE, PURGEVALS)
167 STRINGIFY_CODE(MODULE_CODE, GCNAME)
169 case bitc::PARAMATTR_BLOCK_ID:
171 default: return nullptr;
172 // FIXME: Should these be different?
173 case bitc::PARAMATTR_CODE_ENTRY_OLD: return "ENTRY";
174 case bitc::PARAMATTR_CODE_ENTRY: return "ENTRY";
175 case bitc::PARAMATTR_GRP_CODE_ENTRY: return "ENTRY";
177 case bitc::TYPE_BLOCK_ID_NEW:
179 default: return nullptr;
180 STRINGIFY_CODE(TYPE_CODE, NUMENTRY)
181 STRINGIFY_CODE(TYPE_CODE, VOID)
182 STRINGIFY_CODE(TYPE_CODE, FLOAT)
183 STRINGIFY_CODE(TYPE_CODE, DOUBLE)
184 STRINGIFY_CODE(TYPE_CODE, LABEL)
185 STRINGIFY_CODE(TYPE_CODE, OPAQUE)
186 STRINGIFY_CODE(TYPE_CODE, INTEGER)
187 STRINGIFY_CODE(TYPE_CODE, POINTER)
188 STRINGIFY_CODE(TYPE_CODE, ARRAY)
189 STRINGIFY_CODE(TYPE_CODE, VECTOR)
190 STRINGIFY_CODE(TYPE_CODE, X86_FP80)
191 STRINGIFY_CODE(TYPE_CODE, FP128)
192 STRINGIFY_CODE(TYPE_CODE, PPC_FP128)
193 STRINGIFY_CODE(TYPE_CODE, METADATA)
194 STRINGIFY_CODE(TYPE_CODE, STRUCT_ANON)
195 STRINGIFY_CODE(TYPE_CODE, STRUCT_NAME)
196 STRINGIFY_CODE(TYPE_CODE, STRUCT_NAMED)
197 STRINGIFY_CODE(TYPE_CODE, FUNCTION)
200 case bitc::CONSTANTS_BLOCK_ID:
202 default: return nullptr;
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 case bitc::CST_CODE_BLOCKADDRESS: return "CST_CODE_BLOCKADDRESS";
224 STRINGIFY_CODE(CST_CODE, DATA)
226 case bitc::FUNCTION_BLOCK_ID:
228 default: return nullptr;
229 STRINGIFY_CODE(FUNC_CODE, DECLAREBLOCKS)
230 STRINGIFY_CODE(FUNC_CODE, INST_BINOP)
231 STRINGIFY_CODE(FUNC_CODE, INST_CAST)
232 STRINGIFY_CODE(FUNC_CODE, INST_GEP_OLD)
233 STRINGIFY_CODE(FUNC_CODE, INST_INBOUNDS_GEP_OLD)
234 STRINGIFY_CODE(FUNC_CODE, INST_SELECT)
235 STRINGIFY_CODE(FUNC_CODE, INST_EXTRACTELT)
236 STRINGIFY_CODE(FUNC_CODE, INST_INSERTELT)
237 STRINGIFY_CODE(FUNC_CODE, INST_SHUFFLEVEC)
238 STRINGIFY_CODE(FUNC_CODE, INST_CMP)
239 STRINGIFY_CODE(FUNC_CODE, INST_RET)
240 STRINGIFY_CODE(FUNC_CODE, INST_BR)
241 STRINGIFY_CODE(FUNC_CODE, INST_SWITCH)
242 STRINGIFY_CODE(FUNC_CODE, INST_INVOKE)
243 STRINGIFY_CODE(FUNC_CODE, INST_UNREACHABLE)
244 STRINGIFY_CODE(FUNC_CODE, INST_PHI)
245 STRINGIFY_CODE(FUNC_CODE, INST_ALLOCA)
246 STRINGIFY_CODE(FUNC_CODE, INST_LOAD)
247 STRINGIFY_CODE(FUNC_CODE, INST_VAARG)
248 STRINGIFY_CODE(FUNC_CODE, INST_STORE)
249 STRINGIFY_CODE(FUNC_CODE, INST_EXTRACTVAL)
250 STRINGIFY_CODE(FUNC_CODE, INST_INSERTVAL)
251 STRINGIFY_CODE(FUNC_CODE, INST_CMP2)
252 STRINGIFY_CODE(FUNC_CODE, INST_VSELECT)
253 STRINGIFY_CODE(FUNC_CODE, DEBUG_LOC_AGAIN)
254 STRINGIFY_CODE(FUNC_CODE, INST_CALL)
255 STRINGIFY_CODE(FUNC_CODE, DEBUG_LOC)
256 STRINGIFY_CODE(FUNC_CODE, INST_GEP)
258 case bitc::VALUE_SYMTAB_BLOCK_ID:
260 default: return nullptr;
261 STRINGIFY_CODE(VST_CODE, ENTRY)
262 STRINGIFY_CODE(VST_CODE, BBENTRY)
264 case bitc::METADATA_ATTACHMENT_ID:
266 default:return nullptr;
267 STRINGIFY_CODE(METADATA, ATTACHMENT)
269 case bitc::METADATA_BLOCK_ID:
271 default:return nullptr;
272 STRINGIFY_CODE(METADATA, STRING)
273 STRINGIFY_CODE(METADATA, NAME)
274 STRINGIFY_CODE(METADATA, KIND)
275 STRINGIFY_CODE(METADATA, NODE)
276 STRINGIFY_CODE(METADATA, VALUE)
277 STRINGIFY_CODE(METADATA, OLD_NODE)
278 STRINGIFY_CODE(METADATA, OLD_FN_NODE)
279 STRINGIFY_CODE(METADATA, NAMED_NODE)
280 STRINGIFY_CODE(METADATA, DISTINCT_NODE)
281 STRINGIFY_CODE(METADATA, LOCATION)
282 STRINGIFY_CODE(METADATA, GENERIC_DEBUG)
283 STRINGIFY_CODE(METADATA, SUBRANGE)
284 STRINGIFY_CODE(METADATA, ENUMERATOR)
285 STRINGIFY_CODE(METADATA, BASIC_TYPE)
286 STRINGIFY_CODE(METADATA, FILE)
287 STRINGIFY_CODE(METADATA, DERIVED_TYPE)
288 STRINGIFY_CODE(METADATA, COMPOSITE_TYPE)
289 STRINGIFY_CODE(METADATA, SUBROUTINE_TYPE)
290 STRINGIFY_CODE(METADATA, COMPILE_UNIT)
291 STRINGIFY_CODE(METADATA, SUBPROGRAM)
292 STRINGIFY_CODE(METADATA, LEXICAL_BLOCK)
293 STRINGIFY_CODE(METADATA, LEXICAL_BLOCK_FILE)
294 STRINGIFY_CODE(METADATA, NAMESPACE)
295 STRINGIFY_CODE(METADATA, TEMPLATE_TYPE)
296 STRINGIFY_CODE(METADATA, TEMPLATE_VALUE)
297 STRINGIFY_CODE(METADATA, GLOBAL_VAR)
298 STRINGIFY_CODE(METADATA, LOCAL_VAR)
299 STRINGIFY_CODE(METADATA, EXPRESSION)
300 STRINGIFY_CODE(METADATA, OBJC_PROPERTY)
301 STRINGIFY_CODE(METADATA, IMPORTED_ENTITY)
303 case bitc::USELIST_BLOCK_ID:
305 default:return nullptr;
306 case bitc::USELIST_CODE_DEFAULT: return "USELIST_CODE_DEFAULT";
307 case bitc::USELIST_CODE_BB: return "USELIST_CODE_BB";
310 #undef STRINGIFY_CODE
313 struct PerRecordStats {
314 unsigned NumInstances;
318 PerRecordStats() : NumInstances(0), NumAbbrev(0), TotalBits(0) {}
321 struct PerBlockIDStats {
322 /// NumInstances - This the number of times this block ID has been seen.
323 unsigned NumInstances;
325 /// NumBits - The total size in bits of all of these blocks.
328 /// NumSubBlocks - The total number of blocks these blocks contain.
329 unsigned NumSubBlocks;
331 /// NumAbbrevs - The total number of abbreviations.
334 /// NumRecords - The total number of records these blocks contain, and the
335 /// number that are abbreviated.
336 unsigned NumRecords, NumAbbreviatedRecords;
338 /// CodeFreq - Keep track of the number of times we see each code.
339 std::vector<PerRecordStats> CodeFreq;
342 : NumInstances(0), NumBits(0),
343 NumSubBlocks(0), NumAbbrevs(0), NumRecords(0), NumAbbreviatedRecords(0) {}
346 static std::map<unsigned, PerBlockIDStats> BlockIDStats;
350 /// Error - All bitcode analysis errors go through this function, making this a
351 /// good place to breakpoint if debugging.
352 static bool Error(const Twine &Err) {
353 errs() << Err << "\n";
357 /// ParseBlock - Read a block, updating statistics, etc.
358 static bool ParseBlock(BitstreamCursor &Stream, unsigned BlockID,
359 unsigned IndentLevel, CurStreamTypeType CurStreamType) {
360 std::string Indent(IndentLevel*2, ' ');
361 uint64_t BlockBitStart = Stream.GetCurrentBitNo();
363 // Get the statistics for this BlockID.
364 PerBlockIDStats &BlockStats = BlockIDStats[BlockID];
366 BlockStats.NumInstances++;
368 // BLOCKINFO is a special part of the stream.
369 if (BlockID == bitc::BLOCKINFO_BLOCK_ID) {
370 if (Dump) outs() << Indent << "<BLOCKINFO_BLOCK/>\n";
371 if (Stream.ReadBlockInfoBlock())
372 return Error("Malformed BlockInfoBlock");
373 uint64_t BlockBitEnd = Stream.GetCurrentBitNo();
374 BlockStats.NumBits += BlockBitEnd-BlockBitStart;
378 unsigned NumWords = 0;
379 if (Stream.EnterSubBlock(BlockID, &NumWords))
380 return Error("Malformed block record");
382 const char *BlockName = nullptr;
384 outs() << Indent << "<";
385 if ((BlockName = GetBlockName(BlockID, *Stream.getBitStreamReader(),
389 outs() << "UnknownBlock" << BlockID;
391 if (NonSymbolic && BlockName)
392 outs() << " BlockID=" << BlockID;
394 outs() << " NumWords=" << NumWords
395 << " BlockCodeSize=" << Stream.getAbbrevIDWidth() << ">\n";
398 SmallVector<uint64_t, 64> Record;
400 // Read all the records for this block.
402 if (Stream.AtEndOfStream())
403 return Error("Premature end of bitstream");
405 uint64_t RecordStartBit = Stream.GetCurrentBitNo();
407 BitstreamEntry Entry =
408 Stream.advance(BitstreamCursor::AF_DontAutoprocessAbbrevs);
410 switch (Entry.Kind) {
411 case BitstreamEntry::Error:
412 return Error("malformed bitcode file");
413 case BitstreamEntry::EndBlock: {
414 uint64_t BlockBitEnd = Stream.GetCurrentBitNo();
415 BlockStats.NumBits += BlockBitEnd-BlockBitStart;
417 outs() << Indent << "</";
419 outs() << BlockName << ">\n";
421 outs() << "UnknownBlock" << BlockID << ">\n";
426 case BitstreamEntry::SubBlock: {
427 uint64_t SubBlockBitStart = Stream.GetCurrentBitNo();
428 if (ParseBlock(Stream, Entry.ID, IndentLevel+1, CurStreamType))
430 ++BlockStats.NumSubBlocks;
431 uint64_t SubBlockBitEnd = Stream.GetCurrentBitNo();
433 // Don't include subblock sizes in the size of this block.
434 BlockBitStart += SubBlockBitEnd-SubBlockBitStart;
437 case BitstreamEntry::Record:
438 // The interesting case.
442 if (Entry.ID == bitc::DEFINE_ABBREV) {
443 Stream.ReadAbbrevRecord();
444 ++BlockStats.NumAbbrevs;
450 ++BlockStats.NumRecords;
453 unsigned Code = Stream.readRecord(Entry.ID, Record, &Blob);
455 // Increment the # occurrences of this code.
456 if (BlockStats.CodeFreq.size() <= Code)
457 BlockStats.CodeFreq.resize(Code+1);
458 BlockStats.CodeFreq[Code].NumInstances++;
459 BlockStats.CodeFreq[Code].TotalBits +=
460 Stream.GetCurrentBitNo()-RecordStartBit;
461 if (Entry.ID != bitc::UNABBREV_RECORD) {
462 BlockStats.CodeFreq[Code].NumAbbrev++;
463 ++BlockStats.NumAbbreviatedRecords;
467 outs() << Indent << " <";
468 if (const char *CodeName =
469 GetCodeName(Code, BlockID, *Stream.getBitStreamReader(),
473 outs() << "UnknownCode" << Code;
475 GetCodeName(Code, BlockID, *Stream.getBitStreamReader(),
477 outs() << " codeid=" << Code;
478 if (Entry.ID != bitc::UNABBREV_RECORD)
479 outs() << " abbrevid=" << Entry.ID;
481 for (unsigned i = 0, e = Record.size(); i != e; ++i)
482 outs() << " op" << i << "=" << (int64_t)Record[i];
487 outs() << " blob data = ";
488 if (ShowBinaryBlobs) {
490 outs().write_escaped(Blob, /*hex=*/true) << "'";
492 bool BlobIsPrintable = true;
493 for (unsigned i = 0, e = Blob.size(); i != e; ++i)
494 if (!isprint(static_cast<unsigned char>(Blob[i]))) {
495 BlobIsPrintable = false;
500 outs() << "'" << Blob << "'";
502 outs() << "unprintable, " << Blob.size() << " bytes.";
511 static void PrintSize(double Bits) {
512 outs() << format("%.2f/%.2fB/%luW", Bits, Bits/8,(unsigned long)(Bits/32));
514 static void PrintSize(uint64_t Bits) {
515 outs() << format("%lub/%.2fB/%luW", (unsigned long)Bits,
516 (double)Bits/8, (unsigned long)(Bits/32));
519 static bool openBitcodeFile(StringRef Path,
520 std::unique_ptr<MemoryBuffer> &MemBuf,
521 BitstreamReader &StreamFile,
522 BitstreamCursor &Stream,
523 CurStreamTypeType &CurStreamType) {
524 // Read the input file.
525 ErrorOr<std::unique_ptr<MemoryBuffer>> MemBufOrErr =
526 MemoryBuffer::getFileOrSTDIN(Path);
527 if (std::error_code EC = MemBufOrErr.getError())
528 return Error(Twine("Error reading '") + Path + "': " + EC.message());
529 MemBuf = std::move(MemBufOrErr.get());
531 if (MemBuf->getBufferSize() & 3)
532 return Error("Bitcode stream should be a multiple of 4 bytes in length");
534 const unsigned char *BufPtr = (const unsigned char *)MemBuf->getBufferStart();
535 const unsigned char *EndBufPtr = BufPtr + MemBuf->getBufferSize();
537 // If we have a wrapper header, parse it and ignore the non-bc file contents.
538 // The magic number is 0x0B17C0DE stored in little endian.
539 if (isBitcodeWrapper(BufPtr, EndBufPtr))
540 if (SkipBitcodeWrapperHeader(BufPtr, EndBufPtr, true))
541 return Error("Invalid bitcode wrapper header");
543 StreamFile = BitstreamReader(BufPtr, EndBufPtr);
544 Stream = BitstreamCursor(StreamFile);
545 StreamFile.CollectBlockInfoNames();
547 // Read the stream signature.
549 Signature[0] = Stream.Read(8);
550 Signature[1] = Stream.Read(8);
551 Signature[2] = Stream.Read(4);
552 Signature[3] = Stream.Read(4);
553 Signature[4] = Stream.Read(4);
554 Signature[5] = Stream.Read(4);
556 // Autodetect the file contents, if it is one we know.
557 CurStreamType = UnknownBitstream;
558 if (Signature[0] == 'B' && Signature[1] == 'C' &&
559 Signature[2] == 0x0 && Signature[3] == 0xC &&
560 Signature[4] == 0xE && Signature[5] == 0xD)
561 CurStreamType = LLVMIRBitstream;
566 /// AnalyzeBitcode - Analyze the bitcode file specified by InputFilename.
567 static int AnalyzeBitcode() {
568 std::unique_ptr<MemoryBuffer> StreamBuffer;
569 BitstreamReader StreamFile;
570 BitstreamCursor Stream;
571 CurStreamTypeType CurStreamType;
572 if (openBitcodeFile(InputFilename, StreamBuffer, StreamFile, Stream,
576 // Read block info from BlockInfoFilename, if specified.
577 // The block info must be a top-level block.
578 if (!BlockInfoFilename.empty()) {
579 std::unique_ptr<MemoryBuffer> BlockInfoBuffer;
580 BitstreamReader BlockInfoFile;
581 BitstreamCursor BlockInfoCursor;
582 CurStreamTypeType BlockInfoStreamType;
583 if (openBitcodeFile(BlockInfoFilename, BlockInfoBuffer, BlockInfoFile,
584 BlockInfoCursor, BlockInfoStreamType))
587 while (!BlockInfoCursor.AtEndOfStream()) {
588 unsigned Code = BlockInfoCursor.ReadCode();
589 if (Code != bitc::ENTER_SUBBLOCK)
590 return Error("Invalid record at top-level in block info file");
592 unsigned BlockID = BlockInfoCursor.ReadSubBlockID();
593 if (BlockID == bitc::BLOCKINFO_BLOCK_ID) {
594 if (BlockInfoCursor.ReadBlockInfoBlock())
595 return Error("Malformed BlockInfoBlock in block info file");
599 BlockInfoCursor.SkipBlock();
602 StreamFile.takeBlockInfo(std::move(BlockInfoFile));
605 unsigned NumTopBlocks = 0;
607 // Parse the top-level structure. We only allow blocks at the top-level.
608 while (!Stream.AtEndOfStream()) {
609 unsigned Code = Stream.ReadCode();
610 if (Code != bitc::ENTER_SUBBLOCK)
611 return Error("Invalid record at top-level");
613 unsigned BlockID = Stream.ReadSubBlockID();
615 if (ParseBlock(Stream, BlockID, 0, CurStreamType))
620 if (Dump) outs() << "\n\n";
622 uint64_t BufferSizeBits = StreamFile.getBitcodeBytes().getExtent() * CHAR_BIT;
623 // Print a summary of the read file.
624 outs() << "Summary of " << InputFilename << ":\n";
625 outs() << " Total size: ";
626 PrintSize(BufferSizeBits);
628 outs() << " Stream type: ";
629 switch (CurStreamType) {
630 case UnknownBitstream: outs() << "unknown\n"; break;
631 case LLVMIRBitstream: outs() << "LLVM IR\n"; break;
633 outs() << " # Toplevel Blocks: " << NumTopBlocks << "\n";
636 // Emit per-block stats.
637 outs() << "Per-block Summary:\n";
638 for (std::map<unsigned, PerBlockIDStats>::iterator I = BlockIDStats.begin(),
639 E = BlockIDStats.end(); I != E; ++I) {
640 outs() << " Block ID #" << I->first;
641 if (const char *BlockName = GetBlockName(I->first, StreamFile,
643 outs() << " (" << BlockName << ")";
646 const PerBlockIDStats &Stats = I->second;
647 outs() << " Num Instances: " << Stats.NumInstances << "\n";
648 outs() << " Total Size: ";
649 PrintSize(Stats.NumBits);
651 double pct = (Stats.NumBits * 100.0) / BufferSizeBits;
652 outs() << " Percent of file: " << format("%2.4f%%", pct) << "\n";
653 if (Stats.NumInstances > 1) {
654 outs() << " Average Size: ";
655 PrintSize(Stats.NumBits/(double)Stats.NumInstances);
657 outs() << " Tot/Avg SubBlocks: " << Stats.NumSubBlocks << "/"
658 << Stats.NumSubBlocks/(double)Stats.NumInstances << "\n";
659 outs() << " Tot/Avg Abbrevs: " << Stats.NumAbbrevs << "/"
660 << Stats.NumAbbrevs/(double)Stats.NumInstances << "\n";
661 outs() << " Tot/Avg Records: " << Stats.NumRecords << "/"
662 << Stats.NumRecords/(double)Stats.NumInstances << "\n";
664 outs() << " Num SubBlocks: " << Stats.NumSubBlocks << "\n";
665 outs() << " Num Abbrevs: " << Stats.NumAbbrevs << "\n";
666 outs() << " Num Records: " << Stats.NumRecords << "\n";
668 if (Stats.NumRecords) {
669 double pct = (Stats.NumAbbreviatedRecords * 100.0) / Stats.NumRecords;
670 outs() << " Percent Abbrevs: " << format("%2.4f%%", pct) << "\n";
674 // Print a histogram of the codes we see.
675 if (!NoHistogram && !Stats.CodeFreq.empty()) {
676 std::vector<std::pair<unsigned, unsigned> > FreqPairs; // <freq,code>
677 for (unsigned i = 0, e = Stats.CodeFreq.size(); i != e; ++i)
678 if (unsigned Freq = Stats.CodeFreq[i].NumInstances)
679 FreqPairs.push_back(std::make_pair(Freq, i));
680 std::stable_sort(FreqPairs.begin(), FreqPairs.end());
681 std::reverse(FreqPairs.begin(), FreqPairs.end());
683 outs() << "\tRecord Histogram:\n";
684 outs() << "\t\t Count # Bits %% Abv Record Kind\n";
685 for (unsigned i = 0, e = FreqPairs.size(); i != e; ++i) {
686 const PerRecordStats &RecStats = Stats.CodeFreq[FreqPairs[i].second];
688 outs() << format("\t\t%7d %9lu",
689 RecStats.NumInstances,
690 (unsigned long)RecStats.TotalBits);
692 if (RecStats.NumAbbrev)
695 (double)RecStats.NumAbbrev/RecStats.NumInstances*100);
699 if (const char *CodeName =
700 GetCodeName(FreqPairs[i].second, I->first, StreamFile,
702 outs() << CodeName << "\n";
704 outs() << "UnknownCode" << FreqPairs[i].second << "\n";
714 int main(int argc, char **argv) {
715 // Print a stack trace if we signal out.
716 sys::PrintStackTraceOnErrorSignal();
717 PrettyStackTraceProgram X(argc, argv);
718 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
719 cl::ParseCommandLineOptions(argc, argv, "llvm-bcanalyzer file analyzer\n");
721 return AnalyzeBitcode();