llvm-bcanalyzer.cpp 26 KB

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