1 //===-- llvm-bcanalyzer.cpp - Bitcode Analyzer --------------------------===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
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
13 //
14 // Options:
15 // --help - Output information about command line switches
16 // --dump - Dump low-level bitcode structure in readable format
17 //
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).
27 //
28 //===----------------------------------------------------------------------===//
29
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"
42 #include <algorithm>
43 #include <cctype>
44 #include <map>
45 #include <system_error>
46 using namespace llvm;
47
48 static cl::opt<std::string>
49 InputFilename(cl::Positional, cl::desc("<input bitcode>"), cl::init("-"));
50
51 static cl::opt<bool> Dump("dump", cl::desc("Dump low level bitcode trace"));
52
53 //===----------------------------------------------------------------------===//
54 // Bitcode specific analysis.
55 //===----------------------------------------------------------------------===//
56
57 static cl::opt<bool> NoHistogram("disable-histogram",
58 cl::desc("Do not print per-code histogram"));
59
60 static cl::opt<bool>
61 NonSymbolic("non-symbolic",
62 cl::desc("Emit numeric info in dump even if"
63 " symbolic info is available"));
64
65 static cl::opt<std::string>
66 BlockInfoFilename("block-info",
67 cl::desc("Use the BLOCK_INFO from the given file"));
68
69 static cl::opt<bool>
70 ShowBinaryBlobs("show-binary-blobs",
71 cl::desc("Print binary blobs using hex escapes"));
72
73 namespace {
74
75 /// CurStreamTypeType - A type for CurStreamType
76 enum CurStreamTypeType {
77 UnknownBitstream,
78 LLVMIRBitstream
79 };
80
81 }
82
83 /// GetBlockName - Return a symbolic block name if known, otherwise return
84 /// null.
GetBlockName(unsigned BlockID,const BitstreamReader & StreamFile,CurStreamTypeType CurStreamType)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";
92 return nullptr;
93 }
94
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();
100 }
101
102
103 if (CurStreamType != LLVMIRBitstream) return nullptr;
104
105 switch (BlockID) {
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";
123 }
124 }
125
126 /// GetCodeName - Return a symbolic code name if known, otherwise return
127 /// null.
GetCodeName(unsigned CodeID,unsigned BlockID,const BitstreamReader & StreamFile,CurStreamTypeType CurStreamType)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) {
134 switch (CodeID) {
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";
139 }
140 }
141 return nullptr;
142 }
143
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();
150 }
151
152
153 if (CurStreamType != LLVMIRBitstream) return nullptr;
154
155 #define STRINGIFY_CODE(PREFIX, CODE) \
156 case bitc::PREFIX##_##CODE: \
157 return #CODE;
158 switch (BlockID) {
159 default: return nullptr;
160 case bitc::MODULE_BLOCK_ID:
161 switch (CodeID) {
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)
176 }
177 case bitc::IDENTIFICATION_BLOCK_ID:
178 switch (CodeID) {
179 default:
180 return nullptr;
181 STRINGIFY_CODE(IDENTIFICATION_CODE, STRING)
182 STRINGIFY_CODE(IDENTIFICATION_CODE, EPOCH)
183 }
184 case bitc::PARAMATTR_BLOCK_ID:
185 switch (CodeID) {
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";
191 }
192 case bitc::TYPE_BLOCK_ID_NEW:
193 switch (CodeID) {
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)
213 }
214
215 case bitc::CONSTANTS_BLOCK_ID:
216 switch (CodeID) {
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)
240 }
241 case bitc::FUNCTION_BLOCK_ID:
242 switch (CodeID) {
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_PHI)
263 STRINGIFY_CODE(FUNC_CODE, INST_ALLOCA)
264 STRINGIFY_CODE(FUNC_CODE, INST_LOAD)
265 STRINGIFY_CODE(FUNC_CODE, INST_VAARG)
266 STRINGIFY_CODE(FUNC_CODE, INST_STORE)
267 STRINGIFY_CODE(FUNC_CODE, INST_EXTRACTVAL)
268 STRINGIFY_CODE(FUNC_CODE, INST_INSERTVAL)
269 STRINGIFY_CODE(FUNC_CODE, INST_CMP2)
270 STRINGIFY_CODE(FUNC_CODE, INST_VSELECT)
271 STRINGIFY_CODE(FUNC_CODE, DEBUG_LOC_AGAIN)
272 STRINGIFY_CODE(FUNC_CODE, INST_CALL)
273 STRINGIFY_CODE(FUNC_CODE, DEBUG_LOC)
274 STRINGIFY_CODE(FUNC_CODE, INST_GEP)
275 }
276 case bitc::VALUE_SYMTAB_BLOCK_ID:
277 switch (CodeID) {
278 default: return nullptr;
279 STRINGIFY_CODE(VST_CODE, ENTRY)
280 STRINGIFY_CODE(VST_CODE, BBENTRY)
281 STRINGIFY_CODE(VST_CODE, FNENTRY)
282 STRINGIFY_CODE(VST_CODE, COMBINED_FNENTRY)
283 }
284 case bitc::MODULE_STRTAB_BLOCK_ID:
285 switch (CodeID) {
286 default:
287 return nullptr;
288 STRINGIFY_CODE(MST_CODE, ENTRY)
289 }
290 case bitc::FUNCTION_SUMMARY_BLOCK_ID:
291 switch (CodeID) {
292 default:
293 return nullptr;
294 STRINGIFY_CODE(FS_CODE, PERMODULE_ENTRY)
295 STRINGIFY_CODE(FS_CODE, COMBINED_ENTRY)
296 }
297 case bitc::METADATA_ATTACHMENT_ID:
298 switch(CodeID) {
299 default:return nullptr;
300 STRINGIFY_CODE(METADATA, ATTACHMENT)
301 }
302 case bitc::METADATA_BLOCK_ID:
303 switch(CodeID) {
304 default:return nullptr;
305 STRINGIFY_CODE(METADATA, STRING)
306 STRINGIFY_CODE(METADATA, NAME)
307 STRINGIFY_CODE(METADATA, KIND) // Older bitcode has it in a MODULE_BLOCK
308 STRINGIFY_CODE(METADATA, NODE)
309 STRINGIFY_CODE(METADATA, VALUE)
310 STRINGIFY_CODE(METADATA, OLD_NODE)
311 STRINGIFY_CODE(METADATA, OLD_FN_NODE)
312 STRINGIFY_CODE(METADATA, NAMED_NODE)
313 STRINGIFY_CODE(METADATA, DISTINCT_NODE)
314 STRINGIFY_CODE(METADATA, LOCATION)
315 STRINGIFY_CODE(METADATA, GENERIC_DEBUG)
316 STRINGIFY_CODE(METADATA, SUBRANGE)
317 STRINGIFY_CODE(METADATA, ENUMERATOR)
318 STRINGIFY_CODE(METADATA, BASIC_TYPE)
319 STRINGIFY_CODE(METADATA, FILE)
320 STRINGIFY_CODE(METADATA, DERIVED_TYPE)
321 STRINGIFY_CODE(METADATA, COMPOSITE_TYPE)
322 STRINGIFY_CODE(METADATA, SUBROUTINE_TYPE)
323 STRINGIFY_CODE(METADATA, COMPILE_UNIT)
324 STRINGIFY_CODE(METADATA, SUBPROGRAM)
325 STRINGIFY_CODE(METADATA, LEXICAL_BLOCK)
326 STRINGIFY_CODE(METADATA, LEXICAL_BLOCK_FILE)
327 STRINGIFY_CODE(METADATA, NAMESPACE)
328 STRINGIFY_CODE(METADATA, TEMPLATE_TYPE)
329 STRINGIFY_CODE(METADATA, TEMPLATE_VALUE)
330 STRINGIFY_CODE(METADATA, GLOBAL_VAR)
331 STRINGIFY_CODE(METADATA, LOCAL_VAR)
332 STRINGIFY_CODE(METADATA, EXPRESSION)
333 STRINGIFY_CODE(METADATA, OBJC_PROPERTY)
334 STRINGIFY_CODE(METADATA, IMPORTED_ENTITY)
335 STRINGIFY_CODE(METADATA, MODULE)
336 }
337 case bitc::METADATA_KIND_BLOCK_ID:
338 switch (CodeID) {
339 default:
340 return nullptr;
341 STRINGIFY_CODE(METADATA, KIND)
342 }
343 case bitc::USELIST_BLOCK_ID:
344 switch(CodeID) {
345 default:return nullptr;
346 case bitc::USELIST_CODE_DEFAULT: return "USELIST_CODE_DEFAULT";
347 case bitc::USELIST_CODE_BB: return "USELIST_CODE_BB";
348 }
349 }
350 #undef STRINGIFY_CODE
351 }
352
353 struct PerRecordStats {
354 unsigned NumInstances;
355 unsigned NumAbbrev;
356 uint64_t TotalBits;
357
PerRecordStatsPerRecordStats358 PerRecordStats() : NumInstances(0), NumAbbrev(0), TotalBits(0) {}
359 };
360
361 struct PerBlockIDStats {
362 /// NumInstances - This the number of times this block ID has been seen.
363 unsigned NumInstances;
364
365 /// NumBits - The total size in bits of all of these blocks.
366 uint64_t NumBits;
367
368 /// NumSubBlocks - The total number of blocks these blocks contain.
369 unsigned NumSubBlocks;
370
371 /// NumAbbrevs - The total number of abbreviations.
372 unsigned NumAbbrevs;
373
374 /// NumRecords - The total number of records these blocks contain, and the
375 /// number that are abbreviated.
376 unsigned NumRecords, NumAbbreviatedRecords;
377
378 /// CodeFreq - Keep track of the number of times we see each code.
379 std::vector<PerRecordStats> CodeFreq;
380
PerBlockIDStatsPerBlockIDStats381 PerBlockIDStats()
382 : NumInstances(0), NumBits(0),
383 NumSubBlocks(0), NumAbbrevs(0), NumRecords(0), NumAbbreviatedRecords(0) {}
384 };
385
386 static std::map<unsigned, PerBlockIDStats> BlockIDStats;
387
388
389
390 /// Error - All bitcode analysis errors go through this function, making this a
391 /// good place to breakpoint if debugging.
Error(const Twine & Err)392 static bool Error(const Twine &Err) {
393 errs() << Err << "\n";
394 return true;
395 }
396
397 /// ParseBlock - Read a block, updating statistics, etc.
ParseBlock(BitstreamCursor & Stream,unsigned BlockID,unsigned IndentLevel,CurStreamTypeType CurStreamType)398 static bool ParseBlock(BitstreamCursor &Stream, unsigned BlockID,
399 unsigned IndentLevel, CurStreamTypeType CurStreamType) {
400 std::string Indent(IndentLevel*2, ' ');
401 uint64_t BlockBitStart = Stream.GetCurrentBitNo();
402
403 // Get the statistics for this BlockID.
404 PerBlockIDStats &BlockStats = BlockIDStats[BlockID];
405
406 BlockStats.NumInstances++;
407
408 // BLOCKINFO is a special part of the stream.
409 if (BlockID == bitc::BLOCKINFO_BLOCK_ID) {
410 if (Dump) outs() << Indent << "<BLOCKINFO_BLOCK/>\n";
411 if (Stream.ReadBlockInfoBlock())
412 return Error("Malformed BlockInfoBlock");
413 uint64_t BlockBitEnd = Stream.GetCurrentBitNo();
414 BlockStats.NumBits += BlockBitEnd-BlockBitStart;
415 return false;
416 }
417
418 unsigned NumWords = 0;
419 if (Stream.EnterSubBlock(BlockID, &NumWords))
420 return Error("Malformed block record");
421
422 const char *BlockName = nullptr;
423 if (Dump) {
424 outs() << Indent << "<";
425 if ((BlockName = GetBlockName(BlockID, *Stream.getBitStreamReader(),
426 CurStreamType)))
427 outs() << BlockName;
428 else
429 outs() << "UnknownBlock" << BlockID;
430
431 if (NonSymbolic && BlockName)
432 outs() << " BlockID=" << BlockID;
433
434 outs() << " NumWords=" << NumWords
435 << " BlockCodeSize=" << Stream.getAbbrevIDWidth() << ">\n";
436 }
437
438 SmallVector<uint64_t, 64> Record;
439
440 // Read all the records for this block.
441 while (1) {
442 if (Stream.AtEndOfStream())
443 return Error("Premature end of bitstream");
444
445 uint64_t RecordStartBit = Stream.GetCurrentBitNo();
446
447 BitstreamEntry Entry =
448 Stream.advance(BitstreamCursor::AF_DontAutoprocessAbbrevs);
449
450 switch (Entry.Kind) {
451 case BitstreamEntry::Error:
452 return Error("malformed bitcode file");
453 case BitstreamEntry::EndBlock: {
454 uint64_t BlockBitEnd = Stream.GetCurrentBitNo();
455 BlockStats.NumBits += BlockBitEnd-BlockBitStart;
456 if (Dump) {
457 outs() << Indent << "</";
458 if (BlockName)
459 outs() << BlockName << ">\n";
460 else
461 outs() << "UnknownBlock" << BlockID << ">\n";
462 }
463 return false;
464 }
465
466 case BitstreamEntry::SubBlock: {
467 uint64_t SubBlockBitStart = Stream.GetCurrentBitNo();
468 if (ParseBlock(Stream, Entry.ID, IndentLevel+1, CurStreamType))
469 return true;
470 ++BlockStats.NumSubBlocks;
471 uint64_t SubBlockBitEnd = Stream.GetCurrentBitNo();
472
473 // Don't include subblock sizes in the size of this block.
474 BlockBitStart += SubBlockBitEnd-SubBlockBitStart;
475 continue;
476 }
477 case BitstreamEntry::Record:
478 // The interesting case.
479 break;
480 }
481
482 if (Entry.ID == bitc::DEFINE_ABBREV) {
483 Stream.ReadAbbrevRecord();
484 ++BlockStats.NumAbbrevs;
485 continue;
486 }
487
488 Record.clear();
489
490 ++BlockStats.NumRecords;
491
492 StringRef Blob;
493 unsigned Code = Stream.readRecord(Entry.ID, Record, &Blob);
494
495 // Increment the # occurrences of this code.
496 if (BlockStats.CodeFreq.size() <= Code)
497 BlockStats.CodeFreq.resize(Code+1);
498 BlockStats.CodeFreq[Code].NumInstances++;
499 BlockStats.CodeFreq[Code].TotalBits +=
500 Stream.GetCurrentBitNo()-RecordStartBit;
501 if (Entry.ID != bitc::UNABBREV_RECORD) {
502 BlockStats.CodeFreq[Code].NumAbbrev++;
503 ++BlockStats.NumAbbreviatedRecords;
504 }
505
506 if (Dump) {
507 outs() << Indent << " <";
508 if (const char *CodeName =
509 GetCodeName(Code, BlockID, *Stream.getBitStreamReader(),
510 CurStreamType))
511 outs() << CodeName;
512 else
513 outs() << "UnknownCode" << Code;
514 if (NonSymbolic &&
515 GetCodeName(Code, BlockID, *Stream.getBitStreamReader(),
516 CurStreamType))
517 outs() << " codeid=" << Code;
518 const BitCodeAbbrev *Abbv = nullptr;
519 if (Entry.ID != bitc::UNABBREV_RECORD) {
520 Abbv = Stream.getAbbrev(Entry.ID);
521 outs() << " abbrevid=" << Entry.ID;
522 }
523
524 for (unsigned i = 0, e = Record.size(); i != e; ++i)
525 outs() << " op" << i << "=" << (int64_t)Record[i];
526
527 outs() << "/>";
528
529 if (Abbv) {
530 for (unsigned i = 1, e = Abbv->getNumOperandInfos(); i != e; ++i) {
531 const BitCodeAbbrevOp &Op = Abbv->getOperandInfo(i);
532 if (!Op.isEncoding() || Op.getEncoding() != BitCodeAbbrevOp::Array)
533 continue;
534 assert(i + 2 == e && "Array op not second to last");
535 std::string Str;
536 bool ArrayIsPrintable = true;
537 for (unsigned j = i - 1, je = Record.size(); j != je; ++j) {
538 if (!isprint(static_cast<unsigned char>(Record[j]))) {
539 ArrayIsPrintable = false;
540 break;
541 }
542 Str += (char)Record[j];
543 }
544 if (ArrayIsPrintable)
545 outs() << " record string = '" << Str << "'";
546 break;
547 }
548 }
549
550 if (Blob.data()) {
551 outs() << " blob data = ";
552 if (ShowBinaryBlobs) {
553 outs() << "'";
554 outs().write_escaped(Blob, /*hex=*/true) << "'";
555 } else {
556 bool BlobIsPrintable = true;
557 for (unsigned i = 0, e = Blob.size(); i != e; ++i)
558 if (!isprint(static_cast<unsigned char>(Blob[i]))) {
559 BlobIsPrintable = false;
560 break;
561 }
562
563 if (BlobIsPrintable)
564 outs() << "'" << Blob << "'";
565 else
566 outs() << "unprintable, " << Blob.size() << " bytes.";
567 }
568 }
569
570 outs() << "\n";
571 }
572 }
573 }
574
PrintSize(double Bits)575 static void PrintSize(double Bits) {
576 outs() << format("%.2f/%.2fB/%luW", Bits, Bits/8,(unsigned long)(Bits/32));
577 }
PrintSize(uint64_t Bits)578 static void PrintSize(uint64_t Bits) {
579 outs() << format("%lub/%.2fB/%luW", (unsigned long)Bits,
580 (double)Bits/8, (unsigned long)(Bits/32));
581 }
582
openBitcodeFile(StringRef Path,std::unique_ptr<MemoryBuffer> & MemBuf,BitstreamReader & StreamFile,BitstreamCursor & Stream,CurStreamTypeType & CurStreamType)583 static bool openBitcodeFile(StringRef Path,
584 std::unique_ptr<MemoryBuffer> &MemBuf,
585 BitstreamReader &StreamFile,
586 BitstreamCursor &Stream,
587 CurStreamTypeType &CurStreamType) {
588 // Read the input file.
589 ErrorOr<std::unique_ptr<MemoryBuffer>> MemBufOrErr =
590 MemoryBuffer::getFileOrSTDIN(Path);
591 if (std::error_code EC = MemBufOrErr.getError())
592 return Error(Twine("Error reading '") + Path + "': " + EC.message());
593 MemBuf = std::move(MemBufOrErr.get());
594
595 if (MemBuf->getBufferSize() & 3)
596 return Error("Bitcode stream should be a multiple of 4 bytes in length");
597
598 const unsigned char *BufPtr = (const unsigned char *)MemBuf->getBufferStart();
599 const unsigned char *EndBufPtr = BufPtr + MemBuf->getBufferSize();
600
601 // If we have a wrapper header, parse it and ignore the non-bc file contents.
602 // The magic number is 0x0B17C0DE stored in little endian.
603 if (isBitcodeWrapper(BufPtr, EndBufPtr))
604 if (SkipBitcodeWrapperHeader(BufPtr, EndBufPtr, true))
605 return Error("Invalid bitcode wrapper header");
606
607 StreamFile = BitstreamReader(BufPtr, EndBufPtr);
608 Stream = BitstreamCursor(StreamFile);
609 StreamFile.CollectBlockInfoNames();
610
611 // Read the stream signature.
612 char Signature[6];
613 Signature[0] = Stream.Read(8);
614 Signature[1] = Stream.Read(8);
615 Signature[2] = Stream.Read(4);
616 Signature[3] = Stream.Read(4);
617 Signature[4] = Stream.Read(4);
618 Signature[5] = Stream.Read(4);
619
620 // Autodetect the file contents, if it is one we know.
621 CurStreamType = UnknownBitstream;
622 if (Signature[0] == 'B' && Signature[1] == 'C' &&
623 Signature[2] == 0x0 && Signature[3] == 0xC &&
624 Signature[4] == 0xE && Signature[5] == 0xD)
625 CurStreamType = LLVMIRBitstream;
626
627 return false;
628 }
629
630 /// AnalyzeBitcode - Analyze the bitcode file specified by InputFilename.
AnalyzeBitcode()631 static int AnalyzeBitcode() {
632 std::unique_ptr<MemoryBuffer> StreamBuffer;
633 BitstreamReader StreamFile;
634 BitstreamCursor Stream;
635 CurStreamTypeType CurStreamType;
636 if (openBitcodeFile(InputFilename, StreamBuffer, StreamFile, Stream,
637 CurStreamType))
638 return true;
639
640 // Read block info from BlockInfoFilename, if specified.
641 // The block info must be a top-level block.
642 if (!BlockInfoFilename.empty()) {
643 std::unique_ptr<MemoryBuffer> BlockInfoBuffer;
644 BitstreamReader BlockInfoFile;
645 BitstreamCursor BlockInfoCursor;
646 CurStreamTypeType BlockInfoStreamType;
647 if (openBitcodeFile(BlockInfoFilename, BlockInfoBuffer, BlockInfoFile,
648 BlockInfoCursor, BlockInfoStreamType))
649 return true;
650
651 while (!BlockInfoCursor.AtEndOfStream()) {
652 unsigned Code = BlockInfoCursor.ReadCode();
653 if (Code != bitc::ENTER_SUBBLOCK)
654 return Error("Invalid record at top-level in block info file");
655
656 unsigned BlockID = BlockInfoCursor.ReadSubBlockID();
657 if (BlockID == bitc::BLOCKINFO_BLOCK_ID) {
658 if (BlockInfoCursor.ReadBlockInfoBlock())
659 return Error("Malformed BlockInfoBlock in block info file");
660 break;
661 }
662
663 BlockInfoCursor.SkipBlock();
664 }
665
666 StreamFile.takeBlockInfo(std::move(BlockInfoFile));
667 }
668
669 unsigned NumTopBlocks = 0;
670
671 // Parse the top-level structure. We only allow blocks at the top-level.
672 while (!Stream.AtEndOfStream()) {
673 unsigned Code = Stream.ReadCode();
674 if (Code != bitc::ENTER_SUBBLOCK)
675 return Error("Invalid record at top-level");
676
677 unsigned BlockID = Stream.ReadSubBlockID();
678
679 if (ParseBlock(Stream, BlockID, 0, CurStreamType))
680 return true;
681 ++NumTopBlocks;
682 }
683
684 if (Dump) outs() << "\n\n";
685
686 uint64_t BufferSizeBits = StreamFile.getBitcodeBytes().getExtent() * CHAR_BIT;
687 // Print a summary of the read file.
688 outs() << "Summary of " << InputFilename << ":\n";
689 outs() << " Total size: ";
690 PrintSize(BufferSizeBits);
691 outs() << "\n";
692 outs() << " Stream type: ";
693 switch (CurStreamType) {
694 case UnknownBitstream: outs() << "unknown\n"; break;
695 case LLVMIRBitstream: outs() << "LLVM IR\n"; break;
696 }
697 outs() << " # Toplevel Blocks: " << NumTopBlocks << "\n";
698 outs() << "\n";
699
700 // Emit per-block stats.
701 outs() << "Per-block Summary:\n";
702 for (std::map<unsigned, PerBlockIDStats>::iterator I = BlockIDStats.begin(),
703 E = BlockIDStats.end(); I != E; ++I) {
704 outs() << " Block ID #" << I->first;
705 if (const char *BlockName = GetBlockName(I->first, StreamFile,
706 CurStreamType))
707 outs() << " (" << BlockName << ")";
708 outs() << ":\n";
709
710 const PerBlockIDStats &Stats = I->second;
711 outs() << " Num Instances: " << Stats.NumInstances << "\n";
712 outs() << " Total Size: ";
713 PrintSize(Stats.NumBits);
714 outs() << "\n";
715 double pct = (Stats.NumBits * 100.0) / BufferSizeBits;
716 outs() << " Percent of file: " << format("%2.4f%%", pct) << "\n";
717 if (Stats.NumInstances > 1) {
718 outs() << " Average Size: ";
719 PrintSize(Stats.NumBits/(double)Stats.NumInstances);
720 outs() << "\n";
721 outs() << " Tot/Avg SubBlocks: " << Stats.NumSubBlocks << "/"
722 << Stats.NumSubBlocks/(double)Stats.NumInstances << "\n";
723 outs() << " Tot/Avg Abbrevs: " << Stats.NumAbbrevs << "/"
724 << Stats.NumAbbrevs/(double)Stats.NumInstances << "\n";
725 outs() << " Tot/Avg Records: " << Stats.NumRecords << "/"
726 << Stats.NumRecords/(double)Stats.NumInstances << "\n";
727 } else {
728 outs() << " Num SubBlocks: " << Stats.NumSubBlocks << "\n";
729 outs() << " Num Abbrevs: " << Stats.NumAbbrevs << "\n";
730 outs() << " Num Records: " << Stats.NumRecords << "\n";
731 }
732 if (Stats.NumRecords) {
733 double pct = (Stats.NumAbbreviatedRecords * 100.0) / Stats.NumRecords;
734 outs() << " Percent Abbrevs: " << format("%2.4f%%", pct) << "\n";
735 }
736 outs() << "\n";
737
738 // Print a histogram of the codes we see.
739 if (!NoHistogram && !Stats.CodeFreq.empty()) {
740 std::vector<std::pair<unsigned, unsigned> > FreqPairs; // <freq,code>
741 for (unsigned i = 0, e = Stats.CodeFreq.size(); i != e; ++i)
742 if (unsigned Freq = Stats.CodeFreq[i].NumInstances)
743 FreqPairs.push_back(std::make_pair(Freq, i));
744 std::stable_sort(FreqPairs.begin(), FreqPairs.end());
745 std::reverse(FreqPairs.begin(), FreqPairs.end());
746
747 outs() << "\tRecord Histogram:\n";
748 outs() << "\t\t Count # Bits %% Abv Record Kind\n";
749 for (unsigned i = 0, e = FreqPairs.size(); i != e; ++i) {
750 const PerRecordStats &RecStats = Stats.CodeFreq[FreqPairs[i].second];
751
752 outs() << format("\t\t%7d %9lu",
753 RecStats.NumInstances,
754 (unsigned long)RecStats.TotalBits);
755
756 if (RecStats.NumAbbrev)
757 outs() <<
758 format("%7.2f ",
759 (double)RecStats.NumAbbrev/RecStats.NumInstances*100);
760 else
761 outs() << " ";
762
763 if (const char *CodeName =
764 GetCodeName(FreqPairs[i].second, I->first, StreamFile,
765 CurStreamType))
766 outs() << CodeName << "\n";
767 else
768 outs() << "UnknownCode" << FreqPairs[i].second << "\n";
769 }
770 outs() << "\n";
771
772 }
773 }
774 return 0;
775 }
776
777
main(int argc,char ** argv)778 int main(int argc, char **argv) {
779 // Print a stack trace if we signal out.
780 sys::PrintStackTraceOnErrorSignal();
781 PrettyStackTraceProgram X(argc, argv);
782 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
783 cl::ParseCommandLineOptions(argc, argv, "llvm-bcanalyzer file analyzer\n");
784
785 return AnalyzeBitcode();
786 }
787