| 1 | //===- BuiltinDialectBytecode.cpp - Builtin 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 "BuiltinDialectBytecode.h" |
| 10 | #include "AttributeDetail.h" |
| 11 | #include "mlir/Bytecode/BytecodeImplementation.h" |
| 12 | #include "mlir/IR/AffineExpr.h" |
| 13 | #include "mlir/IR/AffineMap.h" |
| 14 | #include "mlir/IR/BuiltinAttributes.h" |
| 15 | #include "mlir/IR/BuiltinDialect.h" |
| 16 | #include "mlir/IR/BuiltinOps.h" |
| 17 | #include "mlir/IR/BuiltinTypes.h" |
| 18 | #include "mlir/IR/Diagnostics.h" |
| 19 | #include "mlir/IR/DialectResourceBlobManager.h" |
| 20 | #include "mlir/IR/IntegerSet.h" |
| 21 | #include "mlir/IR/Location.h" |
| 22 | #include "mlir/Support/LLVM.h" |
| 23 | #include <cstdint> |
| 24 | |
| 25 | using namespace mlir; |
| 26 | |
| 27 | //===----------------------------------------------------------------------===// |
| 28 | // BuiltinDialectBytecodeInterface |
| 29 | //===----------------------------------------------------------------------===// |
| 30 | |
| 31 | namespace { |
| 32 | |
| 33 | //===----------------------------------------------------------------------===// |
| 34 | // Utility functions |
| 35 | //===----------------------------------------------------------------------===// |
| 36 | |
| 37 | // TODO: Move these to separate file. |
| 38 | |
| 39 | // Returns the bitwidth if known, else return std::nullopt. |
| 40 | static std::optional<unsigned> getIntegerBitWidth(DialectBytecodeReader &reader, |
| 41 | Type type) { |
| 42 | if (auto intType = dyn_cast<IntegerType>(Val&: type)) |
| 43 | return intType.getWidth(); |
| 44 | if (llvm::isa<IndexType>(Val: type)) |
| 45 | return IndexType::kInternalStorageBitWidth; |
| 46 | reader.emitError() |
| 47 | << "expected integer or index type for IntegerAttr, but got: " << type; |
| 48 | return std::nullopt; |
| 49 | } |
| 50 | |
| 51 | static LogicalResult readAPIntWithKnownWidth(DialectBytecodeReader &reader, |
| 52 | Type type, FailureOr<APInt> &val) { |
| 53 | std::optional<unsigned> bitWidth = getIntegerBitWidth(reader, type); |
| 54 | // getIntegerBitWidth returns std::nullopt and emits an error for unsupported |
| 55 | // types. Bail out early to avoid creating a zero-width APInt with a non-zero |
| 56 | // value. |
| 57 | if (!bitWidth) |
| 58 | return failure(); |
| 59 | val = reader.readAPIntWithKnownWidth(bitWidth: *bitWidth); |
| 60 | return val; |
| 61 | } |
| 62 | |
| 63 | static LogicalResult |
| 64 | readAPFloatWithKnownSemantics(DialectBytecodeReader &reader, Type type, |
| 65 | FailureOr<APFloat> &val) { |
| 66 | auto ftype = dyn_cast<FloatType>(Val&: type); |
| 67 | if (!ftype) |
| 68 | return failure(); |
| 69 | val = reader.readAPFloatWithKnownSemantics(semantics: ftype.getFloatSemantics()); |
| 70 | return success(); |
| 71 | } |
| 72 | |
| 73 | LogicalResult |
| 74 | readPotentiallySplatString(DialectBytecodeReader &reader, ShapedType type, |
| 75 | bool isSplat, |
| 76 | SmallVectorImpl<StringRef> &rawStringData) { |
| 77 | rawStringData.resize(N: isSplat ? 1 : type.getNumElements()); |
| 78 | for (StringRef &value : rawStringData) |
| 79 | if (failed(Result: reader.readString(result&: value))) |
| 80 | return failure(); |
| 81 | return success(); |
| 82 | } |
| 83 | |
| 84 | static void writePotentiallySplatString(DialectBytecodeWriter &writer, |
| 85 | DenseStringElementsAttr attr) { |
| 86 | bool isSplat = attr.isSplat(); |
| 87 | if (isSplat) |
| 88 | return writer.writeOwnedString(str: attr.getRawStringData().front()); |
| 89 | |
| 90 | for (StringRef str : attr.getRawStringData()) |
| 91 | writer.writeOwnedString(str); |
| 92 | } |
| 93 | |
| 94 | //===----------------------------------------------------------------------===// |
| 95 | // AffineExpr / AffineMap bytecode helpers |
| 96 | //===----------------------------------------------------------------------===// |
| 97 | |
| 98 | // AffineExpr kind encoding: |
| 99 | // Extra kinds may be appended here but the existing ones and their ordering |
| 100 | // should not be changed. |
| 101 | enum class AffineExprBytecodeKind : uint64_t { |
| 102 | DimId = 0, |
| 103 | SymbolId = 1, |
| 104 | Constant = 2, |
| 105 | Add = 3, |
| 106 | Mul = 4, |
| 107 | Mod = 5, |
| 108 | FloorDiv = 6, |
| 109 | CeilDiv = 7 |
| 110 | }; |
| 111 | |
| 112 | // AffineMap kind encoding. These are packed into the low 2 bits of the header |
| 113 | // varint and fixed. |
| 114 | enum class AffineMapBytecodeKind : unsigned { |
| 115 | Identity = 0, |
| 116 | Permutation = 1, |
| 117 | ProjectedPermutation = 2, |
| 118 | General = 3 |
| 119 | }; |
| 120 | |
| 121 | /// Convert a binary AffineExprKind to its bytecode wire encoding. |
| 122 | static AffineExprBytecodeKind toBytecodeKind(AffineExprKind k) { |
| 123 | switch (k) { |
| 124 | case AffineExprKind::Add: |
| 125 | return AffineExprBytecodeKind::Add; |
| 126 | case AffineExprKind::Mul: |
| 127 | return AffineExprBytecodeKind::Mul; |
| 128 | case AffineExprKind::Mod: |
| 129 | return AffineExprBytecodeKind::Mod; |
| 130 | case AffineExprKind::FloorDiv: |
| 131 | return AffineExprBytecodeKind::FloorDiv; |
| 132 | case AffineExprKind::CeilDiv: |
| 133 | return AffineExprBytecodeKind::CeilDiv; |
| 134 | default: |
| 135 | llvm_unreachable("not a binary AffineExprKind" ); |
| 136 | } |
| 137 | } |
| 138 | |
| 139 | /// Convert a bytecode wire value back to a binary AffineExprKind. |
| 140 | /// Caller must guarantee `kind` is one of the binary operator values. |
| 141 | static AffineExprKind fromBytecodeKind(uint64_t kind) { |
| 142 | switch (kind) { |
| 143 | case static_cast<uint64_t>(AffineExprBytecodeKind::Add): |
| 144 | return AffineExprKind::Add; |
| 145 | case static_cast<uint64_t>(AffineExprBytecodeKind::Mul): |
| 146 | return AffineExprKind::Mul; |
| 147 | case static_cast<uint64_t>(AffineExprBytecodeKind::Mod): |
| 148 | return AffineExprKind::Mod; |
| 149 | case static_cast<uint64_t>(AffineExprBytecodeKind::FloorDiv): |
| 150 | return AffineExprKind::FloorDiv; |
| 151 | case static_cast<uint64_t>(AffineExprBytecodeKind::CeilDiv): |
| 152 | return AffineExprKind::CeilDiv; |
| 153 | } |
| 154 | llvm_unreachable("not a binary AffineExprBytecodeKind" ); |
| 155 | } |
| 156 | |
| 157 | /// Read a single AffineExpr using iterative prefix decoding. The wire format |
| 158 | /// is prefix order (operator and then children), which is self-delimiting. |
| 159 | /// Instead of C++ recursion the reader uses an explicit work stack, bounding |
| 160 | /// memory to O(depth) and eliminating stack-overflow risk on malicious input. |
| 161 | static LogicalResult readAffineExpr(DialectBytecodeReader &reader, |
| 162 | MLIRContext *context, AffineExpr &expr) { |
| 163 | // A work-stack item is either ReadOperand (0) or a combine marker whose |
| 164 | // payload is an AffineExprKind. |
| 165 | struct WorkItem { |
| 166 | bool isCombine; |
| 167 | AffineExprKind combineKind; // only valid when isCombine == true |
| 168 | static WorkItem read() { return {.isCombine: false, .combineKind: {}}; } |
| 169 | static WorkItem combine(AffineExprKind k) { return {.isCombine: true, .combineKind: k}; } |
| 170 | }; |
| 171 | |
| 172 | SmallVector<WorkItem, 16> work; |
| 173 | SmallVector<AffineExpr, 8> operands; |
| 174 | work.push_back(Elt: WorkItem::read()); |
| 175 | |
| 176 | while (!work.empty()) { |
| 177 | // Bound total iterations to catch malformed input. |
| 178 | if (work.size() > 128) |
| 179 | return reader.emitError(msg: "AffineExpr work stack overflow" ); |
| 180 | |
| 181 | WorkItem item = work.pop_back_val(); |
| 182 | |
| 183 | if (item.isCombine) { |
| 184 | // Pop two operands and combine. |
| 185 | if (operands.size() < 2) |
| 186 | return reader.emitError(msg: "malformed AffineExpr: operand underflow" ); |
| 187 | AffineExpr rhs = operands.pop_back_val(); |
| 188 | AffineExpr lhs = operands.pop_back_val(); |
| 189 | operands.push_back(Elt: getAffineBinaryOpExpr(kind: item.combineKind, lhs, rhs)); |
| 190 | continue; |
| 191 | } |
| 192 | |
| 193 | // ReadOperand: read the next token. |
| 194 | uint64_t kind; |
| 195 | if (failed(Result: reader.readVarInt(result&: kind))) |
| 196 | return failure(); |
| 197 | |
| 198 | // Switch on the raw uint64_t to keep the default case valid for |
| 199 | // unknown/future wire values without triggering -Wcovered-switch-default. |
| 200 | switch (kind) { |
| 201 | case static_cast<uint64_t>(AffineExprBytecodeKind::DimId): { |
| 202 | uint64_t position; |
| 203 | if (failed(Result: reader.readVarInt(result&: position))) |
| 204 | return failure(); |
| 205 | operands.push_back(Elt: getAffineDimExpr(position, context)); |
| 206 | break; |
| 207 | } |
| 208 | case static_cast<uint64_t>(AffineExprBytecodeKind::SymbolId): { |
| 209 | uint64_t position; |
| 210 | if (failed(Result: reader.readVarInt(result&: position))) |
| 211 | return failure(); |
| 212 | operands.push_back(Elt: getAffineSymbolExpr(position, context)); |
| 213 | break; |
| 214 | } |
| 215 | case static_cast<uint64_t>(AffineExprBytecodeKind::Constant): { |
| 216 | int64_t value; |
| 217 | if (failed(Result: reader.readSignedVarInt(result&: value))) |
| 218 | return failure(); |
| 219 | operands.push_back(Elt: getAffineConstantExpr(constant: value, context)); |
| 220 | break; |
| 221 | } |
| 222 | case static_cast<uint64_t>(AffineExprBytecodeKind::Add): |
| 223 | case static_cast<uint64_t>(AffineExprBytecodeKind::Mul): |
| 224 | case static_cast<uint64_t>(AffineExprBytecodeKind::Mod): |
| 225 | case static_cast<uint64_t>(AffineExprBytecodeKind::FloorDiv): |
| 226 | case static_cast<uint64_t>(AffineExprBytecodeKind::CeilDiv): { |
| 227 | // Schedule: read RHS, read LHS, then combine. |
| 228 | // Work stack is LIFO, so push in reverse order. |
| 229 | work.push_back(Elt: WorkItem::combine(k: fromBytecodeKind(kind))); |
| 230 | work.push_back(Elt: WorkItem::read()); // RHS |
| 231 | work.push_back(Elt: WorkItem::read()); // LHS |
| 232 | break; |
| 233 | } |
| 234 | default: |
| 235 | return reader.emitError(msg: "unknown AffineExpr kind: " ) << kind, failure(); |
| 236 | } |
| 237 | } |
| 238 | |
| 239 | if (operands.size() != 1) |
| 240 | return reader.emitError(msg: "malformed AffineExpr: expected single result" ), |
| 241 | failure(); |
| 242 | |
| 243 | expr = operands.front(); |
| 244 | return success(); |
| 245 | } |
| 246 | |
| 247 | /// Write an AffineExpr in prefix order (operator first, then children). |
| 248 | static void writeAffineExpr(DialectBytecodeWriter &writer, AffineExpr expr) { |
| 249 | switch (expr.getKind()) { |
| 250 | case AffineExprKind::DimId: |
| 251 | writer.writeVarInt(value: static_cast<uint64_t>(AffineExprBytecodeKind::DimId)); |
| 252 | writer.writeVarInt(value: cast<AffineDimExpr>(Val&: expr).getPosition()); |
| 253 | break; |
| 254 | case AffineExprKind::SymbolId: |
| 255 | writer.writeVarInt(value: static_cast<uint64_t>(AffineExprBytecodeKind::SymbolId)); |
| 256 | writer.writeVarInt(value: cast<AffineSymbolExpr>(Val&: expr).getPosition()); |
| 257 | break; |
| 258 | case AffineExprKind::Constant: |
| 259 | writer.writeVarInt(value: static_cast<uint64_t>(AffineExprBytecodeKind::Constant)); |
| 260 | writer.writeSignedVarInt(value: cast<AffineConstantExpr>(Val&: expr).getValue()); |
| 261 | break; |
| 262 | case AffineExprKind::Add: |
| 263 | case AffineExprKind::Mul: |
| 264 | case AffineExprKind::Mod: |
| 265 | case AffineExprKind::FloorDiv: |
| 266 | case AffineExprKind::CeilDiv: { |
| 267 | // Write operator first (prefix order). |
| 268 | writer.writeVarInt(value: static_cast<uint64_t>(toBytecodeKind(k: expr.getKind()))); |
| 269 | auto binExpr = cast<AffineBinaryOpExpr>(Val&: expr); |
| 270 | writeAffineExpr(writer, expr: binExpr.getLHS()); |
| 271 | writeAffineExpr(writer, expr: binExpr.getRHS()); |
| 272 | break; |
| 273 | } |
| 274 | } |
| 275 | } |
| 276 | |
| 277 | /// Read an AffineMap with packed kind header. |
| 278 | /// |
| 279 | /// AffineMap := |
| 280 | /// header(varint) // (numDims << 2) | mapKind |
| 281 | /// payload // depends on mapKind |
| 282 | /// |
| 283 | /// The header is there for concise encoding of the most common occuring cases. |
| 284 | /// |
| 285 | /// mapKind = header & 0x3: |
| 286 | /// Identity(0): no further data |
| 287 | /// Permutation(1): positions(varint*) |
| 288 | /// ProjectedPermutation(2): numResults(varint), positions(varint*) |
| 289 | /// General(3): numSymbols(varint), numResults(varint), results(AffineExpr*) |
| 290 | static LogicalResult readAffineMap(DialectBytecodeReader &reader, |
| 291 | MLIRContext *context, AffineMap &map) { |
| 292 | uint64_t ; |
| 293 | if (failed(Result: reader.readVarInt(result&: header))) |
| 294 | return failure(); |
| 295 | |
| 296 | // Keep as unsigned to avoid -Wcovered-switch-default below. |
| 297 | unsigned mapKind = header & 0x3; |
| 298 | unsigned numDims = header >> 2; |
| 299 | |
| 300 | switch (mapKind) { |
| 301 | case static_cast<unsigned>(AffineMapBytecodeKind::Identity): |
| 302 | map = AffineMap::getMultiDimIdentityMap(numDims, context); |
| 303 | return success(); |
| 304 | |
| 305 | case static_cast<unsigned>(AffineMapBytecodeKind::Permutation): { |
| 306 | SmallVector<unsigned> perm(numDims); |
| 307 | for (unsigned i = 0; i < numDims; ++i) { |
| 308 | uint64_t pos; |
| 309 | if (failed(Result: reader.readVarInt(result&: pos))) |
| 310 | return failure(); |
| 311 | perm[i] = pos; |
| 312 | } |
| 313 | map = AffineMap::getPermutationMap(permutation: perm, context); |
| 314 | return success(); |
| 315 | } |
| 316 | |
| 317 | case static_cast<unsigned>(AffineMapBytecodeKind::ProjectedPermutation): { |
| 318 | uint64_t numResults; |
| 319 | if (failed(Result: reader.readVarInt(result&: numResults))) |
| 320 | return failure(); |
| 321 | SmallVector<AffineExpr> results; |
| 322 | results.reserve(N: numResults); |
| 323 | for (uint64_t i = 0; i < numResults; ++i) { |
| 324 | uint64_t pos; |
| 325 | if (failed(Result: reader.readVarInt(result&: pos))) |
| 326 | return failure(); |
| 327 | results.push_back(Elt: getAffineDimExpr(position: pos, context)); |
| 328 | } |
| 329 | map = AffineMap::get(dimCount: numDims, /*numSymbols=*/symbolCount: 0, results, context); |
| 330 | return success(); |
| 331 | } |
| 332 | |
| 333 | case static_cast<unsigned>(AffineMapBytecodeKind::General): { |
| 334 | uint64_t numSymbols, numResults; |
| 335 | if (failed(Result: reader.readVarInt(result&: numSymbols)) || |
| 336 | failed(Result: reader.readVarInt(result&: numResults))) |
| 337 | return failure(); |
| 338 | SmallVector<AffineExpr> results; |
| 339 | results.reserve(N: numResults); |
| 340 | for (uint64_t i = 0; i < numResults; ++i) { |
| 341 | AffineExpr expr; |
| 342 | if (failed(Result: readAffineExpr(reader, context, expr))) |
| 343 | return failure(); |
| 344 | results.push_back(Elt: expr); |
| 345 | } |
| 346 | map = AffineMap::get(dimCount: numDims, symbolCount: numSymbols, results, context); |
| 347 | return success(); |
| 348 | } |
| 349 | |
| 350 | default: |
| 351 | return reader.emitError(msg: "unknown AffineMap kind: " ) |
| 352 | << static_cast<unsigned>(mapKind), |
| 353 | failure(); |
| 354 | } |
| 355 | } |
| 356 | |
| 357 | /// Write an AffineMap with packed kind header (see readAffineMap for format). |
| 358 | static void writeAffineMap(DialectBytecodeWriter &writer, AffineMapAttr attr) { |
| 359 | AffineMap map = attr.getValue(); |
| 360 | unsigned numDims = map.getNumDims(); |
| 361 | |
| 362 | // Identity maps: (d0, d1, ..., d_{n-1}) -> (d0, d1, ..., d_{n-1}) |
| 363 | // Note: isIdentity() does not check numSymbols, so guard explicitly. |
| 364 | if (map.getNumSymbols() == 0 && map.isIdentity()) { |
| 365 | writer.writeVarInt(value: (numDims << 2) | |
| 366 | static_cast<unsigned>(AffineMapBytecodeKind::Identity)); |
| 367 | return; |
| 368 | } |
| 369 | |
| 370 | // Permutation maps: numResults == numDims, each result is a unique dim |
| 371 | if (map.isPermutation()) { |
| 372 | writer.writeVarInt( |
| 373 | value: (numDims << 2) | |
| 374 | static_cast<unsigned>(AffineMapBytecodeKind::Permutation)); |
| 375 | for (unsigned i = 0; i < map.getNumResults(); ++i) |
| 376 | writer.writeVarInt(value: map.getDimPosition(idx: i)); |
| 377 | return; |
| 378 | } |
| 379 | |
| 380 | // Projected permutation maps (symbol-less): subset of dims |
| 381 | if (map.getNumSymbols() == 0 && map.isProjectedPermutation()) { |
| 382 | writer.writeVarInt( |
| 383 | value: (numDims << 2) | |
| 384 | static_cast<unsigned>(AffineMapBytecodeKind::ProjectedPermutation)); |
| 385 | writer.writeVarInt(value: map.getNumResults()); |
| 386 | for (unsigned i = 0; i < map.getNumResults(); ++i) |
| 387 | writer.writeVarInt(value: map.getDimPosition(idx: i)); |
| 388 | return; |
| 389 | } |
| 390 | |
| 391 | // General case |
| 392 | writer.writeVarInt(value: (numDims << 2) | |
| 393 | static_cast<unsigned>(AffineMapBytecodeKind::General)); |
| 394 | writer.writeVarInt(value: map.getNumSymbols()); |
| 395 | writer.writeVarInt(value: map.getNumResults()); |
| 396 | for (AffineExpr expr : map.getResults()) |
| 397 | writeAffineExpr(writer, expr); |
| 398 | } |
| 399 | |
| 400 | static FileLineColRange getFileLineColRange(MLIRContext *context, |
| 401 | StringAttr filename, |
| 402 | ArrayRef<uint64_t> lineCols) { |
| 403 | switch (lineCols.size()) { |
| 404 | case 0: |
| 405 | return FileLineColRange::get(filename); |
| 406 | case 1: |
| 407 | return FileLineColRange::get(filename, line: lineCols[0]); |
| 408 | case 2: |
| 409 | return FileLineColRange::get(filename, line: lineCols[0], column: lineCols[1]); |
| 410 | case 3: |
| 411 | return FileLineColRange::get(filename, line: lineCols[0], start_column: lineCols[1], |
| 412 | end_column: lineCols[2]); |
| 413 | case 4: |
| 414 | return FileLineColRange::get(filename, start_line: lineCols[0], start_column: lineCols[1], |
| 415 | end_line: lineCols[2], end_column: lineCols[3]); |
| 416 | default: |
| 417 | return {}; |
| 418 | } |
| 419 | } |
| 420 | |
| 421 | static LogicalResult |
| 422 | readFileLineColRangeLocs(DialectBytecodeReader &reader, |
| 423 | SmallVectorImpl<uint64_t> &lineCols) { |
| 424 | return reader.readList( |
| 425 | result&: lineCols, callback: [&reader](uint64_t &val) { return reader.readVarInt(result&: val); }); |
| 426 | } |
| 427 | |
| 428 | static void writeFileLineColRangeLocs(DialectBytecodeWriter &writer, |
| 429 | FileLineColRange range) { |
| 430 | if (range.getStartLine() == 0 && range.getStartColumn() == 0 && |
| 431 | range.getEndLine() == 0 && range.getEndColumn() == 0) { |
| 432 | writer.writeVarInt(value: 0); |
| 433 | return; |
| 434 | } |
| 435 | if (range.getStartColumn() == 0 && |
| 436 | range.getStartLine() == range.getEndLine()) { |
| 437 | writer.writeVarInt(value: 1); |
| 438 | writer.writeVarInt(value: range.getStartLine()); |
| 439 | return; |
| 440 | } |
| 441 | // The single file:line:col is handled by other writer, but checked here for |
| 442 | // completeness. |
| 443 | if (range.getEndColumn() == range.getStartColumn() && |
| 444 | range.getStartLine() == range.getEndLine()) { |
| 445 | writer.writeVarInt(value: 2); |
| 446 | writer.writeVarInt(value: range.getStartLine()); |
| 447 | writer.writeVarInt(value: range.getStartColumn()); |
| 448 | return; |
| 449 | } |
| 450 | if (range.getStartLine() == range.getEndLine()) { |
| 451 | writer.writeVarInt(value: 3); |
| 452 | writer.writeVarInt(value: range.getStartLine()); |
| 453 | writer.writeVarInt(value: range.getStartColumn()); |
| 454 | writer.writeVarInt(value: range.getEndColumn()); |
| 455 | return; |
| 456 | } |
| 457 | writer.writeVarInt(value: 4); |
| 458 | writer.writeVarInt(value: range.getStartLine()); |
| 459 | writer.writeVarInt(value: range.getStartColumn()); |
| 460 | writer.writeVarInt(value: range.getEndLine()); |
| 461 | writer.writeVarInt(value: range.getEndColumn()); |
| 462 | } |
| 463 | |
| 464 | static LogicalResult |
| 465 | readDenseTypedElementsAttr(DialectBytecodeReader &reader, ShapedType type, |
| 466 | SmallVectorImpl<char> &rawData) { |
| 467 | // Validate that the element type implements DenseElementTypeInterface. |
| 468 | // Without this check, downstream code unconditionally calls |
| 469 | // getDenseElementBitWidth() which asserts on unsupported types. |
| 470 | if (!llvm::isa<DenseElementType>(Val: type.getElementType())) { |
| 471 | reader.emitError() << "DenseTypedElementsAttr element type must implement " |
| 472 | "DenseElementTypeInterface, but got: " |
| 473 | << type.getElementType(); |
| 474 | return failure(); |
| 475 | } |
| 476 | |
| 477 | ArrayRef<char> blob; |
| 478 | if (failed(Result: reader.readBlob(result&: blob))) |
| 479 | return failure(); |
| 480 | |
| 481 | // If the type is not i1, just copy the blob. |
| 482 | if (!type.getElementType().isInteger(width: 1)) { |
| 483 | rawData.append(in_start: blob.begin(), in_end: blob.end()); |
| 484 | return success(); |
| 485 | } |
| 486 | |
| 487 | // Check to see if this is using the packed format. |
| 488 | // Note: this could be asserted instead as this should be the case. But we |
| 489 | // did have period where the unpacked was being serialized, this enables |
| 490 | // consuming those still and the check for which case we are in is pretty |
| 491 | // cheap. |
| 492 | size_t numElements = type.getNumElements(); |
| 493 | size_t packedSize = llvm::divideCeil(Numerator: numElements, Denominator: 8); |
| 494 | |
| 495 | // Unpack splats to single element 0x01 to match unpacked splat format. |
| 496 | if (blob.size() == 1 && blob[0] == static_cast<char>(~0x00)) { |
| 497 | rawData.resize(N: 1); |
| 498 | rawData[0] = 0x01; |
| 499 | return success(); |
| 500 | } |
| 501 | |
| 502 | // Unpack the blob if it's packed. |
| 503 | // Splat and blob.size() == packedSize for all N<=8 elements are ambiguous, |
| 504 | // non 0xFF means not splat so must be unpacked. |
| 505 | if (blob.size() == packedSize && blob.size() != numElements) { |
| 506 | rawData.resize(N: numElements); |
| 507 | for (size_t i = 0; i < numElements; ++i) |
| 508 | rawData[i] = (blob[i / 8] & (1 << (i % 8))) ? 1 : 0; |
| 509 | return success(); |
| 510 | } |
| 511 | // Otherwise, fallback to the default behavior. |
| 512 | rawData.append(in_start: blob.begin(), in_end: blob.end()); |
| 513 | return success(); |
| 514 | } |
| 515 | |
| 516 | static void writeDenseTypedElementsAttr(DialectBytecodeWriter &writer, |
| 517 | DenseTypedElementsAttr attr) { |
| 518 | // Check to see if this is an i1 dense attribute. |
| 519 | if (attr.getElementType().isInteger(width: 1)) { |
| 520 | // Pack the data. |
| 521 | SmallVector<char> data; |
| 522 | ArrayRef<char> rawData = attr.getRawData(); |
| 523 | |
| 524 | // If the attribute is a splat, we can just splat the value directly. |
| 525 | // Use 0xFF to avoid ambiguity with packed format of <=8 elements, |
| 526 | // written ~0x00 to ensure proper compilation with signed chars. |
| 527 | if (attr.isSplat()) { |
| 528 | data.resize(N: 1); |
| 529 | data[0] = rawData[0] ? ~0x00 : 0x00; |
| 530 | writer.writeUnownedBlob(blob: data); |
| 531 | return; |
| 532 | } |
| 533 | |
| 534 | size_t numElements = attr.getNumElements(); |
| 535 | data.resize(N: llvm::divideCeil(Numerator: numElements, Denominator: 8)); |
| 536 | // Otherwise, pack the data manually. |
| 537 | for (size_t i = 0; i < numElements; ++i) |
| 538 | if (rawData[i]) |
| 539 | data[i / 8] |= (1 << (i % 8)); |
| 540 | writer.writeUnownedBlob(blob: data); |
| 541 | return; |
| 542 | } |
| 543 | |
| 544 | writer.writeOwnedBlob(blob: attr.getRawData()); |
| 545 | } |
| 546 | } // namespace |
| 547 | |
| 548 | #include "mlir/IR/BuiltinDialectBytecode.cpp.inc" |
| 549 | |
| 550 | namespace { |
| 551 | /// This class implements the bytecode interface for the builtin dialect. |
| 552 | struct BuiltinDialectBytecodeInterface : public BytecodeDialectInterface { |
| 553 | BuiltinDialectBytecodeInterface(Dialect *dialect) |
| 554 | : BytecodeDialectInterface(dialect) {} |
| 555 | |
| 556 | //===--------------------------------------------------------------------===// |
| 557 | // Attributes |
| 558 | |
| 559 | Attribute readAttribute(DialectBytecodeReader &reader) const override { |
| 560 | return ::readAttribute(context: getContext(), reader); |
| 561 | } |
| 562 | |
| 563 | LogicalResult writeAttribute(Attribute attr, |
| 564 | DialectBytecodeWriter &writer) const override { |
| 565 | return ::writeAttribute(attribute: attr, writer); |
| 566 | } |
| 567 | |
| 568 | //===--------------------------------------------------------------------===// |
| 569 | // Types |
| 570 | |
| 571 | Type readType(DialectBytecodeReader &reader) const override { |
| 572 | return ::readType(context: getContext(), reader); |
| 573 | } |
| 574 | |
| 575 | LogicalResult writeType(Type type, |
| 576 | DialectBytecodeWriter &writer) const override { |
| 577 | return ::writeType(type, writer); |
| 578 | } |
| 579 | |
| 580 | //===--------------------------------------------------------------------===// |
| 581 | // Version |
| 582 | |
| 583 | std::unique_ptr<DialectVersion> |
| 584 | parseVersion(StringRef version) const override { |
| 585 | int64_t parsedVersion; |
| 586 | if (version.getAsInteger(Radix: 10, Result&: parsedVersion) || parsedVersion < 0 || |
| 587 | parsedVersion > BuiltinDialectVersion::getCurrentVersion().getVersion()) |
| 588 | return nullptr; |
| 589 | return std::make_unique<BuiltinDialectVersion>(args&: parsedVersion); |
| 590 | } |
| 591 | |
| 592 | LogicalResult verifyVersion(Operation *topLevelOp, |
| 593 | const DialectVersion &version) const override { |
| 594 | if (static_cast<const BuiltinDialectVersion &>(version).getVersion() >= 1) |
| 595 | return success(); |
| 596 | WalkResult result = topLevelOp->walk(callback: [](ModuleOp module) { |
| 597 | if (!module.getDltiAttr()) |
| 598 | return WalkResult::advance(); |
| 599 | module.emitOpError(message: "cannot emit builtin dialect version 0 with a 'dlti' " |
| 600 | "property" ); |
| 601 | return WalkResult::interrupt(); |
| 602 | }); |
| 603 | return failure(IsFailure: result.wasInterrupted()); |
| 604 | } |
| 605 | |
| 606 | void writeVersion(DialectBytecodeWriter &writer) const override { |
| 607 | auto configVersion = writer.getDialectVersion(dialectName: getDialect()->getNamespace()); |
| 608 | // Write version set in config. |
| 609 | if (succeeded(Result: configVersion)) { |
| 610 | auto *version = |
| 611 | static_cast<const BuiltinDialectVersion *>(*configVersion); |
| 612 | // Version 0 predates dialect version metadata. Preserve its encoding. |
| 613 | if (version->getVersion() > 0) |
| 614 | writer.writeVarInt(value: static_cast<uint64_t>(version->getVersion())); |
| 615 | return; |
| 616 | } |
| 617 | // Else, write current set version version if not 0. |
| 618 | if (auto version = cast<BuiltinDialect>(Val: getDialect())->getVersion(); |
| 619 | version && version->getVersion() > 0) { |
| 620 | writer.writeVarInt(value: static_cast<uint64_t>(version->getVersion())); |
| 621 | } |
| 622 | } |
| 623 | |
| 624 | std::unique_ptr<DialectVersion> |
| 625 | readVersion(DialectBytecodeReader &reader) const override { |
| 626 | uint64_t version; |
| 627 | if (failed(Result: reader.readVarInt(result&: version))) |
| 628 | return nullptr; |
| 629 | |
| 630 | auto dialectVersion = std::make_unique<BuiltinDialectVersion>(args&: version); |
| 631 | if (BuiltinDialectVersion::getCurrentVersion() < *dialectVersion) { |
| 632 | reader.emitError() |
| 633 | << "reading newer builtin dialect version than supported" ; |
| 634 | return nullptr; |
| 635 | } |
| 636 | |
| 637 | return dialectVersion; |
| 638 | } |
| 639 | }; |
| 640 | } // namespace |
| 641 | |
| 642 | void builtin_dialect_detail::addBytecodeInterface(BuiltinDialect *dialect) { |
| 643 | dialect->addInterfaces<BuiltinDialectBytecodeInterface>(); |
| 644 | } |
| 645 | |