]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/tools/llvm-bcanalyzer/llvm-bcanalyzer.cpp
Merge llvm, clang, lld and lldb trunk r300890, and update build glue.
[FreeBSD/FreeBSD.git] / contrib / llvm / 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/ADT/StringExtras.h"
31 #include "llvm/Bitcode/BitcodeReader.h"
32 #include "llvm/Bitcode/BitstreamReader.h"
33 #include "llvm/Bitcode/LLVMBitCodes.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/SHA1.h"
41 #include "llvm/Support/Signals.h"
42 #include "llvm/Support/raw_ostream.h"
43 #include <algorithm>
44 #include <cctype>
45 #include <map>
46 #include <system_error>
47 using namespace llvm;
48
49 static cl::opt<std::string>
50   InputFilename(cl::Positional, cl::desc("<input bitcode>"), cl::init("-"));
51
52 static cl::opt<bool> Dump("dump", cl::desc("Dump low level bitcode trace"));
53
54 //===----------------------------------------------------------------------===//
55 // Bitcode specific analysis.
56 //===----------------------------------------------------------------------===//
57
58 static cl::opt<bool> NoHistogram("disable-histogram",
59                                  cl::desc("Do not print per-code histogram"));
60
61 static cl::opt<bool>
62 NonSymbolic("non-symbolic",
63             cl::desc("Emit numeric info in dump even if"
64                      " symbolic info is available"));
65
66 static cl::opt<std::string>
67   BlockInfoFilename("block-info",
68                     cl::desc("Use the BLOCK_INFO from the given file"));
69
70 static cl::opt<bool>
71   ShowBinaryBlobs("show-binary-blobs",
72                   cl::desc("Print binary blobs using hex escapes"));
73
74 namespace {
75
76 /// CurStreamTypeType - A type for CurStreamType
77 enum CurStreamTypeType {
78   UnknownBitstream,
79   LLVMIRBitstream
80 };
81
82 }
83
84 /// GetBlockName - Return a symbolic block name if known, otherwise return
85 /// null.
86 static const char *GetBlockName(unsigned BlockID,
87                                 const BitstreamBlockInfo &BlockInfo,
88                                 CurStreamTypeType CurStreamType) {
89   // Standard blocks for all bitcode files.
90   if (BlockID < bitc::FIRST_APPLICATION_BLOCKID) {
91     if (BlockID == bitc::BLOCKINFO_BLOCK_ID)
92       return "BLOCKINFO_BLOCK";
93     return nullptr;
94   }
95
96   // Check to see if we have a blockinfo record for this block, with a name.
97   if (const BitstreamBlockInfo::BlockInfo *Info =
98           BlockInfo.getBlockInfo(BlockID)) {
99     if (!Info->Name.empty())
100       return Info->Name.c_str();
101   }
102
103
104   if (CurStreamType != LLVMIRBitstream) return nullptr;
105
106   switch (BlockID) {
107   default:                                 return nullptr;
108   case bitc::OPERAND_BUNDLE_TAGS_BLOCK_ID: return "OPERAND_BUNDLE_TAGS_BLOCK";
109   case bitc::MODULE_BLOCK_ID:              return "MODULE_BLOCK";
110   case bitc::PARAMATTR_BLOCK_ID:           return "PARAMATTR_BLOCK";
111   case bitc::PARAMATTR_GROUP_BLOCK_ID:     return "PARAMATTR_GROUP_BLOCK_ID";
112   case bitc::TYPE_BLOCK_ID_NEW:            return "TYPE_BLOCK_ID";
113   case bitc::CONSTANTS_BLOCK_ID:           return "CONSTANTS_BLOCK";
114   case bitc::FUNCTION_BLOCK_ID:            return "FUNCTION_BLOCK";
115   case bitc::IDENTIFICATION_BLOCK_ID:
116                                            return "IDENTIFICATION_BLOCK_ID";
117   case bitc::VALUE_SYMTAB_BLOCK_ID:        return "VALUE_SYMTAB";
118   case bitc::METADATA_BLOCK_ID:            return "METADATA_BLOCK";
119   case bitc::METADATA_KIND_BLOCK_ID:       return "METADATA_KIND_BLOCK";
120   case bitc::METADATA_ATTACHMENT_ID:       return "METADATA_ATTACHMENT_BLOCK";
121   case bitc::USELIST_BLOCK_ID:             return "USELIST_BLOCK_ID";
122   case bitc::GLOBALVAL_SUMMARY_BLOCK_ID:
123                                            return "GLOBALVAL_SUMMARY_BLOCK";
124   case bitc::MODULE_STRTAB_BLOCK_ID:       return "MODULE_STRTAB_BLOCK";
125   case bitc::STRTAB_BLOCK_ID:              return "STRTAB_BLOCK";
126   }
127 }
128
129 /// GetCodeName - Return a symbolic code name if known, otherwise return
130 /// null.
131 static const char *GetCodeName(unsigned CodeID, unsigned BlockID,
132                                const BitstreamBlockInfo &BlockInfo,
133                                CurStreamTypeType CurStreamType) {
134   // Standard blocks for all bitcode files.
135   if (BlockID < bitc::FIRST_APPLICATION_BLOCKID) {
136     if (BlockID == bitc::BLOCKINFO_BLOCK_ID) {
137       switch (CodeID) {
138       default: return nullptr;
139       case bitc::BLOCKINFO_CODE_SETBID:        return "SETBID";
140       case bitc::BLOCKINFO_CODE_BLOCKNAME:     return "BLOCKNAME";
141       case bitc::BLOCKINFO_CODE_SETRECORDNAME: return "SETRECORDNAME";
142       }
143     }
144     return nullptr;
145   }
146
147   // Check to see if we have a blockinfo record for this record, with a name.
148   if (const BitstreamBlockInfo::BlockInfo *Info =
149         BlockInfo.getBlockInfo(BlockID)) {
150     for (unsigned i = 0, e = Info->RecordNames.size(); i != e; ++i)
151       if (Info->RecordNames[i].first == CodeID)
152         return Info->RecordNames[i].second.c_str();
153   }
154
155
156   if (CurStreamType != LLVMIRBitstream) return nullptr;
157
158 #define STRINGIFY_CODE(PREFIX, CODE)                                           \
159   case bitc::PREFIX##_##CODE:                                                  \
160     return #CODE;
161   switch (BlockID) {
162   default: return nullptr;
163   case bitc::MODULE_BLOCK_ID:
164     switch (CodeID) {
165     default: return nullptr;
166       STRINGIFY_CODE(MODULE_CODE, VERSION)
167       STRINGIFY_CODE(MODULE_CODE, TRIPLE)
168       STRINGIFY_CODE(MODULE_CODE, DATALAYOUT)
169       STRINGIFY_CODE(MODULE_CODE, ASM)
170       STRINGIFY_CODE(MODULE_CODE, SECTIONNAME)
171       STRINGIFY_CODE(MODULE_CODE, DEPLIB) // FIXME: Remove in 4.0
172       STRINGIFY_CODE(MODULE_CODE, GLOBALVAR)
173       STRINGIFY_CODE(MODULE_CODE, FUNCTION)
174       STRINGIFY_CODE(MODULE_CODE, ALIAS)
175       STRINGIFY_CODE(MODULE_CODE, GCNAME)
176       STRINGIFY_CODE(MODULE_CODE, VSTOFFSET)
177       STRINGIFY_CODE(MODULE_CODE, METADATA_VALUES_UNUSED)
178       STRINGIFY_CODE(MODULE_CODE, SOURCE_FILENAME)
179       STRINGIFY_CODE(MODULE_CODE, HASH)
180     }
181   case bitc::IDENTIFICATION_BLOCK_ID:
182     switch (CodeID) {
183     default:
184       return nullptr;
185       STRINGIFY_CODE(IDENTIFICATION_CODE, STRING)
186       STRINGIFY_CODE(IDENTIFICATION_CODE, EPOCH)
187     }
188   case bitc::PARAMATTR_BLOCK_ID:
189     switch (CodeID) {
190     default: return nullptr;
191     // FIXME: Should these be different?
192     case bitc::PARAMATTR_CODE_ENTRY_OLD: return "ENTRY";
193     case bitc::PARAMATTR_CODE_ENTRY:     return "ENTRY";
194     }
195   case bitc::PARAMATTR_GROUP_BLOCK_ID:
196     switch (CodeID) {
197     default: return nullptr;
198     case bitc::PARAMATTR_GRP_CODE_ENTRY: return "ENTRY";
199     }
200   case bitc::TYPE_BLOCK_ID_NEW:
201     switch (CodeID) {
202     default: return nullptr;
203       STRINGIFY_CODE(TYPE_CODE, NUMENTRY)
204       STRINGIFY_CODE(TYPE_CODE, VOID)
205       STRINGIFY_CODE(TYPE_CODE, FLOAT)
206       STRINGIFY_CODE(TYPE_CODE, DOUBLE)
207       STRINGIFY_CODE(TYPE_CODE, LABEL)
208       STRINGIFY_CODE(TYPE_CODE, OPAQUE)
209       STRINGIFY_CODE(TYPE_CODE, INTEGER)
210       STRINGIFY_CODE(TYPE_CODE, POINTER)
211       STRINGIFY_CODE(TYPE_CODE, ARRAY)
212       STRINGIFY_CODE(TYPE_CODE, VECTOR)
213       STRINGIFY_CODE(TYPE_CODE, X86_FP80)
214       STRINGIFY_CODE(TYPE_CODE, FP128)
215       STRINGIFY_CODE(TYPE_CODE, PPC_FP128)
216       STRINGIFY_CODE(TYPE_CODE, METADATA)
217       STRINGIFY_CODE(TYPE_CODE, STRUCT_ANON)
218       STRINGIFY_CODE(TYPE_CODE, STRUCT_NAME)
219       STRINGIFY_CODE(TYPE_CODE, STRUCT_NAMED)
220       STRINGIFY_CODE(TYPE_CODE, FUNCTION)
221     }
222
223   case bitc::CONSTANTS_BLOCK_ID:
224     switch (CodeID) {
225     default: return nullptr;
226       STRINGIFY_CODE(CST_CODE, SETTYPE)
227       STRINGIFY_CODE(CST_CODE, NULL)
228       STRINGIFY_CODE(CST_CODE, UNDEF)
229       STRINGIFY_CODE(CST_CODE, INTEGER)
230       STRINGIFY_CODE(CST_CODE, WIDE_INTEGER)
231       STRINGIFY_CODE(CST_CODE, FLOAT)
232       STRINGIFY_CODE(CST_CODE, AGGREGATE)
233       STRINGIFY_CODE(CST_CODE, STRING)
234       STRINGIFY_CODE(CST_CODE, CSTRING)
235       STRINGIFY_CODE(CST_CODE, CE_BINOP)
236       STRINGIFY_CODE(CST_CODE, CE_CAST)
237       STRINGIFY_CODE(CST_CODE, CE_GEP)
238       STRINGIFY_CODE(CST_CODE, CE_INBOUNDS_GEP)
239       STRINGIFY_CODE(CST_CODE, CE_SELECT)
240       STRINGIFY_CODE(CST_CODE, CE_EXTRACTELT)
241       STRINGIFY_CODE(CST_CODE, CE_INSERTELT)
242       STRINGIFY_CODE(CST_CODE, CE_SHUFFLEVEC)
243       STRINGIFY_CODE(CST_CODE, CE_CMP)
244       STRINGIFY_CODE(CST_CODE, INLINEASM)
245       STRINGIFY_CODE(CST_CODE, CE_SHUFVEC_EX)
246     case bitc::CST_CODE_BLOCKADDRESS:    return "CST_CODE_BLOCKADDRESS";
247       STRINGIFY_CODE(CST_CODE, DATA)
248     }
249   case bitc::FUNCTION_BLOCK_ID:
250     switch (CodeID) {
251     default: return nullptr;
252       STRINGIFY_CODE(FUNC_CODE, DECLAREBLOCKS)
253       STRINGIFY_CODE(FUNC_CODE, INST_BINOP)
254       STRINGIFY_CODE(FUNC_CODE, INST_CAST)
255       STRINGIFY_CODE(FUNC_CODE, INST_GEP_OLD)
256       STRINGIFY_CODE(FUNC_CODE, INST_INBOUNDS_GEP_OLD)
257       STRINGIFY_CODE(FUNC_CODE, INST_SELECT)
258       STRINGIFY_CODE(FUNC_CODE, INST_EXTRACTELT)
259       STRINGIFY_CODE(FUNC_CODE, INST_INSERTELT)
260       STRINGIFY_CODE(FUNC_CODE, INST_SHUFFLEVEC)
261       STRINGIFY_CODE(FUNC_CODE, INST_CMP)
262       STRINGIFY_CODE(FUNC_CODE, INST_RET)
263       STRINGIFY_CODE(FUNC_CODE, INST_BR)
264       STRINGIFY_CODE(FUNC_CODE, INST_SWITCH)
265       STRINGIFY_CODE(FUNC_CODE, INST_INVOKE)
266       STRINGIFY_CODE(FUNC_CODE, INST_UNREACHABLE)
267       STRINGIFY_CODE(FUNC_CODE, INST_CLEANUPRET)
268       STRINGIFY_CODE(FUNC_CODE, INST_CATCHRET)
269       STRINGIFY_CODE(FUNC_CODE, INST_CATCHPAD)
270       STRINGIFY_CODE(FUNC_CODE, INST_PHI)
271       STRINGIFY_CODE(FUNC_CODE, INST_ALLOCA)
272       STRINGIFY_CODE(FUNC_CODE, INST_LOAD)
273       STRINGIFY_CODE(FUNC_CODE, INST_VAARG)
274       STRINGIFY_CODE(FUNC_CODE, INST_STORE)
275       STRINGIFY_CODE(FUNC_CODE, INST_EXTRACTVAL)
276       STRINGIFY_CODE(FUNC_CODE, INST_INSERTVAL)
277       STRINGIFY_CODE(FUNC_CODE, INST_CMP2)
278       STRINGIFY_CODE(FUNC_CODE, INST_VSELECT)
279       STRINGIFY_CODE(FUNC_CODE, DEBUG_LOC_AGAIN)
280       STRINGIFY_CODE(FUNC_CODE, INST_CALL)
281       STRINGIFY_CODE(FUNC_CODE, DEBUG_LOC)
282       STRINGIFY_CODE(FUNC_CODE, INST_GEP)
283       STRINGIFY_CODE(FUNC_CODE, OPERAND_BUNDLE)
284     }
285   case bitc::VALUE_SYMTAB_BLOCK_ID:
286     switch (CodeID) {
287     default: return nullptr;
288     STRINGIFY_CODE(VST_CODE, ENTRY)
289     STRINGIFY_CODE(VST_CODE, BBENTRY)
290     STRINGIFY_CODE(VST_CODE, FNENTRY)
291     STRINGIFY_CODE(VST_CODE, COMBINED_ENTRY)
292     }
293   case bitc::MODULE_STRTAB_BLOCK_ID:
294     switch (CodeID) {
295     default:
296       return nullptr;
297       STRINGIFY_CODE(MST_CODE, ENTRY)
298       STRINGIFY_CODE(MST_CODE, HASH)
299     }
300   case bitc::GLOBALVAL_SUMMARY_BLOCK_ID:
301     switch (CodeID) {
302     default:
303       return nullptr;
304       STRINGIFY_CODE(FS, PERMODULE)
305       STRINGIFY_CODE(FS, PERMODULE_PROFILE)
306       STRINGIFY_CODE(FS, PERMODULE_GLOBALVAR_INIT_REFS)
307       STRINGIFY_CODE(FS, COMBINED)
308       STRINGIFY_CODE(FS, COMBINED_PROFILE)
309       STRINGIFY_CODE(FS, COMBINED_GLOBALVAR_INIT_REFS)
310       STRINGIFY_CODE(FS, ALIAS)
311       STRINGIFY_CODE(FS, COMBINED_ALIAS)
312       STRINGIFY_CODE(FS, COMBINED_ORIGINAL_NAME)
313       STRINGIFY_CODE(FS, VERSION)
314       STRINGIFY_CODE(FS, TYPE_TESTS)
315       STRINGIFY_CODE(FS, TYPE_TEST_ASSUME_VCALLS)
316       STRINGIFY_CODE(FS, TYPE_CHECKED_LOAD_VCALLS)
317       STRINGIFY_CODE(FS, TYPE_TEST_ASSUME_CONST_VCALL)
318       STRINGIFY_CODE(FS, TYPE_CHECKED_LOAD_CONST_VCALL)
319       STRINGIFY_CODE(FS, VALUE_GUID)
320     }
321   case bitc::METADATA_ATTACHMENT_ID:
322     switch(CodeID) {
323     default:return nullptr;
324       STRINGIFY_CODE(METADATA, ATTACHMENT)
325     }
326   case bitc::METADATA_BLOCK_ID:
327     switch(CodeID) {
328     default:return nullptr;
329       STRINGIFY_CODE(METADATA, STRING_OLD)
330       STRINGIFY_CODE(METADATA, VALUE)
331       STRINGIFY_CODE(METADATA, NODE)
332       STRINGIFY_CODE(METADATA, NAME)
333       STRINGIFY_CODE(METADATA, DISTINCT_NODE)
334       STRINGIFY_CODE(METADATA, KIND) // Older bitcode has it in a MODULE_BLOCK
335       STRINGIFY_CODE(METADATA, LOCATION)
336       STRINGIFY_CODE(METADATA, OLD_NODE)
337       STRINGIFY_CODE(METADATA, OLD_FN_NODE)
338       STRINGIFY_CODE(METADATA, NAMED_NODE)
339       STRINGIFY_CODE(METADATA, GENERIC_DEBUG)
340       STRINGIFY_CODE(METADATA, SUBRANGE)
341       STRINGIFY_CODE(METADATA, ENUMERATOR)
342       STRINGIFY_CODE(METADATA, BASIC_TYPE)
343       STRINGIFY_CODE(METADATA, FILE)
344       STRINGIFY_CODE(METADATA, DERIVED_TYPE)
345       STRINGIFY_CODE(METADATA, COMPOSITE_TYPE)
346       STRINGIFY_CODE(METADATA, SUBROUTINE_TYPE)
347       STRINGIFY_CODE(METADATA, COMPILE_UNIT)
348       STRINGIFY_CODE(METADATA, SUBPROGRAM)
349       STRINGIFY_CODE(METADATA, LEXICAL_BLOCK)
350       STRINGIFY_CODE(METADATA, LEXICAL_BLOCK_FILE)
351       STRINGIFY_CODE(METADATA, NAMESPACE)
352       STRINGIFY_CODE(METADATA, TEMPLATE_TYPE)
353       STRINGIFY_CODE(METADATA, TEMPLATE_VALUE)
354       STRINGIFY_CODE(METADATA, GLOBAL_VAR)
355       STRINGIFY_CODE(METADATA, LOCAL_VAR)
356       STRINGIFY_CODE(METADATA, EXPRESSION)
357       STRINGIFY_CODE(METADATA, OBJC_PROPERTY)
358       STRINGIFY_CODE(METADATA, IMPORTED_ENTITY)
359       STRINGIFY_CODE(METADATA, MODULE)
360       STRINGIFY_CODE(METADATA, MACRO)
361       STRINGIFY_CODE(METADATA, MACRO_FILE)
362       STRINGIFY_CODE(METADATA, STRINGS)
363       STRINGIFY_CODE(METADATA, GLOBAL_DECL_ATTACHMENT)
364       STRINGIFY_CODE(METADATA, GLOBAL_VAR_EXPR)
365       STRINGIFY_CODE(METADATA, INDEX_OFFSET)
366       STRINGIFY_CODE(METADATA, INDEX)
367     }
368   case bitc::METADATA_KIND_BLOCK_ID:
369     switch (CodeID) {
370     default:
371       return nullptr;
372       STRINGIFY_CODE(METADATA, KIND)
373     }
374   case bitc::USELIST_BLOCK_ID:
375     switch(CodeID) {
376     default:return nullptr;
377     case bitc::USELIST_CODE_DEFAULT: return "USELIST_CODE_DEFAULT";
378     case bitc::USELIST_CODE_BB:      return "USELIST_CODE_BB";
379     }
380
381   case bitc::OPERAND_BUNDLE_TAGS_BLOCK_ID:
382     switch(CodeID) {
383     default: return nullptr;
384     case bitc::OPERAND_BUNDLE_TAG: return "OPERAND_BUNDLE_TAG";
385     }
386   case bitc::STRTAB_BLOCK_ID:
387     switch(CodeID) {
388     default: return nullptr;
389     case bitc::STRTAB_BLOB: return "BLOB";
390     }
391   }
392 #undef STRINGIFY_CODE
393 }
394
395 struct PerRecordStats {
396   unsigned NumInstances;
397   unsigned NumAbbrev;
398   uint64_t TotalBits;
399
400   PerRecordStats() : NumInstances(0), NumAbbrev(0), TotalBits(0) {}
401 };
402
403 struct PerBlockIDStats {
404   /// NumInstances - This the number of times this block ID has been seen.
405   unsigned NumInstances;
406
407   /// NumBits - The total size in bits of all of these blocks.
408   uint64_t NumBits;
409
410   /// NumSubBlocks - The total number of blocks these blocks contain.
411   unsigned NumSubBlocks;
412
413   /// NumAbbrevs - The total number of abbreviations.
414   unsigned NumAbbrevs;
415
416   /// NumRecords - The total number of records these blocks contain, and the
417   /// number that are abbreviated.
418   unsigned NumRecords, NumAbbreviatedRecords;
419
420   /// CodeFreq - Keep track of the number of times we see each code.
421   std::vector<PerRecordStats> CodeFreq;
422
423   PerBlockIDStats()
424     : NumInstances(0), NumBits(0),
425       NumSubBlocks(0), NumAbbrevs(0), NumRecords(0), NumAbbreviatedRecords(0) {}
426 };
427
428 static std::map<unsigned, PerBlockIDStats> BlockIDStats;
429
430
431
432 /// ReportError - All bitcode analysis errors go through this function, making this a
433 /// good place to breakpoint if debugging.
434 static bool ReportError(const Twine &Err) {
435   errs() << Err << "\n";
436   return true;
437 }
438
439 static bool decodeMetadataStringsBlob(StringRef Indent,
440                                       ArrayRef<uint64_t> Record,
441                                       StringRef Blob) {
442   if (Blob.empty())
443     return true;
444
445   if (Record.size() != 2)
446     return true;
447
448   unsigned NumStrings = Record[0];
449   unsigned StringsOffset = Record[1];
450   outs() << " num-strings = " << NumStrings << " {\n";
451
452   StringRef Lengths = Blob.slice(0, StringsOffset);
453   SimpleBitstreamCursor R(Lengths);
454   StringRef Strings = Blob.drop_front(StringsOffset);
455   do {
456     if (R.AtEndOfStream())
457       return ReportError("bad length");
458
459     unsigned Size = R.ReadVBR(6);
460     if (Strings.size() < Size)
461       return ReportError("truncated chars");
462
463     outs() << Indent << "    '";
464     outs().write_escaped(Strings.slice(0, Size), /*hex=*/true);
465     outs() << "'\n";
466     Strings = Strings.drop_front(Size);
467   } while (--NumStrings);
468
469   outs() << Indent << "  }";
470   return false;
471 }
472
473 static bool decodeBlob(unsigned Code, unsigned BlockID, StringRef Indent,
474                        ArrayRef<uint64_t> Record, StringRef Blob) {
475   if (BlockID != bitc::METADATA_BLOCK_ID)
476     return true;
477   if (Code != bitc::METADATA_STRINGS)
478     return true;
479
480   return decodeMetadataStringsBlob(Indent, Record, Blob);
481 }
482
483 /// ParseBlock - Read a block, updating statistics, etc.
484 static bool ParseBlock(BitstreamCursor &Stream, BitstreamBlockInfo &BlockInfo,
485                        unsigned BlockID, unsigned IndentLevel,
486                        CurStreamTypeType CurStreamType) {
487   std::string Indent(IndentLevel*2, ' ');
488   uint64_t BlockBitStart = Stream.GetCurrentBitNo();
489
490   // Get the statistics for this BlockID.
491   PerBlockIDStats &BlockStats = BlockIDStats[BlockID];
492
493   BlockStats.NumInstances++;
494
495   // BLOCKINFO is a special part of the stream.
496   bool DumpRecords = Dump;
497   if (BlockID == bitc::BLOCKINFO_BLOCK_ID) {
498     if (Dump) outs() << Indent << "<BLOCKINFO_BLOCK/>\n";
499     Optional<BitstreamBlockInfo> NewBlockInfo =
500         Stream.ReadBlockInfoBlock(/*ReadBlockInfoNames=*/true);
501     if (!NewBlockInfo)
502       return ReportError("Malformed BlockInfoBlock");
503     BlockInfo = std::move(*NewBlockInfo);
504     Stream.JumpToBit(BlockBitStart);
505     // It's not really interesting to dump the contents of the blockinfo block.
506     DumpRecords = false;
507   }
508
509   unsigned NumWords = 0;
510   if (Stream.EnterSubBlock(BlockID, &NumWords))
511     return ReportError("Malformed block record");
512
513   // Keep it for later, when we see a MODULE_HASH record
514   uint64_t BlockEntryPos = Stream.getCurrentByteNo();
515
516   const char *BlockName = nullptr;
517   if (DumpRecords) {
518     outs() << Indent << "<";
519     if ((BlockName = GetBlockName(BlockID, BlockInfo, CurStreamType)))
520       outs() << BlockName;
521     else
522       outs() << "UnknownBlock" << BlockID;
523
524     if (NonSymbolic && BlockName)
525       outs() << " BlockID=" << BlockID;
526
527     outs() << " NumWords=" << NumWords
528            << " BlockCodeSize=" << Stream.getAbbrevIDWidth() << ">\n";
529   }
530
531   SmallVector<uint64_t, 64> Record;
532
533   // Keep the offset to the metadata index if seen.
534   uint64_t MetadataIndexOffset = 0;
535
536   // Read all the records for this block.
537   while (1) {
538     if (Stream.AtEndOfStream())
539       return ReportError("Premature end of bitstream");
540
541     uint64_t RecordStartBit = Stream.GetCurrentBitNo();
542
543     BitstreamEntry Entry =
544       Stream.advance(BitstreamCursor::AF_DontAutoprocessAbbrevs);
545     
546     switch (Entry.Kind) {
547     case BitstreamEntry::Error:
548       return ReportError("malformed bitcode file");
549     case BitstreamEntry::EndBlock: {
550       uint64_t BlockBitEnd = Stream.GetCurrentBitNo();
551       BlockStats.NumBits += BlockBitEnd-BlockBitStart;
552       if (DumpRecords) {
553         outs() << Indent << "</";
554         if (BlockName)
555           outs() << BlockName << ">\n";
556         else
557           outs() << "UnknownBlock" << BlockID << ">\n";
558       }
559       return false;
560     }
561         
562     case BitstreamEntry::SubBlock: {
563       uint64_t SubBlockBitStart = Stream.GetCurrentBitNo();
564       if (ParseBlock(Stream, BlockInfo, Entry.ID, IndentLevel + 1,
565                      CurStreamType))
566         return true;
567       ++BlockStats.NumSubBlocks;
568       uint64_t SubBlockBitEnd = Stream.GetCurrentBitNo();
569       
570       // Don't include subblock sizes in the size of this block.
571       BlockBitStart += SubBlockBitEnd-SubBlockBitStart;
572       continue;
573     }
574     case BitstreamEntry::Record:
575       // The interesting case.
576       break;
577     }
578
579     if (Entry.ID == bitc::DEFINE_ABBREV) {
580       Stream.ReadAbbrevRecord();
581       ++BlockStats.NumAbbrevs;
582       continue;
583     }
584     
585     Record.clear();
586
587     ++BlockStats.NumRecords;
588
589     StringRef Blob;
590     unsigned CurrentRecordPos = Stream.GetCurrentBitNo();
591     unsigned Code = Stream.readRecord(Entry.ID, Record, &Blob);
592
593     // Increment the # occurrences of this code.
594     if (BlockStats.CodeFreq.size() <= Code)
595       BlockStats.CodeFreq.resize(Code+1);
596     BlockStats.CodeFreq[Code].NumInstances++;
597     BlockStats.CodeFreq[Code].TotalBits +=
598       Stream.GetCurrentBitNo()-RecordStartBit;
599     if (Entry.ID != bitc::UNABBREV_RECORD) {
600       BlockStats.CodeFreq[Code].NumAbbrev++;
601       ++BlockStats.NumAbbreviatedRecords;
602     }
603
604     if (DumpRecords) {
605       outs() << Indent << "  <";
606       if (const char *CodeName =
607               GetCodeName(Code, BlockID, BlockInfo, CurStreamType))
608         outs() << CodeName;
609       else
610         outs() << "UnknownCode" << Code;
611       if (NonSymbolic && GetCodeName(Code, BlockID, BlockInfo, CurStreamType))
612         outs() << " codeid=" << Code;
613       const BitCodeAbbrev *Abbv = nullptr;
614       if (Entry.ID != bitc::UNABBREV_RECORD) {
615         Abbv = Stream.getAbbrev(Entry.ID);
616         outs() << " abbrevid=" << Entry.ID;
617       }
618
619       for (unsigned i = 0, e = Record.size(); i != e; ++i)
620         outs() << " op" << i << "=" << (int64_t)Record[i];
621
622       // If we found a metadata index, let's verify that we had an offset before
623       // and validate its forward reference offset was correct!
624       if (BlockID == bitc::METADATA_BLOCK_ID) {
625         if (Code == bitc::METADATA_INDEX_OFFSET) {
626           if (Record.size() != 2)
627             outs() << "(Invalid record)";
628           else {
629             auto Offset = Record[0] + (Record[1] << 32);
630             MetadataIndexOffset = Stream.GetCurrentBitNo() + Offset;
631           }
632         }
633         if (Code == bitc::METADATA_INDEX) {
634           outs() << " (offset ";
635           if (MetadataIndexOffset == RecordStartBit)
636             outs() << "match)";
637           else
638             outs() << "mismatch: " << MetadataIndexOffset << " vs "
639                    << RecordStartBit << ")";
640         }
641       }
642
643       // If we found a module hash, let's verify that it matches!
644       if (BlockID == bitc::MODULE_BLOCK_ID && Code == bitc::MODULE_CODE_HASH) {
645         if (Record.size() != 5)
646           outs() << " (invalid)";
647         else {
648           // Recompute the hash and compare it to the one in the bitcode
649           SHA1 Hasher;
650           StringRef Hash;
651           {
652             int BlockSize = (CurrentRecordPos / 8) - BlockEntryPos;
653             auto Ptr = Stream.getPointerToByte(BlockEntryPos, BlockSize);
654             Hasher.update(ArrayRef<uint8_t>(Ptr, BlockSize));
655             Hash = Hasher.result();
656           }
657           SmallString<20> RecordedHash;
658           RecordedHash.resize(20);
659           int Pos = 0;
660           for (auto &Val : Record) {
661             assert(!(Val >> 32) && "Unexpected high bits set");
662             RecordedHash[Pos++] = (Val >> 24) & 0xFF;
663             RecordedHash[Pos++] = (Val >> 16) & 0xFF;
664             RecordedHash[Pos++] = (Val >> 8) & 0xFF;
665             RecordedHash[Pos++] = (Val >> 0) & 0xFF;
666           }
667           if (Hash == RecordedHash)
668             outs() << " (match)";
669           else
670             outs() << " (!mismatch!)";
671         }
672       }
673
674       outs() << "/>";
675
676       if (Abbv) {
677         for (unsigned i = 1, e = Abbv->getNumOperandInfos(); i != e; ++i) {
678           const BitCodeAbbrevOp &Op = Abbv->getOperandInfo(i);
679           if (!Op.isEncoding() || Op.getEncoding() != BitCodeAbbrevOp::Array)
680             continue;
681           assert(i + 2 == e && "Array op not second to last");
682           std::string Str;
683           bool ArrayIsPrintable = true;
684           for (unsigned j = i - 1, je = Record.size(); j != je; ++j) {
685             if (!isprint(static_cast<unsigned char>(Record[j]))) {
686               ArrayIsPrintable = false;
687               break;
688             }
689             Str += (char)Record[j];
690           }
691           if (ArrayIsPrintable)
692             outs() << " record string = '" << Str << "'";
693           break;
694         }
695       }
696
697       if (Blob.data() && decodeBlob(Code, BlockID, Indent, Record, Blob)) {
698         outs() << " blob data = ";
699         if (ShowBinaryBlobs) {
700           outs() << "'";
701           outs().write_escaped(Blob, /*hex=*/true) << "'";
702         } else {
703           bool BlobIsPrintable = true;
704           for (unsigned i = 0, e = Blob.size(); i != e; ++i)
705             if (!isprint(static_cast<unsigned char>(Blob[i]))) {
706               BlobIsPrintable = false;
707               break;
708             }
709
710           if (BlobIsPrintable)
711             outs() << "'" << Blob << "'";
712           else
713             outs() << "unprintable, " << Blob.size() << " bytes.";          
714         }
715       }
716
717       outs() << "\n";
718     }
719
720     // Make sure that we can skip the current record.
721     Stream.JumpToBit(CurrentRecordPos);
722     Stream.skipRecord(Entry.ID);
723   }
724 }
725
726 static void PrintSize(double Bits) {
727   outs() << format("%.2f/%.2fB/%luW", Bits, Bits/8,(unsigned long)(Bits/32));
728 }
729 static void PrintSize(uint64_t Bits) {
730   outs() << format("%lub/%.2fB/%luW", (unsigned long)Bits,
731                    (double)Bits/8, (unsigned long)(Bits/32));
732 }
733
734 static bool openBitcodeFile(StringRef Path,
735                             std::unique_ptr<MemoryBuffer> &MemBuf,
736                             BitstreamCursor &Stream,
737                             CurStreamTypeType &CurStreamType) {
738   // Read the input file.
739   ErrorOr<std::unique_ptr<MemoryBuffer>> MemBufOrErr =
740       MemoryBuffer::getFileOrSTDIN(Path);
741   if (std::error_code EC = MemBufOrErr.getError())
742     return ReportError(Twine("ReportError reading '") + Path + "': " + EC.message());
743   MemBuf = std::move(MemBufOrErr.get());
744
745   if (MemBuf->getBufferSize() & 3)
746     return ReportError("Bitcode stream should be a multiple of 4 bytes in length");
747
748   const unsigned char *BufPtr = (const unsigned char *)MemBuf->getBufferStart();
749   const unsigned char *EndBufPtr = BufPtr + MemBuf->getBufferSize();
750
751   // If we have a wrapper header, parse it and ignore the non-bc file contents.
752   // The magic number is 0x0B17C0DE stored in little endian.
753   if (isBitcodeWrapper(BufPtr, EndBufPtr)) {
754     if (MemBuf->getBufferSize() < BWH_HeaderSize)
755       return ReportError("Invalid bitcode wrapper header");
756
757     if (Dump) {
758       unsigned Magic = support::endian::read32le(&BufPtr[BWH_MagicField]);
759       unsigned Version = support::endian::read32le(&BufPtr[BWH_VersionField]);
760       unsigned Offset = support::endian::read32le(&BufPtr[BWH_OffsetField]);
761       unsigned Size = support::endian::read32le(&BufPtr[BWH_SizeField]);
762       unsigned CPUType = support::endian::read32le(&BufPtr[BWH_CPUTypeField]);
763
764       outs() << "<BITCODE_WRAPPER_HEADER"
765              << " Magic=" << format_hex(Magic, 10)
766              << " Version=" << format_hex(Version, 10)
767              << " Offset=" << format_hex(Offset, 10)
768              << " Size=" << format_hex(Size, 10)
769              << " CPUType=" << format_hex(CPUType, 10) << "/>\n";
770     }
771
772     if (SkipBitcodeWrapperHeader(BufPtr, EndBufPtr, true))
773       return ReportError("Invalid bitcode wrapper header");
774   }
775
776   Stream = BitstreamCursor(ArrayRef<uint8_t>(BufPtr, EndBufPtr));
777
778   // Read the stream signature.
779   char Signature[6];
780   Signature[0] = Stream.Read(8);
781   Signature[1] = Stream.Read(8);
782   Signature[2] = Stream.Read(4);
783   Signature[3] = Stream.Read(4);
784   Signature[4] = Stream.Read(4);
785   Signature[5] = Stream.Read(4);
786
787   // Autodetect the file contents, if it is one we know.
788   CurStreamType = UnknownBitstream;
789   if (Signature[0] == 'B' && Signature[1] == 'C' &&
790       Signature[2] == 0x0 && Signature[3] == 0xC &&
791       Signature[4] == 0xE && Signature[5] == 0xD)
792     CurStreamType = LLVMIRBitstream;
793
794   return false;
795 }
796
797 /// AnalyzeBitcode - Analyze the bitcode file specified by InputFilename.
798 static int AnalyzeBitcode() {
799   std::unique_ptr<MemoryBuffer> StreamBuffer;
800   BitstreamCursor Stream;
801   BitstreamBlockInfo BlockInfo;
802   CurStreamTypeType CurStreamType;
803   if (openBitcodeFile(InputFilename, StreamBuffer, Stream, CurStreamType))
804     return true;
805   Stream.setBlockInfo(&BlockInfo);
806
807   // Read block info from BlockInfoFilename, if specified.
808   // The block info must be a top-level block.
809   if (!BlockInfoFilename.empty()) {
810     std::unique_ptr<MemoryBuffer> BlockInfoBuffer;
811     BitstreamCursor BlockInfoCursor;
812     CurStreamTypeType BlockInfoStreamType;
813     if (openBitcodeFile(BlockInfoFilename, BlockInfoBuffer, BlockInfoCursor,
814                         BlockInfoStreamType))
815       return true;
816
817     while (!BlockInfoCursor.AtEndOfStream()) {
818       unsigned Code = BlockInfoCursor.ReadCode();
819       if (Code != bitc::ENTER_SUBBLOCK)
820         return ReportError("Invalid record at top-level in block info file");
821
822       unsigned BlockID = BlockInfoCursor.ReadSubBlockID();
823       if (BlockID == bitc::BLOCKINFO_BLOCK_ID) {
824         Optional<BitstreamBlockInfo> NewBlockInfo =
825             BlockInfoCursor.ReadBlockInfoBlock(/*ReadBlockInfoNames=*/true);
826         if (!NewBlockInfo)
827           return ReportError("Malformed BlockInfoBlock in block info file");
828         BlockInfo = std::move(*NewBlockInfo);
829         break;
830       }
831
832       BlockInfoCursor.SkipBlock();
833     }
834   }
835
836   unsigned NumTopBlocks = 0;
837
838   // Parse the top-level structure.  We only allow blocks at the top-level.
839   while (!Stream.AtEndOfStream()) {
840     unsigned Code = Stream.ReadCode();
841     if (Code != bitc::ENTER_SUBBLOCK)
842       return ReportError("Invalid record at top-level");
843
844     unsigned BlockID = Stream.ReadSubBlockID();
845
846     if (ParseBlock(Stream, BlockInfo, BlockID, 0, CurStreamType))
847       return true;
848     ++NumTopBlocks;
849   }
850
851   if (Dump) outs() << "\n\n";
852
853   uint64_t BufferSizeBits = Stream.getBitcodeBytes().size() * CHAR_BIT;
854   // Print a summary of the read file.
855   outs() << "Summary of " << InputFilename << ":\n";
856   outs() << "         Total size: ";
857   PrintSize(BufferSizeBits);
858   outs() << "\n";
859   outs() << "        Stream type: ";
860   switch (CurStreamType) {
861   case UnknownBitstream: outs() << "unknown\n"; break;
862   case LLVMIRBitstream:  outs() << "LLVM IR\n"; break;
863   }
864   outs() << "  # Toplevel Blocks: " << NumTopBlocks << "\n";
865   outs() << "\n";
866
867   // Emit per-block stats.
868   outs() << "Per-block Summary:\n";
869   for (std::map<unsigned, PerBlockIDStats>::iterator I = BlockIDStats.begin(),
870        E = BlockIDStats.end(); I != E; ++I) {
871     outs() << "  Block ID #" << I->first;
872     if (const char *BlockName =
873             GetBlockName(I->first, BlockInfo, CurStreamType))
874       outs() << " (" << BlockName << ")";
875     outs() << ":\n";
876
877     const PerBlockIDStats &Stats = I->second;
878     outs() << "      Num Instances: " << Stats.NumInstances << "\n";
879     outs() << "         Total Size: ";
880     PrintSize(Stats.NumBits);
881     outs() << "\n";
882     double pct = (Stats.NumBits * 100.0) / BufferSizeBits;
883     outs() << "    Percent of file: " << format("%2.4f%%", pct) << "\n";
884     if (Stats.NumInstances > 1) {
885       outs() << "       Average Size: ";
886       PrintSize(Stats.NumBits/(double)Stats.NumInstances);
887       outs() << "\n";
888       outs() << "  Tot/Avg SubBlocks: " << Stats.NumSubBlocks << "/"
889              << Stats.NumSubBlocks/(double)Stats.NumInstances << "\n";
890       outs() << "    Tot/Avg Abbrevs: " << Stats.NumAbbrevs << "/"
891              << Stats.NumAbbrevs/(double)Stats.NumInstances << "\n";
892       outs() << "    Tot/Avg Records: " << Stats.NumRecords << "/"
893              << Stats.NumRecords/(double)Stats.NumInstances << "\n";
894     } else {
895       outs() << "      Num SubBlocks: " << Stats.NumSubBlocks << "\n";
896       outs() << "        Num Abbrevs: " << Stats.NumAbbrevs << "\n";
897       outs() << "        Num Records: " << Stats.NumRecords << "\n";
898     }
899     if (Stats.NumRecords) {
900       double pct = (Stats.NumAbbreviatedRecords * 100.0) / Stats.NumRecords;
901       outs() << "    Percent Abbrevs: " << format("%2.4f%%", pct) << "\n";
902     }
903     outs() << "\n";
904
905     // Print a histogram of the codes we see.
906     if (!NoHistogram && !Stats.CodeFreq.empty()) {
907       std::vector<std::pair<unsigned, unsigned> > FreqPairs;  // <freq,code>
908       for (unsigned i = 0, e = Stats.CodeFreq.size(); i != e; ++i)
909         if (unsigned Freq = Stats.CodeFreq[i].NumInstances)
910           FreqPairs.push_back(std::make_pair(Freq, i));
911       std::stable_sort(FreqPairs.begin(), FreqPairs.end());
912       std::reverse(FreqPairs.begin(), FreqPairs.end());
913
914       outs() << "\tRecord Histogram:\n";
915       outs() << "\t\t  Count    # Bits     b/Rec   % Abv  Record Kind\n";
916       for (unsigned i = 0, e = FreqPairs.size(); i != e; ++i) {
917         const PerRecordStats &RecStats = Stats.CodeFreq[FreqPairs[i].second];
918
919         outs() << format("\t\t%7d %9lu",
920                          RecStats.NumInstances,
921                          (unsigned long)RecStats.TotalBits);
922
923         if (RecStats.NumInstances > 1)
924           outs() << format(" %9.1f",
925                            (double)RecStats.TotalBits/RecStats.NumInstances);
926         else
927           outs() << "          ";
928
929         if (RecStats.NumAbbrev)
930           outs() <<
931               format(" %7.2f",
932                      (double)RecStats.NumAbbrev/RecStats.NumInstances*100);
933         else
934           outs() << "        ";
935
936         outs() << "  ";
937         if (const char *CodeName = GetCodeName(FreqPairs[i].second, I->first,
938                                                BlockInfo, CurStreamType))
939           outs() << CodeName << "\n";
940         else
941           outs() << "UnknownCode" << FreqPairs[i].second << "\n";
942       }
943       outs() << "\n";
944
945     }
946   }
947   return 0;
948 }
949
950
951 int main(int argc, char **argv) {
952   // Print a stack trace if we signal out.
953   sys::PrintStackTraceOnErrorSignal(argv[0]);
954   PrettyStackTraceProgram X(argc, argv);
955   llvm_shutdown_obj Y;  // Call llvm_shutdown() on exit.
956   cl::ParseCommandLineOptions(argc, argv, "llvm-bcanalyzer file analyzer\n");
957
958   return AnalyzeBitcode();
959 }