Regen configure
[oota-llvm.git] / tools / llvm-bcanalyzer / llvm-bcanalyzer.cpp
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/Analysis/Verifier.h"
31 #include "llvm/Bitcode/BitstreamReader.h"
32 #include "llvm/Bitcode/LLVMBitCodes.h"
33 #include "llvm/Bitcode/ReaderWriter.h"
34 #include "llvm/Support/CommandLine.h"
35 #include "llvm/Support/Format.h"
36 #include "llvm/Support/ManagedStatic.h"
37 #include "llvm/Support/MemoryBuffer.h"
38 #include "llvm/Support/PrettyStackTrace.h"
39 #include "llvm/Support/raw_ostream.h"
40 #include "llvm/Support/Signals.h"
41 #include "llvm/Support/system_error.h"
42 #include <cstdio>
43 #include <map>
44 #include <algorithm>
45 using namespace llvm;
46
47 static cl::opt<std::string>
48   InputFilename(cl::Positional, cl::desc("<input bitcode>"), cl::init("-"));
49
50 static cl::opt<bool> Dump("dump", cl::desc("Dump low level bitcode trace"));
51
52 //===----------------------------------------------------------------------===//
53 // Bitcode specific analysis.
54 //===----------------------------------------------------------------------===//
55
56 static cl::opt<bool> NoHistogram("disable-histogram",
57                                  cl::desc("Do not print per-code histogram"));
58
59 static cl::opt<bool>
60 NonSymbolic("non-symbolic",
61             cl::desc("Emit numberic info in dump even if"
62                      " symbolic info is available"));
63
64 namespace {
65
66 /// CurStreamTypeType - A type for CurStreamType
67 enum CurStreamTypeType {
68   UnknownBitstream,
69   LLVMIRBitstream
70 };
71
72 }
73
74 /// CurStreamType - If we can sniff the flavor of this stream, we can produce
75 /// better dump info.
76 static CurStreamTypeType CurStreamType;
77
78
79 /// GetBlockName - Return a symbolic block name if known, otherwise return
80 /// null.
81 static const char *GetBlockName(unsigned BlockID,
82                                 const BitstreamReader &StreamFile) {
83   // Standard blocks for all bitcode files.
84   if (BlockID < bitc::FIRST_APPLICATION_BLOCKID) {
85     if (BlockID == bitc::BLOCKINFO_BLOCK_ID)
86       return "BLOCKINFO_BLOCK";
87     return 0;
88   }
89
90   // Check to see if we have a blockinfo record for this block, with a name.
91   if (const BitstreamReader::BlockInfo *Info =
92         StreamFile.getBlockInfo(BlockID)) {
93     if (!Info->Name.empty())
94       return Info->Name.c_str();
95   }
96
97
98   if (CurStreamType != LLVMIRBitstream) return 0;
99
100   switch (BlockID) {
101   default:                           return 0;
102   case bitc::MODULE_BLOCK_ID:        return "MODULE_BLOCK";
103   case bitc::PARAMATTR_BLOCK_ID:     return "PARAMATTR_BLOCK";
104   case bitc::TYPE_BLOCK_ID:          return "TYPE_BLOCK";
105   case bitc::CONSTANTS_BLOCK_ID:     return "CONSTANTS_BLOCK";
106   case bitc::FUNCTION_BLOCK_ID:      return "FUNCTION_BLOCK";
107   case bitc::TYPE_SYMTAB_BLOCK_ID:   return "TYPE_SYMTAB";
108   case bitc::VALUE_SYMTAB_BLOCK_ID:  return "VALUE_SYMTAB";
109   case bitc::METADATA_BLOCK_ID:      return "METADATA_BLOCK";
110   case bitc::METADATA_ATTACHMENT_ID: return "METADATA_ATTACHMENT_BLOCK";
111   }
112 }
113
114 /// GetCodeName - Return a symbolic code name if known, otherwise return
115 /// null.
116 static const char *GetCodeName(unsigned CodeID, unsigned BlockID,
117                                const BitstreamReader &StreamFile) {
118   // Standard blocks for all bitcode files.
119   if (BlockID < bitc::FIRST_APPLICATION_BLOCKID) {
120     if (BlockID == bitc::BLOCKINFO_BLOCK_ID) {
121       switch (CodeID) {
122       default: return 0;
123       case bitc::BLOCKINFO_CODE_SETBID:        return "SETBID";
124       case bitc::BLOCKINFO_CODE_BLOCKNAME:     return "BLOCKNAME";
125       case bitc::BLOCKINFO_CODE_SETRECORDNAME: return "SETRECORDNAME";
126       }
127     }
128     return 0;
129   }
130
131   // Check to see if we have a blockinfo record for this record, with a name.
132   if (const BitstreamReader::BlockInfo *Info =
133         StreamFile.getBlockInfo(BlockID)) {
134     for (unsigned i = 0, e = Info->RecordNames.size(); i != e; ++i)
135       if (Info->RecordNames[i].first == CodeID)
136         return Info->RecordNames[i].second.c_str();
137   }
138
139
140   if (CurStreamType != LLVMIRBitstream) return 0;
141
142   switch (BlockID) {
143   default: return 0;
144   case bitc::MODULE_BLOCK_ID:
145     switch (CodeID) {
146     default: return 0;
147     case bitc::MODULE_CODE_VERSION:     return "VERSION";
148     case bitc::MODULE_CODE_TRIPLE:      return "TRIPLE";
149     case bitc::MODULE_CODE_DATALAYOUT:  return "DATALAYOUT";
150     case bitc::MODULE_CODE_ASM:         return "ASM";
151     case bitc::MODULE_CODE_SECTIONNAME: return "SECTIONNAME";
152     case bitc::MODULE_CODE_DEPLIB:      return "DEPLIB";
153     case bitc::MODULE_CODE_GLOBALVAR:   return "GLOBALVAR";
154     case bitc::MODULE_CODE_FUNCTION:    return "FUNCTION";
155     case bitc::MODULE_CODE_ALIAS:       return "ALIAS";
156     case bitc::MODULE_CODE_PURGEVALS:   return "PURGEVALS";
157     case bitc::MODULE_CODE_GCNAME:      return "GCNAME";
158     }
159   case bitc::PARAMATTR_BLOCK_ID:
160     switch (CodeID) {
161     default: return 0;
162     case bitc::PARAMATTR_CODE_ENTRY: return "ENTRY";
163     }
164   case bitc::TYPE_BLOCK_ID:
165     switch (CodeID) {
166     default: return 0;
167     case bitc::TYPE_CODE_NUMENTRY:  return "NUMENTRY";
168     case bitc::TYPE_CODE_VOID:      return "VOID";
169     case bitc::TYPE_CODE_FLOAT:     return "FLOAT";
170     case bitc::TYPE_CODE_DOUBLE:    return "DOUBLE";
171     case bitc::TYPE_CODE_LABEL:     return "LABEL";
172     case bitc::TYPE_CODE_OPAQUE:    return "OPAQUE";
173     case bitc::TYPE_CODE_INTEGER:   return "INTEGER";
174     case bitc::TYPE_CODE_POINTER:   return "POINTER";
175     case bitc::TYPE_CODE_FUNCTION:  return "FUNCTION";
176     case bitc::TYPE_CODE_STRUCT:    return "STRUCT";
177     case bitc::TYPE_CODE_ARRAY:     return "ARRAY";
178     case bitc::TYPE_CODE_VECTOR:    return "VECTOR";
179     case bitc::TYPE_CODE_X86_FP80:  return "X86_FP80";
180     case bitc::TYPE_CODE_FP128:     return "FP128";
181     case bitc::TYPE_CODE_PPC_FP128: return "PPC_FP128";
182     case bitc::TYPE_CODE_METADATA:  return "METADATA";
183     }
184
185   case bitc::CONSTANTS_BLOCK_ID:
186     switch (CodeID) {
187     default: return 0;
188     case bitc::CST_CODE_SETTYPE:         return "SETTYPE";
189     case bitc::CST_CODE_NULL:            return "NULL";
190     case bitc::CST_CODE_UNDEF:           return "UNDEF";
191     case bitc::CST_CODE_INTEGER:         return "INTEGER";
192     case bitc::CST_CODE_WIDE_INTEGER:    return "WIDE_INTEGER";
193     case bitc::CST_CODE_FLOAT:           return "FLOAT";
194     case bitc::CST_CODE_AGGREGATE:       return "AGGREGATE";
195     case bitc::CST_CODE_STRING:          return "STRING";
196     case bitc::CST_CODE_CSTRING:         return "CSTRING";
197     case bitc::CST_CODE_CE_BINOP:        return "CE_BINOP";
198     case bitc::CST_CODE_CE_CAST:         return "CE_CAST";
199     case bitc::CST_CODE_CE_GEP:          return "CE_GEP";
200     case bitc::CST_CODE_CE_INBOUNDS_GEP: return "CE_INBOUNDS_GEP";
201     case bitc::CST_CODE_CE_SELECT:       return "CE_SELECT";
202     case bitc::CST_CODE_CE_EXTRACTELT:   return "CE_EXTRACTELT";
203     case bitc::CST_CODE_CE_INSERTELT:    return "CE_INSERTELT";
204     case bitc::CST_CODE_CE_SHUFFLEVEC:   return "CE_SHUFFLEVEC";
205     case bitc::CST_CODE_CE_CMP:          return "CE_CMP";
206     case bitc::CST_CODE_INLINEASM:       return "INLINEASM";
207     case bitc::CST_CODE_CE_SHUFVEC_EX:   return "CE_SHUFVEC_EX";
208     }
209   case bitc::FUNCTION_BLOCK_ID:
210     switch (CodeID) {
211     default: return 0;
212     case bitc::FUNC_CODE_DECLAREBLOCKS: return "DECLAREBLOCKS";
213
214     case bitc::FUNC_CODE_INST_BINOP:        return "INST_BINOP";
215     case bitc::FUNC_CODE_INST_CAST:         return "INST_CAST";
216     case bitc::FUNC_CODE_INST_GEP:          return "INST_GEP";
217     case bitc::FUNC_CODE_INST_INBOUNDS_GEP: return "INST_INBOUNDS_GEP";
218     case bitc::FUNC_CODE_INST_SELECT:       return "INST_SELECT";
219     case bitc::FUNC_CODE_INST_EXTRACTELT:   return "INST_EXTRACTELT";
220     case bitc::FUNC_CODE_INST_INSERTELT:    return "INST_INSERTELT";
221     case bitc::FUNC_CODE_INST_SHUFFLEVEC:   return "INST_SHUFFLEVEC";
222     case bitc::FUNC_CODE_INST_CMP:          return "INST_CMP";
223
224     case bitc::FUNC_CODE_INST_RET:          return "INST_RET";
225     case bitc::FUNC_CODE_INST_BR:           return "INST_BR";
226     case bitc::FUNC_CODE_INST_SWITCH:       return "INST_SWITCH";
227     case bitc::FUNC_CODE_INST_INVOKE:       return "INST_INVOKE";
228     case bitc::FUNC_CODE_INST_UNWIND:       return "INST_UNWIND";
229     case bitc::FUNC_CODE_INST_UNREACHABLE:  return "INST_UNREACHABLE";
230
231     case bitc::FUNC_CODE_INST_PHI:          return "INST_PHI";
232     case bitc::FUNC_CODE_INST_MALLOC:       return "INST_MALLOC";
233     case bitc::FUNC_CODE_INST_FREE:         return "INST_FREE";
234     case bitc::FUNC_CODE_INST_ALLOCA:       return "INST_ALLOCA";
235     case bitc::FUNC_CODE_INST_LOAD:         return "INST_LOAD";
236     case bitc::FUNC_CODE_INST_STORE:        return "INST_STORE";
237     case bitc::FUNC_CODE_INST_CALL:         return "INST_CALL";
238     case bitc::FUNC_CODE_INST_VAARG:        return "INST_VAARG";
239     case bitc::FUNC_CODE_INST_STORE2:       return "INST_STORE2";
240     case bitc::FUNC_CODE_INST_GETRESULT:    return "INST_GETRESULT";
241     case bitc::FUNC_CODE_INST_EXTRACTVAL:   return "INST_EXTRACTVAL";
242     case bitc::FUNC_CODE_INST_INSERTVAL:    return "INST_INSERTVAL";
243     case bitc::FUNC_CODE_INST_CMP2:         return "INST_CMP2";
244     case bitc::FUNC_CODE_INST_VSELECT:      return "INST_VSELECT";
245     case bitc::FUNC_CODE_DEBUG_LOC:         return "DEBUG_LOC";
246     case bitc::FUNC_CODE_DEBUG_LOC_AGAIN:   return "DEBUG_LOC_AGAIN";
247     case bitc::FUNC_CODE_INST_CALL2:        return "INST_CALL2";
248     case bitc::FUNC_CODE_DEBUG_LOC2:        return "DEBUG_LOC2";
249     }
250   case bitc::TYPE_SYMTAB_BLOCK_ID:
251     switch (CodeID) {
252     default: return 0;
253     case bitc::TST_CODE_ENTRY: return "ENTRY";
254     }
255   case bitc::VALUE_SYMTAB_BLOCK_ID:
256     switch (CodeID) {
257     default: return 0;
258     case bitc::VST_CODE_ENTRY: return "ENTRY";
259     case bitc::VST_CODE_BBENTRY: return "BBENTRY";
260     }
261   case bitc::METADATA_ATTACHMENT_ID:
262     switch(CodeID) {
263     default:return 0;
264     case bitc::METADATA_ATTACHMENT:  return "METADATA_ATTACHMENT";
265     }
266   case bitc::METADATA_BLOCK_ID:
267     switch(CodeID) {
268     default:return 0;
269     case bitc::METADATA_STRING:      return "METADATA_STRING";
270     case bitc::METADATA_NODE:        return "METADATA_NODE";
271     case bitc::METADATA_FN_NODE:     return "METADATA_FN_NODE";
272     case bitc::METADATA_NAME:        return "METADATA_NAME";
273     case bitc::METADATA_NAMED_NODE:  return "METADATA_NAMED_NODE";
274     case bitc::METADATA_KIND:        return "METADATA_KIND";
275     case bitc::METADATA_ATTACHMENT:  return "METADATA_ATTACHMENT";
276     case bitc::METADATA_NODE2:       return "METADATA_NODE2";
277     case bitc::METADATA_FN_NODE2:    return "METADATA_FN_NODE2";
278     case bitc::METADATA_NAMED_NODE2: return "METADATA_NAMED_NODE2";
279     case bitc::METADATA_ATTACHMENT2: return "METADATA_ATTACHMENT2";
280     }
281   }
282 }
283
284 struct PerRecordStats {
285   unsigned NumInstances;
286   unsigned NumAbbrev;
287   uint64_t TotalBits;
288
289   PerRecordStats() : NumInstances(0), NumAbbrev(0), TotalBits(0) {}
290 };
291
292 struct PerBlockIDStats {
293   /// NumInstances - This the number of times this block ID has been seen.
294   unsigned NumInstances;
295
296   /// NumBits - The total size in bits of all of these blocks.
297   uint64_t NumBits;
298
299   /// NumSubBlocks - The total number of blocks these blocks contain.
300   unsigned NumSubBlocks;
301
302   /// NumAbbrevs - The total number of abbreviations.
303   unsigned NumAbbrevs;
304
305   /// NumRecords - The total number of records these blocks contain, and the
306   /// number that are abbreviated.
307   unsigned NumRecords, NumAbbreviatedRecords;
308
309   /// CodeFreq - Keep track of the number of times we see each code.
310   std::vector<PerRecordStats> CodeFreq;
311
312   PerBlockIDStats()
313     : NumInstances(0), NumBits(0),
314       NumSubBlocks(0), NumAbbrevs(0), NumRecords(0), NumAbbreviatedRecords(0) {}
315 };
316
317 static std::map<unsigned, PerBlockIDStats> BlockIDStats;
318
319
320
321 /// Error - All bitcode analysis errors go through this function, making this a
322 /// good place to breakpoint if debugging.
323 static bool Error(const std::string &Err) {
324   errs() << Err << "\n";
325   return true;
326 }
327
328 /// ParseBlock - Read a block, updating statistics, etc.
329 static bool ParseBlock(BitstreamCursor &Stream, unsigned IndentLevel) {
330   std::string Indent(IndentLevel*2, ' ');
331   uint64_t BlockBitStart = Stream.GetCurrentBitNo();
332   unsigned BlockID = Stream.ReadSubBlockID();
333
334   // Get the statistics for this BlockID.
335   PerBlockIDStats &BlockStats = BlockIDStats[BlockID];
336
337   BlockStats.NumInstances++;
338
339   // BLOCKINFO is a special part of the stream.
340   if (BlockID == bitc::BLOCKINFO_BLOCK_ID) {
341     if (Dump) errs() << Indent << "<BLOCKINFO_BLOCK/>\n";
342     if (Stream.ReadBlockInfoBlock())
343       return Error("Malformed BlockInfoBlock");
344     uint64_t BlockBitEnd = Stream.GetCurrentBitNo();
345     BlockStats.NumBits += BlockBitEnd-BlockBitStart;
346     return false;
347   }
348
349   unsigned NumWords = 0;
350   if (Stream.EnterSubBlock(BlockID, &NumWords))
351     return Error("Malformed block record");
352
353   const char *BlockName = 0;
354   if (Dump) {
355     errs() << Indent << "<";
356     if ((BlockName = GetBlockName(BlockID, *Stream.getBitStreamReader())))
357       errs() << BlockName;
358     else
359       errs() << "UnknownBlock" << BlockID;
360
361     if (NonSymbolic && BlockName)
362       errs() << " BlockID=" << BlockID;
363
364     errs() << " NumWords=" << NumWords
365            << " BlockCodeSize=" << Stream.GetAbbrevIDWidth() << ">\n";
366   }
367
368   SmallVector<uint64_t, 64> Record;
369
370   // Read all the records for this block.
371   while (1) {
372     if (Stream.AtEndOfStream())
373       return Error("Premature end of bitstream");
374
375     uint64_t RecordStartBit = Stream.GetCurrentBitNo();
376
377     // Read the code for this record.
378     unsigned AbbrevID = Stream.ReadCode();
379     switch (AbbrevID) {
380     case bitc::END_BLOCK: {
381       if (Stream.ReadBlockEnd())
382         return Error("Error at end of block");
383       uint64_t BlockBitEnd = Stream.GetCurrentBitNo();
384       BlockStats.NumBits += BlockBitEnd-BlockBitStart;
385       if (Dump) {
386         errs() << Indent << "</";
387         if (BlockName)
388           errs() << BlockName << ">\n";
389         else
390           errs() << "UnknownBlock" << BlockID << ">\n";
391       }
392       return false;
393     }
394     case bitc::ENTER_SUBBLOCK: {
395       uint64_t SubBlockBitStart = Stream.GetCurrentBitNo();
396       if (ParseBlock(Stream, IndentLevel+1))
397         return true;
398       ++BlockStats.NumSubBlocks;
399       uint64_t SubBlockBitEnd = Stream.GetCurrentBitNo();
400
401       // Don't include subblock sizes in the size of this block.
402       BlockBitStart += SubBlockBitEnd-SubBlockBitStart;
403       break;
404     }
405     case bitc::DEFINE_ABBREV:
406       Stream.ReadAbbrevRecord();
407       ++BlockStats.NumAbbrevs;
408       break;
409     default:
410       Record.clear();
411
412       ++BlockStats.NumRecords;
413       if (AbbrevID != bitc::UNABBREV_RECORD)
414         ++BlockStats.NumAbbreviatedRecords;
415
416       const char *BlobStart = 0;
417       unsigned BlobLen = 0;
418       unsigned Code = Stream.ReadRecord(AbbrevID, Record, BlobStart, BlobLen);
419
420
421
422       // Increment the # occurrences of this code.
423       if (BlockStats.CodeFreq.size() <= Code)
424         BlockStats.CodeFreq.resize(Code+1);
425       BlockStats.CodeFreq[Code].NumInstances++;
426       BlockStats.CodeFreq[Code].TotalBits +=
427         Stream.GetCurrentBitNo()-RecordStartBit;
428       if (AbbrevID != bitc::UNABBREV_RECORD)
429         BlockStats.CodeFreq[Code].NumAbbrev++;
430
431       if (Dump) {
432         errs() << Indent << "  <";
433         if (const char *CodeName =
434               GetCodeName(Code, BlockID, *Stream.getBitStreamReader()))
435           errs() << CodeName;
436         else
437           errs() << "UnknownCode" << Code;
438         if (NonSymbolic &&
439             GetCodeName(Code, BlockID, *Stream.getBitStreamReader()))
440           errs() << " codeid=" << Code;
441         if (AbbrevID != bitc::UNABBREV_RECORD)
442           errs() << " abbrevid=" << AbbrevID;
443
444         for (unsigned i = 0, e = Record.size(); i != e; ++i)
445           errs() << " op" << i << "=" << (int64_t)Record[i];
446
447         errs() << "/>";
448
449         if (BlobStart) {
450           errs() << " blob data = ";
451           bool BlobIsPrintable = true;
452           for (unsigned i = 0; i != BlobLen; ++i)
453             if (!isprint(BlobStart[i])) {
454               BlobIsPrintable = false;
455               break;
456             }
457
458           if (BlobIsPrintable)
459             errs() << "'" << std::string(BlobStart, BlobStart+BlobLen) <<"'";
460           else
461             errs() << "unprintable, " << BlobLen << " bytes.";
462         }
463
464         errs() << "\n";
465       }
466
467       break;
468     }
469   }
470 }
471
472 static void PrintSize(double Bits) {
473   fprintf(stderr, "%.2f/%.2fB/%lluW", Bits, Bits/8,(unsigned long long)Bits/32);
474 }
475 static void PrintSize(uint64_t Bits) {
476   fprintf(stderr, "%llub/%.2fB/%lluW", (unsigned long long)Bits,
477           (double)Bits/8, (unsigned long long)Bits/32);
478 }
479
480
481 /// AnalyzeBitcode - Analyze the bitcode file specified by InputFilename.
482 static int AnalyzeBitcode() {
483   // Read the input file.
484   error_code ec;
485   MemoryBuffer *MemBuf =
486     MemoryBuffer::getFileOrSTDIN(InputFilename.c_str(), ec);
487
488   if (MemBuf == 0)
489     return Error("Error reading '" + InputFilename + "': " + ec.message());
490
491   if (MemBuf->getBufferSize() & 3)
492     return Error("Bitcode stream should be a multiple of 4 bytes in length");
493
494   unsigned char *BufPtr = (unsigned char *)MemBuf->getBufferStart();
495   unsigned char *EndBufPtr = BufPtr+MemBuf->getBufferSize();
496
497   // If we have a wrapper header, parse it and ignore the non-bc file contents.
498   // The magic number is 0x0B17C0DE stored in little endian.
499   if (isBitcodeWrapper(BufPtr, EndBufPtr))
500     if (SkipBitcodeWrapperHeader(BufPtr, EndBufPtr))
501       return Error("Invalid bitcode wrapper header");
502
503   BitstreamReader StreamFile(BufPtr, EndBufPtr);
504   BitstreamCursor Stream(StreamFile);
505   StreamFile.CollectBlockInfoNames();
506
507   // Read the stream signature.
508   char Signature[6];
509   Signature[0] = Stream.Read(8);
510   Signature[1] = Stream.Read(8);
511   Signature[2] = Stream.Read(4);
512   Signature[3] = Stream.Read(4);
513   Signature[4] = Stream.Read(4);
514   Signature[5] = Stream.Read(4);
515
516   // Autodetect the file contents, if it is one we know.
517   CurStreamType = UnknownBitstream;
518   if (Signature[0] == 'B' && Signature[1] == 'C' &&
519       Signature[2] == 0x0 && Signature[3] == 0xC &&
520       Signature[4] == 0xE && Signature[5] == 0xD)
521     CurStreamType = LLVMIRBitstream;
522
523   unsigned NumTopBlocks = 0;
524
525   // Parse the top-level structure.  We only allow blocks at the top-level.
526   while (!Stream.AtEndOfStream()) {
527     unsigned Code = Stream.ReadCode();
528     if (Code != bitc::ENTER_SUBBLOCK)
529       return Error("Invalid record at top-level");
530
531     if (ParseBlock(Stream, 0))
532       return true;
533     ++NumTopBlocks;
534   }
535
536   if (Dump) errs() << "\n\n";
537
538   uint64_t BufferSizeBits = (EndBufPtr-BufPtr)*CHAR_BIT;
539   // Print a summary of the read file.
540   errs() << "Summary of " << InputFilename << ":\n";
541   errs() << "         Total size: ";
542   PrintSize(BufferSizeBits);
543   errs() << "\n";
544   errs() << "        Stream type: ";
545   switch (CurStreamType) {
546   default: assert(0 && "Unknown bitstream type");
547   case UnknownBitstream: errs() << "unknown\n"; break;
548   case LLVMIRBitstream:  errs() << "LLVM IR\n"; break;
549   }
550   errs() << "  # Toplevel Blocks: " << NumTopBlocks << "\n";
551   errs() << "\n";
552
553   // Emit per-block stats.
554   errs() << "Per-block Summary:\n";
555   for (std::map<unsigned, PerBlockIDStats>::iterator I = BlockIDStats.begin(),
556        E = BlockIDStats.end(); I != E; ++I) {
557     errs() << "  Block ID #" << I->first;
558     if (const char *BlockName = GetBlockName(I->first, StreamFile))
559       errs() << " (" << BlockName << ")";
560     errs() << ":\n";
561
562     const PerBlockIDStats &Stats = I->second;
563     errs() << "      Num Instances: " << Stats.NumInstances << "\n";
564     errs() << "         Total Size: ";
565     PrintSize(Stats.NumBits);
566     errs() << "\n";
567     double pct = (Stats.NumBits * 100.0) / BufferSizeBits;
568     errs() << "    Percent of file: " << format("%2.4f%%", pct) << "\n";
569     if (Stats.NumInstances > 1) {
570       errs() << "       Average Size: ";
571       PrintSize(Stats.NumBits/(double)Stats.NumInstances);
572       errs() << "\n";
573       errs() << "  Tot/Avg SubBlocks: " << Stats.NumSubBlocks << "/"
574              << Stats.NumSubBlocks/(double)Stats.NumInstances << "\n";
575       errs() << "    Tot/Avg Abbrevs: " << Stats.NumAbbrevs << "/"
576              << Stats.NumAbbrevs/(double)Stats.NumInstances << "\n";
577       errs() << "    Tot/Avg Records: " << Stats.NumRecords << "/"
578              << Stats.NumRecords/(double)Stats.NumInstances << "\n";
579     } else {
580       errs() << "      Num SubBlocks: " << Stats.NumSubBlocks << "\n";
581       errs() << "        Num Abbrevs: " << Stats.NumAbbrevs << "\n";
582       errs() << "        Num Records: " << Stats.NumRecords << "\n";
583     }
584     if (Stats.NumRecords) {
585       double pct = (Stats.NumAbbreviatedRecords * 100.0) / Stats.NumRecords;
586       errs() << "    Percent Abbrevs: " << format("%2.4f%%", pct) << "\n";
587     }
588     errs() << "\n";
589
590     // Print a histogram of the codes we see.
591     if (!NoHistogram && !Stats.CodeFreq.empty()) {
592       std::vector<std::pair<unsigned, unsigned> > FreqPairs;  // <freq,code>
593       for (unsigned i = 0, e = Stats.CodeFreq.size(); i != e; ++i)
594         if (unsigned Freq = Stats.CodeFreq[i].NumInstances)
595           FreqPairs.push_back(std::make_pair(Freq, i));
596       std::stable_sort(FreqPairs.begin(), FreqPairs.end());
597       std::reverse(FreqPairs.begin(), FreqPairs.end());
598
599       errs() << "\tRecord Histogram:\n";
600       fprintf(stderr, "\t\t  Count    # Bits   %% Abv  Record Kind\n");
601       for (unsigned i = 0, e = FreqPairs.size(); i != e; ++i) {
602         const PerRecordStats &RecStats = Stats.CodeFreq[FreqPairs[i].second];
603
604         fprintf(stderr, "\t\t%7d %9llu ", RecStats.NumInstances,
605                 (unsigned long long)RecStats.TotalBits);
606
607         if (RecStats.NumAbbrev)
608           fprintf(stderr, "%7.2f  ",
609                   (double)RecStats.NumAbbrev/RecStats.NumInstances*100);
610         else
611           fprintf(stderr, "         ");
612
613         if (const char *CodeName =
614               GetCodeName(FreqPairs[i].second, I->first, StreamFile))
615           fprintf(stderr, "%s\n", CodeName);
616         else
617           fprintf(stderr, "UnknownCode%d\n", FreqPairs[i].second);
618       }
619       errs() << "\n";
620
621     }
622   }
623   return 0;
624 }
625
626
627 int main(int argc, char **argv) {
628   // Print a stack trace if we signal out.
629   sys::PrintStackTraceOnErrorSignal();
630   PrettyStackTraceProgram X(argc, argv);
631   llvm_shutdown_obj Y;  // Call llvm_shutdown() on exit.
632   cl::ParseCommandLineOptions(argc, argv, "llvm-bcanalyzer file analyzer\n");
633
634   return AnalyzeBitcode();
635 }