1//===- QuantDialectBytecode.cpp - Quant Bytecode Implementation
2//------------===//
3//
4// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
5// See https://llvm.org/LICENSE.txt for license information.
6// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7//
8//===----------------------------------------------------------------------===//
9
10#include "QuantDialectBytecode.h"
11#include "mlir/Bytecode/BytecodeImplementation.h"
12#include "mlir/Dialect/Quant/IR/Quant.h"
13#include "mlir/Dialect/Quant/IR/QuantTypes.h"
14#include "mlir/IR/Diagnostics.h"
15#include "llvm/ADT/APFloat.h"
16
17using namespace mlir;
18using namespace mlir::quant;
19
20namespace {
21
22static LogicalResult readDoubleAPFloat(DialectBytecodeReader &reader,
23 double &val) {
24 auto valOr =
25 reader.readAPFloatWithKnownSemantics(semantics: llvm::APFloat::IEEEdouble());
26 if (failed(Result: valOr))
27 return failure();
28 val = valOr->convertToDouble();
29 return success();
30}
31
32static LogicalResult readOptionalSignedVarInt(DialectBytecodeReader &reader,
33 std::optional<int64_t> &val) {
34 bool hasValue;
35 if (failed(Result: reader.readBool(result&: hasValue)))
36 return failure();
37 if (hasValue) {
38 int64_t v;
39 if (failed(Result: reader.readSignedVarInt(result&: v)))
40 return failure();
41 val = v;
42 } else {
43 val = std::nullopt;
44 }
45 return success();
46}
47
48static void writeOptionalSignedVarInt(DialectBytecodeWriter &writer,
49 std::optional<int64_t> val) {
50 writer.writeOwnedBool(value: val.has_value());
51 if (val.has_value())
52 writer.writeSignedVarInt(value: *val);
53}
54} // namespace
55
56#include "mlir/Dialect/Quant/IR/QuantDialectBytecode.cpp.inc"
57
58namespace {
59/// This class implements the bytecode interface for the Quant dialect.
60struct QuantDialectBytecodeInterface : public BytecodeDialectInterface {
61 QuantDialectBytecodeInterface(Dialect *dialect)
62 : BytecodeDialectInterface(dialect) {}
63
64 //===--------------------------------------------------------------------===//
65 // Attributes
66
67 Attribute readAttribute(DialectBytecodeReader &reader) const override {
68 return ::readAttribute(context: getContext(), reader);
69 }
70
71 LogicalResult writeAttribute(Attribute attr,
72 DialectBytecodeWriter &writer) const override {
73 return ::writeAttribute(attribute: attr, writer);
74 }
75
76 //===--------------------------------------------------------------------===//
77 // Types
78
79 Type readType(DialectBytecodeReader &reader) const override {
80 return ::readType(context: getContext(), reader);
81 }
82
83 LogicalResult writeType(Type type,
84 DialectBytecodeWriter &writer) const override {
85 return ::writeType(type, writer);
86 }
87};
88} // namespace
89
90void quant::detail::addBytecodeInterface(QuantDialect *dialect) {
91 dialect->addInterfaces<QuantDialectBytecodeInterface>();
92}
93