MLIR  21.0.0git
BytecodeWriter.cpp
Go to the documentation of this file.
1 //===- BytecodeWriter.cpp - MLIR Bytecode Writer --------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
10 #include "IRNumbering.h"
13 #include "mlir/Bytecode/Encoding.h"
14 #include "mlir/IR/Attributes.h"
15 #include "mlir/IR/Diagnostics.h"
17 #include "llvm/ADT/ArrayRef.h"
18 #include "llvm/ADT/CachedHashString.h"
19 #include "llvm/ADT/MapVector.h"
20 #include "llvm/ADT/SmallVector.h"
21 #include "llvm/Support/Debug.h"
22 #include "llvm/Support/Endian.h"
23 #include "llvm/Support/raw_ostream.h"
24 #include <optional>
25 
26 #define DEBUG_TYPE "mlir-bytecode-writer"
27 
28 using namespace mlir;
29 using namespace mlir::bytecode::detail;
30 
31 //===----------------------------------------------------------------------===//
32 // BytecodeWriterConfig
33 //===----------------------------------------------------------------------===//
34 
36  Impl(StringRef producer) : producer(producer) {}
37 
38  /// Version to use when writing.
39  /// Note: This only differs from kVersion if a specific version is set.
40  int64_t bytecodeVersion = bytecode::kVersion;
41 
42  /// A flag specifying whether to elide emission of resources into the bytecode
43  /// file.
44  bool shouldElideResourceData = false;
45 
46  /// A map containing dialect version information for each dialect to emit.
47  llvm::StringMap<std::unique_ptr<DialectVersion>> dialectVersionMap;
48 
49  /// The producer of the bytecode.
50  StringRef producer;
51 
52  /// Printer callbacks used to emit custom type and attribute encodings.
57 
58  /// A collection of non-dialect resource printers.
60 };
61 
63  : impl(std::make_unique<Impl>(producer)) {}
65  StringRef producer)
66  : BytecodeWriterConfig(producer) {
68 }
70  : impl(std::move(config.impl)) {}
71 
73 
76  return impl->attributeWriterCallbacks;
77 }
78 
81  return impl->typeWriterCallbacks;
82 }
83 
85  std::unique_ptr<AttrTypeBytecodeWriter<Attribute>> callback) {
86  impl->attributeWriterCallbacks.emplace_back(std::move(callback));
87 }
88 
90  std::unique_ptr<AttrTypeBytecodeWriter<Type>> callback) {
91  impl->typeWriterCallbacks.emplace_back(std::move(callback));
92 }
93 
95  std::unique_ptr<AsmResourcePrinter> printer) {
96  impl->externalResourcePrinters.emplace_back(std::move(printer));
97 }
98 
100  bool shouldElideResourceData) {
101  impl->shouldElideResourceData = shouldElideResourceData;
102 }
103 
104 void BytecodeWriterConfig::setDesiredBytecodeVersion(int64_t bytecodeVersion) {
105  impl->bytecodeVersion = bytecodeVersion;
106 }
107 
109  return impl->bytecodeVersion;
110 }
111 
112 llvm::StringMap<std::unique_ptr<DialectVersion>> &
114  return impl->dialectVersionMap;
115 }
116 
118  llvm::StringRef dialectName,
119  std::unique_ptr<DialectVersion> dialectVersion) const {
120  assert(!impl->dialectVersionMap.contains(dialectName) &&
121  "cannot override a previously set dialect version");
122  impl->dialectVersionMap.insert({dialectName, std::move(dialectVersion)});
123 }
124 
125 //===----------------------------------------------------------------------===//
126 // EncodingEmitter
127 //===----------------------------------------------------------------------===//
128 
129 namespace {
130 /// This class functions as the underlying encoding emitter for the bytecode
131 /// writer. This class is a bit different compared to other types of encoders;
132 /// it does not use a single buffer, but instead may contain several buffers
133 /// (some owned by the writer, and some not) that get concatted during the final
134 /// emission.
135 class EncodingEmitter {
136 public:
137  EncodingEmitter() = default;
138  EncodingEmitter(const EncodingEmitter &) = delete;
139  EncodingEmitter &operator=(const EncodingEmitter &) = delete;
140 
141  /// Write the current contents to the provided stream.
142  void writeTo(raw_ostream &os) const;
143 
144  /// Return the current size of the encoded buffer.
145  size_t size() const { return prevResultSize + currentResult.size(); }
146 
147  //===--------------------------------------------------------------------===//
148  // Emission
149  //===--------------------------------------------------------------------===//
150 
151  /// Backpatch a byte in the result buffer at the given offset.
152  void patchByte(uint64_t offset, uint8_t value, StringLiteral desc) {
153  LLVM_DEBUG(llvm::dbgs() << "patchByte(" << offset << ',' << uint64_t(value)
154  << ")\t" << desc << '\n');
155  assert(offset < size() && offset >= prevResultSize &&
156  "cannot patch previously emitted data");
157  currentResult[offset - prevResultSize] = value;
158  }
159 
160  /// Emit the provided blob of data, which is owned by the caller and is
161  /// guaranteed to not die before the end of the bytecode process.
162  void emitOwnedBlob(ArrayRef<uint8_t> data, StringLiteral desc) {
163  LLVM_DEBUG(llvm::dbgs()
164  << "emitOwnedBlob(" << data.size() << "b)\t" << desc << '\n');
165  // Push the current buffer before adding the provided data.
166  appendResult(std::move(currentResult));
167  appendOwnedResult(data);
168  }
169 
170  /// Emit the provided blob of data that has the given alignment, which is
171  /// owned by the caller and is guaranteed to not die before the end of the
172  /// bytecode process. The alignment value is also encoded, making it available
173  /// on load.
174  void emitOwnedBlobAndAlignment(ArrayRef<uint8_t> data, uint32_t alignment,
175  StringLiteral desc) {
176  emitVarInt(alignment, desc);
177  emitVarInt(data.size(), desc);
178 
179  alignTo(alignment);
180  emitOwnedBlob(data, desc);
181  }
182  void emitOwnedBlobAndAlignment(ArrayRef<char> data, uint32_t alignment,
183  StringLiteral desc) {
184  ArrayRef<uint8_t> castedData(reinterpret_cast<const uint8_t *>(data.data()),
185  data.size());
186  emitOwnedBlobAndAlignment(castedData, alignment, desc);
187  }
188 
189  /// Align the emitter to the given alignment.
190  void alignTo(unsigned alignment) {
191  if (alignment < 2)
192  return;
193  assert(llvm::isPowerOf2_32(alignment) && "expected valid alignment");
194 
195  // Check to see if we need to emit any padding bytes to meet the desired
196  // alignment.
197  size_t curOffset = size();
198  size_t paddingSize = llvm::alignTo(curOffset, alignment) - curOffset;
199  while (paddingSize--)
200  emitByte(bytecode::kAlignmentByte, "alignment byte");
201 
202  // Keep track of the maximum required alignment.
203  requiredAlignment = std::max(requiredAlignment, alignment);
204  }
205 
206  //===--------------------------------------------------------------------===//
207  // Integer Emission
208 
209  /// Emit a single byte.
210  template <typename T>
211  void emitByte(T byte, StringLiteral desc) {
212  LLVM_DEBUG(llvm::dbgs()
213  << "emitByte(" << uint64_t(byte) << ")\t" << desc << '\n');
214  currentResult.push_back(static_cast<uint8_t>(byte));
215  }
216 
217  /// Emit a range of bytes.
218  void emitBytes(ArrayRef<uint8_t> bytes, StringLiteral desc) {
219  LLVM_DEBUG(llvm::dbgs()
220  << "emitBytes(" << bytes.size() << "b)\t" << desc << '\n');
221  llvm::append_range(currentResult, bytes);
222  }
223 
224  /// Emit a variable length integer. The first encoded byte contains a prefix
225  /// in the low bits indicating the encoded length of the value. This length
226  /// prefix is a bit sequence of '0's followed by a '1'. The number of '0' bits
227  /// indicate the number of _additional_ bytes (not including the prefix byte).
228  /// All remaining bits in the first byte, along with all of the bits in
229  /// additional bytes, provide the value of the integer encoded in
230  /// little-endian order.
231  void emitVarInt(uint64_t value, StringLiteral desc) {
232  LLVM_DEBUG(llvm::dbgs() << "emitVarInt(" << value << ")\t" << desc << '\n');
233 
234  // In the most common case, the value can be represented in a single byte.
235  // Given how hot this case is, explicitly handle that here.
236  if ((value >> 7) == 0)
237  return emitByte((value << 1) | 0x1, desc);
238  emitMultiByteVarInt(value, desc);
239  }
240 
241  /// Emit a signed variable length integer. Signed varints are encoded using
242  /// a varint with zigzag encoding, meaning that we use the low bit of the
243  /// value to indicate the sign of the value. This allows for more efficient
244  /// encoding of negative values by limiting the number of active bits
245  void emitSignedVarInt(uint64_t value, StringLiteral desc) {
246  emitVarInt((value << 1) ^ (uint64_t)((int64_t)value >> 63), desc);
247  }
248 
249  /// Emit a variable length integer whose low bit is used to encode the
250  /// provided flag, i.e. encoded as: (value << 1) | (flag ? 1 : 0).
251  void emitVarIntWithFlag(uint64_t value, bool flag, StringLiteral desc) {
252  emitVarInt((value << 1) | (flag ? 1 : 0), desc);
253  }
254 
255  //===--------------------------------------------------------------------===//
256  // String Emission
257 
258  /// Emit the given string as a nul terminated string.
259  void emitNulTerminatedString(StringRef str, StringLiteral desc) {
260  emitString(str, desc);
261  emitByte(0, "null terminator");
262  }
263 
264  /// Emit the given string without a nul terminator.
265  void emitString(StringRef str, StringLiteral desc) {
266  emitBytes({reinterpret_cast<const uint8_t *>(str.data()), str.size()},
267  desc);
268  }
269 
270  //===--------------------------------------------------------------------===//
271  // Section Emission
272 
273  /// Emit a nested section of the given code, whose contents are encoded in the
274  /// provided emitter.
275  void emitSection(bytecode::Section::ID code, EncodingEmitter &&emitter) {
276  // Emit the section code and length. The high bit of the code is used to
277  // indicate whether the section alignment is present, so save an offset to
278  // it.
279  uint64_t codeOffset = currentResult.size();
280  emitByte(code, "section code");
281  emitVarInt(emitter.size(), "section size");
282 
283  // Integrate the alignment of the section into this emitter if necessary.
284  unsigned emitterAlign = emitter.requiredAlignment;
285  if (emitterAlign > 1) {
286  if (size() & (emitterAlign - 1)) {
287  emitVarInt(emitterAlign, "section alignment");
288  alignTo(emitterAlign);
289 
290  // Indicate that we needed to align the section, the high bit of the
291  // code field is used for this.
292  currentResult[codeOffset] |= 0b10000000;
293  } else {
294  // Otherwise, if we happen to be at a compatible offset, we just
295  // remember that we need this alignment.
296  requiredAlignment = std::max(requiredAlignment, emitterAlign);
297  }
298  }
299 
300  // Push our current buffer and then merge the provided section body into
301  // ours.
302  appendResult(std::move(currentResult));
303  for (std::vector<uint8_t> &result : emitter.prevResultStorage)
304  prevResultStorage.push_back(std::move(result));
305  llvm::append_range(prevResultList, emitter.prevResultList);
306  prevResultSize += emitter.prevResultSize;
307  appendResult(std::move(emitter.currentResult));
308  }
309 
310 private:
311  /// Emit the given value using a variable width encoding. This method is a
312  /// fallback when the number of bytes needed to encode the value is greater
313  /// than 1. We mark it noinline here so that the single byte hot path isn't
314  /// pessimized.
315  LLVM_ATTRIBUTE_NOINLINE void emitMultiByteVarInt(uint64_t value,
316  StringLiteral desc);
317 
318  /// Append a new result buffer to the current contents.
319  void appendResult(std::vector<uint8_t> &&result) {
320  if (result.empty())
321  return;
322  prevResultStorage.emplace_back(std::move(result));
323  appendOwnedResult(prevResultStorage.back());
324  }
325  void appendOwnedResult(ArrayRef<uint8_t> result) {
326  if (result.empty())
327  return;
328  prevResultSize += result.size();
329  prevResultList.emplace_back(result);
330  }
331 
332  /// The result of the emitter currently being built. We refrain from building
333  /// a single buffer to simplify emitting sections, large data, and more. The
334  /// result is thus represented using multiple distinct buffers, some of which
335  /// we own (via prevResultStorage), and some of which are just pointers into
336  /// externally owned buffers.
337  std::vector<uint8_t> currentResult;
338  std::vector<ArrayRef<uint8_t>> prevResultList;
339  std::vector<std::vector<uint8_t>> prevResultStorage;
340 
341  /// An up-to-date total size of all of the buffers within `prevResultList`.
342  /// This enables O(1) size checks of the current encoding.
343  size_t prevResultSize = 0;
344 
345  /// The highest required alignment for the start of this section.
346  unsigned requiredAlignment = 1;
347 };
348 
349 //===----------------------------------------------------------------------===//
350 // StringSectionBuilder
351 //===----------------------------------------------------------------------===//
352 
353 namespace {
354 /// This class is used to simplify the process of emitting the string section.
355 class StringSectionBuilder {
356 public:
357  /// Add the given string to the string section, and return the index of the
358  /// string within the section.
359  size_t insert(StringRef str) {
360  auto it = strings.insert({llvm::CachedHashStringRef(str), strings.size()});
361  return it.first->second;
362  }
363 
364  /// Write the current set of strings to the given emitter.
365  void write(EncodingEmitter &emitter) {
366  emitter.emitVarInt(strings.size(), "string section size");
367 
368  // Emit the sizes in reverse order, so that we don't need to backpatch an
369  // offset to the string data or have a separate section.
370  for (const auto &it : llvm::reverse(strings))
371  emitter.emitVarInt(it.first.size() + 1, "string size");
372  // Emit the string data itself.
373  for (const auto &it : strings)
374  emitter.emitNulTerminatedString(it.first.val(), "string");
375  }
376 
377 private:
378  /// A set of strings referenced within the bytecode. The value of the map is
379  /// unused.
380  llvm::MapVector<llvm::CachedHashStringRef, size_t> strings;
381 };
382 } // namespace
383 
384 class DialectWriter : public DialectBytecodeWriter {
385  using DialectVersionMapT = llvm::StringMap<std::unique_ptr<DialectVersion>>;
386 
387 public:
388  DialectWriter(int64_t bytecodeVersion, EncodingEmitter &emitter,
389  IRNumberingState &numberingState,
390  StringSectionBuilder &stringSection,
391  const DialectVersionMapT &dialectVersionMap)
392  : bytecodeVersion(bytecodeVersion), emitter(emitter),
393  numberingState(numberingState), stringSection(stringSection),
394  dialectVersionMap(dialectVersionMap) {}
395 
396  //===--------------------------------------------------------------------===//
397  // IR
398  //===--------------------------------------------------------------------===//
399 
400  void writeAttribute(Attribute attr) override {
401  emitter.emitVarInt(numberingState.getNumber(attr), "dialect attr");
402  }
403  void writeOptionalAttribute(Attribute attr) override {
404  if (!attr) {
405  emitter.emitVarInt(0, "dialect optional attr none");
406  return;
407  }
408  emitter.emitVarIntWithFlag(numberingState.getNumber(attr), true,
409  "dialect optional attr");
410  }
411 
412  void writeType(Type type) override {
413  emitter.emitVarInt(numberingState.getNumber(type), "dialect type");
414  }
415 
416  void writeResourceHandle(const AsmDialectResourceHandle &resource) override {
417  emitter.emitVarInt(numberingState.getNumber(resource), "dialect resource");
418  }
419 
420  //===--------------------------------------------------------------------===//
421  // Primitives
422  //===--------------------------------------------------------------------===//
423 
424  void writeVarInt(uint64_t value) override {
425  emitter.emitVarInt(value, "dialect writer");
426  }
427 
428  void writeSignedVarInt(int64_t value) override {
429  emitter.emitSignedVarInt(value, "dialect writer");
430  }
431 
432  void writeAPIntWithKnownWidth(const APInt &value) override {
433  size_t bitWidth = value.getBitWidth();
434 
435  // If the value is a single byte, just emit it directly without going
436  // through a varint.
437  if (bitWidth <= 8)
438  return emitter.emitByte(value.getLimitedValue(), "dialect APInt");
439 
440  // If the value fits within a single varint, emit it directly.
441  if (bitWidth <= 64)
442  return emitter.emitSignedVarInt(value.getLimitedValue(), "dialect APInt");
443 
444  // Otherwise, we need to encode a variable number of active words. We use
445  // active words instead of the number of total words under the observation
446  // that smaller values will be more common.
447  unsigned numActiveWords = value.getActiveWords();
448  emitter.emitVarInt(numActiveWords, "dialect APInt word count");
449 
450  const uint64_t *rawValueData = value.getRawData();
451  for (unsigned i = 0; i < numActiveWords; ++i)
452  emitter.emitSignedVarInt(rawValueData[i], "dialect APInt word");
453  }
454 
455  void writeAPFloatWithKnownSemantics(const APFloat &value) override {
456  writeAPIntWithKnownWidth(value.bitcastToAPInt());
457  }
458 
459  void writeOwnedString(StringRef str) override {
460  emitter.emitVarInt(stringSection.insert(str), "dialect string");
461  }
462 
463  void writeOwnedBlob(ArrayRef<char> blob) override {
464  emitter.emitVarInt(blob.size(), "dialect blob");
465  emitter.emitOwnedBlob(
466  ArrayRef<uint8_t>(reinterpret_cast<const uint8_t *>(blob.data()),
467  blob.size()),
468  "dialect blob");
469  }
470 
471  void writeOwnedBool(bool value) override {
472  emitter.emitByte(value, "dialect bool");
473  }
474 
475  int64_t getBytecodeVersion() const override { return bytecodeVersion; }
476 
477  FailureOr<const DialectVersion *>
478  getDialectVersion(StringRef dialectName) const override {
479  auto dialectEntry = dialectVersionMap.find(dialectName);
480  if (dialectEntry == dialectVersionMap.end())
481  return failure();
482  return dialectEntry->getValue().get();
483  }
484 
485 private:
486  int64_t bytecodeVersion;
487  EncodingEmitter &emitter;
488  IRNumberingState &numberingState;
489  StringSectionBuilder &stringSection;
490  const DialectVersionMapT &dialectVersionMap;
491 };
492 
493 namespace {
494 class PropertiesSectionBuilder {
495 public:
496  PropertiesSectionBuilder(IRNumberingState &numberingState,
497  StringSectionBuilder &stringSection,
499  : numberingState(numberingState), stringSection(stringSection),
500  config(config) {}
501 
502  /// Emit the op properties in the properties section and return the index of
503  /// the properties within the section. Return -1 if no properties was emitted.
504  std::optional<ssize_t> emit(Operation *op) {
505  EncodingEmitter propertiesEmitter;
506  if (!op->getPropertiesStorageSize())
507  return std::nullopt;
508  if (!op->isRegistered()) {
509  // Unregistered op are storing properties as an optional attribute.
510  Attribute prop = *op->getPropertiesStorage().as<Attribute *>();
511  if (!prop)
512  return std::nullopt;
513  EncodingEmitter sizeEmitter;
514  sizeEmitter.emitVarInt(numberingState.getNumber(prop), "properties size");
515  scratch.clear();
516  llvm::raw_svector_ostream os(scratch);
517  sizeEmitter.writeTo(os);
518  return emit(scratch);
519  }
520 
521  EncodingEmitter emitter;
522  DialectWriter propertiesWriter(config.bytecodeVersion, emitter,
523  numberingState, stringSection,
524  config.dialectVersionMap);
525  auto iface = cast<BytecodeOpInterface>(op);
526  iface.writeProperties(propertiesWriter);
527  scratch.clear();
528  llvm::raw_svector_ostream os(scratch);
529  emitter.writeTo(os);
530  return emit(scratch);
531  }
532 
533  /// Write the current set of properties to the given emitter.
534  void write(EncodingEmitter &emitter) {
535  emitter.emitVarInt(propertiesStorage.size(), "properties size");
536  if (propertiesStorage.empty())
537  return;
538  for (const auto &storage : propertiesStorage) {
539  if (storage.empty()) {
540  emitter.emitBytes(ArrayRef<uint8_t>(), "empty properties");
541  continue;
542  }
543  emitter.emitBytes(ArrayRef(reinterpret_cast<const uint8_t *>(&storage[0]),
544  storage.size()),
545  "property");
546  }
547  }
548 
549  /// Returns true if the section is empty.
550  bool empty() { return propertiesStorage.empty(); }
551 
552 private:
553  /// Emit raw data and returns the offset in the internal buffer.
554  /// Data are deduplicated and will be copied in the internal buffer only if
555  /// they don't exist there already.
556  ssize_t emit(ArrayRef<char> rawProperties) {
557  // Populate a scratch buffer with the properties size.
558  SmallVector<char> sizeScratch;
559  {
560  EncodingEmitter sizeEmitter;
561  sizeEmitter.emitVarInt(rawProperties.size(), "properties");
562  llvm::raw_svector_ostream os(sizeScratch);
563  sizeEmitter.writeTo(os);
564  }
565  // Append a new storage to the table now.
566  size_t index = propertiesStorage.size();
567  propertiesStorage.emplace_back();
568  std::vector<char> &newStorage = propertiesStorage.back();
569  size_t propertiesSize = sizeScratch.size() + rawProperties.size();
570  newStorage.reserve(propertiesSize);
571  newStorage.insert(newStorage.end(), sizeScratch.begin(), sizeScratch.end());
572  newStorage.insert(newStorage.end(), rawProperties.begin(),
573  rawProperties.end());
574 
575  // Try to de-duplicate the new serialized properties.
576  // If the properties is a duplicate, pop it back from the storage.
577  auto inserted = propertiesUniquing.insert(
578  std::make_pair(ArrayRef<char>(newStorage), index));
579  if (!inserted.second)
580  propertiesStorage.pop_back();
581  return inserted.first->getSecond();
582  }
583 
584  /// Storage for properties.
585  std::vector<std::vector<char>> propertiesStorage;
586  SmallVector<char> scratch;
587  DenseMap<ArrayRef<char>, int64_t> propertiesUniquing;
588  IRNumberingState &numberingState;
589  StringSectionBuilder &stringSection;
591 };
592 } // namespace
593 
594 /// A simple raw_ostream wrapper around a EncodingEmitter. This removes the need
595 /// to go through an intermediate buffer when interacting with code that wants a
596 /// raw_ostream.
597 class RawEmitterOstream : public raw_ostream {
598 public:
599  explicit RawEmitterOstream(EncodingEmitter &emitter) : emitter(emitter) {
600  SetUnbuffered();
601  }
602 
603 private:
604  void write_impl(const char *ptr, size_t size) override {
605  emitter.emitBytes({reinterpret_cast<const uint8_t *>(ptr), size},
606  "raw emitter");
607  }
608  uint64_t current_pos() const override { return emitter.size(); }
609 
610  /// The section being emitted to.
611  EncodingEmitter &emitter;
612 };
613 } // namespace
614 
615 void EncodingEmitter::writeTo(raw_ostream &os) const {
616  // Reserve space in the ostream for the encoded contents.
617  os.reserveExtraSpace(size());
618 
619  for (auto &prevResult : prevResultList)
620  os.write((const char *)prevResult.data(), prevResult.size());
621  os.write((const char *)currentResult.data(), currentResult.size());
622 }
623 
624 void EncodingEmitter::emitMultiByteVarInt(uint64_t value, StringLiteral desc) {
625  // Compute the number of bytes needed to encode the value. Each byte can hold
626  // up to 7-bits of data. We only check up to the number of bits we can encode
627  // in the first byte (8).
628  uint64_t it = value >> 7;
629  for (size_t numBytes = 2; numBytes < 9; ++numBytes) {
630  if (LLVM_LIKELY(it >>= 7) == 0) {
631  uint64_t encodedValue = (value << 1) | 0x1;
632  encodedValue <<= (numBytes - 1);
633  llvm::support::ulittle64_t encodedValueLE(encodedValue);
634  emitBytes({reinterpret_cast<uint8_t *>(&encodedValueLE), numBytes}, desc);
635  return;
636  }
637  }
638 
639  // If the value is too large to encode in a single byte, emit a special all
640  // zero marker byte and splat the value directly.
641  emitByte(0, desc);
642  llvm::support::ulittle64_t valueLE(value);
643  emitBytes({reinterpret_cast<uint8_t *>(&valueLE), sizeof(valueLE)}, desc);
644 }
645 
646 //===----------------------------------------------------------------------===//
647 // Bytecode Writer
648 //===----------------------------------------------------------------------===//
649 
650 namespace {
651 class BytecodeWriter {
652 public:
653  BytecodeWriter(Operation *op, const BytecodeWriterConfig &config)
654  : numberingState(op, config), config(config.getImpl()),
655  propertiesSection(numberingState, stringSection, config.getImpl()) {}
656 
657  /// Write the bytecode for the given root operation.
658  LogicalResult write(Operation *rootOp, raw_ostream &os);
659 
660 private:
661  //===--------------------------------------------------------------------===//
662  // Dialects
663 
664  void writeDialectSection(EncodingEmitter &emitter);
665 
666  //===--------------------------------------------------------------------===//
667  // Attributes and Types
668 
669  void writeAttrTypeSection(EncodingEmitter &emitter);
670 
671  //===--------------------------------------------------------------------===//
672  // Operations
673 
674  LogicalResult writeBlock(EncodingEmitter &emitter, Block *block);
675  LogicalResult writeOp(EncodingEmitter &emitter, Operation *op);
676  LogicalResult writeRegion(EncodingEmitter &emitter, Region *region);
677  LogicalResult writeIRSection(EncodingEmitter &emitter, Operation *op);
678 
679  LogicalResult writeRegions(EncodingEmitter &emitter,
680  MutableArrayRef<Region> regions) {
681  return success(llvm::all_of(regions, [&](Region &region) {
682  return succeeded(writeRegion(emitter, &region));
683  }));
684  }
685 
686  //===--------------------------------------------------------------------===//
687  // Resources
688 
689  void writeResourceSection(Operation *op, EncodingEmitter &emitter);
690 
691  //===--------------------------------------------------------------------===//
692  // Strings
693 
694  void writeStringSection(EncodingEmitter &emitter);
695 
696  //===--------------------------------------------------------------------===//
697  // Properties
698 
699  void writePropertiesSection(EncodingEmitter &emitter);
700 
701  //===--------------------------------------------------------------------===//
702  // Helpers
703 
704  void writeUseListOrders(EncodingEmitter &emitter, uint8_t &opEncodingMask,
705  ValueRange range);
706 
707  //===--------------------------------------------------------------------===//
708  // Fields
709 
710  /// The builder used for the string section.
711  StringSectionBuilder stringSection;
712 
713  /// The IR numbering state generated for the root operation.
714  IRNumberingState numberingState;
715 
716  /// Configuration dictating bytecode emission.
718 
719  /// Storage for the properties section
720  PropertiesSectionBuilder propertiesSection;
721 };
722 } // namespace
723 
724 LogicalResult BytecodeWriter::write(Operation *rootOp, raw_ostream &os) {
725  EncodingEmitter emitter;
726 
727  // Emit the bytecode file header. This is how we identify the output as a
728  // bytecode file.
729  emitter.emitString("ML\xefR", "bytecode header");
730 
731  // Emit the bytecode version.
732  if (config.bytecodeVersion < bytecode::kMinSupportedVersion ||
733  config.bytecodeVersion > bytecode::kVersion)
734  return rootOp->emitError()
735  << "unsupported version requested " << config.bytecodeVersion
736  << ", must be in range ["
737  << static_cast<int64_t>(bytecode::kMinSupportedVersion) << ", "
738  << static_cast<int64_t>(bytecode::kVersion) << ']';
739  emitter.emitVarInt(config.bytecodeVersion, "bytecode version");
740 
741  // Emit the producer.
742  emitter.emitNulTerminatedString(config.producer, "bytecode producer");
743 
744  // Emit the dialect section.
745  writeDialectSection(emitter);
746 
747  // Emit the attributes and types section.
748  writeAttrTypeSection(emitter);
749 
750  // Emit the IR section.
751  if (failed(writeIRSection(emitter, rootOp)))
752  return failure();
753 
754  // Emit the resources section.
755  writeResourceSection(rootOp, emitter);
756 
757  // Emit the string section.
758  writeStringSection(emitter);
759 
760  // Emit the properties section.
761  if (config.bytecodeVersion >= bytecode::kNativePropertiesEncoding)
762  writePropertiesSection(emitter);
763  else if (!propertiesSection.empty())
764  return rootOp->emitError(
765  "unexpected properties emitted incompatible with bytecode <5");
766 
767  // Write the generated bytecode to the provided output stream.
768  emitter.writeTo(os);
769 
770  return success();
771 }
772 
773 //===----------------------------------------------------------------------===//
774 // Dialects
775 
776 /// Write the given entries in contiguous groups with the same parent dialect.
777 /// Each dialect sub-group is encoded with the parent dialect and number of
778 /// elements, followed by the encoding for the entries. The given callback is
779 /// invoked to encode each individual entry.
780 template <typename EntriesT, typename EntryCallbackT>
781 static void writeDialectGrouping(EncodingEmitter &emitter, EntriesT &&entries,
782  EntryCallbackT &&callback) {
783  for (auto it = entries.begin(), e = entries.end(); it != e;) {
784  auto groupStart = it++;
785 
786  // Find the end of the group that shares the same parent dialect.
787  DialectNumbering *currentDialect = groupStart->dialect;
788  it = std::find_if(it, e, [&](const auto &entry) {
789  return entry.dialect != currentDialect;
790  });
791 
792  // Emit the dialect and number of elements.
793  emitter.emitVarInt(currentDialect->number, "dialect number");
794  emitter.emitVarInt(std::distance(groupStart, it), "dialect offset");
795 
796  // Emit the entries within the group.
797  for (auto &entry : llvm::make_range(groupStart, it))
798  callback(entry);
799  }
800 }
801 
802 void BytecodeWriter::writeDialectSection(EncodingEmitter &emitter) {
803  EncodingEmitter dialectEmitter;
804 
805  // Emit the referenced dialects.
806  auto dialects = numberingState.getDialects();
807  dialectEmitter.emitVarInt(llvm::size(dialects), "dialects count");
808  for (DialectNumbering &dialect : dialects) {
809  // Write the string section and get the ID.
810  size_t nameID = stringSection.insert(dialect.name);
811 
812  if (config.bytecodeVersion < bytecode::kDialectVersioning) {
813  dialectEmitter.emitVarInt(nameID, "dialect name ID");
814  continue;
815  }
816 
817  // Try writing the version to the versionEmitter.
818  EncodingEmitter versionEmitter;
819  if (dialect.interface) {
820  // The writer used when emitting using a custom bytecode encoding.
821  DialectWriter versionWriter(config.bytecodeVersion, versionEmitter,
822  numberingState, stringSection,
823  config.dialectVersionMap);
824  dialect.interface->writeVersion(versionWriter);
825  }
826 
827  // If the version emitter is empty, version is not available. We can encode
828  // this in the dialect ID, so if there is no version, we don't write the
829  // section.
830  size_t versionAvailable = versionEmitter.size() > 0;
831  dialectEmitter.emitVarIntWithFlag(nameID, versionAvailable,
832  "dialect version");
833  if (versionAvailable)
834  dialectEmitter.emitSection(bytecode::Section::kDialectVersions,
835  std::move(versionEmitter));
836  }
837 
838  if (config.bytecodeVersion >= bytecode::kElideUnknownBlockArgLocation)
839  dialectEmitter.emitVarInt(size(numberingState.getOpNames()),
840  "op names count");
841 
842  // Emit the referenced operation names grouped by dialect.
843  auto emitOpName = [&](OpNameNumbering &name) {
844  size_t stringId = stringSection.insert(name.name.stripDialect());
845  if (config.bytecodeVersion < bytecode::kNativePropertiesEncoding)
846  dialectEmitter.emitVarInt(stringId, "dialect op name");
847  else
848  dialectEmitter.emitVarIntWithFlag(stringId, name.name.isRegistered(),
849  "dialect op name");
850  };
851  writeDialectGrouping(dialectEmitter, numberingState.getOpNames(), emitOpName);
852 
853  emitter.emitSection(bytecode::Section::kDialect, std::move(dialectEmitter));
854 }
855 
856 //===----------------------------------------------------------------------===//
857 // Attributes and Types
858 
859 void BytecodeWriter::writeAttrTypeSection(EncodingEmitter &emitter) {
860  EncodingEmitter attrTypeEmitter;
861  EncodingEmitter offsetEmitter;
862  offsetEmitter.emitVarInt(llvm::size(numberingState.getAttributes()),
863  "attributes count");
864  offsetEmitter.emitVarInt(llvm::size(numberingState.getTypes()),
865  "types count");
866 
867  // A functor used to emit an attribute or type entry.
868  uint64_t prevOffset = 0;
869  auto emitAttrOrType = [&](auto &entry) {
870  auto entryValue = entry.getValue();
871 
872  auto emitAttrOrTypeRawImpl = [&]() -> void {
873  RawEmitterOstream(attrTypeEmitter) << entryValue;
874  attrTypeEmitter.emitByte(0, "attr/type separator");
875  };
876  auto emitAttrOrTypeImpl = [&]() -> bool {
877  // TODO: We don't currently support custom encoded mutable types and
878  // attributes.
879  if (entryValue.template hasTrait<TypeTrait::IsMutable>() ||
880  entryValue.template hasTrait<AttributeTrait::IsMutable>()) {
881  emitAttrOrTypeRawImpl();
882  return false;
883  }
884 
885  DialectWriter dialectWriter(config.bytecodeVersion, attrTypeEmitter,
886  numberingState, stringSection,
887  config.dialectVersionMap);
888  if constexpr (std::is_same_v<std::decay_t<decltype(entryValue)>, Type>) {
889  for (const auto &callback : config.typeWriterCallbacks) {
890  if (succeeded(callback->write(entryValue, dialectWriter)))
891  return true;
892  }
893  if (const BytecodeDialectInterface *interface =
894  entry.dialect->interface) {
895  if (succeeded(interface->writeType(entryValue, dialectWriter)))
896  return true;
897  }
898  } else {
899  for (const auto &callback : config.attributeWriterCallbacks) {
900  if (succeeded(callback->write(entryValue, dialectWriter)))
901  return true;
902  }
903  if (const BytecodeDialectInterface *interface =
904  entry.dialect->interface) {
905  if (succeeded(interface->writeAttribute(entryValue, dialectWriter)))
906  return true;
907  }
908  }
909 
910  // If the entry was not emitted using a callback or a dialect interface,
911  // emit it using the textual format.
912  emitAttrOrTypeRawImpl();
913  return false;
914  };
915 
916  bool hasCustomEncoding = emitAttrOrTypeImpl();
917 
918  // Record the offset of this entry.
919  uint64_t curOffset = attrTypeEmitter.size();
920  offsetEmitter.emitVarIntWithFlag(curOffset - prevOffset, hasCustomEncoding,
921  "attr/type offset");
922  prevOffset = curOffset;
923  };
924 
925  // Emit the attribute and type entries for each dialect.
926  writeDialectGrouping(offsetEmitter, numberingState.getAttributes(),
927  emitAttrOrType);
928  writeDialectGrouping(offsetEmitter, numberingState.getTypes(),
929  emitAttrOrType);
930 
931  // Emit the sections to the stream.
932  emitter.emitSection(bytecode::Section::kAttrTypeOffset,
933  std::move(offsetEmitter));
934  emitter.emitSection(bytecode::Section::kAttrType, std::move(attrTypeEmitter));
935 }
936 
937 //===----------------------------------------------------------------------===//
938 // Operations
939 
940 LogicalResult BytecodeWriter::writeBlock(EncodingEmitter &emitter,
941  Block *block) {
942  ArrayRef<BlockArgument> args = block->getArguments();
943  bool hasArgs = !args.empty();
944 
945  // Emit the number of operations in this block, and if it has arguments. We
946  // use the low bit of the operation count to indicate if the block has
947  // arguments.
948  unsigned numOps = numberingState.getOperationCount(block);
949  emitter.emitVarIntWithFlag(numOps, hasArgs, "block num ops");
950 
951  // Emit the arguments of the block.
952  if (hasArgs) {
953  emitter.emitVarInt(args.size(), "block args count");
954  for (BlockArgument arg : args) {
955  Location argLoc = arg.getLoc();
956  if (config.bytecodeVersion >= bytecode::kElideUnknownBlockArgLocation) {
957  emitter.emitVarIntWithFlag(numberingState.getNumber(arg.getType()),
958  !isa<UnknownLoc>(argLoc), "block arg type");
959  if (!isa<UnknownLoc>(argLoc))
960  emitter.emitVarInt(numberingState.getNumber(argLoc),
961  "block arg location");
962  } else {
963  emitter.emitVarInt(numberingState.getNumber(arg.getType()),
964  "block arg type");
965  emitter.emitVarInt(numberingState.getNumber(argLoc),
966  "block arg location");
967  }
968  }
969  if (config.bytecodeVersion >= bytecode::kUseListOrdering) {
970  uint64_t maskOffset = emitter.size();
971  uint8_t encodingMask = 0;
972  emitter.emitByte(0, "use-list separator");
973  writeUseListOrders(emitter, encodingMask, args);
974  if (encodingMask)
975  emitter.patchByte(maskOffset, encodingMask, "block patch encoding");
976  }
977  }
978 
979  // Emit the operations within the block.
980  for (Operation &op : *block)
981  if (failed(writeOp(emitter, &op)))
982  return failure();
983  return success();
984 }
985 
986 LogicalResult BytecodeWriter::writeOp(EncodingEmitter &emitter, Operation *op) {
987  emitter.emitVarInt(numberingState.getNumber(op->getName()), "op name ID");
988 
989  // Emit a mask for the operation components. We need to fill this in later
990  // (when we actually know what needs to be emitted), so emit a placeholder for
991  // now.
992  uint64_t maskOffset = emitter.size();
993  uint8_t opEncodingMask = 0;
994  emitter.emitByte(0, "op separator");
995 
996  // Emit the location for this operation.
997  emitter.emitVarInt(numberingState.getNumber(op->getLoc()), "op location");
998 
999  // Emit the attributes of this operation.
1000  DictionaryAttr attrs = op->getDiscardableAttrDictionary();
1001  // Allow deployment to version <kNativePropertiesEncoding by merging inherent
1002  // attribute with the discardable ones. We should fail if there are any
1003  // conflicts. When properties are not used by the op, also store everything as
1004  // attributes.
1005  if (config.bytecodeVersion < bytecode::kNativePropertiesEncoding ||
1006  !op->getPropertiesStorage()) {
1007  attrs = op->getAttrDictionary();
1008  }
1009  if (!attrs.empty()) {
1010  opEncodingMask |= bytecode::OpEncodingMask::kHasAttrs;
1011  emitter.emitVarInt(numberingState.getNumber(attrs), "op attrs count");
1012  }
1013 
1014  // Emit the properties of this operation, for now we still support deployment
1015  // to version <kNativePropertiesEncoding.
1016  if (config.bytecodeVersion >= bytecode::kNativePropertiesEncoding) {
1017  std::optional<ssize_t> propertiesId = propertiesSection.emit(op);
1018  if (propertiesId.has_value()) {
1019  opEncodingMask |= bytecode::OpEncodingMask::kHasProperties;
1020  emitter.emitVarInt(*propertiesId, "op properties ID");
1021  }
1022  }
1023 
1024  // Emit the result types of the operation.
1025  if (unsigned numResults = op->getNumResults()) {
1026  opEncodingMask |= bytecode::OpEncodingMask::kHasResults;
1027  emitter.emitVarInt(numResults, "op results count");
1028  for (Type type : op->getResultTypes())
1029  emitter.emitVarInt(numberingState.getNumber(type), "op result type");
1030  }
1031 
1032  // Emit the operands of the operation.
1033  if (unsigned numOperands = op->getNumOperands()) {
1034  opEncodingMask |= bytecode::OpEncodingMask::kHasOperands;
1035  emitter.emitVarInt(numOperands, "op operands count");
1036  for (Value operand : op->getOperands())
1037  emitter.emitVarInt(numberingState.getNumber(operand), "op operand types");
1038  }
1039 
1040  // Emit the successors of the operation.
1041  if (unsigned numSuccessors = op->getNumSuccessors()) {
1042  opEncodingMask |= bytecode::OpEncodingMask::kHasSuccessors;
1043  emitter.emitVarInt(numSuccessors, "op successors count");
1044  for (Block *successor : op->getSuccessors())
1045  emitter.emitVarInt(numberingState.getNumber(successor), "op successor");
1046  }
1047 
1048  // Emit the use-list orders to bytecode, so we can reconstruct the same order
1049  // at parsing.
1050  if (config.bytecodeVersion >= bytecode::kUseListOrdering)
1051  writeUseListOrders(emitter, opEncodingMask, ValueRange(op->getResults()));
1052 
1053  // Check for regions.
1054  unsigned numRegions = op->getNumRegions();
1055  if (numRegions)
1057 
1058  // Update the mask for the operation.
1059  emitter.patchByte(maskOffset, opEncodingMask, "op encoding mask");
1060 
1061  // With the mask emitted, we can now emit the regions of the operation. We do
1062  // this after mask emission to avoid offset complications that may arise by
1063  // emitting the regions first (e.g. if the regions are huge, backpatching the
1064  // op encoding mask is more annoying).
1065  if (numRegions) {
1066  bool isIsolatedFromAbove = numberingState.isIsolatedFromAbove(op);
1067  emitter.emitVarIntWithFlag(numRegions, isIsolatedFromAbove,
1068  "op regions count");
1069 
1070  // If the region is not isolated from above, or we are emitting bytecode
1071  // targeting version <kLazyLoading, we don't use a section.
1072  if (isIsolatedFromAbove &&
1073  config.bytecodeVersion >= bytecode::kLazyLoading) {
1074  EncodingEmitter regionEmitter;
1075  if (failed(writeRegions(regionEmitter, op->getRegions())))
1076  return failure();
1077  emitter.emitSection(bytecode::Section::kIR, std::move(regionEmitter));
1078 
1079  } else if (failed(writeRegions(emitter, op->getRegions()))) {
1080  return failure();
1081  }
1082  }
1083  return success();
1084 }
1085 
1086 void BytecodeWriter::writeUseListOrders(EncodingEmitter &emitter,
1087  uint8_t &opEncodingMask,
1088  ValueRange range) {
1089  // Loop over the results and store the use-list order per result index.
1091  for (auto item : llvm::enumerate(range)) {
1092  auto value = item.value();
1093  // No need to store a custom use-list order if the result does not have
1094  // multiple uses.
1095  if (value.use_empty() || value.hasOneUse())
1096  continue;
1097 
1098  // For each result, assemble the list of pairs (use-list-index,
1099  // global-value-index). While doing so, detect if the global-value-index is
1100  // already ordered with respect to the use-list-index.
1101  bool alreadyOrdered = true;
1102  auto &firstUse = *value.use_begin();
1103  uint64_t prevID = bytecode::getUseID(
1104  firstUse, numberingState.getNumber(firstUse.getOwner()));
1106  {{0, prevID}});
1107 
1108  for (auto use : llvm::drop_begin(llvm::enumerate(value.getUses()))) {
1109  uint64_t currentID = bytecode::getUseID(
1110  use.value(), numberingState.getNumber(use.value().getOwner()));
1111  // The use-list order achieved when building the IR at parsing always
1112  // pushes new uses on front. Hence, if the order by unique ID is
1113  // monotonically decreasing, a roundtrip to bytecode preserves such order.
1114  alreadyOrdered &= (prevID > currentID);
1115  useListPairs.push_back({use.index(), currentID});
1116  prevID = currentID;
1117  }
1118 
1119  // Do not emit if the order is already sorted.
1120  if (alreadyOrdered)
1121  continue;
1122 
1123  // Sort the use indices by the unique ID indices in descending order.
1124  std::sort(
1125  useListPairs.begin(), useListPairs.end(),
1126  [](auto elem1, auto elem2) { return elem1.second > elem2.second; });
1127 
1128  map.try_emplace(item.index(), llvm::map_range(useListPairs, [](auto elem) {
1129  return elem.first;
1130  }));
1131  }
1132 
1133  if (map.empty())
1134  return;
1135 
1137  // Emit the number of results that have a custom use-list order if the number
1138  // of results is greater than one.
1139  if (range.size() != 1) {
1140  emitter.emitVarInt(map.size(), "custom use-list size");
1141  }
1142 
1143  for (const auto &item : map) {
1144  auto resultIdx = item.getFirst();
1145  auto useListOrder = item.getSecond();
1146 
1147  // Compute the number of uses that are actually shuffled. If those are less
1148  // than half of the total uses, encoding the index pair `(src, dst)` is more
1149  // space efficient.
1150  size_t shuffledElements =
1151  llvm::count_if(llvm::enumerate(useListOrder),
1152  [](auto item) { return item.index() != item.value(); });
1153  bool indexPairEncoding = shuffledElements < (useListOrder.size() / 2);
1154 
1155  // For single result, we don't need to store the result index.
1156  if (range.size() != 1)
1157  emitter.emitVarInt(resultIdx, "use-list result index");
1158 
1159  if (indexPairEncoding) {
1160  emitter.emitVarIntWithFlag(shuffledElements * 2, indexPairEncoding,
1161  "use-list index pair size");
1162  for (auto pair : llvm::enumerate(useListOrder)) {
1163  if (pair.index() != pair.value()) {
1164  emitter.emitVarInt(pair.value(), "use-list index pair first");
1165  emitter.emitVarInt(pair.index(), "use-list index pair second");
1166  }
1167  }
1168  } else {
1169  emitter.emitVarIntWithFlag(useListOrder.size(), indexPairEncoding,
1170  "use-list size");
1171  for (const auto &index : useListOrder)
1172  emitter.emitVarInt(index, "use-list order");
1173  }
1174  }
1175 }
1176 
1177 LogicalResult BytecodeWriter::writeRegion(EncodingEmitter &emitter,
1178  Region *region) {
1179  // If the region is empty, we only need to emit the number of blocks (which is
1180  // zero).
1181  if (region->empty()) {
1182  emitter.emitVarInt(/*numBlocks*/ 0, "region block count empty");
1183  return success();
1184  }
1185 
1186  // Emit the number of blocks and values within the region.
1187  unsigned numBlocks, numValues;
1188  std::tie(numBlocks, numValues) = numberingState.getBlockValueCount(region);
1189  emitter.emitVarInt(numBlocks, "region block count");
1190  emitter.emitVarInt(numValues, "region value count");
1191 
1192  // Emit the blocks within the region.
1193  for (Block &block : *region)
1194  if (failed(writeBlock(emitter, &block)))
1195  return failure();
1196  return success();
1197 }
1198 
1199 LogicalResult BytecodeWriter::writeIRSection(EncodingEmitter &emitter,
1200  Operation *op) {
1201  EncodingEmitter irEmitter;
1202 
1203  // Write the IR section the same way as a block with no arguments. Note that
1204  // the low-bit of the operation count for a block is used to indicate if the
1205  // block has arguments, which in this case is always false.
1206  irEmitter.emitVarIntWithFlag(/*numOps*/ 1, /*hasArgs*/ false, "ir section");
1207 
1208  // Emit the operations.
1209  if (failed(writeOp(irEmitter, op)))
1210  return failure();
1211 
1212  emitter.emitSection(bytecode::Section::kIR, std::move(irEmitter));
1213  return success();
1214 }
1215 
1216 //===----------------------------------------------------------------------===//
1217 // Resources
1218 
1219 namespace {
1220 /// This class represents a resource builder implementation for the MLIR
1221 /// bytecode format.
1222 class ResourceBuilder : public AsmResourceBuilder {
1223 public:
1224  using PostProcessFn = function_ref<void(StringRef, AsmResourceEntryKind)>;
1225 
1226  ResourceBuilder(EncodingEmitter &emitter, StringSectionBuilder &stringSection,
1227  PostProcessFn postProcessFn, bool shouldElideData)
1228  : emitter(emitter), stringSection(stringSection),
1229  postProcessFn(postProcessFn), shouldElideData(shouldElideData) {}
1230  ~ResourceBuilder() override = default;
1231 
1232  void buildBlob(StringRef key, ArrayRef<char> data,
1233  uint32_t dataAlignment) final {
1234  if (!shouldElideData)
1235  emitter.emitOwnedBlobAndAlignment(data, dataAlignment, "resource blob");
1236  postProcessFn(key, AsmResourceEntryKind::Blob);
1237  }
1238  void buildBool(StringRef key, bool data) final {
1239  if (!shouldElideData)
1240  emitter.emitByte(data, "resource bool");
1241  postProcessFn(key, AsmResourceEntryKind::Bool);
1242  }
1243  void buildString(StringRef key, StringRef data) final {
1244  if (!shouldElideData)
1245  emitter.emitVarInt(stringSection.insert(data), "resource string");
1246  postProcessFn(key, AsmResourceEntryKind::String);
1247  }
1248 
1249 private:
1250  EncodingEmitter &emitter;
1251  StringSectionBuilder &stringSection;
1252  PostProcessFn postProcessFn;
1253  bool shouldElideData = false;
1254 };
1255 } // namespace
1256 
1257 void BytecodeWriter::writeResourceSection(Operation *op,
1258  EncodingEmitter &emitter) {
1259  EncodingEmitter resourceEmitter;
1260  EncodingEmitter resourceOffsetEmitter;
1261  uint64_t prevOffset = 0;
1263  curResourceEntries;
1264 
1265  // Functor used to process the offset for a resource of `kind` defined by
1266  // 'key'.
1267  auto appendResourceOffset = [&](StringRef key, AsmResourceEntryKind kind) {
1268  uint64_t curOffset = resourceEmitter.size();
1269  curResourceEntries.emplace_back(key, kind, curOffset - prevOffset);
1270  prevOffset = curOffset;
1271  };
1272 
1273  // Functor used to emit a resource group defined by 'key'.
1274  auto emitResourceGroup = [&](uint64_t key) {
1275  resourceOffsetEmitter.emitVarInt(key, "resource group key");
1276  resourceOffsetEmitter.emitVarInt(curResourceEntries.size(),
1277  "resource group size");
1278  for (auto [key, kind, size] : curResourceEntries) {
1279  resourceOffsetEmitter.emitVarInt(stringSection.insert(key),
1280  "resource key");
1281  resourceOffsetEmitter.emitVarInt(size, "resource size");
1282  resourceOffsetEmitter.emitByte(kind, "resource kind");
1283  }
1284  };
1285 
1286  // Builder used to emit resources.
1287  ResourceBuilder entryBuilder(resourceEmitter, stringSection,
1288  appendResourceOffset,
1289  config.shouldElideResourceData);
1290 
1291  // Emit the external resource entries.
1292  resourceOffsetEmitter.emitVarInt(config.externalResourcePrinters.size(),
1293  "external resource printer count");
1294  for (const auto &printer : config.externalResourcePrinters) {
1295  curResourceEntries.clear();
1296  printer->buildResources(op, entryBuilder);
1297  emitResourceGroup(stringSection.insert(printer->getName()));
1298  }
1299 
1300  // Emit the dialect resource entries.
1301  for (DialectNumbering &dialect : numberingState.getDialects()) {
1302  if (!dialect.asmInterface)
1303  continue;
1304  curResourceEntries.clear();
1305  dialect.asmInterface->buildResources(op, dialect.resources, entryBuilder);
1306 
1307  // Emit the declaration resources for this dialect, these didn't get emitted
1308  // by the interface. These resources don't have data attached, so just use a
1309  // "blob" kind as a placeholder.
1310  for (const auto &resource : dialect.resourceMap)
1311  if (resource.second->isDeclaration)
1312  appendResourceOffset(resource.first, AsmResourceEntryKind::Blob);
1313 
1314  // Emit the resource group for this dialect.
1315  if (!curResourceEntries.empty())
1316  emitResourceGroup(dialect.number);
1317  }
1318 
1319  // If we didn't emit any resource groups, elide the resource sections.
1320  if (resourceOffsetEmitter.size() == 0)
1321  return;
1322 
1323  emitter.emitSection(bytecode::Section::kResourceOffset,
1324  std::move(resourceOffsetEmitter));
1325  emitter.emitSection(bytecode::Section::kResource, std::move(resourceEmitter));
1326 }
1327 
1328 //===----------------------------------------------------------------------===//
1329 // Strings
1330 
1331 void BytecodeWriter::writeStringSection(EncodingEmitter &emitter) {
1332  EncodingEmitter stringEmitter;
1333  stringSection.write(stringEmitter);
1334  emitter.emitSection(bytecode::Section::kString, std::move(stringEmitter));
1335 }
1336 
1337 //===----------------------------------------------------------------------===//
1338 // Properties
1339 
1340 void BytecodeWriter::writePropertiesSection(EncodingEmitter &emitter) {
1341  EncodingEmitter propertiesEmitter;
1342  propertiesSection.write(propertiesEmitter);
1343  emitter.emitSection(bytecode::Section::kProperties,
1344  std::move(propertiesEmitter));
1345 }
1346 
1347 //===----------------------------------------------------------------------===//
1348 // Entry Points
1349 //===----------------------------------------------------------------------===//
1350 
1351 LogicalResult mlir::writeBytecodeToFile(Operation *op, raw_ostream &os,
1352  const BytecodeWriterConfig &config) {
1353  BytecodeWriter writer(op, config);
1354  return writer.write(op, os);
1355 }
static void writeDialectGrouping(EncodingEmitter &emitter, EntriesT &&entries, EntryCallbackT &&callback)
Write the given entries in contiguous groups with the same parent dialect.
union mlir::linalg::@1179::ArityGroupAndKind::Kind kind
static Value max(ImplicitLocOpBuilder &builder, Value value, Value bound)
This class represents an opaque handle to a dialect resource entry.
This class is used to build resource entries for use by the printer.
Definition: AsmState.h:246
A class to interact with the attributes and types printer when emitting MLIR bytecode.
Attributes are known-constant values of operations.
Definition: Attributes.h:25
This class represents an argument of a Block.
Definition: Value.h:319
Block represents an ordered list of Operations.
Definition: Block.h:33
BlockArgListType getArguments()
Definition: Block.h:87
This class contains the configuration used for the bytecode writer.
void attachTypeCallback(std::unique_ptr< AttrTypeBytecodeWriter< Type >> callback)
llvm::StringMap< std::unique_ptr< DialectVersion > > & getDialectVersionMap() const
A map containing the dialect versions to emit.
void setElideResourceDataFlag(bool shouldElideResourceData=true)
Set a boolean flag to skip emission of resources into the bytecode file.
BytecodeWriterConfig(StringRef producer="MLIR" LLVM_VERSION_STRING)
producer is an optional string that can be used to identify the producer of the bytecode when reading...
void attachFallbackResourcePrinter(FallbackAsmResourceMap &map)
Attach resource printers to the AsmState for the fallback resources in the given map.
int64_t getDesiredBytecodeVersion() const
Get the set desired bytecode version to emit.
void setDialectVersion(std::unique_ptr< DialectVersion > dialectVersion) const
Set a given dialect version to emit on the map.
ArrayRef< std::unique_ptr< AttrTypeBytecodeWriter< Type > > > getTypeWriterCallbacks() const
ArrayRef< std::unique_ptr< AttrTypeBytecodeWriter< Attribute > > > getAttributeWriterCallbacks() const
Retrieve the callbacks.
void setDesiredBytecodeVersion(int64_t bytecodeVersion)
Set the desired bytecode version to emit.
void attachResourcePrinter(std::unique_ptr< AsmResourcePrinter > printer)
Attach the given resource printer to the writer configuration.
void attachAttributeCallback(std::unique_ptr< AttrTypeBytecodeWriter< Attribute >> callback)
Attach a custom bytecode printer callback to the configuration for the emission of custom type/attrib...
This class defines a virtual interface for writing to a bytecode stream, providing hooks into the byt...
A fallback map containing external resources not explicitly handled by another parser/printer.
Definition: AsmState.h:419
This class defines the main interface for locations in MLIR and acts as a non-nullable wrapper around...
Definition: Location.h:66
Operation is the basic unit of execution within MLIR.
Definition: Operation.h:88
DictionaryAttr getAttrDictionary()
Return all of the attributes on this operation as a DictionaryAttr.
Definition: Operation.cpp:296
unsigned getNumSuccessors()
Definition: Operation.h:707
bool isRegistered()
Returns true if this operation has a registered operation description, otherwise false.
Definition: Operation.h:129
unsigned getNumRegions()
Returns the number of regions held by this operation.
Definition: Operation.h:674
Location getLoc()
The source location the operation was defined or derived from.
Definition: Operation.h:223
unsigned getNumOperands()
Definition: Operation.h:346
InFlightDiagnostic emitError(const Twine &message={})
Emit an error about fatal conditions with this operation, reporting up to any diagnostic handlers tha...
Definition: Operation.cpp:268
MutableArrayRef< Region > getRegions()
Returns the regions held by this operation.
Definition: Operation.h:677
OperationName getName()
The name of an operation is the key identifier for it.
Definition: Operation.h:119
DictionaryAttr getDiscardableAttrDictionary()
Return all of the discardable attributes on this operation as a DictionaryAttr.
Definition: Operation.h:501
result_type_range getResultTypes()
Definition: Operation.h:428
operand_range getOperands()
Returns an iterator on the underlying Value's.
Definition: Operation.h:378
SuccessorRange getSuccessors()
Definition: Operation.h:704
result_range getResults()
Definition: Operation.h:415
int getPropertiesStorageSize() const
Returns the properties storage size.
Definition: Operation.h:897
OpaqueProperties getPropertiesStorage()
Returns the properties storage.
Definition: Operation.h:901
unsigned getNumResults()
Return the number of results held by this operation.
Definition: Operation.h:404
This class contains a list of basic blocks and a link to the parent operation it is attached to.
Definition: Region.h:26
bool empty()
Definition: Region.h:60
Instances of the Type class are uniqued, have an immutable identifier and an optional mutable compone...
Definition: Types.h:74
This class provides an abstraction over the different types of ranges over Values.
Definition: ValueRange.h:381
This class represents an instance of an SSA value in the MLIR system, representing a computable value...
Definition: Value.h:96
This class manages numbering IR entities in preparation of bytecode emission.
Definition: IRNumbering.h:151
@ kAttrType
This section contains the attributes and types referenced within an IR module.
Definition: Encoding.h:73
@ kAttrTypeOffset
This section contains the offsets for the attribute and types within the AttrType section.
Definition: Encoding.h:77
@ kIR
This section contains the list of operations serialized into the bytecode, and their nested regions/o...
Definition: Encoding.h:81
@ kResource
This section contains the resources of the bytecode.
Definition: Encoding.h:84
@ kResourceOffset
This section contains the offsets of resources within the Resource section.
Definition: Encoding.h:88
@ kDialect
This section contains the dialects referenced within an IR module.
Definition: Encoding.h:69
@ kString
This section contains strings referenced within the bytecode.
Definition: Encoding.h:66
@ kDialectVersions
This section contains the versions of each dialect.
Definition: Encoding.h:91
@ kProperties
This section contains the properties for the operations.
Definition: Encoding.h:94
static uint64_t getUseID(OperandT &val, unsigned ownerID)
Get the unique ID of a value use.
Definition: Encoding.h:127
@ kUseListOrdering
Use-list ordering started to be encoded in version 3.
Definition: Encoding.h:38
@ kAlignmentByte
An arbitrary value used to fill alignment padding.
Definition: Encoding.h:56
@ kVersion
The current bytecode version.
Definition: Encoding.h:53
@ kLazyLoading
Support for lazy-loading of isolated region was added in version 2.
Definition: Encoding.h:35
@ kDialectVersioning
Dialects versioning was added in version 1.
Definition: Encoding.h:32
@ kElideUnknownBlockArgLocation
Avoid recording unknown locations on block arguments (compression) started in version 4.
Definition: Encoding.h:42
@ kNativePropertiesEncoding
Support for encoding properties natively in bytecode instead of merged with the discardable attribute...
Definition: Encoding.h:46
@ kMinSupportedVersion
The minimum supported version of the bytecode.
Definition: Encoding.h:29
constexpr void enumerate(std::tuple< Tys... > &tuple, CallbackT &&callback)
Definition: Matchers.h:344
Include the generated interface declarations.
const FrozenRewritePatternSet GreedyRewriteConfig config
AsmResourceEntryKind
This enum represents the different kinds of resource values.
Definition: AsmState.h:279
@ String
A string value.
@ Bool
A boolean value.
@ Blob
A blob of data with an accompanying alignment.
LogicalResult writeBytecodeToFile(Operation *op, raw_ostream &os, const BytecodeWriterConfig &config={})
Write the bytecode for the given operation to the provided output stream.
StringRef producer
The producer of the bytecode.
llvm::StringMap< std::unique_ptr< DialectVersion > > dialectVersionMap
A map containing dialect version information for each dialect to emit.
llvm::SmallVector< std::unique_ptr< AttrTypeBytecodeWriter< Attribute > > > attributeWriterCallbacks
Printer callbacks used to emit custom type and attribute encodings.
SmallVector< std::unique_ptr< AsmResourcePrinter > > externalResourcePrinters
A collection of non-dialect resource printers.
llvm::SmallVector< std::unique_ptr< AttrTypeBytecodeWriter< Type > > > typeWriterCallbacks
This class represents a numbering entry for an Dialect.
Definition: IRNumbering.h:106
unsigned number
The number assigned to the dialect.
Definition: IRNumbering.h:114
This class represents the numbering entry of an operation name.
Definition: IRNumbering.h:65