llvm.org GIT mirror llvm / 742690b
[Bitcode] Move Bitstream to a separate library This moves Bitcode/Bitstream*, Bitcode/BitCodes.h to Bitstream/. This is needed to avoid a circular dependency when using the bitstream code for parsing optimization remarks. Since Bitcode uses Core for the IR part: libLLVMRemarks -> Bitcode -> Core and Core uses libLLVMRemarks to generate remarks (see IR/RemarkStreamer.cpp): Core -> libLLVMRemarks we need to separate the Bitstream and Bitcode part. For clang-doc, it seems that it doesn't need the whole bitcode layer, so I updated the CMake to only use the bitstream part. Differential Revision: https://reviews.llvm.org/D63899 git-svn-id: https://llvm.org/svn/llvm-project/llvm/trunk@365091 91177308-0d34-0410-b5e6-96231b3b80d8 Francis Visoiu Mistrih a month ago
33 changed file(s) with 2096 addition(s) and 2030 deletion(s). Raw diff Collapse all Expand all
+0
-182
include/llvm/Bitcode/BitCodes.h less more
None //===- BitCodes.h - Enum values for the bitcode format ----------*- C++ -*-===//
1 //
2 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
3 // See https://llvm.org/LICENSE.txt for license information.
4 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
5 //
6 //===----------------------------------------------------------------------===//
7 //
8 // This header Bitcode enum values.
9 //
10 // The enum values defined in this file should be considered permanent. If
11 // new features are added, they should have values added at the end of the
12 // respective lists.
13 //
14 //===----------------------------------------------------------------------===//
15
16 #ifndef LLVM_BITCODE_BITCODES_H
17 #define LLVM_BITCODE_BITCODES_H
18
19 #include "llvm/ADT/SmallVector.h"
20 #include "llvm/Support/DataTypes.h"
21 #include "llvm/Support/ErrorHandling.h"
22 #include
23
24 namespace llvm {
25 /// Offsets of the 32-bit fields of bitcode wrapper header.
26 static const unsigned BWH_MagicField = 0 * 4;
27 static const unsigned BWH_VersionField = 1 * 4;
28 static const unsigned BWH_OffsetField = 2 * 4;
29 static const unsigned BWH_SizeField = 3 * 4;
30 static const unsigned BWH_CPUTypeField = 4 * 4;
31 static const unsigned BWH_HeaderSize = 5 * 4;
32
33 namespace bitc {
34 enum StandardWidths {
35 BlockIDWidth = 8, // We use VBR-8 for block IDs.
36 CodeLenWidth = 4, // Codelen are VBR-4.
37 BlockSizeWidth = 32 // BlockSize up to 2^32 32-bit words = 16GB per block.
38 };
39
40 // The standard abbrev namespace always has a way to exit a block, enter a
41 // nested block, define abbrevs, and define an unabbreviated record.
42 enum FixedAbbrevIDs {
43 END_BLOCK = 0, // Must be zero to guarantee termination for broken bitcode.
44 ENTER_SUBBLOCK = 1,
45
46 /// DEFINE_ABBREV - Defines an abbrev for the current block. It consists
47 /// of a vbr5 for # operand infos. Each operand info is emitted with a
48 /// single bit to indicate if it is a literal encoding. If so, the value is
49 /// emitted with a vbr8. If not, the encoding is emitted as 3 bits followed
50 /// by the info value as a vbr5 if needed.
51 DEFINE_ABBREV = 2,
52
53 // UNABBREV_RECORDs are emitted with a vbr6 for the record code, followed by
54 // a vbr6 for the # operands, followed by vbr6's for each operand.
55 UNABBREV_RECORD = 3,
56
57 // This is not a code, this is a marker for the first abbrev assignment.
58 FIRST_APPLICATION_ABBREV = 4
59 };
60
61 /// StandardBlockIDs - All bitcode files can optionally include a BLOCKINFO
62 /// block, which contains metadata about other blocks in the file.
63 enum StandardBlockIDs {
64 /// BLOCKINFO_BLOCK is used to define metadata about blocks, for example,
65 /// standard abbrevs that should be available to all blocks of a specified
66 /// ID.
67 BLOCKINFO_BLOCK_ID = 0,
68
69 // Block IDs 1-7 are reserved for future expansion.
70 FIRST_APPLICATION_BLOCKID = 8
71 };
72
73 /// BlockInfoCodes - The blockinfo block contains metadata about user-defined
74 /// blocks.
75 enum BlockInfoCodes {
76 // DEFINE_ABBREV has magic semantics here, applying to the current SETBID'd
77 // block, instead of the BlockInfo block.
78
79 BLOCKINFO_CODE_SETBID = 1, // SETBID: [blockid#]
80 BLOCKINFO_CODE_BLOCKNAME = 2, // BLOCKNAME: [name]
81 BLOCKINFO_CODE_SETRECORDNAME = 3 // BLOCKINFO_CODE_SETRECORDNAME:
82 // [id, name]
83 };
84
85 } // End bitc namespace
86
87 /// BitCodeAbbrevOp - This describes one or more operands in an abbreviation.
88 /// This is actually a union of two different things:
89 /// 1. It could be a literal integer value ("the operand is always 17").
90 /// 2. It could be an encoding specification ("this operand encoded like so").
91 ///
92 class BitCodeAbbrevOp {
93 uint64_t Val; // A literal value or data for an encoding.
94 bool IsLiteral : 1; // Indicate whether this is a literal value or not.
95 unsigned Enc : 3; // The encoding to use.
96 public:
97 enum Encoding {
98 Fixed = 1, // A fixed width field, Val specifies number of bits.
99 VBR = 2, // A VBR field where Val specifies the width of each chunk.
100 Array = 3, // A sequence of fields, next field species elt encoding.
101 Char6 = 4, // A 6-bit fixed field which maps to [a-zA-Z0-9._].
102 Blob = 5 // 32-bit aligned array of 8-bit characters.
103 };
104
105 explicit BitCodeAbbrevOp(uint64_t V) : Val(V), IsLiteral(true) {}
106 explicit BitCodeAbbrevOp(Encoding E, uint64_t Data = 0)
107 : Val(Data), IsLiteral(false), Enc(E) {}
108
109 bool isLiteral() const { return IsLiteral; }
110 bool isEncoding() const { return !IsLiteral; }
111
112 // Accessors for literals.
113 uint64_t getLiteralValue() const { assert(isLiteral()); return Val; }
114
115 // Accessors for encoding info.
116 Encoding getEncoding() const { assert(isEncoding()); return (Encoding)Enc; }
117 uint64_t getEncodingData() const {
118 assert(isEncoding() && hasEncodingData());
119 return Val;
120 }
121
122 bool hasEncodingData() const { return hasEncodingData(getEncoding()); }
123 static bool hasEncodingData(Encoding E) {
124 switch (E) {
125 case Fixed:
126 case VBR:
127 return true;
128 case Array:
129 case Char6:
130 case Blob:
131 return false;
132 }
133 report_fatal_error("Invalid encoding");
134 }
135
136 /// isChar6 - Return true if this character is legal in the Char6 encoding.
137 static bool isChar6(char C) {
138 if (C >= 'a' && C <= 'z') return true;
139 if (C >= 'A' && C <= 'Z') return true;
140 if (C >= '0' && C <= '9') return true;
141 if (C == '.' || C == '_') return true;
142 return false;
143 }
144 static unsigned EncodeChar6(char C) {
145 if (C >= 'a' && C <= 'z') return C-'a';
146 if (C >= 'A' && C <= 'Z') return C-'A'+26;
147 if (C >= '0' && C <= '9') return C-'0'+26+26;
148 if (C == '.') return 62;
149 if (C == '_') return 63;
150 llvm_unreachable("Not a value Char6 character!");
151 }
152
153 static char DecodeChar6(unsigned V) {
154 assert((V & ~63) == 0 && "Not a Char6 encoded character!");
155 return "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789._"
156 [V];
157 }
158
159 };
160
161 /// BitCodeAbbrev - This class represents an abbreviation record. An
162 /// abbreviation allows a complex record that has redundancy to be stored in a
163 /// specialized format instead of the fully-general, fully-vbr, format.
164 class BitCodeAbbrev {
165 SmallVector OperandList;
166
167 public:
168 unsigned getNumOperandInfos() const {
169 return static_cast(OperandList.size());
170 }
171 const BitCodeAbbrevOp &getOperandInfo(unsigned N) const {
172 return OperandList[N];
173 }
174
175 void Add(const BitCodeAbbrevOp &OpInfo) {
176 OperandList.push_back(OpInfo);
177 }
178 };
179 } // End llvm namespace
180
181 #endif
1414
1515 #include "llvm/ADT/ArrayRef.h"
1616 #include "llvm/ADT/StringRef.h"
17 #include "llvm/Bitcode/BitCodes.h"
17 #include "llvm/Bitstream/BitCodes.h"
1818 #include "llvm/IR/ModuleSummaryIndex.h"
1919 #include "llvm/Support/Endian.h"
2020 #include "llvm/Support/Error.h"
+0
-553
include/llvm/Bitcode/BitstreamReader.h less more
None //===- BitstreamReader.h - Low-level bitstream reader interface -*- C++ -*-===//
1 //
2 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
3 // See https://llvm.org/LICENSE.txt for license information.
4 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
5 //
6 //===----------------------------------------------------------------------===//
7 //
8 // This header defines the BitstreamReader class. This class can be used to
9 // read an arbitrary bitstream, regardless of its contents.
10 //
11 //===----------------------------------------------------------------------===//
12
13 #ifndef LLVM_BITCODE_BITSTREAMREADER_H
14 #define LLVM_BITCODE_BITSTREAMREADER_H
15
16 #include "llvm/ADT/ArrayRef.h"
17 #include "llvm/ADT/SmallVector.h"
18 #include "llvm/Bitcode/BitCodes.h"
19 #include "llvm/Support/Endian.h"
20 #include "llvm/Support/ErrorHandling.h"
21 #include "llvm/Support/MathExtras.h"
22 #include "llvm/Support/MemoryBuffer.h"
23 #include
24 #include
25 #include
26 #include
27 #include
28 #include
29 #include
30 #include
31 #include
32
33 namespace llvm {
34
35 /// This class maintains the abbreviations read from a block info block.
36 class BitstreamBlockInfo {
37 public:
38 /// This contains information emitted to BLOCKINFO_BLOCK blocks. These
39 /// describe abbreviations that all blocks of the specified ID inherit.
40 struct BlockInfo {
41 unsigned BlockID;
42 std::vector> Abbrevs;
43 std::string Name;
44 std::vector> RecordNames;
45 };
46
47 private:
48 std::vector BlockInfoRecords;
49
50 public:
51 /// If there is block info for the specified ID, return it, otherwise return
52 /// null.
53 const BlockInfo *getBlockInfo(unsigned BlockID) const {
54 // Common case, the most recent entry matches BlockID.
55 if (!BlockInfoRecords.empty() && BlockInfoRecords.back().BlockID == BlockID)
56 return &BlockInfoRecords.back();
57
58 for (unsigned i = 0, e = static_cast(BlockInfoRecords.size());
59 i != e; ++i)
60 if (BlockInfoRecords[i].BlockID == BlockID)
61 return &BlockInfoRecords[i];
62 return nullptr;
63 }
64
65 BlockInfo &getOrCreateBlockInfo(unsigned BlockID) {
66 if (const BlockInfo *BI = getBlockInfo(BlockID))
67 return *const_cast(BI);
68
69 // Otherwise, add a new record.
70 BlockInfoRecords.emplace_back();
71 BlockInfoRecords.back().BlockID = BlockID;
72 return BlockInfoRecords.back();
73 }
74 };
75
76 /// This represents a position within a bitstream. There may be multiple
77 /// independent cursors reading within one bitstream, each maintaining their
78 /// own local state.
79 class SimpleBitstreamCursor {
80 ArrayRef BitcodeBytes;
81 size_t NextChar = 0;
82
83 public:
84 /// This is the current data we have pulled from the stream but have not
85 /// returned to the client. This is specifically and intentionally defined to
86 /// follow the word size of the host machine for efficiency. We use word_t in
87 /// places that are aware of this to make it perfectly explicit what is going
88 /// on.
89 using word_t = size_t;
90
91 private:
92 word_t CurWord = 0;
93
94 /// This is the number of bits in CurWord that are valid. This is always from
95 /// [0...bits_of(size_t)-1] inclusive.
96 unsigned BitsInCurWord = 0;
97
98 public:
99 static const constexpr size_t MaxChunkSize = sizeof(word_t) * 8;
100
101 SimpleBitstreamCursor() = default;
102 explicit SimpleBitstreamCursor(ArrayRef BitcodeBytes)
103 : BitcodeBytes(BitcodeBytes) {}
104 explicit SimpleBitstreamCursor(StringRef BitcodeBytes)
105 : BitcodeBytes(arrayRefFromStringRef(BitcodeBytes)) {}
106 explicit SimpleBitstreamCursor(MemoryBufferRef BitcodeBytes)
107 : SimpleBitstreamCursor(BitcodeBytes.getBuffer()) {}
108
109 bool canSkipToPos(size_t pos) const {
110 // pos can be skipped to if it is a valid address or one byte past the end.
111 return pos <= BitcodeBytes.size();
112 }
113
114 bool AtEndOfStream() {
115 return BitsInCurWord == 0 && BitcodeBytes.size() <= NextChar;
116 }
117
118 /// Return the bit # of the bit we are reading.
119 uint64_t GetCurrentBitNo() const {
120 return NextChar*CHAR_BIT - BitsInCurWord;
121 }
122
123 // Return the byte # of the current bit.
124 uint64_t getCurrentByteNo() const { return GetCurrentBitNo() / 8; }
125
126 ArrayRef getBitcodeBytes() const { return BitcodeBytes; }
127
128 /// Reset the stream to the specified bit number.
129 Error JumpToBit(uint64_t BitNo) {
130 size_t ByteNo = size_t(BitNo/8) & ~(sizeof(word_t)-1);
131 unsigned WordBitNo = unsigned(BitNo & (sizeof(word_t)*8-1));
132 assert(canSkipToPos(ByteNo) && "Invalid location");
133
134 // Move the cursor to the right word.
135 NextChar = ByteNo;
136 BitsInCurWord = 0;
137
138 // Skip over any bits that are already consumed.
139 if (WordBitNo) {
140 if (Expected Res = Read(WordBitNo))
141 return Error::success();
142 else
143 return Res.takeError();
144 }
145
146 return Error::success();
147 }
148
149 /// Get a pointer into the bitstream at the specified byte offset.
150 const uint8_t *getPointerToByte(uint64_t ByteNo, uint64_t NumBytes) {
151 return BitcodeBytes.data() + ByteNo;
152 }
153
154 /// Get a pointer into the bitstream at the specified bit offset.
155 ///
156 /// The bit offset must be on a byte boundary.
157 const uint8_t *getPointerToBit(uint64_t BitNo, uint64_t NumBytes) {
158 assert(!(BitNo % 8) && "Expected bit on byte boundary");
159 return getPointerToByte(BitNo / 8, NumBytes);
160 }
161
162 Error fillCurWord() {
163 if (NextChar >= BitcodeBytes.size())
164 return createStringError(std::errc::io_error,
165 "Unexpected end of file reading %u of %u bytes",
166 NextChar, BitcodeBytes.size());
167
168 // Read the next word from the stream.
169 const uint8_t *NextCharPtr = BitcodeBytes.data() + NextChar;
170 unsigned BytesRead;
171 if (BitcodeBytes.size() >= NextChar + sizeof(word_t)) {
172 BytesRead = sizeof(word_t);
173 CurWord =
174 support::endian::read(
175 NextCharPtr);
176 } else {
177 // Short read.
178 BytesRead = BitcodeBytes.size() - NextChar;
179 CurWord = 0;
180 for (unsigned B = 0; B != BytesRead; ++B)
181 CurWord |= uint64_t(NextCharPtr[B]) << (B * 8);
182 }
183 NextChar += BytesRead;
184 BitsInCurWord = BytesRead * 8;
185 return Error::success();
186 }
187
188 Expected Read(unsigned NumBits) {
189 static const unsigned BitsInWord = MaxChunkSize;
190
191 assert(NumBits && NumBits <= BitsInWord &&
192 "Cannot return zero or more than BitsInWord bits!");
193
194 static const unsigned Mask = sizeof(word_t) > 4 ? 0x3f : 0x1f;
195
196 // If the field is fully contained by CurWord, return it quickly.
197 if (BitsInCurWord >= NumBits) {
198 word_t R = CurWord & (~word_t(0) >> (BitsInWord - NumBits));
199
200 // Use a mask to avoid undefined behavior.
201 CurWord >>= (NumBits & Mask);
202
203 BitsInCurWord -= NumBits;
204 return R;
205 }
206
207 word_t R = BitsInCurWord ? CurWord : 0;
208 unsigned BitsLeft = NumBits - BitsInCurWord;
209
210 if (Error fillResult = fillCurWord())
211 return std::move(fillResult);
212
213 // If we run out of data, abort.
214 if (BitsLeft > BitsInCurWord)
215 return createStringError(std::errc::io_error,
216 "Unexpected end of file reading %u of %u bits",
217 BitsInCurWord, BitsLeft);
218
219 word_t R2 = CurWord & (~word_t(0) >> (BitsInWord - BitsLeft));
220
221 // Use a mask to avoid undefined behavior.
222 CurWord >>= (BitsLeft & Mask);
223
224 BitsInCurWord -= BitsLeft;
225
226 R |= R2 << (NumBits - BitsLeft);
227
228 return R;
229 }
230
231 Expected ReadVBR(unsigned NumBits) {
232 Expected MaybeRead = Read(NumBits);
233 if (!MaybeRead)
234 return MaybeRead;
235 uint32_t Piece = MaybeRead.get();
236
237 if ((Piece & (1U << (NumBits-1))) == 0)
238 return Piece;
239
240 uint32_t Result = 0;
241 unsigned NextBit = 0;
242 while (true) {
243 Result |= (Piece & ((1U << (NumBits-1))-1)) << NextBit;
244
245 if ((Piece & (1U << (NumBits-1))) == 0)
246 return Result;
247
248 NextBit += NumBits-1;
249 MaybeRead = Read(NumBits);
250 if (!MaybeRead)
251 return MaybeRead;
252 Piece = MaybeRead.get();
253 }
254 }
255
256 // Read a VBR that may have a value up to 64-bits in size. The chunk size of
257 // the VBR must still be <= 32 bits though.
258 Expected ReadVBR64(unsigned NumBits) {
259 Expected MaybeRead = Read(NumBits);
260 if (!MaybeRead)
261 return MaybeRead;
262 uint32_t Piece = MaybeRead.get();
263
264 if ((Piece & (1U << (NumBits-1))) == 0)
265 return uint64_t(Piece);
266
267 uint64_t Result = 0;
268 unsigned NextBit = 0;
269 while (true) {
270 Result |= uint64_t(Piece & ((1U << (NumBits-1))-1)) << NextBit;
271
272 if ((Piece & (1U << (NumBits-1))) == 0)
273 return Result;
274
275 NextBit += NumBits-1;
276 MaybeRead = Read(NumBits);
277 if (!MaybeRead)
278 return MaybeRead;
279 Piece = MaybeRead.get();
280 }
281 }
282
283 void SkipToFourByteBoundary() {
284 // If word_t is 64-bits and if we've read less than 32 bits, just dump
285 // the bits we have up to the next 32-bit boundary.
286 if (sizeof(word_t) > 4 &&
287 BitsInCurWord >= 32) {
288 CurWord >>= BitsInCurWord-32;
289 BitsInCurWord = 32;
290 return;
291 }
292
293 BitsInCurWord = 0;
294 }
295
296 /// Skip to the end of the file.
297 void skipToEnd() { NextChar = BitcodeBytes.size(); }
298 };
299
300 /// When advancing through a bitstream cursor, each advance can discover a few
301 /// different kinds of entries:
302 struct BitstreamEntry {
303 enum {
304 Error, // Malformed bitcode was found.
305 EndBlock, // We've reached the end of the current block, (or the end of the
306 // file, which is treated like a series of EndBlock records.
307 SubBlock, // This is the start of a new subblock of a specific ID.
308 Record // This is a record with a specific AbbrevID.
309 } Kind;
310
311 unsigned ID;
312
313 static BitstreamEntry getError() {
314 BitstreamEntry E; E.Kind = Error; return E;
315 }
316
317 static BitstreamEntry getEndBlock() {
318 BitstreamEntry E; E.Kind = EndBlock; return E;
319 }
320
321 static BitstreamEntry getSubBlock(unsigned ID) {
322 BitstreamEntry E; E.Kind = SubBlock; E.ID = ID; return E;
323 }
324
325 static BitstreamEntry getRecord(unsigned AbbrevID) {
326 BitstreamEntry E; E.Kind = Record; E.ID = AbbrevID; return E;
327 }
328 };
329
330 /// This represents a position within a bitcode file, implemented on top of a
331 /// SimpleBitstreamCursor.
332 ///
333 /// Unlike iterators, BitstreamCursors are heavy-weight objects that should not
334 /// be passed by value.
335 class BitstreamCursor : SimpleBitstreamCursor {
336 // This is the declared size of code values used for the current block, in
337 // bits.
338 unsigned CurCodeSize = 2;
339
340 /// Abbrevs installed at in this block.
341 std::vector> CurAbbrevs;
342
343 struct Block {
344 unsigned PrevCodeSize;
345 std::vector> PrevAbbrevs;
346
347 explicit Block(unsigned PCS) : PrevCodeSize(PCS) {}
348 };
349
350 /// This tracks the codesize of parent blocks.
351 SmallVector BlockScope;
352
353 BitstreamBlockInfo *BlockInfo = nullptr;
354
355 public:
356 static const size_t MaxChunkSize = sizeof(word_t) * 8;
357
358 BitstreamCursor() = default;
359 explicit BitstreamCursor(ArrayRef BitcodeBytes)
360 : SimpleBitstreamCursor(BitcodeBytes) {}
361 explicit BitstreamCursor(StringRef BitcodeBytes)
362 : SimpleBitstreamCursor(BitcodeBytes) {}
363 explicit BitstreamCursor(MemoryBufferRef BitcodeBytes)
364 : SimpleBitstreamCursor(BitcodeBytes) {}
365
366 using SimpleBitstreamCursor::canSkipToPos;
367 using SimpleBitstreamCursor::AtEndOfStream;
368 using SimpleBitstreamCursor::getBitcodeBytes;
369 using SimpleBitstreamCursor::GetCurrentBitNo;
370 using SimpleBitstreamCursor::getCurrentByteNo;
371 using SimpleBitstreamCursor::getPointerToByte;
372 using SimpleBitstreamCursor::JumpToBit;
373 using SimpleBitstreamCursor::fillCurWord;
374 using SimpleBitstreamCursor::Read;
375 using SimpleBitstreamCursor::ReadVBR;
376 using SimpleBitstreamCursor::ReadVBR64;
377
378 /// Return the number of bits used to encode an abbrev #.
379 unsigned getAbbrevIDWidth() const { return CurCodeSize; }
380
381 /// Flags that modify the behavior of advance().
382 enum {
383 /// If this flag is used, the advance() method does not automatically pop
384 /// the block scope when the end of a block is reached.
385 AF_DontPopBlockAtEnd = 1,
386
387 /// If this flag is used, abbrev entries are returned just like normal
388 /// records.
389 AF_DontAutoprocessAbbrevs = 2
390 };
391
392 /// Advance the current bitstream, returning the next entry in the stream.
393 Expected advance(unsigned Flags = 0) {
394 while (true) {
395 if (AtEndOfStream())
396 return BitstreamEntry::getError();
397
398 Expected MaybeCode = ReadCode();
399 if (!MaybeCode)
400 return MaybeCode.takeError();
401 unsigned Code = MaybeCode.get();
402
403 if (Code == bitc::END_BLOCK) {
404 // Pop the end of the block unless Flags tells us not to.
405 if (!(Flags & AF_DontPopBlockAtEnd) && ReadBlockEnd())
406 return BitstreamEntry::getError();
407 return BitstreamEntry::getEndBlock();
408 }
409
410 if (Code == bitc::ENTER_SUBBLOCK) {
411 if (Expected MaybeSubBlock = ReadSubBlockID())
412 return BitstreamEntry::getSubBlock(MaybeSubBlock.get());
413 else
414 return MaybeSubBlock.takeError();
415 }
416
417 if (Code == bitc::DEFINE_ABBREV &&
418 !(Flags & AF_DontAutoprocessAbbrevs)) {
419 // We read and accumulate abbrev's, the client can't do anything with
420 // them anyway.
421 if (Error Err = ReadAbbrevRecord())
422 return std::move(Err);
423 continue;
424 }
425
426 return BitstreamEntry::getRecord(Code);
427 }
428 }
429
430 /// This is a convenience function for clients that don't expect any
431 /// subblocks. This just skips over them automatically.
432 Expected advanceSkippingSubblocks(unsigned Flags = 0) {
433 while (true) {
434 // If we found a normal entry, return it.
435 Expected MaybeEntry = advance(Flags);
436 if (!MaybeEntry)
437 return MaybeEntry;
438 BitstreamEntry Entry = MaybeEntry.get();
439
440 if (Entry.Kind != BitstreamEntry::SubBlock)
441 return Entry;
442
443 // If we found a sub-block, just skip over it and check the next entry.
444 if (Error Err = SkipBlock())
445 return std::move(Err);
446 }
447 }
448
449 Expected ReadCode() { return Read(CurCodeSize); }
450
451 // Block header:
452 // [ENTER_SUBBLOCK, blockid, newcodelen, , blocklen]
453
454 /// Having read the ENTER_SUBBLOCK code, read the BlockID for the block.
455 Expected ReadSubBlockID() { return ReadVBR(bitc::BlockIDWidth); }
456
457 /// Having read the ENTER_SUBBLOCK abbrevid and a BlockID, skip over the body
458 /// of this block.
459 Error SkipBlock() {
460 // Read and ignore the codelen value.
461 if (Expected Res = ReadVBR(bitc::CodeLenWidth))
462 ; // Since we are skipping this block, we don't care what code widths are
463 // used inside of it.
464 else
465 return Res.takeError();
466
467 SkipToFourByteBoundary();
468 Expected MaybeNum = Read(bitc::BlockSizeWidth);
469 if (!MaybeNum)
470 return MaybeNum.takeError();
471 size_t NumFourBytes = MaybeNum.get();
472
473 // Check that the block wasn't partially defined, and that the offset isn't
474 // bogus.
475 size_t SkipTo = GetCurrentBitNo() + NumFourBytes * 4 * 8;
476 if (AtEndOfStream())
477 return createStringError(std::errc::illegal_byte_sequence,
478 "can't skip block: already at end of stream");
479 if (!canSkipToPos(SkipTo / 8))
480 return createStringError(std::errc::illegal_byte_sequence,
481 "can't skip to bit %zu from %" PRIu64, SkipTo,
482 GetCurrentBitNo());
483
484 if (Error Res = JumpToBit(SkipTo))
485 return Res;
486
487 return Error::success();
488 }
489
490 /// Having read the ENTER_SUBBLOCK abbrevid, and enter the block.
491 Error EnterSubBlock(unsigned BlockID, unsigned *NumWordsP = nullptr);
492
493 bool ReadBlockEnd() {
494 if (BlockScope.empty()) return true;
495
496 // Block tail:
497 // [END_BLOCK, ]
498 SkipToFourByteBoundary();
499
500 popBlockScope();
501 return false;
502 }
503
504 private:
505 void popBlockScope() {
506 CurCodeSize = BlockScope.back().PrevCodeSize;
507
508 CurAbbrevs = std::move(BlockScope.back().PrevAbbrevs);
509 BlockScope.pop_back();
510 }
511
512 //===--------------------------------------------------------------------===//
513 // Record Processing
514 //===--------------------------------------------------------------------===//
515
516 public:
517 /// Return the abbreviation for the specified AbbrevId.
518 const BitCodeAbbrev *getAbbrev(unsigned AbbrevID) {
519 unsigned AbbrevNo = AbbrevID - bitc::FIRST_APPLICATION_ABBREV;
520 if (AbbrevNo >= CurAbbrevs.size())
521 report_fatal_error("Invalid abbrev number");
522 return CurAbbrevs[AbbrevNo].get();
523 }
524
525 /// Read the current record and discard it, returning the code for the record.
526 Expected skipRecord(unsigned AbbrevID);
527
528 Expected readRecord(unsigned AbbrevID,
529 SmallVectorImpl &Vals,
530 StringRef *Blob = nullptr);
531
532 //===--------------------------------------------------------------------===//
533 // Abbrev Processing
534 //===--------------------------------------------------------------------===//
535 Error ReadAbbrevRecord();
536
537 /// Read and return a block info block from the bitstream. If an error was
538 /// encountered, return None.
539 ///
540 /// \param ReadBlockInfoNames Whether to read block/record name information in
541 /// the BlockInfo block. Only llvm-bcanalyzer uses this.
542 Expected>
543 ReadBlockInfoBlock(bool ReadBlockInfoNames = false);
544
545 /// Set the block info to be used by this BitstreamCursor to interpret
546 /// abbreviated records.
547 void setBlockInfo(BitstreamBlockInfo *BI) { BlockInfo = BI; }
548 };
549
550 } // end llvm namespace
551
552 #endif // LLVM_BITCODE_BITSTREAMREADER_H
+0
-547
include/llvm/Bitcode/BitstreamWriter.h less more
None //===- BitstreamWriter.h - Low-level bitstream writer interface -*- C++ -*-===//
1 //
2 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
3 // See https://llvm.org/LICENSE.txt for license information.
4 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
5 //
6 //===----------------------------------------------------------------------===//
7 //
8 // This header defines the BitstreamWriter class. This class can be used to
9 // write an arbitrary bitstream, regardless of its contents.
10 //
11 //===----------------------------------------------------------------------===//
12
13 #ifndef LLVM_BITCODE_BITSTREAMWRITER_H
14 #define LLVM_BITCODE_BITSTREAMWRITER_H
15
16 #include "llvm/ADT/ArrayRef.h"
17 #include "llvm/ADT/Optional.h"
18 #include "llvm/ADT/SmallVector.h"
19 #include "llvm/ADT/StringRef.h"
20 #include "llvm/Bitcode/BitCodes.h"
21 #include "llvm/Support/Endian.h"
22 #include
23
24 namespace llvm {
25
26 class BitstreamWriter {
27 SmallVectorImpl &Out;
28
29 /// CurBit - Always between 0 and 31 inclusive, specifies the next bit to use.
30 unsigned CurBit;
31
32 /// CurValue - The current value. Only bits < CurBit are valid.
33 uint32_t CurValue;
34
35 /// CurCodeSize - This is the declared size of code values used for the
36 /// current block, in bits.
37 unsigned CurCodeSize;
38
39 /// BlockInfoCurBID - When emitting a BLOCKINFO_BLOCK, this is the currently
40 /// selected BLOCK ID.
41 unsigned BlockInfoCurBID;
42
43 /// CurAbbrevs - Abbrevs installed at in this block.
44 std::vector> CurAbbrevs;
45
46 struct Block {
47 unsigned PrevCodeSize;
48 size_t StartSizeWord;
49 std::vector> PrevAbbrevs;
50 Block(unsigned PCS, size_t SSW) : PrevCodeSize(PCS), StartSizeWord(SSW) {}
51 };
52
53 /// BlockScope - This tracks the current blocks that we have entered.
54 std::vector BlockScope;
55
56 /// BlockInfo - This contains information emitted to BLOCKINFO_BLOCK blocks.
57 /// These describe abbreviations that all blocks of the specified ID inherit.
58 struct BlockInfo {
59 unsigned BlockID;
60 std::vector> Abbrevs;
61 };
62 std::vector BlockInfoRecords;
63
64 void WriteByte(unsigned char Value) {
65 Out.push_back(Value);
66 }
67
68 void WriteWord(unsigned Value) {
69 Value = support::endian::byte_swap(Value);
70 Out.append(reinterpret_cast(&Value),
71 reinterpret_cast(&Value + 1));
72 }
73
74 size_t GetBufferOffset() const { return Out.size(); }
75
76 size_t GetWordIndex() const {
77 size_t Offset = GetBufferOffset();
78 assert((Offset & 3) == 0 && "Not 32-bit aligned");
79 return Offset / 4;
80 }
81
82 public:
83 explicit BitstreamWriter(SmallVectorImpl &O)
84 : Out(O), CurBit(0), CurValue(0), CurCodeSize(2) {}
85
86 ~BitstreamWriter() {
87 assert(CurBit == 0 && "Unflushed data remaining");
88 assert(BlockScope.empty() && CurAbbrevs.empty() && "Block imbalance");
89 }
90
91 /// Retrieve the current position in the stream, in bits.
92 uint64_t GetCurrentBitNo() const { return GetBufferOffset() * 8 + CurBit; }
93
94 /// Retrieve the number of bits currently used to encode an abbrev ID.
95 unsigned GetAbbrevIDWidth() const { return CurCodeSize; }
96
97 //===--------------------------------------------------------------------===//
98 // Basic Primitives for emitting bits to the stream.
99 //===--------------------------------------------------------------------===//
100
101 /// Backpatch a 32-bit word in the output at the given bit offset
102 /// with the specified value.
103 void BackpatchWord(uint64_t BitNo, unsigned NewWord) {
104 using namespace llvm::support;
105 unsigned ByteNo = BitNo / 8;
106 assert((!endian::readAtBitAlignment(
107 &Out[ByteNo], BitNo & 7)) &&
108 "Expected to be patching over 0-value placeholders");
109 endian::writeAtBitAlignment(
110 &Out[ByteNo], NewWord, BitNo & 7);
111 }
112
113 void BackpatchWord64(uint64_t BitNo, uint64_t Val) {
114 BackpatchWord(BitNo, (uint32_t)Val);
115 BackpatchWord(BitNo + 32, (uint32_t)(Val >> 32));
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 FlushToWord() {
138 if (CurBit) {
139 WriteWord(CurValue);
140 CurBit = 0;
141 CurValue = 0;
142 }
143 }
144
145 void EmitVBR(uint32_t Val, unsigned NumBits) {
146 assert(NumBits <= 32 && "Too many bits to emit!");
147 uint32_t Threshold = 1U << (NumBits-1);
148
149 // Emit the bits with VBR encoding, NumBits-1 bits at a time.
150 while (Val >= Threshold) {
151 Emit((Val & ((1 << (NumBits-1))-1)) | (1 << (NumBits-1)), NumBits);
152 Val >>= NumBits-1;
153 }
154
155 Emit(Val, NumBits);
156 }
157
158 void EmitVBR64(uint64_t Val, unsigned NumBits) {
159 assert(NumBits <= 32 && "Too many bits to emit!");
160 if ((uint32_t)Val == Val)
161 return EmitVBR((uint32_t)Val, NumBits);
162
163 uint32_t Threshold = 1U << (NumBits-1);
164
165 // Emit the bits with VBR encoding, NumBits-1 bits at a time.
166 while (Val >= Threshold) {
167 Emit(((uint32_t)Val & ((1 << (NumBits-1))-1)) |
168 (1 << (NumBits-1)), NumBits);
169 Val >>= NumBits-1;
170 }
171
172 Emit((uint32_t)Val, NumBits);
173 }
174
175 /// EmitCode - Emit the specified code.
176 void EmitCode(unsigned Val) {
177 Emit(Val, CurCodeSize);
178 }
179
180 //===--------------------------------------------------------------------===//
181 // Block Manipulation
182 //===--------------------------------------------------------------------===//
183
184 /// getBlockInfo - If there is block info for the specified ID, return it,
185 /// otherwise return null.
186 BlockInfo *getBlockInfo(unsigned BlockID) {
187 // Common case, the most recent entry matches BlockID.
188 if (!BlockInfoRecords.empty() && BlockInfoRecords.back().BlockID == BlockID)
189 return &BlockInfoRecords.back();
190
191 for (unsigned i = 0, e = static_cast(BlockInfoRecords.size());
192 i != e; ++i)
193 if (BlockInfoRecords[i].BlockID == BlockID)
194 return &BlockInfoRecords[i];
195 return nullptr;
196 }
197
198 void EnterSubblock(unsigned BlockID, unsigned CodeLen) {
199 // Block header:
200 // [ENTER_SUBBLOCK, blockid, newcodelen, , blocklen]
201 EmitCode(bitc::ENTER_SUBBLOCK);
202 EmitVBR(BlockID, bitc::BlockIDWidth);
203 EmitVBR(CodeLen, bitc::CodeLenWidth);
204 FlushToWord();
205
206 size_t BlockSizeWordIndex = GetWordIndex();
207 unsigned OldCodeSize = CurCodeSize;
208
209 // Emit a placeholder, which will be replaced when the block is popped.
210 Emit(0, bitc::BlockSizeWidth);
211
212 CurCodeSize = CodeLen;
213
214 // Push the outer block's abbrev set onto the stack, start out with an
215 // empty abbrev set.
216 BlockScope.emplace_back(OldCodeSize, BlockSizeWordIndex);
217 BlockScope.back().PrevAbbrevs.swap(CurAbbrevs);
218
219 // If there is a blockinfo for this BlockID, add all the predefined abbrevs
220 // to the abbrev list.
221 if (BlockInfo *Info = getBlockInfo(BlockID)) {
222 CurAbbrevs.insert(CurAbbrevs.end(), Info->Abbrevs.begin(),
223 Info->Abbrevs.end());
224 }
225 }
226
227 void ExitBlock() {
228 assert(!BlockScope.empty() && "Block scope imbalance!");
229 const Block &B = BlockScope.back();
230
231 // Block tail:
232 // [END_BLOCK, ]
233 EmitCode(bitc::END_BLOCK);
234 FlushToWord();
235
236 // Compute the size of the block, in words, not counting the size field.
237 size_t SizeInWords = GetWordIndex() - B.StartSizeWord - 1;
238 uint64_t BitNo = uint64_t(B.StartSizeWord) * 32;
239
240 // Update the block size field in the header of this sub-block.
241 BackpatchWord(BitNo, SizeInWords);
242
243 // Restore the inner block's code size and abbrev table.
244 CurCodeSize = B.PrevCodeSize;
245 CurAbbrevs = std::move(B.PrevAbbrevs);
246 BlockScope.pop_back();
247 }
248
249 //===--------------------------------------------------------------------===//
250 // Record Emission
251 //===--------------------------------------------------------------------===//
252
253 private:
254 /// EmitAbbreviatedLiteral - Emit a literal value according to its abbrev
255 /// record. This is a no-op, since the abbrev specifies the literal to use.
256 template
257 void EmitAbbreviatedLiteral(const BitCodeAbbrevOp &Op, uintty V) {
258 assert(Op.isLiteral() && "Not a literal");
259 // If the abbrev specifies the literal value to use, don't emit
260 // anything.
261 assert(V == Op.getLiteralValue() &&
262 "Invalid abbrev for record!");
263 }
264
265 /// EmitAbbreviatedField - Emit a single scalar field value with the specified
266 /// encoding.
267 template
268 void EmitAbbreviatedField(const BitCodeAbbrevOp &Op, uintty V) {
269 assert(!Op.isLiteral() && "Literals should use EmitAbbreviatedLiteral!");
270
271 // Encode the value as we are commanded.
272 switch (Op.getEncoding()) {
273 default: llvm_unreachable("Unknown encoding!");
274 case BitCodeAbbrevOp::Fixed:
275 if (Op.getEncodingData())
276 Emit((unsigned)V, (unsigned)Op.getEncodingData());
277 break;
278 case BitCodeAbbrevOp::VBR:
279 if (Op.getEncodingData())
280 EmitVBR64(V, (unsigned)Op.getEncodingData());
281 break;
282 case BitCodeAbbrevOp::Char6:
283 Emit(BitCodeAbbrevOp::EncodeChar6((char)V), 6);
284 break;
285 }
286 }
287
288 /// EmitRecordWithAbbrevImpl - This is the core implementation of the record
289 /// emission code. If BlobData is non-null, then it specifies an array of
290 /// data that should be emitted as part of the Blob or Array operand that is
291 /// known to exist at the end of the record. If Code is specified, then
292 /// it is the record code to emit before the Vals, which must not contain
293 /// the code.
294 template
295 void EmitRecordWithAbbrevImpl(unsigned Abbrev, ArrayRef Vals,
296 StringRef Blob, Optional Code) {
297 const char *BlobData = Blob.data();
298 unsigned BlobLen = (unsigned) Blob.size();
299 unsigned AbbrevNo = Abbrev-bitc::FIRST_APPLICATION_ABBREV;
300 assert(AbbrevNo < CurAbbrevs.size() && "Invalid abbrev #!");
301 const BitCodeAbbrev *Abbv = CurAbbrevs[AbbrevNo].get();
302
303 EmitCode(Abbrev);
304
305 unsigned i = 0, e = static_cast(Abbv->getNumOperandInfos());
306 if (Code) {
307 assert(e && "Expected non-empty abbreviation");
308 const BitCodeAbbrevOp &Op = Abbv->getOperandInfo(i++);
309
310 if (Op.isLiteral())
311 EmitAbbreviatedLiteral(Op, Code.getValue());
312 else {
313 assert(Op.getEncoding() != BitCodeAbbrevOp::Array &&
314 Op.getEncoding() != BitCodeAbbrevOp::Blob &&
315 "Expected literal or scalar");
316 EmitAbbreviatedField(Op, Code.getValue());
317 }
318 }
319
320 unsigned RecordIdx = 0;
321 for (; 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(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 = nullptr;
346 } else {
347 // Emit a vbr6 to indicate the number of elements present.
348 EmitVBR(static_cast(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 if (BlobData) {
359 assert(RecordIdx == Vals.size() &&
360 "Blob data and record entries specified for blob operand!");
361
362 assert(Blob.data() == BlobData && "BlobData got moved");
363 assert(Blob.size() == BlobLen && "BlobLen got changed");
364 emitBlob(Blob);
365 BlobData = nullptr;
366 } else {
367 emitBlob(Vals.slice(RecordIdx));
368 }
369 } else { // Single scalar field.
370 assert(RecordIdx < Vals.size() && "Invalid abbrev/record");
371 EmitAbbreviatedField(Op, Vals[RecordIdx]);
372 ++RecordIdx;
373 }
374 }
375 assert(RecordIdx == Vals.size() && "Not all record operands emitted!");
376 assert(BlobData == nullptr &&
377 "Blob data specified for record that doesn't use it!");
378 }
379
380 public:
381 /// Emit a blob, including flushing before and tail-padding.
382 template
383 void emitBlob(ArrayRef Bytes, bool ShouldEmitSize = true) {
384 // Emit a vbr6 to indicate the number of elements present.
385 if (ShouldEmitSize)
386 EmitVBR(static_cast(Bytes.size()), 6);
387
388 // Flush to a 32-bit alignment boundary.
389 FlushToWord();
390
391 // Emit literal bytes.
392 for (const auto &B : Bytes) {
393 assert(isUInt<8>(B) && "Value too large to emit as byte");
394 WriteByte((unsigned char)B);
395 }
396
397 // Align end to 32-bits.
398 while (GetBufferOffset() & 3)
399 WriteByte(0);
400 }
401 void emitBlob(StringRef Bytes, bool ShouldEmitSize = true) {
402 emitBlob(makeArrayRef((const uint8_t *)Bytes.data(), Bytes.size()),
403 ShouldEmitSize);
404 }
405
406 /// EmitRecord - Emit the specified record to the stream, using an abbrev if
407 /// we have one to compress the output.
408 template
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(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
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
439 void EmitRecordWithBlob(unsigned Abbrev, const Container &Vals,
440 StringRef Blob) {
441 EmitRecordWithAbbrevImpl(Abbrev, makeArrayRef(Vals), Blob, None);
442 }
443 template
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
453 void EmitRecordWithArray(unsigned Abbrev, const Container &Vals,
454 StringRef Array) {
455 EmitRecordWithAbbrevImpl(Abbrev, makeArrayRef(Vals), Array, None);
456 }
457 template
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(const BitCodeAbbrev &Abbv) {
471 EmitCode(bitc::DEFINE_ABBREV);
472 EmitVBR(Abbv.getNumOperandInfos(), 5);
473 for (unsigned i = 0, e = static_cast(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 /// Emits the abbreviation \p Abbv to the stream.
489 unsigned EmitAbbrev(std::shared_ptr Abbv) {
490 EncodeAbbrev(*Abbv);
491 CurAbbrevs.push_back(std::move(Abbv));
492 return static_cast(CurAbbrevs.size())-1 +
493 bitc::FIRST_APPLICATION_ABBREV;
494 }
495
496 //===--------------------------------------------------------------------===//
497 // BlockInfo Block Emission
498 //===--------------------------------------------------------------------===//
499
500 /// EnterBlockInfoBlock - Start emitting the BLOCKINFO_BLOCK.
501 void EnterBlockInfoBlock() {
502 EnterSubblock(bitc::BLOCKINFO_BLOCK_ID, 2);
503 BlockInfoCurBID = ~0U;
504 BlockInfoRecords.clear();
505 }
506 private:
507 /// SwitchToBlockID - If we aren't already talking about the specified block
508 /// ID, emit a BLOCKINFO_CODE_SETBID record.
509 void SwitchToBlockID(unsigned BlockID) {
510 if (BlockInfoCurBID == BlockID) return;
511 SmallVector V;
512 V.push_back(BlockID);
513 EmitRecord(bitc::BLOCKINFO_CODE_SETBID, V);
514 BlockInfoCurBID = BlockID;
515 }
516
517 BlockInfo &getOrCreateBlockInfo(unsigned BlockID) {
518 if (BlockInfo *BI = getBlockInfo(BlockID))
519 return *BI;
520
521 // Otherwise, add a new record.
522 BlockInfoRecords.emplace_back();
523 BlockInfoRecords.back().BlockID = BlockID;
524 return BlockInfoRecords.back();
525 }
526
527 public:
528
529 /// EmitBlockInfoAbbrev - Emit a DEFINE_ABBREV record for the specified
530 /// BlockID.
531 unsigned EmitBlockInfoAbbrev(unsigned BlockID, std::shared_ptr Abbv) {
532 SwitchToBlockID(BlockID);
533 EncodeAbbrev(*Abbv);
534
535 // Add the abbrev to the specified block record.
536 BlockInfo &Info = getOrCreateBlockInfo(BlockID);
537 Info.Abbrevs.push_back(std::move(Abbv));
538
539 return Info.Abbrevs.size()-1+bitc::FIRST_APPLICATION_ABBREV;
540 }
541 };
542
543
544 } // End llvm namespace
545
546 #endif
1616 #ifndef LLVM_BITCODE_LLVMBITCODES_H
1717 #define LLVM_BITCODE_LLVMBITCODES_H
1818
19 #include "llvm/Bitcode/BitCodes.h"
19 #include "llvm/Bitstream/BitCodes.h"
2020
2121 namespace llvm {
2222 namespace bitc {
0 //===- BitCodes.h - Enum values for the bitstream format --------*- C++ -*-===//
1 //
2 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
3 // See https://llvm.org/LICENSE.txt for license information.
4 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
5 //
6 //===----------------------------------------------------------------------===//
7 //
8 // This header defines bitstream enum values.
9 //
10 // The enum values defined in this file should be considered permanent. If
11 // new features are added, they should have values added at the end of the
12 // respective lists.
13 //
14 //===----------------------------------------------------------------------===//
15
16 #ifndef LLVM_BITSTREAM_BITCODES_H
17 #define LLVM_BITSTREAM_BITCODES_H
18
19 #include "llvm/ADT/SmallVector.h"
20 #include "llvm/Support/DataTypes.h"
21 #include "llvm/Support/ErrorHandling.h"
22 #include
23
24 namespace llvm {
25 /// Offsets of the 32-bit fields of bitstream wrapper header.
26 static const unsigned BWH_MagicField = 0 * 4;
27 static const unsigned BWH_VersionField = 1 * 4;
28 static const unsigned BWH_OffsetField = 2 * 4;
29 static const unsigned BWH_SizeField = 3 * 4;
30 static const unsigned BWH_CPUTypeField = 4 * 4;
31 static const unsigned BWH_HeaderSize = 5 * 4;
32
33 namespace bitc {
34 enum StandardWidths {
35 BlockIDWidth = 8, // We use VBR-8 for block IDs.
36 CodeLenWidth = 4, // Codelen are VBR-4.
37 BlockSizeWidth = 32 // BlockSize up to 2^32 32-bit words = 16GB per block.
38 };
39
40 // The standard abbrev namespace always has a way to exit a block, enter a
41 // nested block, define abbrevs, and define an unabbreviated record.
42 enum FixedAbbrevIDs {
43 END_BLOCK = 0, // Must be zero to guarantee termination for broken bitcode.
44 ENTER_SUBBLOCK = 1,
45
46 /// DEFINE_ABBREV - Defines an abbrev for the current block. It consists
47 /// of a vbr5 for # operand infos. Each operand info is emitted with a
48 /// single bit to indicate if it is a literal encoding. If so, the value is
49 /// emitted with a vbr8. If not, the encoding is emitted as 3 bits followed
50 /// by the info value as a vbr5 if needed.
51 DEFINE_ABBREV = 2,
52
53 // UNABBREV_RECORDs are emitted with a vbr6 for the record code, followed by
54 // a vbr6 for the # operands, followed by vbr6's for each operand.
55 UNABBREV_RECORD = 3,
56
57 // This is not a code, this is a marker for the first abbrev assignment.
58 FIRST_APPLICATION_ABBREV = 4
59 };
60
61 /// StandardBlockIDs - All bitcode files can optionally include a BLOCKINFO
62 /// block, which contains metadata about other blocks in the file.
63 enum StandardBlockIDs {
64 /// BLOCKINFO_BLOCK is used to define metadata about blocks, for example,
65 /// standard abbrevs that should be available to all blocks of a specified
66 /// ID.
67 BLOCKINFO_BLOCK_ID = 0,
68
69 // Block IDs 1-7 are reserved for future expansion.
70 FIRST_APPLICATION_BLOCKID = 8
71 };
72
73 /// BlockInfoCodes - The blockinfo block contains metadata about user-defined
74 /// blocks.
75 enum BlockInfoCodes {
76 // DEFINE_ABBREV has magic semantics here, applying to the current SETBID'd
77 // block, instead of the BlockInfo block.
78
79 BLOCKINFO_CODE_SETBID = 1, // SETBID: [blockid#]
80 BLOCKINFO_CODE_BLOCKNAME = 2, // BLOCKNAME: [name]
81 BLOCKINFO_CODE_SETRECORDNAME = 3 // BLOCKINFO_CODE_SETRECORDNAME:
82 // [id, name]
83 };
84
85 } // End bitc namespace
86
87 /// BitCodeAbbrevOp - This describes one or more operands in an abbreviation.
88 /// This is actually a union of two different things:
89 /// 1. It could be a literal integer value ("the operand is always 17").
90 /// 2. It could be an encoding specification ("this operand encoded like so").
91 ///
92 class BitCodeAbbrevOp {
93 uint64_t Val; // A literal value or data for an encoding.
94 bool IsLiteral : 1; // Indicate whether this is a literal value or not.
95 unsigned Enc : 3; // The encoding to use.
96 public:
97 enum Encoding {
98 Fixed = 1, // A fixed width field, Val specifies number of bits.
99 VBR = 2, // A VBR field where Val specifies the width of each chunk.
100 Array = 3, // A sequence of fields, next field species elt encoding.
101 Char6 = 4, // A 6-bit fixed field which maps to [a-zA-Z0-9._].
102 Blob = 5 // 32-bit aligned array of 8-bit characters.
103 };
104
105 explicit BitCodeAbbrevOp(uint64_t V) : Val(V), IsLiteral(true) {}
106 explicit BitCodeAbbrevOp(Encoding E, uint64_t Data = 0)
107 : Val(Data), IsLiteral(false), Enc(E) {}
108
109 bool isLiteral() const { return IsLiteral; }
110 bool isEncoding() const { return !IsLiteral; }
111
112 // Accessors for literals.
113 uint64_t getLiteralValue() const { assert(isLiteral()); return Val; }
114
115 // Accessors for encoding info.
116 Encoding getEncoding() const { assert(isEncoding()); return (Encoding)Enc; }
117 uint64_t getEncodingData() const {
118 assert(isEncoding() && hasEncodingData());
119 return Val;
120 }
121
122 bool hasEncodingData() const { return hasEncodingData(getEncoding()); }
123 static bool hasEncodingData(Encoding E) {
124 switch (E) {
125 case Fixed:
126 case VBR:
127 return true;
128 case Array:
129 case Char6:
130 case Blob:
131 return false;
132 }
133 report_fatal_error("Invalid encoding");
134 }
135
136 /// isChar6 - Return true if this character is legal in the Char6 encoding.
137 static bool isChar6(char C) {
138 if (C >= 'a' && C <= 'z') return true;
139 if (C >= 'A' && C <= 'Z') return true;
140 if (C >= '0' && C <= '9') return true;
141 if (C == '.' || C == '_') return true;
142 return false;
143 }
144 static unsigned EncodeChar6(char C) {
145 if (C >= 'a' && C <= 'z') return C-'a';
146 if (C >= 'A' && C <= 'Z') return C-'A'+26;
147 if (C >= '0' && C <= '9') return C-'0'+26+26;
148 if (C == '.') return 62;
149 if (C == '_') return 63;
150 llvm_unreachable("Not a value Char6 character!");
151 }
152
153 static char DecodeChar6(unsigned V) {
154 assert((V & ~63) == 0 && "Not a Char6 encoded character!");
155 return "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789._"
156 [V];
157 }
158
159 };
160
161 /// BitCodeAbbrev - This class represents an abbreviation record. An
162 /// abbreviation allows a complex record that has redundancy to be stored in a
163 /// specialized format instead of the fully-general, fully-vbr, format.
164 class BitCodeAbbrev {
165 SmallVector OperandList;
166
167 public:
168 unsigned getNumOperandInfos() const {
169 return static_cast(OperandList.size());
170 }
171 const BitCodeAbbrevOp &getOperandInfo(unsigned N) const {
172 return OperandList[N];
173 }
174
175 void Add(const BitCodeAbbrevOp &OpInfo) {
176 OperandList.push_back(OpInfo);
177 }
178 };
179 } // End llvm namespace
180
181 #endif
0 //===- BitstreamReader.h - Low-level bitstream reader interface -*- C++ -*-===//
1 //
2 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
3 // See https://llvm.org/LICENSE.txt for license information.
4 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
5 //
6 //===----------------------------------------------------------------------===//
7 //
8 // This header defines the BitstreamReader class. This class can be used to
9 // read an arbitrary bitstream, regardless of its contents.
10 //
11 //===----------------------------------------------------------------------===//
12
13 #ifndef LLVM_BITSTREAM_BITSTREAMREADER_H
14 #define LLVM_BITSTREAM_BITSTREAMREADER_H
15
16 #include "llvm/ADT/ArrayRef.h"
17 #include "llvm/ADT/SmallVector.h"
18 #include "llvm/Bitstream/BitCodes.h"
19 #include "llvm/Support/Endian.h"
20 #include "llvm/Support/ErrorHandling.h"
21 #include "llvm/Support/MathExtras.h"
22 #include "llvm/Support/MemoryBuffer.h"
23 #include
24 #include
25 #include
26 #include
27 #include
28 #include
29 #include
30 #include
31 #include
32
33 namespace llvm {
34
35 /// This class maintains the abbreviations read from a block info block.
36 class BitstreamBlockInfo {
37 public:
38 /// This contains information emitted to BLOCKINFO_BLOCK blocks. These
39 /// describe abbreviations that all blocks of the specified ID inherit.
40 struct BlockInfo {
41 unsigned BlockID;
42 std::vector> Abbrevs;
43 std::string Name;
44 std::vector> RecordNames;
45 };
46
47 private:
48 std::vector BlockInfoRecords;
49
50 public:
51 /// If there is block info for the specified ID, return it, otherwise return
52 /// null.
53 const BlockInfo *getBlockInfo(unsigned BlockID) const {
54 // Common case, the most recent entry matches BlockID.
55 if (!BlockInfoRecords.empty() && BlockInfoRecords.back().BlockID == BlockID)
56 return &BlockInfoRecords.back();
57
58 for (unsigned i = 0, e = static_cast(BlockInfoRecords.size());
59 i != e; ++i)
60 if (BlockInfoRecords[i].BlockID == BlockID)
61 return &BlockInfoRecords[i];
62 return nullptr;
63 }
64
65 BlockInfo &getOrCreateBlockInfo(unsigned BlockID) {
66 if (const BlockInfo *BI = getBlockInfo(BlockID))
67 return *const_cast(BI);
68
69 // Otherwise, add a new record.
70 BlockInfoRecords.emplace_back();
71 BlockInfoRecords.back().BlockID = BlockID;
72 return BlockInfoRecords.back();
73 }
74 };
75
76 /// This represents a position within a bitstream. There may be multiple
77 /// independent cursors reading within one bitstream, each maintaining their
78 /// own local state.
79 class SimpleBitstreamCursor {
80 ArrayRef BitcodeBytes;
81 size_t NextChar = 0;
82
83 public:
84 /// This is the current data we have pulled from the stream but have not
85 /// returned to the client. This is specifically and intentionally defined to
86 /// follow the word size of the host machine for efficiency. We use word_t in
87 /// places that are aware of this to make it perfectly explicit what is going
88 /// on.
89 using word_t = size_t;
90
91 private:
92 word_t CurWord = 0;
93
94 /// This is the number of bits in CurWord that are valid. This is always from
95 /// [0...bits_of(size_t)-1] inclusive.
96 unsigned BitsInCurWord = 0;
97
98 public:
99 static const constexpr size_t MaxChunkSize = sizeof(word_t) * 8;
100
101 SimpleBitstreamCursor() = default;
102 explicit SimpleBitstreamCursor(ArrayRef BitcodeBytes)
103 : BitcodeBytes(BitcodeBytes) {}
104 explicit SimpleBitstreamCursor(StringRef BitcodeBytes)
105 : BitcodeBytes(arrayRefFromStringRef(BitcodeBytes)) {}
106 explicit SimpleBitstreamCursor(MemoryBufferRef BitcodeBytes)
107 : SimpleBitstreamCursor(BitcodeBytes.getBuffer()) {}
108
109 bool canSkipToPos(size_t pos) const {
110 // pos can be skipped to if it is a valid address or one byte past the end.
111 return pos <= BitcodeBytes.size();
112 }
113
114 bool AtEndOfStream() {
115 return BitsInCurWord == 0 && BitcodeBytes.size() <= NextChar;
116 }
117
118 /// Return the bit # of the bit we are reading.
119 uint64_t GetCurrentBitNo() const {
120 return NextChar*CHAR_BIT - BitsInCurWord;
121 }
122
123 // Return the byte # of the current bit.
124 uint64_t getCurrentByteNo() const { return GetCurrentBitNo() / 8; }
125
126 ArrayRef getBitcodeBytes() const { return BitcodeBytes; }
127
128 /// Reset the stream to the specified bit number.
129 Error JumpToBit(uint64_t BitNo) {
130 size_t ByteNo = size_t(BitNo/8) & ~(sizeof(word_t)-1);
131 unsigned WordBitNo = unsigned(BitNo & (sizeof(word_t)*8-1));
132 assert(canSkipToPos(ByteNo) && "Invalid location");
133
134 // Move the cursor to the right word.
135 NextChar = ByteNo;
136 BitsInCurWord = 0;
137
138 // Skip over any bits that are already consumed.
139 if (WordBitNo) {
140 if (Expected Res = Read(WordBitNo))
141 return Error::success();
142 else
143 return Res.takeError();
144 }
145
146 return Error::success();
147 }
148
149 /// Get a pointer into the bitstream at the specified byte offset.
150 const uint8_t *getPointerToByte(uint64_t ByteNo, uint64_t NumBytes) {
151 return BitcodeBytes.data() + ByteNo;
152 }
153
154 /// Get a pointer into the bitstream at the specified bit offset.
155 ///
156 /// The bit offset must be on a byte boundary.
157 const uint8_t *getPointerToBit(uint64_t BitNo, uint64_t NumBytes) {
158 assert(!(BitNo % 8) && "Expected bit on byte boundary");
159 return getPointerToByte(BitNo / 8, NumBytes);
160 }
161
162 Error fillCurWord() {
163 if (NextChar >= BitcodeBytes.size())
164 return createStringError(std::errc::io_error,
165 "Unexpected end of file reading %u of %u bytes",
166 NextChar, BitcodeBytes.size());
167
168 // Read the next word from the stream.
169 const uint8_t *NextCharPtr = BitcodeBytes.data() + NextChar;
170 unsigned BytesRead;
171 if (BitcodeBytes.size() >= NextChar + sizeof(word_t)) {
172 BytesRead = sizeof(word_t);
173 CurWord =
174 support::endian::read(
175 NextCharPtr);
176 } else {
177 // Short read.
178 BytesRead = BitcodeBytes.size() - NextChar;
179 CurWord = 0;
180 for (unsigned B = 0; B != BytesRead; ++B)
181 CurWord |= uint64_t(NextCharPtr[B]) << (B * 8);
182 }
183 NextChar += BytesRead;
184 BitsInCurWord = BytesRead * 8;
185 return Error::success();
186 }
187
188 Expected Read(unsigned NumBits) {
189 static const unsigned BitsInWord = MaxChunkSize;
190
191 assert(NumBits && NumBits <= BitsInWord &&
192 "Cannot return zero or more than BitsInWord bits!");
193
194 static const unsigned Mask = sizeof(word_t) > 4 ? 0x3f : 0x1f;
195
196 // If the field is fully contained by CurWord, return it quickly.
197 if (BitsInCurWord >= NumBits) {
198 word_t R = CurWord & (~word_t(0) >> (BitsInWord - NumBits));
199
200 // Use a mask to avoid undefined behavior.
201 CurWord >>= (NumBits & Mask);
202
203 BitsInCurWord -= NumBits;
204 return R;
205 }
206
207 word_t R = BitsInCurWord ? CurWord : 0;
208 unsigned BitsLeft = NumBits - BitsInCurWord;
209
210 if (Error fillResult = fillCurWord())
211 return std::move(fillResult);
212
213 // If we run out of data, abort.
214 if (BitsLeft > BitsInCurWord)
215 return createStringError(std::errc::io_error,
216 "Unexpected end of file reading %u of %u bits",
217 BitsInCurWord, BitsLeft);
218
219 word_t R2 = CurWord & (~word_t(0) >> (BitsInWord - BitsLeft));
220
221 // Use a mask to avoid undefined behavior.
222 CurWord >>= (BitsLeft & Mask);
223
224 BitsInCurWord -= BitsLeft;
225
226 R |= R2 << (NumBits - BitsLeft);
227
228 return R;
229 }
230
231 Expected ReadVBR(unsigned NumBits) {
232 Expected MaybeRead = Read(NumBits);
233 if (!MaybeRead)
234 return MaybeRead;
235 uint32_t Piece = MaybeRead.get();
236
237 if ((Piece & (1U << (NumBits-1))) == 0)
238 return Piece;
239
240 uint32_t Result = 0;
241 unsigned NextBit = 0;
242 while (true) {
243 Result |= (Piece & ((1U << (NumBits-1))-1)) << NextBit;
244
245 if ((Piece & (1U << (NumBits-1))) == 0)
246 return Result;
247
248 NextBit += NumBits-1;
249 MaybeRead = Read(NumBits);
250 if (!MaybeRead)
251 return MaybeRead;
252 Piece = MaybeRead.get();
253 }
254 }
255
256 // Read a VBR that may have a value up to 64-bits in size. The chunk size of
257 // the VBR must still be <= 32 bits though.
258 Expected ReadVBR64(unsigned NumBits) {
259 Expected MaybeRead = Read(NumBits);
260 if (!MaybeRead)
261 return MaybeRead;
262 uint32_t Piece = MaybeRead.get();
263
264 if ((Piece & (1U << (NumBits-1))) == 0)
265 return uint64_t(Piece);
266
267 uint64_t Result = 0;
268 unsigned NextBit = 0;
269 while (true) {
270 Result |= uint64_t(Piece & ((1U << (NumBits-1))-1)) << NextBit;
271
272 if ((Piece & (1U << (NumBits-1))) == 0)
273 return Result;
274
275 NextBit += NumBits-1;
276 MaybeRead = Read(NumBits);
277 if (!MaybeRead)
278 return MaybeRead;
279 Piece = MaybeRead.get();
280 }
281 }
282
283 void SkipToFourByteBoundary() {
284 // If word_t is 64-bits and if we've read less than 32 bits, just dump
285 // the bits we have up to the next 32-bit boundary.
286 if (sizeof(word_t) > 4 &&
287 BitsInCurWord >= 32) {
288 CurWord >>= BitsInCurWord-32;
289 BitsInCurWord = 32;
290 return;
291 }
292
293 BitsInCurWord = 0;
294 }
295
296 /// Skip to the end of the file.
297 void skipToEnd() { NextChar = BitcodeBytes.size(); }
298 };
299
300 /// When advancing through a bitstream cursor, each advance can discover a few
301 /// different kinds of entries:
302 struct BitstreamEntry {
303 enum {
304 Error, // Malformed bitcode was found.
305 EndBlock, // We've reached the end of the current block, (or the end of the
306 // file, which is treated like a series of EndBlock records.
307 SubBlock, // This is the start of a new subblock of a specific ID.
308 Record // This is a record with a specific AbbrevID.
309 } Kind;
310
311 unsigned ID;
312
313 static BitstreamEntry getError() {
314 BitstreamEntry E; E.Kind = Error; return E;
315 }
316
317 static BitstreamEntry getEndBlock() {
318 BitstreamEntry E; E.Kind = EndBlock; return E;
319 }
320
321 static BitstreamEntry getSubBlock(unsigned ID) {
322 BitstreamEntry E; E.Kind = SubBlock; E.ID = ID; return E;
323 }
324
325 static BitstreamEntry getRecord(unsigned AbbrevID) {
326 BitstreamEntry E; E.Kind = Record; E.ID = AbbrevID; return E;
327 }
328 };
329
330 /// This represents a position within a bitcode file, implemented on top of a
331 /// SimpleBitstreamCursor.
332 ///
333 /// Unlike iterators, BitstreamCursors are heavy-weight objects that should not
334 /// be passed by value.
335 class BitstreamCursor : SimpleBitstreamCursor {
336 // This is the declared size of code values used for the current block, in
337 // bits.
338 unsigned CurCodeSize = 2;
339
340 /// Abbrevs installed at in this block.
341 std::vector> CurAbbrevs;
342
343 struct Block {
344 unsigned PrevCodeSize;
345 std::vector> PrevAbbrevs;
346
347 explicit Block(unsigned PCS) : PrevCodeSize(PCS) {}
348 };
349
350 /// This tracks the codesize of parent blocks.
351 SmallVector BlockScope;
352
353 BitstreamBlockInfo *BlockInfo = nullptr;
354
355 public:
356 static const size_t MaxChunkSize = sizeof(word_t) * 8;
357
358 BitstreamCursor() = default;
359 explicit BitstreamCursor(ArrayRef BitcodeBytes)
360 : SimpleBitstreamCursor(BitcodeBytes) {}
361 explicit BitstreamCursor(StringRef BitcodeBytes)
362 : SimpleBitstreamCursor(BitcodeBytes) {}
363 explicit BitstreamCursor(MemoryBufferRef BitcodeBytes)
364 : SimpleBitstreamCursor(BitcodeBytes) {}
365
366 using SimpleBitstreamCursor::canSkipToPos;
367 using SimpleBitstreamCursor::AtEndOfStream;
368 using SimpleBitstreamCursor::getBitcodeBytes;
369 using SimpleBitstreamCursor::GetCurrentBitNo;
370 using SimpleBitstreamCursor::getCurrentByteNo;
371 using SimpleBitstreamCursor::getPointerToByte;
372 using SimpleBitstreamCursor::JumpToBit;
373 using SimpleBitstreamCursor::fillCurWord;
374 using SimpleBitstreamCursor::Read;
375 using SimpleBitstreamCursor::ReadVBR;
376 using SimpleBitstreamCursor::ReadVBR64;
377
378 /// Return the number of bits used to encode an abbrev #.
379 unsigned getAbbrevIDWidth() const { return CurCodeSize; }
380
381 /// Flags that modify the behavior of advance().
382 enum {
383 /// If this flag is used, the advance() method does not automatically pop
384 /// the block scope when the end of a block is reached.
385 AF_DontPopBlockAtEnd = 1,
386
387 /// If this flag is used, abbrev entries are returned just like normal
388 /// records.
389 AF_DontAutoprocessAbbrevs = 2
390 };
391
392 /// Advance the current bitstream, returning the next entry in the stream.
393 Expected advance(unsigned Flags = 0) {
394 while (true) {
395 if (AtEndOfStream())
396 return BitstreamEntry::getError();
397
398 Expected MaybeCode = ReadCode();
399 if (!MaybeCode)
400 return MaybeCode.takeError();
401 unsigned Code = MaybeCode.get();
402
403 if (Code == bitc::END_BLOCK) {
404 // Pop the end of the block unless Flags tells us not to.
405 if (!(Flags & AF_DontPopBlockAtEnd) && ReadBlockEnd())
406 return BitstreamEntry::getError();
407 return BitstreamEntry::getEndBlock();
408 }
409
410 if (Code == bitc::ENTER_SUBBLOCK) {
411 if (Expected MaybeSubBlock = ReadSubBlockID())
412 return BitstreamEntry::getSubBlock(MaybeSubBlock.get());
413 else
414 return MaybeSubBlock.takeError();
415 }
416
417 if (Code == bitc::DEFINE_ABBREV &&
418 !(Flags & AF_DontAutoprocessAbbrevs)) {
419 // We read and accumulate abbrev's, the client can't do anything with
420 // them anyway.
421 if (Error Err = ReadAbbrevRecord())
422 return std::move(Err);
423 continue;
424 }
425
426 return BitstreamEntry::getRecord(Code);
427 }
428 }
429
430 /// This is a convenience function for clients that don't expect any
431 /// subblocks. This just skips over them automatically.
432 Expected advanceSkippingSubblocks(unsigned Flags = 0) {
433 while (true) {
434 // If we found a normal entry, return it.
435 Expected MaybeEntry = advance(Flags);
436 if (!MaybeEntry)
437 return MaybeEntry;
438 BitstreamEntry Entry = MaybeEntry.get();
439
440 if (Entry.Kind != BitstreamEntry::SubBlock)
441 return Entry;
442
443 // If we found a sub-block, just skip over it and check the next entry.
444 if (Error Err = SkipBlock())
445 return std::move(Err);
446 }
447 }
448
449 Expected ReadCode() { return Read(CurCodeSize); }
450
451 // Block header:
452 // [ENTER_SUBBLOCK, blockid, newcodelen, , blocklen]
453
454 /// Having read the ENTER_SUBBLOCK code, read the BlockID for the block.
455 Expected ReadSubBlockID() { return ReadVBR(bitc::BlockIDWidth); }
456
457 /// Having read the ENTER_SUBBLOCK abbrevid and a BlockID, skip over the body
458 /// of this block.
459 Error SkipBlock() {
460 // Read and ignore the codelen value.
461 if (Expected Res = ReadVBR(bitc::CodeLenWidth))
462 ; // Since we are skipping this block, we don't care what code widths are
463 // used inside of it.
464 else
465 return Res.takeError();
466
467 SkipToFourByteBoundary();
468 Expected MaybeNum = Read(bitc::BlockSizeWidth);
469 if (!MaybeNum)
470 return MaybeNum.takeError();
471 size_t NumFourBytes = MaybeNum.get();
472
473 // Check that the block wasn't partially defined, and that the offset isn't
474 // bogus.
475 size_t SkipTo = GetCurrentBitNo() + NumFourBytes * 4 * 8;
476 if (AtEndOfStream())
477 return createStringError(std::errc::illegal_byte_sequence,
478 "can't skip block: already at end of stream");
479 if (!canSkipToPos(SkipTo / 8))
480 return createStringError(std::errc::illegal_byte_sequence,
481 "can't skip to bit %zu from %" PRIu64, SkipTo,
482 GetCurrentBitNo());
483
484 if (Error Res = JumpToBit(SkipTo))
485 return Res;
486
487 return Error::success();
488 }
489
490 /// Having read the ENTER_SUBBLOCK abbrevid, and enter the block.
491 Error EnterSubBlock(unsigned BlockID, unsigned *NumWordsP = nullptr);
492
493 bool ReadBlockEnd() {
494 if (BlockScope.empty()) return true;
495
496 // Block tail:
497 // [END_BLOCK, ]
498 SkipToFourByteBoundary();
499
500 popBlockScope();
501 return false;
502 }
503
504 private:
505 void popBlockScope() {
506 CurCodeSize = BlockScope.back().PrevCodeSize;
507
508 CurAbbrevs = std::move(BlockScope.back().PrevAbbrevs);
509 BlockScope.pop_back();
510 }
511
512 //===--------------------------------------------------------------------===//
513 // Record Processing
514 //===--------------------------------------------------------------------===//
515
516 public:
517 /// Return the abbreviation for the specified AbbrevId.
518 const BitCodeAbbrev *getAbbrev(unsigned AbbrevID) {
519 unsigned AbbrevNo = AbbrevID - bitc::FIRST_APPLICATION_ABBREV;
520 if (AbbrevNo >= CurAbbrevs.size())
521 report_fatal_error("Invalid abbrev number");
522 return CurAbbrevs[AbbrevNo].get();
523 }
524
525 /// Read the current record and discard it, returning the code for the record.
526 Expected skipRecord(unsigned AbbrevID);
527
528 Expected readRecord(unsigned AbbrevID,
529 SmallVectorImpl &Vals,
530 StringRef *Blob = nullptr);
531
532 //===--------------------------------------------------------------------===//
533 // Abbrev Processing
534 //===--------------------------------------------------------------------===//
535 Error ReadAbbrevRecord();
536
537 /// Read and return a block info block from the bitstream. If an error was
538 /// encountered, return None.
539 ///
540 /// \param ReadBlockInfoNames Whether to read block/record name information in
541 /// the BlockInfo block. Only llvm-bcanalyzer uses this.
542 Expected>
543 ReadBlockInfoBlock(bool ReadBlockInfoNames = false);
544
545 /// Set the block info to be used by this BitstreamCursor to interpret
546 /// abbreviated records.
547 void setBlockInfo(BitstreamBlockInfo *BI) { BlockInfo = BI; }
548 };
549
550 } // end llvm namespace
551
552 #endif // LLVM_BITSTREAM_BITSTREAMREADER_H
0 //===- BitstreamWriter.h - Low-level bitstream writer interface -*- C++ -*-===//
1 //
2 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
3 // See https://llvm.org/LICENSE.txt for license information.
4 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
5 //
6 //===----------------------------------------------------------------------===//
7 //
8 // This header defines the BitstreamWriter class. This class can be used to
9 // write an arbitrary bitstream, regardless of its contents.
10 //
11 //===----------------------------------------------------------------------===//
12
13 #ifndef LLVM_BITSTREAM_BITSTREAMWRITER_H
14 #define LLVM_BITSTREAM_BITSTREAMWRITER_H
15
16 #include "llvm/ADT/ArrayRef.h"
17 #include "llvm/ADT/Optional.h"
18 #include "llvm/ADT/SmallVector.h"
19 #include "llvm/ADT/StringRef.h"
20 #include "llvm/Bitstream/BitCodes.h"
21 #include "llvm/Support/Endian.h"
22 #include
23
24 namespace llvm {
25
26 class BitstreamWriter {
27 SmallVectorImpl &Out;
28
29 /// CurBit - Always between 0 and 31 inclusive, specifies the next bit to use.
30 unsigned CurBit;
31
32 /// CurValue - The current value. Only bits < CurBit are valid.
33 uint32_t CurValue;
34
35 /// CurCodeSize - This is the declared size of code values used for the
36 /// current block, in bits.
37 unsigned CurCodeSize;
38
39 /// BlockInfoCurBID - When emitting a BLOCKINFO_BLOCK, this is the currently
40 /// selected BLOCK ID.
41 unsigned BlockInfoCurBID;
42
43 /// CurAbbrevs - Abbrevs installed at in this block.
44 std::vector> CurAbbrevs;
45
46 struct Block {
47 unsigned PrevCodeSize;
48 size_t StartSizeWord;
49 std::vector> PrevAbbrevs;
50 Block(unsigned PCS, size_t SSW) : PrevCodeSize(PCS), StartSizeWord(SSW) {}
51 };
52
53 /// BlockScope - This tracks the current blocks that we have entered.
54 std::vector BlockScope;
55
56 /// BlockInfo - This contains information emitted to BLOCKINFO_BLOCK blocks.
57 /// These describe abbreviations that all blocks of the specified ID inherit.
58 struct BlockInfo {
59 unsigned BlockID;
60 std::vector> Abbrevs;
61 };
62 std::vector BlockInfoRecords;
63
64 void WriteByte(unsigned char Value) {
65 Out.push_back(Value);
66 }
67
68 void WriteWord(unsigned Value) {
69 Value = support::endian::byte_swap(Value);
70 Out.append(reinterpret_cast(&Value),
71 reinterpret_cast(&Value + 1));
72 }
73
74 size_t GetBufferOffset() const { return Out.size(); }
75
76 size_t GetWordIndex() const {
77 size_t Offset = GetBufferOffset();
78 assert((Offset & 3) == 0 && "Not 32-bit aligned");
79 return Offset / 4;
80 }
81
82 public:
83 explicit BitstreamWriter(SmallVectorImpl &O)
84 : Out(O), CurBit(0), CurValue(0), CurCodeSize(2) {}
85
86 ~BitstreamWriter() {
87 assert(CurBit == 0 && "Unflushed data remaining");
88 assert(BlockScope.empty() && CurAbbrevs.empty() && "Block imbalance");
89 }
90
91 /// Retrieve the current position in the stream, in bits.
92 uint64_t GetCurrentBitNo() const { return GetBufferOffset() * 8 + CurBit; }
93
94 /// Retrieve the number of bits currently used to encode an abbrev ID.
95 unsigned GetAbbrevIDWidth() const { return CurCodeSize; }
96
97 //===--------------------------------------------------------------------===//
98 // Basic Primitives for emitting bits to the stream.
99 //===--------------------------------------------------------------------===//
100
101 /// Backpatch a 32-bit word in the output at the given bit offset
102 /// with the specified value.
103 void BackpatchWord(uint64_t BitNo, unsigned NewWord) {
104 using namespace llvm::support;
105 unsigned ByteNo = BitNo / 8;
106 assert((!endian::readAtBitAlignment(
107 &Out[ByteNo], BitNo & 7)) &&
108 "Expected to be patching over 0-value placeholders");
109 endian::writeAtBitAlignment(
110 &Out[ByteNo], NewWord, BitNo & 7);
111 }
112
113 void BackpatchWord64(uint64_t BitNo, uint64_t Val) {
114 BackpatchWord(BitNo, (uint32_t)Val);
115 BackpatchWord(BitNo + 32, (uint32_t)(Val >> 32));
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 FlushToWord() {
138 if (CurBit) {
139 WriteWord(CurValue);
140 CurBit = 0;
141 CurValue = 0;
142 }
143 }
144
145 void EmitVBR(uint32_t Val, unsigned NumBits) {
146 assert(NumBits <= 32 && "Too many bits to emit!");
147 uint32_t Threshold = 1U << (NumBits-1);
148
149 // Emit the bits with VBR encoding, NumBits-1 bits at a time.
150 while (Val >= Threshold) {
151 Emit((Val & ((1 << (NumBits-1))-1)) | (1 << (NumBits-1)), NumBits);
152 Val >>= NumBits-1;
153 }
154
155 Emit(Val, NumBits);
156 }
157
158 void EmitVBR64(uint64_t Val, unsigned NumBits) {
159 assert(NumBits <= 32 && "Too many bits to emit!");
160 if ((uint32_t)Val == Val)
161 return EmitVBR((uint32_t)Val, NumBits);
162
163 uint32_t Threshold = 1U << (NumBits-1);
164
165 // Emit the bits with VBR encoding, NumBits-1 bits at a time.
166 while (Val >= Threshold) {
167 Emit(((uint32_t)Val & ((1 << (NumBits-1))-1)) |
168 (1 << (NumBits-1)), NumBits);
169 Val >>= NumBits-1;
170 }
171
172 Emit((uint32_t)Val, NumBits);
173 }
174
175 /// EmitCode - Emit the specified code.
176 void EmitCode(unsigned Val) {
177 Emit(Val, CurCodeSize);
178 }
179
180 //===--------------------------------------------------------------------===//
181 // Block Manipulation
182 //===--------------------------------------------------------------------===//
183
184 /// getBlockInfo - If there is block info for the specified ID, return it,
185 /// otherwise return null.
186 BlockInfo *getBlockInfo(unsigned BlockID) {
187 // Common case, the most recent entry matches BlockID.
188 if (!BlockInfoRecords.empty() && BlockInfoRecords.back().BlockID == BlockID)
189 return &BlockInfoRecords.back();
190
191 for (unsigned i = 0, e = static_cast(BlockInfoRecords.size());
192 i != e; ++i)
193 if (BlockInfoRecords[i].BlockID == BlockID)
194 return &BlockInfoRecords[i];
195 return nullptr;
196 }
197
198 void EnterSubblock(unsigned BlockID, unsigned CodeLen) {
199 // Block header:
200 // [ENTER_SUBBLOCK, blockid, newcodelen, , blocklen]
201 EmitCode(bitc::ENTER_SUBBLOCK);
202 EmitVBR(BlockID, bitc::BlockIDWidth);
203 EmitVBR(CodeLen, bitc::CodeLenWidth);
204 FlushToWord();
205
206 size_t BlockSizeWordIndex = GetWordIndex();
207 unsigned OldCodeSize = CurCodeSize;
208
209 // Emit a placeholder, which will be replaced when the block is popped.
210 Emit(0, bitc::BlockSizeWidth);
211
212 CurCodeSize = CodeLen;
213
214 // Push the outer block's abbrev set onto the stack, start out with an
215 // empty abbrev set.
216 BlockScope.emplace_back(OldCodeSize, BlockSizeWordIndex);
217 BlockScope.back().PrevAbbrevs.swap(CurAbbrevs);
218
219 // If there is a blockinfo for this BlockID, add all the predefined abbrevs
220 // to the abbrev list.
221 if (BlockInfo *Info = getBlockInfo(BlockID)) {
222 CurAbbrevs.insert(CurAbbrevs.end(), Info->Abbrevs.begin(),
223 Info->Abbrevs.end());
224 }
225 }
226
227 void ExitBlock() {
228 assert(!BlockScope.empty() && "Block scope imbalance!");
229 const Block &B = BlockScope.back();
230
231 // Block tail:
232 // [END_BLOCK, ]
233 EmitCode(bitc::END_BLOCK);
234 FlushToWord();
235
236 // Compute the size of the block, in words, not counting the size field.
237 size_t SizeInWords = GetWordIndex() - B.StartSizeWord - 1;
238 uint64_t BitNo = uint64_t(B.StartSizeWord) * 32;
239
240 // Update the block size field in the header of this sub-block.
241 BackpatchWord(BitNo, SizeInWords);
242
243 // Restore the inner block's code size and abbrev table.
244 CurCodeSize = B.PrevCodeSize;
245 CurAbbrevs = std::move(B.PrevAbbrevs);
246 BlockScope.pop_back();
247 }
248
249 //===--------------------------------------------------------------------===//
250 // Record Emission
251 //===--------------------------------------------------------------------===//
252
253 private:
254 /// EmitAbbreviatedLiteral - Emit a literal value according to its abbrev
255 /// record. This is a no-op, since the abbrev specifies the literal to use.
256 template
257 void EmitAbbreviatedLiteral(const BitCodeAbbrevOp &Op, uintty V) {
258 assert(Op.isLiteral() && "Not a literal");
259 // If the abbrev specifies the literal value to use, don't emit
260 // anything.
261 assert(V == Op.getLiteralValue() &&
262 "Invalid abbrev for record!");
263 }
264
265 /// EmitAbbreviatedField - Emit a single scalar field value with the specified
266 /// encoding.
267 template
268 void EmitAbbreviatedField(const BitCodeAbbrevOp &Op, uintty V) {
269 assert(!Op.isLiteral() && "Literals should use EmitAbbreviatedLiteral!");
270
271 // Encode the value as we are commanded.
272 switch (Op.getEncoding()) {
273 default: llvm_unreachable("Unknown encoding!");
274 case BitCodeAbbrevOp::Fixed:
275 if (Op.getEncodingData())
276 Emit((unsigned)V, (unsigned)Op.getEncodingData());
277 break;
278 case BitCodeAbbrevOp::VBR:
279 if (Op.getEncodingData())
280 EmitVBR64(V, (unsigned)Op.getEncodingData());
281 break;
282 case BitCodeAbbrevOp::Char6:
283 Emit(BitCodeAbbrevOp::EncodeChar6((char)V), 6);
284 break;
285 }
286 }
287
288 /// EmitRecordWithAbbrevImpl - This is the core implementation of the record
289 /// emission code. If BlobData is non-null, then it specifies an array of
290 /// data that should be emitted as part of the Blob or Array operand that is
291 /// known to exist at the end of the record. If Code is specified, then
292 /// it is the record code to emit before the Vals, which must not contain
293 /// the code.
294 template
295 void EmitRecordWithAbbrevImpl(unsigned Abbrev, ArrayRef Vals,
296 StringRef Blob, Optional Code) {
297 const char *BlobData = Blob.data();
298 unsigned BlobLen = (unsigned) Blob.size();
299 unsigned AbbrevNo = Abbrev-bitc::FIRST_APPLICATION_ABBREV;
300 assert(AbbrevNo < CurAbbrevs.size() && "Invalid abbrev #!");
301 const BitCodeAbbrev *Abbv = CurAbbrevs[AbbrevNo].get();
302
303 EmitCode(Abbrev);
304
305 unsigned i = 0, e = static_cast(Abbv->getNumOperandInfos());
306 if (Code) {
307 assert(e && "Expected non-empty abbreviation");
308 const BitCodeAbbrevOp &Op = Abbv->getOperandInfo(i++);
309
310 if (Op.isLiteral())
311 EmitAbbreviatedLiteral(Op, Code.getValue());
312 else {
313 assert(Op.getEncoding() != BitCodeAbbrevOp::Array &&
314 Op.getEncoding() != BitCodeAbbrevOp::Blob &&
315 "Expected literal or scalar");
316 EmitAbbreviatedField(Op, Code.getValue());
317 }
318 }
319
320 unsigned RecordIdx = 0;
321 for (; 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(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 = nullptr;
346 } else {
347 // Emit a vbr6 to indicate the number of elements present.
348 EmitVBR(static_cast(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 if (BlobData) {
359 assert(RecordIdx == Vals.size() &&
360 "Blob data and record entries specified for blob operand!");
361
362 assert(Blob.data() == BlobData && "BlobData got moved");
363 assert(Blob.size() == BlobLen && "BlobLen got changed");
364 emitBlob(Blob);
365 BlobData = nullptr;
366 } else {
367 emitBlob(Vals.slice(RecordIdx));
368 }
369 } else { // Single scalar field.
370 assert(RecordIdx < Vals.size() && "Invalid abbrev/record");
371 EmitAbbreviatedField(Op, Vals[RecordIdx]);
372 ++RecordIdx;
373 }
374 }
375 assert(RecordIdx == Vals.size() && "Not all record operands emitted!");
376 assert(BlobData == nullptr &&
377 "Blob data specified for record that doesn't use it!");
378 }
379
380 public:
381 /// Emit a blob, including flushing before and tail-padding.
382 template
383 void emitBlob(ArrayRef Bytes, bool ShouldEmitSize = true) {
384 // Emit a vbr6 to indicate the number of elements present.
385 if (ShouldEmitSize)
386 EmitVBR(static_cast(Bytes.size()), 6);
387
388 // Flush to a 32-bit alignment boundary.
389 FlushToWord();
390
391 // Emit literal bytes.
392 for (const auto &B : Bytes) {
393 assert(isUInt<8>(B) && "Value too large to emit as byte");
394 WriteByte((unsigned char)B);
395 }
396
397 // Align end to 32-bits.
398 while (GetBufferOffset() & 3)
399 WriteByte(0);
400 }
401 void emitBlob(StringRef Bytes, bool ShouldEmitSize = true) {
402 emitBlob(makeArrayRef((const uint8_t *)Bytes.data(), Bytes.size()),
403 ShouldEmitSize);
404 }
405
406 /// EmitRecord - Emit the specified record to the stream, using an abbrev if
407 /// we have one to compress the output.
408 template
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(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
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
439 void EmitRecordWithBlob(unsigned Abbrev, const Container &Vals,
440 StringRef Blob) {
441 EmitRecordWithAbbrevImpl(Abbrev, makeArrayRef(Vals), Blob, None);
442 }
443 template
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
453 void EmitRecordWithArray(unsigned Abbrev, const Container &Vals,
454 StringRef Array) {
455 EmitRecordWithAbbrevImpl(Abbrev, makeArrayRef(Vals), Array, None);
456 }
457 template
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(const BitCodeAbbrev &Abbv) {
471 EmitCode(bitc::DEFINE_ABBREV);
472 EmitVBR(Abbv.getNumOperandInfos(), 5);
473 for (unsigned i = 0, e = static_cast(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 /// Emits the abbreviation \p Abbv to the stream.
489 unsigned EmitAbbrev(std::shared_ptr Abbv) {
490 EncodeAbbrev(*Abbv);
491 CurAbbrevs.push_back(std::move(Abbv));
492 return static_cast(CurAbbrevs.size())-1 +
493 bitc::FIRST_APPLICATION_ABBREV;
494 }
495
496 //===--------------------------------------------------------------------===//
497 // BlockInfo Block Emission
498 //===--------------------------------------------------------------------===//
499
500 /// EnterBlockInfoBlock - Start emitting the BLOCKINFO_BLOCK.
501 void EnterBlockInfoBlock() {
502 EnterSubblock(bitc::BLOCKINFO_BLOCK_ID, 2);
503 BlockInfoCurBID = ~0U;
504 BlockInfoRecords.clear();
505 }
506 private:
507 /// SwitchToBlockID - If we aren't already talking about the specified block
508 /// ID, emit a BLOCKINFO_CODE_SETBID record.
509 void SwitchToBlockID(unsigned BlockID) {
510 if (BlockInfoCurBID == BlockID) return;
511 SmallVector V;
512 V.push_back(BlockID);
513 EmitRecord(bitc::BLOCKINFO_CODE_SETBID, V);
514 BlockInfoCurBID = BlockID;
515 }
516
517 BlockInfo &getOrCreateBlockInfo(unsigned BlockID) {
518 if (BlockInfo *BI = getBlockInfo(BlockID))
519 return *BI;
520
521 // Otherwise, add a new record.
522 BlockInfoRecords.emplace_back();
523 BlockInfoRecords.back().BlockID = BlockID;
524 return BlockInfoRecords.back();
525 }
526
527 public:
528
529 /// EmitBlockInfoAbbrev - Emit a DEFINE_ABBREV record for the specified
530 /// BlockID.
531 unsigned EmitBlockInfoAbbrev(unsigned BlockID, std::shared_ptr Abbv) {
532 SwitchToBlockID(BlockID);
533 EncodeAbbrev(*Abbv);
534
535 // Add the abbrev to the specified block record.
536 BlockInfo &Info = getOrCreateBlockInfo(BlockID);
537 Info.Abbrevs.push_back(std::move(Abbv));
538
539 return Info.Abbrevs.size()-1+bitc::FIRST_APPLICATION_ABBREV;
540 }
541 };
542
543
544 } // End llvm namespace
545
546 #endif
3838 ///
3939 /// - LLVM bitstream is a space- and CPU- efficient binary format. Typically it
4040 /// encodes LLVM IR ("bitcode"), but it can be a container for other data.
41 /// Low-level reader/writer libraries are in Bitcode/Bitstream*.h
41 /// Low-level reader/writer libraries are in Bitstream/Bitstream*.h
4242 ///
4343 //===---------------------------------------------------------------------===//
4444
1919 #include "llvm/ADT/StringRef.h"
2020 #include "llvm/ADT/Triple.h"
2121 #include "llvm/ADT/Twine.h"
22 #include "llvm/Bitcode/BitstreamReader.h"
22 #include "llvm/Bitstream/BitstreamReader.h"
2323 #include "llvm/Bitcode/LLVMBitCodes.h"
2424 #include "llvm/Config/llvm-config.h"
2525 #include "llvm/IR/Argument.h"
+0
-510
lib/Bitcode/Reader/BitstreamReader.cpp less more
None //===- BitstreamReader.cpp - BitstreamReader implementation ---------------===//
1 //
2 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
3 // See https://llvm.org/LICENSE.txt for license information.
4 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
5 //
6 //===----------------------------------------------------------------------===//
7
8 #include "llvm/Bitcode/BitstreamReader.h"
9 #include "llvm/ADT/StringRef.h"
10 #include
11 #include
12
13 using namespace llvm;
14
15 //===----------------------------------------------------------------------===//
16 // BitstreamCursor implementation
17 //===----------------------------------------------------------------------===//
18
19 /// Having read the ENTER_SUBBLOCK abbrevid, enter the block.
20 Error BitstreamCursor::EnterSubBlock(unsigned BlockID, unsigned *NumWordsP) {
21 // Save the current block's state on BlockScope.
22 BlockScope.push_back(Block(CurCodeSize));
23 BlockScope.back().PrevAbbrevs.swap(CurAbbrevs);
24
25 // Add the abbrevs specific to this block to the CurAbbrevs list.
26 if (BlockInfo) {
27 if (const BitstreamBlockInfo::BlockInfo *Info =
28 BlockInfo->getBlockInfo(BlockID)) {
29 CurAbbrevs.insert(CurAbbrevs.end(), Info->Abbrevs.begin(),
30 Info->Abbrevs.end());
31 }
32 }
33
34 // Get the codesize of this block.
35 Expected MaybeVBR = ReadVBR(bitc::CodeLenWidth);
36 if (!MaybeVBR)
37 return MaybeVBR.takeError();
38 CurCodeSize = MaybeVBR.get();
39
40 if (CurCodeSize > MaxChunkSize)
41 return llvm::createStringError(
42 std::errc::illegal_byte_sequence,
43 "can't read more than %zu at a time, trying to read %u", +MaxChunkSize,
44 CurCodeSize);
45
46 SkipToFourByteBoundary();
47 Expected MaybeNum = Read(bitc::BlockSizeWidth);
48 if (!MaybeNum)
49 return MaybeNum.takeError();
50 word_t NumWords = MaybeNum.get();
51 if (NumWordsP)
52 *NumWordsP = NumWords;
53
54 if (CurCodeSize == 0)
55 return llvm::createStringError(
56 std::errc::illegal_byte_sequence,
57 "can't enter sub-block: current code size is 0");
58 if (AtEndOfStream())
59 return llvm::createStringError(
60 std::errc::illegal_byte_sequence,
61 "can't enter sub block: already at end of stream");
62
63 return Error::success();
64 }
65
66 static Expected readAbbreviatedField(BitstreamCursor &Cursor,
67 const BitCodeAbbrevOp &Op) {
68 assert(!Op.isLiteral() && "Not to be used with literals!");
69
70 // Decode the value as we are commanded.
71 switch (Op.getEncoding()) {
72 case BitCodeAbbrevOp::Array:
73 case BitCodeAbbrevOp::Blob:
74 llvm_unreachable("Should not reach here");
75 case BitCodeAbbrevOp::Fixed:
76 assert((unsigned)Op.getEncodingData() <= Cursor.MaxChunkSize);
77 return Cursor.Read((unsigned)Op.getEncodingData());
78 case BitCodeAbbrevOp::VBR:
79 assert((unsigned)Op.getEncodingData() <= Cursor.MaxChunkSize);
80 return Cursor.ReadVBR64((unsigned)Op.getEncodingData());
81 case BitCodeAbbrevOp::Char6:
82 if (Expected Res = Cursor.Read(6))
83 return BitCodeAbbrevOp::DecodeChar6(Res.get());
84 else
85 return Res.takeError();
86 }
87 llvm_unreachable("invalid abbreviation encoding");
88 }
89
90 static Error skipAbbreviatedField(BitstreamCursor &Cursor,
91 const BitCodeAbbrevOp &Op) {
92 assert(!Op.isLiteral() && "Not to be used with literals!");
93
94 // Decode the value as we are commanded.
95 switch (Op.getEncoding()) {
96 case BitCodeAbbrevOp::Array:
97 case BitCodeAbbrevOp::Blob:
98 llvm_unreachable("Should not reach here");
99 case BitCodeAbbrevOp::Fixed:
100 assert((unsigned)Op.getEncodingData() <= Cursor.MaxChunkSize);
101 if (Expected Res = Cursor.Read((unsigned)Op.getEncodingData()))
102 break;
103 else
104 return Res.takeError();
105 case BitCodeAbbrevOp::VBR:
106 assert((unsigned)Op.getEncodingData() <= Cursor.MaxChunkSize);
107 if (Expected Res =
108 Cursor.ReadVBR64((unsigned)Op.getEncodingData()))
109 break;
110 else
111 return Res.takeError();
112 case BitCodeAbbrevOp::Char6:
113 if (Expected Res = Cursor.Read(6))
114 break;
115 else
116 return Res.takeError();
117 }
118 return ErrorSuccess();
119 }
120
121 /// skipRecord - Read the current record and discard it.
122 Expected BitstreamCursor::skipRecord(unsigned AbbrevID) {
123 // Skip unabbreviated records by reading past their entries.
124 if (AbbrevID == bitc::UNABBREV_RECORD) {
125 Expected MaybeCode = ReadVBR(6);
126 if (!MaybeCode)
127 return MaybeCode.takeError();
128 unsigned Code = MaybeCode.get();
129 Expected MaybeVBR = ReadVBR(6);
130 if (!MaybeVBR)
131 return MaybeVBR.get();
132 unsigned NumElts = MaybeVBR.get();
133 for (unsigned i = 0; i != NumElts; ++i)
134 if (Expected Res = ReadVBR64(6))
135 ; // Skip!
136 else
137 return Res.takeError();
138 return Code;
139 }
140
141 const BitCodeAbbrev *Abbv = getAbbrev(AbbrevID);
142 const BitCodeAbbrevOp &CodeOp = Abbv->getOperandInfo(0);
143 unsigned Code;
144 if (CodeOp.isLiteral())
145 Code = CodeOp.getLiteralValue();
146 else {
147 if (CodeOp.getEncoding() == BitCodeAbbrevOp::Array ||
148 CodeOp.getEncoding() == BitCodeAbbrevOp::Blob)
149 return llvm::createStringError(
150 std::errc::illegal_byte_sequence,
151 "Abbreviation starts with an Array or a Blob");
152 Expected MaybeCode = readAbbreviatedField(*this, CodeOp);
153 if (!MaybeCode)
154 return MaybeCode.takeError();
155 Code = MaybeCode.get();
156 }
157
158 for (unsigned i = 1, e = Abbv->getNumOperandInfos(); i < e; ++i) {
159 const BitCodeAbbrevOp &Op = Abbv->getOperandInfo(i);
160 if (Op.isLiteral())
161 continue;
162
163 if (Op.getEncoding() != BitCodeAbbrevOp::Array &&
164 Op.getEncoding() != BitCodeAbbrevOp::Blob) {
165 if (Error Err = skipAbbreviatedField(*this, Op))
166 return std::move(Err);
167 continue;
168 }
169
170 if (Op.getEncoding() == BitCodeAbbrevOp::Array) {
171 // Array case. Read the number of elements as a vbr6.
172 Expected MaybeNum = ReadVBR(6);
173 if (!MaybeNum)
174 return MaybeNum.takeError();
175 unsigned NumElts = MaybeNum.get();
176
177 // Get the element encoding.
178 assert(i+2 == e && "array op not second to last?");
179 const BitCodeAbbrevOp &EltEnc = Abbv->getOperandInfo(++i);
180
181 // Read all the elements.
182 // Decode the value as we are commanded.
183 switch (EltEnc.getEncoding()) {
184 default:
185 report_fatal_error("Array element type can't be an Array or a Blob");
186 case BitCodeAbbrevOp::Fixed:
187 assert((unsigned)EltEnc.getEncodingData() <= MaxChunkSize);
188 if (Error Err = JumpToBit(GetCurrentBitNo() +
189 NumElts * EltEnc.getEncodingData()))
190 return std::move(Err);
191 break;
192 case BitCodeAbbrevOp::VBR:
193 assert((unsigned)EltEnc.getEncodingData() <= MaxChunkSize);
194 for (; NumElts; --NumElts)
195 if (Expected Res =
196 ReadVBR64((unsigned)EltEnc.getEncodingData()))
197 ; // Skip!
198 else
199 return Res.takeError();
200 break;
201 case BitCodeAbbrevOp::Char6:
202 if (Error Err = JumpToBit(GetCurrentBitNo() + NumElts * 6))
203 return std::move(Err);
204 break;
205 }
206 continue;
207 }
208
209 assert(Op.getEncoding() == BitCodeAbbrevOp::Blob);
210 // Blob case. Read the number of bytes as a vbr6.
211 Expected MaybeNum = ReadVBR(6);
212 if (!MaybeNum)
213 return MaybeNum.takeError();
214 unsigned NumElts = MaybeNum.get();
215 SkipToFourByteBoundary(); // 32-bit alignment
216
217 // Figure out where the end of this blob will be including tail padding.
218 size_t NewEnd = GetCurrentBitNo()+((NumElts+3)&~3)*8;
219
220 // If this would read off the end of the bitcode file, just set the
221 // record to empty and return.
222 if (!canSkipToPos(NewEnd/8)) {
223 skipToEnd();
224 break;
225 }
226
227 // Skip over the blob.
228 if (Error Err = JumpToBit(NewEnd))
229 return std::move(Err);
230 }
231 return Code;
232 }
233
234 Expected BitstreamCursor::readRecord(unsigned AbbrevID,
235 SmallVectorImpl &Vals,
236 StringRef *Blob) {
237 if (AbbrevID == bitc::UNABBREV_RECORD) {
238 Expected MaybeCode = ReadVBR(6);
239 if (!MaybeCode)
240 return MaybeCode.takeError();
241 uint32_t Code = MaybeCode.get();
242 Expected MaybeNumElts = ReadVBR(6);
243 if (!MaybeNumElts)
244 return MaybeNumElts.takeError();
245 uint32_t NumElts = MaybeNumElts.get();
246
247 for (unsigned i = 0; i != NumElts; ++i)
248 if (Expected MaybeVal = ReadVBR64(6))
249 Vals.push_back(MaybeVal.get());
250 else
251 return MaybeVal.takeError();
252 return Code;
253 }
254
255 const BitCodeAbbrev *Abbv = getAbbrev(AbbrevID);
256
257 // Read the record code first.
258 assert(Abbv->getNumOperandInfos() != 0 && "no record code in abbreviation?");
259 const BitCodeAbbrevOp &CodeOp = Abbv->getOperandInfo(0);
260 unsigned Code;
261 if (CodeOp.isLiteral())
262 Code = CodeOp.getLiteralValue();
263 else {
264 if (CodeOp.getEncoding() == BitCodeAbbrevOp::Array ||
265 CodeOp.getEncoding() == BitCodeAbbrevOp::Blob)
266 report_fatal_error("Abbreviation starts with an Array or a Blob");
267 if (Expected MaybeCode = readAbbreviatedField(*this, CodeOp))
268 Code = MaybeCode.get();
269 else
270 return MaybeCode.takeError();
271 }
272
273 for (unsigned i = 1, e = Abbv->getNumOperandInfos(); i != e; ++i) {
274 const BitCodeAbbrevOp &Op = Abbv->getOperandInfo(i);
275 if (Op.isLiteral()) {
276 Vals.push_back(Op.getLiteralValue());
277 continue;
278 }
279
280 if (Op.getEncoding() != BitCodeAbbrevOp::Array &&
281 Op.getEncoding() != BitCodeAbbrevOp::Blob) {
282 if (Expected MaybeVal = readAbbreviatedField(*this, Op))
283 Vals.push_back(MaybeVal.get());
284 else
285 return MaybeVal.takeError();
286 continue;
287 }
288
289 if (Op.getEncoding() == BitCodeAbbrevOp::Array) {
290 // Array case. Read the number of elements as a vbr6.
291 Expected MaybeNumElts = ReadVBR(6);
292 if (!MaybeNumElts)
293 return MaybeNumElts.takeError();
294 uint32_t NumElts = MaybeNumElts.get();
295
296 // Get the element encoding.
297 if (i + 2 != e)
298 report_fatal_error("Array op not second to last");
299 const BitCodeAbbrevOp &EltEnc = Abbv->getOperandInfo(++i);
300 if (!EltEnc.isEncoding())
301 report_fatal_error(
302 "Array element type has to be an encoding of a type");
303
304 // Read all the elements.
305 switch (EltEnc.getEncoding()) {
306 default:
307 report_fatal_error("Array element type can't be an Array or a Blob");
308 case BitCodeAbbrevOp::Fixed:
309 for (; NumElts; --NumElts)
310 if (Expected MaybeVal =
311 Read((unsigned)EltEnc.getEncodingData()))
312 Vals.push_back(MaybeVal.get());
313 else
314 return MaybeVal.takeError();
315 break;
316 case BitCodeAbbrevOp::VBR:
317 for (; NumElts; --NumElts)
318 if (Expected MaybeVal =
319 ReadVBR64((unsigned)EltEnc.getEncodingData()))
320 Vals.push_back(MaybeVal.get());
321 else
322 return MaybeVal.takeError();
323 break;
324 case BitCodeAbbrevOp::Char6:
325 for (; NumElts; --NumElts)
326 if (Expected MaybeVal = Read(6))
327 Vals.push_back(BitCodeAbbrevOp::DecodeChar6(MaybeVal.get()));
328 else
329 return MaybeVal.takeError();
330 }
331 continue;
332 }
333
334 assert(Op.getEncoding() == BitCodeAbbrevOp::Blob);
335 // Blob case. Read the number of bytes as a vbr6.
336 Expected MaybeNumElts = ReadVBR(6);
337 if (!MaybeNumElts)
338 return MaybeNumElts.takeError();
339 uint32_t NumElts = MaybeNumElts.get();
340 SkipToFourByteBoundary(); // 32-bit alignment
341
342 // Figure out where the end of this blob will be including tail padding.
343 size_t CurBitPos = GetCurrentBitNo();
344 size_t NewEnd = CurBitPos+((NumElts+3)&~3)*8;
345
346 // If this would read off the end of the bitcode file, just set the
347 // record to empty and return.
348 if (!canSkipToPos(NewEnd/8)) {
349 Vals.append(NumElts, 0);
350 skipToEnd();
351 break;
352 }
353
354 // Otherwise, inform the streamer that we need these bytes in memory. Skip
355 // over tail padding first, in case jumping to NewEnd invalidates the Blob
356 // pointer.
357 if (Error Err = JumpToBit(NewEnd))
358 return std::move(Err);
359 const char *Ptr = (const char *)getPointerToBit(CurBitPos, NumElts);
360
361 // If we can return a reference to the data, do so to avoid copying it.
362 if (Blob) {
363 *Blob = StringRef(Ptr, NumElts);
364 } else {
365 // Otherwise, unpack into Vals with zero extension.
366 for (; NumElts; --NumElts)
367 Vals.push_back((unsigned char)*Ptr++);
368 }
369 }
370
371 return Code;
372 }
373
374 Error BitstreamCursor::ReadAbbrevRecord() {
375 auto Abbv = std::make_shared();
376 Expected MaybeNumOpInfo = ReadVBR(5);
377 if (!MaybeNumOpInfo)
378 return MaybeNumOpInfo.takeError();
379 unsigned NumOpInfo = MaybeNumOpInfo.get();
380 for (unsigned i = 0; i != NumOpInfo; ++i) {
381 Expected MaybeIsLiteral = Read(1);
382 if (!MaybeIsLiteral)
383 return MaybeIsLiteral.takeError();
384 bool IsLiteral = MaybeIsLiteral.get();
385 if (IsLiteral) {
386 Expected MaybeOp = ReadVBR64(8);
387 if (!MaybeOp)
388 return MaybeOp.takeError();
389 Abbv->Add(BitCodeAbbrevOp(MaybeOp.get()));
390 continue;
391 }
392
393 Expected MaybeEncoding = Read(3);
394 if (!MaybeEncoding)
395 return MaybeEncoding.takeError();
396 BitCodeAbbrevOp::Encoding E =
397 (BitCodeAbbrevOp::Encoding)MaybeEncoding.get();
398 if (BitCodeAbbrevOp::hasEncodingData(E)) {
399 Expected MaybeData = ReadVBR64(5);
400 if (!MaybeData)
401 return MaybeData.takeError();
402 uint64_t Data = MaybeData.get();
403
404 // As a special case, handle fixed(0) (i.e., a fixed field with zero bits)
405 // and vbr(0) as a literal zero. This is decoded the same way, and avoids
406 // a slow path in Read() to have to handle reading zero bits.
407 if ((E == BitCodeAbbrevOp::Fixed || E == BitCodeAbbrevOp::VBR) &&
408 Data == 0) {
409 Abbv->Add(BitCodeAbbrevOp(0));
410 continue;
411 }
412
413 if ((E == BitCodeAbbrevOp::Fixed || E == BitCodeAbbrevOp::VBR) &&
414 Data > MaxChunkSize)
415 report_fatal_error(
416 "Fixed or VBR abbrev record with size > MaxChunkData");
417
418 Abbv->Add(BitCodeAbbrevOp(E, Data));
419 } else
420 Abbv->Add(BitCodeAbbrevOp(E));
421 }
422
423 if (Abbv->getNumOperandInfos() == 0)
424 report_fatal_error("Abbrev record with no operands");
425 CurAbbrevs.push_back(std::move(Abbv));
426
427 return Error::success();
428 }
429
430 Expected>
431 BitstreamCursor::ReadBlockInfoBlock(bool ReadBlockInfoNames) {
432 if (llvm::Error Err = EnterSubBlock(bitc::BLOCKINFO_BLOCK_ID))
433 return std::move(Err);
434
435 BitstreamBlockInfo NewBlockInfo;
436
437 SmallVector Record;
438 BitstreamBlockInfo::BlockInfo *CurBlockInfo = nullptr;
439
440 // Read all the records for this module.
441 while (true) {
442 Expected MaybeEntry =
443 advanceSkippingSubblocks(AF_DontAutoprocessAbbrevs);
444 if (!MaybeEntry)
445 return MaybeEntry.takeError();
446 BitstreamEntry Entry = MaybeEntry.get();
447
448 switch (Entry.Kind) {
449 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
450 case llvm::BitstreamEntry::Error:
451 return None;
452 case llvm::BitstreamEntry::EndBlock:
453 return std::move(NewBlockInfo);
454 case llvm::BitstreamEntry::Record:
455 // The interesting case.
456 break;
457 }
458
459 // Read abbrev records, associate them with CurBID.
460 if (Entry.ID == bitc::DEFINE_ABBREV) {
461 if (!CurBlockInfo) return None;
462 if (Error Err = ReadAbbrevRecord())
463 return std::move(Err);
464
465 // ReadAbbrevRecord installs the abbrev in CurAbbrevs. Move it to the
466 // appropriate BlockInfo.
467 CurBlockInfo->Abbrevs.push_back(std::move(CurAbbrevs.back()));
468 CurAbbrevs.pop_back();
469 continue;
470 }
471
472 // Read a record.
473 Record.clear();
474 Expected MaybeBlockInfo = readRecord(Entry.ID, Record);
475 if (!MaybeBlockInfo)
476 return MaybeBlockInfo.takeError();
477 switch (MaybeBlockInfo.get()) {
478 default:
479 break; // Default behavior, ignore unknown content.
480 case bitc::BLOCKINFO_CODE_SETBID:
481 if (Record.size() < 1)
482 return None;
483 CurBlockInfo = &NewBlockInfo.getOrCreateBlockInfo((unsigned)Record[0]);
484 break;
485 case bitc::BLOCKINFO_CODE_BLOCKNAME: {
486 if (!CurBlockInfo)
487 return None;
488 if (!ReadBlockInfoNames)
489 break; // Ignore name.
490 std::string Name;
491 for (unsigned i = 0, e = Record.size(); i != e; ++i)
492 Name += (char)Record[i];
493 CurBlockInfo->Name = Name;
494 break;
495 }
496 case bitc::BLOCKINFO_CODE_SETRECORDNAME: {
497 if (!CurBlockInfo) return None;
498 if (!ReadBlockInfoNames)
499 break; // Ignore name.
500 std::string Name;
501 for (unsigned i = 1, e = Record.size(); i != e; ++i)
502 Name += (char)Record[i];
503 CurBlockInfo->RecordNames.push_back(std::make_pair((unsigned)Record[0],
504 Name));
505 break;
506 }
507 }
508 }
509 }
0 add_llvm_library(LLVMBitReader
11 BitReader.cpp
22 BitcodeReader.cpp
3 BitstreamReader.cpp
43 MetadataLoader.cpp
54 ValueList.cpp
65
1717 type = Library
1818 name = BitReader
1919 parent = Bitcode
20 required_libraries = Core Support
20 required_libraries = BitstreamReader Core Support
2121 #include "llvm/ADT/StringRef.h"
2222 #include "llvm/ADT/Twine.h"
2323 #include "llvm/Bitcode/BitcodeReader.h"
24 #include "llvm/Bitcode/BitstreamReader.h"
24 #include "llvm/Bitstream/BitstreamReader.h"
2525 #include "llvm/Bitcode/LLVMBitCodes.h"
2626 #include "llvm/IR/Argument.h"
2727 #include "llvm/IR/Attributes.h"
2323 #include "llvm/ADT/StringMap.h"
2424 #include "llvm/ADT/StringRef.h"
2525 #include "llvm/ADT/Triple.h"
26 #include "llvm/Bitcode/BitCodes.h"
27 #include "llvm/Bitcode/BitstreamWriter.h"
26 #include "llvm/Bitstream/BitCodes.h"
27 #include "llvm/Bitstream/BitstreamWriter.h"
2828 #include "llvm/Bitcode/LLVMBitCodes.h"
2929 #include "llvm/Config/llvm-config.h"
3030 #include "llvm/IR/Attributes.h"
0 add_subdirectory(Reader)
1 # The writer is header-only.
0 ;===- ./lib/Bitstream/LLVMBuild.txt ----------------------------*- Conf -*--===;
1 ;
2 ; Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
3 ; See https://llvm.org/LICENSE.txt for license information.
4 ; SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
5 ;
6 ;===------------------------------------------------------------------------===;
7 ;
8 ; This is an LLVMBuild description file for the components in this subdirectory.
9 ;
10 ; For more information on the LLVMBuild system, please see:
11 ;
12 ; http://llvm.org/docs/LLVMBuild.html
13 ;
14 ;===------------------------------------------------------------------------===;
15
16 [common]
17 subdirectories = Reader
18
19 [component_0]
20 type = Group
21 name = Bitstream
22 parent = Libraries
0 //===- BitstreamReader.cpp - BitstreamReader implementation ---------------===//
1 //
2 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
3 // See https://llvm.org/LICENSE.txt for license information.
4 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
5 //
6 //===----------------------------------------------------------------------===//
7
8 #include "llvm/Bitstream/BitstreamReader.h"
9 #include "llvm/ADT/StringRef.h"
10 #include
11 #include
12
13 using namespace llvm;
14
15 //===----------------------------------------------------------------------===//
16 // BitstreamCursor implementation
17 //===----------------------------------------------------------------------===//
18
19 /// Having read the ENTER_SUBBLOCK abbrevid, enter the block.
20 Error BitstreamCursor::EnterSubBlock(unsigned BlockID, unsigned *NumWordsP) {
21 // Save the current block's state on BlockScope.
22 BlockScope.push_back(Block(CurCodeSize));
23 BlockScope.back().PrevAbbrevs.swap(CurAbbrevs);
24
25 // Add the abbrevs specific to this block to the CurAbbrevs list.
26 if (BlockInfo) {
27 if (const BitstreamBlockInfo::BlockInfo *Info =
28 BlockInfo->getBlockInfo(BlockID)) {
29 CurAbbrevs.insert(CurAbbrevs.end(), Info->Abbrevs.begin(),
30 Info->Abbrevs.end());
31 }
32 }
33
34 // Get the codesize of this block.
35 Expected MaybeVBR = ReadVBR(bitc::CodeLenWidth);
36 if (!MaybeVBR)
37 return MaybeVBR.takeError();
38 CurCodeSize = MaybeVBR.get();
39
40 if (CurCodeSize > MaxChunkSize)
41 return llvm::createStringError(
42 std::errc::illegal_byte_sequence,
43 "can't read more than %zu at a time, trying to read %u", +MaxChunkSize,
44 CurCodeSize);
45
46 SkipToFourByteBoundary();
47 Expected MaybeNum = Read(bitc::BlockSizeWidth);
48 if (!MaybeNum)
49 return MaybeNum.takeError();
50 word_t NumWords = MaybeNum.get();
51 if (NumWordsP)
52 *NumWordsP = NumWords;
53
54 if (CurCodeSize == 0)
55 return llvm::createStringError(
56 std::errc::illegal_byte_sequence,
57 "can't enter sub-block: current code size is 0");
58 if (AtEndOfStream())
59 return llvm::createStringError(
60 std::errc::illegal_byte_sequence,
61 "can't enter sub block: already at end of stream");
62
63 return Error::success();
64 }
65
66 static Expected readAbbreviatedField(BitstreamCursor &Cursor,
67 const BitCodeAbbrevOp &Op) {
68 assert(!Op.isLiteral() && "Not to be used with literals!");
69
70 // Decode the value as we are commanded.
71 switch (Op.getEncoding()) {
72 case BitCodeAbbrevOp::Array:
73 case BitCodeAbbrevOp::Blob:
74 llvm_unreachable("Should not reach here");
75 case BitCodeAbbrevOp::Fixed:
76 assert((unsigned)Op.getEncodingData() <= Cursor.MaxChunkSize);
77 return Cursor.Read((unsigned)Op.getEncodingData());
78 case BitCodeAbbrevOp::VBR:
79 assert((unsigned)Op.getEncodingData() <= Cursor.MaxChunkSize);
80 return Cursor.ReadVBR64((unsigned)Op.getEncodingData());
81 case BitCodeAbbrevOp::Char6:
82 if (Expected Res = Cursor.Read(6))
83 return BitCodeAbbrevOp::DecodeChar6(Res.get());
84 else
85 return Res.takeError();
86 }
87 llvm_unreachable("invalid abbreviation encoding");
88 }
89
90 static Error skipAbbreviatedField(BitstreamCursor &Cursor,
91 const BitCodeAbbrevOp &Op) {
92 assert(!Op.isLiteral() && "Not to be used with literals!");
93
94 // Decode the value as we are commanded.
95 switch (Op.getEncoding()) {
96 case BitCodeAbbrevOp::Array:
97 case BitCodeAbbrevOp::Blob:
98 llvm_unreachable("Should not reach here");
99 case BitCodeAbbrevOp::Fixed:
100 assert((unsigned)Op.getEncodingData() <= Cursor.MaxChunkSize);
101 if (Expected Res = Cursor.Read((unsigned)Op.getEncodingData()))
102 break;
103 else
104 return Res.takeError();
105 case BitCodeAbbrevOp::VBR:
106 assert((unsigned)Op.getEncodingData() <= Cursor.MaxChunkSize);
107 if (Expected Res =
108 Cursor.ReadVBR64((unsigned)Op.getEncodingData()))
109 break;
110 else
111 return Res.takeError();
112 case BitCodeAbbrevOp::Char6:
113 if (Expected Res = Cursor.Read(6))
114 break;
115 else
116 return Res.takeError();
117 }
118 return ErrorSuccess();
119 }
120
121 /// skipRecord - Read the current record and discard it.
122 Expected BitstreamCursor::skipRecord(unsigned AbbrevID) {
123 // Skip unabbreviated records by reading past their entries.
124 if (AbbrevID == bitc::UNABBREV_RECORD) {
125 Expected MaybeCode = ReadVBR(6);
126 if (!MaybeCode)
127 return MaybeCode.takeError();
128 unsigned Code = MaybeCode.get();
129 Expected MaybeVBR = ReadVBR(6);
130 if (!MaybeVBR)
131 return MaybeVBR.get();
132 unsigned NumElts = MaybeVBR.get();
133 for (unsigned i = 0; i != NumElts; ++i)
134 if (Expected Res = ReadVBR64(6))
135 ; // Skip!
136 else
137 return Res.takeError();
138 return Code;
139 }
140
141 const BitCodeAbbrev *Abbv = getAbbrev(AbbrevID);
142 const BitCodeAbbrevOp &CodeOp = Abbv->getOperandInfo(0);
143 unsigned Code;
144 if (CodeOp.isLiteral())
145 Code = CodeOp.getLiteralValue();
146 else {
147 if (CodeOp.getEncoding() == BitCodeAbbrevOp::Array ||
148 CodeOp.getEncoding() == BitCodeAbbrevOp::Blob)
149 return llvm::createStringError(
150 std::errc::illegal_byte_sequence,
151 "Abbreviation starts with an Array or a Blob");
152 Expected MaybeCode = readAbbreviatedField(*this, CodeOp);
153 if (!MaybeCode)
154 return MaybeCode.takeError();
155 Code = MaybeCode.get();
156 }
157
158 for (unsigned i = 1, e = Abbv->getNumOperandInfos(); i < e; ++i) {
159 const BitCodeAbbrevOp &Op = Abbv->getOperandInfo(i);
160 if (Op.isLiteral())
161 continue;
162
163 if (Op.getEncoding() != BitCodeAbbrevOp::Array &&
164 Op.getEncoding() != BitCodeAbbrevOp::Blob) {
165 if (Error Err = skipAbbreviatedField(*this, Op))
166 return std::move(Err);
167 continue;
168 }
169
170 if (Op.getEncoding() == BitCodeAbbrevOp::Array) {
171 // Array case. Read the number of elements as a vbr6.
172 Expected MaybeNum = ReadVBR(6);
173 if (!MaybeNum)
174 return MaybeNum.takeError();
175 unsigned NumElts = MaybeNum.get();
176
177 // Get the element encoding.
178 assert(i+2 == e && "array op not second to last?");
179 const BitCodeAbbrevOp &EltEnc = Abbv->getOperandInfo(++i);
180
181 // Read all the elements.
182 // Decode the value as we are commanded.
183 switch (EltEnc.getEncoding()) {
184 default:
185 report_fatal_error("Array element type can't be an Array or a Blob");
186 case BitCodeAbbrevOp::Fixed:
187 assert((unsigned)EltEnc.getEncodingData() <= MaxChunkSize);
188 if (Error Err = JumpToBit(GetCurrentBitNo() +
189 NumElts * EltEnc.getEncodingData()))
190 return std::move(Err);
191 break;
192 case BitCodeAbbrevOp::VBR:
193 assert((unsigned)EltEnc.getEncodingData() <= MaxChunkSize);
194 for (; NumElts; --NumElts)
195 if (Expected Res =
196 ReadVBR64((unsigned)EltEnc.getEncodingData()))
197 ; // Skip!
198 else
199 return Res.takeError();
200 break;
201 case BitCodeAbbrevOp::Char6:
202 if (Error Err = JumpToBit(GetCurrentBitNo() + NumElts * 6))
203 return std::move(Err);
204 break;
205 }
206 continue;
207 }
208
209 assert(Op.getEncoding() == BitCodeAbbrevOp::Blob);
210 // Blob case. Read the number of bytes as a vbr6.
211 Expected MaybeNum = ReadVBR(6);
212 if (!MaybeNum)
213 return MaybeNum.takeError();
214 unsigned NumElts = MaybeNum.get();
215 SkipToFourByteBoundary(); // 32-bit alignment
216
217 // Figure out where the end of this blob will be including tail padding.
218 size_t NewEnd = GetCurrentBitNo()+((NumElts+3)&~3)*8;
219
220 // If this would read off the end of the bitcode file, just set the
221 // record to empty and return.
222 if (!canSkipToPos(NewEnd/8)) {
223 skipToEnd();
224 break;
225 }
226
227 // Skip over the blob.
228 if (Error Err = JumpToBit(NewEnd))
229 return std::move(Err);
230 }
231 return Code;
232 }
233
234 Expected BitstreamCursor::readRecord(unsigned AbbrevID,
235 SmallVectorImpl &Vals,
236 StringRef *Blob) {
237 if (AbbrevID == bitc::UNABBREV_RECORD) {
238 Expected MaybeCode = ReadVBR(6);
239 if (!MaybeCode)
240 return MaybeCode.takeError();
241 uint32_t Code = MaybeCode.get();
242 Expected MaybeNumElts = ReadVBR(6);
243 if (!MaybeNumElts)
244 return MaybeNumElts.takeError();
245 uint32_t NumElts = MaybeNumElts.get();
246
247 for (unsigned i = 0; i != NumElts; ++i)
248 if (Expected MaybeVal = ReadVBR64(6))
249 Vals.push_back(MaybeVal.get());
250 else
251 return MaybeVal.takeError();
252 return Code;
253 }
254
255 const BitCodeAbbrev *Abbv = getAbbrev(AbbrevID);
256
257 // Read the record code first.
258 assert(Abbv->getNumOperandInfos() != 0 && "no record code in abbreviation?");
259 const BitCodeAbbrevOp &CodeOp = Abbv->getOperandInfo(0);
260 unsigned Code;
261 if (CodeOp.isLiteral())
262 Code = CodeOp.getLiteralValue();
263 else {
264 if (CodeOp.getEncoding() == BitCodeAbbrevOp::Array ||
265 CodeOp.getEncoding() == BitCodeAbbrevOp::Blob)
266 report_fatal_error("Abbreviation starts with an Array or a Blob");
267 if (Expected MaybeCode = readAbbreviatedField(*this, CodeOp))
268 Code = MaybeCode.get();
269 else
270 return MaybeCode.takeError();
271 }
272
273 for (unsigned i = 1, e = Abbv->getNumOperandInfos(); i != e; ++i) {
274 const BitCodeAbbrevOp &Op = Abbv->getOperandInfo(i);
275 if (Op.isLiteral()) {
276 Vals.push_back(Op.getLiteralValue());
277 continue;
278 }
279
280 if (Op.getEncoding() != BitCodeAbbrevOp::Array &&
281 Op.getEncoding() != BitCodeAbbrevOp::Blob) {
282 if (Expected MaybeVal = readAbbreviatedField(*this, Op))
283 Vals.push_back(MaybeVal.get());
284 else
285 return MaybeVal.takeError();
286 continue;
287 }
288
289 if (Op.getEncoding() == BitCodeAbbrevOp::Array) {
290 // Array case. Read the number of elements as a vbr6.
291 Expected MaybeNumElts = ReadVBR(6);
292 if (!MaybeNumElts)
293 return MaybeNumElts.takeError();
294 uint32_t NumElts = MaybeNumElts.get();
295
296 // Get the element encoding.
297 if (i + 2 != e)
298 report_fatal_error("Array op not second to last");
299 const BitCodeAbbrevOp &EltEnc = Abbv->getOperandInfo(++i);
300 if (!EltEnc.isEncoding())
301 report_fatal_error(
302 "Array element type has to be an encoding of a type");
303
304 // Read all the elements.
305 switch (EltEnc.getEncoding()) {
306 default:
307 report_fatal_error("Array element type can't be an Array or a Blob");
308 case BitCodeAbbrevOp::Fixed:
309 for (; NumElts; --NumElts)
310 if (Expected MaybeVal =
311 Read((unsigned)EltEnc.getEncodingData()))
312 Vals.push_back(MaybeVal.get());
313 else
314 return MaybeVal.takeError();
315 break;
316 case BitCodeAbbrevOp::VBR:
317 for (; NumElts; --NumElts)
318 if (Expected MaybeVal =
319 ReadVBR64((unsigned)EltEnc.getEncodingData()))
320 Vals.push_back(MaybeVal.get());
321 else
322 return MaybeVal.takeError();
323 break;
324 case BitCodeAbbrevOp::Char6:
325 for (; NumElts; --NumElts)
326 if (Expected MaybeVal = Read(6))
327 Vals.push_back(BitCodeAbbrevOp::DecodeChar6(MaybeVal.get()));
328 else
329 return MaybeVal.takeError();
330 }
331 continue;
332 }
333
334 assert(Op.getEncoding() == BitCodeAbbrevOp::Blob);
335 // Blob case. Read the number of bytes as a vbr6.
336 Expected MaybeNumElts = ReadVBR(6);
337 if (!MaybeNumElts)
338 return MaybeNumElts.takeError();
339 uint32_t NumElts = MaybeNumElts.get();
340 SkipToFourByteBoundary(); // 32-bit alignment
341
342 // Figure out where the end of this blob will be including tail padding.
343 size_t CurBitPos = GetCurrentBitNo();
344 size_t NewEnd = CurBitPos+((NumElts+3)&~3)*8;
345
346 // If this would read off the end of the bitcode file, just set the
347 // record to empty and return.
348 if (!canSkipToPos(NewEnd/8)) {
349 Vals.append(NumElts, 0);
350 skipToEnd();
351 break;
352 }
353
354 // Otherwise, inform the streamer that we need these bytes in memory. Skip
355 // over tail padding first, in case jumping to NewEnd invalidates the Blob
356 // pointer.
357 if (Error Err = JumpToBit(NewEnd))
358 return std::move(Err);
359 const char *Ptr = (const char *)getPointerToBit(CurBitPos, NumElts);
360
361 // If we can return a reference to the data, do so to avoid copying it.
362 if (Blob) {
363 *Blob = StringRef(Ptr, NumElts);
364 } else {
365 // Otherwise, unpack into Vals with zero extension.
366 for (; NumElts; --NumElts)
367 Vals.push_back((unsigned char)*Ptr++);
368 }
369 }
370
371 return Code;
372 }
373
374 Error BitstreamCursor::ReadAbbrevRecord() {
375 auto Abbv = std::make_shared();
376 Expected MaybeNumOpInfo = ReadVBR(5);
377 if (!MaybeNumOpInfo)
378 return MaybeNumOpInfo.takeError();
379 unsigned NumOpInfo = MaybeNumOpInfo.get();
380 for (unsigned i = 0; i != NumOpInfo; ++i) {
381 Expected MaybeIsLiteral = Read(1);
382 if (!MaybeIsLiteral)
383 return MaybeIsLiteral.takeError();
384 bool IsLiteral = MaybeIsLiteral.get();
385 if (IsLiteral) {
386 Expected MaybeOp = ReadVBR64(8);
387 if (!MaybeOp)
388 return MaybeOp.takeError();
389 Abbv->Add(BitCodeAbbrevOp(MaybeOp.get()));
390 continue;
391 }
392
393 Expected MaybeEncoding = Read(3);
394 if (!MaybeEncoding)
395 return MaybeEncoding.takeError();
396 BitCodeAbbrevOp::Encoding E =
397 (BitCodeAbbrevOp::Encoding)MaybeEncoding.get();
398 if (BitCodeAbbrevOp::hasEncodingData(E)) {
399 Expected MaybeData = ReadVBR64(5);
400 if (!MaybeData)
401 return MaybeData.takeError();
402 uint64_t Data = MaybeData.get();
403
404 // As a special case, handle fixed(0) (i.e., a fixed field with zero bits)
405 // and vbr(0) as a literal zero. This is decoded the same way, and avoids
406 // a slow path in Read() to have to handle reading zero bits.
407 if ((E == BitCodeAbbrevOp::Fixed || E == BitCodeAbbrevOp::VBR) &&
408 Data == 0) {
409 Abbv->Add(BitCodeAbbrevOp(0));
410 continue;
411 }
412
413 if ((E == BitCodeAbbrevOp::Fixed || E == BitCodeAbbrevOp::VBR) &&
414 Data > MaxChunkSize)
415 report_fatal_error(