1//===- CIRDialectBytecode.cpp - CIR Bytecode Implementation ---------------===//
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
9#include "CIRDialectBytecode.h"
10#include "mlir/Bytecode/BytecodeImplementation.h"
11#include "mlir/IR/Diagnostics.h"
12#include "clang/CIR/Dialect/IR/CIRAttrs.h"
13#include "clang/CIR/Dialect/IR/CIRDialect.h"
14#include "clang/CIR/Dialect/IR/CIRTypes.h"
15#include "llvm/ADT/SmallVector.h"
16#include "llvm/ADT/StringRef.h"
17
18#include <limits>
19#include <type_traits>
20
21using namespace mlir;
22using namespace cir;
23
24namespace {
25
26//===--------------------------------------------------------------------===//
27// Helpers referenced by the generated readers
28//===--------------------------------------------------------------------===//
29
30// The payload width is implied by the type (mirroring BuiltinDialectBytecode)
31// and recovered here. A mismatched type fails rather than asserts: it came
32// from the same untrusted file, so it is a corrupt-input case.
33
34static LogicalResult readAPIntWithKnownWidth(DialectBytecodeReader &reader,
35 Type type, FailureOr<APInt> &val) {
36 auto intType = mlir::dyn_cast<cir::IntTypeInterface>(Val&: type);
37 if (!intType)
38 return reader.emitError()
39 << "expected a CIR integer type for cir.int, but got: " << type;
40 val = reader.readAPIntWithKnownWidth(bitWidth: intType.getWidth());
41 return success(IsSuccess: succeeded(Result: val));
42}
43
44static LogicalResult
45readAPFloatWithKnownSemantics(DialectBytecodeReader &reader, Type type,
46 FailureOr<APFloat> &val) {
47 auto fpType = mlir::dyn_cast<cir::FPTypeInterface>(Val&: type);
48 if (!fpType)
49 return reader.emitError()
50 << "expected a CIR floating-point type for cir.fp, but got: "
51 << type;
52 val = reader.readAPFloatWithKnownSemantics(semantics: fpType.getFloatSemantics());
53 return success(IsSuccess: succeeded(Result: val));
54}
55
56// std::optional<T> parameters carry presence as a varint of its own ahead of
57// the value, so the full width survives.
58template <typename EntryTy>
59static LogicalResult readOptionalInt(DialectBytecodeReader &reader,
60 std::optional<EntryTy> &storage) {
61 static_assert(std::is_unsigned_v<EntryTy>,
62 "EntryTy must be unsigned: only unsigned varints are "
63 "supported here, so a negative value cannot be represented");
64 uint64_t present = 0;
65 if (failed(Result: reader.readVarInt(result&: present)))
66 return failure();
67 if (present == 0) {
68 storage = std::nullopt;
69 return success();
70 }
71 if (present != 1)
72 return reader.emitError() << "optional integer presence flag " << present
73 << " is neither 0 nor 1";
74 uint64_t value = 0;
75 if (failed(Result: reader.readVarInt(result&: value)))
76 return failure();
77 // Out-of-range values fail rather than truncating into a plausible index.
78 if (value > static_cast<uint64_t>(std::numeric_limits<EntryTy>::max()))
79 return reader.emitError() << "optional integer value " << value
80 << " does not fit in destination type";
81 storage = static_cast<EntryTy>(value);
82 return success();
83}
84
85template <typename EntryTy>
86static void writeOptionalInt(DialectBytecodeWriter &writer,
87 std::optional<EntryTy> storage) {
88 static_assert(std::is_unsigned_v<EntryTy>,
89 "EntryTy must be unsigned: only unsigned varints are "
90 "supported here, so a negative value cannot be represented");
91 writer.writeVarInt(value: storage.has_value() ? 1 : 0);
92 if (storage)
93 writer.writeVarInt(value: *storage);
94}
95
96// std::optional<Attr> form (cir.method's symbol). A null attribute is not a
97// valid state and normalizes to std::nullopt on the wire.
98
99template <typename AttrTy>
100static LogicalResult readStdOptionalAttribute(DialectBytecodeReader &reader,
101 std::optional<AttrTy> &storage) {
102 AttrTy attr;
103 if (failed(reader.readOptionalAttribute(attr)))
104 return failure();
105 if (attr)
106 storage = attr;
107 else
108 storage = std::nullopt;
109 return success();
110}
111
112template <typename AttrTy>
113static void writeStdOptionalAttribute(DialectBytecodeWriter &writer,
114 std::optional<AttrTy> storage) {
115 assert(!storage || *storage);
116 writer.writeOptionalAttribute(attr: storage.value_or(AttrTy()));
117}
118
119static LogicalResult readOptionalType(DialectBytecodeReader &reader,
120 Type &result) {
121 bool present = false;
122 if (failed(Result: reader.readBool(result&: present)))
123 return failure();
124 if (!present) {
125 result = Type();
126 return success();
127 }
128 return reader.readType(result);
129}
130
131static void writeOptionalType(DialectBytecodeWriter &writer, Type type) {
132 writer.writeOwnedBool(value: static_cast<bool>(type));
133 if (type)
134 writer.writeType(type);
135}
136
137// A scoped enum validated through its symbolizer; out-of-range values fail
138// instead of casting undefined values into the enum.
139template <typename EnumTy>
140static LogicalResult readEnum(DialectBytecodeReader &reader, EnumTy &result,
141 std::optional<EnumTy> (*symbolize)(uint32_t),
142 llvm::StringRef enumName) {
143 uint64_t value = 0;
144 if (failed(Result: reader.readVarInt(result&: value)))
145 return failure();
146 if (value > static_cast<uint64_t>(std::numeric_limits<uint32_t>::max()))
147 return reader.emitError()
148 << enumName << " value " << value << " out of range";
149 std::optional<EnumTy> kind = symbolize(static_cast<uint32_t>(value));
150 if (!kind)
151 return reader.emitError() << "invalid " << enumName << " value " << value;
152 result = *kind;
153 return success();
154}
155
156// A varint narrowed to a fixed-width integer; out-of-range values fail
157// instead of truncating.
158template <typename IntTy>
159static LogicalResult readCheckedInt(DialectBytecodeReader &reader,
160 IntTy &result) {
161 static_assert(std::is_integral_v<IntTy> && !std::is_same_v<IntTy, bool>);
162 if constexpr (std::is_signed_v<IntTy>) {
163 int64_t value = 0;
164 if (failed(Result: reader.readSignedVarInt(result&: value)))
165 return failure();
166 if (value > static_cast<int64_t>(std::numeric_limits<IntTy>::max()) ||
167 value < static_cast<int64_t>(std::numeric_limits<IntTy>::min()))
168 return reader.emitError() << "integer value " << value
169 << " does not fit in destination type";
170 result = static_cast<IntTy>(value);
171 } else {
172 uint64_t value = 0;
173 if (failed(Result: reader.readVarInt(result&: value)))
174 return failure();
175 if (value > static_cast<uint64_t>(std::numeric_limits<IntTy>::max()))
176 return reader.emitError() << "integer value " << value
177 << " does not fit in destination type";
178 result = static_cast<IntTy>(value);
179 }
180 return success();
181}
182
183} // namespace
184
185//===--------------------------------------------------------------------===//
186// Tablegen generated bytecode functions
187//===--------------------------------------------------------------------===//
188
189#include "clang/CIR/Dialect/IR/CIRDialectBytecode.cpp.inc"
190
191namespace {
192
193//===--------------------------------------------------------------------===//
194// CIRDialectBytecodeInterface
195//===--------------------------------------------------------------------===//
196
197/// Bytecode interface for the CIR dialect.
198struct CIRDialectBytecodeInterface : public BytecodeDialectInterface {
199 CIRDialectBytecodeInterface(Dialect *dialect)
200 : BytecodeDialectInterface(dialect) {}
201
202 Attribute readAttribute(DialectBytecodeReader &reader) const override {
203 return ::readAttribute(context: getContext(), reader);
204 }
205
206 LogicalResult writeAttribute(Attribute attr,
207 DialectBytecodeWriter &writer) const override {
208 return ::writeAttribute(attribute: attr, writer);
209 }
210
211 Type readType(DialectBytecodeReader &reader) const override {
212 return ::readType(context: getContext(), reader);
213 }
214
215 LogicalResult writeType(Type type,
216 DialectBytecodeWriter &writer) const override {
217 return ::writeType(type, writer);
218 }
219};
220} // namespace
221
222void cir::detail::addBytecodeInterface(CIRDialect *dialect) {
223 dialect->addInterfaces<CIRDialectBytecodeInterface>();
224}
225