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