blob: c6518a24f4385c68e032be51910a5e437d6fb9c6 [file] [log] [blame]
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001//===-- llvm-bcanalyzer.cpp - Bitcode Analyzer --------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5f5a5732007-12-29 20:44:31 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007//
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/Analysis/Verifier.h"
31#include "llvm/Bitcode/BitstreamReader.h"
32#include "llvm/Bitcode/LLVMBitCodes.h"
33#include "llvm/Support/CommandLine.h"
34#include "llvm/Support/ManagedStatic.h"
35#include "llvm/Support/MemoryBuffer.h"
36#include "llvm/System/Signals.h"
37#include <map>
38#include <fstream>
39#include <iostream>
40#include <algorithm>
41using namespace llvm;
42
43static cl::opt<std::string>
44 InputFilename(cl::Positional, cl::desc("<input bitcode>"), cl::init("-"));
45
46static cl::opt<std::string>
47 OutputFilename("-o", cl::init("-"), cl::desc("<output file>"));
48
49static cl::opt<bool> Dump("dump", cl::desc("Dump low level bitcode trace"));
50
51//===----------------------------------------------------------------------===//
52// Bitcode specific analysis.
53//===----------------------------------------------------------------------===//
54
55static cl::opt<bool> NoHistogram("disable-histogram",
56 cl::desc("Do not print per-code histogram"));
57
58static cl::opt<bool>
59NonSymbolic("non-symbolic",
60 cl::desc("Emit numberic info in dump even if"
61 " symbolic info is available"));
62
63/// CurStreamType - If we can sniff the flavor of this stream, we can produce
64/// better dump info.
65static enum {
66 UnknownBitstream,
67 LLVMIRBitstream
68} CurStreamType;
69
70
71/// GetBlockName - Return a symbolic block name if known, otherwise return
72/// null.
73static const char *GetBlockName(unsigned BlockID) {
74 // Standard blocks for all bitcode files.
75 if (BlockID < bitc::FIRST_APPLICATION_BLOCKID) {
76 if (BlockID == bitc::BLOCKINFO_BLOCK_ID)
77 return "BLOCKINFO_BLOCK";
78 return 0;
79 }
80
81 if (CurStreamType != LLVMIRBitstream) return 0;
82
83 switch (BlockID) {
84 default: return 0;
85 case bitc::MODULE_BLOCK_ID: return "MODULE_BLOCK";
86 case bitc::PARAMATTR_BLOCK_ID: return "PARAMATTR_BLOCK";
87 case bitc::TYPE_BLOCK_ID: return "TYPE_BLOCK";
88 case bitc::CONSTANTS_BLOCK_ID: return "CONSTANTS_BLOCK";
89 case bitc::FUNCTION_BLOCK_ID: return "FUNCTION_BLOCK";
90 case bitc::TYPE_SYMTAB_BLOCK_ID: return "TYPE_SYMTAB";
91 case bitc::VALUE_SYMTAB_BLOCK_ID: return "VALUE_SYMTAB";
92 }
93}
94
95/// GetCodeName - Return a symbolic code name if known, otherwise return
96/// null.
97static const char *GetCodeName(unsigned CodeID, unsigned BlockID) {
98 // Standard blocks for all bitcode files.
99 if (BlockID < bitc::FIRST_APPLICATION_BLOCKID) {
100 if (BlockID == bitc::BLOCKINFO_BLOCK_ID) {
101 switch (CodeID) {
102 default: return 0;
103 case bitc::MODULE_CODE_VERSION: return "VERSION";
104 }
105 }
106 return 0;
107 }
108
109 if (CurStreamType != LLVMIRBitstream) return 0;
110
111 switch (BlockID) {
112 default: return 0;
113 case bitc::MODULE_BLOCK_ID:
114 switch (CodeID) {
115 default: return 0;
116 case bitc::MODULE_CODE_VERSION: return "VERSION";
117 case bitc::MODULE_CODE_TRIPLE: return "TRIPLE";
118 case bitc::MODULE_CODE_DATALAYOUT: return "DATALAYOUT";
119 case bitc::MODULE_CODE_ASM: return "ASM";
120 case bitc::MODULE_CODE_SECTIONNAME: return "SECTIONNAME";
121 case bitc::MODULE_CODE_DEPLIB: return "DEPLIB";
122 case bitc::MODULE_CODE_GLOBALVAR: return "GLOBALVAR";
123 case bitc::MODULE_CODE_FUNCTION: return "FUNCTION";
124 case bitc::MODULE_CODE_ALIAS: return "ALIAS";
125 case bitc::MODULE_CODE_PURGEVALS: return "PURGEVALS";
126 }
127 case bitc::PARAMATTR_BLOCK_ID:
128 switch (CodeID) {
129 default: return 0;
130 case bitc::PARAMATTR_CODE_ENTRY: return "ENTRY";
131 }
132 case bitc::TYPE_BLOCK_ID:
133 switch (CodeID) {
134 default: return 0;
135 case bitc::TYPE_CODE_NUMENTRY: return "NUMENTRY";
136 case bitc::TYPE_CODE_VOID: return "VOID";
137 case bitc::TYPE_CODE_FLOAT: return "FLOAT";
138 case bitc::TYPE_CODE_DOUBLE: return "DOUBLE";
139 case bitc::TYPE_CODE_LABEL: return "LABEL";
140 case bitc::TYPE_CODE_OPAQUE: return "OPAQUE";
141 case bitc::TYPE_CODE_INTEGER: return "INTEGER";
142 case bitc::TYPE_CODE_POINTER: return "POINTER";
143 case bitc::TYPE_CODE_FUNCTION: return "FUNCTION";
144 case bitc::TYPE_CODE_STRUCT: return "STRUCT";
145 case bitc::TYPE_CODE_ARRAY: return "ARRAY";
146 case bitc::TYPE_CODE_VECTOR: return "VECTOR";
147 }
148
149 case bitc::CONSTANTS_BLOCK_ID:
150 switch (CodeID) {
151 default: return 0;
152 case bitc::CST_CODE_SETTYPE: return "SETTYPE";
153 case bitc::CST_CODE_NULL: return "NULL";
154 case bitc::CST_CODE_UNDEF: return "UNDEF";
155 case bitc::CST_CODE_INTEGER: return "INTEGER";
156 case bitc::CST_CODE_WIDE_INTEGER: return "WIDE_INTEGER";
157 case bitc::CST_CODE_FLOAT: return "FLOAT";
158 case bitc::CST_CODE_AGGREGATE: return "AGGREGATE";
159 case bitc::CST_CODE_STRING: return "STRING";
160 case bitc::CST_CODE_CSTRING: return "CSTRING";
161 case bitc::CST_CODE_CE_BINOP: return "CE_BINOP";
162 case bitc::CST_CODE_CE_CAST: return "CE_CAST";
163 case bitc::CST_CODE_CE_GEP: return "CE_GEP";
164 case bitc::CST_CODE_CE_SELECT: return "CE_SELECT";
165 case bitc::CST_CODE_CE_EXTRACTELT: return "CE_EXTRACTELT";
166 case bitc::CST_CODE_CE_INSERTELT: return "CE_INSERTELT";
167 case bitc::CST_CODE_CE_SHUFFLEVEC: return "CE_SHUFFLEVEC";
168 case bitc::CST_CODE_CE_CMP: return "CE_CMP";
169 case bitc::CST_CODE_INLINEASM: return "INLINEASM";
170 }
171 case bitc::FUNCTION_BLOCK_ID:
172 switch (CodeID) {
173 default: return 0;
174 case bitc::FUNC_CODE_DECLAREBLOCKS: return "DECLAREBLOCKS";
Nick Lewycky31f5f242008-03-02 02:48:09 +0000175 case bitc::FUNC_CODE_INST_BB_UNWINDDEST: return "UNWINDDEST";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000176
177 case bitc::FUNC_CODE_INST_BINOP: return "INST_BINOP";
178 case bitc::FUNC_CODE_INST_CAST: return "INST_CAST";
179 case bitc::FUNC_CODE_INST_GEP: return "INST_GEP";
180 case bitc::FUNC_CODE_INST_SELECT: return "INST_SELECT";
181 case bitc::FUNC_CODE_INST_EXTRACTELT: return "INST_EXTRACTELT";
182 case bitc::FUNC_CODE_INST_INSERTELT: return "INST_INSERTELT";
183 case bitc::FUNC_CODE_INST_SHUFFLEVEC: return "INST_SHUFFLEVEC";
184 case bitc::FUNC_CODE_INST_CMP: return "INST_CMP";
185
186 case bitc::FUNC_CODE_INST_RET: return "INST_RET";
187 case bitc::FUNC_CODE_INST_BR: return "INST_BR";
188 case bitc::FUNC_CODE_INST_SWITCH: return "INST_SWITCH";
189 case bitc::FUNC_CODE_INST_INVOKE: return "INST_INVOKE";
190 case bitc::FUNC_CODE_INST_UNWIND: return "INST_UNWIND";
191 case bitc::FUNC_CODE_INST_UNREACHABLE: return "INST_UNREACHABLE";
192
193 case bitc::FUNC_CODE_INST_PHI: return "INST_PHI";
194 case bitc::FUNC_CODE_INST_MALLOC: return "INST_MALLOC";
195 case bitc::FUNC_CODE_INST_FREE: return "INST_FREE";
196 case bitc::FUNC_CODE_INST_ALLOCA: return "INST_ALLOCA";
197 case bitc::FUNC_CODE_INST_LOAD: return "INST_LOAD";
198 case bitc::FUNC_CODE_INST_STORE: return "INST_STORE";
199 case bitc::FUNC_CODE_INST_CALL: return "INST_CALL";
200 case bitc::FUNC_CODE_INST_VAARG: return "INST_VAARG";
Christopher Lamb44d62f62007-12-11 08:59:05 +0000201 case bitc::FUNC_CODE_INST_STORE2: return "INST_STORE2";
Nick Lewycky2c3eced2008-03-01 21:47:06 +0000202 case bitc::FUNC_CODE_INST_GETRESULT: return "INST_GETRESULT";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000203 }
204 case bitc::TYPE_SYMTAB_BLOCK_ID:
205 switch (CodeID) {
206 default: return 0;
207 case bitc::TST_CODE_ENTRY: return "ENTRY";
208 }
209 case bitc::VALUE_SYMTAB_BLOCK_ID:
210 switch (CodeID) {
211 default: return 0;
212 case bitc::VST_CODE_ENTRY: return "ENTRY";
213 case bitc::VST_CODE_BBENTRY: return "BBENTRY";
214 }
215 }
216}
217
218
219struct PerBlockIDStats {
220 /// NumInstances - This the number of times this block ID has been seen.
221 unsigned NumInstances;
222
223 /// NumBits - The total size in bits of all of these blocks.
224 uint64_t NumBits;
225
226 /// NumSubBlocks - The total number of blocks these blocks contain.
227 unsigned NumSubBlocks;
228
229 /// NumAbbrevs - The total number of abbreviations.
230 unsigned NumAbbrevs;
231
232 /// NumRecords - The total number of records these blocks contain, and the
233 /// number that are abbreviated.
234 unsigned NumRecords, NumAbbreviatedRecords;
235
236 /// CodeFreq - Keep track of the number of times we see each code.
237 std::vector<unsigned> CodeFreq;
238
239 PerBlockIDStats()
240 : NumInstances(0), NumBits(0),
241 NumSubBlocks(0), NumAbbrevs(0), NumRecords(0), NumAbbreviatedRecords(0) {}
242};
243
244static std::map<unsigned, PerBlockIDStats> BlockIDStats;
245
246
247
248/// Error - All bitcode analysis errors go through this function, making this a
249/// good place to breakpoint if debugging.
250static bool Error(const std::string &Err) {
251 std::cerr << Err << "\n";
252 return true;
253}
254
255/// ParseBlock - Read a block, updating statistics, etc.
256static bool ParseBlock(BitstreamReader &Stream, unsigned IndentLevel) {
257 std::string Indent(IndentLevel*2, ' ');
258 uint64_t BlockBitStart = Stream.GetCurrentBitNo();
259 unsigned BlockID = Stream.ReadSubBlockID();
260
261 // Get the statistics for this BlockID.
262 PerBlockIDStats &BlockStats = BlockIDStats[BlockID];
263
264 BlockStats.NumInstances++;
265
266 // BLOCKINFO is a special part of the stream.
267 if (BlockID == bitc::BLOCKINFO_BLOCK_ID) {
268 if (Dump) std::cerr << Indent << "<BLOCKINFO_BLOCK/>\n";
269 if (Stream.ReadBlockInfoBlock())
270 return Error("Malformed BlockInfoBlock");
271 uint64_t BlockBitEnd = Stream.GetCurrentBitNo();
272 BlockStats.NumBits += BlockBitEnd-BlockBitStart;
273 return false;
274 }
275
276 unsigned NumWords = 0;
277 if (Stream.EnterSubBlock(BlockID, &NumWords))
278 return Error("Malformed block record");
279
280 const char *BlockName = 0;
281 if (Dump) {
282 std::cerr << Indent << "<";
283 if ((BlockName = GetBlockName(BlockID)))
284 std::cerr << BlockName;
285 else
286 std::cerr << "UnknownBlock" << BlockID;
287
288 if (NonSymbolic && BlockName)
289 std::cerr << " BlockID=" << BlockID;
290
291 std::cerr << " NumWords=" << NumWords
292 << " BlockCodeSize=" << Stream.GetAbbrevIDWidth() << ">\n";
293 }
294
295 SmallVector<uint64_t, 64> Record;
296
297 // Read all the records for this block.
298 while (1) {
299 if (Stream.AtEndOfStream())
300 return Error("Premature end of bitstream");
301
302 // Read the code for this record.
303 unsigned AbbrevID = Stream.ReadCode();
304 switch (AbbrevID) {
305 case bitc::END_BLOCK: {
306 if (Stream.ReadBlockEnd())
307 return Error("Error at end of block");
308 uint64_t BlockBitEnd = Stream.GetCurrentBitNo();
309 BlockStats.NumBits += BlockBitEnd-BlockBitStart;
310 if (Dump) {
311 std::cerr << Indent << "</";
312 if (BlockName)
313 std::cerr << BlockName << ">\n";
314 else
315 std::cerr << "UnknownBlock" << BlockID << ">\n";
316 }
317 return false;
318 }
319 case bitc::ENTER_SUBBLOCK: {
320 uint64_t SubBlockBitStart = Stream.GetCurrentBitNo();
321 if (ParseBlock(Stream, IndentLevel+1))
322 return true;
323 ++BlockStats.NumSubBlocks;
324 uint64_t SubBlockBitEnd = Stream.GetCurrentBitNo();
325
326 // Don't include subblock sizes in the size of this block.
327 BlockBitStart += SubBlockBitEnd-SubBlockBitStart;
328 break;
329 }
330 case bitc::DEFINE_ABBREV:
331 Stream.ReadAbbrevRecord();
332 ++BlockStats.NumAbbrevs;
333 break;
334 default:
335 ++BlockStats.NumRecords;
336 if (AbbrevID != bitc::UNABBREV_RECORD)
337 ++BlockStats.NumAbbreviatedRecords;
338
339 Record.clear();
340 unsigned Code = Stream.ReadRecord(AbbrevID, Record);
341
342 // Increment the # occurrences of this code.
343 if (BlockStats.CodeFreq.size() <= Code)
344 BlockStats.CodeFreq.resize(Code+1);
345 BlockStats.CodeFreq[Code]++;
346
347 if (Dump) {
348 std::cerr << Indent << " <";
349 if (const char *CodeName = GetCodeName(Code, BlockID))
350 std::cerr << CodeName;
351 else
352 std::cerr << "UnknownCode" << Code;
353 if (NonSymbolic && GetCodeName(Code, BlockID))
354 std::cerr << " codeid=" << Code;
355 if (AbbrevID != bitc::UNABBREV_RECORD)
356 std::cerr << " abbrevid=" << AbbrevID;
357
358 for (unsigned i = 0, e = Record.size(); i != e; ++i)
359 std::cerr << " op" << i << "=" << (int64_t)Record[i];
360
361 std::cerr << "/>\n";
362 }
363
364 break;
365 }
366 }
367}
368
369static void PrintSize(double Bits) {
370 std::cerr << Bits << "b/" << Bits/8 << "B/" << Bits/32 << "W";
371}
372
373
374/// AnalyzeBitcode - Analyze the bitcode file specified by InputFilename.
375static int AnalyzeBitcode() {
376 // Read the input file.
377 MemoryBuffer *Buffer;
378 if (InputFilename == "-")
379 Buffer = MemoryBuffer::getSTDIN();
380 else
381 Buffer = MemoryBuffer::getFile(&InputFilename[0], InputFilename.size());
382
383 if (Buffer == 0)
384 return Error("Error reading '" + InputFilename + "'.");
385
386 if (Buffer->getBufferSize() & 3)
387 return Error("Bitcode stream should be a multiple of 4 bytes in length");
388
389 unsigned char *BufPtr = (unsigned char *)Buffer->getBufferStart();
390 BitstreamReader Stream(BufPtr, BufPtr+Buffer->getBufferSize());
391
392
393 // Read the stream signature.
394 char Signature[6];
395 Signature[0] = Stream.Read(8);
396 Signature[1] = Stream.Read(8);
397 Signature[2] = Stream.Read(4);
398 Signature[3] = Stream.Read(4);
399 Signature[4] = Stream.Read(4);
400 Signature[5] = Stream.Read(4);
401
402 // Autodetect the file contents, if it is one we know.
403 CurStreamType = UnknownBitstream;
404 if (Signature[0] == 'B' && Signature[1] == 'C' &&
405 Signature[2] == 0x0 && Signature[3] == 0xC &&
406 Signature[4] == 0xE && Signature[5] == 0xD)
407 CurStreamType = LLVMIRBitstream;
408
409 unsigned NumTopBlocks = 0;
410
411 // Parse the top-level structure. We only allow blocks at the top-level.
412 while (!Stream.AtEndOfStream()) {
413 unsigned Code = Stream.ReadCode();
414 if (Code != bitc::ENTER_SUBBLOCK)
415 return Error("Invalid record at top-level");
416
417 if (ParseBlock(Stream, 0))
418 return true;
419 ++NumTopBlocks;
420 }
421
422 if (Dump) std::cerr << "\n\n";
423
424 uint64_t BufferSizeBits = Buffer->getBufferSize()*8;
425 // Print a summary of the read file.
426 std::cerr << "Summary of " << InputFilename << ":\n";
427 std::cerr << " Total size: ";
428 PrintSize(BufferSizeBits);
429 std::cerr << "\n";
430 std::cerr << " Stream type: ";
431 switch (CurStreamType) {
432 default: assert(0 && "Unknown bitstream type");
433 case UnknownBitstream: std::cerr << "unknown\n"; break;
434 case LLVMIRBitstream: std::cerr << "LLVM IR\n"; break;
435 }
436 std::cerr << " # Toplevel Blocks: " << NumTopBlocks << "\n";
437 std::cerr << "\n";
438
439 // Emit per-block stats.
440 std::cerr << "Per-block Summary:\n";
441 for (std::map<unsigned, PerBlockIDStats>::iterator I = BlockIDStats.begin(),
442 E = BlockIDStats.end(); I != E; ++I) {
443 std::cerr << " Block ID #" << I->first;
444 if (const char *BlockName = GetBlockName(I->first))
445 std::cerr << " (" << BlockName << ")";
446 std::cerr << ":\n";
447
448 const PerBlockIDStats &Stats = I->second;
449 std::cerr << " Num Instances: " << Stats.NumInstances << "\n";
450 std::cerr << " Total Size: ";
451 PrintSize(Stats.NumBits);
452 std::cerr << "\n";
453 std::cerr << " % of file: "
454 << Stats.NumBits/(double)BufferSizeBits*100 << "\n";
455 if (Stats.NumInstances > 1) {
456 std::cerr << " Average Size: ";
457 PrintSize(Stats.NumBits/(double)Stats.NumInstances);
458 std::cerr << "\n";
459 std::cerr << " Tot/Avg SubBlocks: " << Stats.NumSubBlocks << "/"
460 << Stats.NumSubBlocks/(double)Stats.NumInstances << "\n";
461 std::cerr << " Tot/Avg Abbrevs: " << Stats.NumAbbrevs << "/"
462 << Stats.NumAbbrevs/(double)Stats.NumInstances << "\n";
463 std::cerr << " Tot/Avg Records: " << Stats.NumRecords << "/"
464 << Stats.NumRecords/(double)Stats.NumInstances << "\n";
465 } else {
466 std::cerr << " Num SubBlocks: " << Stats.NumSubBlocks << "\n";
467 std::cerr << " Num Abbrevs: " << Stats.NumAbbrevs << "\n";
468 std::cerr << " Num Records: " << Stats.NumRecords << "\n";
469 }
470 if (Stats.NumRecords)
471 std::cerr << " % Abbrev Recs: " << (Stats.NumAbbreviatedRecords/
472 (double)Stats.NumRecords)*100 << "\n";
473 std::cerr << "\n";
474
475 // Print a histogram of the codes we see.
476 if (!NoHistogram && !Stats.CodeFreq.empty()) {
477 std::vector<std::pair<unsigned, unsigned> > FreqPairs; // <freq,code>
478 for (unsigned i = 0, e = Stats.CodeFreq.size(); i != e; ++i)
479 if (unsigned Freq = Stats.CodeFreq[i])
480 FreqPairs.push_back(std::make_pair(Freq, i));
481 std::stable_sort(FreqPairs.begin(), FreqPairs.end());
482 std::reverse(FreqPairs.begin(), FreqPairs.end());
483
484 std::cerr << "\tCode Histogram:\n";
485 for (unsigned i = 0, e = FreqPairs.size(); i != e; ++i) {
486 std::cerr << "\t\t" << FreqPairs[i].first << "\t";
487 if (const char *CodeName = GetCodeName(FreqPairs[i].second, I->first))
488 std::cerr << CodeName << "\n";
489 else
490 std::cerr << "UnknownCode" << FreqPairs[i].second << "\n";
491 }
492 std::cerr << "\n";
493
494 }
495 }
496 return 0;
497}
498
499
500int main(int argc, char **argv) {
501 llvm_shutdown_obj X; // Call llvm_shutdown() on exit.
Dan Gohman6099df82007-10-08 15:45:12 +0000502 cl::ParseCommandLineOptions(argc, argv, "llvm-bcanalyzer file analyzer\n");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000503
504 sys::PrintStackTraceOnErrorSignal();
505
506 return AnalyzeBitcode();
507}