Add an (optional) identification block in the bitcode
[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/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.
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_ATTACHMENT_ID:   return "METADATA_ATTACHMENT_BLOCK";
118   case bitc::USELIST_BLOCK_ID:         return "USELIST_BLOCK_ID";
119   case bitc::FUNCTION_SUMMARY_BLOCK_ID:
120                                        return "FUNCTION_SUMMARY_BLOCK";
121   case bitc::MODULE_STRTAB_BLOCK_ID:   return "MODULE_STRTAB_BLOCK";
122   }
123 }
124
125 /// GetCodeName - Return a symbolic code name if known, otherwise return
126 /// null.
127 static const char *GetCodeName(unsigned CodeID, unsigned BlockID,
128                                const BitstreamReader &StreamFile,
129                                CurStreamTypeType CurStreamType) {
130   // Standard blocks for all bitcode files.
131   if (BlockID < bitc::FIRST_APPLICATION_BLOCKID) {
132     if (BlockID == bitc::BLOCKINFO_BLOCK_ID) {
133       switch (CodeID) {
134       default: return nullptr;
135       case bitc::BLOCKINFO_CODE_SETBID:        return "SETBID";
136       case bitc::BLOCKINFO_CODE_BLOCKNAME:     return "BLOCKNAME";
137       case bitc::BLOCKINFO_CODE_SETRECORDNAME: return "SETRECORDNAME";
138       }
139     }
140     return nullptr;
141   }
142
143   // Check to see if we have a blockinfo record for this record, with a name.
144   if (const BitstreamReader::BlockInfo *Info =
145         StreamFile.getBlockInfo(BlockID)) {
146     for (unsigned i = 0, e = Info->RecordNames.size(); i != e; ++i)
147       if (Info->RecordNames[i].first == CodeID)
148         return Info->RecordNames[i].second.c_str();
149   }
150
151
152   if (CurStreamType != LLVMIRBitstream) return nullptr;
153
154 #define STRINGIFY_CODE(PREFIX, CODE)                                           \
155   case bitc::PREFIX##_##CODE:                                                  \
156     return #CODE;
157   switch (BlockID) {
158   default: return nullptr;
159   case bitc::MODULE_BLOCK_ID:
160     switch (CodeID) {
161     default: return nullptr;
162       STRINGIFY_CODE(MODULE_CODE, VERSION)
163       STRINGIFY_CODE(MODULE_CODE, TRIPLE)
164       STRINGIFY_CODE(MODULE_CODE, DATALAYOUT)
165       STRINGIFY_CODE(MODULE_CODE, ASM)
166       STRINGIFY_CODE(MODULE_CODE, SECTIONNAME)
167       STRINGIFY_CODE(MODULE_CODE, DEPLIB) // FIXME: Remove in 4.0
168       STRINGIFY_CODE(MODULE_CODE, GLOBALVAR)
169       STRINGIFY_CODE(MODULE_CODE, FUNCTION)
170       STRINGIFY_CODE(MODULE_CODE, ALIAS)
171       STRINGIFY_CODE(MODULE_CODE, PURGEVALS)
172       STRINGIFY_CODE(MODULE_CODE, GCNAME)
173       STRINGIFY_CODE(MODULE_CODE, VSTOFFSET)
174     }
175   case bitc::IDENTIFICATION_BLOCK_ID:
176     switch (CodeID) {
177     default:
178       return nullptr;
179       STRINGIFY_CODE(IDENTIFICATION_CODE, STRING)
180       STRINGIFY_CODE(IDENTIFICATION_CODE, EPOCH)
181     }
182   case bitc::PARAMATTR_BLOCK_ID:
183     switch (CodeID) {
184     default: return nullptr;
185     // FIXME: Should these be different?
186     case bitc::PARAMATTR_CODE_ENTRY_OLD: return "ENTRY";
187     case bitc::PARAMATTR_CODE_ENTRY:     return "ENTRY";
188     case bitc::PARAMATTR_GRP_CODE_ENTRY: return "ENTRY";
189     }
190   case bitc::TYPE_BLOCK_ID_NEW:
191     switch (CodeID) {
192     default: return nullptr;
193       STRINGIFY_CODE(TYPE_CODE, NUMENTRY)
194       STRINGIFY_CODE(TYPE_CODE, VOID)
195       STRINGIFY_CODE(TYPE_CODE, FLOAT)
196       STRINGIFY_CODE(TYPE_CODE, DOUBLE)
197       STRINGIFY_CODE(TYPE_CODE, LABEL)
198       STRINGIFY_CODE(TYPE_CODE, OPAQUE)
199       STRINGIFY_CODE(TYPE_CODE, INTEGER)
200       STRINGIFY_CODE(TYPE_CODE, POINTER)
201       STRINGIFY_CODE(TYPE_CODE, ARRAY)
202       STRINGIFY_CODE(TYPE_CODE, VECTOR)
203       STRINGIFY_CODE(TYPE_CODE, X86_FP80)
204       STRINGIFY_CODE(TYPE_CODE, FP128)
205       STRINGIFY_CODE(TYPE_CODE, PPC_FP128)
206       STRINGIFY_CODE(TYPE_CODE, METADATA)
207       STRINGIFY_CODE(TYPE_CODE, STRUCT_ANON)
208       STRINGIFY_CODE(TYPE_CODE, STRUCT_NAME)
209       STRINGIFY_CODE(TYPE_CODE, STRUCT_NAMED)
210       STRINGIFY_CODE(TYPE_CODE, FUNCTION)
211     }
212
213   case bitc::CONSTANTS_BLOCK_ID:
214     switch (CodeID) {
215     default: return nullptr;
216       STRINGIFY_CODE(CST_CODE, SETTYPE)
217       STRINGIFY_CODE(CST_CODE, NULL)
218       STRINGIFY_CODE(CST_CODE, UNDEF)
219       STRINGIFY_CODE(CST_CODE, INTEGER)
220       STRINGIFY_CODE(CST_CODE, WIDE_INTEGER)
221       STRINGIFY_CODE(CST_CODE, FLOAT)
222       STRINGIFY_CODE(CST_CODE, AGGREGATE)
223       STRINGIFY_CODE(CST_CODE, STRING)
224       STRINGIFY_CODE(CST_CODE, CSTRING)
225       STRINGIFY_CODE(CST_CODE, CE_BINOP)
226       STRINGIFY_CODE(CST_CODE, CE_CAST)
227       STRINGIFY_CODE(CST_CODE, CE_GEP)
228       STRINGIFY_CODE(CST_CODE, CE_INBOUNDS_GEP)
229       STRINGIFY_CODE(CST_CODE, CE_SELECT)
230       STRINGIFY_CODE(CST_CODE, CE_EXTRACTELT)
231       STRINGIFY_CODE(CST_CODE, CE_INSERTELT)
232       STRINGIFY_CODE(CST_CODE, CE_SHUFFLEVEC)
233       STRINGIFY_CODE(CST_CODE, CE_CMP)
234       STRINGIFY_CODE(CST_CODE, INLINEASM)
235       STRINGIFY_CODE(CST_CODE, CE_SHUFVEC_EX)
236     case bitc::CST_CODE_BLOCKADDRESS:    return "CST_CODE_BLOCKADDRESS";
237       STRINGIFY_CODE(CST_CODE, DATA)
238     }
239   case bitc::FUNCTION_BLOCK_ID:
240     switch (CodeID) {
241     default: return nullptr;
242       STRINGIFY_CODE(FUNC_CODE, DECLAREBLOCKS)
243       STRINGIFY_CODE(FUNC_CODE, INST_BINOP)
244       STRINGIFY_CODE(FUNC_CODE, INST_CAST)
245       STRINGIFY_CODE(FUNC_CODE, INST_GEP_OLD)
246       STRINGIFY_CODE(FUNC_CODE, INST_INBOUNDS_GEP_OLD)
247       STRINGIFY_CODE(FUNC_CODE, INST_SELECT)
248       STRINGIFY_CODE(FUNC_CODE, INST_EXTRACTELT)
249       STRINGIFY_CODE(FUNC_CODE, INST_INSERTELT)
250       STRINGIFY_CODE(FUNC_CODE, INST_SHUFFLEVEC)
251       STRINGIFY_CODE(FUNC_CODE, INST_CMP)
252       STRINGIFY_CODE(FUNC_CODE, INST_RET)
253       STRINGIFY_CODE(FUNC_CODE, INST_BR)
254       STRINGIFY_CODE(FUNC_CODE, INST_SWITCH)
255       STRINGIFY_CODE(FUNC_CODE, INST_INVOKE)
256       STRINGIFY_CODE(FUNC_CODE, INST_UNREACHABLE)
257       STRINGIFY_CODE(FUNC_CODE, INST_CLEANUPRET)
258       STRINGIFY_CODE(FUNC_CODE, INST_CATCHRET)
259       STRINGIFY_CODE(FUNC_CODE, INST_CATCHPAD)
260       STRINGIFY_CODE(FUNC_CODE, INST_CLEANUPENDPAD)
261       STRINGIFY_CODE(FUNC_CODE, INST_CATCHENDPAD)
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)
276     }
277   case bitc::VALUE_SYMTAB_BLOCK_ID:
278     switch (CodeID) {
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)
284     }
285   case bitc::MODULE_STRTAB_BLOCK_ID:
286     switch (CodeID) {
287     default: return nullptr;
288     STRINGIFY_CODE(MST_CODE, ENTRY)
289     }
290   case bitc::FUNCTION_SUMMARY_BLOCK_ID:
291     switch (CodeID) {
292     default: return nullptr;
293     STRINGIFY_CODE(FS_CODE, PERMODULE_ENTRY)
294     STRINGIFY_CODE(FS_CODE, COMBINED_ENTRY)
295     }
296   case bitc::METADATA_ATTACHMENT_ID:
297     switch(CodeID) {
298     default:return nullptr;
299       STRINGIFY_CODE(METADATA, ATTACHMENT)
300     }
301   case bitc::METADATA_BLOCK_ID:
302     switch(CodeID) {
303     default:return nullptr;
304       STRINGIFY_CODE(METADATA, STRING)
305       STRINGIFY_CODE(METADATA, NAME)
306       STRINGIFY_CODE(METADATA, KIND)
307       STRINGIFY_CODE(METADATA, NODE)
308       STRINGIFY_CODE(METADATA, VALUE)
309       STRINGIFY_CODE(METADATA, OLD_NODE)
310       STRINGIFY_CODE(METADATA, OLD_FN_NODE)
311       STRINGIFY_CODE(METADATA, NAMED_NODE)
312       STRINGIFY_CODE(METADATA, DISTINCT_NODE)
313       STRINGIFY_CODE(METADATA, LOCATION)
314       STRINGIFY_CODE(METADATA, GENERIC_DEBUG)
315       STRINGIFY_CODE(METADATA, SUBRANGE)
316       STRINGIFY_CODE(METADATA, ENUMERATOR)
317       STRINGIFY_CODE(METADATA, BASIC_TYPE)
318       STRINGIFY_CODE(METADATA, FILE)
319       STRINGIFY_CODE(METADATA, DERIVED_TYPE)
320       STRINGIFY_CODE(METADATA, COMPOSITE_TYPE)
321       STRINGIFY_CODE(METADATA, SUBROUTINE_TYPE)
322       STRINGIFY_CODE(METADATA, COMPILE_UNIT)
323       STRINGIFY_CODE(METADATA, SUBPROGRAM)
324       STRINGIFY_CODE(METADATA, LEXICAL_BLOCK)
325       STRINGIFY_CODE(METADATA, LEXICAL_BLOCK_FILE)
326       STRINGIFY_CODE(METADATA, NAMESPACE)
327       STRINGIFY_CODE(METADATA, TEMPLATE_TYPE)
328       STRINGIFY_CODE(METADATA, TEMPLATE_VALUE)
329       STRINGIFY_CODE(METADATA, GLOBAL_VAR)
330       STRINGIFY_CODE(METADATA, LOCAL_VAR)
331       STRINGIFY_CODE(METADATA, EXPRESSION)
332       STRINGIFY_CODE(METADATA, OBJC_PROPERTY)
333       STRINGIFY_CODE(METADATA, IMPORTED_ENTITY)
334       STRINGIFY_CODE(METADATA, MODULE)
335     }
336   case bitc::USELIST_BLOCK_ID:
337     switch(CodeID) {
338     default:return nullptr;
339     case bitc::USELIST_CODE_DEFAULT: return "USELIST_CODE_DEFAULT";
340     case bitc::USELIST_CODE_BB:      return "USELIST_CODE_BB";
341     }
342   }
343 #undef STRINGIFY_CODE
344 }
345
346 struct PerRecordStats {
347   unsigned NumInstances;
348   unsigned NumAbbrev;
349   uint64_t TotalBits;
350
351   PerRecordStats() : NumInstances(0), NumAbbrev(0), TotalBits(0) {}
352 };
353
354 struct PerBlockIDStats {
355   /// NumInstances - This the number of times this block ID has been seen.
356   unsigned NumInstances;
357
358   /// NumBits - The total size in bits of all of these blocks.
359   uint64_t NumBits;
360
361   /// NumSubBlocks - The total number of blocks these blocks contain.
362   unsigned NumSubBlocks;
363
364   /// NumAbbrevs - The total number of abbreviations.
365   unsigned NumAbbrevs;
366
367   /// NumRecords - The total number of records these blocks contain, and the
368   /// number that are abbreviated.
369   unsigned NumRecords, NumAbbreviatedRecords;
370
371   /// CodeFreq - Keep track of the number of times we see each code.
372   std::vector<PerRecordStats> CodeFreq;
373
374   PerBlockIDStats()
375     : NumInstances(0), NumBits(0),
376       NumSubBlocks(0), NumAbbrevs(0), NumRecords(0), NumAbbreviatedRecords(0) {}
377 };
378
379 static std::map<unsigned, PerBlockIDStats> BlockIDStats;
380
381
382
383 /// Error - All bitcode analysis errors go through this function, making this a
384 /// good place to breakpoint if debugging.
385 static bool Error(const Twine &Err) {
386   errs() << Err << "\n";
387   return true;
388 }
389
390 /// ParseBlock - Read a block, updating statistics, etc.
391 static bool ParseBlock(BitstreamCursor &Stream, unsigned BlockID,
392                        unsigned IndentLevel, CurStreamTypeType CurStreamType) {
393   std::string Indent(IndentLevel*2, ' ');
394   uint64_t BlockBitStart = Stream.GetCurrentBitNo();
395
396   // Get the statistics for this BlockID.
397   PerBlockIDStats &BlockStats = BlockIDStats[BlockID];
398
399   BlockStats.NumInstances++;
400
401   // BLOCKINFO is a special part of the stream.
402   if (BlockID == bitc::BLOCKINFO_BLOCK_ID) {
403     if (Dump) outs() << Indent << "<BLOCKINFO_BLOCK/>\n";
404     if (Stream.ReadBlockInfoBlock())
405       return Error("Malformed BlockInfoBlock");
406     uint64_t BlockBitEnd = Stream.GetCurrentBitNo();
407     BlockStats.NumBits += BlockBitEnd-BlockBitStart;
408     return false;
409   }
410
411   unsigned NumWords = 0;
412   if (Stream.EnterSubBlock(BlockID, &NumWords))
413     return Error("Malformed block record");
414
415   const char *BlockName = nullptr;
416   if (Dump) {
417     outs() << Indent << "<";
418     if ((BlockName = GetBlockName(BlockID, *Stream.getBitStreamReader(),
419                                   CurStreamType)))
420       outs() << BlockName;
421     else
422       outs() << "UnknownBlock" << BlockID;
423
424     if (NonSymbolic && BlockName)
425       outs() << " BlockID=" << BlockID;
426
427     outs() << " NumWords=" << NumWords
428            << " BlockCodeSize=" << Stream.getAbbrevIDWidth() << ">\n";
429   }
430
431   SmallVector<uint64_t, 64> Record;
432
433   // Read all the records for this block.
434   while (1) {
435     if (Stream.AtEndOfStream())
436       return Error("Premature end of bitstream");
437
438     uint64_t RecordStartBit = Stream.GetCurrentBitNo();
439
440     BitstreamEntry Entry =
441       Stream.advance(BitstreamCursor::AF_DontAutoprocessAbbrevs);
442     
443     switch (Entry.Kind) {
444     case BitstreamEntry::Error:
445       return Error("malformed bitcode file");
446     case BitstreamEntry::EndBlock: {
447       uint64_t BlockBitEnd = Stream.GetCurrentBitNo();
448       BlockStats.NumBits += BlockBitEnd-BlockBitStart;
449       if (Dump) {
450         outs() << Indent << "</";
451         if (BlockName)
452           outs() << BlockName << ">\n";
453         else
454           outs() << "UnknownBlock" << BlockID << ">\n";
455       }
456       return false;
457     }
458         
459     case BitstreamEntry::SubBlock: {
460       uint64_t SubBlockBitStart = Stream.GetCurrentBitNo();
461       if (ParseBlock(Stream, Entry.ID, IndentLevel+1, CurStreamType))
462         return true;
463       ++BlockStats.NumSubBlocks;
464       uint64_t SubBlockBitEnd = Stream.GetCurrentBitNo();
465       
466       // Don't include subblock sizes in the size of this block.
467       BlockBitStart += SubBlockBitEnd-SubBlockBitStart;
468       continue;
469     }
470     case BitstreamEntry::Record:
471       // The interesting case.
472       break;
473     }
474
475     if (Entry.ID == bitc::DEFINE_ABBREV) {
476       Stream.ReadAbbrevRecord();
477       ++BlockStats.NumAbbrevs;
478       continue;
479     }
480     
481     Record.clear();
482
483     ++BlockStats.NumRecords;
484
485     StringRef Blob;
486     unsigned Code = Stream.readRecord(Entry.ID, Record, &Blob);
487
488     // Increment the # occurrences of this code.
489     if (BlockStats.CodeFreq.size() <= Code)
490       BlockStats.CodeFreq.resize(Code+1);
491     BlockStats.CodeFreq[Code].NumInstances++;
492     BlockStats.CodeFreq[Code].TotalBits +=
493       Stream.GetCurrentBitNo()-RecordStartBit;
494     if (Entry.ID != bitc::UNABBREV_RECORD) {
495       BlockStats.CodeFreq[Code].NumAbbrev++;
496       ++BlockStats.NumAbbreviatedRecords;
497     }
498
499     if (Dump) {
500       outs() << Indent << "  <";
501       if (const char *CodeName =
502             GetCodeName(Code, BlockID, *Stream.getBitStreamReader(),
503                         CurStreamType))
504         outs() << CodeName;
505       else
506         outs() << "UnknownCode" << Code;
507       if (NonSymbolic &&
508           GetCodeName(Code, BlockID, *Stream.getBitStreamReader(),
509                       CurStreamType))
510         outs() << " codeid=" << Code;
511       const BitCodeAbbrev *Abbv = nullptr;
512       if (Entry.ID != bitc::UNABBREV_RECORD) {
513         Abbv = Stream.getAbbrev(Entry.ID);
514         outs() << " abbrevid=" << Entry.ID;
515       }
516
517       for (unsigned i = 0, e = Record.size(); i != e; ++i)
518         outs() << " op" << i << "=" << (int64_t)Record[i];
519
520       outs() << "/>";
521
522       if (Abbv) {
523         for (unsigned i = 1, e = Abbv->getNumOperandInfos(); i != e; ++i) {
524           const BitCodeAbbrevOp &Op = Abbv->getOperandInfo(i);
525           if (!Op.isEncoding() || Op.getEncoding() != BitCodeAbbrevOp::Array)
526             continue;
527           assert(i + 2 == e && "Array op not second to last");
528           std::string Str;
529           bool ArrayIsPrintable = true;
530           for (unsigned j = i - 1, je = Record.size(); j != je; ++j) {
531             if (!isprint(static_cast<unsigned char>(Record[j]))) {
532               ArrayIsPrintable = false;
533               break;
534             }
535             Str += (char)Record[j];
536           }
537           if (ArrayIsPrintable) outs() << " record string = '" << Str << "'";
538           break;
539         }
540       }
541
542       if (Blob.data()) {
543         outs() << " blob data = ";
544         if (ShowBinaryBlobs) {
545           outs() << "'";
546           outs().write_escaped(Blob, /*hex=*/true) << "'";
547         } else {
548           bool BlobIsPrintable = true;
549           for (unsigned i = 0, e = Blob.size(); i != e; ++i)
550             if (!isprint(static_cast<unsigned char>(Blob[i]))) {
551               BlobIsPrintable = false;
552               break;
553             }
554
555           if (BlobIsPrintable)
556             outs() << "'" << Blob << "'";
557           else
558             outs() << "unprintable, " << Blob.size() << " bytes.";          
559         }
560       }
561
562       outs() << "\n";
563     }
564   }
565 }
566
567 static void PrintSize(double Bits) {
568   outs() << format("%.2f/%.2fB/%luW", Bits, Bits/8,(unsigned long)(Bits/32));
569 }
570 static void PrintSize(uint64_t Bits) {
571   outs() << format("%lub/%.2fB/%luW", (unsigned long)Bits,
572                    (double)Bits/8, (unsigned long)(Bits/32));
573 }
574
575 static bool openBitcodeFile(StringRef Path,
576                             std::unique_ptr<MemoryBuffer> &MemBuf,
577                             BitstreamReader &StreamFile,
578                             BitstreamCursor &Stream,
579                             CurStreamTypeType &CurStreamType) {
580   // Read the input file.
581   ErrorOr<std::unique_ptr<MemoryBuffer>> MemBufOrErr =
582       MemoryBuffer::getFileOrSTDIN(Path);
583   if (std::error_code EC = MemBufOrErr.getError())
584     return Error(Twine("Error reading '") + Path + "': " + EC.message());
585   MemBuf = std::move(MemBufOrErr.get());
586
587   if (MemBuf->getBufferSize() & 3)
588     return Error("Bitcode stream should be a multiple of 4 bytes in length");
589
590   const unsigned char *BufPtr = (const unsigned char *)MemBuf->getBufferStart();
591   const unsigned char *EndBufPtr = BufPtr + MemBuf->getBufferSize();
592
593   // If we have a wrapper header, parse it and ignore the non-bc file contents.
594   // The magic number is 0x0B17C0DE stored in little endian.
595   if (isBitcodeWrapper(BufPtr, EndBufPtr))
596     if (SkipBitcodeWrapperHeader(BufPtr, EndBufPtr, true))
597       return Error("Invalid bitcode wrapper header");
598
599   StreamFile = BitstreamReader(BufPtr, EndBufPtr);
600   Stream = BitstreamCursor(StreamFile);
601   StreamFile.CollectBlockInfoNames();
602
603   // Read the stream signature.
604   char Signature[6];
605   Signature[0] = Stream.Read(8);
606   Signature[1] = Stream.Read(8);
607   Signature[2] = Stream.Read(4);
608   Signature[3] = Stream.Read(4);
609   Signature[4] = Stream.Read(4);
610   Signature[5] = Stream.Read(4);
611
612   // Autodetect the file contents, if it is one we know.
613   CurStreamType = UnknownBitstream;
614   if (Signature[0] == 'B' && Signature[1] == 'C' &&
615       Signature[2] == 0x0 && Signature[3] == 0xC &&
616       Signature[4] == 0xE && Signature[5] == 0xD)
617     CurStreamType = LLVMIRBitstream;
618
619   return false;
620 }
621
622 /// AnalyzeBitcode - Analyze the bitcode file specified by InputFilename.
623 static int AnalyzeBitcode() {
624   std::unique_ptr<MemoryBuffer> StreamBuffer;
625   BitstreamReader StreamFile;
626   BitstreamCursor Stream;
627   CurStreamTypeType CurStreamType;
628   if (openBitcodeFile(InputFilename, StreamBuffer, StreamFile, Stream,
629                       CurStreamType))
630     return true;
631
632   // Read block info from BlockInfoFilename, if specified.
633   // The block info must be a top-level block.
634   if (!BlockInfoFilename.empty()) {
635     std::unique_ptr<MemoryBuffer> BlockInfoBuffer;
636     BitstreamReader BlockInfoFile;
637     BitstreamCursor BlockInfoCursor;
638     CurStreamTypeType BlockInfoStreamType;
639     if (openBitcodeFile(BlockInfoFilename, BlockInfoBuffer, BlockInfoFile,
640                         BlockInfoCursor, BlockInfoStreamType))
641       return true;
642
643     while (!BlockInfoCursor.AtEndOfStream()) {
644       unsigned Code = BlockInfoCursor.ReadCode();
645       if (Code != bitc::ENTER_SUBBLOCK)
646         return Error("Invalid record at top-level in block info file");
647
648       unsigned BlockID = BlockInfoCursor.ReadSubBlockID();
649       if (BlockID == bitc::BLOCKINFO_BLOCK_ID) {
650         if (BlockInfoCursor.ReadBlockInfoBlock())
651           return Error("Malformed BlockInfoBlock in block info file");
652         break;
653       }
654
655       BlockInfoCursor.SkipBlock();
656     }
657
658     StreamFile.takeBlockInfo(std::move(BlockInfoFile));
659   }
660
661   unsigned NumTopBlocks = 0;
662
663   // Parse the top-level structure.  We only allow blocks at the top-level.
664   while (!Stream.AtEndOfStream()) {
665     unsigned Code = Stream.ReadCode();
666     if (Code != bitc::ENTER_SUBBLOCK)
667       return Error("Invalid record at top-level");
668
669     unsigned BlockID = Stream.ReadSubBlockID();
670
671     if (ParseBlock(Stream, BlockID, 0, CurStreamType))
672       return true;
673     ++NumTopBlocks;
674   }
675
676   if (Dump) outs() << "\n\n";
677
678   uint64_t BufferSizeBits = StreamFile.getBitcodeBytes().getExtent() * CHAR_BIT;
679   // Print a summary of the read file.
680   outs() << "Summary of " << InputFilename << ":\n";
681   outs() << "         Total size: ";
682   PrintSize(BufferSizeBits);
683   outs() << "\n";
684   outs() << "        Stream type: ";
685   switch (CurStreamType) {
686   case UnknownBitstream: outs() << "unknown\n"; break;
687   case LLVMIRBitstream:  outs() << "LLVM IR\n"; break;
688   }
689   outs() << "  # Toplevel Blocks: " << NumTopBlocks << "\n";
690   outs() << "\n";
691
692   // Emit per-block stats.
693   outs() << "Per-block Summary:\n";
694   for (std::map<unsigned, PerBlockIDStats>::iterator I = BlockIDStats.begin(),
695        E = BlockIDStats.end(); I != E; ++I) {
696     outs() << "  Block ID #" << I->first;
697     if (const char *BlockName = GetBlockName(I->first, StreamFile,
698                                              CurStreamType))
699       outs() << " (" << BlockName << ")";
700     outs() << ":\n";
701
702     const PerBlockIDStats &Stats = I->second;
703     outs() << "      Num Instances: " << Stats.NumInstances << "\n";
704     outs() << "         Total Size: ";
705     PrintSize(Stats.NumBits);
706     outs() << "\n";
707     double pct = (Stats.NumBits * 100.0) / BufferSizeBits;
708     outs() << "    Percent of file: " << format("%2.4f%%", pct) << "\n";
709     if (Stats.NumInstances > 1) {
710       outs() << "       Average Size: ";
711       PrintSize(Stats.NumBits/(double)Stats.NumInstances);
712       outs() << "\n";
713       outs() << "  Tot/Avg SubBlocks: " << Stats.NumSubBlocks << "/"
714              << Stats.NumSubBlocks/(double)Stats.NumInstances << "\n";
715       outs() << "    Tot/Avg Abbrevs: " << Stats.NumAbbrevs << "/"
716              << Stats.NumAbbrevs/(double)Stats.NumInstances << "\n";
717       outs() << "    Tot/Avg Records: " << Stats.NumRecords << "/"
718              << Stats.NumRecords/(double)Stats.NumInstances << "\n";
719     } else {
720       outs() << "      Num SubBlocks: " << Stats.NumSubBlocks << "\n";
721       outs() << "        Num Abbrevs: " << Stats.NumAbbrevs << "\n";
722       outs() << "        Num Records: " << Stats.NumRecords << "\n";
723     }
724     if (Stats.NumRecords) {
725       double pct = (Stats.NumAbbreviatedRecords * 100.0) / Stats.NumRecords;
726       outs() << "    Percent Abbrevs: " << format("%2.4f%%", pct) << "\n";
727     }
728     outs() << "\n";
729
730     // Print a histogram of the codes we see.
731     if (!NoHistogram && !Stats.CodeFreq.empty()) {
732       std::vector<std::pair<unsigned, unsigned> > FreqPairs;  // <freq,code>
733       for (unsigned i = 0, e = Stats.CodeFreq.size(); i != e; ++i)
734         if (unsigned Freq = Stats.CodeFreq[i].NumInstances)
735           FreqPairs.push_back(std::make_pair(Freq, i));
736       std::stable_sort(FreqPairs.begin(), FreqPairs.end());
737       std::reverse(FreqPairs.begin(), FreqPairs.end());
738
739       outs() << "\tRecord Histogram:\n";
740       outs() << "\t\t  Count    # Bits   %% Abv  Record Kind\n";
741       for (unsigned i = 0, e = FreqPairs.size(); i != e; ++i) {
742         const PerRecordStats &RecStats = Stats.CodeFreq[FreqPairs[i].second];
743
744         outs() << format("\t\t%7d %9lu",
745                          RecStats.NumInstances,
746                          (unsigned long)RecStats.TotalBits);
747
748         if (RecStats.NumAbbrev)
749           outs() <<
750               format("%7.2f  ",
751                      (double)RecStats.NumAbbrev/RecStats.NumInstances*100);
752         else
753           outs() << "         ";
754
755         if (const char *CodeName =
756               GetCodeName(FreqPairs[i].second, I->first, StreamFile,
757                           CurStreamType))
758           outs() << CodeName << "\n";
759         else
760           outs() << "UnknownCode" << FreqPairs[i].second << "\n";
761       }
762       outs() << "\n";
763
764     }
765   }
766   return 0;
767 }
768
769
770 int main(int argc, char **argv) {
771   // Print a stack trace if we signal out.
772   sys::PrintStackTraceOnErrorSignal();
773   PrettyStackTraceProgram X(argc, argv);
774   llvm_shutdown_obj Y;  // Call llvm_shutdown() on exit.
775   cl::ParseCommandLineOptions(argc, argv, "llvm-bcanalyzer file analyzer\n");
776
777   return AnalyzeBitcode();
778 }