Fix more -Wshorten-64-to-32 warnings.
[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/Bitcode/BitCodes.h"
19 #include <vector>
20
21 namespace llvm {
22
23 class BitstreamWriter {
24   std::vector<unsigned char> &Out;
25
26   /// CurBit - Always between 0 and 31 inclusive, specifies the next bit to use.
27   unsigned CurBit;
28   
29   /// CurValue - The current value.  Only bits < CurBit are valid.
30   uint32_t CurValue;
31   
32   /// CurCodeSize - This is the declared size of code values used for the
33   /// current block, in bits.
34   unsigned CurCodeSize;
35
36   /// BlockInfoCurBID - When emitting a BLOCKINFO_BLOCK, this is the currently
37   /// selected BLOCK ID.
38   unsigned BlockInfoCurBID;
39   
40   /// CurAbbrevs - Abbrevs installed at in this block.
41   std::vector<BitCodeAbbrev*> CurAbbrevs;
42
43   struct Block {
44     unsigned PrevCodeSize;
45     unsigned StartSizeWord;
46     std::vector<BitCodeAbbrev*> PrevAbbrevs;
47     Block(unsigned PCS, unsigned SSW) : PrevCodeSize(PCS), StartSizeWord(SSW) {}
48   };
49   
50   /// BlockScope - This tracks the current blocks that we have entered.
51   std::vector<Block> BlockScope;
52   
53   /// BlockInfo - This contains information emitted to BLOCKINFO_BLOCK blocks.
54   /// These describe abbreviations that all blocks of the specified ID inherit.
55   struct BlockInfo {
56     unsigned BlockID;
57     std::vector<BitCodeAbbrev*> Abbrevs;
58   };
59   std::vector<BlockInfo> BlockInfoRecords;
60   
61 public:
62   explicit BitstreamWriter(std::vector<unsigned char> &O) 
63     : Out(O), CurBit(0), CurValue(0), CurCodeSize(2) {}
64
65   ~BitstreamWriter() {
66     assert(CurBit == 0 && "Unflused data remaining");
67     assert(BlockScope.empty() && CurAbbrevs.empty() && "Block imbalance");
68     
69     // Free the BlockInfoRecords.
70     while (!BlockInfoRecords.empty()) {
71       BlockInfo &Info = BlockInfoRecords.back();
72       // Free blockinfo abbrev info.
73       for (unsigned i = 0, e = static_cast<unsigned>(Info.Abbrevs.size());
74            i != e; ++i)
75         Info.Abbrevs[i]->dropRef();
76       BlockInfoRecords.pop_back();
77     }
78   }
79   //===--------------------------------------------------------------------===//
80   // Basic Primitives for emitting bits to the stream.
81   //===--------------------------------------------------------------------===//
82   
83   void Emit(uint32_t Val, unsigned NumBits) {
84     assert(NumBits <= 32 && "Invalid value size!");
85     assert((Val & ~(~0U >> (32-NumBits))) == 0 && "High bits set!");
86     CurValue |= Val << CurBit;
87     if (CurBit + NumBits < 32) {
88       CurBit += NumBits;
89       return;
90     }
91     
92     // Add the current word.
93     unsigned V = CurValue;
94     Out.push_back((unsigned char)(V >>  0));
95     Out.push_back((unsigned char)(V >>  8));
96     Out.push_back((unsigned char)(V >> 16));
97     Out.push_back((unsigned char)(V >> 24));
98     
99     if (CurBit)
100       CurValue = Val >> (32-CurBit);
101     else
102       CurValue = 0;
103     CurBit = (CurBit+NumBits) & 31;
104   }
105   
106   void Emit64(uint64_t Val, unsigned NumBits) {
107     if (NumBits <= 32)
108       Emit((uint32_t)Val, NumBits);
109     else {
110       Emit((uint32_t)Val, 32);
111       Emit((uint32_t)(Val >> 32), NumBits-32);
112     }
113   }
114   
115   void FlushToWord() {
116     if (CurBit) {
117       unsigned V = CurValue;
118       Out.push_back((unsigned char)(V >>  0));
119       Out.push_back((unsigned char)(V >>  8));
120       Out.push_back((unsigned char)(V >> 16));
121       Out.push_back((unsigned char)(V >> 24));
122       CurBit = 0;
123       CurValue = 0;
124     }
125   }
126   
127   void EmitVBR(uint32_t Val, unsigned NumBits) {
128     uint32_t Threshold = 1U << (NumBits-1);
129     
130     // Emit the bits with VBR encoding, NumBits-1 bits at a time.
131     while (Val >= Threshold) {
132       Emit((Val & ((1 << (NumBits-1))-1)) | (1 << (NumBits-1)), NumBits);
133       Val >>= NumBits-1;
134     }
135     
136     Emit(Val, NumBits);
137   }
138   
139   void EmitVBR64(uint64_t Val, unsigned NumBits) {
140     if ((uint32_t)Val == Val)
141       return EmitVBR((uint32_t)Val, NumBits);
142     
143     uint64_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(((uint32_t)Val & ((1 << (NumBits-1))-1)) |
148            (1 << (NumBits-1)), NumBits);
149       Val >>= NumBits-1;
150     }
151     
152     Emit((uint32_t)Val, NumBits);
153   }
154   
155   /// EmitCode - Emit the specified code.
156   void EmitCode(unsigned Val) {
157     Emit(Val, CurCodeSize);
158   }
159   
160   //===--------------------------------------------------------------------===//
161   // Block Manipulation
162   //===--------------------------------------------------------------------===//
163   
164   /// getBlockInfo - If there is block info for the specified ID, return it,
165   /// otherwise return null.
166   BlockInfo *getBlockInfo(unsigned BlockID) {
167     // Common case, the most recent entry matches BlockID.
168     if (!BlockInfoRecords.empty() && BlockInfoRecords.back().BlockID == BlockID)
169       return &BlockInfoRecords.back();
170     
171     for (unsigned i = 0, e = static_cast<unsigned>(BlockInfoRecords.size());
172          i != e; ++i)
173       if (BlockInfoRecords[i].BlockID == BlockID)
174         return &BlockInfoRecords[i];
175     return 0;
176   }
177   
178   void EnterSubblock(unsigned BlockID, unsigned CodeLen) {
179     // Block header:
180     //    [ENTER_SUBBLOCK, blockid, newcodelen, <align4bytes>, blocklen]
181     EmitCode(bitc::ENTER_SUBBLOCK);
182     EmitVBR(BlockID, bitc::BlockIDWidth);
183     EmitVBR(CodeLen, bitc::CodeLenWidth);
184     FlushToWord();
185     
186     unsigned BlockSizeWordLoc = static_cast<unsigned>(Out.size());
187     unsigned OldCodeSize = CurCodeSize;
188     
189     // Emit a placeholder, which will be replaced when the block is popped.
190     Emit(0, bitc::BlockSizeWidth);
191     
192     CurCodeSize = CodeLen;
193     
194     // Push the outer block's abbrev set onto the stack, start out with an
195     // empty abbrev set.
196     BlockScope.push_back(Block(OldCodeSize, BlockSizeWordLoc/4));
197     BlockScope.back().PrevAbbrevs.swap(CurAbbrevs);
198
199     // If there is a blockinfo for this BlockID, add all the predefined abbrevs
200     // to the abbrev list.
201     if (BlockInfo *Info = getBlockInfo(BlockID)) {
202       for (unsigned i = 0, e = static_cast<unsigned>(Info->Abbrevs.size());
203            i != e; ++i) {
204         CurAbbrevs.push_back(Info->Abbrevs[i]);
205         Info->Abbrevs[i]->addRef();
206       }
207     }
208   }
209   
210   void ExitBlock() {
211     assert(!BlockScope.empty() && "Block scope imbalance!");
212     
213     // Delete all abbrevs.
214     for (unsigned i = 0, e = static_cast<unsigned>(CurAbbrevs.size());
215          i != e; ++i)
216       CurAbbrevs[i]->dropRef();
217     
218     const Block &B = BlockScope.back();
219     
220     // Block tail:
221     //    [END_BLOCK, <align4bytes>]
222     EmitCode(bitc::END_BLOCK);
223     FlushToWord();
224
225     // Compute the size of the block, in words, not counting the size field.
226     unsigned SizeInWords= static_cast<unsigned>(Out.size())/4-B.StartSizeWord-1;
227     unsigned ByteNo = B.StartSizeWord*4;
228     
229     // Update the block size field in the header of this sub-block.
230     Out[ByteNo++] = (unsigned char)(SizeInWords >>  0);
231     Out[ByteNo++] = (unsigned char)(SizeInWords >>  8);
232     Out[ByteNo++] = (unsigned char)(SizeInWords >> 16);
233     Out[ByteNo++] = (unsigned char)(SizeInWords >> 24);
234     
235     // Restore the inner block's code size and abbrev table.
236     CurCodeSize = B.PrevCodeSize;
237     BlockScope.back().PrevAbbrevs.swap(CurAbbrevs);
238     BlockScope.pop_back();
239   }
240   
241   //===--------------------------------------------------------------------===//
242   // Record Emission
243   //===--------------------------------------------------------------------===//
244   
245 private:
246   /// EmitAbbreviatedField - Emit a single scalar field value with the specified
247   /// encoding.
248   template<typename uintty>
249   void EmitAbbreviatedField(const BitCodeAbbrevOp &Op, uintty V) {
250     if (Op.isLiteral()) {
251       // If the abbrev specifies the literal value to use, don't emit
252       // anything.
253       assert(V == Op.getLiteralValue() &&
254              "Invalid abbrev for record!");
255       return;
256     }
257     
258     // Encode the value as we are commanded.
259     switch (Op.getEncoding()) {
260     default: assert(0 && "Unknown encoding!");
261     case BitCodeAbbrevOp::Fixed:
262       Emit((unsigned)V, (unsigned)Op.getEncodingData());
263       break;
264     case BitCodeAbbrevOp::VBR:
265       EmitVBR64(V, (unsigned)Op.getEncodingData());
266       break;
267     case BitCodeAbbrevOp::Char6:
268       Emit(BitCodeAbbrevOp::EncodeChar6((char)V), 6);
269       break;
270     }        
271   }
272 public:
273     
274   /// EmitRecord - Emit the specified record to the stream, using an abbrev if
275   /// we have one to compress the output.
276   template<typename uintty>
277   void EmitRecord(unsigned Code, SmallVectorImpl<uintty> &Vals,
278                   unsigned Abbrev = 0) {
279     if (Abbrev) {
280       unsigned AbbrevNo = Abbrev-bitc::FIRST_APPLICATION_ABBREV;
281       assert(AbbrevNo < CurAbbrevs.size() && "Invalid abbrev #!");
282       BitCodeAbbrev *Abbv = CurAbbrevs[AbbrevNo];
283       
284       EmitCode(Abbrev);
285       
286       // Insert the code into Vals to treat it uniformly.
287       Vals.insert(Vals.begin(), Code);
288       
289       unsigned RecordIdx = 0;
290       for (unsigned i = 0, e = static_cast<unsigned>(Abbv->getNumOperandInfos());
291            i != e; ++i) {
292         const BitCodeAbbrevOp &Op = Abbv->getOperandInfo(i);
293         if (Op.isLiteral() || Op.getEncoding() != BitCodeAbbrevOp::Array) {
294           assert(RecordIdx < Vals.size() && "Invalid abbrev/record");
295           EmitAbbreviatedField(Op, Vals[RecordIdx]);
296           ++RecordIdx;
297         } else {
298           // Array case.
299           assert(i+2 == e && "array op not second to last?");
300           const BitCodeAbbrevOp &EltEnc = Abbv->getOperandInfo(++i);
301           
302           // Emit a vbr6 to indicate the number of elements present.
303           EmitVBR(static_cast<uint32_t>(Vals.size()-RecordIdx), 6);
304           
305           // Emit each field.
306           for (; RecordIdx != Vals.size(); ++RecordIdx)
307             EmitAbbreviatedField(EltEnc, Vals[RecordIdx]);
308         }
309       }
310       assert(RecordIdx == Vals.size() && "Not all record operands emitted!");
311     } else {
312       // If we don't have an abbrev to use, emit this in its fully unabbreviated
313       // form.
314       EmitCode(bitc::UNABBREV_RECORD);
315       EmitVBR(Code, 6);
316       EmitVBR(static_cast<uint32_t>(Vals.size()), 6);
317       for (unsigned i = 0, e = static_cast<unsigned>(Vals.size()); i != e; ++i)
318         EmitVBR64(Vals[i], 6);
319     }
320   }
321
322   //===--------------------------------------------------------------------===//
323   // Abbrev Emission
324   //===--------------------------------------------------------------------===//
325   
326 private:
327   // Emit the abbreviation as a DEFINE_ABBREV record.
328   void EncodeAbbrev(BitCodeAbbrev *Abbv) {
329     EmitCode(bitc::DEFINE_ABBREV);
330     EmitVBR(Abbv->getNumOperandInfos(), 5);
331     for (unsigned i = 0, e = static_cast<unsigned>(Abbv->getNumOperandInfos());
332          i != e; ++i) {
333       const BitCodeAbbrevOp &Op = Abbv->getOperandInfo(i);
334       Emit(Op.isLiteral(), 1);
335       if (Op.isLiteral()) {
336         EmitVBR64(Op.getLiteralValue(), 8);
337       } else {
338         Emit(Op.getEncoding(), 3);
339         if (Op.hasEncodingData())
340           EmitVBR64(Op.getEncodingData(), 5);
341       }
342     }
343   }
344 public:
345     
346   /// EmitAbbrev - This emits an abbreviation to the stream.  Note that this
347   /// method takes ownership of the specified abbrev.
348   unsigned EmitAbbrev(BitCodeAbbrev *Abbv) {
349     // Emit the abbreviation as a record.
350     EncodeAbbrev(Abbv);
351     CurAbbrevs.push_back(Abbv);
352     return static_cast<unsigned>(CurAbbrevs.size())-1 +
353       bitc::FIRST_APPLICATION_ABBREV;
354   }
355   
356   //===--------------------------------------------------------------------===//
357   // BlockInfo Block Emission
358   //===--------------------------------------------------------------------===//
359   
360   /// EnterBlockInfoBlock - Start emitting the BLOCKINFO_BLOCK.
361   void EnterBlockInfoBlock(unsigned CodeWidth) {
362     EnterSubblock(bitc::BLOCKINFO_BLOCK_ID, CodeWidth);
363     BlockInfoCurBID = -1U;
364   }
365 private:  
366   /// SwitchToBlockID - If we aren't already talking about the specified block
367   /// ID, emit a BLOCKINFO_CODE_SETBID record.
368   void SwitchToBlockID(unsigned BlockID) {
369     if (BlockInfoCurBID == BlockID) return;
370     SmallVector<unsigned, 2> V;
371     V.push_back(BlockID);
372     EmitRecord(bitc::BLOCKINFO_CODE_SETBID, V);
373     BlockInfoCurBID = BlockID;
374   }
375
376   BlockInfo &getOrCreateBlockInfo(unsigned BlockID) {
377     if (BlockInfo *BI = getBlockInfo(BlockID))
378       return *BI;
379     
380     // Otherwise, add a new record.
381     BlockInfoRecords.push_back(BlockInfo());
382     BlockInfoRecords.back().BlockID = BlockID;
383     return BlockInfoRecords.back();
384   }
385   
386 public:
387   
388   /// EmitBlockInfoAbbrev - Emit a DEFINE_ABBREV record for the specified
389   /// BlockID.
390   unsigned EmitBlockInfoAbbrev(unsigned BlockID, BitCodeAbbrev *Abbv) {
391     SwitchToBlockID(BlockID);
392     EncodeAbbrev(Abbv);
393     
394     // Add the abbrev to the specified block record.
395     BlockInfo &Info = getOrCreateBlockInfo(BlockID);
396     Info.Abbrevs.push_back(Abbv);
397     
398     return Info.Abbrevs.size()-1+bitc::FIRST_APPLICATION_ABBREV;
399   }
400 };
401
402
403 } // End llvm namespace
404
405 #endif