xref: /aosp_15_r20/external/llvm-libc/src/__support/FPUtil/x86_64/NextUpDownLongDouble.h (revision 71db0c75aadcf003ffe3238005f61d7618a3fead)
1 //===-- nextupdown implementation for x86 long double numbers ---*- 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_X86_64_NEXTUPDOWNLONGDOUBLE_H
10 #define LLVM_LIBC_SRC___SUPPORT_FPUTIL_X86_64_NEXTUPDOWNLONGDOUBLE_H
11 
12 #include "src/__support/FPUtil/FPBits.h"
13 #include "src/__support/macros/attributes.h"
14 #include "src/__support/macros/config.h"
15 #include "src/__support/macros/properties/architectures.h"
16 
17 #if !defined(LIBC_TARGET_ARCH_IS_X86)
18 #error "Invalid include"
19 #endif
20 
21 namespace LIBC_NAMESPACE_DECL {
22 namespace fputil {
23 
24 template <bool IsDown>
nextupdown(long double x)25 LIBC_INLINE constexpr long double nextupdown(long double x) {
26   constexpr Sign sign = IsDown ? Sign::NEG : Sign::POS;
27 
28   using FPBits_t = FPBits<long double>;
29   FPBits_t xbits(x);
30   if (xbits.is_nan() || xbits == FPBits_t::max_normal(sign) ||
31       xbits == FPBits_t::inf(sign))
32     return x;
33 
34   if (x == 0.0l)
35     return FPBits_t::min_subnormal(sign).get_val();
36 
37   using StorageType = typename FPBits_t::StorageType;
38 
39   if (xbits.sign() == sign) {
40     if (xbits.get_mantissa() == FPBits_t::FRACTION_MASK) {
41       xbits.set_mantissa(0);
42       xbits.set_biased_exponent(xbits.get_biased_exponent() + 1);
43     } else {
44       xbits = FPBits_t(StorageType(xbits.uintval() + 1));
45     }
46 
47     return xbits.get_val();
48   }
49 
50   if (xbits.get_mantissa() == 0) {
51     xbits.set_mantissa(FPBits_t::FRACTION_MASK);
52     xbits.set_biased_exponent(xbits.get_biased_exponent() - 1);
53   } else {
54     xbits = FPBits_t(StorageType(xbits.uintval() - 1));
55   }
56 
57   return xbits.get_val();
58 }
59 
60 } // namespace fputil
61 } // namespace LIBC_NAMESPACE_DECL
62 
63 #endif // LLVM_LIBC_SRC___SUPPORT_FPUTIL_X86_64_NEXTUPDOWNLONGDOUBLE_H
64