Skip to content

Commit 076b46c

Browse files
author
Congcong Cai
authored
Literal: Standardize NaNs in sqrt (#8404)
std::sqrt of a negative number can result a nan. It is different in amd64 (-nan) and aarch64 (+nan), so we must standardize.
1 parent f77f1f1 commit 076b46c

2 files changed

Lines changed: 34 additions & 2 deletions

File tree

src/wasm/literal.cpp

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1148,9 +1148,9 @@ Literal Literal::nearbyint() const {
11481148
Literal Literal::sqrt() const {
11491149
switch (type.getBasic()) {
11501150
case Type::f32:
1151-
return Literal(std::sqrt(getf32()));
1151+
return standardizeNaN(Literal(std::sqrt(getf32())));
11521152
case Type::f64:
1153-
return Literal(std::sqrt(getf64()));
1153+
return standardizeNaN(Literal(std::sqrt(getf64())));
11541154
default:
11551155
WASM_UNREACHABLE("unexpected type");
11561156
}

test/gtest/interpreter.cpp

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -685,6 +685,22 @@ TEST(InterpreterTest, SqrtF32) {
685685
EXPECT_EQ(results, expected);
686686
}
687687

688+
TEST(InterpreterTest, SqrtF32Neg) {
689+
Module wasm;
690+
IRBuilder builder(wasm);
691+
692+
ASSERT_FALSE(builder.makeConst(Literal(float(-5.0))).getErr());
693+
ASSERT_FALSE(builder.makeUnary(SqrtFloat32).getErr());
694+
695+
auto expr = builder.build();
696+
ASSERT_FALSE(expr.getErr());
697+
698+
auto results = Interpreter{}.runTest(*expr);
699+
std::vector<Literal> expected{Literal(std::nanf("0x400000"))};
700+
701+
EXPECT_EQ(results, expected);
702+
}
703+
688704
TEST(InterpreterTest, CeilF32) {
689705
Module wasm;
690706
IRBuilder builder(wasm);
@@ -852,6 +868,22 @@ TEST(InterpreterTest, SqrtF64) {
852868
EXPECT_EQ(results, expected);
853869
}
854870

871+
TEST(InterpreterTest, SqrtF64Neg) {
872+
Module wasm;
873+
IRBuilder builder(wasm);
874+
875+
ASSERT_FALSE(builder.makeConst(Literal(double(-5.0))).getErr());
876+
ASSERT_FALSE(builder.makeUnary(SqrtFloat64).getErr());
877+
878+
auto expr = builder.build();
879+
ASSERT_FALSE(expr.getErr());
880+
881+
auto results = Interpreter{}.runTest(*expr);
882+
std::vector<Literal> expected{Literal(std::nan("0x8000000000000"))};
883+
884+
EXPECT_EQ(results, expected);
885+
}
886+
855887
TEST(InterpreterTest, CeilF64) {
856888
Module wasm;
857889
IRBuilder builder(wasm);

0 commit comments

Comments
 (0)