1//===----------------------------------------------------------------------===//
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/// \file
10/// Floating-point integer check functions.
11///
12//===----------------------------------------------------------------------===//
13
14#ifndef LLVM_LIBC_SRC___SUPPORT_FPUTIL_IS_INTEGER_H
15#define LLVM_LIBC_SRC___SUPPORT_FPUTIL_IS_INTEGER_H
16
17#include "src/__support/CPP/bit.h"
18#include "src/__support/FPUtil/FPBits.h"
19#include "src/__support/macros/attributes.h"
20#include "src/__support/macros/config.h"
21
22namespace LIBC_NAMESPACE_DECL {
23namespace fputil {
24
25// These helpers require finite inputs.
26
27// Check if x is an odd integer: its lowest set significand bit must be at the
28// unit position, so x_e + lsb == UNIT_EXPONENT.
29template <typename T> LIBC_INLINE constexpr bool is_odd_integer(T x) {
30 using FPBits = FPBits<T>;
31 using StorageType = typename FPBits::StorageType;
32 FPBits xbits(x);
33 StorageType x_u = xbits.uintval();
34 unsigned x_e = static_cast<unsigned>(xbits.get_biased_exponent());
35 unsigned lsb = static_cast<unsigned>(
36 cpp::countr_zero(static_cast<StorageType>(x_u | FPBits::EXP_MASK)));
37 constexpr unsigned UNIT_EXPONENT =
38 static_cast<unsigned>(FPBits::EXP_BIAS + FPBits::FRACTION_LEN);
39 return x_e + lsb == UNIT_EXPONENT;
40}
41
42// Check if x is an integer: its lowest set significand bit must be at or above
43// the unit position, so x_e + lsb >= UNIT_EXPONENT.
44template <typename T> LIBC_INLINE constexpr bool is_integer(T x) {
45 using FPBits = FPBits<T>;
46 using StorageType = typename FPBits::StorageType;
47 FPBits xbits(x);
48 if (xbits.is_zero())
49 return true;
50 StorageType x_u = xbits.uintval();
51 unsigned x_e = static_cast<unsigned>(xbits.get_biased_exponent());
52 unsigned lsb = static_cast<unsigned>(
53 cpp::countr_zero(static_cast<StorageType>(x_u | FPBits::EXP_MASK)));
54 constexpr unsigned UNIT_EXPONENT =
55 static_cast<unsigned>(FPBits::EXP_BIAS + FPBits::FRACTION_LEN);
56 return x_e + lsb >= UNIT_EXPONENT;
57}
58
59} // namespace fputil
60} // namespace LIBC_NAMESPACE_DECL
61
62#endif // LLVM_LIBC_SRC___SUPPORT_FPUTIL_IS_INTEGER_H
63