1287516Sdim//===-- lib/fixdfsi.c - Double-precision -> integer conversion ----*- C -*-===//
2287516Sdim//
3287516Sdim//                     The LLVM Compiler Infrastructure
4287516Sdim//
5287516Sdim// This file is dual licensed under the MIT and the University of Illinois Open
6287516Sdim// Source Licenses. See LICENSE.TXT for details.
7287516Sdim//
8287516Sdim//===----------------------------------------------------------------------===//
9287516Sdim//
10287516Sdim// This file implements float to integer conversion for the
11287516Sdim// compiler-rt library.
12287516Sdim//
13287516Sdim//===----------------------------------------------------------------------===//
14287516Sdim
15287516Sdim#include "fp_lib.h"
16287516Sdim
17296417Sdimstatic __inline fixint_t __fixint(fp_t a) {
18287516Sdim    const fixint_t fixint_max = (fixint_t)((~(fixuint_t)0) / 2);
19287516Sdim    const fixint_t fixint_min = -fixint_max - 1;
20287516Sdim    // Break a into sign, exponent, significand
21287516Sdim    const rep_t aRep = toRep(a);
22287516Sdim    const rep_t aAbs = aRep & absMask;
23287516Sdim    const fixint_t sign = aRep & signBit ? -1 : 1;
24287516Sdim    const int exponent = (aAbs >> significandBits) - exponentBias;
25287516Sdim    const rep_t significand = (aAbs & significandMask) | implicitBit;
26287516Sdim
27287516Sdim    // If exponent is negative, the result is zero.
28287516Sdim    if (exponent < 0)
29287516Sdim        return 0;
30287516Sdim
31287516Sdim    // If the value is too large for the integer type, saturate.
32287516Sdim    if ((unsigned)exponent >= sizeof(fixint_t) * CHAR_BIT)
33287516Sdim        return sign == 1 ? fixint_max : fixint_min;
34287516Sdim
35287516Sdim    // If 0 <= exponent < significandBits, right shift to get the result.
36287516Sdim    // Otherwise, shift left.
37287516Sdim    if (exponent < significandBits)
38287516Sdim        return sign * (significand >> (significandBits - exponent));
39287516Sdim    else
40287516Sdim        return sign * ((fixint_t)significand << (exponent - significandBits));
41287516Sdim}
42