BitstreamWriter.h 18 KB

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