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