10b57cec5SDimitry Andric//===-- lib/fixdfsi.c - Double-precision -> integer conversion ----*- C -*-===// 20b57cec5SDimitry Andric// 30b57cec5SDimitry Andric// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 40b57cec5SDimitry Andric// See https://llvm.org/LICENSE.txt for license information. 50b57cec5SDimitry Andric// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 60b57cec5SDimitry Andric// 70b57cec5SDimitry Andric//===----------------------------------------------------------------------===// 80b57cec5SDimitry Andric// 90b57cec5SDimitry Andric// This file implements float to integer conversion for the 100b57cec5SDimitry Andric// compiler-rt library. 110b57cec5SDimitry Andric// 120b57cec5SDimitry Andric//===----------------------------------------------------------------------===// 130b57cec5SDimitry Andric 140b57cec5SDimitry Andric#include "fp_lib.h" 150b57cec5SDimitry Andric 160b57cec5SDimitry Andricstatic __inline fixint_t __fixint(fp_t a) { 170b57cec5SDimitry Andric const fixint_t fixint_max = (fixint_t)((~(fixuint_t)0) / 2); 180b57cec5SDimitry Andric const fixint_t fixint_min = -fixint_max - 1; 190b57cec5SDimitry Andric // Break a into sign, exponent, significand parts. 200b57cec5SDimitry Andric const rep_t aRep = toRep(a); 210b57cec5SDimitry Andric const rep_t aAbs = aRep & absMask; 220b57cec5SDimitry Andric const fixint_t sign = aRep & signBit ? -1 : 1; 230b57cec5SDimitry Andric const int exponent = (aAbs >> significandBits) - exponentBias; 240b57cec5SDimitry Andric const rep_t significand = (aAbs & significandMask) | implicitBit; 250b57cec5SDimitry Andric 260b57cec5SDimitry Andric // If exponent is negative, the result is zero. 270b57cec5SDimitry Andric if (exponent < 0) 280b57cec5SDimitry Andric return 0; 290b57cec5SDimitry Andric 300b57cec5SDimitry Andric // If the value is too large for the integer type, saturate. 310b57cec5SDimitry Andric if ((unsigned)exponent >= sizeof(fixint_t) * CHAR_BIT) 320b57cec5SDimitry Andric return sign == 1 ? fixint_max : fixint_min; 330b57cec5SDimitry Andric 340b57cec5SDimitry Andric // If 0 <= exponent < significandBits, right shift to get the result. 350b57cec5SDimitry Andric // Otherwise, shift left. 360b57cec5SDimitry Andric if (exponent < significandBits) 37*0fca6ea1SDimitry Andric return (fixint_t)(sign * (significand >> (significandBits - exponent))); 380b57cec5SDimitry Andric else 39*0fca6ea1SDimitry Andric return (fixint_t)(sign * ((fixuint_t)significand << (exponent - significandBits))); 400b57cec5SDimitry Andric} 41