Bug Summary

File:tools/llvm-bcanalyzer/llvm-bcanalyzer.cpp
Warning:line 210, column 39
The result of the right shift is undefined due to shifting by '64', which is greater or equal to the width of type 'llvm::SimpleBitstreamCursor::word_t'

Annotated Source Code

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

/build/llvm-toolchain-snapshot-6.0~svn318631/include/llvm/Bitcode/BitstreamReader.h

1//===- BitstreamReader.h - Low-level bitstream reader interface -*- C++ -*-===//
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 header defines the BitstreamReader class. This class can be used to
11// read an arbitrary bitstream, regardless of its contents.
12//
13//===----------------------------------------------------------------------===//
14
15#ifndef LLVM_BITCODE_BITSTREAMREADER_H
16#define LLVM_BITCODE_BITSTREAMREADER_H
17
18#include "llvm/ADT/ArrayRef.h"
19#include "llvm/ADT/SmallVector.h"
20#include "llvm/Bitcode/BitCodes.h"
21#include "llvm/Support/Endian.h"
22#include "llvm/Support/ErrorHandling.h"
23#include "llvm/Support/MathExtras.h"
24#include "llvm/Support/MemoryBuffer.h"
25#include <algorithm>
26#include <cassert>
27#include <climits>
28#include <cstddef>
29#include <cstdint>
30#include <memory>
31#include <string>
32#include <utility>
33#include <vector>
34
35namespace llvm {
36
37/// This class maintains the abbreviations read from a block info block.
38class BitstreamBlockInfo {
39public:
40 /// This contains information emitted to BLOCKINFO_BLOCK blocks. These
41 /// describe abbreviations that all blocks of the specified ID inherit.
42 struct BlockInfo {
43 unsigned BlockID;
44 std::vector<std::shared_ptr<BitCodeAbbrev>> Abbrevs;
45 std::string Name;
46 std::vector<std::pair<unsigned, std::string>> RecordNames;
47 };
48
49private:
50 std::vector<BlockInfo> BlockInfoRecords;
51
52public:
53 /// If there is block info for the specified ID, return it, otherwise return
54 /// null.
55 const BlockInfo *getBlockInfo(unsigned BlockID) const {
56 // Common case, the most recent entry matches BlockID.
57 if (!BlockInfoRecords.empty() && BlockInfoRecords.back().BlockID == BlockID)
58 return &BlockInfoRecords.back();
59
60 for (unsigned i = 0, e = static_cast<unsigned>(BlockInfoRecords.size());
61 i != e; ++i)
62 if (BlockInfoRecords[i].BlockID == BlockID)
63 return &BlockInfoRecords[i];
64 return nullptr;
65 }
66
67 BlockInfo &getOrCreateBlockInfo(unsigned BlockID) {
68 if (const BlockInfo *BI = getBlockInfo(BlockID))
69 return *const_cast<BlockInfo*>(BI);
70
71 // Otherwise, add a new record.
72 BlockInfoRecords.emplace_back();
73 BlockInfoRecords.back().BlockID = BlockID;
74 return BlockInfoRecords.back();
75 }
76};
77
78/// This represents a position within a bitstream. There may be multiple
79/// independent cursors reading within one bitstream, each maintaining their
80/// own local state.
81class SimpleBitstreamCursor {
82 ArrayRef<uint8_t> BitcodeBytes;
83 size_t NextChar = 0;
84
85public:
86 /// This is the current data we have pulled from the stream but have not
87 /// returned to the client. This is specifically and intentionally defined to
88 /// follow the word size of the host machine for efficiency. We use word_t in
89 /// places that are aware of this to make it perfectly explicit what is going
90 /// on.
91 using word_t = size_t;
92
93private:
94 word_t CurWord = 0;
95
96 /// This is the number of bits in CurWord that are valid. This is always from
97 /// [0...bits_of(size_t)-1] inclusive.
98 unsigned BitsInCurWord = 0;
99
100public:
101 static const size_t MaxChunkSize = sizeof(word_t) * 8;
102
103 SimpleBitstreamCursor() = default;
104 explicit SimpleBitstreamCursor(ArrayRef<uint8_t> BitcodeBytes)
105 : BitcodeBytes(BitcodeBytes) {}
106 explicit SimpleBitstreamCursor(StringRef BitcodeBytes)
107 : BitcodeBytes(reinterpret_cast<const uint8_t *>(BitcodeBytes.data()),
108 BitcodeBytes.size()) {}
109 explicit SimpleBitstreamCursor(MemoryBufferRef BitcodeBytes)
110 : SimpleBitstreamCursor(BitcodeBytes.getBuffer()) {}
111
112 bool canSkipToPos(size_t pos) const {
113 // pos can be skipped to if it is a valid address or one byte past the end.
114 return pos <= BitcodeBytes.size();
115 }
116
117 bool AtEndOfStream() {
118 return BitsInCurWord == 0 && BitcodeBytes.size() <= NextChar;
119 }
120
121 /// Return the bit # of the bit we are reading.
122 uint64_t GetCurrentBitNo() const {
123 return NextChar*CHAR_BIT8 - BitsInCurWord;
124 }
125
126 // Return the byte # of the current bit.
127 uint64_t getCurrentByteNo() const { return GetCurrentBitNo() / 8; }
128
129 ArrayRef<uint8_t> getBitcodeBytes() const { return BitcodeBytes; }
130
131 /// Reset the stream to the specified bit number.
132 void JumpToBit(uint64_t BitNo) {
133 size_t ByteNo = size_t(BitNo/8) & ~(sizeof(word_t)-1);
134 unsigned WordBitNo = unsigned(BitNo & (sizeof(word_t)*8-1));
135 assert(canSkipToPos(ByteNo) && "Invalid location")(static_cast <bool> (canSkipToPos(ByteNo) && "Invalid location"
) ? void (0) : __assert_fail ("canSkipToPos(ByteNo) && \"Invalid location\""
, "/build/llvm-toolchain-snapshot-6.0~svn318631/include/llvm/Bitcode/BitstreamReader.h"
, 135, __extension__ __PRETTY_FUNCTION__))
;
136
137 // Move the cursor to the right word.
138 NextChar = ByteNo;
139 BitsInCurWord = 0;
140
141 // Skip over any bits that are already consumed.
142 if (WordBitNo)
143 Read(WordBitNo);
144 }
145
146 /// Get a pointer into the bitstream at the specified byte offset.
147 const uint8_t *getPointerToByte(uint64_t ByteNo, uint64_t NumBytes) {
148 return BitcodeBytes.data() + ByteNo;
149 }
150
151 /// Get a pointer into the bitstream at the specified bit offset.
152 ///
153 /// The bit offset must be on a byte boundary.
154 const uint8_t *getPointerToBit(uint64_t BitNo, uint64_t NumBytes) {
155 assert(!(BitNo % 8) && "Expected bit on byte boundary")(static_cast <bool> (!(BitNo % 8) && "Expected bit on byte boundary"
) ? void (0) : __assert_fail ("!(BitNo % 8) && \"Expected bit on byte boundary\""
, "/build/llvm-toolchain-snapshot-6.0~svn318631/include/llvm/Bitcode/BitstreamReader.h"
, 155, __extension__ __PRETTY_FUNCTION__))
;
156 return getPointerToByte(BitNo / 8, NumBytes);
157 }
158
159 void fillCurWord() {
160 if (NextChar >= BitcodeBytes.size())
161 report_fatal_error("Unexpected end of file");
162
163 // Read the next word from the stream.
164 const uint8_t *NextCharPtr = BitcodeBytes.data() + NextChar;
165 unsigned BytesRead;
166 if (BitcodeBytes.size() >= NextChar + sizeof(word_t)) {
167 BytesRead = sizeof(word_t);
168 CurWord =
169 support::endian::read<word_t, support::little, support::unaligned>(
170 NextCharPtr);
171 } else {
172 // Short read.
173 BytesRead = BitcodeBytes.size() - NextChar;
174 CurWord = 0;
175 for (unsigned B = 0; B != BytesRead; ++B)
176 CurWord |= uint64_t(NextCharPtr[B]) << (B * 8);
177 }
178 NextChar += BytesRead;
179 BitsInCurWord = BytesRead * 8;
180 }
181
182 word_t Read(unsigned NumBits) {
183 static const unsigned BitsInWord = MaxChunkSize;
184
185 assert(NumBits && NumBits <= BitsInWord &&(static_cast <bool> (NumBits && NumBits <= BitsInWord
&& "Cannot return zero or more than BitsInWord bits!"
) ? void (0) : __assert_fail ("NumBits && NumBits <= BitsInWord && \"Cannot return zero or more than BitsInWord bits!\""
, "/build/llvm-toolchain-snapshot-6.0~svn318631/include/llvm/Bitcode/BitstreamReader.h"
, 186, __extension__ __PRETTY_FUNCTION__))
186 "Cannot return zero or more than BitsInWord bits!")(static_cast <bool> (NumBits && NumBits <= BitsInWord
&& "Cannot return zero or more than BitsInWord bits!"
) ? void (0) : __assert_fail ("NumBits && NumBits <= BitsInWord && \"Cannot return zero or more than BitsInWord bits!\""
, "/build/llvm-toolchain-snapshot-6.0~svn318631/include/llvm/Bitcode/BitstreamReader.h"
, 186, __extension__ __PRETTY_FUNCTION__))
;
187
188 static const unsigned Mask = sizeof(word_t) > 4 ? 0x3f : 0x1f;
14
'?' condition is true
189
190 // If the field is fully contained by CurWord, return it quickly.
191 if (BitsInCurWord >= NumBits) {
15
Taking false branch
192 word_t R = CurWord & (~word_t(0) >> (BitsInWord - NumBits));
193
194 // Use a mask to avoid undefined behavior.
195 CurWord >>= (NumBits & Mask);
196
197 BitsInCurWord -= NumBits;
198 return R;
199 }
200
201 word_t R = BitsInCurWord ? CurWord : 0;
16
'?' condition is true
202 unsigned BitsLeft = NumBits - BitsInCurWord;
203
204 fillCurWord();
205
206 // If we run out of data, abort.
207 if (BitsLeft > BitsInCurWord)
17
Assuming the condition is false
18
Taking false branch
208 report_fatal_error("Unexpected end of file");
209
210 word_t R2 = CurWord & (~word_t(0) >> (BitsInWord - BitsLeft));
19
The result of the right shift is undefined due to shifting by '64', which is greater or equal to the width of type 'llvm::SimpleBitstreamCursor::word_t'
211
212 // Use a mask to avoid undefined behavior.
213 CurWord >>= (BitsLeft & Mask);
214
215 BitsInCurWord -= BitsLeft;
216
217 R |= R2 << (NumBits - BitsLeft);
218
219 return R;
220 }
221
222 uint32_t ReadVBR(unsigned NumBits) {
223 uint32_t Piece = Read(NumBits);
224 if ((Piece & (1U << (NumBits-1))) == 0)
225 return Piece;
226
227 uint32_t Result = 0;
228 unsigned NextBit = 0;
229 while (true) {
230 Result |= (Piece & ((1U << (NumBits-1))-1)) << NextBit;
231
232 if ((Piece & (1U << (NumBits-1))) == 0)
233 return Result;
234
235 NextBit += NumBits-1;
236 Piece = Read(NumBits);
237 }
238 }
239
240 // Read a VBR that may have a value up to 64-bits in size. The chunk size of
241 // the VBR must still be <= 32 bits though.
242 uint64_t ReadVBR64(unsigned NumBits) {
243 uint32_t Piece = Read(NumBits);
244 if ((Piece & (1U << (NumBits-1))) == 0)
245 return uint64_t(Piece);
246
247 uint64_t Result = 0;
248 unsigned NextBit = 0;
249 while (true) {
250 Result |= uint64_t(Piece & ((1U << (NumBits-1))-1)) << NextBit;
251
252 if ((Piece & (1U << (NumBits-1))) == 0)
253 return Result;
254
255 NextBit += NumBits-1;
256 Piece = Read(NumBits);
257 }
258 }
259
260 void SkipToFourByteBoundary() {
261 // If word_t is 64-bits and if we've read less than 32 bits, just dump
262 // the bits we have up to the next 32-bit boundary.
263 if (sizeof(word_t) > 4 &&
264 BitsInCurWord >= 32) {
265 CurWord >>= BitsInCurWord-32;
266 BitsInCurWord = 32;
267 return;
268 }
269
270 BitsInCurWord = 0;
271 }
272
273 /// Skip to the end of the file.
274 void skipToEnd() { NextChar = BitcodeBytes.size(); }
275};
276
277/// When advancing through a bitstream cursor, each advance can discover a few
278/// different kinds of entries:
279struct BitstreamEntry {
280 enum {
281 Error, // Malformed bitcode was found.
282 EndBlock, // We've reached the end of the current block, (or the end of the
283 // file, which is treated like a series of EndBlock records.
284 SubBlock, // This is the start of a new subblock of a specific ID.
285 Record // This is a record with a specific AbbrevID.
286 } Kind;
287
288 unsigned ID;
289
290 static BitstreamEntry getError() {
291 BitstreamEntry E; E.Kind = Error; return E;
292 }
293
294 static BitstreamEntry getEndBlock() {
295 BitstreamEntry E; E.Kind = EndBlock; return E;
296 }
297
298 static BitstreamEntry getSubBlock(unsigned ID) {
299 BitstreamEntry E; E.Kind = SubBlock; E.ID = ID; return E;
300 }
301
302 static BitstreamEntry getRecord(unsigned AbbrevID) {
303 BitstreamEntry E; E.Kind = Record; E.ID = AbbrevID; return E;
304 }
305};
306
307/// This represents a position within a bitcode file, implemented on top of a
308/// SimpleBitstreamCursor.
309///
310/// Unlike iterators, BitstreamCursors are heavy-weight objects that should not
311/// be passed by value.
312class BitstreamCursor : SimpleBitstreamCursor {
313 // This is the declared size of code values used for the current block, in
314 // bits.
315 unsigned CurCodeSize = 2;
316
317 /// Abbrevs installed at in this block.
318 std::vector<std::shared_ptr<BitCodeAbbrev>> CurAbbrevs;
319
320 struct Block {
321 unsigned PrevCodeSize;
322 std::vector<std::shared_ptr<BitCodeAbbrev>> PrevAbbrevs;
323
324 explicit Block(unsigned PCS) : PrevCodeSize(PCS) {}
325 };
326
327 /// This tracks the codesize of parent blocks.
328 SmallVector<Block, 8> BlockScope;
329
330 BitstreamBlockInfo *BlockInfo = nullptr;
331
332public:
333 static const size_t MaxChunkSize = sizeof(word_t) * 8;
334
335 BitstreamCursor() = default;
336 explicit BitstreamCursor(ArrayRef<uint8_t> BitcodeBytes)
337 : SimpleBitstreamCursor(BitcodeBytes) {}
338 explicit BitstreamCursor(StringRef BitcodeBytes)
339 : SimpleBitstreamCursor(BitcodeBytes) {}
340 explicit BitstreamCursor(MemoryBufferRef BitcodeBytes)
341 : SimpleBitstreamCursor(BitcodeBytes) {}
342
343 using SimpleBitstreamCursor::canSkipToPos;
344 using SimpleBitstreamCursor::AtEndOfStream;
345 using SimpleBitstreamCursor::getBitcodeBytes;
346 using SimpleBitstreamCursor::GetCurrentBitNo;
347 using SimpleBitstreamCursor::getCurrentByteNo;
348 using SimpleBitstreamCursor::getPointerToByte;
349 using SimpleBitstreamCursor::JumpToBit;
350 using SimpleBitstreamCursor::fillCurWord;
351 using SimpleBitstreamCursor::Read;
352 using SimpleBitstreamCursor::ReadVBR;
353 using SimpleBitstreamCursor::ReadVBR64;
354
355 /// Return the number of bits used to encode an abbrev #.
356 unsigned getAbbrevIDWidth() const { return CurCodeSize; }
357
358 /// Flags that modify the behavior of advance().
359 enum {
360 /// If this flag is used, the advance() method does not automatically pop
361 /// the block scope when the end of a block is reached.
362 AF_DontPopBlockAtEnd = 1,
363
364 /// If this flag is used, abbrev entries are returned just like normal
365 /// records.
366 AF_DontAutoprocessAbbrevs = 2
367 };
368
369 /// Advance the current bitstream, returning the next entry in the stream.
370 BitstreamEntry advance(unsigned Flags = 0) {
371 while (true) {
10
Loop condition is true. Entering loop body
372 if (AtEndOfStream())
11
Taking false branch
373 return BitstreamEntry::getError();
374
375 unsigned Code = ReadCode();
12
Calling 'BitstreamCursor::ReadCode'
376 if (Code == bitc::END_BLOCK) {
377 // Pop the end of the block unless Flags tells us not to.
378 if (!(Flags & AF_DontPopBlockAtEnd) && ReadBlockEnd())
379 return BitstreamEntry::getError();
380 return BitstreamEntry::getEndBlock();
381 }
382
383 if (Code == bitc::ENTER_SUBBLOCK)
384 return BitstreamEntry::getSubBlock(ReadSubBlockID());
385
386 if (Code == bitc::DEFINE_ABBREV &&
387 !(Flags & AF_DontAutoprocessAbbrevs)) {
388 // We read and accumulate abbrev's, the client can't do anything with
389 // them anyway.
390 ReadAbbrevRecord();
391 continue;
392 }
393
394 return BitstreamEntry::getRecord(Code);
395 }
396 }
397
398 /// This is a convenience function for clients that don't expect any
399 /// subblocks. This just skips over them automatically.
400 BitstreamEntry advanceSkippingSubblocks(unsigned Flags = 0) {
401 while (true) {
402 // If we found a normal entry, return it.
403 BitstreamEntry Entry = advance(Flags);
404 if (Entry.Kind != BitstreamEntry::SubBlock)
405 return Entry;
406
407 // If we found a sub-block, just skip over it and check the next entry.
408 if (SkipBlock())
409 return BitstreamEntry::getError();
410 }
411 }
412
413 unsigned ReadCode() {
414 return Read(CurCodeSize);
13
Calling 'SimpleBitstreamCursor::Read'
415 }
416
417 // Block header:
418 // [ENTER_SUBBLOCK, blockid, newcodelen, <align4bytes>, blocklen]
419
420 /// Having read the ENTER_SUBBLOCK code, read the BlockID for the block.
421 unsigned ReadSubBlockID() {
422 return ReadVBR(bitc::BlockIDWidth);
423 }
424
425 /// Having read the ENTER_SUBBLOCK abbrevid and a BlockID, skip over the body
426 /// of this block. If the block record is malformed, return true.
427 bool SkipBlock() {
428 // Read and ignore the codelen value. Since we are skipping this block, we
429 // don't care what code widths are used inside of it.
430 ReadVBR(bitc::CodeLenWidth);
431 SkipToFourByteBoundary();
432 unsigned NumFourBytes = Read(bitc::BlockSizeWidth);
433
434 // Check that the block wasn't partially defined, and that the offset isn't
435 // bogus.
436 size_t SkipTo = GetCurrentBitNo() + NumFourBytes*4*8;
437 if (AtEndOfStream() || !canSkipToPos(SkipTo/8))
438 return true;
439
440 JumpToBit(SkipTo);
441 return false;
442 }
443
444 /// Having read the ENTER_SUBBLOCK abbrevid, enter the block, and return true
445 /// if the block has an error.
446 bool EnterSubBlock(unsigned BlockID, unsigned *NumWordsP = nullptr);
447
448 bool ReadBlockEnd() {
449 if (BlockScope.empty()) return true;
450
451 // Block tail:
452 // [END_BLOCK, <align4bytes>]
453 SkipToFourByteBoundary();
454
455 popBlockScope();
456 return false;
457 }
458
459private:
460 void popBlockScope() {
461 CurCodeSize = BlockScope.back().PrevCodeSize;
462
463 CurAbbrevs = std::move(BlockScope.back().PrevAbbrevs);
464 BlockScope.pop_back();
465 }
466
467 //===--------------------------------------------------------------------===//
468 // Record Processing
469 //===--------------------------------------------------------------------===//
470
471public:
472 /// Return the abbreviation for the specified AbbrevId.
473 const BitCodeAbbrev *getAbbrev(unsigned AbbrevID) {
474 unsigned AbbrevNo = AbbrevID - bitc::FIRST_APPLICATION_ABBREV;
475 if (AbbrevNo >= CurAbbrevs.size())
476 report_fatal_error("Invalid abbrev number");
477 return CurAbbrevs[AbbrevNo].get();
478 }
479
480 /// Read the current record and discard it, returning the code for the record.
481 unsigned skipRecord(unsigned AbbrevID);
482
483 unsigned readRecord(unsigned AbbrevID, SmallVectorImpl<uint64_t> &Vals,
484 StringRef *Blob = nullptr);
485
486 //===--------------------------------------------------------------------===//
487 // Abbrev Processing
488 //===--------------------------------------------------------------------===//
489 void ReadAbbrevRecord();
490
491 /// Read and return a block info block from the bitstream. If an error was
492 /// encountered, return None.
493 ///
494 /// \param ReadBlockInfoNames Whether to read block/record name information in
495 /// the BlockInfo block. Only llvm-bcanalyzer uses this.
496 Optional<BitstreamBlockInfo>
497 ReadBlockInfoBlock(bool ReadBlockInfoNames = false);
498
499 /// Set the block info to be used by this BitstreamCursor to interpret
500 /// abbreviated records.
501 void setBlockInfo(BitstreamBlockInfo *BI) { BlockInfo = BI; }
502};
503
504} // end llvm namespace
505
506#endif // LLVM_BITCODE_BITSTREAMREADER_H