MLIR 24.0.0git
BytecodeReader.cpp
Go to the documentation of this file.
1//===- BytecodeReader.cpp - MLIR Bytecode Reader --------------------------===//
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
14#include "mlir/IR/BuiltinOps.h"
15#include "mlir/IR/Diagnostics.h"
17#include "mlir/IR/Verifier.h"
18#include "mlir/IR/Visitors.h"
19#include "mlir/Support/LLVM.h"
20#include "llvm/ADT/ArrayRef.h"
21#include "llvm/ADT/DenseMap.h"
22#include "llvm/ADT/DenseSet.h"
23#include "llvm/ADT/STLExtras.h"
24#include "llvm/ADT/ScopeExit.h"
25#include "llvm/ADT/SmallVector.h"
26#include "llvm/ADT/StringExtras.h"
27#include "llvm/ADT/StringRef.h"
28#include "llvm/Support/Endian.h"
29#include "llvm/Support/MemoryBufferRef.h"
30#include "llvm/Support/SourceMgr.h"
31
32#include <cstddef>
33#include <cstdint>
34#include <list>
35#include <memory>
36#include <numeric>
37#include <optional>
38#include <utility>
39
40#define DEBUG_TYPE "mlir-bytecode-reader"
41
42using namespace mlir;
43
44/// Stringify the given section ID.
45static std::string toString(bytecode::Section::ID sectionID) {
46 switch (sectionID) {
48 return "String (0)";
50 return "Dialect (1)";
52 return "AttrType (2)";
54 return "AttrTypeOffset (3)";
56 return "IR (4)";
58 return "Resource (5)";
60 return "ResourceOffset (6)";
62 return "DialectVersions (7)";
64 return "Properties (8)";
65 default:
66 return ("Unknown (" + Twine(static_cast<unsigned>(sectionID)) + ")").str();
67 }
68}
69
70/// Returns true if the given top-level section ID is optional.
71static bool isSectionOptional(bytecode::Section::ID sectionID, int version) {
72 switch (sectionID) {
78 return false;
82 return true;
85 default:
86 llvm_unreachable("unknown section ID");
87 }
88}
89
90//===----------------------------------------------------------------------===//
91// EncodingReader
92//===----------------------------------------------------------------------===//
93
94namespace {
95class EncodingReader {
96public:
97 explicit EncodingReader(ArrayRef<uint8_t> contents, Location fileLoc)
98 : buffer(contents), dataIt(buffer.begin()), fileLoc(fileLoc) {}
99 explicit EncodingReader(StringRef contents, Location fileLoc)
100 : EncodingReader({reinterpret_cast<const uint8_t *>(contents.data()),
101 contents.size()},
102 fileLoc) {}
103
104 /// Returns true if the entire section has been read.
105 bool empty() const { return dataIt == buffer.end(); }
106
107 /// Returns the remaining size of the bytecode.
108 size_t size() const { return buffer.end() - dataIt; }
109
110 /// Align the current reader position to the specified alignment.
111 LogicalResult alignTo(unsigned alignment) {
112 if (!llvm::isPowerOf2_32(alignment))
113 return emitError("expected alignment to be a power-of-two");
114
115 auto isUnaligned = [&](const uint8_t *ptr) {
116 return ((uintptr_t)ptr & (alignment - 1)) != 0;
117 };
118
119 // Shift the reader position to the next alignment boundary.
120 // Note: this assumes the pointer alignment matches the alignment of the
121 // data from the start of the buffer. In other words, this code is only
122 // valid if `dataIt` is offsetting into an already aligned buffer.
123 while (isUnaligned(dataIt)) {
124 uint8_t padding;
125 if (failed(parseByte(padding)))
126 return failure();
127 if (padding != bytecode::kAlignmentByte) {
128 return emitError("expected alignment byte (0xCB), but got: '0x" +
129 llvm::utohexstr(padding) + "'");
130 }
131 }
132
133 // Ensure the data iterator is now aligned. This case is unlikely because we
134 // *just* went through the effort to align the data iterator.
135 if (LLVM_UNLIKELY(isUnaligned(dataIt))) {
136 return emitError("expected data iterator aligned to ", alignment,
137 ", but got pointer: '0x" +
138 llvm::utohexstr((uintptr_t)dataIt) + "'");
139 }
140
141 return success();
142 }
143
144 /// Emit an error using the given arguments.
145 template <typename... Args>
146 InFlightDiagnostic emitError(Args &&...args) const {
147 return ::emitError(fileLoc).append(std::forward<Args>(args)...);
148 }
149 InFlightDiagnostic emitError() const { return ::emitError(fileLoc); }
150
151 /// Emit a warning using the given arguments.
152 template <typename... Args>
153 InFlightDiagnostic emitWarning(Args &&...args) const {
154 return ::emitWarning(fileLoc).append(std::forward<Args>(args)...);
155 }
156 InFlightDiagnostic emitWarning() const { return ::emitWarning(fileLoc); }
157
158 /// Parse a single byte from the stream.
159 template <typename T>
160 LogicalResult parseByte(T &value) {
161 if (empty())
162 return emitError("attempting to parse a byte at the end of the bytecode");
163 value = static_cast<T>(*dataIt++);
164 return success();
165 }
166 /// Parse a range of bytes of 'length' into the given result.
167 LogicalResult parseBytes(size_t length, ArrayRef<uint8_t> &result) {
168 if (length > size()) {
169 return emitError("attempting to parse ", length, " bytes when only ",
170 size(), " remain");
171 }
172 result = {dataIt, length};
173 dataIt += length;
174 return success();
175 }
176 /// Parse a range of bytes of 'length' into the given result, which can be
177 /// assumed to be large enough to hold `length`.
178 LogicalResult parseBytes(size_t length, uint8_t *result) {
179 if (length > size()) {
180 return emitError("attempting to parse ", length, " bytes when only ",
181 size(), " remain");
182 }
183 memcpy(result, dataIt, length);
184 dataIt += length;
185 return success();
186 }
187
188 /// Parse an aligned blob of data, where the alignment was encoded alongside
189 /// the data.
190 LogicalResult parseBlobAndAlignment(ArrayRef<uint8_t> &data,
191 uint64_t &alignment) {
192 uint64_t dataSize;
193 if (failed(parseVarInt(alignment)) || failed(parseVarInt(dataSize)) ||
194 failed(alignTo(alignment)))
195 return failure();
196 return parseBytes(dataSize, data);
197 }
198
199 /// Parse a variable length encoded integer from the byte stream. The first
200 /// encoded byte contains a prefix in the low bits indicating the encoded
201 /// length of the value. This length prefix is a bit sequence of '0's followed
202 /// by a '1'. The number of '0' bits indicate the number of _additional_ bytes
203 /// (not including the prefix byte). All remaining bits in the first byte,
204 /// along with all of the bits in additional bytes, provide the value of the
205 /// integer encoded in little-endian order.
206 LogicalResult parseVarInt(uint64_t &result) {
207 // Parse the first byte of the encoding, which contains the length prefix.
208 if (failed(parseByte(result)))
209 return failure();
210
211 // Handle the overwhelmingly common case where the value is stored in a
212 // single byte. In this case, the first bit is the `1` marker bit.
213 if (LLVM_LIKELY(result & 1)) {
214 result >>= 1;
215 return success();
216 }
217
218 // Handle the overwhelming uncommon case where the value required all 8
219 // bytes (i.e. a really really big number). In this case, the marker byte is
220 // all zeros: `00000000`.
221 if (LLVM_UNLIKELY(result == 0)) {
222 llvm::support::ulittle64_t resultLE;
223 if (failed(parseBytes(sizeof(resultLE),
224 reinterpret_cast<uint8_t *>(&resultLE))))
225 return failure();
226 result = resultLE;
227 return success();
228 }
229 return parseMultiByteVarInt(result);
230 }
231
232 /// Parse a signed variable length encoded integer from the byte stream. A
233 /// signed varint is encoded as a normal varint with zigzag encoding applied,
234 /// i.e. the low bit of the value is used to indicate the sign.
235 LogicalResult parseSignedVarInt(uint64_t &result) {
236 if (failed(parseVarInt(result)))
237 return failure();
238 // Essentially (but using unsigned): (x >> 1) ^ -(x & 1)
239 result = (result >> 1) ^ (~(result & 1) + 1);
240 return success();
241 }
242
243 /// Parse a variable length encoded integer whose low bit is used to encode an
244 /// unrelated flag, i.e: `(integerValue << 1) | (flag ? 1 : 0)`.
245 LogicalResult parseVarIntWithFlag(uint64_t &result, bool &flag) {
246 if (failed(parseVarInt(result)))
247 return failure();
248 flag = result & 1;
249 result >>= 1;
250 return success();
251 }
252
253 /// Skip the first `length` bytes within the reader.
254 LogicalResult skipBytes(size_t length) {
255 if (length > size()) {
256 return emitError("attempting to skip ", length, " bytes when only ",
257 size(), " remain");
258 }
259 dataIt += length;
260 return success();
261 }
262
263 /// Parse a null-terminated string into `result` (without including the NUL
264 /// terminator).
265 LogicalResult parseNullTerminatedString(StringRef &result) {
266 const char *startIt = (const char *)dataIt;
267 const char *nulIt = (const char *)memchr(startIt, 0, size());
268 if (!nulIt)
269 return emitError(
270 "malformed null-terminated string, no null character found");
271
272 result = StringRef(startIt, nulIt - startIt);
273 dataIt = (const uint8_t *)nulIt + 1;
274 return success();
275 }
276
277 /// Validate that the alignment requested in the section is valid.
278 using ValidateAlignmentFn = function_ref<LogicalResult(unsigned alignment)>;
279
280 /// Parse a section header, placing the kind of section in `sectionID` and the
281 /// contents of the section in `sectionData`.
282 LogicalResult parseSection(bytecode::Section::ID &sectionID,
283 ValidateAlignmentFn alignmentValidator,
284 ArrayRef<uint8_t> &sectionData) {
285 uint8_t sectionIDAndHasAlignment;
286 uint64_t length;
287 if (failed(parseByte(sectionIDAndHasAlignment)) ||
288 failed(parseVarInt(length)))
289 return failure();
290
291 // Extract the section ID and whether the section is aligned. The high bit
292 // of the ID is the alignment flag.
293 sectionID = static_cast<bytecode::Section::ID>(sectionIDAndHasAlignment &
294 0b01111111);
295 bool hasAlignment = sectionIDAndHasAlignment & 0b10000000;
296
297 // Check that the section is actually valid before trying to process its
298 // data.
299 if (sectionID >= bytecode::Section::kNumSections)
300 return emitError("invalid section ID: ", unsigned(sectionID));
301
302 // Process the section alignment if present.
303 if (hasAlignment) {
304 // Read the requested alignment from the bytecode parser.
305 uint64_t alignment;
306 if (failed(parseVarInt(alignment)))
307 return failure();
308
309 // Check that the requested alignment must not exceed the alignment of
310 // the root buffer itself. Otherwise we cannot guarantee that pointers
311 // derived from this buffer will actually satisfy the requested alignment
312 // globally.
313 //
314 // Consider a bytecode buffer that is guaranteed to be 8k aligned, but not
315 // 16k aligned (e.g. absolute address 40960. If a section inside this
316 // buffer declares a 16k alignment requirement, two problems can arise:
317 //
318 // (a) If we "align forward" the current pointer to the next
319 // 16k boundary, the amount of padding we skip depends on the
320 // buffer's starting address. For example:
321 //
322 // buffer_start = 40960
323 // next 16k boundary = 49152
324 // bytes skipped = 49152 - 40960 = 8192
325 //
326 // This leaves behind variable padding that could be misinterpreted
327 // as part of the next section.
328 //
329 // (b) If we align relative to the buffer start, we may
330 // obtain addresses that are multiples of "buffer_start +
331 // section_alignment" rather than truly globally aligned
332 // addresses. For example:
333 //
334 // buffer_start = 40960 (5×8k, 8k aligned but not 16k)
335 // offset = 16384 (first multiple of 16k)
336 // section_ptr = 40960 + 16384 = 57344
337 //
338 // 57344 is 8k aligned but not 16k aligned.
339 // Any consumer expecting true 16k alignment would see this as a
340 // violation.
341 if (failed(alignmentValidator(alignment)))
342 return emitError("failed to align section ID: ", unsigned(sectionID));
343
344 // Align the buffer.
345 if (failed(alignTo(alignment)))
346 return failure();
347 }
348
349 // Parse the actual section data.
350 return parseBytes(static_cast<size_t>(length), sectionData);
351 }
352
353 Location getLoc() const { return fileLoc; }
354
355private:
356 /// Parse a variable length encoded integer from the byte stream. This method
357 /// is a fallback when the number of bytes used to encode the value is greater
358 /// than 1, but less than the max (9). The provided `result` value can be
359 /// assumed to already contain the first byte of the value.
360 /// NOTE: This method is marked noinline to avoid pessimizing the common case
361 /// of single byte encoding.
362 LLVM_ATTRIBUTE_NOINLINE LogicalResult parseMultiByteVarInt(uint64_t &result) {
363 // Count the number of trailing zeros in the marker byte, this indicates the
364 // number of trailing bytes that are part of the value. We use `uint32_t`
365 // here because we only care about the first byte, and so that be actually
366 // get ctz intrinsic calls when possible (the `uint8_t` overload uses a loop
367 // implementation).
368 uint32_t numBytes = llvm::countr_zero<uint32_t>(result);
369 assert(numBytes > 0 && numBytes <= 7 &&
370 "unexpected number of trailing zeros in varint encoding");
371
372 // Parse in the remaining bytes of the value.
373 llvm::support::ulittle64_t resultLE(result);
374 if (failed(
375 parseBytes(numBytes, reinterpret_cast<uint8_t *>(&resultLE) + 1)))
376 return failure();
377
378 // Shift out the low-order bits that were used to mark how the value was
379 // encoded.
380 result = resultLE >> (numBytes + 1);
381 return success();
382 }
383
384 /// The bytecode buffer.
385 ArrayRef<uint8_t> buffer;
386
387 /// The current iterator within the 'buffer'.
388 const uint8_t *dataIt;
389
390 /// A location for the bytecode used to report errors.
391 Location fileLoc;
392};
393} // namespace
394
395/// Resolve an index into the given entry list. `entry` may either be a
396/// reference, in which case it is assigned to the corresponding value in
397/// `entries`, or a pointer, in which case it is assigned to the address of the
398/// element in `entries`.
399template <typename RangeT, typename T>
400static LogicalResult resolveEntry(EncodingReader &reader, RangeT &entries,
401 uint64_t index, T &entry,
402 StringRef entryStr) {
403 if (index >= entries.size())
404 return reader.emitError("invalid ", entryStr, " index: ", index);
405
406 // If the provided entry is a pointer, resolve to the address of the entry.
407 if constexpr (std::is_convertible_v<llvm::detail::ValueOfRange<RangeT>, T>)
408 entry = entries[index];
409 else
410 entry = &entries[index];
411 return success();
412}
413
414/// Parse and resolve an index into the given entry list.
415template <typename RangeT, typename T>
416static LogicalResult parseEntry(EncodingReader &reader, RangeT &entries,
417 T &entry, StringRef entryStr) {
418 uint64_t entryIdx;
419 if (failed(reader.parseVarInt(entryIdx)))
420 return failure();
421 return resolveEntry(reader, entries, entryIdx, entry, entryStr);
422}
423
424//===----------------------------------------------------------------------===//
425// StringSectionReader
426//===----------------------------------------------------------------------===//
427
428namespace {
429/// This class is used to read references to the string section from the
430/// bytecode.
431class StringSectionReader {
432public:
433 /// Initialize the string section reader with the given section data.
434 LogicalResult initialize(Location fileLoc, ArrayRef<uint8_t> sectionData);
435
436 /// Parse a shared string from the string section. The shared string is
437 /// encoded using an index to a corresponding string in the string section.
438 LogicalResult parseString(EncodingReader &reader, StringRef &result) const {
439 return parseEntry(reader, strings, result, "string");
440 }
441
442 /// Parse a shared string from the string section. The shared string is
443 /// encoded using an index to a corresponding string in the string section.
444 /// This variant parses a flag compressed with the index.
445 LogicalResult parseStringWithFlag(EncodingReader &reader, StringRef &result,
446 bool &flag) const {
447 uint64_t entryIdx;
448 if (failed(reader.parseVarIntWithFlag(entryIdx, flag)))
449 return failure();
450 return parseStringAtIndex(reader, entryIdx, result);
451 }
452
453 /// Parse a shared string from the string section. The shared string is
454 /// encoded using an index to a corresponding string in the string section.
455 LogicalResult parseStringAtIndex(EncodingReader &reader, uint64_t index,
456 StringRef &result) const {
457 return resolveEntry(reader, strings, index, result, "string");
458 }
459
460private:
461 /// The table of strings referenced within the bytecode file.
462 SmallVector<StringRef> strings;
463};
464} // namespace
465
466LogicalResult StringSectionReader::initialize(Location fileLoc,
467 ArrayRef<uint8_t> sectionData) {
468 EncodingReader stringReader(sectionData, fileLoc);
469
470 // Parse the number of strings in the section.
471 uint64_t numStrings;
472 if (failed(stringReader.parseVarInt(numStrings)))
473 return failure();
474 strings.resize(numStrings);
475
476 // Parse each of the strings. The sizes of the strings are encoded in reverse
477 // order, so that's the order we populate the table.
478 size_t stringDataEndOffset = sectionData.size();
479 for (StringRef &string : llvm::reverse(strings)) {
480 uint64_t stringSize;
481 if (failed(stringReader.parseVarInt(stringSize)))
482 return failure();
483 if (stringDataEndOffset < stringSize) {
484 return stringReader.emitError(
485 "string size exceeds the available data size");
486 }
487
488 // Extract the string from the data, dropping the null character.
489 size_t stringOffset = stringDataEndOffset - stringSize;
490 string = StringRef(
491 reinterpret_cast<const char *>(sectionData.data() + stringOffset),
492 stringSize - 1);
493 stringDataEndOffset = stringOffset;
494 }
495
496 // Check that the only remaining data was for the strings, i.e. the reader
497 // should be at the same offset as the first string.
498 if ((sectionData.size() - stringReader.size()) != stringDataEndOffset) {
499 return stringReader.emitError("unexpected trailing data between the "
500 "offsets for strings and their data");
501 }
502 return success();
503}
504
505//===----------------------------------------------------------------------===//
506// BytecodeDialect
507//===----------------------------------------------------------------------===//
508
509namespace {
510class DialectReader;
511
512/// This struct represents a dialect entry within the bytecode.
513struct BytecodeDialect {
514 /// Load the dialect into the provided context if it hasn't been loaded yet.
515 /// Returns failure if the dialect couldn't be loaded *and* the provided
516 /// context does not allow unregistered dialects. The provided reader is used
517 /// for error emission if necessary.
518 LogicalResult load(const DialectReader &reader, MLIRContext *ctx);
519
520 /// Return the loaded dialect, or nullptr if the dialect is unknown. This can
521 /// only be called after `load`.
522 Dialect *getLoadedDialect() const {
523 assert(dialect &&
524 "expected `load` to be invoked before `getLoadedDialect`");
525 return *dialect;
526 }
527
528 /// The loaded dialect entry. This field is std::nullopt if we haven't
529 /// attempted to load, nullptr if we failed to load, otherwise the loaded
530 /// dialect.
531 std::optional<Dialect *> dialect;
532
533 /// The bytecode interface of the dialect, or nullptr if the dialect does not
534 /// implement the bytecode interface. This field should only be checked if the
535 /// `dialect` field is not std::nullopt.
536 const BytecodeDialectInterface *interface = nullptr;
537
538 /// The name of the dialect.
539 StringRef name;
540
541 /// A buffer containing the encoding of the dialect version parsed.
542 ArrayRef<uint8_t> versionBuffer;
543
544 /// Lazy loaded dialect version from the handle above.
545 std::unique_ptr<DialectVersion> loadedVersion;
546};
547
548/// This struct represents an operation name entry within the bytecode.
549struct BytecodeOperationName {
550 BytecodeOperationName(BytecodeDialect *dialect, StringRef name,
551 std::optional<bool> wasRegistered)
552 : dialect(dialect), name(name), wasRegistered(wasRegistered) {}
553
554 /// The loaded operation name, or std::nullopt if it hasn't been processed
555 /// yet.
556 std::optional<OperationName> opName;
557
558 /// The dialect that owns this operation name.
559 BytecodeDialect *dialect;
560
561 /// The name of the operation, without the dialect prefix.
562 StringRef name;
563
564 /// Whether this operation was registered when the bytecode was produced.
565 /// This flag is populated when bytecode version >=kNativePropertiesEncoding.
566 std::optional<bool> wasRegistered;
567};
568} // namespace
569
570/// Parse a single dialect group encoded in the byte stream.
571static LogicalResult parseDialectGrouping(
572 EncodingReader &reader,
573 MutableArrayRef<std::unique_ptr<BytecodeDialect>> dialects,
574 function_ref<LogicalResult(BytecodeDialect *)> entryCallback) {
575 // Parse the dialect and the number of entries in the group.
576 std::unique_ptr<BytecodeDialect> *dialect;
577 if (failed(parseEntry(reader, dialects, dialect, "dialect")))
578 return failure();
579 uint64_t numEntries;
580 if (failed(reader.parseVarInt(numEntries)))
581 return failure();
582
583 for (uint64_t i = 0; i < numEntries; ++i)
584 if (failed(entryCallback(dialect->get())))
585 return failure();
586 return success();
587}
588
589//===----------------------------------------------------------------------===//
590// ResourceSectionReader
591//===----------------------------------------------------------------------===//
592
593namespace {
594/// This class is used to read the resource section from the bytecode.
595class ResourceSectionReader {
596public:
597 /// Initialize the resource section reader with the given section data.
598 LogicalResult
599 initialize(Location fileLoc, const ParserConfig &config,
600 MutableArrayRef<std::unique_ptr<BytecodeDialect>> dialects,
601 StringSectionReader &stringReader, ArrayRef<uint8_t> sectionData,
602 ArrayRef<uint8_t> offsetSectionData, DialectReader &dialectReader,
603 const std::shared_ptr<llvm::SourceMgr> &bufferOwnerRef);
604
605 /// Parse a dialect resource handle from the resource section.
606 LogicalResult parseResourceHandle(EncodingReader &reader,
607 AsmDialectResourceHandle &result) const {
608 return parseEntry(reader, dialectResources, result, "resource handle");
609 }
610
611private:
612 /// The table of dialect resources within the bytecode file.
613 SmallVector<AsmDialectResourceHandle> dialectResources;
614 llvm::StringMap<std::string> dialectResourceHandleRenamingMap;
615};
616
617class ParsedResourceEntry : public AsmParsedResourceEntry {
618public:
619 ParsedResourceEntry(StringRef key, AsmResourceEntryKind kind,
620 EncodingReader &reader, StringSectionReader &stringReader,
621 const std::shared_ptr<llvm::SourceMgr> &bufferOwnerRef)
622 : key(key), kind(kind), reader(reader), stringReader(stringReader),
623 bufferOwnerRef(bufferOwnerRef) {}
624 ~ParsedResourceEntry() override = default;
625
626 StringRef getKey() const final { return key; }
627
628 InFlightDiagnostic emitError() const final { return reader.emitError(); }
629
630 AsmResourceEntryKind getKind() const final { return kind; }
631
632 FailureOr<bool> parseAsBool() const final {
633 if (kind != AsmResourceEntryKind::Bool)
634 return emitError() << "expected a bool resource entry, but found a "
635 << toString(kind) << " entry instead";
636
637 bool value;
638 if (failed(reader.parseByte(value)))
639 return failure();
640 return value;
641 }
642 FailureOr<std::string> parseAsString() const final {
643 if (kind != AsmResourceEntryKind::String)
644 return emitError() << "expected a string resource entry, but found a "
645 << toString(kind) << " entry instead";
646
647 StringRef string;
648 if (failed(stringReader.parseString(reader, string)))
649 return failure();
650 return string.str();
651 }
652
653 FailureOr<AsmResourceBlob>
654 parseAsBlob(BlobAllocatorFn allocator) const final {
655 if (kind != AsmResourceEntryKind::Blob)
656 return emitError() << "expected a blob resource entry, but found a "
657 << toString(kind) << " entry instead";
658
659 ArrayRef<uint8_t> data;
660 uint64_t alignment;
661 if (failed(reader.parseBlobAndAlignment(data, alignment)))
662 return failure();
663
664 // If we have an extendable reference to the buffer owner, we don't need to
665 // allocate a new buffer for the data, and can use the data directly.
666 if (bufferOwnerRef) {
667 ArrayRef<char> charData(reinterpret_cast<const char *>(data.data()),
668 data.size());
669
670 // Allocate an unmanager buffer which captures a reference to the owner.
671 // For now we just mark this as immutable, but in the future we should
672 // explore marking this as mutable when desired.
674 charData, alignment,
675 [bufferOwnerRef = bufferOwnerRef](void *, size_t, size_t) {});
676 }
677
678 // Allocate memory for the blob using the provided allocator and copy the
679 // data into it.
680 AsmResourceBlob blob = allocator(data.size(), alignment);
681 assert(llvm::isAddrAligned(llvm::Align(alignment), blob.getData().data()) &&
682 blob.isMutable() &&
683 "blob allocator did not return a properly aligned address");
684 memcpy(blob.getMutableData().data(), data.data(), data.size());
685 return blob;
686 }
687
688private:
689 StringRef key;
691 EncodingReader &reader;
692 StringSectionReader &stringReader;
693 const std::shared_ptr<llvm::SourceMgr> &bufferOwnerRef;
694};
695} // namespace
696
697template <typename T>
698static LogicalResult
699parseResourceGroup(Location fileLoc, bool allowEmpty,
700 EncodingReader &offsetReader, EncodingReader &resourceReader,
701 StringSectionReader &stringReader, T *handler,
702 const std::shared_ptr<llvm::SourceMgr> &bufferOwnerRef,
703 function_ref<StringRef(StringRef)> remapKey = {},
704 function_ref<LogicalResult(StringRef)> processKeyFn = {}) {
705 uint64_t numResources;
706 if (failed(offsetReader.parseVarInt(numResources)))
707 return failure();
708
709 for (uint64_t i = 0; i < numResources; ++i) {
710 StringRef key;
712 uint64_t resourceOffset;
713 ArrayRef<uint8_t> data;
714 if (failed(stringReader.parseString(offsetReader, key)) ||
715 failed(offsetReader.parseVarInt(resourceOffset)) ||
716 failed(offsetReader.parseByte(kind)) ||
717 failed(resourceReader.parseBytes(resourceOffset, data)))
718 return failure();
719
720 // Process the resource key.
721 if ((processKeyFn && failed(processKeyFn(key))))
722 return failure();
723
724 // If the resource data is empty and we allow it, don't error out when
725 // parsing below, just skip it.
726 if (allowEmpty && data.empty())
727 continue;
728
729 // Ignore the entry if we don't have a valid handler.
730 if (!handler)
731 continue;
732
733 // Otherwise, parse the resource value.
734 EncodingReader entryReader(data, fileLoc);
735 key = remapKey(key);
736 ParsedResourceEntry entry(key, kind, entryReader, stringReader,
737 bufferOwnerRef);
738 if (failed(handler->parseResource(entry)))
739 return failure();
740 if (!entryReader.empty()) {
741 return entryReader.emitError(
742 "unexpected trailing bytes in resource entry '", key, "'");
743 }
744 }
745 return success();
746}
747
748LogicalResult ResourceSectionReader::initialize(
749 Location fileLoc, const ParserConfig &config,
750 MutableArrayRef<std::unique_ptr<BytecodeDialect>> dialects,
751 StringSectionReader &stringReader, ArrayRef<uint8_t> sectionData,
752 ArrayRef<uint8_t> offsetSectionData, DialectReader &dialectReader,
753 const std::shared_ptr<llvm::SourceMgr> &bufferOwnerRef) {
754 EncodingReader resourceReader(sectionData, fileLoc);
755 EncodingReader offsetReader(offsetSectionData, fileLoc);
756
757 // Read the number of external resource providers.
758 uint64_t numExternalResourceGroups;
759 if (failed(offsetReader.parseVarInt(numExternalResourceGroups)))
760 return failure();
761
762 // Utility functor that dispatches to `parseResourceGroup`, but implicitly
763 // provides most of the arguments.
764 auto parseGroup = [&](auto *handler, bool allowEmpty = false,
765 function_ref<LogicalResult(StringRef)> keyFn = {}) {
766 auto resolveKey = [&](StringRef key) -> StringRef {
767 auto it = dialectResourceHandleRenamingMap.find(key);
768 if (it == dialectResourceHandleRenamingMap.end())
769 return key;
770 return it->second;
771 };
772
773 return parseResourceGroup(fileLoc, allowEmpty, offsetReader, resourceReader,
774 stringReader, handler, bufferOwnerRef, resolveKey,
775 keyFn);
776 };
777
778 // Read the external resources from the bytecode.
779 for (uint64_t i = 0; i < numExternalResourceGroups; ++i) {
780 StringRef key;
781 if (failed(stringReader.parseString(offsetReader, key)))
782 return failure();
783
784 // Get the handler for these resources.
785 // TODO: Should we require handling external resources in some scenarios?
786 AsmResourceParser *handler = config.getResourceParser(key);
787 if (!handler) {
788 emitWarning(fileLoc) << "ignoring unknown external resources for '" << key
789 << "'";
790 }
791
792 if (failed(parseGroup(handler)))
793 return failure();
794 }
795
796 // Read the dialect resources from the bytecode.
797 MLIRContext *ctx = fileLoc->getContext();
798 while (!offsetReader.empty()) {
799 std::unique_ptr<BytecodeDialect> *dialect;
800 if (failed(parseEntry(offsetReader, dialects, dialect, "dialect")) ||
801 failed((*dialect)->load(dialectReader, ctx)))
802 return failure();
803 Dialect *loadedDialect = (*dialect)->getLoadedDialect();
804 if (!loadedDialect) {
805 return resourceReader.emitError()
806 << "dialect '" << (*dialect)->name << "' is unknown";
807 }
808 const auto *handler = dyn_cast<OpAsmDialectInterface>(loadedDialect);
809 if (!handler) {
810 return resourceReader.emitError()
811 << "unexpected resources for dialect '" << (*dialect)->name << "'";
812 }
813
814 // Ensure that each resource is declared before being processed.
815 auto processResourceKeyFn = [&](StringRef key) -> LogicalResult {
816 FailureOr<AsmDialectResourceHandle> handle =
817 handler->declareResource(key);
818 if (failed(handle)) {
819 return resourceReader.emitError()
820 << "unknown 'resource' key '" << key << "' for dialect '"
821 << (*dialect)->name << "'";
822 }
823 dialectResourceHandleRenamingMap[key] = handler->getResourceKey(*handle);
824 dialectResources.push_back(*handle);
825 return success();
826 };
827
828 // Parse the resources for this dialect. We allow empty resources because we
829 // just treat these as declarations.
830 if (failed(parseGroup(handler, /*allowEmpty=*/true, processResourceKeyFn)))
831 return failure();
832 }
833
834 return success();
835}
836
837//===----------------------------------------------------------------------===//
838// Attribute/Type Reader
839//===----------------------------------------------------------------------===//
840
841namespace {
842/// This class provides support for reading attribute and type entries from the
843/// bytecode. Attribute and Type entries are read lazily on demand, so we use
844/// this reader to manage when to actually parse them from the bytecode.
845///
846/// The parsing of attributes & types are generally recursive, this can lead to
847/// stack overflows for deeply nested structures, so we track a few extra pieces
848/// of information to avoid this:
849///
850/// - `depth`: The current depth while parsing nested attributes. We defer on
851/// parsing deeply nested attributes to avoid potential stack overflows. The
852/// deferred parsing is achieved by reporting a failure when parsing a nested
853/// attribute/type and registering the index of the encountered attribute/type
854/// in the deferred parsing worklist. Hence, a failure with deffered entry
855/// does not constitute a failure, it also requires that folks return on
856/// first failure rather than attempting additional parses.
857/// - `deferredWorklist`: A list of attribute/type indices that we could not
858/// parse due to hitting the depth limit. The worklist is used to capture the
859/// indices of attributes/types that need to be parsed/reparsed when we hit
860/// the depth limit. This enables moving the tracking of what needs to be
861/// parsed to the heap.
862class AttrTypeReader {
863 /// This class represents a single attribute or type entry.
864 template <typename T>
865 struct Entry {
866 /// The entry, or null if it hasn't been resolved yet.
867 T entry = {};
868 /// The parent dialect of this entry.
869 BytecodeDialect *dialect = nullptr;
870 /// A flag indicating if the entry was encoded using a custom encoding,
871 /// instead of using the textual assembly format.
872 bool hasCustomEncoding = false;
873 /// Index of the next custom reader callback to try; callbacks before this
874 /// index already fell through on an earlier attempt.
875 size_t nextCallbackIndex = 0;
876 /// The raw data of this entry in the bytecode.
877 ArrayRef<uint8_t> data;
878 };
879 using AttrEntry = Entry<Attribute>;
880 using TypeEntry = Entry<Type>;
881
882public:
883 AttrTypeReader(const StringSectionReader &stringReader,
884 const ResourceSectionReader &resourceReader,
885 const llvm::StringMap<BytecodeDialect *> &dialectsMap,
886 uint64_t &bytecodeVersion, Location fileLoc,
887 const ParserConfig &config)
888 : stringReader(stringReader), resourceReader(resourceReader),
889 dialectsMap(dialectsMap), fileLoc(fileLoc),
890 bytecodeVersion(bytecodeVersion), parserConfig(config) {}
891
892 /// Initialize the attribute and type information within the reader.
893 LogicalResult
894 initialize(MutableArrayRef<std::unique_ptr<BytecodeDialect>> dialects,
895 ArrayRef<uint8_t> sectionData,
896 ArrayRef<uint8_t> offsetSectionData);
897
898 LogicalResult readAttribute(uint64_t index, Attribute &result,
899 uint64_t depth = 0) {
900 return readEntry(attributes, index, result, "attribute", depth);
901 }
902
903 LogicalResult readType(uint64_t index, Type &result, uint64_t depth = 0) {
904 return readEntry(types, index, result, "type", depth);
905 }
906
907 /// Resolve the attribute or type at the given index. Returns nullptr on
908 /// failure.
909 Attribute resolveAttribute(size_t index) {
910 return resolveEntry(attributes, index, "Attribute");
911 }
912 Type resolveType(size_t index) { return resolveEntry(types, index, "Type"); }
913
914 Attribute getAttributeOrSentinel(size_t index) {
915 if (index >= attributes.size())
916 return nullptr;
917 return attributes[index].entry;
918 }
919 Type getTypeOrSentinel(size_t index) {
920 if (index >= types.size())
921 return nullptr;
922 return types[index].entry;
923 }
924
925 /// Parse a reference to an attribute or type using the given reader.
926 LogicalResult parseAttribute(EncodingReader &reader, Attribute &result) {
927 uint64_t attrIdx;
928 if (failed(reader.parseVarInt(attrIdx)))
929 return failure();
930 result = resolveAttribute(attrIdx);
931 return success(!!result);
932 }
933
934 LogicalResult parseType(EncodingReader &reader, Type &result) {
935 uint64_t typeIdx;
936 if (failed(reader.parseVarInt(typeIdx)))
937 return failure();
938 result = resolveType(typeIdx);
939 return success(!!result);
940 }
941
942 template <typename T>
943 LogicalResult parseAttribute(EncodingReader &reader, T &result) {
944 Attribute baseResult;
945 if (failed(parseAttribute(reader, baseResult)))
946 return failure();
947 if ((result = dyn_cast<T>(baseResult)))
948 return success();
949 return reader.emitError("expected attribute of type: ",
950 llvm::getTypeName<T>(), ", but got: ", baseResult);
951 }
952
953 /// The kind of entry being parsed.
954 enum class EntryKind { Attribute, Type };
955 using WorklistEntry = std::pair<uint64_t, EntryKind>;
956
957 /// Add an index to the deferred worklist for re-parsing.
958 void addDeferredParsing(uint64_t index, EntryKind kind) {
959 deferredWorklist.emplace_back(index, kind);
960 }
961
962 /// Whether currently resolving.
963 bool isResolving() const { return resolving; }
964
965 /// Register `type` as the partial result of the type entry at `index`. The
966 /// partial stays visible to nested reads until the entry finishes parsing (or
967 /// the top-level resolve ends on error). Re-publishing the same instance
968 /// succeeds because deferred entries re-run the dialect reader. Returns the
969 /// bound instance for `index` so the caller can detect conflicts.
970 Type publishPartialType(uint64_t index, Type type) {
971 auto [it, inserted] = partialTypes.try_emplace(index, type);
972 if (inserted) {
973 partialHistory.push_back(index);
974 ++progressGeneration;
975 }
976 return it->second;
977 }
978
979 /// Return the incomplete type published for `index`, or null if none is
980 /// currently active. Consumers may hold this instance safely because the type
981 /// is mutable with stable identity: completing the entry mutates the same
982 /// instance in place before any non-cyclic dependent entry finishes.
983 Type getPartialType(uint64_t index) const {
984 return partialTypes.lookup(index);
985 }
986
987private:
988 /// Snapshot of speculative state recorded before trying a reader callback.
989 struct RollbackPoint {
990 size_t deferredWorklistSize;
991 size_t partialHistorySize;
992 uint64_t resolvedCount;
993 };
994
995 /// Post-order DFS worklist that deduplicates queued entries and supports O(1)
996 /// splicing of dependencies ahead of their dependents.
997 class AttrTypeWorklist {
998 public:
999 bool empty() const { return entries.empty(); }
1000
1001 void pushFront(WorklistEntry entry) {
1002 auto [it, inserted] = positions.try_emplace(entry);
1003 if (inserted)
1004 it->second = entries.insert(entries.begin(), entry);
1005 else
1006 entries.splice(entries.begin(), entries, it->second);
1007 }
1008
1009 void pushBack(WorklistEntry entry) {
1010 auto [it, inserted] = positions.try_emplace(entry);
1011 if (inserted)
1012 it->second = entries.insert(entries.end(), entry);
1013 }
1014
1015 WorklistEntry popFront() {
1016 assert(!empty() && "cannot pop from an empty worklist");
1017 WorklistEntry front = entries.front();
1018 positions.erase(front);
1019 entries.pop_front();
1020 return front;
1021 }
1022
1023 private:
1024 std::list<WorklistEntry> entries;
1025 DenseMap<WorklistEntry, std::list<WorklistEntry>::iterator> positions;
1026 };
1027
1028 /// Return whether any partial type published at or after
1029 /// `partialHistory[start]` is still live.
1030 bool hasLivePartialSince(size_t start) const {
1031 return llvm::any_of(
1032 ArrayRef(partialHistory).drop_front(start),
1033 [&](uint64_t idx) { return partialTypes.contains(idx); });
1034 }
1035
1036 void eraseUncommittedPartialType(uint64_t index) {
1037 if (partialTypes.erase(index))
1038 --progressGeneration;
1039 }
1040
1041 RollbackPoint saveRollbackPoint() const {
1042 return {deferredWorklist.size(), partialHistory.size(), resolvedCount};
1043 }
1044
1045 void restoreRollbackPoint(RollbackPoint point) {
1046 deferredWorklist.resize(point.deferredWorklistSize);
1047 while (partialHistory.size() > point.partialHistorySize) {
1048 uint64_t idx = partialHistory.pop_back_val();
1049 if (!types[idx].entry)
1050 eraseUncommittedPartialType(idx);
1051 }
1052 }
1053
1054 /// Resolve the given entry at `index`.
1055 template <typename T>
1056 T resolveEntry(SmallVectorImpl<Entry<T>> &entries, uint64_t index,
1057 StringRef entryType);
1058
1059 /// Read the entry at the given index, returning failure if the entry is not
1060 /// yet resolved.
1061 template <typename T>
1062 LogicalResult readEntry(SmallVectorImpl<Entry<T>> &entries, uint64_t index,
1063 T &result, StringRef entryType, uint64_t depth);
1064
1065 /// Parse an entry using the given reader that was encoded using a custom
1066 /// bytecode format.
1067 template <typename T>
1068 LogicalResult parseCustomEntry(Entry<T> &entry, EncodingReader &reader,
1069 uint64_t index, uint64_t depth, T &result);
1070
1071 /// Parse an entry using the given reader that was encoded using the textual
1072 /// assembly format.
1073 template <typename T>
1074 LogicalResult parseAsmEntry(T &result, EncodingReader &reader,
1075 StringRef entryType);
1076
1077 /// The string section reader used to resolve string references when parsing
1078 /// custom encoded attribute/type entries.
1079 const StringSectionReader &stringReader;
1080
1081 /// The resource section reader used to resolve resource references when
1082 /// parsing custom encoded attribute/type entries.
1083 const ResourceSectionReader &resourceReader;
1084
1085 /// The map of the loaded dialects used to retrieve dialect information, such
1086 /// as the dialect version.
1087 const llvm::StringMap<BytecodeDialect *> &dialectsMap;
1088
1089 /// The set of attribute and type entries.
1090 SmallVector<AttrEntry> attributes;
1091 SmallVector<TypeEntry> types;
1092
1093 /// Type entries that have published an incomplete value so a self-reference
1094 /// can resolve, and whose custom read has not yet completed.
1095 DenseMap<uint64_t, Type> partialTypes;
1096 SmallVector<uint64_t, 4> partialHistory;
1097
1098 /// Entries currently on the active C++ `readEntry` call stack, mapped to
1099 /// `partialHistory.size()` when their read began, used to distinguish guarded
1100 /// cycles (which defer) from unguarded cycles (which fail).
1101 llvm::SmallDenseMap<WorklistEntry, size_t, 8> activeEntries;
1102
1103 /// Potential counter incremented on each committed entry and each newly
1104 /// published partial type, and decremented if an uncommitted partial is
1105 /// rolled back or discarded; used to detect non-progressing worklist cycles.
1106 uint64_t progressGeneration = 0;
1107
1108 /// Monotonic count of committed attribute/type entries, used to detect
1109 /// speculative partials that escaped into a cached entry before fallthrough.
1110 uint64_t resolvedCount = 0;
1111
1112 /// A location used for error emission.
1113 Location fileLoc;
1114
1115 /// Current bytecode version being used.
1116 uint64_t &bytecodeVersion;
1117
1118 /// Reference to the parser configuration.
1119 const ParserConfig &parserConfig;
1120
1121 /// Worklist for deferred attribute/type parsing. This is used to handle
1122 /// deeply nested structures like CallSiteLoc iteratively.
1123 /// - The first element is the index of the attribute/type to parse.
1124 /// - The second element is the kind of entry being parsed.
1125 std::vector<WorklistEntry> deferredWorklist;
1126
1127 /// Flag indicating if we are currently resolving an attribute or type.
1128 bool resolving = false;
1129};
1130
1131class DialectReader : public DialectBytecodeReader {
1132public:
1133 DialectReader(AttrTypeReader &attrTypeReader,
1134 const StringSectionReader &stringReader,
1135 const ResourceSectionReader &resourceReader,
1136 const llvm::StringMap<BytecodeDialect *> &dialectsMap,
1137 EncodingReader &reader, uint64_t &bytecodeVersion,
1138 uint64_t depth = 0,
1139 std::optional<uint64_t> cyclicTypeIndex = std::nullopt)
1140 : attrTypeReader(attrTypeReader), stringReader(stringReader),
1141 resourceReader(resourceReader), dialectsMap(dialectsMap),
1142 reader(reader), bytecodeVersion(bytecodeVersion), depth(depth),
1143 cyclicTypeIndex(cyclicTypeIndex) {}
1144
1145 /// See DialectBytecodeReader::tryStartCyclicRead.
1146 ///
1147 /// The partial is registered against the entry index, deliberately *not*
1148 /// stored into the entry itself. An attempt can be abandoned and retried
1149 /// by the deferred worklist, and an incomplete type left behind in the
1150 /// entry would be handed out as if it were fully resolved.
1151 LogicalResult tryStartCyclicRead(Type type) override;
1152
1153 InFlightDiagnostic emitError(const Twine &msg) const override {
1154 return reader.emitError(msg);
1155 }
1156
1157 InFlightDiagnostic emitWarning(const Twine &msg) const override {
1158 return reader.emitWarning(msg);
1159 }
1160
1161 FailureOr<const DialectVersion *>
1162 getDialectVersion(StringRef dialectName) const override {
1163 // First check if the dialect is available in the map.
1164 auto dialectEntry = dialectsMap.find(dialectName);
1165 if (dialectEntry == dialectsMap.end())
1166 return failure();
1167 // If the dialect was found, try to load it. This will trigger reading the
1168 // bytecode version from the version buffer if it wasn't already processed.
1169 // Return failure if either of those two actions could not be completed.
1170 if (failed(dialectEntry->getValue()->load(*this, getLoc().getContext())) ||
1171 dialectEntry->getValue()->loadedVersion == nullptr)
1172 return failure();
1173 return dialectEntry->getValue()->loadedVersion.get();
1174 }
1175
1176 MLIRContext *getContext() const override { return getLoc().getContext(); }
1177
1178 uint64_t getBytecodeVersion() const override { return bytecodeVersion; }
1179
1180 DialectReader withEncodingReader(EncodingReader &encReader) const {
1181 return DialectReader(attrTypeReader, stringReader, resourceReader,
1182 dialectsMap, encReader, bytecodeVersion);
1183 }
1184
1185 Location getLoc() const { return reader.getLoc(); }
1186
1187 //===--------------------------------------------------------------------===//
1188 // IR
1189 //===--------------------------------------------------------------------===//
1190
1191 /// The maximum depth to eagerly parse nested attributes/types before
1192 /// deferring.
1193 static constexpr uint64_t maxAttrTypeDepth = 5;
1194
1195 LogicalResult readAttribute(Attribute &result) override {
1196 uint64_t index;
1197 if (failed(reader.parseVarInt(index)))
1198 return failure();
1199 return readEntryAtIndex(index, result);
1200 }
1201 LogicalResult readOptionalAttribute(Attribute &result) override {
1202 uint64_t index;
1203 bool hasAttr = false;
1204 if (failed(reader.parseVarIntWithFlag(index, hasAttr)))
1205 return failure();
1206 if (!hasAttr)
1207 return success();
1208 return readEntryAtIndex(index, result);
1209 }
1210 LogicalResult readType(Type &result) override {
1211 uint64_t index;
1212 if (failed(reader.parseVarInt(index)))
1213 return failure();
1214 return readEntryAtIndex(index, result);
1215 }
1216
1217 FailureOr<AsmDialectResourceHandle> readResourceHandle() override {
1218 AsmDialectResourceHandle handle;
1219 if (failed(resourceReader.parseResourceHandle(reader, handle)))
1220 return failure();
1221 return handle;
1222 }
1223
1224 //===--------------------------------------------------------------------===//
1225 // Primitives
1226 //===--------------------------------------------------------------------===//
1227
1228 LogicalResult readVarInt(uint64_t &result) override {
1229 return reader.parseVarInt(result);
1230 }
1231
1232 LogicalResult readSignedVarInt(int64_t &result) override {
1233 uint64_t unsignedResult;
1234 if (failed(reader.parseSignedVarInt(unsignedResult)))
1235 return failure();
1236 result = static_cast<int64_t>(unsignedResult);
1237 return success();
1238 }
1239
1240 FailureOr<APInt> readAPIntWithKnownWidth(unsigned bitWidth) override {
1241 // Small values are encoded using a single byte.
1242 if (bitWidth <= 8) {
1243 uint8_t value;
1244 if (failed(reader.parseByte(value)))
1245 return failure();
1246 return APInt(bitWidth, value);
1247 }
1248
1249 // Large values up to 64 bits are encoded using a single varint.
1250 if (bitWidth <= 64) {
1251 uint64_t value;
1252 if (failed(reader.parseSignedVarInt(value)))
1253 return failure();
1254 return APInt(bitWidth, value);
1255 }
1256
1257 // Otherwise, for really big values we encode the array of active words in
1258 // the value.
1259 uint64_t numActiveWords;
1260 if (failed(reader.parseVarInt(numActiveWords)))
1261 return failure();
1262 SmallVector<uint64_t, 4> words(numActiveWords);
1263 for (uint64_t i = 0; i < numActiveWords; ++i)
1264 if (failed(reader.parseSignedVarInt(words[i])))
1265 return failure();
1266 return APInt(bitWidth, words);
1267 }
1268
1269 FailureOr<APFloat>
1270 readAPFloatWithKnownSemantics(const llvm::fltSemantics &semantics) override {
1271 FailureOr<APInt> intVal =
1272 readAPIntWithKnownWidth(APFloat::getSizeInBits(semantics));
1273 if (failed(intVal))
1274 return failure();
1275 return APFloat(semantics, *intVal);
1276 }
1277
1278 LogicalResult readString(StringRef &result) override {
1279 return stringReader.parseString(reader, result);
1280 }
1281
1282 LogicalResult readBlob(ArrayRef<char> &result) override {
1283 uint64_t dataSize;
1284 ArrayRef<uint8_t> data;
1285 if (failed(reader.parseVarInt(dataSize)) ||
1286 failed(reader.parseBytes(dataSize, data)))
1287 return failure();
1288 result = llvm::ArrayRef(reinterpret_cast<const char *>(data.data()),
1289 data.size());
1290 return success();
1291 }
1292
1293 LogicalResult readBool(bool &result) override {
1294 return reader.parseByte(result);
1295 }
1296
1297private:
1298 template <typename T>
1299 LogicalResult readEntryAtIndex(uint64_t index, T &result) {
1300 // If we aren't currently resolving an attribute/type, resolve this entry
1301 // eagerly. This is the case when parsing properties, which aren't processed
1302 // via the worklist.
1303 if (!attrTypeReader.isResolving()) {
1304 T resolved;
1305 if constexpr (std::is_same_v<T, Type>)
1306 resolved = attrTypeReader.resolveType(index);
1307 else
1308 resolved = attrTypeReader.resolveAttribute(index);
1309 if (!resolved)
1310 return failure();
1311 result = resolved;
1312 return success();
1313 }
1314
1315 if constexpr (std::is_same_v<T, Type>) {
1316 if (Type type = attrTypeReader.getTypeOrSentinel(index)) {
1317 result = type;
1318 return success();
1319 }
1320 if (Type partial = attrTypeReader.getPartialType(index)) {
1321 result = partial;
1322 return success();
1323 }
1324 if (depth > maxAttrTypeDepth) {
1325 attrTypeReader.addDeferredParsing(index,
1326 AttrTypeReader::EntryKind::Type);
1327 return failure();
1328 }
1329 return attrTypeReader.readType(index, result, depth + 1);
1330 } else {
1331 if (Attribute attr = attrTypeReader.getAttributeOrSentinel(index)) {
1332 result = attr;
1333 return success();
1334 }
1335 if (depth > maxAttrTypeDepth) {
1336 attrTypeReader.addDeferredParsing(index,
1337 AttrTypeReader::EntryKind::Attribute);
1338 return failure();
1339 }
1340 return attrTypeReader.readAttribute(index, result, depth + 1);
1341 }
1342 }
1343
1344 AttrTypeReader &attrTypeReader;
1345 const StringSectionReader &stringReader;
1346 const ResourceSectionReader &resourceReader;
1347 const llvm::StringMap<BytecodeDialect *> &dialectsMap;
1348 EncodingReader &reader;
1349 uint64_t &bytecodeVersion;
1350 uint64_t depth;
1351
1352 /// Index of the type entry being parsed, when this reader is parsing one.
1353 /// Only then can a cyclic read be published.
1354 std::optional<uint64_t> cyclicTypeIndex;
1355};
1356
1357/// Wraps the properties section and handles reading properties out of it.
1358class PropertiesSectionReader {
1359public:
1360 /// Initialize the properties section reader with the given section data.
1361 LogicalResult initialize(Location fileLoc, ArrayRef<uint8_t> sectionData) {
1362 if (sectionData.empty())
1363 return success();
1364 EncodingReader propReader(sectionData, fileLoc);
1365 uint64_t count;
1366 if (failed(propReader.parseVarInt(count)))
1367 return failure();
1368 // Parse the raw properties buffer.
1369 if (failed(propReader.parseBytes(propReader.size(), propertiesBuffers)))
1370 return failure();
1371
1372 EncodingReader offsetsReader(propertiesBuffers, fileLoc);
1373 offsetTable.reserve(count);
1374 for (auto idx : llvm::seq<int64_t>(0, count)) {
1375 (void)idx;
1376 offsetTable.push_back(propertiesBuffers.size() - offsetsReader.size());
1377 ArrayRef<uint8_t> rawProperties;
1378 uint64_t dataSize;
1379 if (failed(offsetsReader.parseVarInt(dataSize)) ||
1380 failed(offsetsReader.parseBytes(dataSize, rawProperties)))
1381 return failure();
1382 }
1383 if (!offsetsReader.empty())
1384 return offsetsReader.emitError()
1385 << "Broken properties section: didn't exhaust the offsets table";
1386 return success();
1387 }
1388
1389 LogicalResult read(Location fileLoc, DialectReader &dialectReader,
1390 OperationName *opName, OperationState &opState) const {
1391 uint64_t propertiesIdx;
1392 if (failed(dialectReader.readVarInt(propertiesIdx)))
1393 return failure();
1394 if (propertiesIdx >= offsetTable.size())
1395 return dialectReader.emitError("Properties idx out-of-bound for ")
1396 << opName->getStringRef();
1397 size_t propertiesOffset = offsetTable[propertiesIdx];
1398 if (propertiesIdx >= propertiesBuffers.size())
1399 return dialectReader.emitError("Properties offset out-of-bound for ")
1400 << opName->getStringRef();
1401
1402 // Acquire the sub-buffer that represent the requested properties.
1403 ArrayRef<char> rawProperties;
1404 {
1405 // "Seek" to the requested offset by getting a new reader with the right
1406 // sub-buffer.
1407 EncodingReader reader(propertiesBuffers.drop_front(propertiesOffset),
1408 fileLoc);
1409 // Properties are stored as a sequence of {size + raw_data}.
1410 if (failed(
1411 dialectReader.withEncodingReader(reader).readBlob(rawProperties)))
1412 return failure();
1413 }
1414 // Setup a new reader to read from the `rawProperties` sub-buffer.
1415 EncodingReader reader(
1416 StringRef(rawProperties.begin(), rawProperties.size()), fileLoc);
1417 DialectReader propReader = dialectReader.withEncodingReader(reader);
1418
1419 auto *iface = opName->getInterface<BytecodeOpInterface>();
1420 if (iface)
1421 return iface->readProperties(propReader, opState);
1422 if (opName->isRegistered())
1423 return propReader.emitError(
1424 "has properties but missing BytecodeOpInterface for ")
1425 << opName->getStringRef();
1426 // Unregistered op are storing properties as an attribute.
1427 return propReader.readAttribute(opState.propertiesAttr);
1428 }
1429
1430private:
1431 /// The properties buffer referenced within the bytecode file.
1432 ArrayRef<uint8_t> propertiesBuffers;
1433
1434 /// Table of offset in the buffer above.
1435 SmallVector<int64_t> offsetTable;
1436};
1437} // namespace
1438
1439LogicalResult AttrTypeReader::initialize(
1440 MutableArrayRef<std::unique_ptr<BytecodeDialect>> dialects,
1441 ArrayRef<uint8_t> sectionData, ArrayRef<uint8_t> offsetSectionData) {
1442 EncodingReader offsetReader(offsetSectionData, fileLoc);
1443
1444 // Parse the number of attribute and type entries.
1445 uint64_t numAttributes, numTypes;
1446 if (failed(offsetReader.parseVarInt(numAttributes)) ||
1447 failed(offsetReader.parseVarInt(numTypes)))
1448 return failure();
1449 attributes.resize(numAttributes);
1450 types.resize(numTypes);
1451
1452 // A functor used to accumulate the offsets for the entries in the given
1453 // range.
1454 uint64_t currentOffset = 0;
1455 auto parseEntries = [&](auto &&range) {
1456 size_t currentIndex = 0, endIndex = range.size();
1457
1458 // Parse an individual entry.
1459 auto parseEntryFn = [&](BytecodeDialect *dialect) -> LogicalResult {
1460 // Verify that the dialect groups don't contain more entries than were
1461 // declared for this range.
1462 if (currentIndex == endIndex) {
1463 return offsetReader.emitError(
1464 "Attribute or Type dialect group entries exceed the declared "
1465 "number of entries (",
1466 endIndex, ")");
1467 }
1468 auto &entry = range[currentIndex++];
1469
1470 uint64_t entrySize;
1471 if (failed(offsetReader.parseVarIntWithFlag(entrySize,
1472 entry.hasCustomEncoding)))
1473 return failure();
1474
1475 // Verify that the offset is actually valid.
1476 if (currentOffset + entrySize > sectionData.size()) {
1477 return offsetReader.emitError(
1478 "Attribute or Type entry offset points past the end of section");
1479 }
1480
1481 entry.data = sectionData.slice(currentOffset, entrySize);
1482 entry.dialect = dialect;
1483 currentOffset += entrySize;
1484 return success();
1485 };
1486 while (currentIndex != endIndex)
1487 if (failed(parseDialectGrouping(offsetReader, dialects, parseEntryFn)))
1488 return failure();
1489 return success();
1490 };
1491
1492 // Process each of the attributes, and then the types.
1493 if (failed(parseEntries(attributes)) || failed(parseEntries(types)))
1494 return failure();
1495
1496 // Ensure that we read everything from the section.
1497 if (!offsetReader.empty()) {
1498 return offsetReader.emitError(
1499 "unexpected trailing data in the Attribute/Type offset section");
1500 }
1501
1502 return success();
1503}
1504
1505template <typename T>
1506T AttrTypeReader::resolveEntry(SmallVectorImpl<Entry<T>> &entries,
1507 uint64_t index, StringRef entryType) {
1508 assert(!resolving && "resolveEntry is not re-entrant");
1509 resolving = true;
1510 llvm::scope_exit restoreResolving([&]() {
1511 resolving = false;
1512 // Partials published to break cycles are scoped to one top-level resolve.
1513 // Past that point every entry is either fully resolved or the resolve
1514 // failed, so keeping them would risk handing out an incomplete type.
1515 partialTypes.clear();
1516 partialHistory.clear();
1517 deferredWorklist.clear();
1518 });
1519
1520 if (index >= entries.size()) {
1521 emitError(fileLoc) << "invalid " << entryType << " index: " << index;
1522 return {};
1523 }
1524
1525 // Fast path: Try direct parsing without worklist overhead. This handles the
1526 // common case where there are no deferred dependencies.
1527 assert(deferredWorklist.empty());
1528 T result;
1529 if (succeeded(readEntry(entries, index, result, entryType, /*depth=*/0))) {
1530 assert(deferredWorklist.empty());
1531 assert(partialTypes.empty());
1532 return result;
1533 }
1534 if (deferredWorklist.empty()) {
1535 // Failed with no deferred entries is an error.
1536 return T();
1537 }
1538
1539 // Slow path: Use a post-order DFS worklist to iteratively resolve deferred
1540 // dependencies before retrying the entries that depend on them.
1541 static_assert((std::is_same_v<T, Type> || std::is_same_v<T, Attribute>) &&
1542 "Only support resolving Attributes and Types");
1543 constexpr EntryKind rootKind =
1544 std::is_same_v<T, Type> ? EntryKind::Type : EntryKind::Attribute;
1545
1546 AttrTypeWorklist worklist;
1547 worklist.pushBack({index, rootKind});
1548 for (WorklistEntry dep : llvm::reverse(deferredWorklist))
1549 worklist.pushFront(dep);
1550 deferredWorklist.clear();
1551
1552 DenseSet<WorklistEntry> failedInEpoch;
1553 uint64_t lastGeneration = progressGeneration;
1554
1555 while (!worklist.empty()) {
1556 WorklistEntry current = worklist.popFront();
1557 auto [currentIndex, entryKind] = current;
1558
1559 // Clear the deferred worklist before parsing to capture any new entries.
1560 deferredWorklist.clear();
1561
1562 LogicalResult parseStatus = failure();
1563 if (entryKind == EntryKind::Type) {
1564 Type typeResult;
1565 parseStatus = readType(currentIndex, typeResult, /*depth=*/0);
1566 } else {
1567 assert(entryKind == EntryKind::Attribute && "Unexpected entry kind");
1568 Attribute attrResult;
1569 parseStatus = readAttribute(currentIndex, attrResult, /*depth=*/0);
1570 }
1571
1572 if (succeeded(parseStatus)) {
1573 failedInEpoch.clear();
1574 lastGeneration = progressGeneration;
1575 continue;
1576 }
1577
1578 if (deferredWorklist.empty()) {
1579 // Parsing failed with no deferred entries, which implies an error.
1580 return T();
1581 }
1582
1583 if (progressGeneration != lastGeneration) {
1584 failedInEpoch.clear();
1585 lastGeneration = progressGeneration;
1586 }
1587 if (!failedInEpoch.insert(current).second) {
1588 StringRef kindStr = entryKind == EntryKind::Type ? "type" : "attribute";
1589 emitError(fileLoc) << "cyclic dependency detected in " << kindStr
1590 << " entry " << currentIndex;
1591 deferredWorklist.clear();
1592 return T();
1593 }
1594
1595 // Keep `current` ahead of its callers, and splice its newly discovered
1596 // dependencies in front of `current` (in reverse to preserve order).
1597 worklist.pushFront(current);
1598 for (WorklistEntry dep : llvm::reverse(deferredWorklist))
1599 worklist.pushFront(dep);
1600 deferredWorklist.clear();
1601 }
1602
1603 assert(partialTypes.empty());
1604 return entries[index].entry;
1605}
1606
1607LogicalResult DialectReader::tryStartCyclicRead(Type type) {
1608 if (!cyclicTypeIndex)
1609 return emitError(
1610 "tryStartCyclicRead called while not reading a custom type entry");
1611 if (!type)
1612 return emitError("cannot start cyclic read with null type");
1613 if (!type.hasTrait<TypeTrait::IsMutable>())
1614 return emitError("cannot start cyclic read on immutable type: ") << type;
1615 Type published = attrTypeReader.publishPartialType(*cyclicTypeIndex, type);
1616 if (published != type) {
1617 return emitError("type entry ")
1618 << *cyclicTypeIndex << " already published a different '"
1619 << published.getAbstractType().getName() << "' instance";
1620 }
1621 return success();
1622}
1623
1624template <typename T>
1625LogicalResult AttrTypeReader::readEntry(SmallVectorImpl<Entry<T>> &entries,
1626 uint64_t index, T &result,
1627 StringRef entryType, uint64_t depth) {
1628 if (index >= entries.size()) {
1629 deferredWorklist.clear();
1630 return emitError(fileLoc) << "invalid " << entryType << " index: " << index;
1631 }
1632
1633 // If the entry has already been resolved, return it.
1634 Entry<T> &entry = entries[index];
1635 if (entry.entry) {
1636 result = entry.entry;
1637 return success();
1638 }
1639
1640 constexpr EntryKind kind =
1641 std::is_same_v<T, Type> ? EntryKind::Type : EntryKind::Attribute;
1642 WorklistEntry activeKey(index, kind);
1643 auto [activeIt, firstActivation] =
1644 activeEntries.try_emplace(activeKey, partialHistory.size());
1645 if (!firstActivation) {
1646 // Re-entering an active entry is guarded if a partial type published since
1647 // the outer read began is still live: defer so the worklist parses this
1648 // entry once using the published partial before completing the mutable
1649 // type.
1650 if (hasLivePartialSince(activeIt->second)) {
1651 addDeferredParsing(index, kind);
1652 return failure();
1653 }
1654 deferredWorklist.clear();
1655 StringRef kindStr = std::is_same_v<T, Type> ? "type" : "attribute";
1656 return emitError(fileLoc)
1657 << "cyclic dependency detected in " << kindStr << " entry " << index;
1658 }
1659 llvm::scope_exit eraseActive([&]() { activeEntries.erase(activeKey); });
1660
1661 // If the entry hasn't been resolved, try to parse it.
1662 EncodingReader reader(entry.data, fileLoc);
1663 T parsedEntry = {};
1664 LogicalResult parseResult =
1665 entry.hasCustomEncoding
1666 ? parseCustomEntry(entry, reader, index, depth, parsedEntry)
1667 : parseAsmEntry(parsedEntry, reader, entryType);
1668 if (failed(parseResult)) {
1669 if constexpr (std::is_same_v<T, Type>) {
1670 if (partialTypes.contains(index)) {
1671 // If a nested read deferred, keep the partial bound and schedule this
1672 // entry to complete once its dependencies are resolved.
1673 if (!deferredWorklist.empty())
1674 addDeferredParsing(index, EntryKind::Type);
1675 else
1676 eraseUncommittedPartialType(index);
1677 }
1678 }
1679 return failure();
1680 }
1681
1682 if (!reader.empty()) {
1683 deferredWorklist.clear();
1684 if constexpr (std::is_same_v<T, Type>)
1685 eraseUncommittedPartialType(index);
1686 return reader.emitError("unexpected trailing bytes after ", entryType,
1687 " entry");
1688 }
1689
1690 if constexpr (std::is_same_v<T, Type>)
1691 partialTypes.erase(index);
1692 entry.entry = result = parsedEntry;
1693 ++progressGeneration;
1694 ++resolvedCount;
1695 return success();
1696}
1697
1698template <typename T>
1699LogicalResult
1700AttrTypeReader::parseCustomEntry(Entry<T> &entry, EncodingReader &reader,
1701 uint64_t index, uint64_t depth, T &result) {
1702 std::optional<uint64_t> cyclicTypeIndex;
1703 if constexpr (std::is_same_v<T, Type>)
1704 cyclicTypeIndex = index;
1705 DialectReader dialectReader(*this, stringReader, resourceReader, dialectsMap,
1706 reader, bytecodeVersion, depth, cyclicTypeIndex);
1707 if (failed(entry.dialect->load(dialectReader, fileLoc.getContext())))
1708 return failure();
1709
1710 auto verifyPublishedPartial = [&](T parsed) -> LogicalResult {
1711 if constexpr (std::is_same_v<T, Type>) {
1712 // A dialect or callback that published a partial must return that same
1713 // instance: consumers may already hold it.
1714 if (Type partial = getPartialType(index)) {
1715 if (parsed && parsed != partial) {
1716 deferredWorklist.clear();
1717 return reader.emitError("custom type reader for dialect '",
1718 entry.dialect->name,
1719 "' returned a different type than the one "
1720 "published with tryStartCyclicRead");
1721 }
1722 }
1723 }
1724 return success();
1725 };
1726
1727 // Try parsing with callbacks first if available.
1728 ArrayRef<std::unique_ptr<AttrTypeBytecodeReader<T>>> callbacks = [&]() {
1729 if constexpr (std::is_same_v<T, Type>)
1730 return parserConfig.getBytecodeReaderConfig().getTypeCallbacks();
1731 else
1732 return parserConfig.getBytecodeReaderConfig().getAttributeCallbacks();
1733 }();
1734 for (size_t e = callbacks.size(); entry.nextCallbackIndex < e;
1735 ++entry.nextCallbackIndex) {
1736 const std::unique_ptr<AttrTypeBytecodeReader<T>> &callback =
1737 callbacks[entry.nextCallbackIndex];
1738 RollbackPoint rollback = saveRollbackPoint();
1739 if (failed(callback->read(dialectReader, entry.dialect->name, result)))
1740 return failure();
1741 if (result)
1742 return verifyPublishedPartial(result);
1743
1744 if (partialHistory.size() > rollback.partialHistorySize &&
1745 resolvedCount != rollback.resolvedCount) {
1746 restoreRollbackPoint(rollback);
1747 deferredWorklist.clear();
1748 return reader.emitError(
1749 "custom type reader callback published a partial type that may "
1750 "have escaped into a resolved nested entry before falling through");
1751 }
1752
1753 // The callback fell through without consuming the encoding. Reset the
1754 // reader and restore deferred entries and uncommitted partial types.
1755 restoreRollbackPoint(rollback);
1756 reader = EncodingReader(entry.data, reader.getLoc());
1757 }
1758
1759 // Ensure that the dialect implements the bytecode interface.
1760 if (!entry.dialect->interface) {
1761 return reader.emitError("dialect '", entry.dialect->name,
1762 "' does not implement the bytecode interface");
1763 }
1764
1765 if constexpr (std::is_same_v<T, Type>)
1766 result = entry.dialect->interface->readType(dialectReader);
1767 else
1768 result = entry.dialect->interface->readAttribute(dialectReader);
1769
1770 if (failed(verifyPublishedPartial(result)))
1771 return failure();
1772
1773 return success(static_cast<bool>(result));
1774}
1775
1776template <typename T>
1777LogicalResult AttrTypeReader::parseAsmEntry(T &result, EncodingReader &reader,
1778 StringRef entryType) {
1779 StringRef asmStr;
1780 if (failed(reader.parseNullTerminatedString(asmStr)))
1781 return failure();
1782
1783 // Invoke the MLIR assembly parser to parse the entry text.
1784 size_t numRead = 0;
1785 MLIRContext *context = fileLoc->getContext();
1786 if constexpr (std::is_same_v<T, Type>)
1787 result =
1788 ::parseType(asmStr, context, &numRead, /*isKnownNullTerminated=*/true);
1789 else
1790 result = ::parseAttribute(asmStr, context, Type(), &numRead,
1791 /*isKnownNullTerminated=*/true);
1792 if (!result)
1793 return failure();
1794
1795 // Ensure there weren't dangling characters after the entry.
1796 if (numRead != asmStr.size()) {
1797 return reader.emitError("trailing characters found after ", entryType,
1798 " assembly format: ", asmStr.drop_front(numRead));
1799 }
1800 return success();
1801}
1802
1803//===----------------------------------------------------------------------===//
1804// Bytecode Reader
1805//===----------------------------------------------------------------------===//
1806
1807/// This class is used to read a bytecode buffer and translate it into MLIR.
1809 struct RegionReadState;
1810 using LazyLoadableOpsInfo =
1811 std::list<std::pair<Operation *, RegionReadState>>;
1812 using LazyLoadableOpsMap =
1814
1815public:
1816 Impl(Location fileLoc, const ParserConfig &config, bool lazyLoading,
1817 llvm::MemoryBufferRef buffer,
1818 const std::shared_ptr<llvm::SourceMgr> &bufferOwnerRef)
1819 : config(config), fileLoc(fileLoc), lazyLoading(lazyLoading),
1820 attrTypeReader(stringReader, resourceReader, dialectsMap, version,
1821 fileLoc, config),
1822 // Use the builtin unrealized conversion cast operation to represent
1823 // forward references to values that aren't yet defined.
1824 forwardRefOpState(UnknownLoc::get(config.getContext()),
1825 "builtin.unrealized_conversion_cast", ValueRange(),
1826 NoneType::get(config.getContext())),
1827 buffer(buffer), bufferOwnerRef(bufferOwnerRef) {}
1828
1829 /// Read the bytecode defined within `buffer` into the given block.
1830 LogicalResult read(Block *block,
1831 llvm::function_ref<bool(Operation *)> lazyOps);
1832
1833 /// Return the number of ops that haven't been materialized yet.
1834 int64_t getNumOpsToMaterialize() const { return lazyLoadableOpsMap.size(); }
1835
1836 bool isMaterializable(Operation *op) { return lazyLoadableOpsMap.count(op); }
1837
1838 /// Materialize the provided operation, invoke the lazyOpsCallback on every
1839 /// newly found lazy operation.
1840 LogicalResult
1842 llvm::function_ref<bool(Operation *)> lazyOpsCallback) {
1843 this->lazyOpsCallback = lazyOpsCallback;
1844 llvm::scope_exit resetlazyOpsCallback(
1845 [&] { this->lazyOpsCallback = nullptr; });
1846 auto it = lazyLoadableOpsMap.find(op);
1847 assert(it != lazyLoadableOpsMap.end() &&
1848 "materialize called on non-materializable op");
1849 return materialize(it);
1850 }
1851
1852 /// Materialize all operations.
1853 LogicalResult materializeAll() {
1854 while (!lazyLoadableOpsMap.empty()) {
1855 if (failed(materialize(lazyLoadableOpsMap.begin())))
1856 return failure();
1857 }
1858 return success();
1859 }
1860
1861 /// Finalize the lazy-loading by calling back with every op that hasn't been
1862 /// materialized to let the client decide if the op should be deleted or
1863 /// materialized. The op is materialized if the callback returns true, deleted
1864 /// otherwise.
1865 LogicalResult finalize(function_ref<bool(Operation *)> shouldMaterialize) {
1866 while (!lazyLoadableOps.empty()) {
1867 Operation *op = lazyLoadableOps.begin()->first;
1868 if (shouldMaterialize(op)) {
1869 if (failed(materialize(lazyLoadableOpsMap.find(op))))
1870 return failure();
1871 continue;
1872 }
1873 op->dropAllReferences();
1874 op->erase();
1875 lazyLoadableOps.pop_front();
1876 lazyLoadableOpsMap.erase(op);
1877 }
1878 return success();
1879 }
1880
1881private:
1882 LogicalResult materialize(LazyLoadableOpsMap::iterator it) {
1883 assert(it != lazyLoadableOpsMap.end() &&
1884 "materialize called on non-materializable op");
1885 valueScopes.emplace_back();
1886 std::vector<RegionReadState> regionStack;
1887 regionStack.push_back(std::move(it->getSecond()->second));
1888 lazyLoadableOps.erase(it->getSecond());
1889 lazyLoadableOpsMap.erase(it);
1890
1891 while (!regionStack.empty())
1892 if (failed(parseRegions(regionStack, regionStack.back())))
1893 return failure();
1894 return success();
1895 }
1896
1897 LogicalResult checkSectionAlignment(
1898 unsigned alignment,
1899 function_ref<InFlightDiagnostic(const Twine &error)> emitError) {
1900 // Check that the bytecode buffer meets the requested section alignment.
1901 //
1902 // If it does not, the virtual address of the item in the section will
1903 // not be aligned to the requested alignment.
1904 //
1905 // The typical case where this is necessary is the resource blob
1906 // optimization in `parseAsBlob` where we reference the weights from the
1907 // provided buffer instead of copying them to a new allocation.
1908 const bool isGloballyAligned =
1909 ((uintptr_t)buffer.getBufferStart() & (alignment - 1)) == 0;
1910
1911 if (!isGloballyAligned)
1912 return emitError("expected section alignment ")
1913 << alignment << " but bytecode buffer 0x"
1914 << Twine::utohexstr((uint64_t)buffer.getBufferStart())
1915 << " is not aligned";
1916
1917 return success();
1918 };
1919
1920 /// Return the context for this config.
1921 MLIRContext *getContext() const { return config.getContext(); }
1922
1923 /// Parse the bytecode version.
1924 LogicalResult parseVersion(EncodingReader &reader);
1925
1926 //===--------------------------------------------------------------------===//
1927 // Dialect Section
1928
1929 LogicalResult parseDialectSection(ArrayRef<uint8_t> sectionData);
1930
1931 /// Parse an operation name reference using the given reader, and set the
1932 /// `wasRegistered` flag that indicates if the bytecode was produced by a
1933 /// context where opName was registered.
1934 FailureOr<OperationName> parseOpName(EncodingReader &reader,
1935 std::optional<bool> &wasRegistered);
1936
1937 //===--------------------------------------------------------------------===//
1938 // Attribute/Type Section
1939
1940 /// Parse an attribute or type using the given reader.
1941 template <typename T>
1942 LogicalResult parseAttribute(EncodingReader &reader, T &result) {
1943 return attrTypeReader.parseAttribute(reader, result);
1944 }
1945 LogicalResult parseType(EncodingReader &reader, Type &result) {
1946 return attrTypeReader.parseType(reader, result);
1947 }
1948
1949 //===--------------------------------------------------------------------===//
1950 // Resource Section
1951
1952 LogicalResult
1953 parseResourceSection(EncodingReader &reader,
1954 std::optional<ArrayRef<uint8_t>> resourceData,
1955 std::optional<ArrayRef<uint8_t>> resourceOffsetData);
1956
1957 //===--------------------------------------------------------------------===//
1958 // IR Section
1959
1960 /// This struct represents the current read state of a range of regions. This
1961 /// struct is used to enable iterative parsing of regions.
1962 struct RegionReadState {
1963 RegionReadState(Operation *op, EncodingReader *reader,
1964 bool isIsolatedFromAbove)
1965 : RegionReadState(op->getRegions(), reader, isIsolatedFromAbove) {}
1966 RegionReadState(MutableArrayRef<Region> regions, EncodingReader *reader,
1967 bool isIsolatedFromAbove)
1968 : curRegion(regions.begin()), endRegion(regions.end()), reader(reader),
1969 isIsolatedFromAbove(isIsolatedFromAbove) {}
1970
1971 /// The current regions being read.
1972 MutableArrayRef<Region>::iterator curRegion, endRegion;
1973 /// This is the reader to use for this region, this pointer is pointing to
1974 /// the parent region reader unless the current region is IsolatedFromAbove,
1975 /// in which case the pointer is pointing to the `owningReader` which is a
1976 /// section dedicated to the current region.
1977 EncodingReader *reader;
1978 std::unique_ptr<EncodingReader> owningReader;
1979
1980 /// The number of values defined immediately within this region.
1981 unsigned numValues = 0;
1982
1983 /// The current blocks of the region being read.
1984 SmallVector<Block *> curBlocks;
1985 Region::iterator curBlock = {};
1986
1987 /// The number of operations remaining to be read from the current block
1988 /// being read.
1989 uint64_t numOpsRemaining = 0;
1990
1991 /// A flag indicating if the regions being read are isolated from above.
1992 bool isIsolatedFromAbove = false;
1993 };
1994
1995 LogicalResult parseIRSection(ArrayRef<uint8_t> sectionData, Block *block);
1996 LogicalResult parseRegions(std::vector<RegionReadState> &regionStack,
1997 RegionReadState &readState);
1998 FailureOr<Operation *> parseOpWithoutRegions(EncodingReader &reader,
1999 RegionReadState &readState,
2000 bool &isIsolatedFromAbove);
2001
2002 LogicalResult parseRegion(RegionReadState &readState);
2003 LogicalResult parseBlockHeader(EncodingReader &reader,
2004 RegionReadState &readState);
2005 LogicalResult parseBlockArguments(EncodingReader &reader, Block *block);
2006
2007 //===--------------------------------------------------------------------===//
2008 // Value Processing
2009
2010 /// Parse an operand reference using the given reader. Returns nullptr in the
2011 /// case of failure.
2012 Value parseOperand(EncodingReader &reader);
2013
2014 /// Sequentially define the given value range.
2015 LogicalResult defineValues(EncodingReader &reader, ValueRange values);
2016
2017 /// Create a value to use for a forward reference.
2018 Value createForwardRef();
2019
2020 //===--------------------------------------------------------------------===//
2021 // Use-list order helpers
2022
2023 /// This struct is a simple storage that contains information required to
2024 /// reorder the use-list of a value with respect to the pre-order traversal
2025 /// ordering.
2026 struct UseListOrderStorage {
2027 UseListOrderStorage(bool isIndexPairEncoding,
2028 SmallVector<unsigned, 4> &&indices)
2029 : indices(std::move(indices)),
2030 isIndexPairEncoding(isIndexPairEncoding) {};
2031 /// The vector containing the information required to reorder the
2032 /// use-list of a value.
2033 SmallVector<unsigned, 4> indices;
2034
2035 /// Whether indices represent a pair of type `(src, dst)` or it is a direct
2036 /// indexing, such as `dst = order[src]`.
2037 bool isIndexPairEncoding;
2038 };
2039
2040 /// Parse use-list order from bytecode for a range of values if available. The
2041 /// range is expected to be either a block argument or an op result range. On
2042 /// success, return a map of the position in the range and the use-list order
2043 /// encoding. The function assumes to know the size of the range it is
2044 /// processing.
2045 using UseListMapT = DenseMap<unsigned, UseListOrderStorage>;
2046 FailureOr<UseListMapT> parseUseListOrderForRange(EncodingReader &reader,
2047 uint64_t rangeSize);
2048
2049 /// Shuffle the use-chain according to the order parsed.
2050 LogicalResult sortUseListOrder(Value value);
2051
2052 /// Recursively visit all the values defined within topLevelOp and sort the
2053 /// use-list orders according to the indices parsed.
2054 LogicalResult processUseLists(Operation *topLevelOp);
2055
2056 //===--------------------------------------------------------------------===//
2057 // Fields
2058
2059 /// This class represents a single value scope, in which a value scope is
2060 /// delimited by isolated from above regions.
2061 struct ValueScope {
2062 /// Push a new region state onto this scope, reserving enough values for
2063 /// those defined within the current region of the provided state.
2064 void push(RegionReadState &readState) {
2065 nextValueIDs.push_back(values.size());
2066 values.resize(values.size() + readState.numValues);
2067 }
2068
2069 /// Pop the values defined for the current region within the provided region
2070 /// state.
2071 void pop(RegionReadState &readState) {
2072 values.resize(values.size() - readState.numValues);
2073 nextValueIDs.pop_back();
2074 }
2075
2076 /// The set of values defined in this scope.
2077 std::vector<Value> values;
2078
2079 /// The ID for the next defined value for each region current being
2080 /// processed in this scope.
2081 SmallVector<unsigned, 4> nextValueIDs;
2082 };
2083
2084 /// The configuration of the parser.
2085 const ParserConfig &config;
2086
2087 /// A location to use when emitting errors.
2088 Location fileLoc;
2089
2090 /// Flag that indicates if lazyloading is enabled.
2091 bool lazyLoading;
2092
2093 /// Keep track of operations that have been lazy loaded (their regions haven't
2094 /// been materialized), along with the `RegionReadState` that allows to
2095 /// lazy-load the regions nested under the operation.
2096 LazyLoadableOpsInfo lazyLoadableOps;
2097 LazyLoadableOpsMap lazyLoadableOpsMap;
2098 llvm::function_ref<bool(Operation *)> lazyOpsCallback;
2099
2100 /// The reader used to process attribute and types within the bytecode.
2101 AttrTypeReader attrTypeReader;
2102
2103 /// The version of the bytecode being read.
2104 uint64_t version = 0;
2105
2106 /// The producer of the bytecode being read.
2107 StringRef producer;
2108
2109 /// The table of IR units referenced within the bytecode file.
2110 SmallVector<std::unique_ptr<BytecodeDialect>> dialects;
2111 llvm::StringMap<BytecodeDialect *> dialectsMap;
2112 SmallVector<BytecodeOperationName> opNames;
2113
2114 /// The reader used to process resources within the bytecode.
2115 ResourceSectionReader resourceReader;
2116
2117 /// Worklist of values with custom use-list orders to process before the end
2118 /// of the parsing.
2119 DenseMap<void *, UseListOrderStorage> valueToUseListMap;
2120
2121 /// The table of strings referenced within the bytecode file.
2122 StringSectionReader stringReader;
2123
2124 /// The table of properties referenced by the operation in the bytecode file.
2125 PropertiesSectionReader propertiesReader;
2126
2127 /// The current set of available IR value scopes.
2128 std::vector<ValueScope> valueScopes;
2129
2130 /// The global pre-order operation ordering.
2132
2133 /// A block containing the set of operations defined to create forward
2134 /// references.
2135 Block forwardRefOps;
2136
2137 /// A block containing previously created, and no longer used, forward
2138 /// reference operations.
2139 Block openForwardRefOps;
2140
2141 /// An operation state used when instantiating forward references.
2142 OperationState forwardRefOpState;
2143
2144 /// Reference to the input buffer.
2145 llvm::MemoryBufferRef buffer;
2146
2147 /// The optional owning source manager, which when present may be used to
2148 /// extend the lifetime of the input buffer.
2149 const std::shared_ptr<llvm::SourceMgr> bufferOwnerRef;
2150};
2151
2153 Block *block, llvm::function_ref<bool(Operation *)> lazyOpsCallback) {
2154 EncodingReader reader(buffer.getBuffer(), fileLoc);
2155 this->lazyOpsCallback = lazyOpsCallback;
2156 llvm::scope_exit resetlazyOpsCallback(
2157 [&] { this->lazyOpsCallback = nullptr; });
2158
2159 // Skip over the bytecode header, this should have already been checked.
2160 if (failed(reader.skipBytes(StringRef("ML\xefR").size())))
2161 return failure();
2162 // Parse the bytecode version and producer.
2163 if (failed(parseVersion(reader)) ||
2164 failed(reader.parseNullTerminatedString(producer)))
2165 return failure();
2166
2167 // Add a diagnostic handler that attaches a note that includes the original
2168 // producer of the bytecode.
2169 ScopedDiagnosticHandler diagHandler(getContext(), [&](Diagnostic &diag) {
2170 diag.attachNote() << "in bytecode version " << version
2171 << " produced by: " << producer;
2172 return failure();
2173 });
2174
2175 const auto checkSectionAlignment = [&](unsigned alignment) {
2176 return this->checkSectionAlignment(
2177 alignment, [&](const auto &msg) { return reader.emitError(msg); });
2178 };
2179
2180 // Parse the raw data for each of the top-level sections of the bytecode.
2181 std::optional<ArrayRef<uint8_t>>
2182 sectionDatas[bytecode::Section::kNumSections];
2183 while (!reader.empty()) {
2184 // Read the next section from the bytecode.
2185 bytecode::Section::ID sectionID;
2186 ArrayRef<uint8_t> sectionData;
2187 if (failed(
2188 reader.parseSection(sectionID, checkSectionAlignment, sectionData)))
2189 return failure();
2190
2191 // Check for duplicate sections, we only expect one instance of each.
2192 if (sectionDatas[sectionID]) {
2193 return reader.emitError("duplicate top-level section: ",
2194 ::toString(sectionID));
2195 }
2196 sectionDatas[sectionID] = sectionData;
2197 }
2198 // Check that all of the required sections were found.
2199 for (int i = 0; i < bytecode::Section::kNumSections; ++i) {
2200 bytecode::Section::ID sectionID = static_cast<bytecode::Section::ID>(i);
2201 if (!sectionDatas[i] && !isSectionOptional(sectionID, version)) {
2202 return reader.emitError("missing data for top-level section: ",
2203 ::toString(sectionID));
2204 }
2205 }
2206
2207 // Process the string section first.
2208 if (failed(stringReader.initialize(
2209 fileLoc, *sectionDatas[bytecode::Section::kString])))
2210 return failure();
2211
2212 // Process the properties section.
2213 if (sectionDatas[bytecode::Section::kProperties] &&
2214 failed(propertiesReader.initialize(
2215 fileLoc, *sectionDatas[bytecode::Section::kProperties])))
2216 return failure();
2217
2218 // Process the dialect section.
2219 if (failed(parseDialectSection(*sectionDatas[bytecode::Section::kDialect])))
2220 return failure();
2221
2222 // Process the resource section if present.
2223 if (failed(parseResourceSection(
2224 reader, sectionDatas[bytecode::Section::kResource],
2225 sectionDatas[bytecode::Section::kResourceOffset])))
2226 return failure();
2227
2228 // Process the attribute and type section.
2229 if (failed(attrTypeReader.initialize(
2230 dialects, *sectionDatas[bytecode::Section::kAttrType],
2231 *sectionDatas[bytecode::Section::kAttrTypeOffset])))
2232 return failure();
2233
2234 // Finally, process the IR section.
2235 return parseIRSection(*sectionDatas[bytecode::Section::kIR], block);
2236}
2237
2238LogicalResult BytecodeReader::Impl::parseVersion(EncodingReader &reader) {
2239 if (failed(reader.parseVarInt(version)))
2240 return failure();
2241
2242 // Validate the bytecode version.
2243 uint64_t currentVersion = bytecode::kVersion;
2244 uint64_t minSupportedVersion = bytecode::kMinSupportedVersion;
2245 if (version < minSupportedVersion) {
2246 return reader.emitError("bytecode version ", version,
2247 " is older than the current version of ",
2248 currentVersion, ", and upgrade is not supported");
2249 }
2250 if (version > currentVersion) {
2251 return reader.emitError("bytecode version ", version,
2252 " is newer than the current version ",
2253 currentVersion);
2254 }
2255 // Override any request to lazy-load if the bytecode version is too old.
2256 if (version < bytecode::kLazyLoading)
2257 lazyLoading = false;
2258 return success();
2259}
2260
2261//===----------------------------------------------------------------------===//
2262// Dialect Section
2263//===----------------------------------------------------------------------===//
2264
2265LogicalResult BytecodeDialect::load(const DialectReader &reader,
2266 MLIRContext *ctx) {
2267 if (dialect)
2268 return success();
2269 Dialect *loadedDialect = ctx->getOrLoadDialect(name);
2270 if (!loadedDialect && !ctx->allowsUnregisteredDialects()) {
2271 return reader.emitError("dialect '")
2272 << name
2273 << "' is unknown. If this is intended, please call "
2274 "allowUnregisteredDialects() on the MLIRContext, or use "
2275 "-allow-unregistered-dialect with the MLIR tool used.";
2276 }
2277 dialect = loadedDialect;
2278
2279 // If the dialect was actually loaded, check to see if it has a bytecode
2280 // interface.
2281 if (loadedDialect)
2282 interface = dyn_cast<BytecodeDialectInterface>(loadedDialect);
2283 if (!versionBuffer.empty()) {
2284 if (!interface)
2285 return reader.emitError("dialect '")
2286 << name
2287 << "' does not implement the bytecode interface, "
2288 "but found a version entry";
2289 EncodingReader encReader(versionBuffer, reader.getLoc());
2290 DialectReader versionReader = reader.withEncodingReader(encReader);
2291 loadedVersion = interface->readVersion(versionReader);
2292 if (!loadedVersion)
2293 return failure();
2294 }
2295 return success();
2296}
2297
2298LogicalResult
2299BytecodeReader::Impl::parseDialectSection(ArrayRef<uint8_t> sectionData) {
2300 EncodingReader sectionReader(sectionData, fileLoc);
2301
2302 // Parse the number of dialects in the section.
2303 uint64_t numDialects;
2304 if (failed(sectionReader.parseVarInt(numDialects)))
2305 return failure();
2306 dialects.resize(numDialects);
2307
2308 const auto checkSectionAlignment = [&](unsigned alignment) {
2309 return this->checkSectionAlignment(alignment, [&](const auto &msg) {
2310 return sectionReader.emitError(msg);
2311 });
2312 };
2313
2314 // Parse each of the dialects.
2315 for (uint64_t i = 0; i < numDialects; ++i) {
2316 dialects[i] = std::make_unique<BytecodeDialect>();
2317 /// Before version kDialectVersioning, there wasn't any versioning available
2318 /// for dialects, and the entryIdx represent the string itself.
2319 if (version < bytecode::kDialectVersioning) {
2320 if (failed(stringReader.parseString(sectionReader, dialects[i]->name)))
2321 return failure();
2322 continue;
2323 }
2324
2325 // Parse ID representing dialect and version.
2326 uint64_t dialectNameIdx;
2327 bool versionAvailable;
2328 if (failed(sectionReader.parseVarIntWithFlag(dialectNameIdx,
2329 versionAvailable)))
2330 return failure();
2331 if (failed(stringReader.parseStringAtIndex(sectionReader, dialectNameIdx,
2332 dialects[i]->name)))
2333 return failure();
2334 if (versionAvailable) {
2335 bytecode::Section::ID sectionID;
2336 if (failed(sectionReader.parseSection(sectionID, checkSectionAlignment,
2337 dialects[i]->versionBuffer)))
2338 return failure();
2339 if (sectionID != bytecode::Section::kDialectVersions) {
2340 emitError(fileLoc, "expected dialect version section");
2341 return failure();
2342 }
2343 }
2344 dialectsMap[dialects[i]->name] = dialects[i].get();
2345 }
2346
2347 // Parse the operation names, which are grouped by dialect.
2348 auto parseOpName = [&](BytecodeDialect *dialect) {
2349 StringRef opName;
2350 std::optional<bool> wasRegistered;
2351 // Prior to version kNativePropertiesEncoding, the information about wheter
2352 // an op was registered or not wasn't encoded.
2354 if (failed(stringReader.parseString(sectionReader, opName)))
2355 return failure();
2356 } else {
2357 bool wasRegisteredFlag;
2358 if (failed(stringReader.parseStringWithFlag(sectionReader, opName,
2359 wasRegisteredFlag)))
2360 return failure();
2361 wasRegistered = wasRegisteredFlag;
2362 }
2363 opNames.emplace_back(dialect, opName, wasRegistered);
2364 return success();
2365 };
2366 // Avoid re-allocation in bytecode version >=kElideUnknownBlockArgLocation
2367 // where the number of ops are known.
2369 uint64_t numOps;
2370 if (failed(sectionReader.parseVarInt(numOps)))
2371 return failure();
2372 opNames.reserve(numOps);
2373 }
2374 while (!sectionReader.empty())
2375 if (failed(parseDialectGrouping(sectionReader, dialects, parseOpName)))
2376 return failure();
2377 return success();
2378}
2379
2380FailureOr<OperationName>
2381BytecodeReader::Impl::parseOpName(EncodingReader &reader,
2382 std::optional<bool> &wasRegistered) {
2383 BytecodeOperationName *opName = nullptr;
2384 if (failed(parseEntry(reader, opNames, opName, "operation name")))
2385 return failure();
2386 wasRegistered = opName->wasRegistered;
2387 // Check to see if this operation name has already been resolved. If we
2388 // haven't, load the dialect and build the operation name.
2389 if (!opName->opName) {
2390 // If the opName is empty, this is because we use to accept names such as
2391 // `foo` without any `.` separator. We shouldn't tolerate this in textual
2392 // format anymore but for now we'll be backward compatible. This can only
2393 // happen with unregistered dialects.
2394 if (opName->name.empty()) {
2395 opName->opName.emplace(opName->dialect->name, getContext());
2396 } else {
2397 // Load the dialect and its version.
2398 DialectReader dialectReader(attrTypeReader, stringReader, resourceReader,
2399 dialectsMap, reader, version);
2400 if (failed(opName->dialect->load(dialectReader, getContext())))
2401 return failure();
2402 opName->opName.emplace((opName->dialect->name + "." + opName->name).str(),
2403 getContext());
2404 }
2405 }
2406 return *opName->opName;
2407}
2408
2409//===----------------------------------------------------------------------===//
2410// Resource Section
2411//===----------------------------------------------------------------------===//
2412
2413LogicalResult BytecodeReader::Impl::parseResourceSection(
2414 EncodingReader &reader, std::optional<ArrayRef<uint8_t>> resourceData,
2415 std::optional<ArrayRef<uint8_t>> resourceOffsetData) {
2416 // Ensure both sections are either present or not.
2417 if (resourceData.has_value() != resourceOffsetData.has_value()) {
2418 if (resourceOffsetData)
2419 return emitError(fileLoc, "unexpected resource offset section when "
2420 "resource section is not present");
2421 return emitError(
2422 fileLoc,
2423 "expected resource offset section when resource section is present");
2424 }
2425
2426 // If the resource sections are absent, there is nothing to do.
2427 if (!resourceData)
2428 return success();
2429
2430 // Initialize the resource reader with the resource sections.
2431 DialectReader dialectReader(attrTypeReader, stringReader, resourceReader,
2432 dialectsMap, reader, version);
2433 return resourceReader.initialize(fileLoc, config, dialects, stringReader,
2434 *resourceData, *resourceOffsetData,
2435 dialectReader, bufferOwnerRef);
2436}
2437
2438//===----------------------------------------------------------------------===//
2439// UseListOrder Helpers
2440//===----------------------------------------------------------------------===//
2441
2442FailureOr<BytecodeReader::Impl::UseListMapT>
2443BytecodeReader::Impl::parseUseListOrderForRange(EncodingReader &reader,
2444 uint64_t numResults) {
2445 BytecodeReader::Impl::UseListMapT map;
2446 uint64_t numValuesToRead = 1;
2447 if (numResults > 1 && failed(reader.parseVarInt(numValuesToRead)))
2448 return failure();
2449
2450 for (size_t valueIdx = 0; valueIdx < numValuesToRead; valueIdx++) {
2451 uint64_t resultIdx = 0;
2452 if (numResults > 1 && failed(reader.parseVarInt(resultIdx)))
2453 return failure();
2454
2455 uint64_t numValues;
2456 bool indexPairEncoding;
2457 if (failed(reader.parseVarIntWithFlag(numValues, indexPairEncoding)))
2458 return failure();
2459
2460 SmallVector<unsigned, 4> useListOrders;
2461 for (size_t idx = 0; idx < numValues; idx++) {
2462 uint64_t index;
2463 if (failed(reader.parseVarInt(index)))
2464 return failure();
2465 useListOrders.push_back(index);
2466 }
2467
2468 // Store in a map the result index
2469 map.try_emplace(resultIdx, UseListOrderStorage(indexPairEncoding,
2470 std::move(useListOrders)));
2471 }
2472
2473 return map;
2474}
2475
2476/// Sorts each use according to the order specified in the use-list parsed. If
2477/// the custom use-list is not found, this means that the order needs to be
2478/// consistent with the reverse pre-order walk of the IR. If multiple uses lie
2479/// on the same operation, the order will follow the reverse operand number
2480/// ordering.
2481LogicalResult BytecodeReader::Impl::sortUseListOrder(Value value) {
2482 // Early return for trivial use-lists.
2483 if (value.use_empty() || value.hasOneUse())
2484 return success();
2485
2486 bool hasIncomingOrder =
2487 valueToUseListMap.contains(value.getAsOpaquePointer());
2488
2489 // Compute the current order of the use-list with respect to the global
2490 // ordering. Detect if the order is already sorted while doing so.
2491 bool alreadySorted = true;
2492 auto &firstUse = *value.use_begin();
2493 uint64_t prevID =
2494 bytecode::getUseID(firstUse, operationIDs.at(firstUse.getOwner()));
2495 llvm::SmallVector<std::pair<unsigned, uint64_t>> currentOrder = {{0, prevID}};
2496 for (auto item : llvm::drop_begin(llvm::enumerate(value.getUses()))) {
2497 uint64_t currentID = bytecode::getUseID(
2498 item.value(), operationIDs.at(item.value().getOwner()));
2499 alreadySorted &= prevID > currentID;
2500 currentOrder.push_back({item.index(), currentID});
2501 prevID = currentID;
2502 }
2503
2504 // If the order is already sorted, and there wasn't a custom order to apply
2505 // from the bytecode file, we are done.
2506 if (alreadySorted && !hasIncomingOrder)
2507 return success();
2508
2509 // If not already sorted, sort the indices of the current order by descending
2510 // useIDs.
2511 if (!alreadySorted)
2512 std::sort(
2513 currentOrder.begin(), currentOrder.end(),
2514 [](auto elem1, auto elem2) { return elem1.second > elem2.second; });
2515
2516 if (!hasIncomingOrder) {
2517 // If the bytecode file did not contain any custom use-list order, it means
2518 // that the order was descending useID. Hence, shuffle by the first index
2519 // of the `currentOrder` pair.
2520 SmallVector<unsigned> shuffle(llvm::make_first_range(currentOrder));
2521 value.shuffleUseList(shuffle);
2522 return success();
2523 }
2524
2525 // Pull the custom order info from the map.
2526 UseListOrderStorage customOrder =
2527 valueToUseListMap.at(value.getAsOpaquePointer());
2528 SmallVector<unsigned, 4> shuffle = std::move(customOrder.indices);
2529 uint64_t numUses = value.getNumUses();
2530
2531 // If the encoding was a pair of indices `(src, dst)` for every permutation,
2532 // reconstruct the shuffle vector for every use. Initialize the shuffle vector
2533 // as identity, and then apply the mapping encoded in the indices.
2534 // This produces shuffle[oldIdx] = newPos (i.e., old_index -> new_position).
2535 if (customOrder.isIndexPairEncoding) {
2536 // Return failure if the number of indices was not representing pairs.
2537 if (shuffle.size() & 1)
2538 return failure();
2539
2540 SmallVector<unsigned, 4> newShuffle(numUses);
2541 size_t idx = 0;
2542 std::iota(newShuffle.begin(), newShuffle.end(), idx);
2543 for (idx = 0; idx < shuffle.size(); idx += 2)
2544 newShuffle[shuffle[idx]] = shuffle[idx + 1];
2545
2546 shuffle = std::move(newShuffle);
2547 }
2548
2549 // Make sure that the indices represent a valid mapping. That is, the sum of
2550 // all the values needs to be equal to (numUses - 1) * numUses / 2, and no
2551 // duplicates are allowed in the list.
2553 uint64_t accumulator = 0;
2554 for (const auto &elem : shuffle) {
2555 if (!set.insert(elem).second)
2556 return failure();
2557 accumulator += elem;
2558 }
2559 if (numUses != shuffle.size() ||
2560 accumulator != (((numUses - 1) * numUses) >> 1))
2561 return failure();
2562
2563 // Compose the shuffle with the current memory layout to produce the final
2564 // indices for shuffleUseList. shuffleUseList(indices) places the use at
2565 // current position i into position indices[i], so we need to compute
2566 // finalShuffle[readerMemIdx] = writerMemIdx.
2567 //
2568 // The two encoding paths have different shuffle conventions:
2569 //
2570 // Index-pair encoding (already normalized above):
2571 // shuffle[writerMemIdx] = sortedPos (old_index -> new_position)
2572 //
2573 // Full-shuffle encoding (writer's native format):
2574 // shuffle[sortedPos] = writerMemIdx (new_position -> old_index)
2575 //
2576 // In both cases, currentOrder[sortedPos].first gives the readerMemIdx for
2577 // a given sorted position. We fold the permutation inversion for the
2578 // full-shuffle case directly into the composition to avoid an extra pass.
2579 SmallVector<unsigned, 4> finalShuffle(numUses);
2580 if (customOrder.isIndexPairEncoding) {
2581 for (size_t writerMemIdx = 0; writerMemIdx < numUses; ++writerMemIdx)
2582 finalShuffle[currentOrder[shuffle[writerMemIdx]].first] = writerMemIdx;
2583 } else {
2584 for (size_t sortedPos = 0; sortedPos < numUses; ++sortedPos)
2585 finalShuffle[currentOrder[sortedPos].first] = shuffle[sortedPos];
2586 }
2587 shuffle = std::move(finalShuffle);
2588
2589 value.shuffleUseList(shuffle);
2590 return success();
2591}
2592
2593LogicalResult BytecodeReader::Impl::processUseLists(Operation *topLevelOp) {
2594 // Precompute operation IDs according to the pre-order walk of the IR. We
2595 // can't do this while parsing since parseRegions ordering is not strictly
2596 // equal to the pre-order walk.
2597 unsigned operationID = 0;
2598 topLevelOp->walk<mlir::WalkOrder::PreOrder>(
2599 [&](Operation *op) { operationIDs.try_emplace(op, operationID++); });
2600
2601 auto blockWalk = topLevelOp->walk([this](Block *block) {
2602 for (auto arg : block->getArguments())
2603 if (failed(sortUseListOrder(arg)))
2604 return WalkResult::interrupt();
2605 return WalkResult::advance();
2606 });
2607
2608 auto resultWalk = topLevelOp->walk([this](Operation *op) {
2609 for (auto result : op->getResults())
2610 if (failed(sortUseListOrder(result)))
2611 return WalkResult::interrupt();
2612 return WalkResult::advance();
2613 });
2614
2615 return failure(blockWalk.wasInterrupted() || resultWalk.wasInterrupted());
2616}
2617
2618//===----------------------------------------------------------------------===//
2619// IR Section
2620//===----------------------------------------------------------------------===//
2621
2622LogicalResult
2623BytecodeReader::Impl::parseIRSection(ArrayRef<uint8_t> sectionData,
2624 Block *block) {
2625 EncodingReader reader(sectionData, fileLoc);
2626
2627 // A stack of operation regions currently being read from the bytecode.
2628 std::vector<RegionReadState> regionStack;
2629
2630 // Parse the top-level block using a temporary module operation.
2631 OwningOpRef<ModuleOp> moduleOp = ModuleOp::create(fileLoc);
2632 regionStack.emplace_back(*moduleOp, &reader, /*isIsolatedFromAbove=*/true);
2633 regionStack.back().curBlocks.push_back(moduleOp->getBody());
2634 regionStack.back().curBlock = regionStack.back().curRegion->begin();
2635 if (failed(parseBlockHeader(reader, regionStack.back())))
2636 return failure();
2637 valueScopes.emplace_back();
2638 valueScopes.back().push(regionStack.back());
2639
2640 // Iteratively parse regions until everything has been resolved.
2641 while (!regionStack.empty())
2642 if (failed(parseRegions(regionStack, regionStack.back())))
2643 return failure();
2644 if (!forwardRefOps.empty()) {
2645 return reader.emitError(
2646 "not all forward unresolved forward operand references");
2647 }
2648
2649 // Sort use-lists according to what specified in bytecode.
2650 if (failed(processUseLists(*moduleOp)))
2651 return reader.emitError(
2652 "parsed use-list orders were invalid and could not be applied");
2653
2654 // Resolve dialect version.
2655 for (const std::unique_ptr<BytecodeDialect> &byteCodeDialect : dialects) {
2656 // Parsing is complete, give an opportunity to each dialect to visit the
2657 // IR and perform upgrades.
2658 if (!byteCodeDialect->loadedVersion)
2659 continue;
2660 if (byteCodeDialect->interface &&
2661 failed(byteCodeDialect->interface->upgradeFromVersion(
2662 *moduleOp, *byteCodeDialect->loadedVersion)))
2663 return failure();
2664 }
2665
2666 // Verify that the parsed operations are valid.
2667 if (config.shouldVerifyAfterParse() && failed(verify(*moduleOp)))
2668 return failure();
2669
2670 // Splice the parsed operations over to the provided top-level block.
2671 auto &parsedOps = moduleOp->getBody()->getOperations();
2672 auto &destOps = block->getOperations();
2673 destOps.splice(destOps.end(), parsedOps, parsedOps.begin(), parsedOps.end());
2674 return success();
2675}
2676
2677LogicalResult
2678BytecodeReader::Impl::parseRegions(std::vector<RegionReadState> &regionStack,
2679 RegionReadState &readState) {
2680 const auto checkSectionAlignment = [&](unsigned alignment) {
2681 return this->checkSectionAlignment(
2682 alignment, [&](const auto &msg) { return emitError(fileLoc, msg); });
2683 };
2684
2685 // Process regions, blocks, and operations until the end or if a nested
2686 // region is encountered. In this case we push a new state in regionStack and
2687 // return, the processing of the current region will resume afterward.
2688 for (; readState.curRegion != readState.endRegion; ++readState.curRegion) {
2689 // If the current block hasn't been setup yet, parse the header for this
2690 // region. The current block is already setup when this function was
2691 // interrupted to recurse down in a nested region and we resume the current
2692 // block after processing the nested region.
2693 if (readState.curBlock == Region::iterator()) {
2694 if (failed(parseRegion(readState)))
2695 return failure();
2696
2697 // If the region is empty, there is nothing to more to do.
2698 if (readState.curRegion->empty())
2699 continue;
2700 }
2701
2702 // Parse the blocks within the region.
2703 EncodingReader &reader = *readState.reader;
2704 do {
2705 while (readState.numOpsRemaining--) {
2706 // Read in the next operation. We don't read its regions directly, we
2707 // handle those afterwards as necessary.
2708 bool isIsolatedFromAbove = false;
2709 FailureOr<Operation *> op =
2710 parseOpWithoutRegions(reader, readState, isIsolatedFromAbove);
2711 if (failed(op))
2712 return failure();
2713
2714 // If the op has regions, add it to the stack for processing and return:
2715 // we stop the processing of the current region and resume it after the
2716 // inner one is completed. Unless LazyLoading is activated in which case
2717 // nested region parsing is delayed.
2718 if ((*op)->getNumRegions()) {
2719 RegionReadState childState(*op, &reader, isIsolatedFromAbove);
2720
2721 // Isolated regions are encoded as a section in version 2 and above.
2722 if (version >= bytecode::kLazyLoading && isIsolatedFromAbove) {
2723 bytecode::Section::ID sectionID;
2724 ArrayRef<uint8_t> sectionData;
2725 if (failed(reader.parseSection(sectionID, checkSectionAlignment,
2726 sectionData)))
2727 return failure();
2728 if (sectionID != bytecode::Section::kIR)
2729 return emitError(fileLoc, "expected IR section for region");
2730 childState.owningReader =
2731 std::make_unique<EncodingReader>(sectionData, fileLoc);
2732 childState.reader = childState.owningReader.get();
2733
2734 // If the user has a callback set, they have the opportunity to
2735 // control lazyloading as we go.
2736 if (lazyLoading && (!lazyOpsCallback || !lazyOpsCallback(*op))) {
2737 lazyLoadableOps.emplace_back(*op, std::move(childState));
2738 lazyLoadableOpsMap.try_emplace(*op,
2739 std::prev(lazyLoadableOps.end()));
2740 continue;
2741 }
2742 }
2743 regionStack.push_back(std::move(childState));
2744
2745 // If the op is isolated from above, push a new value scope.
2746 if (isIsolatedFromAbove)
2747 valueScopes.emplace_back();
2748 return success();
2749 }
2750 }
2751
2752 // Move to the next block of the region.
2753 if (++readState.curBlock == readState.curRegion->end())
2754 break;
2755 if (failed(parseBlockHeader(reader, readState)))
2756 return failure();
2757 } while (true);
2758
2759 // Reset the current block and any values reserved for this region.
2760 readState.curBlock = {};
2761 valueScopes.back().pop(readState);
2762 }
2763
2764 // When the regions have been fully parsed, pop them off of the read stack. If
2765 // the regions were isolated from above, we also pop the last value scope.
2766 if (readState.isIsolatedFromAbove) {
2767 assert(!valueScopes.empty() && "Expect a valueScope after reading region");
2768 valueScopes.pop_back();
2769 }
2770 assert(!regionStack.empty() && "Expect a regionStack after reading region");
2771 regionStack.pop_back();
2772 return success();
2773}
2774
2775FailureOr<Operation *>
2776BytecodeReader::Impl::parseOpWithoutRegions(EncodingReader &reader,
2777 RegionReadState &readState,
2778 bool &isIsolatedFromAbove) {
2779 // Parse the name of the operation.
2780 std::optional<bool> wasRegistered;
2781 FailureOr<OperationName> opName = parseOpName(reader, wasRegistered);
2782 if (failed(opName))
2783 return failure();
2784
2785 // Parse the operation mask, which indicates which components of the operation
2786 // are present.
2787 uint8_t opMask;
2788 if (failed(reader.parseByte(opMask)))
2789 return failure();
2790
2791 /// Parse the location.
2792 LocationAttr opLoc;
2793 if (failed(parseAttribute(reader, opLoc)))
2794 return failure();
2795
2796 // With the location and name resolved, we can start building the operation
2797 // state.
2798 OperationState opState(opLoc, *opName);
2799
2800 // Parse the attributes of the operation.
2802 DictionaryAttr dictAttr;
2803 if (failed(parseAttribute(reader, dictAttr)))
2804 return failure();
2805 opState.attributes = dictAttr;
2806 }
2807
2809 // kHasProperties wasn't emitted in older bytecode, we should never get
2810 // there without also having the `wasRegistered` flag available.
2811 if (!wasRegistered)
2812 return emitError(fileLoc,
2813 "Unexpected missing `wasRegistered` opname flag at "
2814 "bytecode version ")
2815 << version << " with properties.";
2816 // When an operation is emitted without being registered, the properties are
2817 // stored as an attribute. Otherwise the op must implement the bytecode
2818 // interface and control the serialization.
2819 if (wasRegistered) {
2820 DialectReader dialectReader(attrTypeReader, stringReader, resourceReader,
2821 dialectsMap, reader, version);
2822 if (failed(
2823 propertiesReader.read(fileLoc, dialectReader, &*opName, opState)))
2824 return failure();
2825 } else {
2826 // If the operation wasn't registered when it was emitted, the properties
2827 // was serialized as an attribute.
2828 if (failed(parseAttribute(reader, opState.propertiesAttr)))
2829 return failure();
2830 }
2831 }
2832
2833 /// Parse the results of the operation.
2835 uint64_t numResults;
2836 if (failed(reader.parseVarInt(numResults)))
2837 return failure();
2838 opState.types.resize(numResults);
2839 for (int i = 0, e = numResults; i < e; ++i)
2840 if (failed(parseType(reader, opState.types[i])))
2841 return failure();
2842 }
2843
2844 /// Parse the operands of the operation.
2846 uint64_t numOperands;
2847 if (failed(reader.parseVarInt(numOperands)))
2848 return failure();
2849 opState.operands.resize(numOperands);
2850 for (int i = 0, e = numOperands; i < e; ++i)
2851 if (!(opState.operands[i] = parseOperand(reader)))
2852 return failure();
2853 }
2854
2855 /// Parse the successors of the operation.
2857 uint64_t numSuccs;
2858 if (failed(reader.parseVarInt(numSuccs)))
2859 return failure();
2860 opState.successors.resize(numSuccs);
2861 for (int i = 0, e = numSuccs; i < e; ++i) {
2862 if (failed(parseEntry(reader, readState.curBlocks, opState.successors[i],
2863 "successor")))
2864 return failure();
2865 }
2866 }
2867
2868 /// Parse the use-list orders for the results of the operation. Use-list
2869 /// orders are available since version 3 of the bytecode.
2870 std::optional<UseListMapT> resultIdxToUseListMap = std::nullopt;
2871 if (version >= bytecode::kUseListOrdering &&
2873 size_t numResults = opState.types.size();
2874 auto parseResult = parseUseListOrderForRange(reader, numResults);
2875 if (failed(parseResult))
2876 return failure();
2877 resultIdxToUseListMap = std::move(*parseResult);
2878 }
2879
2880 /// Parse the regions of the operation.
2882 uint64_t numRegions;
2883 if (failed(reader.parseVarIntWithFlag(numRegions, isIsolatedFromAbove)))
2884 return failure();
2885
2886 opState.regions.reserve(numRegions);
2887 for (int i = 0, e = numRegions; i < e; ++i)
2888 opState.regions.push_back(std::make_unique<Region>());
2889 }
2890
2891 // Create the operation at the back of the current block.
2892 Operation *op = Operation::create(opState);
2893 readState.curBlock->push_back(op);
2894
2895 // If the operation had results, update the value references. We don't need to
2896 // do this if the current value scope is empty. That is, the op was not
2897 // encoded within a parent region.
2898 if (readState.numValues && op->getNumResults() &&
2899 failed(defineValues(reader, op->getResults())))
2900 return failure();
2901
2902 /// Store a map for every value that received a custom use-list order from the
2903 /// bytecode file.
2904 if (resultIdxToUseListMap.has_value()) {
2905 for (size_t idx = 0; idx < op->getNumResults(); idx++) {
2906 if (resultIdxToUseListMap->contains(idx)) {
2907 valueToUseListMap.try_emplace(op->getResult(idx).getAsOpaquePointer(),
2908 resultIdxToUseListMap->at(idx));
2909 }
2910 }
2911 }
2912 return op;
2913}
2914
2915LogicalResult BytecodeReader::Impl::parseRegion(RegionReadState &readState) {
2916 EncodingReader &reader = *readState.reader;
2917
2918 // Parse the number of blocks in the region.
2919 uint64_t numBlocks;
2920 if (failed(reader.parseVarInt(numBlocks)))
2921 return failure();
2922
2923 // If the region is empty, there is nothing else to do.
2924 if (numBlocks == 0)
2925 return success();
2926
2927 // Parse the number of values defined in this region.
2928 uint64_t numValues;
2929 if (failed(reader.parseVarInt(numValues)))
2930 return failure();
2931 readState.numValues = numValues;
2932
2933 // Create the blocks within this region. We do this before processing so that
2934 // we can rely on the blocks existing when creating operations.
2935 readState.curBlocks.clear();
2936 readState.curBlocks.reserve(numBlocks);
2937 for (uint64_t i = 0; i < numBlocks; ++i) {
2938 readState.curBlocks.push_back(new Block());
2939 readState.curRegion->push_back(readState.curBlocks.back());
2940 }
2941
2942 // Prepare the current value scope for this region.
2943 valueScopes.back().push(readState);
2944
2945 // Parse the entry block of the region.
2946 readState.curBlock = readState.curRegion->begin();
2947 return parseBlockHeader(reader, readState);
2948}
2949
2950LogicalResult
2951BytecodeReader::Impl::parseBlockHeader(EncodingReader &reader,
2952 RegionReadState &readState) {
2953 bool hasArgs;
2954 if (failed(reader.parseVarIntWithFlag(readState.numOpsRemaining, hasArgs)))
2955 return failure();
2956
2957 // Parse the arguments of the block.
2958 if (hasArgs && failed(parseBlockArguments(reader, &*readState.curBlock)))
2959 return failure();
2960
2961 // Uselist orders are available since version 3 of the bytecode.
2962 if (version < bytecode::kUseListOrdering)
2963 return success();
2964
2965 uint8_t hasUseListOrders = 0;
2966 if (hasArgs && failed(reader.parseByte(hasUseListOrders)))
2967 return failure();
2968
2969 if (!hasUseListOrders)
2970 return success();
2971
2972 Block &blk = *readState.curBlock;
2973 auto argIdxToUseListMap =
2974 parseUseListOrderForRange(reader, blk.getNumArguments());
2975 if (failed(argIdxToUseListMap) || argIdxToUseListMap->empty())
2976 return failure();
2977
2978 for (size_t idx = 0; idx < blk.getNumArguments(); idx++)
2979 if (argIdxToUseListMap->contains(idx))
2980 valueToUseListMap.try_emplace(blk.getArgument(idx).getAsOpaquePointer(),
2981 argIdxToUseListMap->at(idx));
2982
2983 // We don't parse the operations of the block here, that's done elsewhere.
2984 return success();
2985}
2986
2987LogicalResult BytecodeReader::Impl::parseBlockArguments(EncodingReader &reader,
2988 Block *block) {
2989 // Parse the value ID for the first argument, and the number of arguments.
2990 uint64_t numArgs;
2991 if (failed(reader.parseVarInt(numArgs)))
2992 return failure();
2993
2994 SmallVector<Type> argTypes;
2995 SmallVector<Location> argLocs;
2996 argTypes.reserve(numArgs);
2997 argLocs.reserve(numArgs);
2998
2999 Location unknownLoc = UnknownLoc::get(config.getContext());
3000 while (numArgs--) {
3001 Type argType;
3002 LocationAttr argLoc = unknownLoc;
3004 // Parse the type with hasLoc flag to determine if it has type.
3005 uint64_t typeIdx;
3006 bool hasLoc;
3007 if (failed(reader.parseVarIntWithFlag(typeIdx, hasLoc)) ||
3008 !(argType = attrTypeReader.resolveType(typeIdx)))
3009 return failure();
3010 if (hasLoc && failed(parseAttribute(reader, argLoc)))
3011 return failure();
3012 } else {
3013 // All args has type and location.
3014 if (failed(parseType(reader, argType)) ||
3015 failed(parseAttribute(reader, argLoc)))
3016 return failure();
3017 }
3018 argTypes.push_back(argType);
3019 argLocs.push_back(argLoc);
3020 }
3021 block->addArguments(argTypes, argLocs);
3022 return defineValues(reader, block->getArguments());
3023}
3024
3025//===----------------------------------------------------------------------===//
3026// Value Processing
3027//===----------------------------------------------------------------------===//
3028
3029Value BytecodeReader::Impl::parseOperand(EncodingReader &reader) {
3030 std::vector<Value> &values = valueScopes.back().values;
3031 Value *value = nullptr;
3032 if (failed(parseEntry(reader, values, value, "value")))
3033 return Value();
3034
3035 // Create a new forward reference if necessary.
3036 if (!*value)
3037 *value = createForwardRef();
3038 return *value;
3039}
3040
3041LogicalResult BytecodeReader::Impl::defineValues(EncodingReader &reader,
3042 ValueRange newValues) {
3043 ValueScope &valueScope = valueScopes.back();
3044 std::vector<Value> &values = valueScope.values;
3045
3046 unsigned &valueID = valueScope.nextValueIDs.back();
3047 unsigned valueIDEnd = valueID + newValues.size();
3048 if (valueIDEnd > values.size()) {
3049 return reader.emitError(
3050 "value index range was outside of the expected range for "
3051 "the parent region, got [",
3052 valueID, ", ", valueIDEnd, "), but the maximum index was ",
3053 values.size() - 1);
3054 }
3055
3056 // Assign the values and update any forward references.
3057 for (unsigned i = 0, e = newValues.size(); i != e; ++i, ++valueID) {
3058 Value newValue = newValues[i];
3059
3060 // Check to see if a definition for this value already exists.
3061 if (Value oldValue = std::exchange(values[valueID], newValue)) {
3062 Operation *forwardRefOp = oldValue.getDefiningOp();
3063
3064 // Assert that this is a forward reference operation. Given how we compute
3065 // definition ids (incrementally as we parse), it shouldn't be possible
3066 // for the value to be defined any other way.
3067 assert(forwardRefOp && forwardRefOp->getBlock() == &forwardRefOps &&
3068 "value index was already defined?");
3069
3070 oldValue.replaceAllUsesWith(newValue);
3071 forwardRefOp->moveBefore(&openForwardRefOps, openForwardRefOps.end());
3072 }
3073 }
3074 return success();
3075}
3076
3077Value BytecodeReader::Impl::createForwardRef() {
3078 // Check for an available existing operation to use. Otherwise, create a new
3079 // fake operation to use for the reference.
3080 if (!openForwardRefOps.empty()) {
3081 Operation *op = &openForwardRefOps.back();
3082 op->moveBefore(&forwardRefOps, forwardRefOps.end());
3083 } else {
3084 forwardRefOps.push_back(Operation::create(forwardRefOpState));
3085 }
3086 return forwardRefOps.back().getResult(0);
3087}
3088
3089//===----------------------------------------------------------------------===//
3090// Entry Points
3091//===----------------------------------------------------------------------===//
3092
3094
3096 llvm::MemoryBufferRef buffer, const ParserConfig &config, bool lazyLoading,
3097 const std::shared_ptr<llvm::SourceMgr> &bufferOwnerRef) {
3098 Location sourceFileLoc =
3099 FileLineColLoc::get(config.getContext(), buffer.getBufferIdentifier(),
3100 /*line=*/0, /*column=*/0);
3101 impl = std::make_unique<Impl>(sourceFileLoc, config, lazyLoading, buffer,
3102 bufferOwnerRef);
3103}
3104
3106 Block *block, llvm::function_ref<bool(Operation *)> lazyOpsCallback) {
3107 return impl->read(block, lazyOpsCallback);
3108}
3109
3111 return impl->getNumOpsToMaterialize();
3112}
3113
3115 return impl->isMaterializable(op);
3116}
3117
3119 Operation *op, llvm::function_ref<bool(Operation *)> lazyOpsCallback) {
3120 return impl->materialize(op, lazyOpsCallback);
3121}
3122
3123LogicalResult
3125 return impl->finalize(shouldMaterialize);
3126}
3127
3128bool mlir::isBytecode(llvm::MemoryBufferRef buffer) {
3129 return buffer.getBuffer().starts_with("ML\xefR");
3130}
3131
3132/// Read the bytecode from the provided memory buffer reference.
3133/// `bufferOwnerRef` if provided is the owning source manager for the buffer,
3134/// and may be used to extend the lifetime of the buffer.
3135static LogicalResult
3136readBytecodeFileImpl(llvm::MemoryBufferRef buffer, Block *block,
3137 const ParserConfig &config,
3138 const std::shared_ptr<llvm::SourceMgr> &bufferOwnerRef) {
3139 Location sourceFileLoc =
3140 FileLineColLoc::get(config.getContext(), buffer.getBufferIdentifier(),
3141 /*line=*/0, /*column=*/0);
3142 if (!isBytecode(buffer)) {
3143 return emitError(sourceFileLoc,
3144 "input buffer is not an MLIR bytecode file");
3145 }
3146
3147 BytecodeReader::Impl reader(sourceFileLoc, config, /*lazyLoading=*/false,
3148 buffer, bufferOwnerRef);
3149 return reader.read(block, /*lazyOpsCallback=*/nullptr);
3150}
3151
3152LogicalResult mlir::readBytecodeFile(llvm::MemoryBufferRef buffer, Block *block,
3153 const ParserConfig &config) {
3154 return readBytecodeFileImpl(buffer, block, config, /*bufferOwnerRef=*/{});
3155}
3156LogicalResult
3157mlir::readBytecodeFile(const std::shared_ptr<llvm::SourceMgr> &sourceMgr,
3158 Block *block, const ParserConfig &config) {
3159 return readBytecodeFileImpl(
3160 *sourceMgr->getMemoryBuffer(sourceMgr->getMainFileID()), block, config,
3161 sourceMgr);
3162}
return success()
static LogicalResult parseDialectGrouping(EncodingReader &reader, MutableArrayRef< std::unique_ptr< BytecodeDialect > > dialects, function_ref< LogicalResult(BytecodeDialect *)> entryCallback)
Parse a single dialect group encoded in the byte stream.
static LogicalResult readBytecodeFileImpl(llvm::MemoryBufferRef buffer, Block *block, const ParserConfig &config, const std::shared_ptr< llvm::SourceMgr > &bufferOwnerRef)
Read the bytecode from the provided memory buffer reference.
static bool isSectionOptional(bytecode::Section::ID sectionID, int version)
Returns true if the given top-level section ID is optional.
static LogicalResult parseResourceGroup(Location fileLoc, bool allowEmpty, EncodingReader &offsetReader, EncodingReader &resourceReader, StringSectionReader &stringReader, T *handler, const std::shared_ptr< llvm::SourceMgr > &bufferOwnerRef, function_ref< StringRef(StringRef)> remapKey={}, function_ref< LogicalResult(StringRef)> processKeyFn={})
static LogicalResult resolveEntry(EncodingReader &reader, RangeT &entries, uint64_t index, T &entry, StringRef entryStr)
Resolve an index into the given entry list.
static LogicalResult parseEntry(EncodingReader &reader, RangeT &entries, T &entry, StringRef entryStr)
Parse and resolve an index into the given entry list.
LogicalResult initialize(unsigned origNumLoops, ArrayRef< ReassociationIndices > foldedIterationDims)
b getContext())
auto load
*if copies could not be generated due to yet unimplemented cases *copyInPlacementStart and copyOutPlacementStart in copyPlacementBlock *specify the insertion points where the incoming copies and outgoing should be inserted(the insertion happens right before the *insertion point). Since `begin` can itself be invalidated due to the memref *rewriting done from this method
StringRef getName() const
Return the unique name representing the type.
MutableArrayRef< char > getMutableData()
Return a mutable reference to the raw underlying data of this blob.
Definition AsmState.h:157
ArrayRef< char > getData() const
Return the raw underlying data of this blob.
Definition AsmState.h:145
bool isMutable() const
Return if the data of this blob is mutable.
Definition AsmState.h:164
MLIRContext * getContext() const
Return the context this attribute belongs to.
Block represents an ordered list of Operations.
Definition Block.h:34
BlockArgument getArgument(unsigned i)
Definition Block.h:154
unsigned getNumArguments()
Definition Block.h:153
iterator_range< args_iterator > addArguments(TypeRange types, ArrayRef< Location > locs)
Add one argument to the argument list for each type specified in the list.
Definition Block.cpp:165
OpListType & getOperations()
Definition Block.h:162
BlockArgListType getArguments()
Definition Block.h:112
ArrayRef< std::unique_ptr< AttrTypeBytecodeReader< Type > > > getTypeCallbacks() const
ArrayRef< std::unique_ptr< AttrTypeBytecodeReader< Attribute > > > getAttributeCallbacks() const
Returns the callbacks available to the parser.
This class is used to read a bytecode buffer and translate it into MLIR.
LogicalResult materializeAll()
Materialize all operations.
LogicalResult read(Block *block, llvm::function_ref< bool(Operation *)> lazyOps)
Read the bytecode defined within buffer into the given block.
bool isMaterializable(Operation *op)
Impl(Location fileLoc, const ParserConfig &config, bool lazyLoading, llvm::MemoryBufferRef buffer, const std::shared_ptr< llvm::SourceMgr > &bufferOwnerRef)
LogicalResult finalize(function_ref< bool(Operation *)> shouldMaterialize)
Finalize the lazy-loading by calling back with every op that hasn't been materialized to let the clie...
LogicalResult materialize(Operation *op, llvm::function_ref< bool(Operation *)> lazyOpsCallback)
Materialize the provided operation, invoke the lazyOpsCallback on every newly found lazy operation.
int64_t getNumOpsToMaterialize() const
Return the number of ops that haven't been materialized yet.
LogicalResult materialize(Operation *op, llvm::function_ref< bool(Operation *)> lazyOpsCallback=[](Operation *) { return false;})
Materialize the provide operation.
LogicalResult finalize(function_ref< bool(Operation *)> shouldMaterialize=[](Operation *) { return true;})
Finalize the lazy-loading by calling back with every op that hasn't been materialized to let the clie...
BytecodeReader(llvm::MemoryBufferRef buffer, const ParserConfig &config, bool lazyLoad, const std::shared_ptr< llvm::SourceMgr > &bufferOwnerRef={})
Create a bytecode reader for the given buffer.
int64_t getNumOpsToMaterialize() const
Return the number of ops that haven't been materialized yet.
bool isMaterializable(Operation *op)
Return true if the provided op is materializable.
LogicalResult readTopLevel(Block *block, llvm::function_ref< bool(Operation *)> lazyOps=[](Operation *) { return false;})
Read the operations defined within the given memory buffer, containing MLIR bytecode,...
This class contains all of the information necessary to report a diagnostic to the DiagnosticEngine.
static FileLineColLoc get(StringAttr filename, unsigned line, unsigned column)
Definition Location.cpp:161
This class represents a diagnostic that is inflight and set to be reported.
InFlightDiagnostic & append(Args &&...args) &
Append arguments to the diagnostic.
This class defines the main interface for locations in MLIR and acts as a non-nullable wrapper around...
Definition Location.h:76
MLIRContext * getContext() const
Return the context this location is uniqued in.
Definition Location.h:86
MLIRContext is the top-level object for a collection of MLIR operations.
Definition MLIRContext.h:71
T * getOrLoadDialect()
Get (or create) a dialect for the given derived dialect type.
bool allowsUnregisteredDialects()
Return true if we allow to create operation for unregistered dialects.
StringRef getStringRef() const
Return the name of this operation. This always succeeds.
bool isRegistered() const
Return if this operation is registered.
T::Concept * getInterface() const
Returns an instance of the concept object for the given interface if it was registered to this operat...
Operation is the basic unit of execution within MLIR.
Definition Operation.h:87
void dropAllReferences()
This drops all operand uses from this operation, which is an essential step in breaking cyclic depend...
Block * getBlock()
Returns the operation block that contains this operation.
Definition Operation.h:230
OpResult getResult(unsigned idx)
Get the 'idx'th result of this operation.
Definition Operation.h:434
static Operation * create(Location location, OperationName name, TypeRange resultTypes, ValueRange operands, NamedAttrList &&attributes, PropertyRef properties, BlockRange successors, unsigned numRegions)
Create a new Operation with the specific fields.
Definition Operation.cpp:65
void moveBefore(Operation *existingOp)
Unlink this operation from its current block and insert it right before existingOp which may be in th...
std::enable_if_t< llvm::function_traits< std::decay_t< FnT > >::num_args==1, RetT > walk(FnT &&callback)
Walk the operation by calling the callback for each nested operation (including this one),...
Definition Operation.h:851
result_range getResults()
Definition Operation.h:442
void erase()
Remove this operation from its parent block and delete it.
unsigned getNumResults()
Return the number of results held by this operation.
Definition Operation.h:431
This class represents a configuration for the MLIR assembly parser.
Definition AsmState.h:469
MLIRContext * getContext() const
Return the MLIRContext to be used when parsing.
Definition AsmState.h:483
bool shouldVerifyAfterParse() const
Returns if the parser should verify the IR after parsing.
Definition AsmState.h:486
BytecodeReaderConfig & getBytecodeReaderConfig() const
Returns the parsing configurations associated to the bytecode read.
Definition AsmState.h:489
AsmResourceParser * getResourceParser(StringRef name) const
Return the resource parser registered to the given name, or nullptr if no parser with name is registe...
Definition AsmState.h:495
BlockListType::iterator iterator
Definition Region.h:52
This diagnostic handler is a simple RAII class that registers and erases a diagnostic handler on a gi...
const AbstractTy & getAbstractType() const
Return the abstract type descriptor for this type.
Definition Types.h:192
bool hasTrait()
Returns true if the type was registered with a particular trait.
Definition Types.h:187
static AsmResourceBlob allocateWithAlign(ArrayRef< char > data, size_t align, AsmResourceBlob::DeleterFn deleter={}, bool dataIsMutable=false)
Create a new unmanaged resource directly referencing the provided data.
Definition AsmState.h:228
This class provides an abstraction over the different types of ranges over Values.
Definition ValueRange.h:392
bool use_empty() const
Returns true if this value has no uses.
Definition Value.h:208
void shuffleUseList(ArrayRef< unsigned > indices)
Shuffle the use list order according to the provided indices.
Definition Value.cpp:111
use_range getUses() const
Returns a range of all uses, which is useful for iterating over all uses.
Definition Value.h:188
void * getAsOpaquePointer() const
Methods for supporting PointerLikeTypeTraits.
Definition Value.h:235
unsigned getNumUses() const
This method computes the number of uses of this Value.
Definition Value.cpp:52
bool hasOneUse() const
Returns true if this value has exactly one use.
Definition Value.h:197
use_iterator use_begin() const
Definition Value.h:184
static WalkResult advance()
Definition WalkResult.h:47
static WalkResult interrupt()
Definition WalkResult.h:46
detail::StorageUserTrait::IsMutable< ConcreteType > IsMutable
Definition Types.h:299
@ 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
@ kNumSections
The total number of section types.
Definition Encoding.h:97
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
detail::InFlightRemark failed(Location loc, RemarkOpts opts)
Report an optimization remark that failed.
Definition Remarks.h:886
Include the generated interface declarations.
InFlightDiagnostic emitWarning(Location loc)
Utility method to emit a warning message using this location.
StringRef toString(AsmResourceEntryKind kind)
bool isBytecode(llvm::MemoryBufferRef buffer)
Returns true if the given buffer starts with the magic bytes that signal MLIR bytecode.
llvm::DenseSet< ValueT, ValueInfoT > DenseSet
Definition LLVM.h:125
InFlightDiagnostic emitError(Location loc)
Utility method to emit an error message using this location.
Attribute parseAttribute(llvm::StringRef attrStr, MLIRContext *context, Type type={}, size_t *numRead=nullptr, bool isKnownNullTerminated=false)
This parses a single MLIR attribute to an MLIR context if it was valid.
auto get(MLIRContext *context, Ts &&...params)
Helper method that injects context only if needed, this helps unify some of the attribute constructio...
Type parseType(llvm::StringRef typeStr, MLIRContext *context, size_t *numRead=nullptr, bool isKnownNullTerminated=false)
This parses a single MLIR type to an MLIR context if it was valid.
llvm::DenseMap< KeyT, ValueT, KeyInfoT, BucketT > DenseMap
Definition LLVM.h:123
AsmResourceEntryKind
This enum represents the different kinds of resource values.
Definition AsmState.h:280
LogicalResult readBytecodeFile(llvm::MemoryBufferRef buffer, Block *block, const ParserConfig &config)
Read the operations defined within the given memory buffer, containing MLIR bytecode,...
LogicalResult verify(Operation *op, bool verifyRecursively=true)
Perform (potentially expensive) checks of invariants, used to detect compiler bugs,...
Definition Verifier.cpp:566
llvm::function_ref< Fn > function_ref
Definition LLVM.h:155
LogicalResult readResourceHandle(DialectBytecodeReader &reader, FailureOr< T > &value, Ts &&...params)
Helper for resource handle reading that returns LogicalResult.
SmallVector< Block *, 1 > successors
Successors of this operation and their respective operands.
SmallVector< Value, 4 > operands
SmallVector< std::unique_ptr< Region >, 1 > regions
Regions that the op will hold.
Attribute propertiesAttr
This Attribute is used to opaquely construct the properties of the operation.
SmallVector< Type, 4 > types
Types of the results of this operation.