Counter Strike : Global Offensive Source Code
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

558 lines
17 KiB

  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. #ifndef LLVM_BITCODE_BITSTREAMREADER_H
  15. #define LLVM_BITCODE_BITSTREAMREADER_H
  16. #include "llvm/ADT/OwningPtr.h"
  17. #include "llvm/Bitcode/BitCodes.h"
  18. #include "llvm/Support/Endian.h"
  19. #include "llvm/Support/StreamableMemoryObject.h"
  20. #include <climits>
  21. #include <string>
  22. #include <vector>
  23. namespace llvm {
  24. class Deserializer;
  25. /// BitstreamReader - This class is used to read from an LLVM bitcode stream,
  26. /// maintaining information that is global to decoding the entire file. While
  27. /// a file is being read, multiple cursors can be independently advanced or
  28. /// skipped around within the file. These are represented by the
  29. /// BitstreamCursor class.
  30. class BitstreamReader {
  31. public:
  32. /// BlockInfo - This contains information emitted to BLOCKINFO_BLOCK blocks.
  33. /// These describe abbreviations that all blocks of the specified ID inherit.
  34. struct BlockInfo {
  35. unsigned BlockID;
  36. std::vector<BitCodeAbbrev*> Abbrevs;
  37. std::string Name;
  38. std::vector<std::pair<unsigned, std::string> > RecordNames;
  39. };
  40. private:
  41. OwningPtr<StreamableMemoryObject> BitcodeBytes;
  42. std::vector<BlockInfo> BlockInfoRecords;
  43. /// IgnoreBlockInfoNames - This is set to true if we don't care about the
  44. /// block/record name information in the BlockInfo block. Only llvm-bcanalyzer
  45. /// uses this.
  46. bool IgnoreBlockInfoNames;
  47. BitstreamReader(const BitstreamReader&) LLVM_DELETED_FUNCTION;
  48. void operator=(const BitstreamReader&) LLVM_DELETED_FUNCTION;
  49. public:
  50. BitstreamReader() : IgnoreBlockInfoNames(true) {
  51. }
  52. BitstreamReader(const unsigned char *Start, const unsigned char *End) {
  53. IgnoreBlockInfoNames = true;
  54. init(Start, End);
  55. }
  56. BitstreamReader(StreamableMemoryObject *bytes) {
  57. BitcodeBytes.reset(bytes);
  58. }
  59. void init(const unsigned char *Start, const unsigned char *End) {
  60. assert(((End-Start) & 3) == 0 &&"Bitcode stream not a multiple of 4 bytes");
  61. BitcodeBytes.reset(getNonStreamedMemoryObject(Start, End));
  62. }
  63. StreamableMemoryObject &getBitcodeBytes() { return *BitcodeBytes; }
  64. ~BitstreamReader() {
  65. // Free the BlockInfoRecords.
  66. while (!BlockInfoRecords.empty()) {
  67. BlockInfo &Info = BlockInfoRecords.back();
  68. // Free blockinfo abbrev info.
  69. for (unsigned i = 0, e = static_cast<unsigned>(Info.Abbrevs.size());
  70. i != e; ++i)
  71. Info.Abbrevs[i]->dropRef();
  72. BlockInfoRecords.pop_back();
  73. }
  74. }
  75. /// CollectBlockInfoNames - This is called by clients that want block/record
  76. /// name information.
  77. void CollectBlockInfoNames() { IgnoreBlockInfoNames = false; }
  78. bool isIgnoringBlockInfoNames() { return IgnoreBlockInfoNames; }
  79. //===--------------------------------------------------------------------===//
  80. // Block Manipulation
  81. //===--------------------------------------------------------------------===//
  82. /// hasBlockInfoRecords - Return true if we've already read and processed the
  83. /// block info block for this Bitstream. We only process it for the first
  84. /// cursor that walks over it.
  85. bool hasBlockInfoRecords() const { return !BlockInfoRecords.empty(); }
  86. /// getBlockInfo - If there is block info for the specified ID, return it,
  87. /// otherwise return null.
  88. const BlockInfo *getBlockInfo(unsigned BlockID) const {
  89. // Common case, the most recent entry matches BlockID.
  90. if (!BlockInfoRecords.empty() && BlockInfoRecords.back().BlockID == BlockID)
  91. return &BlockInfoRecords.back();
  92. for (unsigned i = 0, e = static_cast<unsigned>(BlockInfoRecords.size());
  93. i != e; ++i)
  94. if (BlockInfoRecords[i].BlockID == BlockID)
  95. return &BlockInfoRecords[i];
  96. return 0;
  97. }
  98. BlockInfo &getOrCreateBlockInfo(unsigned BlockID) {
  99. if (const BlockInfo *BI = getBlockInfo(BlockID))
  100. return *const_cast<BlockInfo*>(BI);
  101. // Otherwise, add a new record.
  102. BlockInfoRecords.push_back(BlockInfo());
  103. BlockInfoRecords.back().BlockID = BlockID;
  104. return BlockInfoRecords.back();
  105. }
  106. };
  107. /// BitstreamEntry - When advancing through a bitstream cursor, each advance can
  108. /// discover a few different kinds of entries:
  109. /// Error - Malformed bitcode was found.
  110. /// EndBlock - We've reached the end of the current block, (or the end of the
  111. /// file, which is treated like a series of EndBlock records.
  112. /// SubBlock - This is the start of a new subblock of a specific ID.
  113. /// Record - This is a record with a specific AbbrevID.
  114. ///
  115. struct BitstreamEntry {
  116. enum {
  117. Error,
  118. EndBlock,
  119. SubBlock,
  120. Record
  121. } Kind;
  122. unsigned ID;
  123. static BitstreamEntry getError() {
  124. BitstreamEntry E; E.Kind = Error; return E;
  125. }
  126. static BitstreamEntry getEndBlock() {
  127. BitstreamEntry E; E.Kind = EndBlock; return E;
  128. }
  129. static BitstreamEntry getSubBlock(unsigned ID) {
  130. BitstreamEntry E; E.Kind = SubBlock; E.ID = ID; return E;
  131. }
  132. static BitstreamEntry getRecord(unsigned AbbrevID) {
  133. BitstreamEntry E; E.Kind = Record; E.ID = AbbrevID; return E;
  134. }
  135. };
  136. /// BitstreamCursor - This represents a position within a bitcode file. There
  137. /// may be multiple independent cursors reading within one bitstream, each
  138. /// maintaining their own local state.
  139. ///
  140. /// Unlike iterators, BitstreamCursors are heavy-weight objects that should not
  141. /// be passed by value.
  142. class BitstreamCursor {
  143. friend class Deserializer;
  144. BitstreamReader *BitStream;
  145. size_t NextChar;
  146. /// CurWord/word_t - This is the current data we have pulled from the stream
  147. /// but have not returned to the client. This is specifically and
  148. /// intentionally defined to follow the word size of the host machine for
  149. /// efficiency. We use word_t in places that are aware of this to make it
  150. /// perfectly explicit what is going on.
  151. typedef uint32_t word_t;
  152. word_t CurWord;
  153. /// BitsInCurWord - This is the number of bits in CurWord that are valid. This
  154. /// is always from [0...31/63] inclusive (depending on word size).
  155. unsigned BitsInCurWord;
  156. // CurCodeSize - This is the declared size of code values used for the current
  157. // block, in bits.
  158. unsigned CurCodeSize;
  159. /// CurAbbrevs - Abbrevs installed at in this block.
  160. std::vector<BitCodeAbbrev*> CurAbbrevs;
  161. struct Block {
  162. unsigned PrevCodeSize;
  163. std::vector<BitCodeAbbrev*> PrevAbbrevs;
  164. explicit Block(unsigned PCS) : PrevCodeSize(PCS) {}
  165. };
  166. /// BlockScope - This tracks the codesize of parent blocks.
  167. SmallVector<Block, 8> BlockScope;
  168. public:
  169. BitstreamCursor() : BitStream(0), NextChar(0) {
  170. }
  171. BitstreamCursor(const BitstreamCursor &RHS) : BitStream(0), NextChar(0) {
  172. operator=(RHS);
  173. }
  174. explicit BitstreamCursor(BitstreamReader &R) : BitStream(&R) {
  175. NextChar = 0;
  176. CurWord = 0;
  177. BitsInCurWord = 0;
  178. CurCodeSize = 2;
  179. }
  180. void init(BitstreamReader &R) {
  181. freeState();
  182. BitStream = &R;
  183. NextChar = 0;
  184. CurWord = 0;
  185. BitsInCurWord = 0;
  186. CurCodeSize = 2;
  187. }
  188. ~BitstreamCursor() {
  189. freeState();
  190. }
  191. void operator=(const BitstreamCursor &RHS);
  192. void freeState();
  193. bool isEndPos(size_t pos) {
  194. return BitStream->getBitcodeBytes().isObjectEnd(static_cast<uint64_t>(pos));
  195. }
  196. bool canSkipToPos(size_t pos) const {
  197. // pos can be skipped to if it is a valid address or one byte past the end.
  198. return pos == 0 || BitStream->getBitcodeBytes().isValidAddress(
  199. static_cast<uint64_t>(pos - 1));
  200. }
  201. uint32_t getWord(size_t pos) {
  202. uint8_t buf[4] = { 0xFF, 0xFF, 0xFF, 0xFF };
  203. BitStream->getBitcodeBytes().readBytes(pos, sizeof(buf), buf, NULL);
  204. return *reinterpret_cast<support::ulittle32_t *>(buf);
  205. }
  206. bool AtEndOfStream() {
  207. return BitsInCurWord == 0 && isEndPos(NextChar);
  208. }
  209. /// getAbbrevIDWidth - Return the number of bits used to encode an abbrev #.
  210. unsigned getAbbrevIDWidth() const { return CurCodeSize; }
  211. /// GetCurrentBitNo - Return the bit # of the bit we are reading.
  212. uint64_t GetCurrentBitNo() const {
  213. return NextChar*CHAR_BIT - BitsInCurWord;
  214. }
  215. BitstreamReader *getBitStreamReader() {
  216. return BitStream;
  217. }
  218. const BitstreamReader *getBitStreamReader() const {
  219. return BitStream;
  220. }
  221. /// Flags that modify the behavior of advance().
  222. enum {
  223. /// AF_DontPopBlockAtEnd - If this flag is used, the advance() method does
  224. /// not automatically pop the block scope when the end of a block is
  225. /// reached.
  226. AF_DontPopBlockAtEnd = 1,
  227. /// AF_DontAutoprocessAbbrevs - If this flag is used, abbrev entries are
  228. /// returned just like normal records.
  229. AF_DontAutoprocessAbbrevs = 2
  230. };
  231. /// advance - Advance the current bitstream, returning the next entry in the
  232. /// stream.
  233. BitstreamEntry advance(unsigned Flags = 0) {
  234. while (1) {
  235. unsigned Code = ReadCode();
  236. if (Code == bitc::END_BLOCK) {
  237. // Pop the end of the block unless Flags tells us not to.
  238. if (!(Flags & AF_DontPopBlockAtEnd) && ReadBlockEnd())
  239. return BitstreamEntry::getError();
  240. return BitstreamEntry::getEndBlock();
  241. }
  242. if (Code == bitc::ENTER_SUBBLOCK)
  243. return BitstreamEntry::getSubBlock(ReadSubBlockID());
  244. if (Code == bitc::DEFINE_ABBREV &&
  245. !(Flags & AF_DontAutoprocessAbbrevs)) {
  246. // We read and accumulate abbrev's, the client can't do anything with
  247. // them anyway.
  248. ReadAbbrevRecord();
  249. continue;
  250. }
  251. return BitstreamEntry::getRecord(Code);
  252. }
  253. }
  254. /// advanceSkippingSubblocks - This is a convenience function for clients that
  255. /// don't expect any subblocks. This just skips over them automatically.
  256. BitstreamEntry advanceSkippingSubblocks(unsigned Flags = 0) {
  257. while (1) {
  258. // If we found a normal entry, return it.
  259. BitstreamEntry Entry = advance(Flags);
  260. if (Entry.Kind != BitstreamEntry::SubBlock)
  261. return Entry;
  262. // If we found a sub-block, just skip over it and check the next entry.
  263. if (SkipBlock())
  264. return BitstreamEntry::getError();
  265. }
  266. }
  267. /// JumpToBit - Reset the stream to the specified bit number.
  268. void JumpToBit(uint64_t BitNo) {
  269. uintptr_t ByteNo = uintptr_t(BitNo/8) & ~(sizeof(word_t)-1);
  270. unsigned WordBitNo = unsigned(BitNo & (sizeof(word_t)*8-1));
  271. assert(canSkipToPos(ByteNo) && "Invalid location");
  272. // Move the cursor to the right word.
  273. NextChar = ByteNo;
  274. BitsInCurWord = 0;
  275. CurWord = 0;
  276. // Skip over any bits that are already consumed.
  277. if (WordBitNo) {
  278. if (sizeof(word_t) > 4)
  279. Read64(WordBitNo);
  280. else
  281. Read(WordBitNo);
  282. }
  283. }
  284. uint32_t Read(unsigned NumBits) {
  285. assert(NumBits && NumBits <= 32 &&
  286. "Cannot return zero or more than 32 bits!");
  287. // If the field is fully contained by CurWord, return it quickly.
  288. if (BitsInCurWord >= NumBits) {
  289. uint32_t R = uint32_t(CurWord) & (~0U >> (32-NumBits));
  290. CurWord >>= NumBits;
  291. BitsInCurWord -= NumBits;
  292. return R;
  293. }
  294. // If we run out of data, stop at the end of the stream.
  295. if (isEndPos(NextChar)) {
  296. CurWord = 0;
  297. BitsInCurWord = 0;
  298. return 0;
  299. }
  300. uint32_t R = uint32_t(CurWord);
  301. // Read the next word from the stream.
  302. uint8_t Array[sizeof(word_t)] = {0};
  303. BitStream->getBitcodeBytes().readBytes(NextChar, sizeof(Array),
  304. Array, NULL);
  305. // Handle big-endian byte-swapping if necessary.
  306. support::detail::packed_endian_specific_integral
  307. <word_t, support::little, support::unaligned> EndianValue;
  308. memcpy(&EndianValue, Array, sizeof(Array));
  309. CurWord = EndianValue;
  310. NextChar += sizeof(word_t);
  311. // Extract NumBits-BitsInCurWord from what we just read.
  312. unsigned BitsLeft = NumBits-BitsInCurWord;
  313. // Be careful here, BitsLeft is in the range [1..32]/[1..64] inclusive.
  314. R |= uint32_t((CurWord & (word_t(~0ULL) >> (sizeof(word_t)*8-BitsLeft)))
  315. << BitsInCurWord);
  316. // BitsLeft bits have just been used up from CurWord. BitsLeft is in the
  317. // range [1..32]/[1..64] so be careful how we shift.
  318. if (BitsLeft != sizeof(word_t)*8)
  319. CurWord >>= BitsLeft;
  320. else
  321. CurWord = 0;
  322. BitsInCurWord = sizeof(word_t)*8-BitsLeft;
  323. return R;
  324. }
  325. uint64_t Read64(unsigned NumBits) {
  326. if (NumBits <= 32) return Read(NumBits);
  327. uint64_t V = Read(32);
  328. return V | (uint64_t)Read(NumBits-32) << 32;
  329. }
  330. uint32_t ReadVBR(unsigned NumBits) {
  331. uint32_t Piece = Read(NumBits);
  332. if ((Piece & (1U << (NumBits-1))) == 0)
  333. return Piece;
  334. uint32_t Result = 0;
  335. unsigned NextBit = 0;
  336. while (1) {
  337. Result |= (Piece & ((1U << (NumBits-1))-1)) << NextBit;
  338. if ((Piece & (1U << (NumBits-1))) == 0)
  339. return Result;
  340. NextBit += NumBits-1;
  341. Piece = Read(NumBits);
  342. }
  343. }
  344. // ReadVBR64 - Read a VBR that may have a value up to 64-bits in size. The
  345. // chunk size of the VBR must still be <= 32 bits though.
  346. uint64_t ReadVBR64(unsigned NumBits) {
  347. uint32_t Piece = Read(NumBits);
  348. if ((Piece & (1U << (NumBits-1))) == 0)
  349. return uint64_t(Piece);
  350. uint64_t Result = 0;
  351. unsigned NextBit = 0;
  352. while (1) {
  353. Result |= uint64_t(Piece & ((1U << (NumBits-1))-1)) << NextBit;
  354. if ((Piece & (1U << (NumBits-1))) == 0)
  355. return Result;
  356. NextBit += NumBits-1;
  357. Piece = Read(NumBits);
  358. }
  359. }
  360. private:
  361. void SkipToFourByteBoundary() {
  362. // If word_t is 64-bits and if we've read less than 32 bits, just dump
  363. // the bits we have up to the next 32-bit boundary.
  364. if (sizeof(word_t) > 4 &&
  365. BitsInCurWord >= 32) {
  366. CurWord >>= BitsInCurWord-32;
  367. BitsInCurWord = 32;
  368. return;
  369. }
  370. BitsInCurWord = 0;
  371. CurWord = 0;
  372. }
  373. public:
  374. unsigned ReadCode() {
  375. return Read(CurCodeSize);
  376. }
  377. // Block header:
  378. // [ENTER_SUBBLOCK, blockid, newcodelen, <align4bytes>, blocklen]
  379. /// ReadSubBlockID - Having read the ENTER_SUBBLOCK code, read the BlockID for
  380. /// the block.
  381. unsigned ReadSubBlockID() {
  382. return ReadVBR(bitc::BlockIDWidth);
  383. }
  384. /// SkipBlock - Having read the ENTER_SUBBLOCK abbrevid and a BlockID, skip
  385. /// over the body of this block. If the block record is malformed, return
  386. /// true.
  387. bool SkipBlock() {
  388. // Read and ignore the codelen value. Since we are skipping this block, we
  389. // don't care what code widths are used inside of it.
  390. ReadVBR(bitc::CodeLenWidth);
  391. SkipToFourByteBoundary();
  392. unsigned NumFourBytes = Read(bitc::BlockSizeWidth);
  393. // Check that the block wasn't partially defined, and that the offset isn't
  394. // bogus.
  395. size_t SkipTo = GetCurrentBitNo() + NumFourBytes*4*8;
  396. if (AtEndOfStream() || !canSkipToPos(SkipTo/8))
  397. return true;
  398. JumpToBit(SkipTo);
  399. return false;
  400. }
  401. /// EnterSubBlock - Having read the ENTER_SUBBLOCK abbrevid, enter
  402. /// the block, and return true if the block has an error.
  403. bool EnterSubBlock(unsigned BlockID, unsigned *NumWordsP = 0);
  404. bool ReadBlockEnd() {
  405. if (BlockScope.empty()) return true;
  406. // Block tail:
  407. // [END_BLOCK, <align4bytes>]
  408. SkipToFourByteBoundary();
  409. popBlockScope();
  410. return false;
  411. }
  412. private:
  413. void popBlockScope() {
  414. CurCodeSize = BlockScope.back().PrevCodeSize;
  415. // Delete abbrevs from popped scope.
  416. for (unsigned i = 0, e = static_cast<unsigned>(CurAbbrevs.size());
  417. i != e; ++i)
  418. CurAbbrevs[i]->dropRef();
  419. BlockScope.back().PrevAbbrevs.swap(CurAbbrevs);
  420. BlockScope.pop_back();
  421. }
  422. //===--------------------------------------------------------------------===//
  423. // Record Processing
  424. //===--------------------------------------------------------------------===//
  425. private:
  426. void readAbbreviatedLiteral(const BitCodeAbbrevOp &Op,
  427. SmallVectorImpl<uint64_t> &Vals);
  428. void readAbbreviatedField(const BitCodeAbbrevOp &Op,
  429. SmallVectorImpl<uint64_t> &Vals);
  430. void skipAbbreviatedField(const BitCodeAbbrevOp &Op);
  431. public:
  432. /// getAbbrev - Return the abbreviation for the specified AbbrevId.
  433. const BitCodeAbbrev *getAbbrev(unsigned AbbrevID) {
  434. unsigned AbbrevNo = AbbrevID-bitc::FIRST_APPLICATION_ABBREV;
  435. assert(AbbrevNo < CurAbbrevs.size() && "Invalid abbrev #!");
  436. return CurAbbrevs[AbbrevNo];
  437. }
  438. /// skipRecord - Read the current record and discard it.
  439. void skipRecord(unsigned AbbrevID);
  440. unsigned readRecord(unsigned AbbrevID, SmallVectorImpl<uint64_t> &Vals,
  441. StringRef *Blob = 0);
  442. //===--------------------------------------------------------------------===//
  443. // Abbrev Processing
  444. //===--------------------------------------------------------------------===//
  445. void ReadAbbrevRecord();
  446. bool ReadBlockInfoBlock();
  447. };
  448. } // End llvm namespace
  449. #endif