1//===-- Exhaustive tests for float -> bfloat16 conversion -----------------===//
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 "exhaustive_test.h"
10#include "src/__support/FPUtil/bfloat16.h"
11#include "utils/MPFRWrapper/MPCommon.h"
12
13using BFloat16 = LIBC_NAMESPACE::fputil::BFloat16;
14namespace mpfr = LIBC_NAMESPACE::testing::mpfr;
15using MPFRNumber = LIBC_NAMESPACE::testing::mpfr::MPFRNumber;
16
17template <typename InType>
18struct Bfloat16ConversionChecker
19 : public virtual LIBC_NAMESPACE::testing::Test {
20 using FloatType = InType;
21 using FPBits = LIBC_NAMESPACE::fputil::FPBits<FloatType>;
22 using StorageType = typename FPBits::StorageType;
23
24 // Check in a range, return the number of failures.
25 // Slightly modified version of UnaryOpChecker.
26 uint64_t check(StorageType start, StorageType stop,
27 mpfr::RoundingMode rounding) {
28 mpfr::ForceRoundingMode r(rounding);
29 if (!r.success)
30 return (stop > start);
31 StorageType bits = start;
32 uint64_t failed = 0;
33 do {
34 FPBits x_bits(bits);
35 FloatType x = x_bits.get_val();
36
37 const BFloat16 libc_bfloat{x};
38 const BFloat16 mpfr_bfloat = MPFRNumber(x).as<BFloat16>();
39
40 const bool correct =
41 LIBC_NAMESPACE::testing::getMatcher<
42 LIBC_NAMESPACE::testing::TestCond::EQ>(mpfr_bfloat)
43 .match(libc_bfloat);
44
45 failed += (!correct);
46 } while (bits++ < stop);
47 return failed;
48 }
49};
50
51template <typename FloatType>
52using LlvmLibcBfloat16ExhaustiveTest =
53 LlvmLibcExhaustiveMathTest<Bfloat16ConversionChecker<FloatType>>;
54using LlvmLibcBfloat16FromFloatTest = LlvmLibcBfloat16ExhaustiveTest<float>;
55
56// Positive Range: [0, Inf];
57constexpr uint32_t POS_START = 0x0000'0000U;
58constexpr uint32_t POS_STOP = 0x7f80'0000U;
59
60// Negative Range: [-Inf, 0];
61constexpr uint32_t NEG_START = 0xb000'0000U;
62constexpr uint32_t NEG_STOP = 0xff80'0000U;
63
64TEST_F(LlvmLibcBfloat16FromFloatTest, PostiveRange) {
65 test_full_range_all_roundings(POS_START, POS_STOP);
66}
67
68TEST_F(LlvmLibcBfloat16FromFloatTest, NegativeRange) {
69 test_full_range_all_roundings(NEG_START, NEG_STOP);
70}
71

source code of libc/test/src/math/exhaustive/bfloat16_test.cpp