BitstreamWriter.h 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632
  1. #pragma once
  2. #ifdef __GNUC__
  3. #pragma GCC diagnostic push
  4. #pragma GCC diagnostic ignored "-Wunused-parameter"
  5. #endif
  6. //===- BitstreamWriter.h - Low-level bitstream writer interface -*- C++ -*-===//
  7. //
  8. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  9. // See https://llvm.org/LICENSE.txt for license information.
  10. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  11. //
  12. //===----------------------------------------------------------------------===//
  13. //
  14. // This header defines the BitstreamWriter class. This class can be used to
  15. // write an arbitrary bitstream, regardless of its contents.
  16. //
  17. //===----------------------------------------------------------------------===//
  18. #ifndef LLVM_BITSTREAM_BITSTREAMWRITER_H
  19. #define LLVM_BITSTREAM_BITSTREAMWRITER_H
  20. #include "llvm/ADT/ArrayRef.h"
  21. #include "llvm/ADT/SmallVector.h"
  22. #include "llvm/ADT/StringRef.h"
  23. #include "llvm/Bitstream/BitCodes.h"
  24. #include "llvm/Support/Endian.h"
  25. #include "llvm/Support/MathExtras.h"
  26. #include "llvm/Support/raw_ostream.h"
  27. #include <algorithm>
  28. #include <optional>
  29. #include <vector>
  30. namespace llvm {
  31. class BitstreamWriter {
  32. /// Out - The buffer that keeps unflushed bytes.
  33. SmallVectorImpl<char> &Out;
  34. /// FS - The file stream that Out flushes to. If FS is nullptr, it does not
  35. /// support read or seek, Out cannot be flushed until all data are written.
  36. raw_fd_stream *FS;
  37. /// FlushThreshold - If FS is valid, this is the threshold (unit B) to flush
  38. /// FS.
  39. const uint64_t FlushThreshold;
  40. /// CurBit - Always between 0 and 31 inclusive, specifies the next bit to use.
  41. unsigned CurBit;
  42. /// CurValue - The current value. Only bits < CurBit are valid.
  43. uint32_t CurValue;
  44. /// CurCodeSize - This is the declared size of code values used for the
  45. /// current block, in bits.
  46. unsigned CurCodeSize;
  47. /// BlockInfoCurBID - When emitting a BLOCKINFO_BLOCK, this is the currently
  48. /// selected BLOCK ID.
  49. unsigned BlockInfoCurBID;
  50. /// CurAbbrevs - Abbrevs installed at in this block.
  51. std::vector<std::shared_ptr<BitCodeAbbrev>> CurAbbrevs;
  52. struct Block {
  53. unsigned PrevCodeSize;
  54. size_t StartSizeWord;
  55. std::vector<std::shared_ptr<BitCodeAbbrev>> PrevAbbrevs;
  56. Block(unsigned PCS, size_t SSW) : PrevCodeSize(PCS), StartSizeWord(SSW) {}
  57. };
  58. /// BlockScope - This tracks the current blocks that we have entered.
  59. std::vector<Block> BlockScope;
  60. /// BlockInfo - This contains information emitted to BLOCKINFO_BLOCK blocks.
  61. /// These describe abbreviations that all blocks of the specified ID inherit.
  62. struct BlockInfo {
  63. unsigned BlockID;
  64. std::vector<std::shared_ptr<BitCodeAbbrev>> Abbrevs;
  65. };
  66. std::vector<BlockInfo> BlockInfoRecords;
  67. void WriteWord(unsigned Value) {
  68. Value = support::endian::byte_swap<uint32_t, support::little>(Value);
  69. Out.append(reinterpret_cast<const char *>(&Value),
  70. reinterpret_cast<const char *>(&Value + 1));
  71. }
  72. uint64_t GetNumOfFlushedBytes() const { return FS ? FS->tell() : 0; }
  73. size_t GetBufferOffset() const { return Out.size() + GetNumOfFlushedBytes(); }
  74. size_t GetWordIndex() const {
  75. size_t Offset = GetBufferOffset();
  76. assert((Offset & 3) == 0 && "Not 32-bit aligned");
  77. return Offset / 4;
  78. }
  79. /// If the related file stream supports reading, seeking and writing, flush
  80. /// the buffer if its size is above a threshold.
  81. void FlushToFile() {
  82. if (!FS)
  83. return;
  84. if (Out.size() < FlushThreshold)
  85. return;
  86. FS->write((char *)&Out.front(), Out.size());
  87. Out.clear();
  88. }
  89. public:
  90. /// Create a BitstreamWriter that writes to Buffer \p O.
  91. ///
  92. /// \p FS is the file stream that \p O flushes to incrementally. If \p FS is
  93. /// null, \p O does not flush incrementially, but writes to disk at the end.
  94. ///
  95. /// \p FlushThreshold is the threshold (unit M) to flush \p O if \p FS is
  96. /// valid. Flushing only occurs at (sub)block boundaries.
  97. BitstreamWriter(SmallVectorImpl<char> &O, raw_fd_stream *FS = nullptr,
  98. uint32_t FlushThreshold = 512)
  99. : Out(O), FS(FS), FlushThreshold(FlushThreshold << 20), CurBit(0),
  100. CurValue(0), CurCodeSize(2) {}
  101. ~BitstreamWriter() {
  102. assert(CurBit == 0 && "Unflushed data remaining");
  103. assert(BlockScope.empty() && CurAbbrevs.empty() && "Block imbalance");
  104. }
  105. /// Retrieve the current position in the stream, in bits.
  106. uint64_t GetCurrentBitNo() const { return GetBufferOffset() * 8 + CurBit; }
  107. /// Retrieve the number of bits currently used to encode an abbrev ID.
  108. unsigned GetAbbrevIDWidth() const { return CurCodeSize; }
  109. //===--------------------------------------------------------------------===//
  110. // Basic Primitives for emitting bits to the stream.
  111. //===--------------------------------------------------------------------===//
  112. /// Backpatch a 32-bit word in the output at the given bit offset
  113. /// with the specified value.
  114. void BackpatchWord(uint64_t BitNo, unsigned NewWord) {
  115. using namespace llvm::support;
  116. uint64_t ByteNo = BitNo / 8;
  117. uint64_t StartBit = BitNo & 7;
  118. uint64_t NumOfFlushedBytes = GetNumOfFlushedBytes();
  119. if (ByteNo >= NumOfFlushedBytes) {
  120. assert((!endian::readAtBitAlignment<uint32_t, little, unaligned>(
  121. &Out[ByteNo - NumOfFlushedBytes], StartBit)) &&
  122. "Expected to be patching over 0-value placeholders");
  123. endian::writeAtBitAlignment<uint32_t, little, unaligned>(
  124. &Out[ByteNo - NumOfFlushedBytes], NewWord, StartBit);
  125. return;
  126. }
  127. // If the byte offset to backpatch is flushed, use seek to backfill data.
  128. // First, save the file position to restore later.
  129. uint64_t CurPos = FS->tell();
  130. // Copy data to update into Bytes from the file FS and the buffer Out.
  131. char Bytes[9]; // Use one more byte to silence a warning from Visual C++.
  132. size_t BytesNum = StartBit ? 8 : 4;
  133. size_t BytesFromDisk = std::min(static_cast<uint64_t>(BytesNum), NumOfFlushedBytes - ByteNo);
  134. size_t BytesFromBuffer = BytesNum - BytesFromDisk;
  135. // When unaligned, copy existing data into Bytes from the file FS and the
  136. // buffer Out so that it can be updated before writing. For debug builds
  137. // read bytes unconditionally in order to check that the existing value is 0
  138. // as expected.
  139. #ifdef NDEBUG
  140. if (StartBit)
  141. #endif
  142. {
  143. FS->seek(ByteNo);
  144. ssize_t BytesRead = FS->read(Bytes, BytesFromDisk);
  145. (void)BytesRead; // silence warning
  146. assert(BytesRead >= 0 && static_cast<size_t>(BytesRead) == BytesFromDisk);
  147. for (size_t i = 0; i < BytesFromBuffer; ++i)
  148. Bytes[BytesFromDisk + i] = Out[i];
  149. assert((!endian::readAtBitAlignment<uint32_t, little, unaligned>(
  150. Bytes, StartBit)) &&
  151. "Expected to be patching over 0-value placeholders");
  152. }
  153. // Update Bytes in terms of bit offset and value.
  154. endian::writeAtBitAlignment<uint32_t, little, unaligned>(Bytes, NewWord,
  155. StartBit);
  156. // Copy updated data back to the file FS and the buffer Out.
  157. FS->seek(ByteNo);
  158. FS->write(Bytes, BytesFromDisk);
  159. for (size_t i = 0; i < BytesFromBuffer; ++i)
  160. Out[i] = Bytes[BytesFromDisk + i];
  161. // Restore the file position.
  162. FS->seek(CurPos);
  163. }
  164. void BackpatchWord64(uint64_t BitNo, uint64_t Val) {
  165. BackpatchWord(BitNo, (uint32_t)Val);
  166. BackpatchWord(BitNo + 32, (uint32_t)(Val >> 32));
  167. }
  168. void Emit(uint32_t Val, unsigned NumBits) {
  169. assert(NumBits && NumBits <= 32 && "Invalid value size!");
  170. assert((Val & ~(~0U >> (32-NumBits))) == 0 && "High bits set!");
  171. CurValue |= Val << CurBit;
  172. if (CurBit + NumBits < 32) {
  173. CurBit += NumBits;
  174. return;
  175. }
  176. // Add the current word.
  177. WriteWord(CurValue);
  178. if (CurBit)
  179. CurValue = Val >> (32-CurBit);
  180. else
  181. CurValue = 0;
  182. CurBit = (CurBit+NumBits) & 31;
  183. }
  184. void FlushToWord() {
  185. if (CurBit) {
  186. WriteWord(CurValue);
  187. CurBit = 0;
  188. CurValue = 0;
  189. }
  190. }
  191. void EmitVBR(uint32_t Val, unsigned NumBits) {
  192. assert(NumBits <= 32 && "Too many bits to emit!");
  193. uint32_t Threshold = 1U << (NumBits-1);
  194. // Emit the bits with VBR encoding, NumBits-1 bits at a time.
  195. while (Val >= Threshold) {
  196. Emit((Val & ((1 << (NumBits-1))-1)) | (1 << (NumBits-1)), NumBits);
  197. Val >>= NumBits-1;
  198. }
  199. Emit(Val, NumBits);
  200. }
  201. void EmitVBR64(uint64_t Val, unsigned NumBits) {
  202. assert(NumBits <= 32 && "Too many bits to emit!");
  203. if ((uint32_t)Val == Val)
  204. return EmitVBR((uint32_t)Val, NumBits);
  205. uint32_t Threshold = 1U << (NumBits-1);
  206. // Emit the bits with VBR encoding, NumBits-1 bits at a time.
  207. while (Val >= Threshold) {
  208. Emit(((uint32_t)Val & ((1 << (NumBits - 1)) - 1)) | (1 << (NumBits - 1)),
  209. NumBits);
  210. Val >>= NumBits-1;
  211. }
  212. Emit((uint32_t)Val, NumBits);
  213. }
  214. /// EmitCode - Emit the specified code.
  215. void EmitCode(unsigned Val) {
  216. Emit(Val, CurCodeSize);
  217. }
  218. //===--------------------------------------------------------------------===//
  219. // Block Manipulation
  220. //===--------------------------------------------------------------------===//
  221. /// getBlockInfo - If there is block info for the specified ID, return it,
  222. /// otherwise return null.
  223. BlockInfo *getBlockInfo(unsigned BlockID) {
  224. // Common case, the most recent entry matches BlockID.
  225. if (!BlockInfoRecords.empty() && BlockInfoRecords.back().BlockID == BlockID)
  226. return &BlockInfoRecords.back();
  227. for (BlockInfo &BI : BlockInfoRecords)
  228. if (BI.BlockID == BlockID)
  229. return &BI;
  230. return nullptr;
  231. }
  232. void EnterSubblock(unsigned BlockID, unsigned CodeLen) {
  233. // Block header:
  234. // [ENTER_SUBBLOCK, blockid, newcodelen, <align4bytes>, blocklen]
  235. EmitCode(bitc::ENTER_SUBBLOCK);
  236. EmitVBR(BlockID, bitc::BlockIDWidth);
  237. EmitVBR(CodeLen, bitc::CodeLenWidth);
  238. FlushToWord();
  239. size_t BlockSizeWordIndex = GetWordIndex();
  240. unsigned OldCodeSize = CurCodeSize;
  241. // Emit a placeholder, which will be replaced when the block is popped.
  242. Emit(0, bitc::BlockSizeWidth);
  243. CurCodeSize = CodeLen;
  244. // Push the outer block's abbrev set onto the stack, start out with an
  245. // empty abbrev set.
  246. BlockScope.emplace_back(OldCodeSize, BlockSizeWordIndex);
  247. BlockScope.back().PrevAbbrevs.swap(CurAbbrevs);
  248. // If there is a blockinfo for this BlockID, add all the predefined abbrevs
  249. // to the abbrev list.
  250. if (BlockInfo *Info = getBlockInfo(BlockID))
  251. append_range(CurAbbrevs, Info->Abbrevs);
  252. }
  253. void ExitBlock() {
  254. assert(!BlockScope.empty() && "Block scope imbalance!");
  255. const Block &B = BlockScope.back();
  256. // Block tail:
  257. // [END_BLOCK, <align4bytes>]
  258. EmitCode(bitc::END_BLOCK);
  259. FlushToWord();
  260. // Compute the size of the block, in words, not counting the size field.
  261. size_t SizeInWords = GetWordIndex() - B.StartSizeWord - 1;
  262. uint64_t BitNo = uint64_t(B.StartSizeWord) * 32;
  263. // Update the block size field in the header of this sub-block.
  264. BackpatchWord(BitNo, SizeInWords);
  265. // Restore the inner block's code size and abbrev table.
  266. CurCodeSize = B.PrevCodeSize;
  267. CurAbbrevs = std::move(B.PrevAbbrevs);
  268. BlockScope.pop_back();
  269. FlushToFile();
  270. }
  271. //===--------------------------------------------------------------------===//
  272. // Record Emission
  273. //===--------------------------------------------------------------------===//
  274. private:
  275. /// EmitAbbreviatedLiteral - Emit a literal value according to its abbrev
  276. /// record. This is a no-op, since the abbrev specifies the literal to use.
  277. template<typename uintty>
  278. void EmitAbbreviatedLiteral(const BitCodeAbbrevOp &Op, uintty V) {
  279. assert(Op.isLiteral() && "Not a literal");
  280. // If the abbrev specifies the literal value to use, don't emit
  281. // anything.
  282. assert(V == Op.getLiteralValue() &&
  283. "Invalid abbrev for record!");
  284. }
  285. /// EmitAbbreviatedField - Emit a single scalar field value with the specified
  286. /// encoding.
  287. template<typename uintty>
  288. void EmitAbbreviatedField(const BitCodeAbbrevOp &Op, uintty V) {
  289. assert(!Op.isLiteral() && "Literals should use EmitAbbreviatedLiteral!");
  290. // Encode the value as we are commanded.
  291. switch (Op.getEncoding()) {
  292. default: llvm_unreachable("Unknown encoding!");
  293. case BitCodeAbbrevOp::Fixed:
  294. if (Op.getEncodingData())
  295. Emit((unsigned)V, (unsigned)Op.getEncodingData());
  296. break;
  297. case BitCodeAbbrevOp::VBR:
  298. if (Op.getEncodingData())
  299. EmitVBR64(V, (unsigned)Op.getEncodingData());
  300. break;
  301. case BitCodeAbbrevOp::Char6:
  302. Emit(BitCodeAbbrevOp::EncodeChar6((char)V), 6);
  303. break;
  304. }
  305. }
  306. /// EmitRecordWithAbbrevImpl - This is the core implementation of the record
  307. /// emission code. If BlobData is non-null, then it specifies an array of
  308. /// data that should be emitted as part of the Blob or Array operand that is
  309. /// known to exist at the end of the record. If Code is specified, then
  310. /// it is the record code to emit before the Vals, which must not contain
  311. /// the code.
  312. template <typename uintty>
  313. void EmitRecordWithAbbrevImpl(unsigned Abbrev, ArrayRef<uintty> Vals,
  314. StringRef Blob, std::optional<unsigned> Code) {
  315. const char *BlobData = Blob.data();
  316. unsigned BlobLen = (unsigned) Blob.size();
  317. unsigned AbbrevNo = Abbrev-bitc::FIRST_APPLICATION_ABBREV;
  318. assert(AbbrevNo < CurAbbrevs.size() && "Invalid abbrev #!");
  319. const BitCodeAbbrev *Abbv = CurAbbrevs[AbbrevNo].get();
  320. EmitCode(Abbrev);
  321. unsigned i = 0, e = static_cast<unsigned>(Abbv->getNumOperandInfos());
  322. if (Code) {
  323. assert(e && "Expected non-empty abbreviation");
  324. const BitCodeAbbrevOp &Op = Abbv->getOperandInfo(i++);
  325. if (Op.isLiteral())
  326. EmitAbbreviatedLiteral(Op, *Code);
  327. else {
  328. assert(Op.getEncoding() != BitCodeAbbrevOp::Array &&
  329. Op.getEncoding() != BitCodeAbbrevOp::Blob &&
  330. "Expected literal or scalar");
  331. EmitAbbreviatedField(Op, *Code);
  332. }
  333. }
  334. unsigned RecordIdx = 0;
  335. for (; i != e; ++i) {
  336. const BitCodeAbbrevOp &Op = Abbv->getOperandInfo(i);
  337. if (Op.isLiteral()) {
  338. assert(RecordIdx < Vals.size() && "Invalid abbrev/record");
  339. EmitAbbreviatedLiteral(Op, Vals[RecordIdx]);
  340. ++RecordIdx;
  341. } else if (Op.getEncoding() == BitCodeAbbrevOp::Array) {
  342. // Array case.
  343. assert(i + 2 == e && "array op not second to last?");
  344. const BitCodeAbbrevOp &EltEnc = Abbv->getOperandInfo(++i);
  345. // If this record has blob data, emit it, otherwise we must have record
  346. // entries to encode this way.
  347. if (BlobData) {
  348. assert(RecordIdx == Vals.size() &&
  349. "Blob data and record entries specified for array!");
  350. // Emit a vbr6 to indicate the number of elements present.
  351. EmitVBR(static_cast<uint32_t>(BlobLen), 6);
  352. // Emit each field.
  353. for (unsigned i = 0; i != BlobLen; ++i)
  354. EmitAbbreviatedField(EltEnc, (unsigned char)BlobData[i]);
  355. // Know that blob data is consumed for assertion below.
  356. BlobData = nullptr;
  357. } else {
  358. // Emit a vbr6 to indicate the number of elements present.
  359. EmitVBR(static_cast<uint32_t>(Vals.size()-RecordIdx), 6);
  360. // Emit each field.
  361. for (unsigned e = Vals.size(); RecordIdx != e; ++RecordIdx)
  362. EmitAbbreviatedField(EltEnc, Vals[RecordIdx]);
  363. }
  364. } else if (Op.getEncoding() == BitCodeAbbrevOp::Blob) {
  365. // If this record has blob data, emit it, otherwise we must have record
  366. // entries to encode this way.
  367. if (BlobData) {
  368. assert(RecordIdx == Vals.size() &&
  369. "Blob data and record entries specified for blob operand!");
  370. assert(Blob.data() == BlobData && "BlobData got moved");
  371. assert(Blob.size() == BlobLen && "BlobLen got changed");
  372. emitBlob(Blob);
  373. BlobData = nullptr;
  374. } else {
  375. emitBlob(Vals.slice(RecordIdx));
  376. }
  377. } else { // Single scalar field.
  378. assert(RecordIdx < Vals.size() && "Invalid abbrev/record");
  379. EmitAbbreviatedField(Op, Vals[RecordIdx]);
  380. ++RecordIdx;
  381. }
  382. }
  383. assert(RecordIdx == Vals.size() && "Not all record operands emitted!");
  384. assert(BlobData == nullptr &&
  385. "Blob data specified for record that doesn't use it!");
  386. }
  387. public:
  388. /// Emit a blob, including flushing before and tail-padding.
  389. template <class UIntTy>
  390. void emitBlob(ArrayRef<UIntTy> Bytes, bool ShouldEmitSize = true) {
  391. // Emit a vbr6 to indicate the number of elements present.
  392. if (ShouldEmitSize)
  393. EmitVBR(static_cast<uint32_t>(Bytes.size()), 6);
  394. // Flush to a 32-bit alignment boundary.
  395. FlushToWord();
  396. // Emit literal bytes.
  397. assert(llvm::all_of(Bytes, [](UIntTy B) { return isUInt<8>(B); }));
  398. Out.append(Bytes.begin(), Bytes.end());
  399. // Align end to 32-bits.
  400. while (GetBufferOffset() & 3)
  401. Out.push_back(0);
  402. }
  403. void emitBlob(StringRef Bytes, bool ShouldEmitSize = true) {
  404. emitBlob(ArrayRef((const uint8_t *)Bytes.data(), Bytes.size()),
  405. ShouldEmitSize);
  406. }
  407. /// EmitRecord - Emit the specified record to the stream, using an abbrev if
  408. /// we have one to compress the output.
  409. template <typename Container>
  410. void EmitRecord(unsigned Code, const Container &Vals, unsigned Abbrev = 0) {
  411. if (!Abbrev) {
  412. // If we don't have an abbrev to use, emit this in its fully unabbreviated
  413. // form.
  414. auto Count = static_cast<uint32_t>(std::size(Vals));
  415. EmitCode(bitc::UNABBREV_RECORD);
  416. EmitVBR(Code, 6);
  417. EmitVBR(Count, 6);
  418. for (unsigned i = 0, e = Count; i != e; ++i)
  419. EmitVBR64(Vals[i], 6);
  420. return;
  421. }
  422. EmitRecordWithAbbrevImpl(Abbrev, ArrayRef(Vals), StringRef(), Code);
  423. }
  424. /// EmitRecordWithAbbrev - Emit a record with the specified abbreviation.
  425. /// Unlike EmitRecord, the code for the record should be included in Vals as
  426. /// the first entry.
  427. template <typename Container>
  428. void EmitRecordWithAbbrev(unsigned Abbrev, const Container &Vals) {
  429. EmitRecordWithAbbrevImpl(Abbrev, ArrayRef(Vals), StringRef(), std::nullopt);
  430. }
  431. /// EmitRecordWithBlob - Emit the specified record to the stream, using an
  432. /// abbrev that includes a blob at the end. The blob data to emit is
  433. /// specified by the pointer and length specified at the end. In contrast to
  434. /// EmitRecord, this routine expects that the first entry in Vals is the code
  435. /// of the record.
  436. template <typename Container>
  437. void EmitRecordWithBlob(unsigned Abbrev, const Container &Vals,
  438. StringRef Blob) {
  439. EmitRecordWithAbbrevImpl(Abbrev, ArrayRef(Vals), Blob, std::nullopt);
  440. }
  441. template <typename Container>
  442. void EmitRecordWithBlob(unsigned Abbrev, const Container &Vals,
  443. const char *BlobData, unsigned BlobLen) {
  444. return EmitRecordWithAbbrevImpl(Abbrev, ArrayRef(Vals),
  445. StringRef(BlobData, BlobLen), std::nullopt);
  446. }
  447. /// EmitRecordWithArray - Just like EmitRecordWithBlob, works with records
  448. /// that end with an array.
  449. template <typename Container>
  450. void EmitRecordWithArray(unsigned Abbrev, const Container &Vals,
  451. StringRef Array) {
  452. EmitRecordWithAbbrevImpl(Abbrev, ArrayRef(Vals), Array, std::nullopt);
  453. }
  454. template <typename Container>
  455. void EmitRecordWithArray(unsigned Abbrev, const Container &Vals,
  456. const char *ArrayData, unsigned ArrayLen) {
  457. return EmitRecordWithAbbrevImpl(
  458. Abbrev, ArrayRef(Vals), StringRef(ArrayData, ArrayLen), std::nullopt);
  459. }
  460. //===--------------------------------------------------------------------===//
  461. // Abbrev Emission
  462. //===--------------------------------------------------------------------===//
  463. private:
  464. // Emit the abbreviation as a DEFINE_ABBREV record.
  465. void EncodeAbbrev(const BitCodeAbbrev &Abbv) {
  466. EmitCode(bitc::DEFINE_ABBREV);
  467. EmitVBR(Abbv.getNumOperandInfos(), 5);
  468. for (unsigned i = 0, e = static_cast<unsigned>(Abbv.getNumOperandInfos());
  469. i != e; ++i) {
  470. const BitCodeAbbrevOp &Op = Abbv.getOperandInfo(i);
  471. Emit(Op.isLiteral(), 1);
  472. if (Op.isLiteral()) {
  473. EmitVBR64(Op.getLiteralValue(), 8);
  474. } else {
  475. Emit(Op.getEncoding(), 3);
  476. if (Op.hasEncodingData())
  477. EmitVBR64(Op.getEncodingData(), 5);
  478. }
  479. }
  480. }
  481. public:
  482. /// Emits the abbreviation \p Abbv to the stream.
  483. unsigned EmitAbbrev(std::shared_ptr<BitCodeAbbrev> Abbv) {
  484. EncodeAbbrev(*Abbv);
  485. CurAbbrevs.push_back(std::move(Abbv));
  486. return static_cast<unsigned>(CurAbbrevs.size())-1 +
  487. bitc::FIRST_APPLICATION_ABBREV;
  488. }
  489. //===--------------------------------------------------------------------===//
  490. // BlockInfo Block Emission
  491. //===--------------------------------------------------------------------===//
  492. /// EnterBlockInfoBlock - Start emitting the BLOCKINFO_BLOCK.
  493. void EnterBlockInfoBlock() {
  494. EnterSubblock(bitc::BLOCKINFO_BLOCK_ID, 2);
  495. BlockInfoCurBID = ~0U;
  496. BlockInfoRecords.clear();
  497. }
  498. private:
  499. /// SwitchToBlockID - If we aren't already talking about the specified block
  500. /// ID, emit a BLOCKINFO_CODE_SETBID record.
  501. void SwitchToBlockID(unsigned BlockID) {
  502. if (BlockInfoCurBID == BlockID) return;
  503. SmallVector<unsigned, 2> V;
  504. V.push_back(BlockID);
  505. EmitRecord(bitc::BLOCKINFO_CODE_SETBID, V);
  506. BlockInfoCurBID = BlockID;
  507. }
  508. BlockInfo &getOrCreateBlockInfo(unsigned BlockID) {
  509. if (BlockInfo *BI = getBlockInfo(BlockID))
  510. return *BI;
  511. // Otherwise, add a new record.
  512. BlockInfoRecords.emplace_back();
  513. BlockInfoRecords.back().BlockID = BlockID;
  514. return BlockInfoRecords.back();
  515. }
  516. public:
  517. /// EmitBlockInfoAbbrev - Emit a DEFINE_ABBREV record for the specified
  518. /// BlockID.
  519. unsigned EmitBlockInfoAbbrev(unsigned BlockID, std::shared_ptr<BitCodeAbbrev> Abbv) {
  520. SwitchToBlockID(BlockID);
  521. EncodeAbbrev(*Abbv);
  522. // Add the abbrev to the specified block record.
  523. BlockInfo &Info = getOrCreateBlockInfo(BlockID);
  524. Info.Abbrevs.push_back(std::move(Abbv));
  525. return Info.Abbrevs.size()-1+bitc::FIRST_APPLICATION_ABBREV;
  526. }
  527. };
  528. } // End llvm namespace
  529. #endif
  530. #ifdef __GNUC__
  531. #pragma GCC diagnostic pop
  532. #endif