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