BitstreamWriter.h 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527
  1. //===- BitstreamWriter.h - Low-level bitstream writer 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 BitstreamWriter class. This class can be used to
  11. // write an arbitrary bitstream, regardless of its contents.
  12. //
  13. //===----------------------------------------------------------------------===//
  14. #ifndef LLVM_BITCODE_BITSTREAMWRITER_H
  15. #define LLVM_BITCODE_BITSTREAMWRITER_H
  16. #include "llvm/ADT/SmallVector.h"
  17. #include "llvm/ADT/StringRef.h"
  18. #include "llvm/Bitcode/BitCodes.h"
  19. #include "llvm/Support/Endian.h"
  20. #include <vector>
  21. namespace llvm {
  22. class BitstreamWriter {
  23. SmallVectorImpl<char> &Out;
  24. /// CurBit - Always between 0 and 31 inclusive, specifies the next bit to use.
  25. unsigned CurBit;
  26. /// CurValue - The current value. Only bits < CurBit are valid.
  27. uint32_t CurValue;
  28. /// CurCodeSize - This is the declared size of code values used for the
  29. /// current block, in bits.
  30. unsigned CurCodeSize;
  31. /// BlockInfoCurBID - When emitting a BLOCKINFO_BLOCK, this is the currently
  32. /// selected BLOCK ID.
  33. unsigned BlockInfoCurBID;
  34. /// CurAbbrevs - Abbrevs installed at in this block.
  35. std::vector<IntrusiveRefCntPtr<BitCodeAbbrev>> CurAbbrevs;
  36. struct Block {
  37. unsigned PrevCodeSize;
  38. unsigned StartSizeWord;
  39. std::vector<IntrusiveRefCntPtr<BitCodeAbbrev>> PrevAbbrevs;
  40. Block(unsigned PCS, unsigned SSW) : PrevCodeSize(PCS), StartSizeWord(SSW) {}
  41. };
  42. /// BlockScope - This tracks the current blocks that we have entered.
  43. std::vector<Block> BlockScope;
  44. /// BlockInfo - This contains information emitted to BLOCKINFO_BLOCK blocks.
  45. /// These describe abbreviations that all blocks of the specified ID inherit.
  46. struct BlockInfo {
  47. unsigned BlockID;
  48. std::vector<IntrusiveRefCntPtr<BitCodeAbbrev>> Abbrevs;
  49. };
  50. std::vector<BlockInfo> BlockInfoRecords;
  51. // BackpatchWord - Backpatch a 32-bit word in the output with the specified
  52. // value.
  53. void BackpatchWord(unsigned ByteNo, unsigned NewWord) {
  54. support::endian::write32le(&Out[ByteNo], NewWord);
  55. }
  56. void WriteByte(unsigned char Value) {
  57. Out.push_back(Value);
  58. }
  59. void WriteWord(unsigned Value) {
  60. Value = support::endian::byte_swap<uint32_t, support::little>(Value);
  61. Out.append(reinterpret_cast<const char *>(&Value),
  62. reinterpret_cast<const char *>(&Value + 1));
  63. }
  64. unsigned GetBufferOffset() const {
  65. return Out.size();
  66. }
  67. unsigned GetWordIndex() const {
  68. unsigned Offset = GetBufferOffset();
  69. assert((Offset & 3) == 0 && "Not 32-bit aligned");
  70. return Offset / 4;
  71. }
  72. public:
  73. explicit BitstreamWriter(SmallVectorImpl<char> &O)
  74. : Out(O), CurBit(0), CurValue(0), CurCodeSize(2) {}
  75. ~BitstreamWriter() {
  76. #if 0 // HLSL Change - these are not true when recovering from OOM
  77. assert(CurBit == 0 && "Unflushed data remaining");
  78. assert(BlockScope.empty() && CurAbbrevs.empty() && "Block imbalance");
  79. #endif
  80. }
  81. /// \brief Retrieve the current position in the stream, in bits.
  82. uint64_t GetCurrentBitNo() const { return GetBufferOffset() * 8 + CurBit; }
  83. //===--------------------------------------------------------------------===//
  84. // Basic Primitives for emitting bits to the stream.
  85. //===--------------------------------------------------------------------===//
  86. void Emit(uint32_t Val, unsigned NumBits) {
  87. assert(NumBits && NumBits <= 32 && "Invalid value size!");
  88. assert((Val & ~(~0U >> (32-NumBits))) == 0 && "High bits set!");
  89. CurValue |= Val << CurBit;
  90. if (CurBit + NumBits < 32) {
  91. CurBit += NumBits;
  92. return;
  93. }
  94. // Add the current word.
  95. WriteWord(CurValue);
  96. if (CurBit)
  97. CurValue = Val >> (32-CurBit);
  98. else
  99. CurValue = 0;
  100. CurBit = (CurBit+NumBits) & 31;
  101. }
  102. void Emit64(uint64_t Val, unsigned NumBits) {
  103. if (NumBits <= 32)
  104. Emit((uint32_t)Val, NumBits);
  105. else {
  106. Emit((uint32_t)Val, 32);
  107. Emit((uint32_t)(Val >> 32), NumBits-32);
  108. }
  109. }
  110. void FlushToWord() {
  111. if (CurBit) {
  112. WriteWord(CurValue);
  113. CurBit = 0;
  114. CurValue = 0;
  115. }
  116. }
  117. void EmitVBR(uint32_t Val, unsigned NumBits) {
  118. assert(NumBits <= 32 && "Too many bits to emit!");
  119. uint32_t Threshold = 1U << (NumBits-1);
  120. // Emit the bits with VBR encoding, NumBits-1 bits at a time.
  121. while (Val >= Threshold) {
  122. Emit((Val & ((1 << (NumBits-1))-1)) | (1 << (NumBits-1)), NumBits);
  123. Val >>= NumBits-1;
  124. }
  125. Emit(Val, NumBits);
  126. }
  127. void EmitVBR64(uint64_t Val, unsigned NumBits) {
  128. assert(NumBits <= 32 && "Too many bits to emit!");
  129. if ((uint32_t)Val == Val)
  130. return EmitVBR((uint32_t)Val, NumBits);
  131. uint32_t Threshold = 1U << (NumBits-1);
  132. // Emit the bits with VBR encoding, NumBits-1 bits at a time.
  133. while (Val >= Threshold) {
  134. Emit(((uint32_t)Val & ((1 << (NumBits-1))-1)) |
  135. (1 << (NumBits-1)), NumBits);
  136. Val >>= NumBits-1;
  137. }
  138. Emit((uint32_t)Val, NumBits);
  139. }
  140. /// EmitCode - Emit the specified code.
  141. void EmitCode(unsigned Val) {
  142. Emit(Val, CurCodeSize);
  143. }
  144. //===--------------------------------------------------------------------===//
  145. // Block Manipulation
  146. //===--------------------------------------------------------------------===//
  147. /// getBlockInfo - If there is block info for the specified ID, return it,
  148. /// otherwise return null.
  149. BlockInfo *getBlockInfo(unsigned BlockID) {
  150. // Common case, the most recent entry matches BlockID.
  151. if (!BlockInfoRecords.empty() && BlockInfoRecords.back().BlockID == BlockID)
  152. return &BlockInfoRecords.back();
  153. for (unsigned i = 0, e = static_cast<unsigned>(BlockInfoRecords.size());
  154. i != e; ++i)
  155. if (BlockInfoRecords[i].BlockID == BlockID)
  156. return &BlockInfoRecords[i];
  157. return nullptr;
  158. }
  159. void EnterSubblock(unsigned BlockID, unsigned CodeLen) {
  160. // Block header:
  161. // [ENTER_SUBBLOCK, blockid, newcodelen, <align4bytes>, blocklen]
  162. EmitCode(bitc::ENTER_SUBBLOCK);
  163. EmitVBR(BlockID, bitc::BlockIDWidth);
  164. EmitVBR(CodeLen, bitc::CodeLenWidth);
  165. FlushToWord();
  166. unsigned BlockSizeWordIndex = GetWordIndex();
  167. unsigned OldCodeSize = CurCodeSize;
  168. // Emit a placeholder, which will be replaced when the block is popped.
  169. Emit(0, bitc::BlockSizeWidth);
  170. CurCodeSize = CodeLen;
  171. // Push the outer block's abbrev set onto the stack, start out with an
  172. // empty abbrev set.
  173. BlockScope.emplace_back(OldCodeSize, BlockSizeWordIndex);
  174. BlockScope.back().PrevAbbrevs.swap(CurAbbrevs);
  175. // If there is a blockinfo for this BlockID, add all the predefined abbrevs
  176. // to the abbrev list.
  177. if (BlockInfo *Info = getBlockInfo(BlockID)) {
  178. CurAbbrevs.insert(CurAbbrevs.end(), Info->Abbrevs.begin(),
  179. Info->Abbrevs.end());
  180. }
  181. }
  182. void ExitBlock() {
  183. assert(!BlockScope.empty() && "Block scope imbalance!");
  184. const Block &B = BlockScope.back();
  185. // Block tail:
  186. // [END_BLOCK, <align4bytes>]
  187. EmitCode(bitc::END_BLOCK);
  188. FlushToWord();
  189. // Compute the size of the block, in words, not counting the size field.
  190. unsigned SizeInWords = GetWordIndex() - B.StartSizeWord - 1;
  191. unsigned ByteNo = B.StartSizeWord*4;
  192. // Update the block size field in the header of this sub-block.
  193. BackpatchWord(ByteNo, SizeInWords);
  194. // Restore the inner block's code size and abbrev table.
  195. CurCodeSize = B.PrevCodeSize;
  196. CurAbbrevs = std::move(B.PrevAbbrevs);
  197. BlockScope.pop_back();
  198. }
  199. //===--------------------------------------------------------------------===//
  200. // Record Emission
  201. //===--------------------------------------------------------------------===//
  202. private:
  203. /// EmitAbbreviatedLiteral - Emit a literal value according to its abbrev
  204. /// record. This is a no-op, since the abbrev specifies the literal to use.
  205. template<typename uintty>
  206. void EmitAbbreviatedLiteral(const BitCodeAbbrevOp &Op, uintty V) {
  207. assert(Op.isLiteral() && "Not a literal");
  208. // If the abbrev specifies the literal value to use, don't emit
  209. // anything.
  210. assert(V == Op.getLiteralValue() &&
  211. "Invalid abbrev for record!");
  212. }
  213. /// EmitAbbreviatedField - Emit a single scalar field value with the specified
  214. /// encoding.
  215. template<typename uintty>
  216. void EmitAbbreviatedField(const BitCodeAbbrevOp &Op, uintty V) {
  217. assert(!Op.isLiteral() && "Literals should use EmitAbbreviatedLiteral!");
  218. // Encode the value as we are commanded.
  219. switch (Op.getEncoding()) {
  220. default: llvm_unreachable("Unknown encoding!");
  221. case BitCodeAbbrevOp::Fixed:
  222. if (Op.getEncodingData())
  223. Emit((unsigned)V, (unsigned)Op.getEncodingData());
  224. break;
  225. case BitCodeAbbrevOp::VBR:
  226. if (Op.getEncodingData())
  227. EmitVBR64(V, (unsigned)Op.getEncodingData());
  228. break;
  229. case BitCodeAbbrevOp::Char6:
  230. Emit(BitCodeAbbrevOp::EncodeChar6((char)V), 6);
  231. break;
  232. }
  233. }
  234. /// EmitRecordWithAbbrevImpl - This is the core implementation of the record
  235. /// emission code. If BlobData is non-null, then it specifies an array of
  236. /// data that should be emitted as part of the Blob or Array operand that is
  237. /// known to exist at the end of the record.
  238. template<typename uintty>
  239. void EmitRecordWithAbbrevImpl(unsigned Abbrev, SmallVectorImpl<uintty> &Vals,
  240. StringRef Blob) {
  241. const char *BlobData = Blob.data();
  242. unsigned BlobLen = (unsigned) Blob.size();
  243. unsigned AbbrevNo = Abbrev-bitc::FIRST_APPLICATION_ABBREV;
  244. assert(AbbrevNo < CurAbbrevs.size() && "Invalid abbrev #!");
  245. const BitCodeAbbrev *Abbv = CurAbbrevs[AbbrevNo].get();
  246. EmitCode(Abbrev);
  247. unsigned RecordIdx = 0;
  248. for (unsigned i = 0, e = static_cast<unsigned>(Abbv->getNumOperandInfos());
  249. i != e; ++i) {
  250. const BitCodeAbbrevOp &Op = Abbv->getOperandInfo(i);
  251. if (Op.isLiteral()) {
  252. assert(RecordIdx < Vals.size() && "Invalid abbrev/record");
  253. EmitAbbreviatedLiteral(Op, Vals[RecordIdx]);
  254. ++RecordIdx;
  255. } else if (Op.getEncoding() == BitCodeAbbrevOp::Array) {
  256. // Array case.
  257. assert(i+2 == e && "array op not second to last?");
  258. const BitCodeAbbrevOp &EltEnc = Abbv->getOperandInfo(++i);
  259. // If this record has blob data, emit it, otherwise we must have record
  260. // entries to encode this way.
  261. if (BlobData) {
  262. assert(RecordIdx == Vals.size() &&
  263. "Blob data and record entries specified for array!");
  264. // Emit a vbr6 to indicate the number of elements present.
  265. EmitVBR(static_cast<uint32_t>(BlobLen), 6);
  266. // Emit each field.
  267. for (unsigned i = 0; i != BlobLen; ++i)
  268. EmitAbbreviatedField(EltEnc, (unsigned char)BlobData[i]);
  269. // Know that blob data is consumed for assertion below.
  270. BlobData = nullptr;
  271. } else {
  272. // Emit a vbr6 to indicate the number of elements present.
  273. EmitVBR(static_cast<uint32_t>(Vals.size()-RecordIdx), 6);
  274. // Emit each field.
  275. for (unsigned e = Vals.size(); RecordIdx != e; ++RecordIdx)
  276. EmitAbbreviatedField(EltEnc, Vals[RecordIdx]);
  277. }
  278. } else if (Op.getEncoding() == BitCodeAbbrevOp::Blob) {
  279. // If this record has blob data, emit it, otherwise we must have record
  280. // entries to encode this way.
  281. // Emit a vbr6 to indicate the number of elements present.
  282. if (BlobData) {
  283. EmitVBR(static_cast<uint32_t>(BlobLen), 6);
  284. assert(RecordIdx == Vals.size() &&
  285. "Blob data and record entries specified for blob operand!");
  286. } else {
  287. EmitVBR(static_cast<uint32_t>(Vals.size()-RecordIdx), 6);
  288. }
  289. // Flush to a 32-bit alignment boundary.
  290. FlushToWord();
  291. // Emit each field as a literal byte.
  292. if (BlobData) {
  293. for (unsigned i = 0; i != BlobLen; ++i)
  294. WriteByte((unsigned char)BlobData[i]);
  295. // Know that blob data is consumed for assertion below.
  296. BlobData = nullptr;
  297. } else {
  298. for (unsigned e = Vals.size(); RecordIdx != e; ++RecordIdx) {
  299. assert(isUInt<8>(Vals[RecordIdx]) &&
  300. "Value too large to emit as blob");
  301. WriteByte((unsigned char)Vals[RecordIdx]);
  302. }
  303. }
  304. // Align end to 32-bits.
  305. while (GetBufferOffset() & 3)
  306. WriteByte(0);
  307. } else { // Single scalar field.
  308. assert(RecordIdx < Vals.size() && "Invalid abbrev/record");
  309. EmitAbbreviatedField(Op, Vals[RecordIdx]);
  310. ++RecordIdx;
  311. }
  312. }
  313. assert(RecordIdx == Vals.size() && "Not all record operands emitted!");
  314. assert(BlobData == nullptr &&
  315. "Blob data specified for record that doesn't use it!");
  316. }
  317. public:
  318. /// EmitRecord - Emit the specified record to the stream, using an abbrev if
  319. /// we have one to compress the output.
  320. template<typename uintty>
  321. void EmitRecord(unsigned Code, SmallVectorImpl<uintty> &Vals,
  322. unsigned Abbrev = 0) {
  323. if (!Abbrev) {
  324. // If we don't have an abbrev to use, emit this in its fully unabbreviated
  325. // form.
  326. EmitCode(bitc::UNABBREV_RECORD);
  327. EmitVBR(Code, 6);
  328. EmitVBR(static_cast<uint32_t>(Vals.size()), 6);
  329. for (unsigned i = 0, e = static_cast<unsigned>(Vals.size()); i != e; ++i)
  330. EmitVBR64(Vals[i], 6);
  331. return;
  332. }
  333. // Insert the code into Vals to treat it uniformly.
  334. Vals.insert(Vals.begin(), Code);
  335. EmitRecordWithAbbrev(Abbrev, Vals);
  336. }
  337. /// EmitRecordWithAbbrev - Emit a record with the specified abbreviation.
  338. /// Unlike EmitRecord, the code for the record should be included in Vals as
  339. /// the first entry.
  340. template<typename uintty>
  341. void EmitRecordWithAbbrev(unsigned Abbrev, SmallVectorImpl<uintty> &Vals) {
  342. EmitRecordWithAbbrevImpl(Abbrev, Vals, StringRef());
  343. }
  344. /// EmitRecordWithBlob - Emit the specified record to the stream, using an
  345. /// abbrev that includes a blob at the end. The blob data to emit is
  346. /// specified by the pointer and length specified at the end. In contrast to
  347. /// EmitRecord, this routine expects that the first entry in Vals is the code
  348. /// of the record.
  349. template<typename uintty>
  350. void EmitRecordWithBlob(unsigned Abbrev, SmallVectorImpl<uintty> &Vals,
  351. StringRef Blob) {
  352. EmitRecordWithAbbrevImpl(Abbrev, Vals, Blob);
  353. }
  354. template<typename uintty>
  355. void EmitRecordWithBlob(unsigned Abbrev, SmallVectorImpl<uintty> &Vals,
  356. const char *BlobData, unsigned BlobLen) {
  357. return EmitRecordWithAbbrevImpl(Abbrev, Vals, StringRef(BlobData, BlobLen));
  358. }
  359. /// EmitRecordWithArray - Just like EmitRecordWithBlob, works with records
  360. /// that end with an array.
  361. template<typename uintty>
  362. void EmitRecordWithArray(unsigned Abbrev, SmallVectorImpl<uintty> &Vals,
  363. StringRef Array) {
  364. EmitRecordWithAbbrevImpl(Abbrev, Vals, Array);
  365. }
  366. template<typename uintty>
  367. void EmitRecordWithArray(unsigned Abbrev, SmallVectorImpl<uintty> &Vals,
  368. const char *ArrayData, unsigned ArrayLen) {
  369. return EmitRecordWithAbbrevImpl(Abbrev, Vals, StringRef(ArrayData,
  370. ArrayLen));
  371. }
  372. //===--------------------------------------------------------------------===//
  373. // Abbrev Emission
  374. //===--------------------------------------------------------------------===//
  375. private:
  376. // Emit the abbreviation as a DEFINE_ABBREV record.
  377. void EncodeAbbrev(BitCodeAbbrev *Abbv) {
  378. EmitCode(bitc::DEFINE_ABBREV);
  379. EmitVBR(Abbv->getNumOperandInfos(), 5);
  380. for (unsigned i = 0, e = static_cast<unsigned>(Abbv->getNumOperandInfos());
  381. i != e; ++i) {
  382. const BitCodeAbbrevOp &Op = Abbv->getOperandInfo(i);
  383. Emit(Op.isLiteral(), 1);
  384. if (Op.isLiteral()) {
  385. EmitVBR64(Op.getLiteralValue(), 8);
  386. } else {
  387. Emit(Op.getEncoding(), 3);
  388. if (Op.hasEncodingData())
  389. EmitVBR64(Op.getEncodingData(), 5);
  390. }
  391. }
  392. }
  393. public:
  394. /// EmitAbbrev - This emits an abbreviation to the stream. Note that this
  395. /// method takes ownership of the specified abbrev.
  396. unsigned EmitAbbrev(BitCodeAbbrev *Abbv) {
  397. // Emit the abbreviation as a record.
  398. EncodeAbbrev(Abbv);
  399. CurAbbrevs.push_back(Abbv);
  400. return static_cast<unsigned>(CurAbbrevs.size())-1 +
  401. bitc::FIRST_APPLICATION_ABBREV;
  402. }
  403. //===--------------------------------------------------------------------===//
  404. // BlockInfo Block Emission
  405. //===--------------------------------------------------------------------===//
  406. /// EnterBlockInfoBlock - Start emitting the BLOCKINFO_BLOCK.
  407. void EnterBlockInfoBlock(unsigned CodeWidth) {
  408. EnterSubblock(bitc::BLOCKINFO_BLOCK_ID, CodeWidth);
  409. BlockInfoCurBID = ~0U;
  410. }
  411. private:
  412. /// SwitchToBlockID - If we aren't already talking about the specified block
  413. /// ID, emit a BLOCKINFO_CODE_SETBID record.
  414. void SwitchToBlockID(unsigned BlockID) {
  415. if (BlockInfoCurBID == BlockID) return;
  416. SmallVector<unsigned, 2> V;
  417. V.push_back(BlockID);
  418. EmitRecord(bitc::BLOCKINFO_CODE_SETBID, V);
  419. BlockInfoCurBID = BlockID;
  420. }
  421. BlockInfo &getOrCreateBlockInfo(unsigned BlockID) {
  422. if (BlockInfo *BI = getBlockInfo(BlockID))
  423. return *BI;
  424. // Otherwise, add a new record.
  425. BlockInfoRecords.emplace_back();
  426. BlockInfoRecords.back().BlockID = BlockID;
  427. return BlockInfoRecords.back();
  428. }
  429. public:
  430. /// EmitBlockInfoAbbrev - Emit a DEFINE_ABBREV record for the specified
  431. /// BlockID.
  432. unsigned EmitBlockInfoAbbrev(unsigned BlockID, BitCodeAbbrev *Abbv) {
  433. SwitchToBlockID(BlockID);
  434. EncodeAbbrev(Abbv);
  435. // Add the abbrev to the specified block record.
  436. BlockInfo &Info = getOrCreateBlockInfo(BlockID);
  437. Info.Abbrevs.push_back(Abbv);
  438. return Info.Abbrevs.size()-1+bitc::FIRST_APPLICATION_ABBREV;
  439. }
  440. };
  441. } // End llvm namespace
  442. #endif