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::IDENTIFICATION_BLOCK_ID:
114 return "IDENTIFICATION_BLOCK_ID";
115 case bitc::VALUE_SYMTAB_BLOCK_ID: return "VALUE_SYMTAB";
116 case bitc::METADATA_BLOCK_ID: return "METADATA_BLOCK";
117 case bitc::METADATA_KIND_BLOCK_ID: return "METADATA_KIND_BLOCK";
118 case bitc::METADATA_ATTACHMENT_ID: return "METADATA_ATTACHMENT_BLOCK";
119 case bitc::USELIST_BLOCK_ID: return "USELIST_BLOCK_ID";
120 case bitc::FUNCTION_SUMMARY_BLOCK_ID:
121 return "FUNCTION_SUMMARY_BLOCK";
122 case bitc::MODULE_STRTAB_BLOCK_ID: return "MODULE_STRTAB_BLOCK";
126 /// GetCodeName - Return a symbolic code name if known, otherwise return
128 static const char *GetCodeName(unsigned CodeID, unsigned BlockID,
129 const BitstreamReader &StreamFile,
130 CurStreamTypeType CurStreamType) {
131 // Standard blocks for all bitcode files.
132 if (BlockID < bitc::FIRST_APPLICATION_BLOCKID) {
133 if (BlockID == bitc::BLOCKINFO_BLOCK_ID) {
135 default: return nullptr;
136 case bitc::BLOCKINFO_CODE_SETBID: return "SETBID";
137 case bitc::BLOCKINFO_CODE_BLOCKNAME: return "BLOCKNAME";
138 case bitc::BLOCKINFO_CODE_SETRECORDNAME: return "SETRECORDNAME";
144 // Check to see if we have a blockinfo record for this record, with a name.
145 if (const BitstreamReader::BlockInfo *Info =
146 StreamFile.getBlockInfo(BlockID)) {
147 for (unsigned i = 0, e = Info->RecordNames.size(); i != e; ++i)
148 if (Info->RecordNames[i].first == CodeID)
149 return Info->RecordNames[i].second.c_str();
153 if (CurStreamType != LLVMIRBitstream) return nullptr;
155 #define STRINGIFY_CODE(PREFIX, CODE) \
156 case bitc::PREFIX##_##CODE: \
159 default: return nullptr;
160 case bitc::MODULE_BLOCK_ID:
162 default: return nullptr;
163 STRINGIFY_CODE(MODULE_CODE, VERSION)
164 STRINGIFY_CODE(MODULE_CODE, TRIPLE)
165 STRINGIFY_CODE(MODULE_CODE, DATALAYOUT)
166 STRINGIFY_CODE(MODULE_CODE, ASM)
167 STRINGIFY_CODE(MODULE_CODE, SECTIONNAME)
168 STRINGIFY_CODE(MODULE_CODE, DEPLIB) // FIXME: Remove in 4.0
169 STRINGIFY_CODE(MODULE_CODE, GLOBALVAR)
170 STRINGIFY_CODE(MODULE_CODE, FUNCTION)
171 STRINGIFY_CODE(MODULE_CODE, ALIAS)
172 STRINGIFY_CODE(MODULE_CODE, PURGEVALS)
173 STRINGIFY_CODE(MODULE_CODE, GCNAME)
174 STRINGIFY_CODE(MODULE_CODE, VSTOFFSET)
175 STRINGIFY_CODE(MODULE_CODE, METADATA_VALUES)
177 case bitc::IDENTIFICATION_BLOCK_ID:
181 STRINGIFY_CODE(IDENTIFICATION_CODE, STRING)
182 STRINGIFY_CODE(IDENTIFICATION_CODE, EPOCH)
184 case bitc::PARAMATTR_BLOCK_ID:
186 default: return nullptr;
187 // FIXME: Should these be different?
188 case bitc::PARAMATTR_CODE_ENTRY_OLD: return "ENTRY";
189 case bitc::PARAMATTR_CODE_ENTRY: return "ENTRY";
190 case bitc::PARAMATTR_GRP_CODE_ENTRY: return "ENTRY";
192 case bitc::TYPE_BLOCK_ID_NEW:
194 default: return nullptr;
195 STRINGIFY_CODE(TYPE_CODE, NUMENTRY)
196 STRINGIFY_CODE(TYPE_CODE, VOID)
197 STRINGIFY_CODE(TYPE_CODE, FLOAT)
198 STRINGIFY_CODE(TYPE_CODE, DOUBLE)
199 STRINGIFY_CODE(TYPE_CODE, LABEL)
200 STRINGIFY_CODE(TYPE_CODE, OPAQUE)
201 STRINGIFY_CODE(TYPE_CODE, INTEGER)
202 STRINGIFY_CODE(TYPE_CODE, POINTER)
203 STRINGIFY_CODE(TYPE_CODE, ARRAY)
204 STRINGIFY_CODE(TYPE_CODE, VECTOR)
205 STRINGIFY_CODE(TYPE_CODE, X86_FP80)
206 STRINGIFY_CODE(TYPE_CODE, FP128)
207 STRINGIFY_CODE(TYPE_CODE, PPC_FP128)
208 STRINGIFY_CODE(TYPE_CODE, METADATA)
209 STRINGIFY_CODE(TYPE_CODE, STRUCT_ANON)
210 STRINGIFY_CODE(TYPE_CODE, STRUCT_NAME)
211 STRINGIFY_CODE(TYPE_CODE, STRUCT_NAMED)
212 STRINGIFY_CODE(TYPE_CODE, FUNCTION)
215 case bitc::CONSTANTS_BLOCK_ID:
217 default: return nullptr;
218 STRINGIFY_CODE(CST_CODE, SETTYPE)
219 STRINGIFY_CODE(CST_CODE, NULL)
220 STRINGIFY_CODE(CST_CODE, UNDEF)
221 STRINGIFY_CODE(CST_CODE, INTEGER)
222 STRINGIFY_CODE(CST_CODE, WIDE_INTEGER)
223 STRINGIFY_CODE(CST_CODE, FLOAT)
224 STRINGIFY_CODE(CST_CODE, AGGREGATE)
225 STRINGIFY_CODE(CST_CODE, STRING)
226 STRINGIFY_CODE(CST_CODE, CSTRING)
227 STRINGIFY_CODE(CST_CODE, CE_BINOP)
228 STRINGIFY_CODE(CST_CODE, CE_CAST)
229 STRINGIFY_CODE(CST_CODE, CE_GEP)
230 STRINGIFY_CODE(CST_CODE, CE_INBOUNDS_GEP)
231 STRINGIFY_CODE(CST_CODE, CE_SELECT)
232 STRINGIFY_CODE(CST_CODE, CE_EXTRACTELT)
233 STRINGIFY_CODE(CST_CODE, CE_INSERTELT)
234 STRINGIFY_CODE(CST_CODE, CE_SHUFFLEVEC)
235 STRINGIFY_CODE(CST_CODE, CE_CMP)
236 STRINGIFY_CODE(CST_CODE, INLINEASM)
237 STRINGIFY_CODE(CST_CODE, CE_SHUFVEC_EX)
238 case bitc::CST_CODE_BLOCKADDRESS: return "CST_CODE_BLOCKADDRESS";
239 STRINGIFY_CODE(CST_CODE, DATA)
241 case bitc::FUNCTION_BLOCK_ID:
243 default: return nullptr;
244 STRINGIFY_CODE(FUNC_CODE, DECLAREBLOCKS)
245 STRINGIFY_CODE(FUNC_CODE, INST_BINOP)
246 STRINGIFY_CODE(FUNC_CODE, INST_CAST)
247 STRINGIFY_CODE(FUNC_CODE, INST_GEP_OLD)
248 STRINGIFY_CODE(FUNC_CODE, INST_INBOUNDS_GEP_OLD)
249 STRINGIFY_CODE(FUNC_CODE, INST_SELECT)
250 STRINGIFY_CODE(FUNC_CODE, INST_EXTRACTELT)
251 STRINGIFY_CODE(FUNC_CODE, INST_INSERTELT)
252 STRINGIFY_CODE(FUNC_CODE, INST_SHUFFLEVEC)
253 STRINGIFY_CODE(FUNC_CODE, INST_CMP)
254 STRINGIFY_CODE(FUNC_CODE, INST_RET)
255 STRINGIFY_CODE(FUNC_CODE, INST_BR)
256 STRINGIFY_CODE(FUNC_CODE, INST_SWITCH)
257 STRINGIFY_CODE(FUNC_CODE, INST_INVOKE)
258 STRINGIFY_CODE(FUNC_CODE, INST_UNREACHABLE)
259 STRINGIFY_CODE(FUNC_CODE, INST_CLEANUPRET)
260 STRINGIFY_CODE(FUNC_CODE, INST_CATCHRET)
261 STRINGIFY_CODE(FUNC_CODE, INST_CATCHPAD)
262 STRINGIFY_CODE(FUNC_CODE, INST_TERMINATEPAD)
263 STRINGIFY_CODE(FUNC_CODE, INST_PHI)
264 STRINGIFY_CODE(FUNC_CODE, INST_ALLOCA)
265 STRINGIFY_CODE(FUNC_CODE, INST_LOAD)
266 STRINGIFY_CODE(FUNC_CODE, INST_VAARG)
267 STRINGIFY_CODE(FUNC_CODE, INST_STORE)
268 STRINGIFY_CODE(FUNC_CODE, INST_EXTRACTVAL)
269 STRINGIFY_CODE(FUNC_CODE, INST_INSERTVAL)
270 STRINGIFY_CODE(FUNC_CODE, INST_CMP2)
271 STRINGIFY_CODE(FUNC_CODE, INST_VSELECT)
272 STRINGIFY_CODE(FUNC_CODE, DEBUG_LOC_AGAIN)
273 STRINGIFY_CODE(FUNC_CODE, INST_CALL)
274 STRINGIFY_CODE(FUNC_CODE, DEBUG_LOC)
275 STRINGIFY_CODE(FUNC_CODE, INST_GEP)
277 case bitc::VALUE_SYMTAB_BLOCK_ID:
279 default: return nullptr;
280 STRINGIFY_CODE(VST_CODE, ENTRY)
281 STRINGIFY_CODE(VST_CODE, BBENTRY)
282 STRINGIFY_CODE(VST_CODE, FNENTRY)
283 STRINGIFY_CODE(VST_CODE, COMBINED_FNENTRY)
285 case bitc::MODULE_STRTAB_BLOCK_ID:
289 STRINGIFY_CODE(MST_CODE, ENTRY)
291 case bitc::FUNCTION_SUMMARY_BLOCK_ID:
295 STRINGIFY_CODE(FS_CODE, PERMODULE_ENTRY)
296 STRINGIFY_CODE(FS_CODE, COMBINED_ENTRY)
298 case bitc::METADATA_ATTACHMENT_ID:
300 default:return nullptr;
301 STRINGIFY_CODE(METADATA, ATTACHMENT)
303 case bitc::METADATA_BLOCK_ID:
305 default:return nullptr;
306 STRINGIFY_CODE(METADATA, STRING)
307 STRINGIFY_CODE(METADATA, NAME)
308 STRINGIFY_CODE(METADATA, KIND) // Older bitcode has it in a MODULE_BLOCK
309 STRINGIFY_CODE(METADATA, NODE)
310 STRINGIFY_CODE(METADATA, VALUE)
311 STRINGIFY_CODE(METADATA, OLD_NODE)
312 STRINGIFY_CODE(METADATA, OLD_FN_NODE)
313 STRINGIFY_CODE(METADATA, NAMED_NODE)
314 STRINGIFY_CODE(METADATA, DISTINCT_NODE)
315 STRINGIFY_CODE(METADATA, LOCATION)
316 STRINGIFY_CODE(METADATA, GENERIC_DEBUG)
317 STRINGIFY_CODE(METADATA, SUBRANGE)
318 STRINGIFY_CODE(METADATA, ENUMERATOR)
319 STRINGIFY_CODE(METADATA, BASIC_TYPE)
320 STRINGIFY_CODE(METADATA, FILE)
321 STRINGIFY_CODE(METADATA, DERIVED_TYPE)
322 STRINGIFY_CODE(METADATA, COMPOSITE_TYPE)
323 STRINGIFY_CODE(METADATA, SUBROUTINE_TYPE)
324 STRINGIFY_CODE(METADATA, COMPILE_UNIT)
325 STRINGIFY_CODE(METADATA, SUBPROGRAM)
326 STRINGIFY_CODE(METADATA, LEXICAL_BLOCK)
327 STRINGIFY_CODE(METADATA, LEXICAL_BLOCK_FILE)
328 STRINGIFY_CODE(METADATA, NAMESPACE)
329 STRINGIFY_CODE(METADATA, TEMPLATE_TYPE)
330 STRINGIFY_CODE(METADATA, TEMPLATE_VALUE)
331 STRINGIFY_CODE(METADATA, GLOBAL_VAR)
332 STRINGIFY_CODE(METADATA, LOCAL_VAR)
333 STRINGIFY_CODE(METADATA, EXPRESSION)
334 STRINGIFY_CODE(METADATA, OBJC_PROPERTY)
335 STRINGIFY_CODE(METADATA, IMPORTED_ENTITY)
336 STRINGIFY_CODE(METADATA, MODULE)
338 case bitc::METADATA_KIND_BLOCK_ID:
342 STRINGIFY_CODE(METADATA, KIND)
344 case bitc::USELIST_BLOCK_ID:
346 default:return nullptr;
347 case bitc::USELIST_CODE_DEFAULT: return "USELIST_CODE_DEFAULT";
348 case bitc::USELIST_CODE_BB: return "USELIST_CODE_BB";
351 #undef STRINGIFY_CODE
354 struct PerRecordStats {
355 unsigned NumInstances;
359 PerRecordStats() : NumInstances(0), NumAbbrev(0), TotalBits(0) {}
362 struct PerBlockIDStats {
363 /// NumInstances - This the number of times this block ID has been seen.
364 unsigned NumInstances;
366 /// NumBits - The total size in bits of all of these blocks.
369 /// NumSubBlocks - The total number of blocks these blocks contain.
370 unsigned NumSubBlocks;
372 /// NumAbbrevs - The total number of abbreviations.
375 /// NumRecords - The total number of records these blocks contain, and the
376 /// number that are abbreviated.
377 unsigned NumRecords, NumAbbreviatedRecords;
379 /// CodeFreq - Keep track of the number of times we see each code.
380 std::vector<PerRecordStats> CodeFreq;
383 : NumInstances(0), NumBits(0),
384 NumSubBlocks(0), NumAbbrevs(0), NumRecords(0), NumAbbreviatedRecords(0) {}
387 static std::map<unsigned, PerBlockIDStats> BlockIDStats;
391 /// Error - All bitcode analysis errors go through this function, making this a
392 /// good place to breakpoint if debugging.
393 static bool Error(const Twine &Err) {
394 errs() << Err << "\n";
398 /// ParseBlock - Read a block, updating statistics, etc.
399 static bool ParseBlock(BitstreamCursor &Stream, unsigned BlockID,
400 unsigned IndentLevel, CurStreamTypeType CurStreamType) {
401 std::string Indent(IndentLevel*2, ' ');
402 uint64_t BlockBitStart = Stream.GetCurrentBitNo();
404 // Get the statistics for this BlockID.
405 PerBlockIDStats &BlockStats = BlockIDStats[BlockID];
407 BlockStats.NumInstances++;
409 // BLOCKINFO is a special part of the stream.
410 if (BlockID == bitc::BLOCKINFO_BLOCK_ID) {
411 if (Dump) outs() << Indent << "<BLOCKINFO_BLOCK/>\n";
412 if (Stream.ReadBlockInfoBlock())
413 return Error("Malformed BlockInfoBlock");
414 uint64_t BlockBitEnd = Stream.GetCurrentBitNo();
415 BlockStats.NumBits += BlockBitEnd-BlockBitStart;
419 unsigned NumWords = 0;
420 if (Stream.EnterSubBlock(BlockID, &NumWords))
421 return Error("Malformed block record");
423 const char *BlockName = nullptr;
425 outs() << Indent << "<";
426 if ((BlockName = GetBlockName(BlockID, *Stream.getBitStreamReader(),
430 outs() << "UnknownBlock" << BlockID;
432 if (NonSymbolic && BlockName)
433 outs() << " BlockID=" << BlockID;
435 outs() << " NumWords=" << NumWords
436 << " BlockCodeSize=" << Stream.getAbbrevIDWidth() << ">\n";
439 SmallVector<uint64_t, 64> Record;
441 // Read all the records for this block.
443 if (Stream.AtEndOfStream())
444 return Error("Premature end of bitstream");
446 uint64_t RecordStartBit = Stream.GetCurrentBitNo();
448 BitstreamEntry Entry =
449 Stream.advance(BitstreamCursor::AF_DontAutoprocessAbbrevs);
451 switch (Entry.Kind) {
452 case BitstreamEntry::Error:
453 return Error("malformed bitcode file");
454 case BitstreamEntry::EndBlock: {
455 uint64_t BlockBitEnd = Stream.GetCurrentBitNo();
456 BlockStats.NumBits += BlockBitEnd-BlockBitStart;
458 outs() << Indent << "</";
460 outs() << BlockName << ">\n";
462 outs() << "UnknownBlock" << BlockID << ">\n";
467 case BitstreamEntry::SubBlock: {
468 uint64_t SubBlockBitStart = Stream.GetCurrentBitNo();
469 if (ParseBlock(Stream, Entry.ID, IndentLevel+1, CurStreamType))
471 ++BlockStats.NumSubBlocks;
472 uint64_t SubBlockBitEnd = Stream.GetCurrentBitNo();
474 // Don't include subblock sizes in the size of this block.
475 BlockBitStart += SubBlockBitEnd-SubBlockBitStart;
478 case BitstreamEntry::Record:
479 // The interesting case.
483 if (Entry.ID == bitc::DEFINE_ABBREV) {
484 Stream.ReadAbbrevRecord();
485 ++BlockStats.NumAbbrevs;
491 ++BlockStats.NumRecords;
494 unsigned Code = Stream.readRecord(Entry.ID, Record, &Blob);
496 // Increment the # occurrences of this code.
497 if (BlockStats.CodeFreq.size() <= Code)
498 BlockStats.CodeFreq.resize(Code+1);
499 BlockStats.CodeFreq[Code].NumInstances++;
500 BlockStats.CodeFreq[Code].TotalBits +=
501 Stream.GetCurrentBitNo()-RecordStartBit;
502 if (Entry.ID != bitc::UNABBREV_RECORD) {
503 BlockStats.CodeFreq[Code].NumAbbrev++;
504 ++BlockStats.NumAbbreviatedRecords;
508 outs() << Indent << " <";
509 if (const char *CodeName =
510 GetCodeName(Code, BlockID, *Stream.getBitStreamReader(),
514 outs() << "UnknownCode" << Code;
516 GetCodeName(Code, BlockID, *Stream.getBitStreamReader(),
518 outs() << " codeid=" << Code;
519 const BitCodeAbbrev *Abbv = nullptr;
520 if (Entry.ID != bitc::UNABBREV_RECORD) {
521 Abbv = Stream.getAbbrev(Entry.ID);
522 outs() << " abbrevid=" << Entry.ID;
525 for (unsigned i = 0, e = Record.size(); i != e; ++i)
526 outs() << " op" << i << "=" << (int64_t)Record[i];
531 for (unsigned i = 1, e = Abbv->getNumOperandInfos(); i != e; ++i) {
532 const BitCodeAbbrevOp &Op = Abbv->getOperandInfo(i);
533 if (!Op.isEncoding() || Op.getEncoding() != BitCodeAbbrevOp::Array)
535 assert(i + 2 == e && "Array op not second to last");
537 bool ArrayIsPrintable = true;
538 for (unsigned j = i - 1, je = Record.size(); j != je; ++j) {
539 if (!isprint(static_cast<unsigned char>(Record[j]))) {
540 ArrayIsPrintable = false;
543 Str += (char)Record[j];
545 if (ArrayIsPrintable)
546 outs() << " record string = '" << Str << "'";
552 outs() << " blob data = ";
553 if (ShowBinaryBlobs) {
555 outs().write_escaped(Blob, /*hex=*/true) << "'";
557 bool BlobIsPrintable = true;
558 for (unsigned i = 0, e = Blob.size(); i != e; ++i)
559 if (!isprint(static_cast<unsigned char>(Blob[i]))) {
560 BlobIsPrintable = false;
565 outs() << "'" << Blob << "'";
567 outs() << "unprintable, " << Blob.size() << " bytes.";
576 static void PrintSize(double Bits) {
577 outs() << format("%.2f/%.2fB/%luW", Bits, Bits/8,(unsigned long)(Bits/32));
579 static void PrintSize(uint64_t Bits) {
580 outs() << format("%lub/%.2fB/%luW", (unsigned long)Bits,
581 (double)Bits/8, (unsigned long)(Bits/32));
584 static bool openBitcodeFile(StringRef Path,
585 std::unique_ptr<MemoryBuffer> &MemBuf,
586 BitstreamReader &StreamFile,
587 BitstreamCursor &Stream,
588 CurStreamTypeType &CurStreamType) {
589 // Read the input file.
590 ErrorOr<std::unique_ptr<MemoryBuffer>> MemBufOrErr =
591 MemoryBuffer::getFileOrSTDIN(Path);
592 if (std::error_code EC = MemBufOrErr.getError())
593 return Error(Twine("Error reading '") + Path + "': " + EC.message());
594 MemBuf = std::move(MemBufOrErr.get());
596 if (MemBuf->getBufferSize() & 3)
597 return Error("Bitcode stream should be a multiple of 4 bytes in length");
599 const unsigned char *BufPtr = (const unsigned char *)MemBuf->getBufferStart();
600 const unsigned char *EndBufPtr = BufPtr + MemBuf->getBufferSize();
602 // If we have a wrapper header, parse it and ignore the non-bc file contents.
603 // The magic number is 0x0B17C0DE stored in little endian.
604 if (isBitcodeWrapper(BufPtr, EndBufPtr))
605 if (SkipBitcodeWrapperHeader(BufPtr, EndBufPtr, true))
606 return Error("Invalid bitcode wrapper header");
608 StreamFile = BitstreamReader(BufPtr, EndBufPtr);
609 Stream = BitstreamCursor(StreamFile);
610 StreamFile.CollectBlockInfoNames();
612 // Read the stream signature.
614 Signature[0] = Stream.Read(8);
615 Signature[1] = Stream.Read(8);
616 Signature[2] = Stream.Read(4);
617 Signature[3] = Stream.Read(4);
618 Signature[4] = Stream.Read(4);
619 Signature[5] = Stream.Read(4);
621 // Autodetect the file contents, if it is one we know.
622 CurStreamType = UnknownBitstream;
623 if (Signature[0] == 'B' && Signature[1] == 'C' &&
624 Signature[2] == 0x0 && Signature[3] == 0xC &&
625 Signature[4] == 0xE && Signature[5] == 0xD)
626 CurStreamType = LLVMIRBitstream;
631 /// AnalyzeBitcode - Analyze the bitcode file specified by InputFilename.
632 static int AnalyzeBitcode() {
633 std::unique_ptr<MemoryBuffer> StreamBuffer;
634 BitstreamReader StreamFile;
635 BitstreamCursor Stream;
636 CurStreamTypeType CurStreamType;
637 if (openBitcodeFile(InputFilename, StreamBuffer, StreamFile, Stream,
641 // Read block info from BlockInfoFilename, if specified.
642 // The block info must be a top-level block.
643 if (!BlockInfoFilename.empty()) {
644 std::unique_ptr<MemoryBuffer> BlockInfoBuffer;
645 BitstreamReader BlockInfoFile;
646 BitstreamCursor BlockInfoCursor;
647 CurStreamTypeType BlockInfoStreamType;
648 if (openBitcodeFile(BlockInfoFilename, BlockInfoBuffer, BlockInfoFile,
649 BlockInfoCursor, BlockInfoStreamType))
652 while (!BlockInfoCursor.AtEndOfStream()) {
653 unsigned Code = BlockInfoCursor.ReadCode();
654 if (Code != bitc::ENTER_SUBBLOCK)
655 return Error("Invalid record at top-level in block info file");
657 unsigned BlockID = BlockInfoCursor.ReadSubBlockID();
658 if (BlockID == bitc::BLOCKINFO_BLOCK_ID) {
659 if (BlockInfoCursor.ReadBlockInfoBlock())
660 return Error("Malformed BlockInfoBlock in block info file");
664 BlockInfoCursor.SkipBlock();
667 StreamFile.takeBlockInfo(std::move(BlockInfoFile));
670 unsigned NumTopBlocks = 0;
672 // Parse the top-level structure. We only allow blocks at the top-level.
673 while (!Stream.AtEndOfStream()) {
674 unsigned Code = Stream.ReadCode();
675 if (Code != bitc::ENTER_SUBBLOCK)
676 return Error("Invalid record at top-level");
678 unsigned BlockID = Stream.ReadSubBlockID();
680 if (ParseBlock(Stream, BlockID, 0, CurStreamType))
685 if (Dump) outs() << "\n\n";
687 uint64_t BufferSizeBits = StreamFile.getBitcodeBytes().getExtent() * CHAR_BIT;
688 // Print a summary of the read file.
689 outs() << "Summary of " << InputFilename << ":\n";
690 outs() << " Total size: ";
691 PrintSize(BufferSizeBits);
693 outs() << " Stream type: ";
694 switch (CurStreamType) {
695 case UnknownBitstream: outs() << "unknown\n"; break;
696 case LLVMIRBitstream: outs() << "LLVM IR\n"; break;
698 outs() << " # Toplevel Blocks: " << NumTopBlocks << "\n";
701 // Emit per-block stats.
702 outs() << "Per-block Summary:\n";
703 for (std::map<unsigned, PerBlockIDStats>::iterator I = BlockIDStats.begin(),
704 E = BlockIDStats.end(); I != E; ++I) {
705 outs() << " Block ID #" << I->first;
706 if (const char *BlockName = GetBlockName(I->first, StreamFile,
708 outs() << " (" << BlockName << ")";
711 const PerBlockIDStats &Stats = I->second;
712 outs() << " Num Instances: " << Stats.NumInstances << "\n";
713 outs() << " Total Size: ";
714 PrintSize(Stats.NumBits);
716 double pct = (Stats.NumBits * 100.0) / BufferSizeBits;
717 outs() << " Percent of file: " << format("%2.4f%%", pct) << "\n";
718 if (Stats.NumInstances > 1) {
719 outs() << " Average Size: ";
720 PrintSize(Stats.NumBits/(double)Stats.NumInstances);
722 outs() << " Tot/Avg SubBlocks: " << Stats.NumSubBlocks << "/"
723 << Stats.NumSubBlocks/(double)Stats.NumInstances << "\n";
724 outs() << " Tot/Avg Abbrevs: " << Stats.NumAbbrevs << "/"
725 << Stats.NumAbbrevs/(double)Stats.NumInstances << "\n";
726 outs() << " Tot/Avg Records: " << Stats.NumRecords << "/"
727 << Stats.NumRecords/(double)Stats.NumInstances << "\n";
729 outs() << " Num SubBlocks: " << Stats.NumSubBlocks << "\n";
730 outs() << " Num Abbrevs: " << Stats.NumAbbrevs << "\n";
731 outs() << " Num Records: " << Stats.NumRecords << "\n";
733 if (Stats.NumRecords) {
734 double pct = (Stats.NumAbbreviatedRecords * 100.0) / Stats.NumRecords;
735 outs() << " Percent Abbrevs: " << format("%2.4f%%", pct) << "\n";
739 // Print a histogram of the codes we see.
740 if (!NoHistogram && !Stats.CodeFreq.empty()) {
741 std::vector<std::pair<unsigned, unsigned> > FreqPairs; // <freq,code>
742 for (unsigned i = 0, e = Stats.CodeFreq.size(); i != e; ++i)
743 if (unsigned Freq = Stats.CodeFreq[i].NumInstances)
744 FreqPairs.push_back(std::make_pair(Freq, i));
745 std::stable_sort(FreqPairs.begin(), FreqPairs.end());
746 std::reverse(FreqPairs.begin(), FreqPairs.end());
748 outs() << "\tRecord Histogram:\n";
749 outs() << "\t\t Count # Bits %% Abv Record Kind\n";
750 for (unsigned i = 0, e = FreqPairs.size(); i != e; ++i) {
751 const PerRecordStats &RecStats = Stats.CodeFreq[FreqPairs[i].second];
753 outs() << format("\t\t%7d %9lu",
754 RecStats.NumInstances,
755 (unsigned long)RecStats.TotalBits);
757 if (RecStats.NumAbbrev)
760 (double)RecStats.NumAbbrev/RecStats.NumInstances*100);
764 if (const char *CodeName =
765 GetCodeName(FreqPairs[i].second, I->first, StreamFile,
767 outs() << CodeName << "\n";
769 outs() << "UnknownCode" << FreqPairs[i].second << "\n";
779 int main(int argc, char **argv) {
780 // Print a stack trace if we signal out.
781 sys::PrintStackTraceOnErrorSignal();
782 PrettyStackTraceProgram X(argc, argv);
783 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
784 cl::ParseCommandLineOptions(argc, argv, "llvm-bcanalyzer file analyzer\n");
786 return AnalyzeBitcode();