kit

kit
git clone https://git.ryansepassi.com/git/kit.git
Log | Files | Refs | README

fp_fixuint_impl.inc (1876B)


      1 //===-- lib/fixdfsi.c - Double-precision -> integer conversion ----*- 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 // This file implements float to unsigned integer conversion for the
     10 // compiler-rt library.
     11 //
     12 //===----------------------------------------------------------------------===//
     13 
     14 #include "fp_lib.h"
     15 
     16 #ifndef FP_FIX_SUFFIX
     17 #error "fp_fixuint_impl.inc: FP_FIX_SUFFIX must be defined before #include"
     18 #endif
     19 
     20 #ifndef FP_FIX_IMPL_PASTE_
     21 #define FP_FIX_IMPL_PASTE_(a, b) a##_##b
     22 #define FP_FIX_IMPL_PASTE(a, b)  FP_FIX_IMPL_PASTE_(a, b)
     23 #endif
     24 
     25 #ifdef __fixuint
     26 #undef __fixuint
     27 #endif
     28 #define __fixuint FP_FIX_IMPL_PASTE(__fixuint, FP_FIX_SUFFIX)
     29 
     30 static inline fixuint_t __fixuint(fp_t a) {
     31   // Break a into sign, exponent, significand parts.
     32   const rep_t aRep = toRep(a);
     33   const rep_t aAbs = aRep & absMask;
     34   const int sign = aRep & signBit ? -1 : 1;
     35   const int exponent = (aAbs >> significandBits) - exponentBias;
     36   const rep_t significand = (aAbs & significandMask) | implicitBit;
     37 
     38   // If either the value or the exponent is negative, the result is zero.
     39   if (sign == -1 || exponent < 0)
     40     return 0;
     41 
     42   // If the value is too large for the integer type, saturate.
     43   if ((unsigned)exponent >= sizeof(fixuint_t) * CHAR_BIT)
     44     return ~(fixuint_t)0;
     45 
     46   // If 0 <= exponent < significandBits, right shift to get the result.
     47   // Otherwise, shift left.
     48   if (exponent < significandBits)
     49     return significand >> (significandBits - exponent);
     50   else
     51     return (fixuint_t)significand << (exponent - significandBits);
     52 }
     53 
     54 // FP_FIX_SUFFIX, fixuint_t intentionally left defined; see fp_fixint_impl.inc.