1//===-- Conversion between floating-point types -----------------*- 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#ifndef LLVM_LIBC_SRC___SUPPORT_FPUTIL_CAST_H
10#define LLVM_LIBC_SRC___SUPPORT_FPUTIL_CAST_H
11
12#include "FPBits.h"
13#include "dyadic_float.h"
14#include "hdr/fenv_macros.h"
15#include "src/__support/CPP/algorithm.h"
16#include "src/__support/CPP/type_traits.h"
17#include "src/__support/macros/properties/types.h"
18
19namespace LIBC_NAMESPACE_DECL {
20namespace fputil {
21
22// TODO: Add optimization for known good targets with fast
23// float to float16 conversion:
24// https://github.com/llvm/llvm-project/issues/133517
25template <typename OutType, typename InType>
26LIBC_INLINE constexpr cpp::enable_if_t<cpp::is_floating_point_v<OutType> &&
27 cpp::is_floating_point_v<InType>,
28 OutType>
29cast(InType x) {
30 // Casting to the same type is a no-op.
31 if constexpr (cpp::is_same_v<InType, OutType>) {
32 return x;
33 } else {
34 if constexpr (cpp::is_same_v<OutType, bfloat16> ||
35 cpp::is_same_v<InType, bfloat16> ||
36 cpp::is_same_v<OutType, Float128> ||
37 cpp::is_same_v<InType, Float128> ||
38 cpp::is_same_v<OutType, Float80> ||
39 cpp::is_same_v<InType, Float80>
40#if defined(LIBC_TYPES_HAS_FLOAT16) && !defined(__LIBC_USE_FLOAT16_CONVERSION)
41 || cpp::is_same_v<OutType, float16> ||
42 cpp::is_same_v<InType, float16>
43#endif
44 ) {
45 using InFPBits = FPBits<InType>;
46 using InStorageType = typename InFPBits::StorageType;
47 using OutFPBits = FPBits<OutType>;
48 using OutStorageType = typename OutFPBits::StorageType;
49
50 InFPBits x_bits(x);
51
52 if (x_bits.is_nan()) {
53 if (x_bits.is_signaling_nan()) {
54 raise_except_if_required(FE_INVALID);
55 return OutFPBits::quiet_nan().get_val();
56 }
57
58 InStorageType x_mant = x_bits.get_mantissa();
59 if constexpr (InFPBits::FRACTION_LEN > OutFPBits::FRACTION_LEN)
60 x_mant >>= InFPBits::FRACTION_LEN - OutFPBits::FRACTION_LEN;
61 return OutFPBits::quiet_nan(x_bits.sign(),
62 static_cast<OutStorageType>(x_mant))
63 .get_val();
64 }
65
66 if (x_bits.is_inf())
67 return OutFPBits::inf(x_bits.sign()).get_val();
68
69 constexpr size_t MAX_FRACTION_LEN =
70 cpp::max(OutFPBits::FRACTION_LEN, InFPBits::FRACTION_LEN);
71 DyadicFloat<cpp::bit_ceil(value: MAX_FRACTION_LEN)> xd(x);
72 return xd.template as<OutType, /*ShouldSignalExceptions=*/true>();
73 } else {
74 return static_cast<OutType>(x);
75 }
76 }
77}
78
79} // namespace fputil
80} // namespace LIBC_NAMESPACE_DECL
81
82#endif // LLVM_LIBC_SRC___SUPPORT_FPUTIL_CAST_H
83