BitstreamWriter.h 22 KB

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