[MLIR] Guard optional operand resolution in generated op parsers (#180796)

Skip resolveOperands for optional operands when they are absent to
avoid out-of-bounds access on the empty types vector.
This commit is contained in:
Henrich Lauko 2026-02-11 08:25:03 +01:00 committed by GitHub
parent 128437fb6a
commit 6c51938067
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
3 changed files with 23 additions and 0 deletions

View File

@ -667,6 +667,17 @@ def FormatTypesMatchContextOp : TEST_Op<"format_types_match_context", [
let assemblyFormat = "attr-dict $value `:` type($value)";
}
def FormatTypesMatchOptionalOp : TEST_Op<"format_types_match_optional", [
OptionalTypesMatchWith<"optional type matches result",
"result", "optional", "$_self">
]> {
let arguments = (ins Optional<AnyType>:$optional);
let results = (outs Optional<AnyType>:$result);
let assemblyFormat = [{
(`(` $optional^ `:` type($result) `)`)? attr-dict
}];
}
//===----------------------------------------------------------------------===//
// InferTypeOpInterface type inference in assembly format
//===----------------------------------------------------------------------===//

View File

@ -488,6 +488,12 @@ test.format_infer_variadic_type_from_non_variadic %i64, %i64 : i64
// CHECK: test.format_types_match_context %[[I64]] : i64
%ignored_res6 = test.format_types_match_context %i64 : i64
// CHECK: test.format_types_match_optional(%[[I64]] : i64)
%ignored_res7 = test.format_types_match_optional(%i64 : i64)
// CHECK: test.format_types_match_optional
test.format_types_match_optional
//===----------------------------------------------------------------------===//
// InferTypeOpInterface type inference
//===----------------------------------------------------------------------===//

View File

@ -1848,6 +1848,10 @@ void OperationFormat::genParserOperandTypeResolution(
// separately.
for (unsigned i = 0, e = op.getNumOperands(); i != e; ++i) {
NamedTypeConstraint &operand = op.getOperand(i);
// Optional operands may not be present; guard resolution to avoid
// out-of-bounds access on the (potentially empty) types vector.
if (operand.isOptional())
body << " if (!" << operand.name << "Operands.empty()) {\n";
body << " if (parser.resolveOperands(" << operand.name << "Operands, ";
// Resolve the type of this operand.
@ -1856,6 +1860,8 @@ void OperationFormat::genParserOperandTypeResolution(
body << ", " << operand.name
<< "OperandsLoc, result.operands))\n return ::mlir::failure();\n";
if (operand.isOptional())
body << " }\n";
}
}