Skip to content
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

Don't crash when constant folding an integer division by zero #105

Merged
merged 1 commit into from
Jun 17, 2024
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
11 changes: 10 additions & 1 deletion src/Dialect/ONNX/Transforms/ConstProp.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -203,7 +203,16 @@ struct ElementWiseBinaryOpImpl<ONNXMulOp, T, EnableNotBool<T>> {

template <typename T>
struct ElementWiseBinaryOpImpl<ONNXDivOp, T, EnableNotBool<T>> {
static T eval(T lhs, T rhs) { return lhs / rhs; }
static T eval(T lhs, T rhs) {
if constexpr (std::is_integral_v<T>) {
if (rhs == 0) {
// Undefined behavior. We can return any value.
// Performing the divison would crash.
return lhs;
}
}
return lhs / rhs;
}
};

template <typename T>
Expand Down
12 changes: 12 additions & 0 deletions test/mlir/onnx/onnx_constprop.mlir
Original file line number Diff line number Diff line change
Expand Up @@ -379,6 +379,18 @@ func.func @test_div_ones(%arg0 : tensor<1x2xui8>) -> tensor<1x2xui8> {
// CHECK: onnx.Return %arg0 : tensor<1x2xui8>
}

// -----

// CHECK-LABEL: test_div_by_zero()
func.func @test_div_by_zero() -> tensor<2xui32> {
%0 = onnx.Constant dense<[2, 4]> : tensor<2xui32>
%1 = onnx.Constant dense<[0]> : tensor<1xui32>
%2 = "onnx.Div"(%0, %1) : (tensor<2xui32>, tensor<1xui32>) -> tensor<2xui32>
"onnx.Return"(%2) : (tensor<2xui32>) -> ()
// The behavior is undefined, so the value don't matter. Just don't crash.
// CHECK-NOT: {{.*}} = "onnx.Div"{{.*}}
}

//===----------------------------------------------------------------------===//
/// Equal test

Expand Down
Loading