1 //===-- Utility class to test fabs[f|l] -------------------------*- C++ -*-===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 9 #include "utils/FPUtil/TestHelpers.h" 10 #include "utils/MPFRWrapper/MPFRUtils.h" 11 #include "utils/UnitTest/Test.h" 12 13 #include <math.h> 14 15 namespace mpfr = __llvm_libc::testing::mpfr; 16 17 template <typename T> class SqrtTest : public __llvm_libc::testing::Test { 18 19 DECLARE_SPECIAL_CONSTANTS(T) 20 21 static constexpr UIntType HiddenBit = 22 UIntType(1) << __llvm_libc::fputil::MantissaWidth<T>::value; 23 24 public: 25 typedef T (*SqrtFunc)(T); 26 27 void testSpecialNumbers(SqrtFunc func) { 28 ASSERT_FP_EQ(aNaN, func(aNaN)); 29 ASSERT_FP_EQ(inf, func(inf)); 30 ASSERT_FP_EQ(aNaN, func(negInf)); 31 ASSERT_FP_EQ(0.0, func(0.0)); 32 ASSERT_FP_EQ(-0.0, func(-0.0)); 33 ASSERT_FP_EQ(aNaN, func(T(-1.0))); 34 ASSERT_FP_EQ(T(1.0), func(T(1.0))); 35 ASSERT_FP_EQ(T(2.0), func(T(4.0))); 36 ASSERT_FP_EQ(T(3.0), func(T(9.0))); 37 } 38 39 void testDenormalValues(SqrtFunc func) { 40 for (UIntType mant = 1; mant < HiddenBit; mant <<= 1) { 41 FPBits denormal(T(0.0)); 42 denormal.encoding.mantissa = mant; 43 44 ASSERT_MPFR_MATCH(mpfr::Operation::Sqrt, T(denormal), func(T(denormal)), 45 T(0.5)); 46 } 47 48 constexpr UIntType count = 1'000'001; 49 constexpr UIntType step = HiddenBit / count; 50 for (UIntType i = 0, v = 0; i <= count; ++i, v += step) { 51 T x = *reinterpret_cast<T *>(&v); 52 ASSERT_MPFR_MATCH(mpfr::Operation::Sqrt, x, func(x), 0.5); 53 } 54 } 55 56 void testNormalRange(SqrtFunc func) { 57 constexpr UIntType count = 10'000'001; 58 constexpr UIntType step = UIntType(-1) / count; 59 for (UIntType i = 0, v = 0; i <= count; ++i, v += step) { 60 T x = *reinterpret_cast<T *>(&v); 61 if (isnan(x) || (x < 0)) { 62 continue; 63 } 64 ASSERT_MPFR_MATCH(mpfr::Operation::Sqrt, x, func(x), 0.5); 65 } 66 } 67 }; 68 69 #define LIST_SQRT_TESTS(T, func) \ 70 using LlvmLibcSqrtTest = SqrtTest<T>; \ 71 TEST_F(LlvmLibcSqrtTest, SpecialNumbers) { testSpecialNumbers(&func); } \ 72 TEST_F(LlvmLibcSqrtTest, DenormalValues) { testDenormalValues(&func); } \ 73 TEST_F(LlvmLibcSqrtTest, NormalRange) { testNormalRange(&func); } 74