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