Skip to content

Commit f35ac8a

Browse files
committed
Fix SimplifyAllocConst pattern when we have alloc of negative sizes
This is UB, but we shouldn't crash the compiler either. Fixes llvm#61056 Reviewed By: jpienaar Differential Revision: https://reviews.llvm.org/D144978
1 parent 9a9fce1 commit f35ac8a

File tree

2 files changed

+20
-5
lines changed

2 files changed

+20
-5
lines changed

mlir/lib/Dialect/MemRef/IR/MemRefOps.cpp

Lines changed: 8 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -284,7 +284,10 @@ struct SimplifyAllocConst : public OpRewritePattern<AllocLikeOp> {
284284
// Check to see if any dimensions operands are constants. If so, we can
285285
// substitute and drop them.
286286
if (llvm::none_of(alloc.getDynamicSizes(), [](Value operand) {
287-
return matchPattern(operand, matchConstantIndex());
287+
APInt constSizeArg;
288+
if (!matchPattern(operand, m_ConstantInt(&constSizeArg)))
289+
return false;
290+
return constSizeArg.isNonNegative();
288291
}))
289292
return failure();
290293

@@ -305,11 +308,11 @@ struct SimplifyAllocConst : public OpRewritePattern<AllocLikeOp> {
305308
continue;
306309
}
307310
auto dynamicSize = alloc.getDynamicSizes()[dynamicDimPos];
308-
auto *defOp = dynamicSize.getDefiningOp();
309-
if (auto constantIndexOp =
310-
dyn_cast_or_null<arith::ConstantIndexOp>(defOp)) {
311+
APInt constSizeArg;
312+
if (matchPattern(dynamicSize, m_ConstantInt(&constSizeArg)) &&
313+
constSizeArg.isNonNegative()) {
311314
// Dynamic shape dimension will be folded.
312-
newShapeConstants.push_back(constantIndexOp.value());
315+
newShapeConstants.push_back(constSizeArg.getZExtValue());
313316
} else {
314317
// Dynamic shape dimension not folded; copy dynamicSize from old memref.
315318
newShapeConstants.push_back(ShapedType::kDynamic);

mlir/test/Dialect/MemRef/canonicalize.mlir

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -928,3 +928,15 @@ func.func @fold_multiple_memory_space_cast(%arg : memref<?xf32>) -> memref<?xf32
928928
%1 = memref.memory_space_cast %0 : memref<?xf32, 1> to memref<?xf32, 2>
929929
return %1 : memref<?xf32, 2>
930930
}
931+
932+
// -----
933+
934+
// CHECK-lABEL: func @ub_negative_alloc_size
935+
func.func private @ub_negative_alloc_size() -> memref<?x?x?xi1> {
936+
%idx1 = index.constant 1
937+
%c-2 = arith.constant -2 : index
938+
%c15 = arith.constant 15 : index
939+
// CHECK: %[[ALLOC:.*]] = memref.alloc(%c-2) : memref<15x?x1xi1>
940+
%alloc = memref.alloc(%c15, %c-2, %idx1) : memref<?x?x?xi1>
941+
return %alloc : memref<?x?x?xi1>
942+
}

0 commit comments

Comments
 (0)