1131676Sdas/*- 2131676Sdas * Copyright (c) 2004 David Schultz <das@FreeBSD.ORG> 3131676Sdas * All rights reserved. 4131676Sdas * 5131676Sdas * Redistribution and use in source and binary forms, with or without 6131676Sdas * modification, are permitted provided that the following conditions 7131676Sdas * are met: 8131676Sdas * 1. Redistributions of source code must retain the above copyright 9131676Sdas * notice, this list of conditions and the following disclaimer. 10131676Sdas * 2. Redistributions in binary form must reproduce the above copyright 11131676Sdas * notice, this list of conditions and the following disclaimer in the 12131676Sdas * documentation and/or other materials provided with the distribution. 13131676Sdas * 14131676Sdas * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND 15131676Sdas * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 16131676Sdas * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 17131676Sdas * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE 18131676Sdas * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 19131676Sdas * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS 20131676Sdas * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 21131676Sdas * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT 22131676Sdas * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY 23131676Sdas * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF 24131676Sdas * SUCH DAMAGE. 25131676Sdas */ 26131676Sdas 27131676Sdas#include <sys/cdefs.h> 28131676Sdas__FBSDID("$FreeBSD$"); 29131676Sdas 30131676Sdas#include <fenv.h> 31131676Sdas#include <math.h> 32131676Sdas 33131676Sdas/* 34131676Sdas * We save and restore the floating-point environment to avoid raising 35131676Sdas * an inexact exception. We can get away with using fesetenv() 36131676Sdas * instead of feclearexcept()/feupdateenv() to restore the environment 37131676Sdas * because the only exception defined for rint() is overflow, and 38131676Sdas * rounding can't overflow as long as emax >= p. 39251024Sdas * 40251024Sdas * The volatile keyword is needed below because clang incorrectly assumes 41251024Sdas * that rint won't raise any floating-point exceptions. Declaring ret volatile 42251024Sdas * is sufficient to trick the compiler into doing the right thing. 43131676Sdas */ 44131676Sdas#define DECL(type, fn, rint) \ 45131676Sdastype \ 46131676Sdasfn(type x) \ 47131676Sdas{ \ 48251024Sdas volatile type ret; \ 49131676Sdas fenv_t env; \ 50131676Sdas \ 51131676Sdas fegetenv(&env); \ 52131676Sdas ret = rint(x); \ 53131676Sdas fesetenv(&env); \ 54131676Sdas return (ret); \ 55131676Sdas} 56131676Sdas 57131676SdasDECL(double, nearbyint, rint) 58131676SdasDECL(float, nearbyintf, rintf) 59175309SdasDECL(long double, nearbyintl, rintl) 60