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