From 95af688ee3ff163a421e4d01920baf4e67d9a98c Mon Sep 17 00:00:00 2001 From: lorenzo chelini Date: Mon, 24 Feb 2025 16:19:37 +0100 Subject: [PATCH] [MLIR] Improve error handling when parsing dense attributes Avoid triggering assertions when we expect to parse a string but encounter a different type. Instead, handle the mismatch gracefully by emitting a parser error. --- mlir/lib/AsmParser/AttributeParser.cpp | 5 +++++ mlir/test/IR/invalid-builtin-attributes.mlir | 10 ++++++++++ 2 files changed, 15 insertions(+) diff --git a/mlir/lib/AsmParser/AttributeParser.cpp b/mlir/lib/AsmParser/AttributeParser.cpp index 32c68e093a0b0..2013d3623711b 100644 --- a/mlir/lib/AsmParser/AttributeParser.cpp +++ b/mlir/lib/AsmParser/AttributeParser.cpp @@ -680,6 +680,11 @@ DenseElementsAttr TensorLiteralParser::getStringAttr(SMLoc loc, ShapedType type, stringRefValues.reserve(storage.size()); for (auto val : storage) { + if (!val.second.is(Token::string)) { + p.emitError(loc) << "expected string token, got " + << val.second.getSpelling(); + return nullptr; + } stringValues.push_back(val.second.getStringValue()); stringRefValues.emplace_back(stringValues.back()); } diff --git a/mlir/test/IR/invalid-builtin-attributes.mlir b/mlir/test/IR/invalid-builtin-attributes.mlir index 64201950b2306..10988be91d84a 100644 --- a/mlir/test/IR/invalid-builtin-attributes.mlir +++ b/mlir/test/IR/invalid-builtin-attributes.mlir @@ -626,3 +626,13 @@ func.func @print_error_on_correct_line() { sparse <> : i32 return } + +// ----- + +// Prevent assertions when parsing a dense attribute expected to be a string +// but encountering a different type. +func.func @expect_to_parse_literal() { + // expected-error@below {{expected string token, got 23}} + %0 = arith.constant dense<[23]> : tensor<1x!unknown<>> + return +}