Skip to content

[mlir][memref] Fix out-of-bounds crash when reifying result dims #70774

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,9 @@ struct DimOfReifyRankedShapedTypeOpInterface : public OpRewritePattern<OpTy> {
reifiedResultShapes)))
return failure();
unsigned resultNumber = dimValue.getResultNumber();
// Do not apply pattern if the IR is invalid (dim out of bounds).
if (*dimIndex >= reifiedResultShapes[resultNumber].size())
return rewriter.notifyMatchFailure(dimOp, "dimension is out of bounds");
Value replacement = getValueOrCreateConstantIndexOp(
rewriter, dimOp.getLoc(), reifiedResultShapes[resultNumber][*dimIndex]);
rewriter.replaceOp(dimOp, replacement);
Expand Down
27 changes: 27 additions & 0 deletions mlir/test/Dialect/MemRef/resolve-dim-ops.mlir
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
// RUN: mlir-opt --resolve-ranked-shaped-type-result-dims --split-input-file %s | FileCheck %s

// CHECK-LABEL: func @dim_out_of_bounds(
// CHECK-NEXT: arith.constant
// CHECK-NEXT: memref.dim
// CHECK-NEXT: return
func.func @dim_out_of_bounds(%m : memref<7x8xf32>) -> index {
%idx = arith.constant 7 : index
%0 = memref.dim %m, %idx : memref<7x8xf32>
return %0 : index
}

// -----

// CHECK-LABEL: func @dim_out_of_bounds_2(
// CHECK-NEXT: arith.constant
// CHECK-NEXT: arith.constant
// CHECK-NEXT: bufferization.alloc_tensor
// CHECK-NEXT: tensor.dim
// CHECK-NEXT: return
func.func @dim_out_of_bounds_2(%idx1 : index, %idx2 : index) -> index {
%idx = arith.constant 7 : index
%sz = arith.constant 5 : index
%alloc = bufferization.alloc_tensor(%sz, %sz) : tensor<?x?xf32>
%0 = tensor.dim %alloc, %idx : tensor<?x?xf32>
return %0 : index
}