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