blob: b79baf1834a78aba698d2fb5dfe8a0ff502f2b7a [file] [log] [blame]
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001//===-- APFloat.cpp - Implement APFloat class -----------------------------===//
2//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// 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
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00006//
7//===----------------------------------------------------------------------===//
8//
9// This file implements a class to represent arbitrary precision floating
10// point values and provide a variety of arithmetic operations on them.
11//
12//===----------------------------------------------------------------------===//
13
Chris Lattnere5256752007-12-08 19:00:03 +000014#include "llvm/ADT/APFloat.h"
Jeffrey Yasskin03b81a22011-07-15 07:04:56 +000015#include "llvm/ADT/APSInt.h"
Mehdi Amini47b292d2016-04-16 07:51:28 +000016#include "llvm/ADT/ArrayRef.h"
Ted Kremenek6f30a072008-02-11 17:24:50 +000017#include "llvm/ADT/FoldingSet.h"
Chandler Carruth71bd7d12012-03-04 12:02:57 +000018#include "llvm/ADT/Hashing.h"
Jordan Rosee1f76582013-01-18 21:45:30 +000019#include "llvm/ADT/StringExtras.h"
Chandler Carruth71bd7d12012-03-04 12:02:57 +000020#include "llvm/ADT/StringRef.h"
Nico Weber432a3882018-04-30 14:59:11 +000021#include "llvm/Config/llvm-config.h"
Tim Shen44bde892016-12-12 21:59:30 +000022#include "llvm/Support/Debug.h"
Torok Edwin56d06592009-07-11 20:10:48 +000023#include "llvm/Support/ErrorHandling.h"
Dale Johannesen918c33c2007-08-24 05:08:11 +000024#include "llvm/Support/MathExtras.h"
Tim Shen44bde892016-12-12 21:59:30 +000025#include "llvm/Support/raw_ostream.h"
Chris Lattner17f71652008-08-17 07:19:36 +000026#include <cstring>
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +000027#include <limits.h>
Chris Lattnerfe02c1f2007-08-20 22:49:32 +000028
Tim Shen601ba8c2017-01-27 02:11:07 +000029#define APFLOAT_DISPATCH_ON_SEMANTICS(METHOD_CALL) \
30 do { \
31 if (usesLayout<IEEEFloat>(getSemantics())) \
32 return U.IEEE.METHOD_CALL; \
33 if (usesLayout<DoubleAPFloat>(getSemantics())) \
34 return U.Double.METHOD_CALL; \
35 llvm_unreachable("Unexpected semantics"); \
36 } while (false)
37
Chris Lattnerfe02c1f2007-08-20 22:49:32 +000038using namespace llvm;
39
Michael Gottesman9b877e12013-06-24 09:57:57 +000040/// A macro used to combine two fcCategory enums into one key which can be used
41/// in a switch statement to classify how the interaction of two APFloat's
42/// categories affects an operation.
43///
44/// TODO: If clang source code is ever allowed to use constexpr in its own
45/// codebase, change this into a static inline function.
46#define PackCategoriesIntoKey(_lhs, _rhs) ((_lhs) * 4 + (_rhs))
Chris Lattnerfe02c1f2007-08-20 22:49:32 +000047
Neil Booth8f1946f2007-10-03 22:26:02 +000048/* Assumed in hexadecimal significand parsing, and conversion to
49 hexadecimal strings. */
Craig Topperc85be522017-06-18 18:15:41 +000050static_assert(APFloatBase::integerPartWidth % 4 == 0, "Part width must be divisible by 4!");
Chris Lattnerfe02c1f2007-08-20 22:49:32 +000051
52namespace llvm {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +000053 /* Represents floating point arithmetic semantics. */
54 struct fltSemantics {
55 /* The largest E such that 2^E is representable; this matches the
56 definition of IEEE 754. */
Tim Shen85de51d2016-10-25 19:55:59 +000057 APFloatBase::ExponentType maxExponent;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +000058
59 /* The smallest E such that 2^E is a normalized number; this
60 matches the definition of IEEE 754. */
Tim Shen85de51d2016-10-25 19:55:59 +000061 APFloatBase::ExponentType minExponent;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +000062
63 /* Number of bits in the significand. This includes the integer
64 bit. */
Neil Booth146fdb32007-10-12 15:33:27 +000065 unsigned int precision;
Tamas Berghammerb6b0ddf2015-07-09 10:13:39 +000066
67 /* Number of bits actually used in the semantics. */
68 unsigned int sizeInBits;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +000069 };
70
Stephan Bergmann17c7f702016-12-14 11:57:17 +000071 static const fltSemantics semIEEEhalf = {15, -14, 11, 16};
72 static const fltSemantics semIEEEsingle = {127, -126, 24, 32};
73 static const fltSemantics semIEEEdouble = {1023, -1022, 53, 64};
74 static const fltSemantics semIEEEquad = {16383, -16382, 113, 128};
75 static const fltSemantics semX87DoubleExtended = {16383, -16382, 64, 80};
76 static const fltSemantics semBogus = {0, 0, 0, 0};
Dale Johannesen007aa372007-10-11 18:07:22 +000077
Tim Shen7117e692017-01-26 00:11:07 +000078 /* The IBM double-double semantics. Such a number consists of a pair of IEEE
79 64-bit doubles (Hi, Lo), where |Hi| > |Lo|, and if normal,
80 (double)(Hi + Lo) == Hi. The numeric value it's modeling is Hi + Lo.
81 Therefore it has two 53-bit mantissa parts that aren't necessarily adjacent
82 to each other, and two 11-bit exponents.
Michal Gorny21c12042017-01-03 16:33:50 +000083
84 Note: we need to make the value different from semBogus as otherwise
85 an unsafe optimization may collapse both values to a single address,
86 and we heavily rely on them having distinct addresses. */
87 static const fltSemantics semPPCDoubleDouble = {-1, 0, 0, 0};
Tim Shen139a58f2016-10-27 22:52:40 +000088
Tim Shenfd1e5aa2017-01-23 22:39:35 +000089 /* These are legacy semantics for the fallback, inaccrurate implementation of
90 IBM double-double, if the accurate semPPCDoubleDouble doesn't handle the
Tim Shen7117e692017-01-26 00:11:07 +000091 operation. It's equivalent to having an IEEE number with consecutive 106
92 bits of mantissa and 11 bits of exponent.
93
94 It's not equivalent to IBM double-double. For example, a legit IBM
95 double-double, 1 + epsilon:
96
97 1 + epsilon = 1 + (1 >> 1076)
98
99 is not representable by a consecutive 106 bits of mantissa.
Tim Shen139a58f2016-10-27 22:52:40 +0000100
Tim Shenfd1e5aa2017-01-23 22:39:35 +0000101 Currently, these semantics are used in the following way:
102
Tim Shen7117e692017-01-26 00:11:07 +0000103 semPPCDoubleDouble -> (IEEEdouble, IEEEdouble) ->
104 (64-bit APInt, 64-bit APInt) -> (128-bit APInt) ->
105 semPPCDoubleDoubleLegacy -> IEEE operations
Tim Shenfd1e5aa2017-01-23 22:39:35 +0000106
107 We use bitcastToAPInt() to get the bit representation (in APInt) of the
108 underlying IEEEdouble, then use the APInt constructor to construct the
109 legacy IEEE float.
110
111 TODO: Implement all operations in semPPCDoubleDouble, and delete these
112 semantics. */
113 static const fltSemantics semPPCDoubleDoubleLegacy = {1023, -1022 + 53,
114 53 + 53, 128};
Stephan Bergmann17c7f702016-12-14 11:57:17 +0000115
Gauthier Harnisch83c7b612019-06-15 10:24:47 +0000116 const llvm::fltSemantics &APFloatBase::EnumToSemantics(Semantics S) {
117 switch (S) {
118 case S_IEEEhalf:
119 return IEEEhalf();
120 case S_IEEEsingle:
121 return IEEEsingle();
122 case S_IEEEdouble:
123 return IEEEdouble();
124 case S_x87DoubleExtended:
125 return x87DoubleExtended();
126 case S_IEEEquad:
127 return IEEEquad();
128 case S_PPCDoubleDouble:
129 return PPCDoubleDouble();
130 }
131 llvm_unreachable("Unrecognised floating semantics");
132 }
133
134 APFloatBase::Semantics
135 APFloatBase::SemanticsToEnum(const llvm::fltSemantics &Sem) {
136 if (&Sem == &llvm::APFloat::IEEEhalf())
137 return S_IEEEhalf;
138 else if (&Sem == &llvm::APFloat::IEEEsingle())
139 return S_IEEEsingle;
140 else if (&Sem == &llvm::APFloat::IEEEdouble())
141 return S_IEEEdouble;
142 else if (&Sem == &llvm::APFloat::x87DoubleExtended())
143 return S_x87DoubleExtended;
144 else if (&Sem == &llvm::APFloat::IEEEquad())
145 return S_IEEEquad;
146 else if (&Sem == &llvm::APFloat::PPCDoubleDouble())
147 return S_PPCDoubleDouble;
148 else
149 llvm_unreachable("Unknown floating semantics");
150 }
151
Stephan Bergmann17c7f702016-12-14 11:57:17 +0000152 const fltSemantics &APFloatBase::IEEEhalf() {
153 return semIEEEhalf;
154 }
155 const fltSemantics &APFloatBase::IEEEsingle() {
156 return semIEEEsingle;
157 }
158 const fltSemantics &APFloatBase::IEEEdouble() {
159 return semIEEEdouble;
160 }
161 const fltSemantics &APFloatBase::IEEEquad() {
162 return semIEEEquad;
163 }
164 const fltSemantics &APFloatBase::x87DoubleExtended() {
165 return semX87DoubleExtended;
166 }
167 const fltSemantics &APFloatBase::Bogus() {
168 return semBogus;
169 }
170 const fltSemantics &APFloatBase::PPCDoubleDouble() {
171 return semPPCDoubleDouble;
172 }
Neil Boothb93d90e2007-10-12 16:02:31 +0000173
174 /* A tight upper bound on number of parts required to hold the value
175 pow(5, power) is
176
Neil Booth91305512007-10-15 15:00:55 +0000177 power * 815 / (351 * integerPartWidth) + 1
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000178
Neil Boothb93d90e2007-10-12 16:02:31 +0000179 However, whilst the result may require only this many parts,
180 because we are multiplying two values to get it, the
181 multiplication may require an extra part with the excess part
182 being zero (consider the trivial case of 1 * 1, tcFullMultiply
183 requires two parts to hold the single-part result). So we add an
184 extra one to guarantee enough space whilst multiplying. */
185 const unsigned int maxExponent = 16383;
186 const unsigned int maxPrecision = 113;
187 const unsigned int maxPowerOfFiveExponent = maxExponent + maxPrecision - 1;
Craig Topperc85be522017-06-18 18:15:41 +0000188 const unsigned int maxPowerOfFiveParts = 2 + ((maxPowerOfFiveExponent * 815) / (351 * APFloatBase::integerPartWidth));
Tim Shen85de51d2016-10-25 19:55:59 +0000189
190 unsigned int APFloatBase::semanticsPrecision(const fltSemantics &semantics) {
191 return semantics.precision;
192 }
193 APFloatBase::ExponentType
194 APFloatBase::semanticsMaxExponent(const fltSemantics &semantics) {
195 return semantics.maxExponent;
196 }
197 APFloatBase::ExponentType
198 APFloatBase::semanticsMinExponent(const fltSemantics &semantics) {
199 return semantics.minExponent;
200 }
201 unsigned int APFloatBase::semanticsSizeInBits(const fltSemantics &semantics) {
202 return semantics.sizeInBits;
203 }
204
205 unsigned APFloatBase::getSizeInBits(const fltSemantics &Sem) {
206 return Sem.sizeInBits;
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000207}
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000208
Chris Lattner91702092009-03-12 23:59:55 +0000209/* A bunch of private, handy routines. */
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000210
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000211static inline unsigned int
Chris Lattner91702092009-03-12 23:59:55 +0000212partCountForBits(unsigned int bits)
213{
Craig Topperc85be522017-06-18 18:15:41 +0000214 return ((bits) + APFloatBase::integerPartWidth - 1) / APFloatBase::integerPartWidth;
Chris Lattner91702092009-03-12 23:59:55 +0000215}
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000216
Chris Lattner91702092009-03-12 23:59:55 +0000217/* Returns 0U-9U. Return values >= 10U are not digits. */
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000218static inline unsigned int
Chris Lattner91702092009-03-12 23:59:55 +0000219decDigitValue(unsigned int c)
220{
221 return c - '0';
222}
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000223
Chris Lattner91702092009-03-12 23:59:55 +0000224/* Return the value of a decimal exponent of the form
225 [+-]ddddddd.
Neil Booth4ed401b2007-10-14 10:16:12 +0000226
Chris Lattner91702092009-03-12 23:59:55 +0000227 If the exponent overflows, returns a large exponent with the
228 appropriate sign. */
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000229static int
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000230readExponent(StringRef::iterator begin, StringRef::iterator end)
Chris Lattner91702092009-03-12 23:59:55 +0000231{
232 bool isNegative;
233 unsigned int absExponent;
234 const unsigned int overlargeExponent = 24000; /* FIXME. */
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000235 StringRef::iterator p = begin;
236
Eli Friedman3dd72ea2019-03-28 21:12:28 +0000237 // Treat no exponent as 0 to match binutils
238 if (p == end || ((*p == '-' || *p == '+') && (p + 1) == end)) {
239 return 0;
240 }
Neil Booth4ed401b2007-10-14 10:16:12 +0000241
Chris Lattner91702092009-03-12 23:59:55 +0000242 isNegative = (*p == '-');
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000243 if (*p == '-' || *p == '+') {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000244 p++;
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000245 assert(p != end && "Exponent has no digits");
246 }
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000247
Chris Lattner91702092009-03-12 23:59:55 +0000248 absExponent = decDigitValue(*p++);
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000249 assert(absExponent < 10U && "Invalid character in exponent");
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000250
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000251 for (; p != end; ++p) {
Chris Lattner91702092009-03-12 23:59:55 +0000252 unsigned int value;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000253
Chris Lattner91702092009-03-12 23:59:55 +0000254 value = decDigitValue(*p);
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000255 assert(value < 10U && "Invalid character in exponent");
Chris Lattner91702092009-03-12 23:59:55 +0000256
Chris Lattner91702092009-03-12 23:59:55 +0000257 value += absExponent * 10;
258 if (absExponent >= overlargeExponent) {
259 absExponent = overlargeExponent;
Dale Johannesen370c77c2010-08-19 17:58:35 +0000260 p = end; /* outwit assert below */
Chris Lattner91702092009-03-12 23:59:55 +0000261 break;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000262 }
Chris Lattner91702092009-03-12 23:59:55 +0000263 absExponent = value;
264 }
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000265
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000266 assert(p == end && "Invalid exponent in exponent");
267
Chris Lattner91702092009-03-12 23:59:55 +0000268 if (isNegative)
269 return -(int) absExponent;
270 else
271 return (int) absExponent;
272}
273
274/* This is ugly and needs cleaning up, but I don't immediately see
275 how whilst remaining safe. */
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000276static int
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000277totalExponent(StringRef::iterator p, StringRef::iterator end,
278 int exponentAdjustment)
Chris Lattner91702092009-03-12 23:59:55 +0000279{
280 int unsignedExponent;
281 bool negative, overflow;
Ted Kremenek3c4408c2011-01-23 17:05:06 +0000282 int exponent = 0;
Chris Lattner91702092009-03-12 23:59:55 +0000283
Erick Tryzelaarda666c82009-08-20 23:30:43 +0000284 assert(p != end && "Exponent has no digits");
285
Chris Lattner91702092009-03-12 23:59:55 +0000286 negative = *p == '-';
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000287 if (*p == '-' || *p == '+') {
Chris Lattner91702092009-03-12 23:59:55 +0000288 p++;
Erick Tryzelaarda666c82009-08-20 23:30:43 +0000289 assert(p != end && "Exponent has no digits");
290 }
Chris Lattner91702092009-03-12 23:59:55 +0000291
292 unsignedExponent = 0;
293 overflow = false;
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000294 for (; p != end; ++p) {
Chris Lattner91702092009-03-12 23:59:55 +0000295 unsigned int value;
296
297 value = decDigitValue(*p);
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000298 assert(value < 10U && "Invalid character in exponent");
Chris Lattner91702092009-03-12 23:59:55 +0000299
Chris Lattner91702092009-03-12 23:59:55 +0000300 unsignedExponent = unsignedExponent * 10 + value;
Richard Smith156d9202012-08-24 00:01:19 +0000301 if (unsignedExponent > 32767) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000302 overflow = true;
Richard Smith156d9202012-08-24 00:01:19 +0000303 break;
304 }
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000305 }
306
Abramo Bagnaraa41d7ae2011-01-06 16:55:14 +0000307 if (exponentAdjustment > 32767 || exponentAdjustment < -32768)
Chris Lattner91702092009-03-12 23:59:55 +0000308 overflow = true;
309
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000310 if (!overflow) {
Chris Lattner91702092009-03-12 23:59:55 +0000311 exponent = unsignedExponent;
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000312 if (negative)
Chris Lattner91702092009-03-12 23:59:55 +0000313 exponent = -exponent;
314 exponent += exponentAdjustment;
Abramo Bagnaraa41d7ae2011-01-06 16:55:14 +0000315 if (exponent > 32767 || exponent < -32768)
Chris Lattner91702092009-03-12 23:59:55 +0000316 overflow = true;
317 }
318
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000319 if (overflow)
Abramo Bagnaraa41d7ae2011-01-06 16:55:14 +0000320 exponent = negative ? -32768: 32767;
Chris Lattner91702092009-03-12 23:59:55 +0000321
322 return exponent;
323}
324
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000325static StringRef::iterator
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000326skipLeadingZeroesAndAnyDot(StringRef::iterator begin, StringRef::iterator end,
327 StringRef::iterator *dot)
Chris Lattner91702092009-03-12 23:59:55 +0000328{
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000329 StringRef::iterator p = begin;
330 *dot = end;
Nick Lewycky095b92e2014-09-06 01:16:42 +0000331 while (p != end && *p == '0')
Chris Lattner91702092009-03-12 23:59:55 +0000332 p++;
333
Nick Lewycky095b92e2014-09-06 01:16:42 +0000334 if (p != end && *p == '.') {
Chris Lattner91702092009-03-12 23:59:55 +0000335 *dot = p++;
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000336
Erick Tryzelaarda666c82009-08-20 23:30:43 +0000337 assert(end - begin != 1 && "Significand has no digits");
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000338
Nick Lewycky095b92e2014-09-06 01:16:42 +0000339 while (p != end && *p == '0')
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000340 p++;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000341 }
342
Chris Lattner91702092009-03-12 23:59:55 +0000343 return p;
344}
Neil Booth4ed401b2007-10-14 10:16:12 +0000345
Chris Lattner91702092009-03-12 23:59:55 +0000346/* Given a normal decimal floating point number of the form
Neil Booth4ed401b2007-10-14 10:16:12 +0000347
Chris Lattner91702092009-03-12 23:59:55 +0000348 dddd.dddd[eE][+-]ddd
Neil Booth91305512007-10-15 15:00:55 +0000349
Chris Lattner91702092009-03-12 23:59:55 +0000350 where the decimal point and exponent are optional, fill out the
351 structure D. Exponent is appropriate if the significand is
352 treated as an integer, and normalizedExponent if the significand
353 is taken to have the decimal point after a single leading
354 non-zero digit.
Neil Booth4ed401b2007-10-14 10:16:12 +0000355
Chris Lattner91702092009-03-12 23:59:55 +0000356 If the value is zero, V->firstSigDigit points to a non-digit, and
357 the return exponent is zero.
358*/
359struct decimalInfo {
360 const char *firstSigDigit;
361 const char *lastSigDigit;
362 int exponent;
363 int normalizedExponent;
364};
Neil Booth4ed401b2007-10-14 10:16:12 +0000365
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000366static void
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000367interpretDecimal(StringRef::iterator begin, StringRef::iterator end,
368 decimalInfo *D)
Chris Lattner91702092009-03-12 23:59:55 +0000369{
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000370 StringRef::iterator dot = end;
371 StringRef::iterator p = skipLeadingZeroesAndAnyDot (begin, end, &dot);
Neil Booth4ed401b2007-10-14 10:16:12 +0000372
Chris Lattner91702092009-03-12 23:59:55 +0000373 D->firstSigDigit = p;
374 D->exponent = 0;
375 D->normalizedExponent = 0;
376
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000377 for (; p != end; ++p) {
Chris Lattner91702092009-03-12 23:59:55 +0000378 if (*p == '.') {
Erick Tryzelaarda666c82009-08-20 23:30:43 +0000379 assert(dot == end && "String contains multiple dots");
Chris Lattner91702092009-03-12 23:59:55 +0000380 dot = p++;
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000381 if (p == end)
382 break;
Neil Booth4ed401b2007-10-14 10:16:12 +0000383 }
Chris Lattner91702092009-03-12 23:59:55 +0000384 if (decDigitValue(*p) >= 10U)
385 break;
Chris Lattner91702092009-03-12 23:59:55 +0000386 }
Neil Booth4ed401b2007-10-14 10:16:12 +0000387
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000388 if (p != end) {
Erick Tryzelaarda666c82009-08-20 23:30:43 +0000389 assert((*p == 'e' || *p == 'E') && "Invalid character in significand");
390 assert(p != begin && "Significand has no digits");
391 assert((dot == end || p - begin != 1) && "Significand has no digits");
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000392
393 /* p points to the first non-digit in the string */
Erick Tryzelaarda666c82009-08-20 23:30:43 +0000394 D->exponent = readExponent(p + 1, end);
Neil Booth4ed401b2007-10-14 10:16:12 +0000395
Chris Lattner91702092009-03-12 23:59:55 +0000396 /* Implied decimal point? */
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000397 if (dot == end)
Chris Lattner91702092009-03-12 23:59:55 +0000398 dot = p;
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000399 }
Neil Booth4ed401b2007-10-14 10:16:12 +0000400
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000401 /* If number is all zeroes accept any exponent. */
402 if (p != D->firstSigDigit) {
Chris Lattner91702092009-03-12 23:59:55 +0000403 /* Drop insignificant trailing zeroes. */
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000404 if (p != begin) {
Neil Booth4ed401b2007-10-14 10:16:12 +0000405 do
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000406 do
407 p--;
408 while (p != begin && *p == '0');
409 while (p != begin && *p == '.');
410 }
Neil Booth4ed401b2007-10-14 10:16:12 +0000411
Chris Lattner91702092009-03-12 23:59:55 +0000412 /* Adjust the exponents for any decimal point. */
Michael Gottesman9dc98332013-06-24 04:06:23 +0000413 D->exponent += static_cast<APFloat::ExponentType>((dot - p) - (dot > p));
Chris Lattner91702092009-03-12 23:59:55 +0000414 D->normalizedExponent = (D->exponent +
Michael Gottesman9dc98332013-06-24 04:06:23 +0000415 static_cast<APFloat::ExponentType>((p - D->firstSigDigit)
Chris Lattner91702092009-03-12 23:59:55 +0000416 - (dot > D->firstSigDigit && dot < p)));
Neil Booth4ed401b2007-10-14 10:16:12 +0000417 }
418
Chris Lattner91702092009-03-12 23:59:55 +0000419 D->lastSigDigit = p;
420}
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000421
Chris Lattner91702092009-03-12 23:59:55 +0000422/* Return the trailing fraction of a hexadecimal number.
423 DIGITVALUE is the first hex digit of the fraction, P points to
424 the next digit. */
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000425static lostFraction
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000426trailingHexadecimalFraction(StringRef::iterator p, StringRef::iterator end,
427 unsigned int digitValue)
Chris Lattner91702092009-03-12 23:59:55 +0000428{
429 unsigned int hexDigit;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000430
Chris Lattner91702092009-03-12 23:59:55 +0000431 /* If the first trailing digit isn't 0 or 8 we can work out the
432 fraction immediately. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000433 if (digitValue > 8)
Chris Lattner91702092009-03-12 23:59:55 +0000434 return lfMoreThanHalf;
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000435 else if (digitValue < 8 && digitValue > 0)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000436 return lfLessThanHalf;
Chris Lattner91702092009-03-12 23:59:55 +0000437
Eli Friedmand2eb07a2013-07-17 22:17:29 +0000438 // Otherwise we need to find the first non-zero digit.
439 while (p != end && (*p == '0' || *p == '.'))
Chris Lattner91702092009-03-12 23:59:55 +0000440 p++;
441
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000442 assert(p != end && "Invalid trailing hexadecimal fraction!");
443
Chris Lattner91702092009-03-12 23:59:55 +0000444 hexDigit = hexDigitValue(*p);
445
446 /* If we ran off the end it is exactly zero or one-half, otherwise
447 a little more. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000448 if (hexDigit == -1U)
Chris Lattner91702092009-03-12 23:59:55 +0000449 return digitValue == 0 ? lfExactlyZero: lfExactlyHalf;
450 else
451 return digitValue == 0 ? lfLessThanHalf: lfMoreThanHalf;
452}
453
454/* Return the fraction lost were a bignum truncated losing the least
455 significant BITS bits. */
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000456static lostFraction
Craig Topperc85be522017-06-18 18:15:41 +0000457lostFractionThroughTruncation(const APFloatBase::integerPart *parts,
Chris Lattner91702092009-03-12 23:59:55 +0000458 unsigned int partCount,
459 unsigned int bits)
460{
461 unsigned int lsb;
462
463 lsb = APInt::tcLSB(parts, partCount);
464
465 /* Note this is guaranteed true if bits == 0, or LSB == -1U. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000466 if (bits <= lsb)
Chris Lattner91702092009-03-12 23:59:55 +0000467 return lfExactlyZero;
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000468 if (bits == lsb + 1)
Chris Lattner91702092009-03-12 23:59:55 +0000469 return lfExactlyHalf;
Craig Topperc85be522017-06-18 18:15:41 +0000470 if (bits <= partCount * APFloatBase::integerPartWidth &&
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000471 APInt::tcExtractBit(parts, bits - 1))
Chris Lattner91702092009-03-12 23:59:55 +0000472 return lfMoreThanHalf;
473
474 return lfLessThanHalf;
475}
476
477/* Shift DST right BITS bits noting lost fraction. */
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000478static lostFraction
Craig Topperc85be522017-06-18 18:15:41 +0000479shiftRight(APFloatBase::integerPart *dst, unsigned int parts, unsigned int bits)
Chris Lattner91702092009-03-12 23:59:55 +0000480{
481 lostFraction lost_fraction;
482
483 lost_fraction = lostFractionThroughTruncation(dst, parts, bits);
484
485 APInt::tcShiftRight(dst, parts, bits);
486
487 return lost_fraction;
488}
489
490/* Combine the effect of two lost fractions. */
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000491static lostFraction
Chris Lattner91702092009-03-12 23:59:55 +0000492combineLostFractions(lostFraction moreSignificant,
493 lostFraction lessSignificant)
494{
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000495 if (lessSignificant != lfExactlyZero) {
496 if (moreSignificant == lfExactlyZero)
Chris Lattner91702092009-03-12 23:59:55 +0000497 moreSignificant = lfLessThanHalf;
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000498 else if (moreSignificant == lfExactlyHalf)
Chris Lattner91702092009-03-12 23:59:55 +0000499 moreSignificant = lfMoreThanHalf;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000500 }
501
Chris Lattner91702092009-03-12 23:59:55 +0000502 return moreSignificant;
503}
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000504
Chris Lattner91702092009-03-12 23:59:55 +0000505/* The error from the true value, in half-ulps, on multiplying two
506 floating point numbers, which differ from the value they
507 approximate by at most HUE1 and HUE2 half-ulps, is strictly less
508 than the returned value.
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000509
Chris Lattner91702092009-03-12 23:59:55 +0000510 See "How to Read Floating Point Numbers Accurately" by William D
511 Clinger. */
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000512static unsigned int
Chris Lattner91702092009-03-12 23:59:55 +0000513HUerrBound(bool inexactMultiply, unsigned int HUerr1, unsigned int HUerr2)
514{
515 assert(HUerr1 < 2 || HUerr2 < 2 || (HUerr1 + HUerr2 < 8));
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000516
Chris Lattner91702092009-03-12 23:59:55 +0000517 if (HUerr1 + HUerr2 == 0)
518 return inexactMultiply * 2; /* <= inexactMultiply half-ulps. */
519 else
520 return inexactMultiply + 2 * (HUerr1 + HUerr2);
521}
Neil Booth8f1946f2007-10-03 22:26:02 +0000522
Chris Lattner91702092009-03-12 23:59:55 +0000523/* The number of ulps from the boundary (zero, or half if ISNEAREST)
524 when the least significant BITS are truncated. BITS cannot be
525 zero. */
Craig Topperc85be522017-06-18 18:15:41 +0000526static APFloatBase::integerPart
527ulpsFromBoundary(const APFloatBase::integerPart *parts, unsigned int bits,
528 bool isNearest) {
Chris Lattner91702092009-03-12 23:59:55 +0000529 unsigned int count, partBits;
Craig Topperc85be522017-06-18 18:15:41 +0000530 APFloatBase::integerPart part, boundary;
Neil Boothd3985922007-10-07 08:51:21 +0000531
Evan Cheng67c90212009-10-27 21:35:42 +0000532 assert(bits != 0);
Neil Booth8f1946f2007-10-03 22:26:02 +0000533
Chris Lattner91702092009-03-12 23:59:55 +0000534 bits--;
Craig Topperc85be522017-06-18 18:15:41 +0000535 count = bits / APFloatBase::integerPartWidth;
536 partBits = bits % APFloatBase::integerPartWidth + 1;
Neil Boothb93d90e2007-10-12 16:02:31 +0000537
Craig Topperc85be522017-06-18 18:15:41 +0000538 part = parts[count] & (~(APFloatBase::integerPart) 0 >> (APFloatBase::integerPartWidth - partBits));
Neil Boothb93d90e2007-10-12 16:02:31 +0000539
Chris Lattner91702092009-03-12 23:59:55 +0000540 if (isNearest)
Craig Topperc85be522017-06-18 18:15:41 +0000541 boundary = (APFloatBase::integerPart) 1 << (partBits - 1);
Chris Lattner91702092009-03-12 23:59:55 +0000542 else
543 boundary = 0;
544
545 if (count == 0) {
546 if (part - boundary <= boundary - part)
547 return part - boundary;
Neil Boothb93d90e2007-10-12 16:02:31 +0000548 else
Chris Lattner91702092009-03-12 23:59:55 +0000549 return boundary - part;
Neil Boothb93d90e2007-10-12 16:02:31 +0000550 }
551
Chris Lattner91702092009-03-12 23:59:55 +0000552 if (part == boundary) {
553 while (--count)
554 if (parts[count])
Craig Topperc85be522017-06-18 18:15:41 +0000555 return ~(APFloatBase::integerPart) 0; /* A lot. */
Neil Boothb93d90e2007-10-12 16:02:31 +0000556
Chris Lattner91702092009-03-12 23:59:55 +0000557 return parts[0];
558 } else if (part == boundary - 1) {
559 while (--count)
560 if (~parts[count])
Craig Topperc85be522017-06-18 18:15:41 +0000561 return ~(APFloatBase::integerPart) 0; /* A lot. */
Neil Boothb93d90e2007-10-12 16:02:31 +0000562
Chris Lattner91702092009-03-12 23:59:55 +0000563 return -parts[0];
564 }
Neil Boothb93d90e2007-10-12 16:02:31 +0000565
Craig Topperc85be522017-06-18 18:15:41 +0000566 return ~(APFloatBase::integerPart) 0; /* A lot. */
Chris Lattner91702092009-03-12 23:59:55 +0000567}
Neil Boothb93d90e2007-10-12 16:02:31 +0000568
Chris Lattner91702092009-03-12 23:59:55 +0000569/* Place pow(5, power) in DST, and return the number of parts used.
570 DST must be at least one part larger than size of the answer. */
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000571static unsigned int
Craig Topperc85be522017-06-18 18:15:41 +0000572powerOf5(APFloatBase::integerPart *dst, unsigned int power) {
573 static const APFloatBase::integerPart firstEightPowers[] = { 1, 5, 25, 125, 625, 3125, 15625, 78125 };
574 APFloatBase::integerPart pow5s[maxPowerOfFiveParts * 2 + 5];
Chris Lattnerb858c0e2009-03-13 00:24:01 +0000575 pow5s[0] = 78125 * 5;
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000576
Chris Lattner0bf18692009-03-13 00:03:51 +0000577 unsigned int partsCount[16] = { 1 };
Craig Topperc85be522017-06-18 18:15:41 +0000578 APFloatBase::integerPart scratch[maxPowerOfFiveParts], *p1, *p2, *pow5;
Chris Lattner91702092009-03-12 23:59:55 +0000579 unsigned int result;
Chris Lattner91702092009-03-12 23:59:55 +0000580 assert(power <= maxExponent);
581
582 p1 = dst;
583 p2 = scratch;
584
585 *p1 = firstEightPowers[power & 7];
586 power >>= 3;
587
588 result = 1;
589 pow5 = pow5s;
590
591 for (unsigned int n = 0; power; power >>= 1, n++) {
592 unsigned int pc;
593
594 pc = partsCount[n];
595
596 /* Calculate pow(5,pow(2,n+3)) if we haven't yet. */
597 if (pc == 0) {
598 pc = partsCount[n - 1];
599 APInt::tcFullMultiply(pow5, pow5 - pc, pow5 - pc, pc, pc);
600 pc *= 2;
601 if (pow5[pc - 1] == 0)
602 pc--;
603 partsCount[n] = pc;
Neil Boothb93d90e2007-10-12 16:02:31 +0000604 }
605
Chris Lattner91702092009-03-12 23:59:55 +0000606 if (power & 1) {
Craig Topperc85be522017-06-18 18:15:41 +0000607 APFloatBase::integerPart *tmp;
Neil Boothb93d90e2007-10-12 16:02:31 +0000608
Chris Lattner91702092009-03-12 23:59:55 +0000609 APInt::tcFullMultiply(p2, p1, pow5, result, pc);
610 result += pc;
611 if (p2[result - 1] == 0)
612 result--;
Neil Boothb93d90e2007-10-12 16:02:31 +0000613
Chris Lattner91702092009-03-12 23:59:55 +0000614 /* Now result is in p1 with partsCount parts and p2 is scratch
615 space. */
Richard Trieu7a083812016-02-18 22:09:30 +0000616 tmp = p1;
617 p1 = p2;
618 p2 = tmp;
Neil Boothb93d90e2007-10-12 16:02:31 +0000619 }
620
Chris Lattner91702092009-03-12 23:59:55 +0000621 pow5 += pc;
Neil Boothb93d90e2007-10-12 16:02:31 +0000622 }
623
Chris Lattner91702092009-03-12 23:59:55 +0000624 if (p1 != dst)
625 APInt::tcAssign(dst, p1, result);
Neil Boothb93d90e2007-10-12 16:02:31 +0000626
Chris Lattner91702092009-03-12 23:59:55 +0000627 return result;
628}
Neil Boothb93d90e2007-10-12 16:02:31 +0000629
Chris Lattner91702092009-03-12 23:59:55 +0000630/* Zero at the end to avoid modular arithmetic when adding one; used
631 when rounding up during hexadecimal output. */
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000632static const char hexDigitsLower[] = "0123456789abcdef0";
633static const char hexDigitsUpper[] = "0123456789ABCDEF0";
634static const char infinityL[] = "infinity";
635static const char infinityU[] = "INFINITY";
636static const char NaNL[] = "nan";
637static const char NaNU[] = "NAN";
Neil Boothb93d90e2007-10-12 16:02:31 +0000638
Chris Lattner91702092009-03-12 23:59:55 +0000639/* Write out an integerPart in hexadecimal, starting with the most
640 significant nibble. Write out exactly COUNT hexdigits, return
641 COUNT. */
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000642static unsigned int
Craig Topperc85be522017-06-18 18:15:41 +0000643partAsHex (char *dst, APFloatBase::integerPart part, unsigned int count,
Chris Lattner91702092009-03-12 23:59:55 +0000644 const char *hexDigitChars)
645{
646 unsigned int result = count;
Neil Boothb93d90e2007-10-12 16:02:31 +0000647
Craig Topperc85be522017-06-18 18:15:41 +0000648 assert(count != 0 && count <= APFloatBase::integerPartWidth / 4);
Neil Boothb93d90e2007-10-12 16:02:31 +0000649
Craig Topperc85be522017-06-18 18:15:41 +0000650 part >>= (APFloatBase::integerPartWidth - 4 * count);
Chris Lattner91702092009-03-12 23:59:55 +0000651 while (count--) {
652 dst[count] = hexDigitChars[part & 0xf];
653 part >>= 4;
Neil Boothb93d90e2007-10-12 16:02:31 +0000654 }
655
Chris Lattner91702092009-03-12 23:59:55 +0000656 return result;
657}
Neil Booth8f1946f2007-10-03 22:26:02 +0000658
Chris Lattner91702092009-03-12 23:59:55 +0000659/* Write out an unsigned decimal integer. */
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000660static char *
Chris Lattner91702092009-03-12 23:59:55 +0000661writeUnsignedDecimal (char *dst, unsigned int n)
662{
663 char buff[40], *p;
Neil Booth8f1946f2007-10-03 22:26:02 +0000664
Chris Lattner91702092009-03-12 23:59:55 +0000665 p = buff;
666 do
667 *p++ = '0' + n % 10;
668 while (n /= 10);
Neil Booth8f1946f2007-10-03 22:26:02 +0000669
Chris Lattner91702092009-03-12 23:59:55 +0000670 do
671 *dst++ = *--p;
672 while (p != buff);
Neil Booth8f1946f2007-10-03 22:26:02 +0000673
Chris Lattner91702092009-03-12 23:59:55 +0000674 return dst;
675}
Neil Booth8f1946f2007-10-03 22:26:02 +0000676
Chris Lattner91702092009-03-12 23:59:55 +0000677/* Write out a signed decimal integer. */
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000678static char *
Chris Lattner91702092009-03-12 23:59:55 +0000679writeSignedDecimal (char *dst, int value)
680{
681 if (value < 0) {
682 *dst++ = '-';
683 dst = writeUnsignedDecimal(dst, -(unsigned) value);
684 } else
685 dst = writeUnsignedDecimal(dst, value);
Neil Booth8f1946f2007-10-03 22:26:02 +0000686
Chris Lattner91702092009-03-12 23:59:55 +0000687 return dst;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000688}
689
Tim Shen85de51d2016-10-25 19:55:59 +0000690namespace detail {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000691/* Constructors. */
Tim Shen85de51d2016-10-25 19:55:59 +0000692void IEEEFloat::initialize(const fltSemantics *ourSemantics) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000693 unsigned int count;
694
695 semantics = ourSemantics;
696 count = partCount();
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000697 if (count > 1)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000698 significand.parts = new integerPart[count];
699}
700
Tim Shen85de51d2016-10-25 19:55:59 +0000701void IEEEFloat::freeSignificand() {
Manuel Klimekd0cf5b22013-06-03 13:03:05 +0000702 if (needsCleanup())
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000703 delete [] significand.parts;
704}
705
Tim Shen85de51d2016-10-25 19:55:59 +0000706void IEEEFloat::assign(const IEEEFloat &rhs) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000707 assert(semantics == rhs.semantics);
708
709 sign = rhs.sign;
710 category = rhs.category;
711 exponent = rhs.exponent;
Michael Gottesman8136c382013-06-26 23:17:28 +0000712 if (isFiniteNonZero() || category == fcNaN)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000713 copySignificand(rhs);
714}
715
Tim Shen85de51d2016-10-25 19:55:59 +0000716void IEEEFloat::copySignificand(const IEEEFloat &rhs) {
Michael Gottesman8136c382013-06-26 23:17:28 +0000717 assert(isFiniteNonZero() || category == fcNaN);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000718 assert(rhs.partCount() >= partCount());
719
720 APInt::tcAssign(significandParts(), rhs.significandParts(),
Neil Booth9acbf5a2007-09-26 21:33:42 +0000721 partCount());
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000722}
723
Neil Booth5fe658b2007-10-14 10:39:51 +0000724/* Make this number a NaN, with an arbitrary but deterministic value
Dale Johannesen1f864982009-01-21 20:32:55 +0000725 for the significand. If double or longer, this is a signalling NaN,
Mike Stump799bf582009-05-30 03:49:43 +0000726 which may not be ideal. If float, this is QNaN(0). */
Tim Shen85de51d2016-10-25 19:55:59 +0000727void IEEEFloat::makeNaN(bool SNaN, bool Negative, const APInt *fill) {
Neil Booth5fe658b2007-10-14 10:39:51 +0000728 category = fcNaN;
John McCalldcb9a7a2010-02-28 02:51:25 +0000729 sign = Negative;
730
John McCallc12b1332010-02-28 12:49:50 +0000731 integerPart *significand = significandParts();
732 unsigned numParts = partCount();
733
John McCalldcb9a7a2010-02-28 02:51:25 +0000734 // Set the significand bits to the fill.
John McCallc12b1332010-02-28 12:49:50 +0000735 if (!fill || fill->getNumWords() < numParts)
736 APInt::tcSet(significand, 0, numParts);
737 if (fill) {
John McCallc6dbe302010-03-01 18:38:45 +0000738 APInt::tcAssign(significand, fill->getRawData(),
739 std::min(fill->getNumWords(), numParts));
John McCallc12b1332010-02-28 12:49:50 +0000740
741 // Zero out the excess bits of the significand.
742 unsigned bitsToPreserve = semantics->precision - 1;
743 unsigned part = bitsToPreserve / 64;
744 bitsToPreserve %= 64;
745 significand[part] &= ((1ULL << bitsToPreserve) - 1);
746 for (part++; part != numParts; ++part)
747 significand[part] = 0;
748 }
749
750 unsigned QNaNBit = semantics->precision - 2;
John McCalldcb9a7a2010-02-28 02:51:25 +0000751
752 if (SNaN) {
753 // We always have to clear the QNaN bit to make it an SNaN.
John McCallc12b1332010-02-28 12:49:50 +0000754 APInt::tcClearBit(significand, QNaNBit);
John McCalldcb9a7a2010-02-28 02:51:25 +0000755
756 // If there are no bits set in the payload, we have to set
757 // *something* to make it a NaN instead of an infinity;
758 // conventionally, this is the next bit down from the QNaN bit.
John McCallc12b1332010-02-28 12:49:50 +0000759 if (APInt::tcIsZero(significand, numParts))
760 APInt::tcSetBit(significand, QNaNBit - 1);
John McCalldcb9a7a2010-02-28 02:51:25 +0000761 } else {
762 // We always have to set the QNaN bit to make it a QNaN.
John McCallc12b1332010-02-28 12:49:50 +0000763 APInt::tcSetBit(significand, QNaNBit);
John McCalldcb9a7a2010-02-28 02:51:25 +0000764 }
John McCallc12b1332010-02-28 12:49:50 +0000765
766 // For x87 extended precision, we want to make a NaN, not a
767 // pseudo-NaN. Maybe we should expose the ability to make
768 // pseudo-NaNs?
Stephan Bergmann17c7f702016-12-14 11:57:17 +0000769 if (semantics == &semX87DoubleExtended)
John McCallc12b1332010-02-28 12:49:50 +0000770 APInt::tcSetBit(significand, QNaNBit + 1);
John McCalldcb9a7a2010-02-28 02:51:25 +0000771}
772
Tim Shen85de51d2016-10-25 19:55:59 +0000773IEEEFloat &IEEEFloat::operator=(const IEEEFloat &rhs) {
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000774 if (this != &rhs) {
775 if (semantics != rhs.semantics) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000776 freeSignificand();
777 initialize(rhs.semantics);
778 }
779 assign(rhs);
780 }
781
782 return *this;
783}
784
Tim Shen85de51d2016-10-25 19:55:59 +0000785IEEEFloat &IEEEFloat::operator=(IEEEFloat &&rhs) {
Benjamin Kramer06f47782014-03-04 20:26:51 +0000786 freeSignificand();
787
788 semantics = rhs.semantics;
789 significand = rhs.significand;
790 exponent = rhs.exponent;
791 category = rhs.category;
792 sign = rhs.sign;
793
Stephan Bergmann17c7f702016-12-14 11:57:17 +0000794 rhs.semantics = &semBogus;
Benjamin Kramer06f47782014-03-04 20:26:51 +0000795 return *this;
796}
797
Tim Shen85de51d2016-10-25 19:55:59 +0000798bool IEEEFloat::isDenormal() const {
Michael Gottesman3cb77ab2013-06-19 21:23:18 +0000799 return isFiniteNonZero() && (exponent == semantics->minExponent) &&
Simon Pilgrima2849592017-03-20 13:53:59 +0000800 (APInt::tcExtractBit(significandParts(),
Shuxin Yang4fb504f2013-01-07 18:59:35 +0000801 semantics->precision - 1) == 0);
802}
803
Tim Shen85de51d2016-10-25 19:55:59 +0000804bool IEEEFloat::isSmallest() const {
Michael Gottesman0c622ea2013-05-30 18:07:13 +0000805 // The smallest number by magnitude in our format will be the smallest
Michael Gottesmana7cc1242013-06-19 07:34:21 +0000806 // denormal, i.e. the floating point number with exponent being minimum
Michael Gottesman0c622ea2013-05-30 18:07:13 +0000807 // exponent and significand bitwise equal to 1 (i.e. with MSB equal to 0).
Michael Gottesman3cb77ab2013-06-19 21:23:18 +0000808 return isFiniteNonZero() && exponent == semantics->minExponent &&
Michael Gottesman0c622ea2013-05-30 18:07:13 +0000809 significandMSB() == 0;
810}
811
Tim Shen85de51d2016-10-25 19:55:59 +0000812bool IEEEFloat::isSignificandAllOnes() const {
Michael Gottesman0c622ea2013-05-30 18:07:13 +0000813 // Test if the significand excluding the integral bit is all ones. This allows
814 // us to test for binade boundaries.
815 const integerPart *Parts = significandParts();
816 const unsigned PartCount = partCount();
817 for (unsigned i = 0; i < PartCount - 1; i++)
818 if (~Parts[i])
819 return false;
820
821 // Set the unused high bits to all ones when we compare.
822 const unsigned NumHighBits =
823 PartCount*integerPartWidth - semantics->precision + 1;
824 assert(NumHighBits <= integerPartWidth && "Can not have more high bits to "
825 "fill than integerPartWidth");
826 const integerPart HighBitFill =
827 ~integerPart(0) << (integerPartWidth - NumHighBits);
828 if (~(Parts[PartCount - 1] | HighBitFill))
829 return false;
830
831 return true;
832}
833
Tim Shen85de51d2016-10-25 19:55:59 +0000834bool IEEEFloat::isSignificandAllZeros() const {
Michael Gottesman0c622ea2013-05-30 18:07:13 +0000835 // Test if the significand excluding the integral bit is all zeros. This
836 // allows us to test for binade boundaries.
837 const integerPart *Parts = significandParts();
838 const unsigned PartCount = partCount();
839
840 for (unsigned i = 0; i < PartCount - 1; i++)
841 if (Parts[i])
842 return false;
843
844 const unsigned NumHighBits =
845 PartCount*integerPartWidth - semantics->precision + 1;
846 assert(NumHighBits <= integerPartWidth && "Can not have more high bits to "
847 "clear than integerPartWidth");
848 const integerPart HighBitMask = ~integerPart(0) >> NumHighBits;
849
850 if (Parts[PartCount - 1] & HighBitMask)
851 return false;
852
853 return true;
854}
855
Tim Shen85de51d2016-10-25 19:55:59 +0000856bool IEEEFloat::isLargest() const {
Michael Gottesman0c622ea2013-05-30 18:07:13 +0000857 // The largest number by magnitude in our format will be the floating point
858 // number with maximum exponent and with significand that is all ones.
Michael Gottesman3cb77ab2013-06-19 21:23:18 +0000859 return isFiniteNonZero() && exponent == semantics->maxExponent
Michael Gottesman0c622ea2013-05-30 18:07:13 +0000860 && isSignificandAllOnes();
861}
862
Tim Shen85de51d2016-10-25 19:55:59 +0000863bool IEEEFloat::isInteger() const {
Stephen Canon1bfc89b2015-11-16 21:52:48 +0000864 // This could be made more efficient; I'm going for obviously correct.
865 if (!isFinite()) return false;
Tim Shen85de51d2016-10-25 19:55:59 +0000866 IEEEFloat truncated = *this;
Stephen Canon1bfc89b2015-11-16 21:52:48 +0000867 truncated.roundToIntegral(rmTowardZero);
868 return compare(truncated) == cmpEqual;
869}
870
Tim Shen85de51d2016-10-25 19:55:59 +0000871bool IEEEFloat::bitwiseIsEqual(const IEEEFloat &rhs) const {
Dale Johannesena719a602007-08-24 00:56:33 +0000872 if (this == &rhs)
873 return true;
874 if (semantics != rhs.semantics ||
Dale Johannesen3cf889f2007-08-31 04:03:46 +0000875 category != rhs.category ||
876 sign != rhs.sign)
Dale Johannesena719a602007-08-24 00:56:33 +0000877 return false;
Dale Johannesen3cf889f2007-08-31 04:03:46 +0000878 if (category==fcZero || category==fcInfinity)
Dale Johannesena719a602007-08-24 00:56:33 +0000879 return true;
Benjamin Kramer103fc942015-08-21 16:44:52 +0000880
881 if (isFiniteNonZero() && exponent != rhs.exponent)
Dale Johannesen3cf889f2007-08-31 04:03:46 +0000882 return false;
Benjamin Kramer103fc942015-08-21 16:44:52 +0000883
884 return std::equal(significandParts(), significandParts() + partCount(),
885 rhs.significandParts());
Dale Johannesena719a602007-08-24 00:56:33 +0000886}
887
Tim Shen85de51d2016-10-25 19:55:59 +0000888IEEEFloat::IEEEFloat(const fltSemantics &ourSemantics, integerPart value) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000889 initialize(&ourSemantics);
890 sign = 0;
Michael Gottesman30a90eb2013-07-27 21:49:21 +0000891 category = fcNormal;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000892 zeroSignificand();
893 exponent = ourSemantics.precision - 1;
894 significandParts()[0] = value;
895 normalize(rmNearestTiesToEven, lfExactlyZero);
896}
897
Tim Shen85de51d2016-10-25 19:55:59 +0000898IEEEFloat::IEEEFloat(const fltSemantics &ourSemantics) {
Chris Lattnerac6271e2009-09-17 01:08:43 +0000899 initialize(&ourSemantics);
900 category = fcZero;
901 sign = false;
902}
903
Tim Shenb49915482016-10-28 22:45:33 +0000904// Delegate to the previous constructor, because later copy constructor may
905// actually inspects category, which can't be garbage.
906IEEEFloat::IEEEFloat(const fltSemantics &ourSemantics, uninitializedTag tag)
Tim Shen1bab9cf2016-10-29 00:51:41 +0000907 : IEEEFloat(ourSemantics) {}
Chris Lattnerac6271e2009-09-17 01:08:43 +0000908
Tim Shen85de51d2016-10-25 19:55:59 +0000909IEEEFloat::IEEEFloat(const IEEEFloat &rhs) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000910 initialize(rhs.semantics);
911 assign(rhs);
912}
913
Stephan Bergmann17c7f702016-12-14 11:57:17 +0000914IEEEFloat::IEEEFloat(IEEEFloat &&rhs) : semantics(&semBogus) {
Benjamin Kramer06f47782014-03-04 20:26:51 +0000915 *this = std::move(rhs);
916}
917
Tim Shen85de51d2016-10-25 19:55:59 +0000918IEEEFloat::~IEEEFloat() { freeSignificand(); }
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000919
Tim Shen85de51d2016-10-25 19:55:59 +0000920unsigned int IEEEFloat::partCount() const {
Dale Johannesen146a0ea2007-09-20 23:47:58 +0000921 return partCountForBits(semantics->precision + 1);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000922}
923
Craig Topperc85be522017-06-18 18:15:41 +0000924const IEEEFloat::integerPart *IEEEFloat::significandParts() const {
Tim Shen85de51d2016-10-25 19:55:59 +0000925 return const_cast<IEEEFloat *>(this)->significandParts();
JF Bastiena1d3c242015-08-26 02:32:45 +0000926}
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000927
Craig Topperc85be522017-06-18 18:15:41 +0000928IEEEFloat::integerPart *IEEEFloat::significandParts() {
Evan Cheng67c90212009-10-27 21:35:42 +0000929 if (partCount() > 1)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000930 return significand.parts;
931 else
932 return &significand.part;
933}
934
Tim Shen85de51d2016-10-25 19:55:59 +0000935void IEEEFloat::zeroSignificand() {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000936 APInt::tcSet(significandParts(), 0, partCount());
937}
938
939/* Increment an fcNormal floating point number's significand. */
Tim Shen85de51d2016-10-25 19:55:59 +0000940void IEEEFloat::incrementSignificand() {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000941 integerPart carry;
942
943 carry = APInt::tcIncrement(significandParts(), partCount());
944
945 /* Our callers should never cause us to overflow. */
946 assert(carry == 0);
Duncan Sandsa41634e2011-08-12 14:54:45 +0000947 (void)carry;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000948}
949
950/* Add the significand of the RHS. Returns the carry flag. */
Craig Topperc85be522017-06-18 18:15:41 +0000951IEEEFloat::integerPart IEEEFloat::addSignificand(const IEEEFloat &rhs) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000952 integerPart *parts;
953
954 parts = significandParts();
955
956 assert(semantics == rhs.semantics);
957 assert(exponent == rhs.exponent);
958
959 return APInt::tcAdd(parts, rhs.significandParts(), 0, partCount());
960}
961
962/* Subtract the significand of the RHS with a borrow flag. Returns
963 the borrow flag. */
Craig Topperc85be522017-06-18 18:15:41 +0000964IEEEFloat::integerPart IEEEFloat::subtractSignificand(const IEEEFloat &rhs,
965 integerPart borrow) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000966 integerPart *parts;
967
968 parts = significandParts();
969
970 assert(semantics == rhs.semantics);
971 assert(exponent == rhs.exponent);
972
973 return APInt::tcSubtract(parts, rhs.significandParts(), borrow,
Neil Booth9acbf5a2007-09-26 21:33:42 +0000974 partCount());
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000975}
976
977/* Multiply the significand of the RHS. If ADDEND is non-NULL, add it
978 on to the full-precision result of the multiplication. Returns the
979 lost fraction. */
Tim Shen85de51d2016-10-25 19:55:59 +0000980lostFraction IEEEFloat::multiplySignificand(const IEEEFloat &rhs,
981 const IEEEFloat *addend) {
Neil Booth9acbf5a2007-09-26 21:33:42 +0000982 unsigned int omsb; // One, not zero, based MSB.
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000983 unsigned int partsCount, newPartsCount, precision;
984 integerPart *lhsSignificand;
985 integerPart scratch[4];
986 integerPart *fullSignificand;
987 lostFraction lost_fraction;
Dale Johannesen4f0bd682008-10-09 23:00:39 +0000988 bool ignored;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000989
990 assert(semantics == rhs.semantics);
991
992 precision = semantics->precision;
Lang Hames56c0eb22014-11-19 19:15:41 +0000993
994 // Allocate space for twice as many bits as the original significand, plus one
995 // extra bit for the addition to overflow into.
996 newPartsCount = partCountForBits(precision * 2 + 1);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000997
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000998 if (newPartsCount > 4)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000999 fullSignificand = new integerPart[newPartsCount];
1000 else
1001 fullSignificand = scratch;
1002
1003 lhsSignificand = significandParts();
1004 partsCount = partCount();
1005
1006 APInt::tcFullMultiply(fullSignificand, lhsSignificand,
Neil Booth0ea72a92007-10-06 00:24:48 +00001007 rhs.significandParts(), partsCount, partsCount);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001008
1009 lost_fraction = lfExactlyZero;
1010 omsb = APInt::tcMSB(fullSignificand, newPartsCount) + 1;
1011 exponent += rhs.exponent;
1012
Shuxin Yangbbddbac2013-05-13 18:03:12 +00001013 // Assume the operands involved in the multiplication are single-precision
1014 // FP, and the two multiplicants are:
1015 // *this = a23 . a22 ... a0 * 2^e1
1016 // rhs = b23 . b22 ... b0 * 2^e2
1017 // the result of multiplication is:
Lang Hames56c0eb22014-11-19 19:15:41 +00001018 // *this = c48 c47 c46 . c45 ... c0 * 2^(e1+e2)
Simon Pilgrima2849592017-03-20 13:53:59 +00001019 // Note that there are three significant bits at the left-hand side of the
Lang Hames56c0eb22014-11-19 19:15:41 +00001020 // radix point: two for the multiplication, and an overflow bit for the
1021 // addition (that will always be zero at this point). Move the radix point
1022 // toward left by two bits, and adjust exponent accordingly.
1023 exponent += 2;
Shuxin Yangbbddbac2013-05-13 18:03:12 +00001024
Hal Finkel171c2ec2014-10-14 19:23:07 +00001025 if (addend && addend->isNonZero()) {
Simon Pilgrima2849592017-03-20 13:53:59 +00001026 // The intermediate result of the multiplication has "2 * precision"
Shuxin Yangbbddbac2013-05-13 18:03:12 +00001027 // signicant bit; adjust the addend to be consistent with mul result.
1028 //
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001029 Significand savedSignificand = significand;
1030 const fltSemantics *savedSemantics = semantics;
1031 fltSemantics extendedSemantics;
1032 opStatus status;
1033 unsigned int extendedPrecision;
1034
Lang Hames56c0eb22014-11-19 19:15:41 +00001035 // Normalize our MSB to one below the top bit to allow for overflow.
1036 extendedPrecision = 2 * precision + 1;
1037 if (omsb != extendedPrecision - 1) {
Shuxin Yangbbddbac2013-05-13 18:03:12 +00001038 assert(extendedPrecision > omsb);
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001039 APInt::tcShiftLeft(fullSignificand, newPartsCount,
Lang Hames56c0eb22014-11-19 19:15:41 +00001040 (extendedPrecision - 1) - omsb);
1041 exponent -= (extendedPrecision - 1) - omsb;
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001042 }
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001043
1044 /* Create new semantics. */
1045 extendedSemantics = *semantics;
1046 extendedSemantics.precision = extendedPrecision;
1047
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001048 if (newPartsCount == 1)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001049 significand.part = fullSignificand[0];
1050 else
1051 significand.parts = fullSignificand;
1052 semantics = &extendedSemantics;
1053
Tim Shen85de51d2016-10-25 19:55:59 +00001054 IEEEFloat extendedAddend(*addend);
Dale Johannesen4f0bd682008-10-09 23:00:39 +00001055 status = extendedAddend.convert(extendedSemantics, rmTowardZero, &ignored);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001056 assert(status == opOK);
Duncan Sandsa41634e2011-08-12 14:54:45 +00001057 (void)status;
Lang Hames56c0eb22014-11-19 19:15:41 +00001058
1059 // Shift the significand of the addend right by one bit. This guarantees
1060 // that the high bit of the significand is zero (same as fullSignificand),
1061 // so the addition will overflow (if it does overflow at all) into the top bit.
1062 lost_fraction = extendedAddend.shiftSignificandRight(1);
1063 assert(lost_fraction == lfExactlyZero &&
1064 "Lost precision while shifting addend for fused-multiply-add.");
1065
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001066 lost_fraction = addOrSubtractSignificand(extendedAddend, false);
1067
1068 /* Restore our state. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001069 if (newPartsCount == 1)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001070 fullSignificand[0] = significand.part;
1071 significand = savedSignificand;
1072 semantics = savedSemantics;
1073
1074 omsb = APInt::tcMSB(fullSignificand, newPartsCount) + 1;
1075 }
1076
Shuxin Yangbbddbac2013-05-13 18:03:12 +00001077 // Convert the result having "2 * precision" significant-bits back to the one
Simon Pilgrima2849592017-03-20 13:53:59 +00001078 // having "precision" significant-bits. First, move the radix point from
Shuxin Yangbbddbac2013-05-13 18:03:12 +00001079 // poision "2*precision - 1" to "precision - 1". The exponent need to be
1080 // adjusted by "2*precision - 1" - "precision - 1" = "precision".
Lang Hames56c0eb22014-11-19 19:15:41 +00001081 exponent -= precision + 1;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001082
Shuxin Yangbbddbac2013-05-13 18:03:12 +00001083 // In case MSB resides at the left-hand side of radix point, shift the
1084 // mantissa right by some amount to make sure the MSB reside right before
1085 // the radix point (i.e. "MSB . rest-significant-bits").
1086 //
1087 // Note that the result is not normalized when "omsb < precision". So, the
Tim Shen85de51d2016-10-25 19:55:59 +00001088 // caller needs to call IEEEFloat::normalize() if normalized value is
1089 // expected.
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001090 if (omsb > precision) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001091 unsigned int bits, significantParts;
1092 lostFraction lf;
1093
1094 bits = omsb - precision;
1095 significantParts = partCountForBits(omsb);
1096 lf = shiftRight(fullSignificand, significantParts, bits);
1097 lost_fraction = combineLostFractions(lf, lost_fraction);
1098 exponent += bits;
1099 }
1100
1101 APInt::tcAssign(lhsSignificand, fullSignificand, partsCount);
1102
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001103 if (newPartsCount > 4)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001104 delete [] fullSignificand;
1105
1106 return lost_fraction;
1107}
1108
1109/* Multiply the significands of LHS and RHS to DST. */
Tim Shen85de51d2016-10-25 19:55:59 +00001110lostFraction IEEEFloat::divideSignificand(const IEEEFloat &rhs) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001111 unsigned int bit, i, partsCount;
1112 const integerPart *rhsSignificand;
1113 integerPart *lhsSignificand, *dividend, *divisor;
1114 integerPart scratch[4];
1115 lostFraction lost_fraction;
1116
1117 assert(semantics == rhs.semantics);
1118
1119 lhsSignificand = significandParts();
1120 rhsSignificand = rhs.significandParts();
1121 partsCount = partCount();
1122
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001123 if (partsCount > 2)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001124 dividend = new integerPart[partsCount * 2];
1125 else
1126 dividend = scratch;
1127
1128 divisor = dividend + partsCount;
1129
1130 /* Copy the dividend and divisor as they will be modified in-place. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001131 for (i = 0; i < partsCount; i++) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001132 dividend[i] = lhsSignificand[i];
1133 divisor[i] = rhsSignificand[i];
1134 lhsSignificand[i] = 0;
1135 }
1136
1137 exponent -= rhs.exponent;
1138
1139 unsigned int precision = semantics->precision;
1140
1141 /* Normalize the divisor. */
1142 bit = precision - APInt::tcMSB(divisor, partsCount) - 1;
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001143 if (bit) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001144 exponent += bit;
1145 APInt::tcShiftLeft(divisor, partsCount, bit);
1146 }
1147
1148 /* Normalize the dividend. */
1149 bit = precision - APInt::tcMSB(dividend, partsCount) - 1;
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001150 if (bit) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001151 exponent -= bit;
1152 APInt::tcShiftLeft(dividend, partsCount, bit);
1153 }
1154
Neil Boothb93d90e2007-10-12 16:02:31 +00001155 /* Ensure the dividend >= divisor initially for the loop below.
1156 Incidentally, this means that the division loop below is
1157 guaranteed to set the integer bit to one. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001158 if (APInt::tcCompare(dividend, divisor, partsCount) < 0) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001159 exponent--;
1160 APInt::tcShiftLeft(dividend, partsCount, 1);
1161 assert(APInt::tcCompare(dividend, divisor, partsCount) >= 0);
1162 }
1163
1164 /* Long division. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001165 for (bit = precision; bit; bit -= 1) {
1166 if (APInt::tcCompare(dividend, divisor, partsCount) >= 0) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001167 APInt::tcSubtract(dividend, divisor, 0, partsCount);
1168 APInt::tcSetBit(lhsSignificand, bit - 1);
1169 }
1170
1171 APInt::tcShiftLeft(dividend, partsCount, 1);
1172 }
1173
1174 /* Figure out the lost fraction. */
1175 int cmp = APInt::tcCompare(dividend, divisor, partsCount);
1176
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001177 if (cmp > 0)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001178 lost_fraction = lfMoreThanHalf;
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001179 else if (cmp == 0)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001180 lost_fraction = lfExactlyHalf;
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001181 else if (APInt::tcIsZero(dividend, partsCount))
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001182 lost_fraction = lfExactlyZero;
1183 else
1184 lost_fraction = lfLessThanHalf;
1185
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001186 if (partsCount > 2)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001187 delete [] dividend;
1188
1189 return lost_fraction;
1190}
1191
Tim Shen85de51d2016-10-25 19:55:59 +00001192unsigned int IEEEFloat::significandMSB() const {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001193 return APInt::tcMSB(significandParts(), partCount());
1194}
1195
Tim Shen85de51d2016-10-25 19:55:59 +00001196unsigned int IEEEFloat::significandLSB() const {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001197 return APInt::tcLSB(significandParts(), partCount());
1198}
1199
1200/* Note that a zero result is NOT normalized to fcZero. */
Tim Shen85de51d2016-10-25 19:55:59 +00001201lostFraction IEEEFloat::shiftSignificandRight(unsigned int bits) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001202 /* Our exponent should not overflow. */
Michael Gottesman9dc98332013-06-24 04:06:23 +00001203 assert((ExponentType) (exponent + bits) >= exponent);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001204
1205 exponent += bits;
1206
1207 return shiftRight(significandParts(), partCount(), bits);
1208}
1209
1210/* Shift the significand left BITS bits, subtract BITS from its exponent. */
Tim Shen85de51d2016-10-25 19:55:59 +00001211void IEEEFloat::shiftSignificandLeft(unsigned int bits) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001212 assert(bits < semantics->precision);
1213
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001214 if (bits) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001215 unsigned int partsCount = partCount();
1216
1217 APInt::tcShiftLeft(significandParts(), partsCount, bits);
1218 exponent -= bits;
1219
1220 assert(!APInt::tcIsZero(significandParts(), partsCount));
1221 }
1222}
1223
Tim Shen85de51d2016-10-25 19:55:59 +00001224IEEEFloat::cmpResult
1225IEEEFloat::compareAbsoluteValue(const IEEEFloat &rhs) const {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001226 int compare;
1227
1228 assert(semantics == rhs.semantics);
Michael Gottesman8136c382013-06-26 23:17:28 +00001229 assert(isFiniteNonZero());
1230 assert(rhs.isFiniteNonZero());
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001231
1232 compare = exponent - rhs.exponent;
1233
1234 /* If exponents are equal, do an unsigned bignum comparison of the
1235 significands. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001236 if (compare == 0)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001237 compare = APInt::tcCompare(significandParts(), rhs.significandParts(),
Neil Booth9acbf5a2007-09-26 21:33:42 +00001238 partCount());
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001239
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001240 if (compare > 0)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001241 return cmpGreaterThan;
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001242 else if (compare < 0)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001243 return cmpLessThan;
1244 else
1245 return cmpEqual;
1246}
1247
1248/* Handle overflow. Sign is preserved. We either become infinity or
1249 the largest finite number. */
Tim Shen85de51d2016-10-25 19:55:59 +00001250IEEEFloat::opStatus IEEEFloat::handleOverflow(roundingMode rounding_mode) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001251 /* Infinity? */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001252 if (rounding_mode == rmNearestTiesToEven ||
1253 rounding_mode == rmNearestTiesToAway ||
1254 (rounding_mode == rmTowardPositive && !sign) ||
1255 (rounding_mode == rmTowardNegative && sign)) {
1256 category = fcInfinity;
1257 return (opStatus) (opOverflow | opInexact);
1258 }
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001259
1260 /* Otherwise we become the largest finite number. */
1261 category = fcNormal;
1262 exponent = semantics->maxExponent;
1263 APInt::tcSetLeastSignificantBits(significandParts(), partCount(),
Neil Booth9acbf5a2007-09-26 21:33:42 +00001264 semantics->precision);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001265
1266 return opInexact;
1267}
1268
Neil Booth1ca1f802007-10-03 15:16:41 +00001269/* Returns TRUE if, when truncating the current number, with BIT the
1270 new LSB, with the given lost fraction and rounding mode, the result
1271 would need to be rounded away from zero (i.e., by increasing the
1272 signficand). This routine must work for fcZero of both signs, and
1273 fcNormal numbers. */
Tim Shen85de51d2016-10-25 19:55:59 +00001274bool IEEEFloat::roundAwayFromZero(roundingMode rounding_mode,
1275 lostFraction lost_fraction,
1276 unsigned int bit) const {
Dale Johannesen3cf889f2007-08-31 04:03:46 +00001277 /* NaNs and infinities should not have lost fractions. */
Michael Gottesman8136c382013-06-26 23:17:28 +00001278 assert(isFiniteNonZero() || category == fcZero);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001279
Neil Booth1ca1f802007-10-03 15:16:41 +00001280 /* Current callers never pass this so we don't handle it. */
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001281 assert(lost_fraction != lfExactlyZero);
1282
Mike Stump889285d2009-05-13 23:23:20 +00001283 switch (rounding_mode) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001284 case rmNearestTiesToAway:
1285 return lost_fraction == lfExactlyHalf || lost_fraction == lfMoreThanHalf;
1286
1287 case rmNearestTiesToEven:
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001288 if (lost_fraction == lfMoreThanHalf)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001289 return true;
1290
1291 /* Our zeroes don't have a significand to test. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001292 if (lost_fraction == lfExactlyHalf && category != fcZero)
Neil Booth1ca1f802007-10-03 15:16:41 +00001293 return APInt::tcExtractBit(significandParts(), bit);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001294
1295 return false;
1296
1297 case rmTowardZero:
1298 return false;
1299
1300 case rmTowardPositive:
David Blaikiedc3f01e2015-03-09 01:57:13 +00001301 return !sign;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001302
1303 case rmTowardNegative:
David Blaikiedc3f01e2015-03-09 01:57:13 +00001304 return sign;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001305 }
Chandler Carruthf3e85022012-01-10 18:08:01 +00001306 llvm_unreachable("Invalid rounding mode found");
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001307}
1308
Tim Shen85de51d2016-10-25 19:55:59 +00001309IEEEFloat::opStatus IEEEFloat::normalize(roundingMode rounding_mode,
1310 lostFraction lost_fraction) {
Neil Booth9acbf5a2007-09-26 21:33:42 +00001311 unsigned int omsb; /* One, not zero, based MSB. */
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001312 int exponentChange;
1313
Michael Gottesman8136c382013-06-26 23:17:28 +00001314 if (!isFiniteNonZero())
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001315 return opOK;
1316
1317 /* Before rounding normalize the exponent of fcNormal numbers. */
1318 omsb = significandMSB() + 1;
1319
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001320 if (omsb) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001321 /* OMSB is numbered from 1. We want to place it in the integer
Nick Lewyckyf66daac2011-10-03 21:30:08 +00001322 bit numbered PRECISION if possible, with a compensating change in
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001323 the exponent. */
1324 exponentChange = omsb - semantics->precision;
1325
1326 /* If the resulting exponent is too high, overflow according to
1327 the rounding mode. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001328 if (exponent + exponentChange > semantics->maxExponent)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001329 return handleOverflow(rounding_mode);
1330
1331 /* Subnormal numbers have exponent minExponent, and their MSB
1332 is forced based on that. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001333 if (exponent + exponentChange < semantics->minExponent)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001334 exponentChange = semantics->minExponent - exponent;
1335
1336 /* Shifting left is easy as we don't lose precision. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001337 if (exponentChange < 0) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001338 assert(lost_fraction == lfExactlyZero);
1339
1340 shiftSignificandLeft(-exponentChange);
1341
1342 return opOK;
1343 }
1344
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001345 if (exponentChange > 0) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001346 lostFraction lf;
1347
1348 /* Shift right and capture any new lost fraction. */
1349 lf = shiftSignificandRight(exponentChange);
1350
1351 lost_fraction = combineLostFractions(lf, lost_fraction);
1352
1353 /* Keep OMSB up-to-date. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001354 if (omsb > (unsigned) exponentChange)
Neil Boothb93d90e2007-10-12 16:02:31 +00001355 omsb -= exponentChange;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001356 else
Neil Booth9acbf5a2007-09-26 21:33:42 +00001357 omsb = 0;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001358 }
1359 }
1360
1361 /* Now round the number according to rounding_mode given the lost
1362 fraction. */
1363
1364 /* As specified in IEEE 754, since we do not trap we do not report
1365 underflow for exact results. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001366 if (lost_fraction == lfExactlyZero) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001367 /* Canonicalize zeroes. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001368 if (omsb == 0)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001369 category = fcZero;
1370
1371 return opOK;
1372 }
1373
1374 /* Increment the significand if we're rounding away from zero. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001375 if (roundAwayFromZero(rounding_mode, lost_fraction, 0)) {
1376 if (omsb == 0)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001377 exponent = semantics->minExponent;
1378
1379 incrementSignificand();
1380 omsb = significandMSB() + 1;
1381
1382 /* Did the significand increment overflow? */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001383 if (omsb == (unsigned) semantics->precision + 1) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001384 /* Renormalize by incrementing the exponent and shifting our
Neil Booth9acbf5a2007-09-26 21:33:42 +00001385 significand right one. However if we already have the
1386 maximum exponent we overflow to infinity. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001387 if (exponent == semantics->maxExponent) {
Neil Booth9acbf5a2007-09-26 21:33:42 +00001388 category = fcInfinity;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001389
Neil Booth9acbf5a2007-09-26 21:33:42 +00001390 return (opStatus) (opOverflow | opInexact);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001391 }
1392
1393 shiftSignificandRight(1);
1394
1395 return opInexact;
1396 }
1397 }
1398
1399 /* The normal case - we were and are not denormal, and any
1400 significand increment above didn't overflow. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001401 if (omsb == semantics->precision)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001402 return opInexact;
1403
1404 /* We have a non-zero denormal. */
1405 assert(omsb < semantics->precision);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001406
1407 /* Canonicalize zeroes. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001408 if (omsb == 0)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001409 category = fcZero;
1410
1411 /* The fcZero case is a denormal that underflowed to zero. */
1412 return (opStatus) (opUnderflow | opInexact);
1413}
1414
Tim Shen85de51d2016-10-25 19:55:59 +00001415IEEEFloat::opStatus IEEEFloat::addOrSubtractSpecials(const IEEEFloat &rhs,
1416 bool subtract) {
Michael Gottesman9b877e12013-06-24 09:57:57 +00001417 switch (PackCategoriesIntoKey(category, rhs.category)) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001418 default:
Craig Topper2617dcc2014-04-15 06:32:26 +00001419 llvm_unreachable(nullptr);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001420
Michael Gottesman9b877e12013-06-24 09:57:57 +00001421 case PackCategoriesIntoKey(fcNaN, fcZero):
1422 case PackCategoriesIntoKey(fcNaN, fcNormal):
1423 case PackCategoriesIntoKey(fcNaN, fcInfinity):
1424 case PackCategoriesIntoKey(fcNaN, fcNaN):
1425 case PackCategoriesIntoKey(fcNormal, fcZero):
1426 case PackCategoriesIntoKey(fcInfinity, fcNormal):
1427 case PackCategoriesIntoKey(fcInfinity, fcZero):
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001428 return opOK;
1429
Michael Gottesman9b877e12013-06-24 09:57:57 +00001430 case PackCategoriesIntoKey(fcZero, fcNaN):
1431 case PackCategoriesIntoKey(fcNormal, fcNaN):
1432 case PackCategoriesIntoKey(fcInfinity, fcNaN):
Stephen Canond3278282014-06-08 16:53:31 +00001433 // We need to be sure to flip the sign here for subtraction because we
1434 // don't have a separate negate operation so -NaN becomes 0 - NaN here.
1435 sign = rhs.sign ^ subtract;
Dale Johannesen3cf889f2007-08-31 04:03:46 +00001436 category = fcNaN;
1437 copySignificand(rhs);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001438 return opOK;
1439
Michael Gottesman9b877e12013-06-24 09:57:57 +00001440 case PackCategoriesIntoKey(fcNormal, fcInfinity):
1441 case PackCategoriesIntoKey(fcZero, fcInfinity):
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001442 category = fcInfinity;
1443 sign = rhs.sign ^ subtract;
1444 return opOK;
1445
Michael Gottesman9b877e12013-06-24 09:57:57 +00001446 case PackCategoriesIntoKey(fcZero, fcNormal):
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001447 assign(rhs);
1448 sign = rhs.sign ^ subtract;
1449 return opOK;
1450
Michael Gottesman9b877e12013-06-24 09:57:57 +00001451 case PackCategoriesIntoKey(fcZero, fcZero):
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001452 /* Sign depends on rounding mode; handled by caller. */
1453 return opOK;
1454
Michael Gottesman9b877e12013-06-24 09:57:57 +00001455 case PackCategoriesIntoKey(fcInfinity, fcInfinity):
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001456 /* Differently signed infinities can only be validly
1457 subtracted. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001458 if (((sign ^ rhs.sign)!=0) != subtract) {
Neil Booth5fe658b2007-10-14 10:39:51 +00001459 makeNaN();
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001460 return opInvalidOp;
1461 }
1462
1463 return opOK;
1464
Michael Gottesman9b877e12013-06-24 09:57:57 +00001465 case PackCategoriesIntoKey(fcNormal, fcNormal):
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001466 return opDivByZero;
1467 }
1468}
1469
1470/* Add or subtract two normal numbers. */
Tim Shen85de51d2016-10-25 19:55:59 +00001471lostFraction IEEEFloat::addOrSubtractSignificand(const IEEEFloat &rhs,
1472 bool subtract) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001473 integerPart carry;
1474 lostFraction lost_fraction;
1475 int bits;
1476
1477 /* Determine if the operation on the absolute values is effectively
1478 an addition or subtraction. */
Aaron Ballmand5cc45f2015-03-24 12:47:51 +00001479 subtract ^= static_cast<bool>(sign ^ rhs.sign);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001480
1481 /* Are we bigger exponent-wise than the RHS? */
1482 bits = exponent - rhs.exponent;
1483
1484 /* Subtraction is more subtle than one might naively expect. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001485 if (subtract) {
Tim Shen85de51d2016-10-25 19:55:59 +00001486 IEEEFloat temp_rhs(rhs);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001487 bool reverse;
1488
Chris Lattner3da18eb2007-08-24 03:02:34 +00001489 if (bits == 0) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001490 reverse = compareAbsoluteValue(temp_rhs) == cmpLessThan;
1491 lost_fraction = lfExactlyZero;
Chris Lattner3da18eb2007-08-24 03:02:34 +00001492 } else if (bits > 0) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001493 lost_fraction = temp_rhs.shiftSignificandRight(bits - 1);
1494 shiftSignificandLeft(1);
1495 reverse = false;
Chris Lattner3da18eb2007-08-24 03:02:34 +00001496 } else {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001497 lost_fraction = shiftSignificandRight(-bits - 1);
1498 temp_rhs.shiftSignificandLeft(1);
1499 reverse = true;
1500 }
1501
Chris Lattner3da18eb2007-08-24 03:02:34 +00001502 if (reverse) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001503 carry = temp_rhs.subtractSignificand
Neil Booth9acbf5a2007-09-26 21:33:42 +00001504 (*this, lost_fraction != lfExactlyZero);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001505 copySignificand(temp_rhs);
1506 sign = !sign;
1507 } else {
1508 carry = subtractSignificand
Neil Booth9acbf5a2007-09-26 21:33:42 +00001509 (temp_rhs, lost_fraction != lfExactlyZero);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001510 }
1511
1512 /* Invert the lost fraction - it was on the RHS and
1513 subtracted. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001514 if (lost_fraction == lfLessThanHalf)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001515 lost_fraction = lfMoreThanHalf;
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001516 else if (lost_fraction == lfMoreThanHalf)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001517 lost_fraction = lfLessThanHalf;
1518
1519 /* The code above is intended to ensure that no borrow is
1520 necessary. */
1521 assert(!carry);
Duncan Sandsa41634e2011-08-12 14:54:45 +00001522 (void)carry;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001523 } else {
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001524 if (bits > 0) {
Tim Shen85de51d2016-10-25 19:55:59 +00001525 IEEEFloat temp_rhs(rhs);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001526
1527 lost_fraction = temp_rhs.shiftSignificandRight(bits);
1528 carry = addSignificand(temp_rhs);
1529 } else {
1530 lost_fraction = shiftSignificandRight(-bits);
1531 carry = addSignificand(rhs);
1532 }
1533
1534 /* We have a guard bit; generating a carry cannot happen. */
1535 assert(!carry);
Duncan Sandsa41634e2011-08-12 14:54:45 +00001536 (void)carry;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001537 }
1538
1539 return lost_fraction;
1540}
1541
Tim Shen85de51d2016-10-25 19:55:59 +00001542IEEEFloat::opStatus IEEEFloat::multiplySpecials(const IEEEFloat &rhs) {
Michael Gottesman9b877e12013-06-24 09:57:57 +00001543 switch (PackCategoriesIntoKey(category, rhs.category)) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001544 default:
Craig Topper2617dcc2014-04-15 06:32:26 +00001545 llvm_unreachable(nullptr);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001546
Michael Gottesman9b877e12013-06-24 09:57:57 +00001547 case PackCategoriesIntoKey(fcNaN, fcZero):
1548 case PackCategoriesIntoKey(fcNaN, fcNormal):
1549 case PackCategoriesIntoKey(fcNaN, fcInfinity):
1550 case PackCategoriesIntoKey(fcNaN, fcNaN):
Michael Gottesmanb0e688e2013-07-27 21:49:25 +00001551 sign = false;
Dale Johannesen3cf889f2007-08-31 04:03:46 +00001552 return opOK;
1553
Michael Gottesman9b877e12013-06-24 09:57:57 +00001554 case PackCategoriesIntoKey(fcZero, fcNaN):
1555 case PackCategoriesIntoKey(fcNormal, fcNaN):
1556 case PackCategoriesIntoKey(fcInfinity, fcNaN):
Michael Gottesmanb0e688e2013-07-27 21:49:25 +00001557 sign = false;
Dale Johannesen3cf889f2007-08-31 04:03:46 +00001558 category = fcNaN;
1559 copySignificand(rhs);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001560 return opOK;
1561
Michael Gottesman9b877e12013-06-24 09:57:57 +00001562 case PackCategoriesIntoKey(fcNormal, fcInfinity):
1563 case PackCategoriesIntoKey(fcInfinity, fcNormal):
1564 case PackCategoriesIntoKey(fcInfinity, fcInfinity):
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001565 category = fcInfinity;
1566 return opOK;
1567
Michael Gottesman9b877e12013-06-24 09:57:57 +00001568 case PackCategoriesIntoKey(fcZero, fcNormal):
1569 case PackCategoriesIntoKey(fcNormal, fcZero):
1570 case PackCategoriesIntoKey(fcZero, fcZero):
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001571 category = fcZero;
1572 return opOK;
1573
Michael Gottesman9b877e12013-06-24 09:57:57 +00001574 case PackCategoriesIntoKey(fcZero, fcInfinity):
1575 case PackCategoriesIntoKey(fcInfinity, fcZero):
Neil Booth5fe658b2007-10-14 10:39:51 +00001576 makeNaN();
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001577 return opInvalidOp;
1578
Michael Gottesman9b877e12013-06-24 09:57:57 +00001579 case PackCategoriesIntoKey(fcNormal, fcNormal):
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001580 return opOK;
1581 }
1582}
1583
Tim Shen85de51d2016-10-25 19:55:59 +00001584IEEEFloat::opStatus IEEEFloat::divideSpecials(const IEEEFloat &rhs) {
Michael Gottesman9b877e12013-06-24 09:57:57 +00001585 switch (PackCategoriesIntoKey(category, rhs.category)) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001586 default:
Craig Topper2617dcc2014-04-15 06:32:26 +00001587 llvm_unreachable(nullptr);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001588
Michael Gottesman9b877e12013-06-24 09:57:57 +00001589 case PackCategoriesIntoKey(fcZero, fcNaN):
1590 case PackCategoriesIntoKey(fcNormal, fcNaN):
1591 case PackCategoriesIntoKey(fcInfinity, fcNaN):
Dale Johannesen3cf889f2007-08-31 04:03:46 +00001592 category = fcNaN;
1593 copySignificand(rhs);
Galina Kistanova5c4f1a92017-05-30 03:30:34 +00001594 LLVM_FALLTHROUGH;
Michael Gottesmanb0e688e2013-07-27 21:49:25 +00001595 case PackCategoriesIntoKey(fcNaN, fcZero):
1596 case PackCategoriesIntoKey(fcNaN, fcNormal):
1597 case PackCategoriesIntoKey(fcNaN, fcInfinity):
1598 case PackCategoriesIntoKey(fcNaN, fcNaN):
1599 sign = false;
Galina Kistanova5c4f1a92017-05-30 03:30:34 +00001600 LLVM_FALLTHROUGH;
Michael Gottesmanb0e688e2013-07-27 21:49:25 +00001601 case PackCategoriesIntoKey(fcInfinity, fcZero):
1602 case PackCategoriesIntoKey(fcInfinity, fcNormal):
1603 case PackCategoriesIntoKey(fcZero, fcInfinity):
1604 case PackCategoriesIntoKey(fcZero, fcNormal):
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001605 return opOK;
1606
Michael Gottesman9b877e12013-06-24 09:57:57 +00001607 case PackCategoriesIntoKey(fcNormal, fcInfinity):
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001608 category = fcZero;
1609 return opOK;
1610
Michael Gottesman9b877e12013-06-24 09:57:57 +00001611 case PackCategoriesIntoKey(fcNormal, fcZero):
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001612 category = fcInfinity;
1613 return opDivByZero;
1614
Michael Gottesman9b877e12013-06-24 09:57:57 +00001615 case PackCategoriesIntoKey(fcInfinity, fcInfinity):
1616 case PackCategoriesIntoKey(fcZero, fcZero):
Neil Booth5fe658b2007-10-14 10:39:51 +00001617 makeNaN();
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001618 return opInvalidOp;
1619
Michael Gottesman9b877e12013-06-24 09:57:57 +00001620 case PackCategoriesIntoKey(fcNormal, fcNormal):
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001621 return opOK;
1622 }
1623}
1624
Tim Shen85de51d2016-10-25 19:55:59 +00001625IEEEFloat::opStatus IEEEFloat::modSpecials(const IEEEFloat &rhs) {
Michael Gottesman9b877e12013-06-24 09:57:57 +00001626 switch (PackCategoriesIntoKey(category, rhs.category)) {
Dale Johannesenb5721632009-01-21 00:35:19 +00001627 default:
Craig Topper2617dcc2014-04-15 06:32:26 +00001628 llvm_unreachable(nullptr);
Dale Johannesenb5721632009-01-21 00:35:19 +00001629
Michael Gottesman9b877e12013-06-24 09:57:57 +00001630 case PackCategoriesIntoKey(fcNaN, fcZero):
1631 case PackCategoriesIntoKey(fcNaN, fcNormal):
1632 case PackCategoriesIntoKey(fcNaN, fcInfinity):
1633 case PackCategoriesIntoKey(fcNaN, fcNaN):
1634 case PackCategoriesIntoKey(fcZero, fcInfinity):
1635 case PackCategoriesIntoKey(fcZero, fcNormal):
1636 case PackCategoriesIntoKey(fcNormal, fcInfinity):
Dale Johannesenb5721632009-01-21 00:35:19 +00001637 return opOK;
1638
Michael Gottesman9b877e12013-06-24 09:57:57 +00001639 case PackCategoriesIntoKey(fcZero, fcNaN):
1640 case PackCategoriesIntoKey(fcNormal, fcNaN):
1641 case PackCategoriesIntoKey(fcInfinity, fcNaN):
Michael Gottesmanb0e688e2013-07-27 21:49:25 +00001642 sign = false;
Dale Johannesenb5721632009-01-21 00:35:19 +00001643 category = fcNaN;
1644 copySignificand(rhs);
1645 return opOK;
1646
Michael Gottesman9b877e12013-06-24 09:57:57 +00001647 case PackCategoriesIntoKey(fcNormal, fcZero):
1648 case PackCategoriesIntoKey(fcInfinity, fcZero):
1649 case PackCategoriesIntoKey(fcInfinity, fcNormal):
1650 case PackCategoriesIntoKey(fcInfinity, fcInfinity):
1651 case PackCategoriesIntoKey(fcZero, fcZero):
Dale Johannesenb5721632009-01-21 00:35:19 +00001652 makeNaN();
1653 return opInvalidOp;
1654
Michael Gottesman9b877e12013-06-24 09:57:57 +00001655 case PackCategoriesIntoKey(fcNormal, fcNormal):
Dale Johannesenb5721632009-01-21 00:35:19 +00001656 return opOK;
1657 }
1658}
1659
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001660/* Change sign. */
Tim Shen85de51d2016-10-25 19:55:59 +00001661void IEEEFloat::changeSign() {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001662 /* Look mummy, this one's easy. */
1663 sign = !sign;
1664}
1665
1666/* Normalized addition or subtraction. */
Tim Shen85de51d2016-10-25 19:55:59 +00001667IEEEFloat::opStatus IEEEFloat::addOrSubtract(const IEEEFloat &rhs,
1668 roundingMode rounding_mode,
1669 bool subtract) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001670 opStatus fs;
1671
1672 fs = addOrSubtractSpecials(rhs, subtract);
1673
1674 /* This return code means it was not a simple case. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001675 if (fs == opDivByZero) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001676 lostFraction lost_fraction;
1677
1678 lost_fraction = addOrSubtractSignificand(rhs, subtract);
1679 fs = normalize(rounding_mode, lost_fraction);
1680
1681 /* Can only be zero if we lost no fraction. */
1682 assert(category != fcZero || lost_fraction == lfExactlyZero);
1683 }
1684
1685 /* If two numbers add (exactly) to zero, IEEE 754 decrees it is a
1686 positive zero unless rounding to minus infinity, except that
1687 adding two like-signed zeroes gives that zero. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001688 if (category == fcZero) {
1689 if (rhs.category != fcZero || (sign == rhs.sign) == subtract)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001690 sign = (rounding_mode == rmTowardNegative);
1691 }
1692
1693 return fs;
1694}
1695
1696/* Normalized addition. */
Tim Shen85de51d2016-10-25 19:55:59 +00001697IEEEFloat::opStatus IEEEFloat::add(const IEEEFloat &rhs,
1698 roundingMode rounding_mode) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001699 return addOrSubtract(rhs, rounding_mode, false);
1700}
1701
1702/* Normalized subtraction. */
Tim Shen85de51d2016-10-25 19:55:59 +00001703IEEEFloat::opStatus IEEEFloat::subtract(const IEEEFloat &rhs,
1704 roundingMode rounding_mode) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001705 return addOrSubtract(rhs, rounding_mode, true);
1706}
1707
1708/* Normalized multiply. */
Tim Shen85de51d2016-10-25 19:55:59 +00001709IEEEFloat::opStatus IEEEFloat::multiply(const IEEEFloat &rhs,
1710 roundingMode rounding_mode) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001711 opStatus fs;
1712
1713 sign ^= rhs.sign;
1714 fs = multiplySpecials(rhs);
1715
Michael Gottesman8136c382013-06-26 23:17:28 +00001716 if (isFiniteNonZero()) {
Craig Topperc10719f2014-04-07 04:17:22 +00001717 lostFraction lost_fraction = multiplySignificand(rhs, nullptr);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001718 fs = normalize(rounding_mode, lost_fraction);
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001719 if (lost_fraction != lfExactlyZero)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001720 fs = (opStatus) (fs | opInexact);
1721 }
1722
1723 return fs;
1724}
1725
1726/* Normalized divide. */
Tim Shen85de51d2016-10-25 19:55:59 +00001727IEEEFloat::opStatus IEEEFloat::divide(const IEEEFloat &rhs,
1728 roundingMode rounding_mode) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001729 opStatus fs;
1730
1731 sign ^= rhs.sign;
1732 fs = divideSpecials(rhs);
1733
Michael Gottesman8136c382013-06-26 23:17:28 +00001734 if (isFiniteNonZero()) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001735 lostFraction lost_fraction = divideSignificand(rhs);
1736 fs = normalize(rounding_mode, lost_fraction);
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001737 if (lost_fraction != lfExactlyZero)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001738 fs = (opStatus) (fs | opInexact);
1739 }
1740
1741 return fs;
1742}
1743
Dale Johannesenfe750172009-01-20 18:35:05 +00001744/* Normalized remainder. This is not currently correct in all cases. */
Tim Shen85de51d2016-10-25 19:55:59 +00001745IEEEFloat::opStatus IEEEFloat::remainder(const IEEEFloat &rhs) {
Dale Johannesenfe750172009-01-20 18:35:05 +00001746 opStatus fs;
Tim Shen85de51d2016-10-25 19:55:59 +00001747 IEEEFloat V = *this;
Dale Johannesenfe750172009-01-20 18:35:05 +00001748 unsigned int origSign = sign;
1749
Dale Johannesenfe750172009-01-20 18:35:05 +00001750 fs = V.divide(rhs, rmNearestTiesToEven);
1751 if (fs == opDivByZero)
1752 return fs;
1753
1754 int parts = partCount();
Dylan Noblesmith4e69e292014-08-26 02:03:33 +00001755 integerPart *x = new integerPart[parts];
Dale Johannesenfe750172009-01-20 18:35:05 +00001756 bool ignored;
Simon Pilgrim00b34992017-03-20 14:40:12 +00001757 fs = V.convertToInteger(makeMutableArrayRef(x, parts),
1758 parts * integerPartWidth, true, rmNearestTiesToEven,
1759 &ignored);
1760 if (fs == opInvalidOp) {
Sylvestre Ledru3ce346d2016-11-08 10:00:45 +00001761 delete[] x;
Dale Johannesenfe750172009-01-20 18:35:05 +00001762 return fs;
Sylvestre Ledru3ce346d2016-11-08 10:00:45 +00001763 }
Dale Johannesenfe750172009-01-20 18:35:05 +00001764
1765 fs = V.convertFromZeroExtendedInteger(x, parts * integerPartWidth, true,
1766 rmNearestTiesToEven);
1767 assert(fs==opOK); // should always work
1768
1769 fs = V.multiply(rhs, rmNearestTiesToEven);
1770 assert(fs==opOK || fs==opInexact); // should not overflow or underflow
1771
1772 fs = subtract(V, rmNearestTiesToEven);
1773 assert(fs==opOK || fs==opInexact); // likewise
1774
1775 if (isZero())
1776 sign = origSign; // IEEE754 requires this
Dylan Noblesmith4e69e292014-08-26 02:03:33 +00001777 delete[] x;
Dale Johannesenfe750172009-01-20 18:35:05 +00001778 return fs;
1779}
1780
Stephen Canon157c8692017-03-31 20:31:33 +00001781/* Normalized llvm frem (C fmod). */
Tim Shen85de51d2016-10-25 19:55:59 +00001782IEEEFloat::opStatus IEEEFloat::mod(const IEEEFloat &rhs) {
Dale Johannesen689d17d2007-08-31 23:35:31 +00001783 opStatus fs;
Dale Johannesenb5721632009-01-21 00:35:19 +00001784 fs = modSpecials(rhs);
Serguei Katkovf2c28512017-11-01 07:56:55 +00001785 unsigned int origSign = sign;
Dale Johannesen689d17d2007-08-31 23:35:31 +00001786
Stephen Canon157c8692017-03-31 20:31:33 +00001787 while (isFiniteNonZero() && rhs.isFiniteNonZero() &&
1788 compareAbsoluteValue(rhs) != cmpLessThan) {
1789 IEEEFloat V = scalbn(rhs, ilogb(*this) - ilogb(rhs), rmNearestTiesToEven);
1790 if (compareAbsoluteValue(V) == cmpLessThan)
1791 V = scalbn(V, -1, rmNearestTiesToEven);
1792 V.sign = sign;
Fangrui Songf78650a2018-07-30 19:41:25 +00001793
Stephen Canonb12db0e2015-09-21 19:29:25 +00001794 fs = subtract(V, rmNearestTiesToEven);
Stephen Canon157c8692017-03-31 20:31:33 +00001795 assert(fs==opOK);
Dale Johannesenb5721632009-01-21 00:35:19 +00001796 }
Serguei Katkovf2c28512017-11-01 07:56:55 +00001797 if (isZero())
1798 sign = origSign; // fmod requires this
Dale Johannesen689d17d2007-08-31 23:35:31 +00001799 return fs;
1800}
1801
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001802/* Normalized fused-multiply-add. */
Tim Shen85de51d2016-10-25 19:55:59 +00001803IEEEFloat::opStatus IEEEFloat::fusedMultiplyAdd(const IEEEFloat &multiplicand,
1804 const IEEEFloat &addend,
1805 roundingMode rounding_mode) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001806 opStatus fs;
1807
1808 /* Post-multiplication sign, before addition. */
1809 sign ^= multiplicand.sign;
1810
1811 /* If and only if all arguments are normal do we need to do an
1812 extended-precision calculation. */
Michael Gottesman8136c382013-06-26 23:17:28 +00001813 if (isFiniteNonZero() &&
1814 multiplicand.isFiniteNonZero() &&
Hal Finkel171c2ec2014-10-14 19:23:07 +00001815 addend.isFinite()) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001816 lostFraction lost_fraction;
1817
1818 lost_fraction = multiplySignificand(multiplicand, &addend);
1819 fs = normalize(rounding_mode, lost_fraction);
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001820 if (lost_fraction != lfExactlyZero)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001821 fs = (opStatus) (fs | opInexact);
1822
1823 /* If two numbers add (exactly) to zero, IEEE 754 decrees it is a
1824 positive zero unless rounding to minus infinity, except that
1825 adding two like-signed zeroes gives that zero. */
Lang Hames12b12e82015-01-04 01:20:55 +00001826 if (category == fcZero && !(fs & opUnderflow) && sign != addend.sign)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001827 sign = (rounding_mode == rmTowardNegative);
1828 } else {
1829 fs = multiplySpecials(multiplicand);
1830
1831 /* FS can only be opOK or opInvalidOp. There is no more work
1832 to do in the latter case. The IEEE-754R standard says it is
1833 implementation-defined in this case whether, if ADDEND is a
Dale Johannesen3cf889f2007-08-31 04:03:46 +00001834 quiet NaN, we raise invalid op; this implementation does so.
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001835
1836 If we need to do the addition we can do so with normal
1837 precision. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001838 if (fs == opOK)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001839 fs = addOrSubtract(addend, rounding_mode, false);
1840 }
1841
1842 return fs;
1843}
1844
Owen Andersona40319b2012-08-13 23:32:49 +00001845/* Rounding-mode corrrect round to integral value. */
Tim Shen85de51d2016-10-25 19:55:59 +00001846IEEEFloat::opStatus IEEEFloat::roundToIntegral(roundingMode rounding_mode) {
Owen Andersona40319b2012-08-13 23:32:49 +00001847 opStatus fs;
Owen Andersona40319b2012-08-13 23:32:49 +00001848
Owen Anderson352dfff2012-08-15 18:28:45 +00001849 // If the exponent is large enough, we know that this value is already
1850 // integral, and the arithmetic below would potentially cause it to saturate
1851 // to +/-Inf. Bail out early instead.
Michael Gottesman8136c382013-06-26 23:17:28 +00001852 if (isFiniteNonZero() && exponent+1 >= (int)semanticsPrecision(*semantics))
Owen Anderson352dfff2012-08-15 18:28:45 +00001853 return opOK;
1854
Owen Andersona40319b2012-08-13 23:32:49 +00001855 // The algorithm here is quite simple: we add 2^(p-1), where p is the
1856 // precision of our format, and then subtract it back off again. The choice
1857 // of rounding modes for the addition/subtraction determines the rounding mode
1858 // for our integral rounding as well.
Owen Andersonbe7e2972012-08-15 16:42:53 +00001859 // NOTE: When the input value is negative, we do subtraction followed by
Owen Anderson1ff74b02012-08-15 05:39:46 +00001860 // addition instead.
Owen Anderson0b357222012-08-14 18:51:15 +00001861 APInt IntegerConstant(NextPowerOf2(semanticsPrecision(*semantics)), 1);
1862 IntegerConstant <<= semanticsPrecision(*semantics)-1;
Tim Shen85de51d2016-10-25 19:55:59 +00001863 IEEEFloat MagicConstant(*semantics);
Owen Andersona40319b2012-08-13 23:32:49 +00001864 fs = MagicConstant.convertFromAPInt(IntegerConstant, false,
1865 rmNearestTiesToEven);
Tim Shenfd1e5aa2017-01-23 22:39:35 +00001866 MagicConstant.sign = sign;
Owen Anderson1ff74b02012-08-15 05:39:46 +00001867
Owen Andersona40319b2012-08-13 23:32:49 +00001868 if (fs != opOK)
1869 return fs;
1870
Owen Anderson1ff74b02012-08-15 05:39:46 +00001871 // Preserve the input sign so that we can handle 0.0/-0.0 cases correctly.
1872 bool inputSign = isNegative();
1873
Owen Andersona40319b2012-08-13 23:32:49 +00001874 fs = add(MagicConstant, rounding_mode);
1875 if (fs != opOK && fs != opInexact)
1876 return fs;
1877
1878 fs = subtract(MagicConstant, rounding_mode);
Owen Anderson1ff74b02012-08-15 05:39:46 +00001879
1880 // Restore the input sign.
1881 if (inputSign != isNegative())
1882 changeSign();
1883
Owen Andersona40319b2012-08-13 23:32:49 +00001884 return fs;
1885}
1886
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +00001887
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001888/* Comparison requires normalized numbers. */
Tim Shen85de51d2016-10-25 19:55:59 +00001889IEEEFloat::cmpResult IEEEFloat::compare(const IEEEFloat &rhs) const {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001890 cmpResult result;
1891
1892 assert(semantics == rhs.semantics);
1893
Michael Gottesman9b877e12013-06-24 09:57:57 +00001894 switch (PackCategoriesIntoKey(category, rhs.category)) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001895 default:
Craig Topper2617dcc2014-04-15 06:32:26 +00001896 llvm_unreachable(nullptr);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001897
Michael Gottesman9b877e12013-06-24 09:57:57 +00001898 case PackCategoriesIntoKey(fcNaN, fcZero):
1899 case PackCategoriesIntoKey(fcNaN, fcNormal):
1900 case PackCategoriesIntoKey(fcNaN, fcInfinity):
1901 case PackCategoriesIntoKey(fcNaN, fcNaN):
1902 case PackCategoriesIntoKey(fcZero, fcNaN):
1903 case PackCategoriesIntoKey(fcNormal, fcNaN):
1904 case PackCategoriesIntoKey(fcInfinity, fcNaN):
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001905 return cmpUnordered;
1906
Michael Gottesman9b877e12013-06-24 09:57:57 +00001907 case PackCategoriesIntoKey(fcInfinity, fcNormal):
1908 case PackCategoriesIntoKey(fcInfinity, fcZero):
1909 case PackCategoriesIntoKey(fcNormal, fcZero):
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001910 if (sign)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001911 return cmpLessThan;
1912 else
1913 return cmpGreaterThan;
1914
Michael Gottesman9b877e12013-06-24 09:57:57 +00001915 case PackCategoriesIntoKey(fcNormal, fcInfinity):
1916 case PackCategoriesIntoKey(fcZero, fcInfinity):
1917 case PackCategoriesIntoKey(fcZero, fcNormal):
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001918 if (rhs.sign)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001919 return cmpGreaterThan;
1920 else
1921 return cmpLessThan;
1922
Michael Gottesman9b877e12013-06-24 09:57:57 +00001923 case PackCategoriesIntoKey(fcInfinity, fcInfinity):
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001924 if (sign == rhs.sign)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001925 return cmpEqual;
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001926 else if (sign)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001927 return cmpLessThan;
1928 else
1929 return cmpGreaterThan;
1930
Michael Gottesman9b877e12013-06-24 09:57:57 +00001931 case PackCategoriesIntoKey(fcZero, fcZero):
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001932 return cmpEqual;
1933
Michael Gottesman9b877e12013-06-24 09:57:57 +00001934 case PackCategoriesIntoKey(fcNormal, fcNormal):
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001935 break;
1936 }
1937
1938 /* Two normal numbers. Do they have the same sign? */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001939 if (sign != rhs.sign) {
1940 if (sign)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001941 result = cmpLessThan;
1942 else
1943 result = cmpGreaterThan;
1944 } else {
1945 /* Compare absolute values; invert result if negative. */
1946 result = compareAbsoluteValue(rhs);
1947
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001948 if (sign) {
1949 if (result == cmpLessThan)
Neil Booth9acbf5a2007-09-26 21:33:42 +00001950 result = cmpGreaterThan;
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001951 else if (result == cmpGreaterThan)
Neil Booth9acbf5a2007-09-26 21:33:42 +00001952 result = cmpLessThan;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001953 }
1954 }
1955
1956 return result;
1957}
1958
Tim Shen85de51d2016-10-25 19:55:59 +00001959/// IEEEFloat::convert - convert a value of one floating point type to another.
Dale Johannesen4f0bd682008-10-09 23:00:39 +00001960/// The return value corresponds to the IEEE754 exceptions. *losesInfo
1961/// records whether the transformation lost information, i.e. whether
1962/// converting the result back to the original type will produce the
1963/// original value (this is almost the same as return value==fsOK, but there
1964/// are edge cases where this is not so).
1965
Tim Shen85de51d2016-10-25 19:55:59 +00001966IEEEFloat::opStatus IEEEFloat::convert(const fltSemantics &toSemantics,
1967 roundingMode rounding_mode,
1968 bool *losesInfo) {
Neil Bootha8d72692007-09-22 02:56:19 +00001969 lostFraction lostFraction;
1970 unsigned int newPartCount, oldPartCount;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001971 opStatus fs;
Eli Friedmana84ad7d2011-11-26 03:38:02 +00001972 int shift;
1973 const fltSemantics &fromSemantics = *semantics;
Neil Booth9acbf5a2007-09-26 21:33:42 +00001974
Neil Bootha8d72692007-09-22 02:56:19 +00001975 lostFraction = lfExactlyZero;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001976 newPartCount = partCountForBits(toSemantics.precision + 1);
Neil Bootha8d72692007-09-22 02:56:19 +00001977 oldPartCount = partCount();
Eli Friedmana84ad7d2011-11-26 03:38:02 +00001978 shift = toSemantics.precision - fromSemantics.precision;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001979
Eli Friedmana84ad7d2011-11-26 03:38:02 +00001980 bool X86SpecialNan = false;
Stephan Bergmann17c7f702016-12-14 11:57:17 +00001981 if (&fromSemantics == &semX87DoubleExtended &&
1982 &toSemantics != &semX87DoubleExtended && category == fcNaN &&
Eli Friedmana84ad7d2011-11-26 03:38:02 +00001983 (!(*significandParts() & 0x8000000000000000ULL) ||
1984 !(*significandParts() & 0x4000000000000000ULL))) {
1985 // x86 has some unusual NaNs which cannot be represented in any other
1986 // format; note them here.
1987 X86SpecialNan = true;
1988 }
1989
Ulrich Weigand1d4dbda2013-07-16 13:03:25 +00001990 // If this is a truncation of a denormal number, and the target semantics
1991 // has larger exponent range than the source semantics (this can happen
1992 // when truncating from PowerPC double-double to double format), the
1993 // right shift could lose result mantissa bits. Adjust exponent instead
1994 // of performing excessive shift.
1995 if (shift < 0 && isFiniteNonZero()) {
1996 int exponentChange = significandMSB() + 1 - fromSemantics.precision;
1997 if (exponent + exponentChange < toSemantics.minExponent)
1998 exponentChange = toSemantics.minExponent - exponent;
1999 if (exponentChange < shift)
2000 exponentChange = shift;
2001 if (exponentChange < 0) {
2002 shift -= exponentChange;
2003 exponent += exponentChange;
2004 }
2005 }
2006
Eli Friedmana84ad7d2011-11-26 03:38:02 +00002007 // If this is a truncation, perform the shift before we narrow the storage.
Michael Gottesman8136c382013-06-26 23:17:28 +00002008 if (shift < 0 && (isFiniteNonZero() || category==fcNaN))
Eli Friedmana84ad7d2011-11-26 03:38:02 +00002009 lostFraction = shiftRight(significandParts(), oldPartCount, -shift);
2010
2011 // Fix the storage so it can hold to new value.
Neil Bootha8d72692007-09-22 02:56:19 +00002012 if (newPartCount > oldPartCount) {
Eli Friedmana84ad7d2011-11-26 03:38:02 +00002013 // The new type requires more storage; make it available.
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002014 integerPart *newParts;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002015 newParts = new integerPart[newPartCount];
2016 APInt::tcSet(newParts, 0, newPartCount);
Michael Gottesman8136c382013-06-26 23:17:28 +00002017 if (isFiniteNonZero() || category==fcNaN)
Dale Johannesen4f55d9f2007-09-25 17:25:00 +00002018 APInt::tcAssign(newParts, significandParts(), oldPartCount);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002019 freeSignificand();
2020 significand.parts = newParts;
Eli Friedmana84ad7d2011-11-26 03:38:02 +00002021 } else if (newPartCount == 1 && oldPartCount != 1) {
2022 // Switch to built-in storage for a single part.
2023 integerPart newPart = 0;
Michael Gottesman8136c382013-06-26 23:17:28 +00002024 if (isFiniteNonZero() || category==fcNaN)
Eli Friedmana84ad7d2011-11-26 03:38:02 +00002025 newPart = significandParts()[0];
2026 freeSignificand();
2027 significand.part = newPart;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002028 }
2029
Eli Friedmana84ad7d2011-11-26 03:38:02 +00002030 // Now that we have the right storage, switch the semantics.
2031 semantics = &toSemantics;
2032
2033 // If this is an extension, perform the shift now that the storage is
2034 // available.
Michael Gottesman8136c382013-06-26 23:17:28 +00002035 if (shift > 0 && (isFiniteNonZero() || category==fcNaN))
Eli Friedmana84ad7d2011-11-26 03:38:02 +00002036 APInt::tcShiftLeft(significandParts(), newPartCount, shift);
2037
Michael Gottesman8136c382013-06-26 23:17:28 +00002038 if (isFiniteNonZero()) {
Neil Bootha8d72692007-09-22 02:56:19 +00002039 fs = normalize(rounding_mode, lostFraction);
Dale Johannesen4f0bd682008-10-09 23:00:39 +00002040 *losesInfo = (fs != opOK);
Dale Johannesen4f55d9f2007-09-25 17:25:00 +00002041 } else if (category == fcNaN) {
Eli Friedmana84ad7d2011-11-26 03:38:02 +00002042 *losesInfo = lostFraction != lfExactlyZero || X86SpecialNan;
Benjamin Kramerb361adb2013-01-25 17:01:00 +00002043
2044 // For x87 extended precision, we want to make a NaN, not a special NaN if
2045 // the input wasn't special either.
Stephan Bergmann17c7f702016-12-14 11:57:17 +00002046 if (!X86SpecialNan && semantics == &semX87DoubleExtended)
Benjamin Kramerb361adb2013-01-25 17:01:00 +00002047 APInt::tcSetBit(significandParts(), semantics->precision - 1);
2048
Dale Johannesen4f55d9f2007-09-25 17:25:00 +00002049 // gcc forces the Quiet bit on, which means (float)(double)(float_sNan)
2050 // does not give you back the same bits. This is dubious, and we
2051 // don't currently do it. You're really supposed to get
2052 // an invalid operation signal at runtime, but nobody does that.
Dale Johannesen4f0bd682008-10-09 23:00:39 +00002053 fs = opOK;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002054 } else {
Dale Johannesen4f0bd682008-10-09 23:00:39 +00002055 *losesInfo = false;
Eli Friedman31f01162011-11-28 18:50:37 +00002056 fs = opOK;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002057 }
2058
2059 return fs;
2060}
2061
2062/* Convert a floating point number to an integer according to the
2063 rounding mode. If the rounded integer value is out of range this
Neil Booth618d0fc2007-11-01 22:43:37 +00002064 returns an invalid operation exception and the contents of the
2065 destination parts are unspecified. If the rounded value is in
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002066 range but the floating point number is not the exact integer, the C
2067 standard doesn't require an inexact exception to be raised. IEEE
2068 854 does require it so we do that.
2069
2070 Note that for conversions to integer type the C standard requires
2071 round-to-zero to always be used. */
Tim Shen85de51d2016-10-25 19:55:59 +00002072IEEEFloat::opStatus IEEEFloat::convertToSignExtendedInteger(
Simon Pilgrim00b34992017-03-20 14:40:12 +00002073 MutableArrayRef<integerPart> parts, unsigned int width, bool isSigned,
Tim Shen85de51d2016-10-25 19:55:59 +00002074 roundingMode rounding_mode, bool *isExact) const {
Neil Booth618d0fc2007-11-01 22:43:37 +00002075 lostFraction lost_fraction;
2076 const integerPart *src;
2077 unsigned int dstPartsCount, truncatedBits;
2078
Dale Johannesen4f0bd682008-10-09 23:00:39 +00002079 *isExact = false;
2080
Neil Booth618d0fc2007-11-01 22:43:37 +00002081 /* Handle the three special cases first. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002082 if (category == fcInfinity || category == fcNaN)
Neil Booth618d0fc2007-11-01 22:43:37 +00002083 return opInvalidOp;
2084
2085 dstPartsCount = partCountForBits(width);
Simon Pilgrim00b34992017-03-20 14:40:12 +00002086 assert(dstPartsCount <= parts.size() && "Integer too big");
Neil Booth618d0fc2007-11-01 22:43:37 +00002087
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002088 if (category == fcZero) {
Simon Pilgrim00b34992017-03-20 14:40:12 +00002089 APInt::tcSet(parts.data(), 0, dstPartsCount);
Dale Johannesen7221af32008-10-07 00:40:01 +00002090 // Negative zero can't be represented as an int.
Dale Johannesen4f0bd682008-10-09 23:00:39 +00002091 *isExact = !sign;
2092 return opOK;
Neil Booth618d0fc2007-11-01 22:43:37 +00002093 }
2094
2095 src = significandParts();
2096
2097 /* Step 1: place our absolute value, with any fraction truncated, in
2098 the destination. */
2099 if (exponent < 0) {
2100 /* Our absolute value is less than one; truncate everything. */
Simon Pilgrim00b34992017-03-20 14:40:12 +00002101 APInt::tcSet(parts.data(), 0, dstPartsCount);
Dale Johannesen740e9872009-01-19 21:17:05 +00002102 /* For exponent -1 the integer bit represents .5, look at that.
2103 For smaller exponents leftmost truncated bit is 0. */
2104 truncatedBits = semantics->precision -1U - exponent;
Neil Booth618d0fc2007-11-01 22:43:37 +00002105 } else {
2106 /* We want the most significant (exponent + 1) bits; the rest are
2107 truncated. */
2108 unsigned int bits = exponent + 1U;
2109
2110 /* Hopelessly large in magnitude? */
2111 if (bits > width)
2112 return opInvalidOp;
2113
2114 if (bits < semantics->precision) {
2115 /* We truncate (semantics->precision - bits) bits. */
2116 truncatedBits = semantics->precision - bits;
Simon Pilgrim00b34992017-03-20 14:40:12 +00002117 APInt::tcExtract(parts.data(), dstPartsCount, src, bits, truncatedBits);
Neil Booth618d0fc2007-11-01 22:43:37 +00002118 } else {
2119 /* We want at least as many bits as are available. */
Simon Pilgrim00b34992017-03-20 14:40:12 +00002120 APInt::tcExtract(parts.data(), dstPartsCount, src, semantics->precision,
2121 0);
2122 APInt::tcShiftLeft(parts.data(), dstPartsCount,
2123 bits - semantics->precision);
Neil Booth618d0fc2007-11-01 22:43:37 +00002124 truncatedBits = 0;
2125 }
2126 }
2127
2128 /* Step 2: work out any lost fraction, and increment the absolute
2129 value if we would round away from zero. */
2130 if (truncatedBits) {
2131 lost_fraction = lostFractionThroughTruncation(src, partCount(),
2132 truncatedBits);
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002133 if (lost_fraction != lfExactlyZero &&
2134 roundAwayFromZero(rounding_mode, lost_fraction, truncatedBits)) {
Simon Pilgrim00b34992017-03-20 14:40:12 +00002135 if (APInt::tcIncrement(parts.data(), dstPartsCount))
Neil Booth618d0fc2007-11-01 22:43:37 +00002136 return opInvalidOp; /* Overflow. */
2137 }
2138 } else {
2139 lost_fraction = lfExactlyZero;
2140 }
2141
2142 /* Step 3: check if we fit in the destination. */
Simon Pilgrim00b34992017-03-20 14:40:12 +00002143 unsigned int omsb = APInt::tcMSB(parts.data(), dstPartsCount) + 1;
Neil Booth618d0fc2007-11-01 22:43:37 +00002144
2145 if (sign) {
2146 if (!isSigned) {
2147 /* Negative numbers cannot be represented as unsigned. */
2148 if (omsb != 0)
2149 return opInvalidOp;
2150 } else {
2151 /* It takes omsb bits to represent the unsigned integer value.
2152 We lose a bit for the sign, but care is needed as the
2153 maximally negative integer is a special case. */
Simon Pilgrim00b34992017-03-20 14:40:12 +00002154 if (omsb == width &&
2155 APInt::tcLSB(parts.data(), dstPartsCount) + 1 != omsb)
Neil Booth618d0fc2007-11-01 22:43:37 +00002156 return opInvalidOp;
2157
2158 /* This case can happen because of rounding. */
2159 if (omsb > width)
2160 return opInvalidOp;
2161 }
2162
Simon Pilgrim00b34992017-03-20 14:40:12 +00002163 APInt::tcNegate (parts.data(), dstPartsCount);
Neil Booth618d0fc2007-11-01 22:43:37 +00002164 } else {
2165 if (omsb >= width + !isSigned)
2166 return opInvalidOp;
2167 }
2168
Dale Johannesen4f0bd682008-10-09 23:00:39 +00002169 if (lost_fraction == lfExactlyZero) {
2170 *isExact = true;
Neil Booth618d0fc2007-11-01 22:43:37 +00002171 return opOK;
Dale Johannesen4f0bd682008-10-09 23:00:39 +00002172 } else
Neil Booth618d0fc2007-11-01 22:43:37 +00002173 return opInexact;
2174}
2175
2176/* Same as convertToSignExtendedInteger, except we provide
2177 deterministic values in case of an invalid operation exception,
2178 namely zero for NaNs and the minimal or maximal value respectively
Dale Johannesen4f0bd682008-10-09 23:00:39 +00002179 for underflow or overflow.
2180 The *isExact output tells whether the result is exact, in the sense
2181 that converting it back to the original floating point type produces
2182 the original value. This is almost equivalent to result==opOK,
2183 except for negative zeroes.
2184*/
Simon Pilgrim00b34992017-03-20 14:40:12 +00002185IEEEFloat::opStatus
2186IEEEFloat::convertToInteger(MutableArrayRef<integerPart> parts,
2187 unsigned int width, bool isSigned,
2188 roundingMode rounding_mode, bool *isExact) const {
Neil Booth618d0fc2007-11-01 22:43:37 +00002189 opStatus fs;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002190
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002191 fs = convertToSignExtendedInteger(parts, width, isSigned, rounding_mode,
Dale Johannesen4f0bd682008-10-09 23:00:39 +00002192 isExact);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002193
Neil Booth618d0fc2007-11-01 22:43:37 +00002194 if (fs == opInvalidOp) {
2195 unsigned int bits, dstPartsCount;
2196
2197 dstPartsCount = partCountForBits(width);
Simon Pilgrim00b34992017-03-20 14:40:12 +00002198 assert(dstPartsCount <= parts.size() && "Integer too big");
Neil Booth618d0fc2007-11-01 22:43:37 +00002199
2200 if (category == fcNaN)
2201 bits = 0;
2202 else if (sign)
2203 bits = isSigned;
2204 else
2205 bits = width - isSigned;
2206
Simon Pilgrim00b34992017-03-20 14:40:12 +00002207 APInt::tcSetLeastSignificantBits(parts.data(), dstPartsCount, bits);
Neil Booth618d0fc2007-11-01 22:43:37 +00002208 if (sign && isSigned)
Simon Pilgrim00b34992017-03-20 14:40:12 +00002209 APInt::tcShiftLeft(parts.data(), dstPartsCount, width - 1);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002210 }
2211
Neil Booth618d0fc2007-11-01 22:43:37 +00002212 return fs;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002213}
2214
Neil Booth6c1c8582007-10-07 12:07:53 +00002215/* Convert an unsigned integer SRC to a floating point number,
2216 rounding according to ROUNDING_MODE. The sign of the floating
2217 point number is not modified. */
Tim Shen85de51d2016-10-25 19:55:59 +00002218IEEEFloat::opStatus IEEEFloat::convertFromUnsignedParts(
2219 const integerPart *src, unsigned int srcCount, roundingMode rounding_mode) {
Neil Booth49c6aab2007-10-08 14:39:42 +00002220 unsigned int omsb, precision, dstCount;
Neil Booth6c1c8582007-10-07 12:07:53 +00002221 integerPart *dst;
Neil Booth49c6aab2007-10-08 14:39:42 +00002222 lostFraction lost_fraction;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002223
2224 category = fcNormal;
Neil Booth49c6aab2007-10-08 14:39:42 +00002225 omsb = APInt::tcMSB(src, srcCount) + 1;
Neil Booth6c1c8582007-10-07 12:07:53 +00002226 dst = significandParts();
2227 dstCount = partCount();
Neil Booth49c6aab2007-10-08 14:39:42 +00002228 precision = semantics->precision;
Neil Booth6c1c8582007-10-07 12:07:53 +00002229
Nick Lewyckyf66daac2011-10-03 21:30:08 +00002230 /* We want the most significant PRECISION bits of SRC. There may not
Neil Booth49c6aab2007-10-08 14:39:42 +00002231 be that many; extract what we can. */
2232 if (precision <= omsb) {
2233 exponent = omsb - 1;
Neil Booth6c1c8582007-10-07 12:07:53 +00002234 lost_fraction = lostFractionThroughTruncation(src, srcCount,
Neil Booth49c6aab2007-10-08 14:39:42 +00002235 omsb - precision);
2236 APInt::tcExtract(dst, dstCount, src, precision, omsb - precision);
2237 } else {
2238 exponent = precision - 1;
2239 lost_fraction = lfExactlyZero;
2240 APInt::tcExtract(dst, dstCount, src, omsb, 0);
Neil Booth6c1c8582007-10-07 12:07:53 +00002241 }
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002242
2243 return normalize(rounding_mode, lost_fraction);
2244}
2245
Tim Shen85de51d2016-10-25 19:55:59 +00002246IEEEFloat::opStatus IEEEFloat::convertFromAPInt(const APInt &Val, bool isSigned,
2247 roundingMode rounding_mode) {
Dan Gohman35723eb2008-02-29 01:26:11 +00002248 unsigned int partCount = Val.getNumWords();
2249 APInt api = Val;
2250
2251 sign = false;
2252 if (isSigned && api.isNegative()) {
2253 sign = true;
2254 api = -api;
2255 }
2256
2257 return convertFromUnsignedParts(api.getRawData(), partCount, rounding_mode);
2258}
2259
Neil Booth03f58ab2007-10-07 12:15:41 +00002260/* Convert a two's complement integer SRC to a floating point number,
2261 rounding according to ROUNDING_MODE. ISSIGNED is true if the
2262 integer is signed, in which case it must be sign-extended. */
Tim Shen85de51d2016-10-25 19:55:59 +00002263IEEEFloat::opStatus
2264IEEEFloat::convertFromSignExtendedInteger(const integerPart *src,
2265 unsigned int srcCount, bool isSigned,
2266 roundingMode rounding_mode) {
Neil Booth03f58ab2007-10-07 12:15:41 +00002267 opStatus status;
2268
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002269 if (isSigned &&
2270 APInt::tcExtractBit(src, srcCount * integerPartWidth - 1)) {
Dylan Noblesmith4e69e292014-08-26 02:03:33 +00002271 integerPart *copy;
Neil Booth03f58ab2007-10-07 12:15:41 +00002272
2273 /* If we're signed and negative negate a copy. */
2274 sign = true;
Dylan Noblesmith4e69e292014-08-26 02:03:33 +00002275 copy = new integerPart[srcCount];
Neil Booth03f58ab2007-10-07 12:15:41 +00002276 APInt::tcAssign(copy, src, srcCount);
2277 APInt::tcNegate(copy, srcCount);
2278 status = convertFromUnsignedParts(copy, srcCount, rounding_mode);
Dylan Noblesmith4e69e292014-08-26 02:03:33 +00002279 delete [] copy;
Neil Booth03f58ab2007-10-07 12:15:41 +00002280 } else {
2281 sign = false;
2282 status = convertFromUnsignedParts(src, srcCount, rounding_mode);
2283 }
2284
2285 return status;
2286}
2287
Neil Booth5f009732007-10-07 11:45:55 +00002288/* FIXME: should this just take a const APInt reference? */
Tim Shen85de51d2016-10-25 19:55:59 +00002289IEEEFloat::opStatus
2290IEEEFloat::convertFromZeroExtendedInteger(const integerPart *parts,
2291 unsigned int width, bool isSigned,
2292 roundingMode rounding_mode) {
Dale Johannesen42305122007-09-21 22:09:37 +00002293 unsigned int partCount = partCountForBits(width);
Jeffrey Yasskin7a162882011-07-18 21:45:40 +00002294 APInt api = APInt(width, makeArrayRef(parts, partCount));
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002295
2296 sign = false;
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002297 if (isSigned && APInt::tcExtractBit(parts, width - 1)) {
Dale Johannesen28a2c4a2007-09-30 18:17:01 +00002298 sign = true;
2299 api = -api;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002300 }
2301
Neil Boothba205222007-10-07 12:10:57 +00002302 return convertFromUnsignedParts(api.getRawData(), partCount, rounding_mode);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002303}
2304
Tim Shen85de51d2016-10-25 19:55:59 +00002305IEEEFloat::opStatus
2306IEEEFloat::convertFromHexadecimalString(StringRef s,
2307 roundingMode rounding_mode) {
Erick Tryzelaara9680df2009-08-18 18:20:37 +00002308 lostFraction lost_fraction = lfExactlyZero;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002309
Michael Gottesman30a90eb2013-07-27 21:49:21 +00002310 category = fcNormal;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002311 zeroSignificand();
2312 exponent = 0;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002313
Eli Friedmand2eb07a2013-07-17 22:17:29 +00002314 integerPart *significand = significandParts();
2315 unsigned partsCount = partCount();
2316 unsigned bitPos = partsCount * integerPartWidth;
2317 bool computedTrailingFraction = false;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002318
Eli Friedmand2eb07a2013-07-17 22:17:29 +00002319 // Skip leading zeroes and any (hexa)decimal point.
Erick Tryzelaarda666c82009-08-20 23:30:43 +00002320 StringRef::iterator begin = s.begin();
2321 StringRef::iterator end = s.end();
Eli Friedmand2eb07a2013-07-17 22:17:29 +00002322 StringRef::iterator dot;
Erick Tryzelaarda666c82009-08-20 23:30:43 +00002323 StringRef::iterator p = skipLeadingZeroesAndAnyDot(begin, end, &dot);
Eli Friedmand2eb07a2013-07-17 22:17:29 +00002324 StringRef::iterator firstSignificantDigit = p;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002325
Eli Friedmand2eb07a2013-07-17 22:17:29 +00002326 while (p != end) {
Dale Johannesenfa483722008-05-14 22:53:25 +00002327 integerPart hex_value;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002328
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002329 if (*p == '.') {
Erick Tryzelaarda666c82009-08-20 23:30:43 +00002330 assert(dot == end && "String contains multiple dots");
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002331 dot = p++;
Eli Friedmand2eb07a2013-07-17 22:17:29 +00002332 continue;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002333 }
2334
2335 hex_value = hexDigitValue(*p);
Eli Friedmand2eb07a2013-07-17 22:17:29 +00002336 if (hex_value == -1U)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002337 break;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002338
2339 p++;
2340
Eli Friedmand2eb07a2013-07-17 22:17:29 +00002341 // Store the number while we have space.
2342 if (bitPos) {
2343 bitPos -= 4;
2344 hex_value <<= bitPos % integerPartWidth;
2345 significand[bitPos / integerPartWidth] |= hex_value;
2346 } else if (!computedTrailingFraction) {
2347 lost_fraction = trailingHexadecimalFraction(p, end, hex_value);
2348 computedTrailingFraction = true;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002349 }
2350 }
2351
2352 /* Hex floats require an exponent but not a hexadecimal point. */
Erick Tryzelaarda666c82009-08-20 23:30:43 +00002353 assert(p != end && "Hex strings require an exponent");
2354 assert((*p == 'p' || *p == 'P') && "Invalid character in significand");
2355 assert(p != begin && "Significand has no digits");
2356 assert((dot == end || p - begin != 1) && "Significand has no digits");
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002357
2358 /* Ignore the exponent if we are zero. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002359 if (p != firstSignificantDigit) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002360 int expAdjustment;
2361
2362 /* Implicit hexadecimal point? */
Erick Tryzelaarda666c82009-08-20 23:30:43 +00002363 if (dot == end)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002364 dot = p;
2365
2366 /* Calculate the exponent adjustment implicit in the number of
2367 significant digits. */
Evan Cheng82b9e962008-05-02 21:15:08 +00002368 expAdjustment = static_cast<int>(dot - firstSignificantDigit);
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002369 if (expAdjustment < 0)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002370 expAdjustment++;
2371 expAdjustment = expAdjustment * 4 - 1;
2372
2373 /* Adjust for writing the significand starting at the most
2374 significant nibble. */
2375 expAdjustment += semantics->precision;
2376 expAdjustment -= partsCount * integerPartWidth;
2377
2378 /* Adjust for the given exponent. */
Erick Tryzelaarda666c82009-08-20 23:30:43 +00002379 exponent = totalExponent(p + 1, end, expAdjustment);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002380 }
2381
2382 return normalize(rounding_mode, lost_fraction);
2383}
2384
Tim Shen85de51d2016-10-25 19:55:59 +00002385IEEEFloat::opStatus
2386IEEEFloat::roundSignificandWithExponent(const integerPart *decSigParts,
2387 unsigned sigPartCount, int exp,
2388 roundingMode rounding_mode) {
Neil Boothb93d90e2007-10-12 16:02:31 +00002389 unsigned int parts, pow5PartCount;
Tamas Berghammerb6b0ddf2015-07-09 10:13:39 +00002390 fltSemantics calcSemantics = { 32767, -32767, 0, 0 };
Neil Boothb93d90e2007-10-12 16:02:31 +00002391 integerPart pow5Parts[maxPowerOfFiveParts];
2392 bool isNearest;
2393
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002394 isNearest = (rounding_mode == rmNearestTiesToEven ||
2395 rounding_mode == rmNearestTiesToAway);
Neil Boothb93d90e2007-10-12 16:02:31 +00002396
2397 parts = partCountForBits(semantics->precision + 11);
2398
2399 /* Calculate pow(5, abs(exp)). */
2400 pow5PartCount = powerOf5(pow5Parts, exp >= 0 ? exp: -exp);
2401
2402 for (;; parts *= 2) {
2403 opStatus sigStatus, powStatus;
2404 unsigned int excessPrecision, truncatedBits;
2405
2406 calcSemantics.precision = parts * integerPartWidth - 1;
2407 excessPrecision = calcSemantics.precision - semantics->precision;
2408 truncatedBits = excessPrecision;
2409
Tim Shen139a58f2016-10-27 22:52:40 +00002410 IEEEFloat decSig(calcSemantics, uninitialized);
2411 decSig.makeZero(sign);
Tim Shen85de51d2016-10-25 19:55:59 +00002412 IEEEFloat pow5(calcSemantics);
Neil Boothb93d90e2007-10-12 16:02:31 +00002413
2414 sigStatus = decSig.convertFromUnsignedParts(decSigParts, sigPartCount,
2415 rmNearestTiesToEven);
2416 powStatus = pow5.convertFromUnsignedParts(pow5Parts, pow5PartCount,
2417 rmNearestTiesToEven);
2418 /* Add exp, as 10^n = 5^n * 2^n. */
2419 decSig.exponent += exp;
2420
2421 lostFraction calcLostFraction;
Evan Cheng82b9e962008-05-02 21:15:08 +00002422 integerPart HUerr, HUdistance;
2423 unsigned int powHUerr;
Neil Boothb93d90e2007-10-12 16:02:31 +00002424
2425 if (exp >= 0) {
2426 /* multiplySignificand leaves the precision-th bit set to 1. */
Craig Topperc10719f2014-04-07 04:17:22 +00002427 calcLostFraction = decSig.multiplySignificand(pow5, nullptr);
Neil Boothb93d90e2007-10-12 16:02:31 +00002428 powHUerr = powStatus != opOK;
2429 } else {
2430 calcLostFraction = decSig.divideSignificand(pow5);
2431 /* Denormal numbers have less precision. */
2432 if (decSig.exponent < semantics->minExponent) {
2433 excessPrecision += (semantics->minExponent - decSig.exponent);
2434 truncatedBits = excessPrecision;
2435 if (excessPrecision > calcSemantics.precision)
2436 excessPrecision = calcSemantics.precision;
2437 }
2438 /* Extra half-ulp lost in reciprocal of exponent. */
Evan Cheng82b9e962008-05-02 21:15:08 +00002439 powHUerr = (powStatus == opOK && calcLostFraction == lfExactlyZero) ? 0:2;
Neil Boothb93d90e2007-10-12 16:02:31 +00002440 }
2441
2442 /* Both multiplySignificand and divideSignificand return the
2443 result with the integer bit set. */
Evan Cheng67c90212009-10-27 21:35:42 +00002444 assert(APInt::tcExtractBit
2445 (decSig.significandParts(), calcSemantics.precision - 1) == 1);
Neil Boothb93d90e2007-10-12 16:02:31 +00002446
2447 HUerr = HUerrBound(calcLostFraction != lfExactlyZero, sigStatus != opOK,
2448 powHUerr);
2449 HUdistance = 2 * ulpsFromBoundary(decSig.significandParts(),
2450 excessPrecision, isNearest);
2451
2452 /* Are we guaranteed to round correctly if we truncate? */
2453 if (HUdistance >= HUerr) {
2454 APInt::tcExtract(significandParts(), partCount(), decSig.significandParts(),
2455 calcSemantics.precision - excessPrecision,
2456 excessPrecision);
2457 /* Take the exponent of decSig. If we tcExtract-ed less bits
2458 above we must adjust our exponent to compensate for the
2459 implicit right shift. */
2460 exponent = (decSig.exponent + semantics->precision
2461 - (calcSemantics.precision - excessPrecision));
2462 calcLostFraction = lostFractionThroughTruncation(decSig.significandParts(),
2463 decSig.partCount(),
2464 truncatedBits);
2465 return normalize(rounding_mode, calcLostFraction);
2466 }
2467 }
2468}
2469
Tim Shen85de51d2016-10-25 19:55:59 +00002470IEEEFloat::opStatus
2471IEEEFloat::convertFromDecimalString(StringRef str, roundingMode rounding_mode) {
Neil Booth4ed401b2007-10-14 10:16:12 +00002472 decimalInfo D;
Neil Boothb93d90e2007-10-12 16:02:31 +00002473 opStatus fs;
2474
Neil Booth4ed401b2007-10-14 10:16:12 +00002475 /* Scan the text. */
Erick Tryzelaar19f63b22009-08-16 23:36:19 +00002476 StringRef::iterator p = str.begin();
2477 interpretDecimal(p, str.end(), &D);
Neil Boothb93d90e2007-10-12 16:02:31 +00002478
Neil Booth91305512007-10-15 15:00:55 +00002479 /* Handle the quick cases. First the case of no significant digits,
2480 i.e. zero, and then exponents that are obviously too large or too
2481 small. Writing L for log 10 / log 2, a number d.ddddd*10^exp
2482 definitely overflows if
2483
2484 (exp - 1) * L >= maxExponent
2485
2486 and definitely underflows to zero where
2487
2488 (exp + 1) * L <= minExponent - precision
2489
2490 With integer arithmetic the tightest bounds for L are
2491
2492 93/28 < L < 196/59 [ numerator <= 256 ]
2493 42039/12655 < L < 28738/8651 [ numerator <= 65536 ]
2494 */
2495
Michael Gottesman228156c2013-07-01 23:54:08 +00002496 // Test if we have a zero number allowing for strings with no null terminators
2497 // and zero decimals with non-zero exponents.
Simon Pilgrima2849592017-03-20 13:53:59 +00002498 //
Michael Gottesman228156c2013-07-01 23:54:08 +00002499 // We computed firstSigDigit by ignoring all zeros and dots. Thus if
2500 // D->firstSigDigit equals str.end(), every digit must be a zero and there can
2501 // be at most one dot. On the other hand, if we have a zero with a non-zero
2502 // exponent, then we know that D.firstSigDigit will be non-numeric.
Michael Gottesman94d61952013-07-02 15:50:05 +00002503 if (D.firstSigDigit == str.end() || decDigitValue(*D.firstSigDigit) >= 10U) {
Neil Boothb93d90e2007-10-12 16:02:31 +00002504 category = fcZero;
2505 fs = opOK;
John McCallb42cc682010-02-26 22:20:41 +00002506
2507 /* Check whether the normalized exponent is high enough to overflow
2508 max during the log-rebasing in the max-exponent check below. */
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +00002509 } else if (D.normalizedExponent - 1 > INT_MAX / 42039) {
John McCallb42cc682010-02-26 22:20:41 +00002510 fs = handleOverflow(rounding_mode);
2511
2512 /* If it wasn't, then it also wasn't high enough to overflow max
2513 during the log-rebasing in the min-exponent check. Check that it
2514 won't overflow min in either check, then perform the min-exponent
2515 check. */
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +00002516 } else if (D.normalizedExponent - 1 < INT_MIN / 42039 ||
John McCallb42cc682010-02-26 22:20:41 +00002517 (D.normalizedExponent + 1) * 28738 <=
2518 8651 * (semantics->minExponent - (int) semantics->precision)) {
Neil Booth91305512007-10-15 15:00:55 +00002519 /* Underflow to zero and round. */
Michael Gottesman30a90eb2013-07-27 21:49:21 +00002520 category = fcNormal;
Neil Booth91305512007-10-15 15:00:55 +00002521 zeroSignificand();
2522 fs = normalize(rounding_mode, lfLessThanHalf);
John McCallb42cc682010-02-26 22:20:41 +00002523
2524 /* We can finally safely perform the max-exponent check. */
Neil Booth91305512007-10-15 15:00:55 +00002525 } else if ((D.normalizedExponent - 1) * 42039
2526 >= 12655 * semantics->maxExponent) {
2527 /* Overflow and round. */
2528 fs = handleOverflow(rounding_mode);
Neil Boothb93d90e2007-10-12 16:02:31 +00002529 } else {
Dylan Noblesmith4e69e292014-08-26 02:03:33 +00002530 integerPart *decSignificand;
Neil Booth4ed401b2007-10-14 10:16:12 +00002531 unsigned int partCount;
Neil Boothb93d90e2007-10-12 16:02:31 +00002532
Neil Booth4ed401b2007-10-14 10:16:12 +00002533 /* A tight upper bound on number of bits required to hold an
Neil Booth91305512007-10-15 15:00:55 +00002534 N-digit decimal integer is N * 196 / 59. Allocate enough space
Neil Booth4ed401b2007-10-14 10:16:12 +00002535 to hold the full significand, and an extra part required by
2536 tcMultiplyPart. */
Evan Cheng82b9e962008-05-02 21:15:08 +00002537 partCount = static_cast<unsigned int>(D.lastSigDigit - D.firstSigDigit) + 1;
Neil Booth91305512007-10-15 15:00:55 +00002538 partCount = partCountForBits(1 + 196 * partCount / 59);
Dylan Noblesmith4e69e292014-08-26 02:03:33 +00002539 decSignificand = new integerPart[partCount + 1];
Neil Booth4ed401b2007-10-14 10:16:12 +00002540 partCount = 0;
Neil Boothb93d90e2007-10-12 16:02:31 +00002541
Neil Booth4ed401b2007-10-14 10:16:12 +00002542 /* Convert to binary efficiently - we do almost all multiplication
2543 in an integerPart. When this would overflow do we do a single
2544 bignum multiplication, and then revert again to multiplication
2545 in an integerPart. */
2546 do {
2547 integerPart decValue, val, multiplier;
2548
2549 val = 0;
2550 multiplier = 1;
2551
2552 do {
Erick Tryzelaar19f63b22009-08-16 23:36:19 +00002553 if (*p == '.') {
Neil Booth4ed401b2007-10-14 10:16:12 +00002554 p++;
Erick Tryzelaar19f63b22009-08-16 23:36:19 +00002555 if (p == str.end()) {
2556 break;
2557 }
2558 }
Neil Booth4ed401b2007-10-14 10:16:12 +00002559 decValue = decDigitValue(*p++);
Erick Tryzelaarda666c82009-08-20 23:30:43 +00002560 assert(decValue < 10U && "Invalid character in significand");
Neil Booth4ed401b2007-10-14 10:16:12 +00002561 multiplier *= 10;
2562 val = val * 10 + decValue;
2563 /* The maximum number that can be multiplied by ten with any
2564 digit added without overflowing an integerPart. */
2565 } while (p <= D.lastSigDigit && multiplier <= (~ (integerPart) 0 - 9) / 10);
2566
2567 /* Multiply out the current part. */
2568 APInt::tcMultiplyPart(decSignificand, decSignificand, multiplier, val,
2569 partCount, partCount + 1, false);
2570
2571 /* If we used another part (likely but not guaranteed), increase
2572 the count. */
2573 if (decSignificand[partCount])
2574 partCount++;
2575 } while (p <= D.lastSigDigit);
Neil Boothb93d90e2007-10-12 16:02:31 +00002576
Neil Boothae077d22007-11-01 22:51:07 +00002577 category = fcNormal;
Neil Boothb93d90e2007-10-12 16:02:31 +00002578 fs = roundSignificandWithExponent(decSignificand, partCount,
Neil Booth4ed401b2007-10-14 10:16:12 +00002579 D.exponent, rounding_mode);
Dylan Noblesmith4e69e292014-08-26 02:03:33 +00002580
2581 delete [] decSignificand;
Neil Booth4ed401b2007-10-14 10:16:12 +00002582 }
Neil Boothb93d90e2007-10-12 16:02:31 +00002583
2584 return fs;
2585}
2586
Tim Shen85de51d2016-10-25 19:55:59 +00002587bool IEEEFloat::convertFromStringSpecials(StringRef str) {
Serguei Katkov768d6dd2017-12-19 04:27:39 +00002588 if (str.equals("inf") || str.equals("INFINITY") || str.equals("+Inf")) {
Michael Gottesman40e8a182013-06-24 09:58:05 +00002589 makeInf(false);
2590 return true;
2591 }
2592
Serguei Katkov768d6dd2017-12-19 04:27:39 +00002593 if (str.equals("-inf") || str.equals("-INFINITY") || str.equals("-Inf")) {
Michael Gottesman40e8a182013-06-24 09:58:05 +00002594 makeInf(true);
2595 return true;
2596 }
2597
2598 if (str.equals("nan") || str.equals("NaN")) {
2599 makeNaN(false, false);
2600 return true;
2601 }
2602
2603 if (str.equals("-nan") || str.equals("-NaN")) {
2604 makeNaN(false, true);
2605 return true;
2606 }
2607
2608 return false;
2609}
2610
Tim Shen85de51d2016-10-25 19:55:59 +00002611IEEEFloat::opStatus IEEEFloat::convertFromString(StringRef str,
2612 roundingMode rounding_mode) {
Erick Tryzelaar19f63b22009-08-16 23:36:19 +00002613 assert(!str.empty() && "Invalid string length");
Neil Booth06077e72007-10-14 10:29:28 +00002614
Michael Gottesman40e8a182013-06-24 09:58:05 +00002615 // Handle special cases.
2616 if (convertFromStringSpecials(str))
2617 return opOK;
2618
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002619 /* Handle a leading minus sign. */
Erick Tryzelaar19f63b22009-08-16 23:36:19 +00002620 StringRef::iterator p = str.begin();
2621 size_t slen = str.size();
Erick Tryzelaarda666c82009-08-20 23:30:43 +00002622 sign = *p == '-' ? 1 : 0;
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002623 if (*p == '-' || *p == '+') {
Erick Tryzelaar19f63b22009-08-16 23:36:19 +00002624 p++;
2625 slen--;
Erick Tryzelaarda666c82009-08-20 23:30:43 +00002626 assert(slen && "String has no digits");
Erick Tryzelaar19f63b22009-08-16 23:36:19 +00002627 }
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002628
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002629 if (slen >= 2 && p[0] == '0' && (p[1] == 'x' || p[1] == 'X')) {
Erick Tryzelaar19f63b22009-08-16 23:36:19 +00002630 assert(slen - 2 && "Invalid string");
Erick Tryzelaarda666c82009-08-20 23:30:43 +00002631 return convertFromHexadecimalString(StringRef(p + 2, slen - 2),
Erick Tryzelaar19f63b22009-08-16 23:36:19 +00002632 rounding_mode);
2633 }
Bill Wendlingc6075402008-11-27 08:00:12 +00002634
Erick Tryzelaarda666c82009-08-20 23:30:43 +00002635 return convertFromDecimalString(StringRef(p, slen), rounding_mode);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002636}
Dale Johannesena719a602007-08-24 00:56:33 +00002637
Neil Booth8f1946f2007-10-03 22:26:02 +00002638/* Write out a hexadecimal representation of the floating point value
2639 to DST, which must be of sufficient size, in the C99 form
2640 [-]0xh.hhhhp[+-]d. Return the number of characters written,
2641 excluding the terminating NUL.
2642
2643 If UPPERCASE, the output is in upper case, otherwise in lower case.
2644
2645 HEXDIGITS digits appear altogether, rounding the value if
2646 necessary. If HEXDIGITS is 0, the minimal precision to display the
2647 number precisely is used instead. If nothing would appear after
2648 the decimal point it is suppressed.
2649
2650 The decimal exponent is always printed and has at least one digit.
2651 Zero values display an exponent of zero. Infinities and NaNs
2652 appear as "infinity" or "nan" respectively.
2653
2654 The above rules are as specified by C99. There is ambiguity about
2655 what the leading hexadecimal digit should be. This implementation
2656 uses whatever is necessary so that the exponent is displayed as
2657 stored. This implies the exponent will fall within the IEEE format
2658 range, and the leading hexadecimal digit will be 0 (for denormals),
2659 1 (normal numbers) or 2 (normal numbers rounded-away-from-zero with
2660 any other digits zero).
2661*/
Tim Shen85de51d2016-10-25 19:55:59 +00002662unsigned int IEEEFloat::convertToHexString(char *dst, unsigned int hexDigits,
2663 bool upperCase,
2664 roundingMode rounding_mode) const {
Neil Booth8f1946f2007-10-03 22:26:02 +00002665 char *p;
2666
2667 p = dst;
2668 if (sign)
2669 *dst++ = '-';
2670
2671 switch (category) {
2672 case fcInfinity:
2673 memcpy (dst, upperCase ? infinityU: infinityL, sizeof infinityU - 1);
2674 dst += sizeof infinityL - 1;
2675 break;
2676
2677 case fcNaN:
2678 memcpy (dst, upperCase ? NaNU: NaNL, sizeof NaNU - 1);
2679 dst += sizeof NaNU - 1;
2680 break;
2681
2682 case fcZero:
2683 *dst++ = '0';
2684 *dst++ = upperCase ? 'X': 'x';
2685 *dst++ = '0';
2686 if (hexDigits > 1) {
2687 *dst++ = '.';
2688 memset (dst, '0', hexDigits - 1);
2689 dst += hexDigits - 1;
2690 }
2691 *dst++ = upperCase ? 'P': 'p';
2692 *dst++ = '0';
2693 break;
2694
2695 case fcNormal:
2696 dst = convertNormalToHexString (dst, hexDigits, upperCase, rounding_mode);
2697 break;
2698 }
2699
2700 *dst = 0;
2701
Evan Cheng82b9e962008-05-02 21:15:08 +00002702 return static_cast<unsigned int>(dst - p);
Neil Booth8f1946f2007-10-03 22:26:02 +00002703}
2704
2705/* Does the hard work of outputting the correctly rounded hexadecimal
2706 form of a normal floating point number with the specified number of
2707 hexadecimal digits. If HEXDIGITS is zero the minimum number of
2708 digits necessary to print the value precisely is output. */
Tim Shen85de51d2016-10-25 19:55:59 +00002709char *IEEEFloat::convertNormalToHexString(char *dst, unsigned int hexDigits,
2710 bool upperCase,
2711 roundingMode rounding_mode) const {
Neil Booth8f1946f2007-10-03 22:26:02 +00002712 unsigned int count, valueBits, shift, partsCount, outputDigits;
2713 const char *hexDigitChars;
2714 const integerPart *significand;
2715 char *p;
2716 bool roundUp;
2717
2718 *dst++ = '0';
2719 *dst++ = upperCase ? 'X': 'x';
2720
2721 roundUp = false;
2722 hexDigitChars = upperCase ? hexDigitsUpper: hexDigitsLower;
2723
2724 significand = significandParts();
2725 partsCount = partCount();
2726
2727 /* +3 because the first digit only uses the single integer bit, so
2728 we have 3 virtual zero most-significant-bits. */
2729 valueBits = semantics->precision + 3;
2730 shift = integerPartWidth - valueBits % integerPartWidth;
2731
2732 /* The natural number of digits required ignoring trailing
2733 insignificant zeroes. */
2734 outputDigits = (valueBits - significandLSB () + 3) / 4;
2735
2736 /* hexDigits of zero means use the required number for the
2737 precision. Otherwise, see if we are truncating. If we are,
Neil Booth0ea72a92007-10-06 00:24:48 +00002738 find out if we need to round away from zero. */
Neil Booth8f1946f2007-10-03 22:26:02 +00002739 if (hexDigits) {
2740 if (hexDigits < outputDigits) {
2741 /* We are dropping non-zero bits, so need to check how to round.
2742 "bits" is the number of dropped bits. */
2743 unsigned int bits;
2744 lostFraction fraction;
2745
2746 bits = valueBits - hexDigits * 4;
2747 fraction = lostFractionThroughTruncation (significand, partsCount, bits);
2748 roundUp = roundAwayFromZero(rounding_mode, fraction, bits);
2749 }
2750 outputDigits = hexDigits;
2751 }
2752
2753 /* Write the digits consecutively, and start writing in the location
2754 of the hexadecimal point. We move the most significant digit
2755 left and add the hexadecimal point later. */
2756 p = ++dst;
2757
2758 count = (valueBits + integerPartWidth - 1) / integerPartWidth;
2759
2760 while (outputDigits && count) {
2761 integerPart part;
2762
2763 /* Put the most significant integerPartWidth bits in "part". */
2764 if (--count == partsCount)
2765 part = 0; /* An imaginary higher zero part. */
2766 else
2767 part = significand[count] << shift;
2768
2769 if (count && shift)
2770 part |= significand[count - 1] >> (integerPartWidth - shift);
2771
2772 /* Convert as much of "part" to hexdigits as we can. */
2773 unsigned int curDigits = integerPartWidth / 4;
2774
2775 if (curDigits > outputDigits)
2776 curDigits = outputDigits;
2777 dst += partAsHex (dst, part, curDigits, hexDigitChars);
2778 outputDigits -= curDigits;
2779 }
2780
2781 if (roundUp) {
2782 char *q = dst;
2783
2784 /* Note that hexDigitChars has a trailing '0'. */
2785 do {
2786 q--;
2787 *q = hexDigitChars[hexDigitValue (*q) + 1];
Neil Booth0ea72a92007-10-06 00:24:48 +00002788 } while (*q == '0');
Evan Cheng67c90212009-10-27 21:35:42 +00002789 assert(q >= p);
Neil Booth8f1946f2007-10-03 22:26:02 +00002790 } else {
2791 /* Add trailing zeroes. */
2792 memset (dst, '0', outputDigits);
2793 dst += outputDigits;
2794 }
2795
2796 /* Move the most significant digit to before the point, and if there
2797 is something after the decimal point add it. This must come
2798 after rounding above. */
2799 p[-1] = p[0];
2800 if (dst -1 == p)
2801 dst--;
2802 else
2803 p[0] = '.';
2804
2805 /* Finally output the exponent. */
2806 *dst++ = upperCase ? 'P': 'p';
2807
Neil Booth32897f52007-10-06 07:29:25 +00002808 return writeSignedDecimal (dst, exponent);
Neil Booth8f1946f2007-10-03 22:26:02 +00002809}
2810
Tim Shen85de51d2016-10-25 19:55:59 +00002811hash_code hash_value(const IEEEFloat &Arg) {
Michael Gottesman8136c382013-06-26 23:17:28 +00002812 if (!Arg.isFiniteNonZero())
Chandler Carruth71bd7d12012-03-04 12:02:57 +00002813 return hash_combine((uint8_t)Arg.category,
2814 // NaN has no sign, fix it at zero.
2815 Arg.isNaN() ? (uint8_t)0 : (uint8_t)Arg.sign,
2816 Arg.semantics->precision);
2817
2818 // Normal floats need their exponent and significand hashed.
2819 return hash_combine((uint8_t)Arg.category, (uint8_t)Arg.sign,
2820 Arg.semantics->precision, Arg.exponent,
2821 hash_combine_range(
2822 Arg.significandParts(),
2823 Arg.significandParts() + Arg.partCount()));
Dale Johannesena719a602007-08-24 00:56:33 +00002824}
2825
2826// Conversion from APFloat to/from host float/double. It may eventually be
2827// possible to eliminate these and have everybody deal with APFloats, but that
2828// will take a while. This approach will not easily extend to long double.
Dale Johannesen146a0ea2007-09-20 23:47:58 +00002829// Current implementation requires integerPartWidth==64, which is correct at
2830// the moment but could be made more general.
Dale Johannesena719a602007-08-24 00:56:33 +00002831
Dale Johannesen728687c2007-09-05 20:39:49 +00002832// Denormals have exponent minExponent in APFloat, but minExponent-1 in
Dale Johannesen146a0ea2007-09-20 23:47:58 +00002833// the actual IEEE respresentations. We compensate for that here.
Dale Johannesen728687c2007-09-05 20:39:49 +00002834
Tim Shen85de51d2016-10-25 19:55:59 +00002835APInt IEEEFloat::convertF80LongDoubleAPFloatToAPInt() const {
Stephan Bergmann17c7f702016-12-14 11:57:17 +00002836 assert(semantics == (const llvm::fltSemantics*)&semX87DoubleExtended);
Evan Cheng67c90212009-10-27 21:35:42 +00002837 assert(partCount()==2);
Dale Johannesen245dceb2007-09-11 18:32:33 +00002838
2839 uint64_t myexponent, mysignificand;
2840
Michael Gottesman8136c382013-06-26 23:17:28 +00002841 if (isFiniteNonZero()) {
Dale Johannesen245dceb2007-09-11 18:32:33 +00002842 myexponent = exponent+16383; //bias
Dale Johannesen146a0ea2007-09-20 23:47:58 +00002843 mysignificand = significandParts()[0];
Dale Johannesen245dceb2007-09-11 18:32:33 +00002844 if (myexponent==1 && !(mysignificand & 0x8000000000000000ULL))
2845 myexponent = 0; // denormal
2846 } else if (category==fcZero) {
2847 myexponent = 0;
2848 mysignificand = 0;
2849 } else if (category==fcInfinity) {
2850 myexponent = 0x7fff;
2851 mysignificand = 0x8000000000000000ULL;
Chris Lattner2a9bcb92007-10-06 06:13:42 +00002852 } else {
2853 assert(category == fcNaN && "Unknown category");
Dale Johannesen245dceb2007-09-11 18:32:33 +00002854 myexponent = 0x7fff;
Dale Johannesen146a0ea2007-09-20 23:47:58 +00002855 mysignificand = significandParts()[0];
Chris Lattner2a9bcb92007-10-06 06:13:42 +00002856 }
Dale Johannesen245dceb2007-09-11 18:32:33 +00002857
2858 uint64_t words[2];
Dale Johannesen93eefa02009-03-23 21:16:53 +00002859 words[0] = mysignificand;
2860 words[1] = ((uint64_t)(sign & 1) << 15) |
2861 (myexponent & 0x7fffLL);
Jeffrey Yasskin7a162882011-07-18 21:45:40 +00002862 return APInt(80, words);
Dale Johannesen245dceb2007-09-11 18:32:33 +00002863}
2864
Tim Shen85de51d2016-10-25 19:55:59 +00002865APInt IEEEFloat::convertPPCDoubleDoubleAPFloatToAPInt() const {
Tim Shenfd1e5aa2017-01-23 22:39:35 +00002866 assert(semantics == (const llvm::fltSemantics *)&semPPCDoubleDoubleLegacy);
Evan Cheng67c90212009-10-27 21:35:42 +00002867 assert(partCount()==2);
Dale Johannesen007aa372007-10-11 18:07:22 +00002868
Ulrich Weigandd9f7e252012-10-29 18:09:01 +00002869 uint64_t words[2];
2870 opStatus fs;
2871 bool losesInfo;
Dale Johannesen007aa372007-10-11 18:07:22 +00002872
Ulrich Weigandd9f7e252012-10-29 18:09:01 +00002873 // Convert number to double. To avoid spurious underflows, we re-
2874 // normalize against the "double" minExponent first, and only *then*
2875 // truncate the mantissa. The result of that second conversion
2876 // may be inexact, but should never underflow.
Alexey Samsonov2b431d92012-11-30 22:27:54 +00002877 // Declare fltSemantics before APFloat that uses it (and
2878 // saves pointer to it) to ensure correct destruction order.
Ulrich Weigandd9f7e252012-10-29 18:09:01 +00002879 fltSemantics extendedSemantics = *semantics;
Stephan Bergmann17c7f702016-12-14 11:57:17 +00002880 extendedSemantics.minExponent = semIEEEdouble.minExponent;
Tim Shen85de51d2016-10-25 19:55:59 +00002881 IEEEFloat extended(*this);
Ulrich Weigandd9f7e252012-10-29 18:09:01 +00002882 fs = extended.convert(extendedSemantics, rmNearestTiesToEven, &losesInfo);
2883 assert(fs == opOK && !losesInfo);
2884 (void)fs;
2885
Tim Shen85de51d2016-10-25 19:55:59 +00002886 IEEEFloat u(extended);
Stephan Bergmann17c7f702016-12-14 11:57:17 +00002887 fs = u.convert(semIEEEdouble, rmNearestTiesToEven, &losesInfo);
Ulrich Weigandd9f7e252012-10-29 18:09:01 +00002888 assert(fs == opOK || fs == opInexact);
2889 (void)fs;
2890 words[0] = *u.convertDoubleAPFloatToAPInt().getRawData();
2891
2892 // If conversion was exact or resulted in a special case, we're done;
2893 // just set the second double to zero. Otherwise, re-convert back to
2894 // the extended format and compute the difference. This now should
2895 // convert exactly to double.
Michael Gottesman8136c382013-06-26 23:17:28 +00002896 if (u.isFiniteNonZero() && losesInfo) {
Ulrich Weigandd9f7e252012-10-29 18:09:01 +00002897 fs = u.convert(extendedSemantics, rmNearestTiesToEven, &losesInfo);
2898 assert(fs == opOK && !losesInfo);
2899 (void)fs;
2900
Tim Shen85de51d2016-10-25 19:55:59 +00002901 IEEEFloat v(extended);
Ulrich Weigandd9f7e252012-10-29 18:09:01 +00002902 v.subtract(u, rmNearestTiesToEven);
Stephan Bergmann17c7f702016-12-14 11:57:17 +00002903 fs = v.convert(semIEEEdouble, rmNearestTiesToEven, &losesInfo);
Ulrich Weigandd9f7e252012-10-29 18:09:01 +00002904 assert(fs == opOK && !losesInfo);
2905 (void)fs;
2906 words[1] = *v.convertDoubleAPFloatToAPInt().getRawData();
Dale Johannesen007aa372007-10-11 18:07:22 +00002907 } else {
Ulrich Weigandd9f7e252012-10-29 18:09:01 +00002908 words[1] = 0;
Dale Johannesen007aa372007-10-11 18:07:22 +00002909 }
2910
Jeffrey Yasskin7a162882011-07-18 21:45:40 +00002911 return APInt(128, words);
Dale Johannesen007aa372007-10-11 18:07:22 +00002912}
2913
Tim Shen85de51d2016-10-25 19:55:59 +00002914APInt IEEEFloat::convertQuadrupleAPFloatToAPInt() const {
Stephan Bergmann17c7f702016-12-14 11:57:17 +00002915 assert(semantics == (const llvm::fltSemantics*)&semIEEEquad);
Evan Cheng67c90212009-10-27 21:35:42 +00002916 assert(partCount()==2);
Anton Korobeynikov13e8c7e2009-08-21 22:10:30 +00002917
2918 uint64_t myexponent, mysignificand, mysignificand2;
2919
Michael Gottesman8136c382013-06-26 23:17:28 +00002920 if (isFiniteNonZero()) {
Anton Korobeynikov13e8c7e2009-08-21 22:10:30 +00002921 myexponent = exponent+16383; //bias
2922 mysignificand = significandParts()[0];
2923 mysignificand2 = significandParts()[1];
2924 if (myexponent==1 && !(mysignificand2 & 0x1000000000000LL))
2925 myexponent = 0; // denormal
2926 } else if (category==fcZero) {
2927 myexponent = 0;
2928 mysignificand = mysignificand2 = 0;
2929 } else if (category==fcInfinity) {
2930 myexponent = 0x7fff;
2931 mysignificand = mysignificand2 = 0;
2932 } else {
2933 assert(category == fcNaN && "Unknown category!");
2934 myexponent = 0x7fff;
2935 mysignificand = significandParts()[0];
2936 mysignificand2 = significandParts()[1];
2937 }
2938
2939 uint64_t words[2];
2940 words[0] = mysignificand;
2941 words[1] = ((uint64_t)(sign & 1) << 63) |
2942 ((myexponent & 0x7fff) << 48) |
Anton Korobeynikov876955c2009-08-21 23:09:47 +00002943 (mysignificand2 & 0xffffffffffffLL);
Anton Korobeynikov13e8c7e2009-08-21 22:10:30 +00002944
Jeffrey Yasskin7a162882011-07-18 21:45:40 +00002945 return APInt(128, words);
Anton Korobeynikov13e8c7e2009-08-21 22:10:30 +00002946}
2947
Tim Shen85de51d2016-10-25 19:55:59 +00002948APInt IEEEFloat::convertDoubleAPFloatToAPInt() const {
Stephan Bergmann17c7f702016-12-14 11:57:17 +00002949 assert(semantics == (const llvm::fltSemantics*)&semIEEEdouble);
Evan Cheng67c90212009-10-27 21:35:42 +00002950 assert(partCount()==1);
Dale Johannesena719a602007-08-24 00:56:33 +00002951
Dale Johannesen3cf889f2007-08-31 04:03:46 +00002952 uint64_t myexponent, mysignificand;
Dale Johannesena719a602007-08-24 00:56:33 +00002953
Michael Gottesman8136c382013-06-26 23:17:28 +00002954 if (isFiniteNonZero()) {
Dale Johannesena719a602007-08-24 00:56:33 +00002955 myexponent = exponent+1023; //bias
Dale Johannesen728687c2007-09-05 20:39:49 +00002956 mysignificand = *significandParts();
2957 if (myexponent==1 && !(mysignificand & 0x10000000000000LL))
2958 myexponent = 0; // denormal
Dale Johannesena719a602007-08-24 00:56:33 +00002959 } else if (category==fcZero) {
Dale Johannesena719a602007-08-24 00:56:33 +00002960 myexponent = 0;
2961 mysignificand = 0;
2962 } else if (category==fcInfinity) {
Dale Johannesena719a602007-08-24 00:56:33 +00002963 myexponent = 0x7ff;
2964 mysignificand = 0;
Chris Lattner2a9bcb92007-10-06 06:13:42 +00002965 } else {
2966 assert(category == fcNaN && "Unknown category!");
Dale Johannesena719a602007-08-24 00:56:33 +00002967 myexponent = 0x7ff;
Dale Johannesen3cf889f2007-08-31 04:03:46 +00002968 mysignificand = *significandParts();
Chris Lattner2a9bcb92007-10-06 06:13:42 +00002969 }
Dale Johannesena719a602007-08-24 00:56:33 +00002970
Evan Cheng82b9e962008-05-02 21:15:08 +00002971 return APInt(64, ((((uint64_t)(sign & 1) << 63) |
Chris Lattner2a9bcb92007-10-06 06:13:42 +00002972 ((myexponent & 0x7ff) << 52) |
2973 (mysignificand & 0xfffffffffffffLL))));
Dale Johannesena719a602007-08-24 00:56:33 +00002974}
2975
Tim Shen85de51d2016-10-25 19:55:59 +00002976APInt IEEEFloat::convertFloatAPFloatToAPInt() const {
Stephan Bergmann17c7f702016-12-14 11:57:17 +00002977 assert(semantics == (const llvm::fltSemantics*)&semIEEEsingle);
Evan Cheng67c90212009-10-27 21:35:42 +00002978 assert(partCount()==1);
Neil Booth9acbf5a2007-09-26 21:33:42 +00002979
Dale Johannesen3cf889f2007-08-31 04:03:46 +00002980 uint32_t myexponent, mysignificand;
Dale Johannesena719a602007-08-24 00:56:33 +00002981
Michael Gottesman8136c382013-06-26 23:17:28 +00002982 if (isFiniteNonZero()) {
Dale Johannesena719a602007-08-24 00:56:33 +00002983 myexponent = exponent+127; //bias
Evan Cheng82b9e962008-05-02 21:15:08 +00002984 mysignificand = (uint32_t)*significandParts();
Dale Johannesen06a10df2007-11-17 01:02:27 +00002985 if (myexponent == 1 && !(mysignificand & 0x800000))
Dale Johannesen728687c2007-09-05 20:39:49 +00002986 myexponent = 0; // denormal
Dale Johannesena719a602007-08-24 00:56:33 +00002987 } else if (category==fcZero) {
Dale Johannesena719a602007-08-24 00:56:33 +00002988 myexponent = 0;
2989 mysignificand = 0;
2990 } else if (category==fcInfinity) {
Dale Johannesena719a602007-08-24 00:56:33 +00002991 myexponent = 0xff;
2992 mysignificand = 0;
Chris Lattner2a9bcb92007-10-06 06:13:42 +00002993 } else {
2994 assert(category == fcNaN && "Unknown category!");
Dale Johannesen728687c2007-09-05 20:39:49 +00002995 myexponent = 0xff;
Evan Cheng82b9e962008-05-02 21:15:08 +00002996 mysignificand = (uint32_t)*significandParts();
Chris Lattner2a9bcb92007-10-06 06:13:42 +00002997 }
Dale Johannesena719a602007-08-24 00:56:33 +00002998
Chris Lattner2a9bcb92007-10-06 06:13:42 +00002999 return APInt(32, (((sign&1) << 31) | ((myexponent&0xff) << 23) |
3000 (mysignificand & 0x7fffff)));
Dale Johannesena719a602007-08-24 00:56:33 +00003001}
3002
Tim Shen85de51d2016-10-25 19:55:59 +00003003APInt IEEEFloat::convertHalfAPFloatToAPInt() const {
Stephan Bergmann17c7f702016-12-14 11:57:17 +00003004 assert(semantics == (const llvm::fltSemantics*)&semIEEEhalf);
Evan Cheng67c90212009-10-27 21:35:42 +00003005 assert(partCount()==1);
Chris Lattner4794b2b2009-10-16 02:13:51 +00003006
3007 uint32_t myexponent, mysignificand;
3008
Michael Gottesman8136c382013-06-26 23:17:28 +00003009 if (isFiniteNonZero()) {
Chris Lattner4794b2b2009-10-16 02:13:51 +00003010 myexponent = exponent+15; //bias
3011 mysignificand = (uint32_t)*significandParts();
3012 if (myexponent == 1 && !(mysignificand & 0x400))
3013 myexponent = 0; // denormal
3014 } else if (category==fcZero) {
3015 myexponent = 0;
3016 mysignificand = 0;
3017 } else if (category==fcInfinity) {
Dale Johannesen0d670b52009-10-23 04:02:51 +00003018 myexponent = 0x1f;
Chris Lattner4794b2b2009-10-16 02:13:51 +00003019 mysignificand = 0;
3020 } else {
3021 assert(category == fcNaN && "Unknown category!");
Dale Johannesen0d670b52009-10-23 04:02:51 +00003022 myexponent = 0x1f;
Chris Lattner4794b2b2009-10-16 02:13:51 +00003023 mysignificand = (uint32_t)*significandParts();
3024 }
3025
3026 return APInt(16, (((sign&1) << 15) | ((myexponent&0x1f) << 10) |
3027 (mysignificand & 0x3ff)));
3028}
3029
Dale Johannesen007aa372007-10-11 18:07:22 +00003030// This function creates an APInt that is just a bit map of the floating
3031// point constant as it would appear in memory. It is not a conversion,
3032// and treating the result as a normal integer is unlikely to be useful.
3033
Tim Shen85de51d2016-10-25 19:55:59 +00003034APInt IEEEFloat::bitcastToAPInt() const {
Stephan Bergmann17c7f702016-12-14 11:57:17 +00003035 if (semantics == (const llvm::fltSemantics*)&semIEEEhalf)
Chris Lattner4794b2b2009-10-16 02:13:51 +00003036 return convertHalfAPFloatToAPInt();
3037
Stephan Bergmann17c7f702016-12-14 11:57:17 +00003038 if (semantics == (const llvm::fltSemantics*)&semIEEEsingle)
Dale Johannesen245dceb2007-09-11 18:32:33 +00003039 return convertFloatAPFloatToAPInt();
Anton Korobeynikov13e8c7e2009-08-21 22:10:30 +00003040
Stephan Bergmann17c7f702016-12-14 11:57:17 +00003041 if (semantics == (const llvm::fltSemantics*)&semIEEEdouble)
Dale Johannesen245dceb2007-09-11 18:32:33 +00003042 return convertDoubleAPFloatToAPInt();
Neil Booth9acbf5a2007-09-26 21:33:42 +00003043
Stephan Bergmann17c7f702016-12-14 11:57:17 +00003044 if (semantics == (const llvm::fltSemantics*)&semIEEEquad)
Anton Korobeynikov13e8c7e2009-08-21 22:10:30 +00003045 return convertQuadrupleAPFloatToAPInt();
3046
Tim Shenfd1e5aa2017-01-23 22:39:35 +00003047 if (semantics == (const llvm::fltSemantics *)&semPPCDoubleDoubleLegacy)
Dale Johannesen007aa372007-10-11 18:07:22 +00003048 return convertPPCDoubleDoubleAPFloatToAPInt();
3049
Stephan Bergmann17c7f702016-12-14 11:57:17 +00003050 assert(semantics == (const llvm::fltSemantics*)&semX87DoubleExtended &&
Chris Lattner2a9bcb92007-10-06 06:13:42 +00003051 "unknown format!");
3052 return convertF80LongDoubleAPFloatToAPInt();
Dale Johannesen245dceb2007-09-11 18:32:33 +00003053}
3054
Tim Shen85de51d2016-10-25 19:55:59 +00003055float IEEEFloat::convertToFloat() const {
Stephan Bergmann17c7f702016-12-14 11:57:17 +00003056 assert(semantics == (const llvm::fltSemantics*)&semIEEEsingle &&
Chris Lattner688f9912009-09-24 21:44:20 +00003057 "Float semantics are not IEEEsingle");
Dale Johannesen54306fe2008-10-09 18:53:47 +00003058 APInt api = bitcastToAPInt();
Dale Johannesen245dceb2007-09-11 18:32:33 +00003059 return api.bitsToFloat();
3060}
3061
Tim Shen85de51d2016-10-25 19:55:59 +00003062double IEEEFloat::convertToDouble() const {
Stephan Bergmann17c7f702016-12-14 11:57:17 +00003063 assert(semantics == (const llvm::fltSemantics*)&semIEEEdouble &&
Chris Lattner688f9912009-09-24 21:44:20 +00003064 "Float semantics are not IEEEdouble");
Dale Johannesen54306fe2008-10-09 18:53:47 +00003065 APInt api = bitcastToAPInt();
Dale Johannesen245dceb2007-09-11 18:32:33 +00003066 return api.bitsToDouble();
3067}
3068
Dale Johannesenfff29952008-10-06 18:22:29 +00003069/// Integer bit is explicit in this format. Intel hardware (387 and later)
3070/// does not support these bit patterns:
3071/// exponent = all 1's, integer bit 0, significand 0 ("pseudoinfinity")
3072/// exponent = all 1's, integer bit 0, significand nonzero ("pseudoNaN")
Dale Johannesenfff29952008-10-06 18:22:29 +00003073/// exponent!=0 nor all 1's, integer bit 0 ("unnormal")
Pavel Labathb1bcafd2018-05-09 15:13:45 +00003074/// exponent = 0, integer bit 1 ("pseudodenormal")
3075/// At the moment, the first three are treated as NaNs, the last one as Normal.
Tim Shen85de51d2016-10-25 19:55:59 +00003076void IEEEFloat::initFromF80LongDoubleAPInt(const APInt &api) {
Dale Johannesen245dceb2007-09-11 18:32:33 +00003077 assert(api.getBitWidth()==80);
3078 uint64_t i1 = api.getRawData()[0];
3079 uint64_t i2 = api.getRawData()[1];
Dale Johannesen93eefa02009-03-23 21:16:53 +00003080 uint64_t myexponent = (i2 & 0x7fff);
3081 uint64_t mysignificand = i1;
Pavel Labathb1bcafd2018-05-09 15:13:45 +00003082 uint8_t myintegerbit = mysignificand >> 63;
Dale Johannesen245dceb2007-09-11 18:32:33 +00003083
Stephan Bergmann17c7f702016-12-14 11:57:17 +00003084 initialize(&semX87DoubleExtended);
Dale Johannesen146a0ea2007-09-20 23:47:58 +00003085 assert(partCount()==2);
Dale Johannesen245dceb2007-09-11 18:32:33 +00003086
Dale Johannesen93eefa02009-03-23 21:16:53 +00003087 sign = static_cast<unsigned int>(i2>>15);
Pavel Labathb1bcafd2018-05-09 15:13:45 +00003088 if (myexponent == 0 && mysignificand == 0) {
Dale Johannesen245dceb2007-09-11 18:32:33 +00003089 // exponent, significand meaningless
3090 category = fcZero;
3091 } else if (myexponent==0x7fff && mysignificand==0x8000000000000000ULL) {
3092 // exponent, significand meaningless
3093 category = fcInfinity;
Pavel Labathb1bcafd2018-05-09 15:13:45 +00003094 } else if ((myexponent == 0x7fff && mysignificand != 0x8000000000000000ULL) ||
3095 (myexponent != 0x7fff && myexponent != 0 && myintegerbit == 0)) {
Dale Johannesen245dceb2007-09-11 18:32:33 +00003096 // exponent meaningless
3097 category = fcNaN;
Dale Johannesen146a0ea2007-09-20 23:47:58 +00003098 significandParts()[0] = mysignificand;
3099 significandParts()[1] = 0;
Dale Johannesen245dceb2007-09-11 18:32:33 +00003100 } else {
3101 category = fcNormal;
3102 exponent = myexponent - 16383;
Dale Johannesen146a0ea2007-09-20 23:47:58 +00003103 significandParts()[0] = mysignificand;
3104 significandParts()[1] = 0;
Dale Johannesen245dceb2007-09-11 18:32:33 +00003105 if (myexponent==0) // denormal
3106 exponent = -16382;
Neil Booth9acbf5a2007-09-26 21:33:42 +00003107 }
Dale Johannesen245dceb2007-09-11 18:32:33 +00003108}
3109
Tim Shen85de51d2016-10-25 19:55:59 +00003110void IEEEFloat::initFromPPCDoubleDoubleAPInt(const APInt &api) {
Dale Johannesen007aa372007-10-11 18:07:22 +00003111 assert(api.getBitWidth()==128);
3112 uint64_t i1 = api.getRawData()[0];
3113 uint64_t i2 = api.getRawData()[1];
Ulrich Weigandd9f7e252012-10-29 18:09:01 +00003114 opStatus fs;
3115 bool losesInfo;
Dale Johannesen007aa372007-10-11 18:07:22 +00003116
Ulrich Weigandd9f7e252012-10-29 18:09:01 +00003117 // Get the first double and convert to our format.
3118 initFromDoubleAPInt(APInt(64, i1));
Tim Shenfd1e5aa2017-01-23 22:39:35 +00003119 fs = convert(semPPCDoubleDoubleLegacy, rmNearestTiesToEven, &losesInfo);
Ulrich Weigandd9f7e252012-10-29 18:09:01 +00003120 assert(fs == opOK && !losesInfo);
3121 (void)fs;
Dale Johannesen007aa372007-10-11 18:07:22 +00003122
Ulrich Weigandd9f7e252012-10-29 18:09:01 +00003123 // Unless we have a special case, add in second double.
Michael Gottesman8136c382013-06-26 23:17:28 +00003124 if (isFiniteNonZero()) {
Stephan Bergmann17c7f702016-12-14 11:57:17 +00003125 IEEEFloat v(semIEEEdouble, APInt(64, i2));
Tim Shenfd1e5aa2017-01-23 22:39:35 +00003126 fs = v.convert(semPPCDoubleDoubleLegacy, rmNearestTiesToEven, &losesInfo);
Ulrich Weigandd9f7e252012-10-29 18:09:01 +00003127 assert(fs == opOK && !losesInfo);
3128 (void)fs;
3129
3130 add(v, rmNearestTiesToEven);
Dale Johannesen007aa372007-10-11 18:07:22 +00003131 }
3132}
3133
Tim Shen85de51d2016-10-25 19:55:59 +00003134void IEEEFloat::initFromQuadrupleAPInt(const APInt &api) {
Anton Korobeynikov13e8c7e2009-08-21 22:10:30 +00003135 assert(api.getBitWidth()==128);
3136 uint64_t i1 = api.getRawData()[0];
3137 uint64_t i2 = api.getRawData()[1];
3138 uint64_t myexponent = (i2 >> 48) & 0x7fff;
3139 uint64_t mysignificand = i1;
3140 uint64_t mysignificand2 = i2 & 0xffffffffffffLL;
3141
Stephan Bergmann17c7f702016-12-14 11:57:17 +00003142 initialize(&semIEEEquad);
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +00003143 assert(partCount()==2);
Anton Korobeynikov13e8c7e2009-08-21 22:10:30 +00003144
3145 sign = static_cast<unsigned int>(i2>>63);
3146 if (myexponent==0 &&
3147 (mysignificand==0 && mysignificand2==0)) {
3148 // exponent, significand meaningless
3149 category = fcZero;
3150 } else if (myexponent==0x7fff &&
3151 (mysignificand==0 && mysignificand2==0)) {
3152 // exponent, significand meaningless
3153 category = fcInfinity;
3154 } else if (myexponent==0x7fff &&
3155 (mysignificand!=0 || mysignificand2 !=0)) {
3156 // exponent meaningless
3157 category = fcNaN;
3158 significandParts()[0] = mysignificand;
3159 significandParts()[1] = mysignificand2;
3160 } else {
3161 category = fcNormal;
3162 exponent = myexponent - 16383;
3163 significandParts()[0] = mysignificand;
3164 significandParts()[1] = mysignificand2;
3165 if (myexponent==0) // denormal
3166 exponent = -16382;
3167 else
3168 significandParts()[1] |= 0x1000000000000LL; // integer bit
3169 }
3170}
3171
Tim Shen85de51d2016-10-25 19:55:59 +00003172void IEEEFloat::initFromDoubleAPInt(const APInt &api) {
Dale Johannesen245dceb2007-09-11 18:32:33 +00003173 assert(api.getBitWidth()==64);
3174 uint64_t i = *api.getRawData();
Dale Johannesen918c33c2007-08-24 05:08:11 +00003175 uint64_t myexponent = (i >> 52) & 0x7ff;
3176 uint64_t mysignificand = i & 0xfffffffffffffLL;
3177
Stephan Bergmann17c7f702016-12-14 11:57:17 +00003178 initialize(&semIEEEdouble);
Dale Johannesena719a602007-08-24 00:56:33 +00003179 assert(partCount()==1);
3180
Evan Cheng82b9e962008-05-02 21:15:08 +00003181 sign = static_cast<unsigned int>(i>>63);
Dale Johannesena719a602007-08-24 00:56:33 +00003182 if (myexponent==0 && mysignificand==0) {
3183 // exponent, significand meaningless
3184 category = fcZero;
Dale Johannesena719a602007-08-24 00:56:33 +00003185 } else if (myexponent==0x7ff && mysignificand==0) {
3186 // exponent, significand meaningless
3187 category = fcInfinity;
Dale Johannesen3cf889f2007-08-31 04:03:46 +00003188 } else if (myexponent==0x7ff && mysignificand!=0) {
3189 // exponent meaningless
3190 category = fcNaN;
3191 *significandParts() = mysignificand;
Dale Johannesena719a602007-08-24 00:56:33 +00003192 } else {
Dale Johannesena719a602007-08-24 00:56:33 +00003193 category = fcNormal;
3194 exponent = myexponent - 1023;
Dale Johannesen728687c2007-09-05 20:39:49 +00003195 *significandParts() = mysignificand;
3196 if (myexponent==0) // denormal
3197 exponent = -1022;
3198 else
3199 *significandParts() |= 0x10000000000000LL; // integer bit
Neil Booth9acbf5a2007-09-26 21:33:42 +00003200 }
Dale Johannesena719a602007-08-24 00:56:33 +00003201}
3202
Tim Shen85de51d2016-10-25 19:55:59 +00003203void IEEEFloat::initFromFloatAPInt(const APInt &api) {
Dale Johannesen245dceb2007-09-11 18:32:33 +00003204 assert(api.getBitWidth()==32);
3205 uint32_t i = (uint32_t)*api.getRawData();
Dale Johannesen918c33c2007-08-24 05:08:11 +00003206 uint32_t myexponent = (i >> 23) & 0xff;
3207 uint32_t mysignificand = i & 0x7fffff;
3208
Stephan Bergmann17c7f702016-12-14 11:57:17 +00003209 initialize(&semIEEEsingle);
Dale Johannesena719a602007-08-24 00:56:33 +00003210 assert(partCount()==1);
3211
Dale Johannesen3cf889f2007-08-31 04:03:46 +00003212 sign = i >> 31;
Dale Johannesena719a602007-08-24 00:56:33 +00003213 if (myexponent==0 && mysignificand==0) {
3214 // exponent, significand meaningless
3215 category = fcZero;
Dale Johannesena719a602007-08-24 00:56:33 +00003216 } else if (myexponent==0xff && mysignificand==0) {
3217 // exponent, significand meaningless
3218 category = fcInfinity;
Dale Johannesen4f55d9f2007-09-25 17:25:00 +00003219 } else if (myexponent==0xff && mysignificand!=0) {
Dale Johannesena719a602007-08-24 00:56:33 +00003220 // sign, exponent, significand meaningless
Dale Johannesen3cf889f2007-08-31 04:03:46 +00003221 category = fcNaN;
3222 *significandParts() = mysignificand;
Dale Johannesena719a602007-08-24 00:56:33 +00003223 } else {
3224 category = fcNormal;
Dale Johannesena719a602007-08-24 00:56:33 +00003225 exponent = myexponent - 127; //bias
Dale Johannesen728687c2007-09-05 20:39:49 +00003226 *significandParts() = mysignificand;
3227 if (myexponent==0) // denormal
3228 exponent = -126;
3229 else
3230 *significandParts() |= 0x800000; // integer bit
Dale Johannesena719a602007-08-24 00:56:33 +00003231 }
3232}
Dale Johannesen245dceb2007-09-11 18:32:33 +00003233
Tim Shen85de51d2016-10-25 19:55:59 +00003234void IEEEFloat::initFromHalfAPInt(const APInt &api) {
Chris Lattner4794b2b2009-10-16 02:13:51 +00003235 assert(api.getBitWidth()==16);
3236 uint32_t i = (uint32_t)*api.getRawData();
Dale Johannesen0d670b52009-10-23 04:02:51 +00003237 uint32_t myexponent = (i >> 10) & 0x1f;
Chris Lattner4794b2b2009-10-16 02:13:51 +00003238 uint32_t mysignificand = i & 0x3ff;
3239
Stephan Bergmann17c7f702016-12-14 11:57:17 +00003240 initialize(&semIEEEhalf);
Chris Lattner4794b2b2009-10-16 02:13:51 +00003241 assert(partCount()==1);
3242
3243 sign = i >> 15;
3244 if (myexponent==0 && mysignificand==0) {
3245 // exponent, significand meaningless
3246 category = fcZero;
3247 } else if (myexponent==0x1f && mysignificand==0) {
3248 // exponent, significand meaningless
3249 category = fcInfinity;
3250 } else if (myexponent==0x1f && mysignificand!=0) {
3251 // sign, exponent, significand meaningless
3252 category = fcNaN;
3253 *significandParts() = mysignificand;
3254 } else {
3255 category = fcNormal;
3256 exponent = myexponent - 15; //bias
3257 *significandParts() = mysignificand;
3258 if (myexponent==0) // denormal
3259 exponent = -14;
3260 else
3261 *significandParts() |= 0x400; // integer bit
3262 }
3263}
3264
Dale Johannesen245dceb2007-09-11 18:32:33 +00003265/// Treat api as containing the bits of a floating point number. Currently
Dale Johannesen007aa372007-10-11 18:07:22 +00003266/// we infer the floating point type from the size of the APInt. The
3267/// isIEEE argument distinguishes between PPC128 and IEEE128 (not meaningful
3268/// when the size is anything else).
Tim Shen85de51d2016-10-25 19:55:59 +00003269void IEEEFloat::initFromAPInt(const fltSemantics *Sem, const APInt &api) {
Stephan Bergmann17c7f702016-12-14 11:57:17 +00003270 if (Sem == &semIEEEhalf)
Chris Lattner4794b2b2009-10-16 02:13:51 +00003271 return initFromHalfAPInt(api);
Stephan Bergmann17c7f702016-12-14 11:57:17 +00003272 if (Sem == &semIEEEsingle)
Dale Johannesen245dceb2007-09-11 18:32:33 +00003273 return initFromFloatAPInt(api);
Stephan Bergmann17c7f702016-12-14 11:57:17 +00003274 if (Sem == &semIEEEdouble)
Dale Johannesen245dceb2007-09-11 18:32:33 +00003275 return initFromDoubleAPInt(api);
Stephan Bergmann17c7f702016-12-14 11:57:17 +00003276 if (Sem == &semX87DoubleExtended)
Dale Johannesen245dceb2007-09-11 18:32:33 +00003277 return initFromF80LongDoubleAPInt(api);
Stephan Bergmann17c7f702016-12-14 11:57:17 +00003278 if (Sem == &semIEEEquad)
Tim Northover29178a32013-01-22 09:46:31 +00003279 return initFromQuadrupleAPInt(api);
Tim Shenfd1e5aa2017-01-23 22:39:35 +00003280 if (Sem == &semPPCDoubleDoubleLegacy)
Tim Northover29178a32013-01-22 09:46:31 +00003281 return initFromPPCDoubleDoubleAPInt(api);
3282
Craig Topper2617dcc2014-04-15 06:32:26 +00003283 llvm_unreachable(nullptr);
Dale Johannesen245dceb2007-09-11 18:32:33 +00003284}
3285
Michael Gottesman0c622ea2013-05-30 18:07:13 +00003286/// Make this number the largest magnitude normal number in the given
3287/// semantics.
Tim Shen85de51d2016-10-25 19:55:59 +00003288void IEEEFloat::makeLargest(bool Negative) {
John McCall29b5c282009-12-24 08:56:26 +00003289 // We want (in interchange format):
3290 // sign = {Negative}
3291 // exponent = 1..10
3292 // significand = 1..1
Michael Gottesman0c622ea2013-05-30 18:07:13 +00003293 category = fcNormal;
3294 sign = Negative;
3295 exponent = semantics->maxExponent;
John McCall29b5c282009-12-24 08:56:26 +00003296
Michael Gottesman0c622ea2013-05-30 18:07:13 +00003297 // Use memset to set all but the highest integerPart to all ones.
3298 integerPart *significand = significandParts();
3299 unsigned PartCount = partCount();
3300 memset(significand, 0xFF, sizeof(integerPart)*(PartCount - 1));
John McCall29b5c282009-12-24 08:56:26 +00003301
Michael Gottesman0c622ea2013-05-30 18:07:13 +00003302 // Set the high integerPart especially setting all unused top bits for
3303 // internal consistency.
3304 const unsigned NumUnusedHighBits =
3305 PartCount*integerPartWidth - semantics->precision;
Alexey Samsonovba1ecbc2014-09-06 00:41:19 +00003306 significand[PartCount - 1] = (NumUnusedHighBits < integerPartWidth)
3307 ? (~integerPart(0) >> NumUnusedHighBits)
3308 : 0;
John McCall29b5c282009-12-24 08:56:26 +00003309}
3310
Michael Gottesman0c622ea2013-05-30 18:07:13 +00003311/// Make this number the smallest magnitude denormal number in the given
3312/// semantics.
Tim Shen85de51d2016-10-25 19:55:59 +00003313void IEEEFloat::makeSmallest(bool Negative) {
John McCall29b5c282009-12-24 08:56:26 +00003314 // We want (in interchange format):
3315 // sign = {Negative}
3316 // exponent = 0..0
3317 // significand = 0..01
Michael Gottesman0c622ea2013-05-30 18:07:13 +00003318 category = fcNormal;
3319 sign = Negative;
3320 exponent = semantics->minExponent;
3321 APInt::tcSet(significandParts(), 1, partCount());
3322}
John McCall29b5c282009-12-24 08:56:26 +00003323
Tim Shen139a58f2016-10-27 22:52:40 +00003324void IEEEFloat::makeSmallestNormalized(bool Negative) {
John McCall29b5c282009-12-24 08:56:26 +00003325 // We want (in interchange format):
3326 // sign = {Negative}
3327 // exponent = 0..0
3328 // significand = 10..0
3329
Tim Shen139a58f2016-10-27 22:52:40 +00003330 category = fcNormal;
3331 zeroSignificand();
3332 sign = Negative;
3333 exponent = semantics->minExponent;
3334 significandParts()[partCountForBits(semantics->precision) - 1] |=
3335 (((integerPart)1) << ((semantics->precision - 1) % integerPartWidth));
John McCall29b5c282009-12-24 08:56:26 +00003336}
3337
Tim Shen85de51d2016-10-25 19:55:59 +00003338IEEEFloat::IEEEFloat(const fltSemantics &Sem, const APInt &API) {
Tim Northover29178a32013-01-22 09:46:31 +00003339 initFromAPInt(&Sem, API);
Dale Johannesen245dceb2007-09-11 18:32:33 +00003340}
3341
Tim Shen85de51d2016-10-25 19:55:59 +00003342IEEEFloat::IEEEFloat(float f) {
Stephan Bergmann17c7f702016-12-14 11:57:17 +00003343 initFromAPInt(&semIEEEsingle, APInt::floatToBits(f));
Dale Johannesen245dceb2007-09-11 18:32:33 +00003344}
3345
Tim Shen85de51d2016-10-25 19:55:59 +00003346IEEEFloat::IEEEFloat(double d) {
Stephan Bergmann17c7f702016-12-14 11:57:17 +00003347 initFromAPInt(&semIEEEdouble, APInt::doubleToBits(d));
Dale Johannesen245dceb2007-09-11 18:32:33 +00003348}
John McCall29b5c282009-12-24 08:56:26 +00003349
3350namespace {
David Blaikie70fdf722012-07-25 18:04:24 +00003351 void append(SmallVectorImpl<char> &Buffer, StringRef Str) {
3352 Buffer.append(Str.begin(), Str.end());
John McCall29b5c282009-12-24 08:56:26 +00003353 }
3354
John McCalle6212ace2009-12-24 12:16:56 +00003355 /// Removes data from the given significand until it is no more
3356 /// precise than is required for the desired precision.
3357 void AdjustToPrecision(APInt &significand,
3358 int &exp, unsigned FormatPrecision) {
3359 unsigned bits = significand.getActiveBits();
3360
3361 // 196/59 is a very slight overestimate of lg_2(10).
3362 unsigned bitsRequired = (FormatPrecision * 196 + 58) / 59;
3363
3364 if (bits <= bitsRequired) return;
3365
3366 unsigned tensRemovable = (bits - bitsRequired) * 59 / 196;
3367 if (!tensRemovable) return;
3368
3369 exp += tensRemovable;
3370
3371 APInt divisor(significand.getBitWidth(), 1);
3372 APInt powten(significand.getBitWidth(), 10);
3373 while (true) {
3374 if (tensRemovable & 1)
3375 divisor *= powten;
3376 tensRemovable >>= 1;
3377 if (!tensRemovable) break;
3378 powten *= powten;
3379 }
3380
3381 significand = significand.udiv(divisor);
3382
Hao Liube99cc32013-03-20 01:46:36 +00003383 // Truncate the significand down to its active bit count.
3384 significand = significand.trunc(significand.getActiveBits());
John McCalle6212ace2009-12-24 12:16:56 +00003385 }
3386
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +00003387
John McCall29b5c282009-12-24 08:56:26 +00003388 void AdjustToPrecision(SmallVectorImpl<char> &buffer,
3389 int &exp, unsigned FormatPrecision) {
3390 unsigned N = buffer.size();
3391 if (N <= FormatPrecision) return;
3392
3393 // The most significant figures are the last ones in the buffer.
3394 unsigned FirstSignificant = N - FormatPrecision;
3395
3396 // Round.
3397 // FIXME: this probably shouldn't use 'round half up'.
3398
3399 // Rounding down is just a truncation, except we also want to drop
3400 // trailing zeros from the new result.
3401 if (buffer[FirstSignificant - 1] < '5') {
NAKAMURA Takumi5adeb932012-02-19 03:18:29 +00003402 while (FirstSignificant < N && buffer[FirstSignificant] == '0')
John McCall29b5c282009-12-24 08:56:26 +00003403 FirstSignificant++;
3404
3405 exp += FirstSignificant;
3406 buffer.erase(&buffer[0], &buffer[FirstSignificant]);
3407 return;
3408 }
3409
3410 // Rounding up requires a decimal add-with-carry. If we continue
3411 // the carry, the newly-introduced zeros will just be truncated.
3412 for (unsigned I = FirstSignificant; I != N; ++I) {
3413 if (buffer[I] == '9') {
3414 FirstSignificant++;
3415 } else {
3416 buffer[I]++;
3417 break;
3418 }
3419 }
3420
3421 // If we carried through, we have exactly one digit of precision.
3422 if (FirstSignificant == N) {
3423 exp += FirstSignificant;
3424 buffer.clear();
3425 buffer.push_back('1');
3426 return;
3427 }
3428
3429 exp += FirstSignificant;
3430 buffer.erase(&buffer[0], &buffer[FirstSignificant]);
3431 }
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +00003432}
John McCall29b5c282009-12-24 08:56:26 +00003433
Tim Shen85de51d2016-10-25 19:55:59 +00003434void IEEEFloat::toString(SmallVectorImpl<char> &Str, unsigned FormatPrecision,
Serguei Katkov3a46eb42017-04-21 02:52:17 +00003435 unsigned FormatMaxPadding, bool TruncateZero) const {
John McCall29b5c282009-12-24 08:56:26 +00003436 switch (category) {
3437 case fcInfinity:
3438 if (isNegative())
3439 return append(Str, "-Inf");
3440 else
3441 return append(Str, "+Inf");
3442
3443 case fcNaN: return append(Str, "NaN");
3444
3445 case fcZero:
3446 if (isNegative())
3447 Str.push_back('-');
3448
Serguei Katkov3a46eb42017-04-21 02:52:17 +00003449 if (!FormatMaxPadding) {
3450 if (TruncateZero)
3451 append(Str, "0.0E+0");
3452 else {
3453 append(Str, "0.0");
3454 if (FormatPrecision > 1)
3455 Str.append(FormatPrecision - 1, '0');
3456 append(Str, "e+00");
3457 }
3458 } else
John McCall29b5c282009-12-24 08:56:26 +00003459 Str.push_back('0');
3460 return;
3461
3462 case fcNormal:
3463 break;
3464 }
3465
3466 if (isNegative())
3467 Str.push_back('-');
3468
3469 // Decompose the number into an APInt and an exponent.
3470 int exp = exponent - ((int) semantics->precision - 1);
3471 APInt significand(semantics->precision,
Jeffrey Yasskin7a162882011-07-18 21:45:40 +00003472 makeArrayRef(significandParts(),
3473 partCountForBits(semantics->precision)));
John McCall29b5c282009-12-24 08:56:26 +00003474
John McCalldd5044a2009-12-24 23:18:09 +00003475 // Set FormatPrecision if zero. We want to do this before we
3476 // truncate trailing zeros, as those are part of the precision.
3477 if (!FormatPrecision) {
Eli Friedmane72f1322013-08-29 23:44:34 +00003478 // We use enough digits so the number can be round-tripped back to an
3479 // APFloat. The formula comes from "How to Print Floating-Point Numbers
3480 // Accurately" by Steele and White.
3481 // FIXME: Using a formula based purely on the precision is conservative;
3482 // we can print fewer digits depending on the actual value being printed.
John McCalldd5044a2009-12-24 23:18:09 +00003483
Eli Friedmane72f1322013-08-29 23:44:34 +00003484 // FormatPrecision = 2 + floor(significandBits / lg_2(10))
3485 FormatPrecision = 2 + semantics->precision * 59 / 196;
John McCalldd5044a2009-12-24 23:18:09 +00003486 }
3487
John McCall29b5c282009-12-24 08:56:26 +00003488 // Ignore trailing binary zeros.
3489 int trailingZeros = significand.countTrailingZeros();
3490 exp += trailingZeros;
Craig Topperfc947bc2017-04-18 17:14:21 +00003491 significand.lshrInPlace(trailingZeros);
John McCall29b5c282009-12-24 08:56:26 +00003492
3493 // Change the exponent from 2^e to 10^e.
3494 if (exp == 0) {
3495 // Nothing to do.
3496 } else if (exp > 0) {
3497 // Just shift left.
Jay Foad583abbc2010-12-07 08:25:19 +00003498 significand = significand.zext(semantics->precision + exp);
John McCall29b5c282009-12-24 08:56:26 +00003499 significand <<= exp;
3500 exp = 0;
3501 } else { /* exp < 0 */
3502 int texp = -exp;
3503
3504 // We transform this using the identity:
3505 // (N)(2^-e) == (N)(5^e)(10^-e)
3506 // This means we have to multiply N (the significand) by 5^e.
3507 // To avoid overflow, we have to operate on numbers large
3508 // enough to store N * 5^e:
3509 // log2(N * 5^e) == log2(N) + e * log2(5)
John McCalldd5044a2009-12-24 23:18:09 +00003510 // <= semantics->precision + e * 137 / 59
3511 // (log_2(5) ~ 2.321928 < 2.322034 ~ 137/59)
Dan Gohmanb452d4e2010-03-24 19:38:02 +00003512
Eli Friedman19546412011-10-07 23:40:49 +00003513 unsigned precision = semantics->precision + (137 * texp + 136) / 59;
John McCall29b5c282009-12-24 08:56:26 +00003514
3515 // Multiply significand by 5^e.
3516 // N * 5^0101 == N * 5^(1*1) * 5^(0*2) * 5^(1*4) * 5^(0*8)
Jay Foad583abbc2010-12-07 08:25:19 +00003517 significand = significand.zext(precision);
John McCall29b5c282009-12-24 08:56:26 +00003518 APInt five_to_the_i(precision, 5);
3519 while (true) {
3520 if (texp & 1) significand *= five_to_the_i;
Dan Gohmanb452d4e2010-03-24 19:38:02 +00003521
John McCall29b5c282009-12-24 08:56:26 +00003522 texp >>= 1;
3523 if (!texp) break;
3524 five_to_the_i *= five_to_the_i;
3525 }
3526 }
3527
John McCalle6212ace2009-12-24 12:16:56 +00003528 AdjustToPrecision(significand, exp, FormatPrecision);
3529
Dmitri Gribenko226fea52013-01-13 16:01:15 +00003530 SmallVector<char, 256> buffer;
John McCall29b5c282009-12-24 08:56:26 +00003531
3532 // Fill the buffer.
3533 unsigned precision = significand.getBitWidth();
3534 APInt ten(precision, 10);
3535 APInt digit(precision, 0);
3536
3537 bool inTrail = true;
3538 while (significand != 0) {
3539 // digit <- significand % 10
3540 // significand <- significand / 10
3541 APInt::udivrem(significand, ten, significand, digit);
3542
3543 unsigned d = digit.getZExtValue();
3544
3545 // Drop trailing zeros.
3546 if (inTrail && !d) exp++;
3547 else {
3548 buffer.push_back((char) ('0' + d));
3549 inTrail = false;
3550 }
3551 }
3552
3553 assert(!buffer.empty() && "no characters in buffer!");
3554
3555 // Drop down to FormatPrecision.
3556 // TODO: don't do more precise calculations above than are required.
3557 AdjustToPrecision(buffer, exp, FormatPrecision);
3558
3559 unsigned NDigits = buffer.size();
3560
John McCalldd5044a2009-12-24 23:18:09 +00003561 // Check whether we should use scientific notation.
John McCall29b5c282009-12-24 08:56:26 +00003562 bool FormatScientific;
3563 if (!FormatMaxPadding)
3564 FormatScientific = true;
3565 else {
John McCall29b5c282009-12-24 08:56:26 +00003566 if (exp >= 0) {
John McCalldd5044a2009-12-24 23:18:09 +00003567 // 765e3 --> 765000
3568 // ^^^
3569 // But we shouldn't make the number look more precise than it is.
3570 FormatScientific = ((unsigned) exp > FormatMaxPadding ||
3571 NDigits + (unsigned) exp > FormatPrecision);
John McCall29b5c282009-12-24 08:56:26 +00003572 } else {
John McCalldd5044a2009-12-24 23:18:09 +00003573 // Power of the most significant digit.
3574 int MSD = exp + (int) (NDigits - 1);
3575 if (MSD >= 0) {
John McCall29b5c282009-12-24 08:56:26 +00003576 // 765e-2 == 7.65
John McCalldd5044a2009-12-24 23:18:09 +00003577 FormatScientific = false;
John McCall29b5c282009-12-24 08:56:26 +00003578 } else {
3579 // 765e-5 == 0.00765
3580 // ^ ^^
John McCalldd5044a2009-12-24 23:18:09 +00003581 FormatScientific = ((unsigned) -MSD) > FormatMaxPadding;
John McCall29b5c282009-12-24 08:56:26 +00003582 }
3583 }
John McCall29b5c282009-12-24 08:56:26 +00003584 }
3585
3586 // Scientific formatting is pretty straightforward.
3587 if (FormatScientific) {
3588 exp += (NDigits - 1);
3589
3590 Str.push_back(buffer[NDigits-1]);
3591 Str.push_back('.');
Serguei Katkov3a46eb42017-04-21 02:52:17 +00003592 if (NDigits == 1 && TruncateZero)
John McCall29b5c282009-12-24 08:56:26 +00003593 Str.push_back('0');
3594 else
3595 for (unsigned I = 1; I != NDigits; ++I)
3596 Str.push_back(buffer[NDigits-1-I]);
Serguei Katkov3a46eb42017-04-21 02:52:17 +00003597 // Fill with zeros up to FormatPrecision.
3598 if (!TruncateZero && FormatPrecision > NDigits - 1)
3599 Str.append(FormatPrecision - NDigits + 1, '0');
3600 // For !TruncateZero we use lower 'e'.
3601 Str.push_back(TruncateZero ? 'E' : 'e');
John McCall29b5c282009-12-24 08:56:26 +00003602
3603 Str.push_back(exp >= 0 ? '+' : '-');
3604 if (exp < 0) exp = -exp;
3605 SmallVector<char, 6> expbuf;
3606 do {
3607 expbuf.push_back((char) ('0' + (exp % 10)));
3608 exp /= 10;
3609 } while (exp);
Serguei Katkov3a46eb42017-04-21 02:52:17 +00003610 // Exponent always at least two digits if we do not truncate zeros.
3611 if (!TruncateZero && expbuf.size() < 2)
3612 expbuf.push_back('0');
John McCall29b5c282009-12-24 08:56:26 +00003613 for (unsigned I = 0, E = expbuf.size(); I != E; ++I)
3614 Str.push_back(expbuf[E-1-I]);
3615 return;
3616 }
3617
3618 // Non-scientific, positive exponents.
3619 if (exp >= 0) {
3620 for (unsigned I = 0; I != NDigits; ++I)
3621 Str.push_back(buffer[NDigits-1-I]);
3622 for (unsigned I = 0; I != (unsigned) exp; ++I)
3623 Str.push_back('0');
3624 return;
3625 }
3626
3627 // Non-scientific, negative exponents.
3628
3629 // The number of digits to the left of the decimal point.
3630 int NWholeDigits = exp + (int) NDigits;
3631
3632 unsigned I = 0;
3633 if (NWholeDigits > 0) {
3634 for (; I != (unsigned) NWholeDigits; ++I)
3635 Str.push_back(buffer[NDigits-I-1]);
3636 Str.push_back('.');
3637 } else {
3638 unsigned NZeros = 1 + (unsigned) -NWholeDigits;
3639
3640 Str.push_back('0');
3641 Str.push_back('.');
3642 for (unsigned Z = 1; Z != NZeros; ++Z)
3643 Str.push_back('0');
3644 }
3645
3646 for (; I != NDigits; ++I)
3647 Str.push_back(buffer[NDigits-I-1]);
3648}
Benjamin Kramer03fd6722011-03-30 15:42:27 +00003649
Tim Shenfd1e5aa2017-01-23 22:39:35 +00003650bool IEEEFloat::getExactInverse(APFloat *inv) const {
Benjamin Kramer03fd6722011-03-30 15:42:27 +00003651 // Special floats and denormals have no exact inverse.
Michael Gottesman8136c382013-06-26 23:17:28 +00003652 if (!isFiniteNonZero())
Benjamin Kramer03fd6722011-03-30 15:42:27 +00003653 return false;
3654
3655 // Check that the number is a power of two by making sure that only the
3656 // integer bit is set in the significand.
3657 if (significandLSB() != semantics->precision - 1)
3658 return false;
3659
3660 // Get the inverse.
Tim Shen85de51d2016-10-25 19:55:59 +00003661 IEEEFloat reciprocal(*semantics, 1ULL);
Benjamin Kramer03fd6722011-03-30 15:42:27 +00003662 if (reciprocal.divide(*this, rmNearestTiesToEven) != opOK)
3663 return false;
3664
Benjamin Krameraf0ed952011-03-30 17:02:54 +00003665 // Avoid multiplication with a denormal, it is not safe on all platforms and
3666 // may be slower than a normal division.
Benjamin Kramer6bef24f2013-06-01 11:26:33 +00003667 if (reciprocal.isDenormal())
Benjamin Krameraf0ed952011-03-30 17:02:54 +00003668 return false;
3669
Michael Gottesman8136c382013-06-26 23:17:28 +00003670 assert(reciprocal.isFiniteNonZero() &&
Benjamin Krameraf0ed952011-03-30 17:02:54 +00003671 reciprocal.significandLSB() == reciprocal.semantics->precision - 1);
3672
Benjamin Kramer03fd6722011-03-30 15:42:27 +00003673 if (inv)
Tim Shenfd1e5aa2017-01-23 22:39:35 +00003674 *inv = APFloat(reciprocal, *semantics);
Benjamin Kramer03fd6722011-03-30 15:42:27 +00003675
3676 return true;
3677}
Michael Gottesman0c622ea2013-05-30 18:07:13 +00003678
Tim Shen85de51d2016-10-25 19:55:59 +00003679bool IEEEFloat::isSignaling() const {
Michael Gottesman0c622ea2013-05-30 18:07:13 +00003680 if (!isNaN())
3681 return false;
3682
3683 // IEEE-754R 2008 6.2.1: A signaling NaN bit string should be encoded with the
3684 // first bit of the trailing significand being 0.
3685 return !APInt::tcExtractBit(significandParts(), semantics->precision - 2);
3686}
3687
3688/// IEEE-754R 2008 5.3.1: nextUp/nextDown.
3689///
3690/// *NOTE* since nextDown(x) = -nextUp(-x), we only implement nextUp with
3691/// appropriate sign switching before/after the computation.
Tim Shen85de51d2016-10-25 19:55:59 +00003692IEEEFloat::opStatus IEEEFloat::next(bool nextDown) {
Michael Gottesman0c622ea2013-05-30 18:07:13 +00003693 // If we are performing nextDown, swap sign so we have -x.
3694 if (nextDown)
3695 changeSign();
3696
3697 // Compute nextUp(x)
3698 opStatus result = opOK;
3699
3700 // Handle each float category separately.
3701 switch (category) {
3702 case fcInfinity:
3703 // nextUp(+inf) = +inf
3704 if (!isNegative())
3705 break;
3706 // nextUp(-inf) = -getLargest()
3707 makeLargest(true);
3708 break;
3709 case fcNaN:
3710 // IEEE-754R 2008 6.2 Par 2: nextUp(sNaN) = qNaN. Set Invalid flag.
3711 // IEEE-754R 2008 6.2: nextUp(qNaN) = qNaN. Must be identity so we do not
3712 // change the payload.
3713 if (isSignaling()) {
3714 result = opInvalidOp;
Alp Tokercb402912014-01-24 17:20:08 +00003715 // For consistency, propagate the sign of the sNaN to the qNaN.
Craig Topperc10719f2014-04-07 04:17:22 +00003716 makeNaN(false, isNegative(), nullptr);
Michael Gottesman0c622ea2013-05-30 18:07:13 +00003717 }
3718 break;
3719 case fcZero:
3720 // nextUp(pm 0) = +getSmallest()
3721 makeSmallest(false);
3722 break;
3723 case fcNormal:
3724 // nextUp(-getSmallest()) = -0
3725 if (isSmallest() && isNegative()) {
3726 APInt::tcSet(significandParts(), 0, partCount());
3727 category = fcZero;
3728 exponent = 0;
3729 break;
3730 }
3731
3732 // nextUp(getLargest()) == INFINITY
3733 if (isLargest() && !isNegative()) {
3734 APInt::tcSet(significandParts(), 0, partCount());
3735 category = fcInfinity;
3736 exponent = semantics->maxExponent + 1;
3737 break;
3738 }
3739
3740 // nextUp(normal) == normal + inc.
3741 if (isNegative()) {
3742 // If we are negative, we need to decrement the significand.
3743
3744 // We only cross a binade boundary that requires adjusting the exponent
3745 // if:
3746 // 1. exponent != semantics->minExponent. This implies we are not in the
3747 // smallest binade or are dealing with denormals.
3748 // 2. Our significand excluding the integral bit is all zeros.
3749 bool WillCrossBinadeBoundary =
3750 exponent != semantics->minExponent && isSignificandAllZeros();
3751
3752 // Decrement the significand.
3753 //
3754 // We always do this since:
Alp Tokerf907b892013-12-05 05:44:44 +00003755 // 1. If we are dealing with a non-binade decrement, by definition we
Michael Gottesman0c622ea2013-05-30 18:07:13 +00003756 // just decrement the significand.
3757 // 2. If we are dealing with a normal -> normal binade decrement, since
3758 // we have an explicit integral bit the fact that all bits but the
3759 // integral bit are zero implies that subtracting one will yield a
3760 // significand with 0 integral bit and 1 in all other spots. Thus we
3761 // must just adjust the exponent and set the integral bit to 1.
3762 // 3. If we are dealing with a normal -> denormal binade decrement,
3763 // since we set the integral bit to 0 when we represent denormals, we
3764 // just decrement the significand.
3765 integerPart *Parts = significandParts();
3766 APInt::tcDecrement(Parts, partCount());
3767
3768 if (WillCrossBinadeBoundary) {
3769 // Our result is a normal number. Do the following:
3770 // 1. Set the integral bit to 1.
3771 // 2. Decrement the exponent.
3772 APInt::tcSetBit(Parts, semantics->precision - 1);
3773 exponent--;
3774 }
3775 } else {
3776 // If we are positive, we need to increment the significand.
3777
3778 // We only cross a binade boundary that requires adjusting the exponent if
3779 // the input is not a denormal and all of said input's significand bits
3780 // are set. If all of said conditions are true: clear the significand, set
3781 // the integral bit to 1, and increment the exponent. If we have a
3782 // denormal always increment since moving denormals and the numbers in the
3783 // smallest normal binade have the same exponent in our representation.
3784 bool WillCrossBinadeBoundary = !isDenormal() && isSignificandAllOnes();
3785
3786 if (WillCrossBinadeBoundary) {
3787 integerPart *Parts = significandParts();
3788 APInt::tcSet(Parts, 0, partCount());
3789 APInt::tcSetBit(Parts, semantics->precision - 1);
3790 assert(exponent != semantics->maxExponent &&
3791 "We can not increment an exponent beyond the maxExponent allowed"
3792 " by the given floating point semantics.");
3793 exponent++;
3794 } else {
3795 incrementSignificand();
3796 }
3797 }
3798 break;
3799 }
3800
3801 // If we are performing nextDown, swap sign so we have -nextUp(-x)
3802 if (nextDown)
3803 changeSign();
3804
3805 return result;
3806}
Michael Gottesmanc4facdf2013-06-24 09:58:02 +00003807
Tim Shen85de51d2016-10-25 19:55:59 +00003808void IEEEFloat::makeInf(bool Negative) {
Michael Gottesmanc4facdf2013-06-24 09:58:02 +00003809 category = fcInfinity;
3810 sign = Negative;
3811 exponent = semantics->maxExponent + 1;
3812 APInt::tcSet(significandParts(), 0, partCount());
3813}
3814
Tim Shen85de51d2016-10-25 19:55:59 +00003815void IEEEFloat::makeZero(bool Negative) {
Michael Gottesmanc4facdf2013-06-24 09:58:02 +00003816 category = fcZero;
3817 sign = Negative;
3818 exponent = semantics->minExponent-1;
Matt Arsenaultc25a7112016-03-21 16:49:16 +00003819 APInt::tcSet(significandParts(), 0, partCount());
3820}
3821
Tim Shen85de51d2016-10-25 19:55:59 +00003822void IEEEFloat::makeQuiet() {
Matt Arsenaultc25a7112016-03-21 16:49:16 +00003823 assert(isNaN());
3824 APInt::tcSetBit(significandParts(), semantics->precision - 2);
Michael Gottesmanc4facdf2013-06-24 09:58:02 +00003825}
Chandler Carruthd9edd1e2014-10-10 04:54:30 +00003826
Tim Shen85de51d2016-10-25 19:55:59 +00003827int ilogb(const IEEEFloat &Arg) {
Matt Arsenault69fdf9b2016-03-13 05:12:32 +00003828 if (Arg.isNaN())
Tim Shen85de51d2016-10-25 19:55:59 +00003829 return IEEEFloat::IEK_NaN;
Matt Arsenault69fdf9b2016-03-13 05:12:32 +00003830 if (Arg.isZero())
Tim Shen85de51d2016-10-25 19:55:59 +00003831 return IEEEFloat::IEK_Zero;
Matt Arsenault69fdf9b2016-03-13 05:12:32 +00003832 if (Arg.isInfinity())
Tim Shen85de51d2016-10-25 19:55:59 +00003833 return IEEEFloat::IEK_Inf;
Matt Arsenault69fdf9b2016-03-13 05:12:32 +00003834 if (!Arg.isDenormal())
3835 return Arg.exponent;
3836
Tim Shen85de51d2016-10-25 19:55:59 +00003837 IEEEFloat Normalized(Arg);
Matt Arsenault69fdf9b2016-03-13 05:12:32 +00003838 int SignificandBits = Arg.getSemantics().precision - 1;
3839
3840 Normalized.exponent += SignificandBits;
Tim Shen85de51d2016-10-25 19:55:59 +00003841 Normalized.normalize(IEEEFloat::rmNearestTiesToEven, lfExactlyZero);
Matt Arsenault69fdf9b2016-03-13 05:12:32 +00003842 return Normalized.exponent - SignificandBits;
3843}
3844
Tim Shen85de51d2016-10-25 19:55:59 +00003845IEEEFloat scalbn(IEEEFloat X, int Exp, IEEEFloat::roundingMode RoundingMode) {
Chandler Carruthd9edd1e2014-10-10 04:54:30 +00003846 auto MaxExp = X.getSemantics().maxExponent;
3847 auto MinExp = X.getSemantics().minExponent;
Chandler Carruthd9edd1e2014-10-10 04:54:30 +00003848
Matt Arsenaultafa31cf2016-03-13 05:11:51 +00003849 // If Exp is wildly out-of-scale, simply adding it to X.exponent will
3850 // overflow; clamp it to a safe range before adding, but ensure that the range
3851 // is large enough that the clamp does not change the result. The range we
3852 // need to support is the difference between the largest possible exponent and
3853 // the normalized exponent of half the smallest denormal.
3854
3855 int SignificandBits = X.getSemantics().precision - 1;
3856 int MaxIncrement = MaxExp - (MinExp - SignificandBits) + 1;
3857
3858 // Clamp to one past the range ends to let normalize handle overlflow.
3859 X.exponent += std::min(std::max(Exp, -MaxIncrement - 1), MaxIncrement);
3860 X.normalize(RoundingMode, lfExactlyZero);
Matt Arsenaultea00b492016-03-23 23:51:45 +00003861 if (X.isNaN())
3862 X.makeQuiet();
Richard Trieu6ae37962015-04-30 23:07:00 +00003863 return X;
Chandler Carruthd9edd1e2014-10-10 04:54:30 +00003864}
Matt Arsenaultc25a7112016-03-21 16:49:16 +00003865
Tim Shen85de51d2016-10-25 19:55:59 +00003866IEEEFloat frexp(const IEEEFloat &Val, int &Exp, IEEEFloat::roundingMode RM) {
Matt Arsenaultc25a7112016-03-21 16:49:16 +00003867 Exp = ilogb(Val);
3868
3869 // Quiet signalling nans.
Tim Shen85de51d2016-10-25 19:55:59 +00003870 if (Exp == IEEEFloat::IEK_NaN) {
3871 IEEEFloat Quiet(Val);
Matt Arsenaultc25a7112016-03-21 16:49:16 +00003872 Quiet.makeQuiet();
3873 return Quiet;
3874 }
3875
Tim Shen85de51d2016-10-25 19:55:59 +00003876 if (Exp == IEEEFloat::IEK_Inf)
Matt Arsenaultc25a7112016-03-21 16:49:16 +00003877 return Val;
3878
3879 // 1 is added because frexp is defined to return a normalized fraction in
3880 // +/-[0.5, 1.0), rather than the usual +/-[1.0, 2.0).
Tim Shen85de51d2016-10-25 19:55:59 +00003881 Exp = Exp == IEEEFloat::IEK_Zero ? 0 : Exp + 1;
Matt Arsenaultc25a7112016-03-21 16:49:16 +00003882 return scalbn(Val, -Exp, RM);
3883}
Tim Shen85de51d2016-10-25 19:55:59 +00003884
Tim Shen139a58f2016-10-27 22:52:40 +00003885DoubleAPFloat::DoubleAPFloat(const fltSemantics &S)
Tim Shenfd1e5aa2017-01-23 22:39:35 +00003886 : Semantics(&S),
3887 Floats(new APFloat[2]{APFloat(semIEEEdouble), APFloat(semIEEEdouble)}) {
Stephan Bergmann17c7f702016-12-14 11:57:17 +00003888 assert(Semantics == &semPPCDoubleDouble);
Tim Shen139a58f2016-10-27 22:52:40 +00003889}
3890
3891DoubleAPFloat::DoubleAPFloat(const fltSemantics &S, uninitializedTag)
3892 : Semantics(&S),
Tim Shenfd1e5aa2017-01-23 22:39:35 +00003893 Floats(new APFloat[2]{APFloat(semIEEEdouble, uninitialized),
Stephan Bergmann17c7f702016-12-14 11:57:17 +00003894 APFloat(semIEEEdouble, uninitialized)}) {
3895 assert(Semantics == &semPPCDoubleDouble);
Tim Shen139a58f2016-10-27 22:52:40 +00003896}
3897
3898DoubleAPFloat::DoubleAPFloat(const fltSemantics &S, integerPart I)
Tim Shenfd1e5aa2017-01-23 22:39:35 +00003899 : Semantics(&S), Floats(new APFloat[2]{APFloat(semIEEEdouble, I),
Stephan Bergmann17c7f702016-12-14 11:57:17 +00003900 APFloat(semIEEEdouble)}) {
3901 assert(Semantics == &semPPCDoubleDouble);
Tim Shen139a58f2016-10-27 22:52:40 +00003902}
3903
3904DoubleAPFloat::DoubleAPFloat(const fltSemantics &S, const APInt &I)
Tim Shenfd1e5aa2017-01-23 22:39:35 +00003905 : Semantics(&S),
3906 Floats(new APFloat[2]{
3907 APFloat(semIEEEdouble, APInt(64, I.getRawData()[0])),
3908 APFloat(semIEEEdouble, APInt(64, I.getRawData()[1]))}) {
Stephan Bergmann17c7f702016-12-14 11:57:17 +00003909 assert(Semantics == &semPPCDoubleDouble);
Tim Shen139a58f2016-10-27 22:52:40 +00003910}
3911
3912DoubleAPFloat::DoubleAPFloat(const fltSemantics &S, APFloat &&First,
3913 APFloat &&Second)
3914 : Semantics(&S),
3915 Floats(new APFloat[2]{std::move(First), std::move(Second)}) {
Stephan Bergmann17c7f702016-12-14 11:57:17 +00003916 assert(Semantics == &semPPCDoubleDouble);
Tim Shenfd1e5aa2017-01-23 22:39:35 +00003917 assert(&Floats[0].getSemantics() == &semIEEEdouble);
Stephan Bergmann17c7f702016-12-14 11:57:17 +00003918 assert(&Floats[1].getSemantics() == &semIEEEdouble);
Tim Shen139a58f2016-10-27 22:52:40 +00003919}
3920
3921DoubleAPFloat::DoubleAPFloat(const DoubleAPFloat &RHS)
3922 : Semantics(RHS.Semantics),
Tim Shenb49915482016-10-28 22:45:33 +00003923 Floats(RHS.Floats ? new APFloat[2]{APFloat(RHS.Floats[0]),
3924 APFloat(RHS.Floats[1])}
3925 : nullptr) {
Stephan Bergmann17c7f702016-12-14 11:57:17 +00003926 assert(Semantics == &semPPCDoubleDouble);
Tim Shen139a58f2016-10-27 22:52:40 +00003927}
3928
3929DoubleAPFloat::DoubleAPFloat(DoubleAPFloat &&RHS)
3930 : Semantics(RHS.Semantics), Floats(std::move(RHS.Floats)) {
Stephan Bergmann17c7f702016-12-14 11:57:17 +00003931 RHS.Semantics = &semBogus;
3932 assert(Semantics == &semPPCDoubleDouble);
Tim Shen139a58f2016-10-27 22:52:40 +00003933}
3934
3935DoubleAPFloat &DoubleAPFloat::operator=(const DoubleAPFloat &RHS) {
Tim Shenb49915482016-10-28 22:45:33 +00003936 if (Semantics == RHS.Semantics && RHS.Floats) {
Tim Shen139a58f2016-10-27 22:52:40 +00003937 Floats[0] = RHS.Floats[0];
3938 Floats[1] = RHS.Floats[1];
3939 } else if (this != &RHS) {
3940 this->~DoubleAPFloat();
3941 new (this) DoubleAPFloat(RHS);
3942 }
3943 return *this;
3944}
3945
Tim Shen7f127622017-01-24 00:19:45 +00003946// Implement addition, subtraction, multiplication and division based on:
Tim Shen44bde892016-12-12 21:59:30 +00003947// "Software for Doubled-Precision Floating-Point Computations",
3948// by Seppo Linnainmaa, ACM TOMS vol 7 no 3, September 1981, pages 272-283.
3949APFloat::opStatus DoubleAPFloat::addImpl(const APFloat &a, const APFloat &aa,
3950 const APFloat &c, const APFloat &cc,
3951 roundingMode RM) {
3952 int Status = opOK;
3953 APFloat z = a;
3954 Status |= z.add(c, RM);
3955 if (!z.isFinite()) {
3956 if (!z.isInfinity()) {
3957 Floats[0] = std::move(z);
Tim Shen7117e692017-01-26 00:11:07 +00003958 Floats[1].makeZero(/* Neg = */ false);
Tim Shen44bde892016-12-12 21:59:30 +00003959 return (opStatus)Status;
3960 }
3961 Status = opOK;
3962 auto AComparedToC = a.compareAbsoluteValue(c);
3963 z = cc;
3964 Status |= z.add(aa, RM);
3965 if (AComparedToC == APFloat::cmpGreaterThan) {
3966 // z = cc + aa + c + a;
3967 Status |= z.add(c, RM);
3968 Status |= z.add(a, RM);
3969 } else {
3970 // z = cc + aa + a + c;
3971 Status |= z.add(a, RM);
3972 Status |= z.add(c, RM);
3973 }
3974 if (!z.isFinite()) {
3975 Floats[0] = std::move(z);
Tim Shen7117e692017-01-26 00:11:07 +00003976 Floats[1].makeZero(/* Neg = */ false);
Tim Shen44bde892016-12-12 21:59:30 +00003977 return (opStatus)Status;
3978 }
3979 Floats[0] = z;
3980 APFloat zz = aa;
3981 Status |= zz.add(cc, RM);
3982 if (AComparedToC == APFloat::cmpGreaterThan) {
3983 // Floats[1] = a - z + c + zz;
3984 Floats[1] = a;
3985 Status |= Floats[1].subtract(z, RM);
3986 Status |= Floats[1].add(c, RM);
3987 Status |= Floats[1].add(zz, RM);
3988 } else {
3989 // Floats[1] = c - z + a + zz;
3990 Floats[1] = c;
3991 Status |= Floats[1].subtract(z, RM);
3992 Status |= Floats[1].add(a, RM);
3993 Status |= Floats[1].add(zz, RM);
3994 }
3995 } else {
3996 // q = a - z;
3997 APFloat q = a;
3998 Status |= q.subtract(z, RM);
3999
4000 // zz = q + c + (a - (q + z)) + aa + cc;
4001 // Compute a - (q + z) as -((q + z) - a) to avoid temporary copies.
4002 auto zz = q;
4003 Status |= zz.add(c, RM);
4004 Status |= q.add(z, RM);
4005 Status |= q.subtract(a, RM);
4006 q.changeSign();
4007 Status |= zz.add(q, RM);
4008 Status |= zz.add(aa, RM);
4009 Status |= zz.add(cc, RM);
4010 if (zz.isZero() && !zz.isNegative()) {
4011 Floats[0] = std::move(z);
Tim Shen7117e692017-01-26 00:11:07 +00004012 Floats[1].makeZero(/* Neg = */ false);
Tim Shen44bde892016-12-12 21:59:30 +00004013 return opOK;
4014 }
4015 Floats[0] = z;
4016 Status |= Floats[0].add(zz, RM);
4017 if (!Floats[0].isFinite()) {
Tim Shen7117e692017-01-26 00:11:07 +00004018 Floats[1].makeZero(/* Neg = */ false);
Tim Shen44bde892016-12-12 21:59:30 +00004019 return (opStatus)Status;
4020 }
4021 Floats[1] = std::move(z);
4022 Status |= Floats[1].subtract(Floats[0], RM);
4023 Status |= Floats[1].add(zz, RM);
4024 }
4025 return (opStatus)Status;
4026}
4027
4028APFloat::opStatus DoubleAPFloat::addWithSpecial(const DoubleAPFloat &LHS,
4029 const DoubleAPFloat &RHS,
4030 DoubleAPFloat &Out,
4031 roundingMode RM) {
4032 if (LHS.getCategory() == fcNaN) {
4033 Out = LHS;
4034 return opOK;
4035 }
4036 if (RHS.getCategory() == fcNaN) {
4037 Out = RHS;
4038 return opOK;
4039 }
4040 if (LHS.getCategory() == fcZero) {
4041 Out = RHS;
4042 return opOK;
4043 }
4044 if (RHS.getCategory() == fcZero) {
4045 Out = LHS;
4046 return opOK;
4047 }
4048 if (LHS.getCategory() == fcInfinity && RHS.getCategory() == fcInfinity &&
4049 LHS.isNegative() != RHS.isNegative()) {
4050 Out.makeNaN(false, Out.isNegative(), nullptr);
4051 return opInvalidOp;
4052 }
4053 if (LHS.getCategory() == fcInfinity) {
4054 Out = LHS;
4055 return opOK;
4056 }
4057 if (RHS.getCategory() == fcInfinity) {
4058 Out = RHS;
4059 return opOK;
4060 }
4061 assert(LHS.getCategory() == fcNormal && RHS.getCategory() == fcNormal);
4062
Tim Shenfd1e5aa2017-01-23 22:39:35 +00004063 APFloat A(LHS.Floats[0]), AA(LHS.Floats[1]), C(RHS.Floats[0]),
Tim Shen44bde892016-12-12 21:59:30 +00004064 CC(RHS.Floats[1]);
Tim Shenfd1e5aa2017-01-23 22:39:35 +00004065 assert(&A.getSemantics() == &semIEEEdouble);
Stephan Bergmann17c7f702016-12-14 11:57:17 +00004066 assert(&AA.getSemantics() == &semIEEEdouble);
Tim Shenfd1e5aa2017-01-23 22:39:35 +00004067 assert(&C.getSemantics() == &semIEEEdouble);
Stephan Bergmann17c7f702016-12-14 11:57:17 +00004068 assert(&CC.getSemantics() == &semIEEEdouble);
Tim Shenfd1e5aa2017-01-23 22:39:35 +00004069 assert(&Out.Floats[0].getSemantics() == &semIEEEdouble);
Stephan Bergmann17c7f702016-12-14 11:57:17 +00004070 assert(&Out.Floats[1].getSemantics() == &semIEEEdouble);
Tim Shenfd1e5aa2017-01-23 22:39:35 +00004071 return Out.addImpl(A, AA, C, CC, RM);
Tim Shen44bde892016-12-12 21:59:30 +00004072}
4073
4074APFloat::opStatus DoubleAPFloat::add(const DoubleAPFloat &RHS,
4075 roundingMode RM) {
4076 return addWithSpecial(*this, RHS, *this, RM);
4077}
4078
4079APFloat::opStatus DoubleAPFloat::subtract(const DoubleAPFloat &RHS,
4080 roundingMode RM) {
4081 changeSign();
4082 auto Ret = add(RHS, RM);
4083 changeSign();
4084 return Ret;
4085}
4086
Tim Shenfd1e5aa2017-01-23 22:39:35 +00004087APFloat::opStatus DoubleAPFloat::multiply(const DoubleAPFloat &RHS,
4088 APFloat::roundingMode RM) {
Tim Shen7f127622017-01-24 00:19:45 +00004089 const auto &LHS = *this;
4090 auto &Out = *this;
4091 /* Interesting observation: For special categories, finding the lowest
4092 common ancestor of the following layered graph gives the correct
4093 return category:
4094
4095 NaN
4096 / \
4097 Zero Inf
4098 \ /
4099 Normal
4100
4101 e.g. NaN * NaN = NaN
4102 Zero * Inf = NaN
4103 Normal * Zero = Zero
4104 Normal * Inf = Inf
4105 */
4106 if (LHS.getCategory() == fcNaN) {
4107 Out = LHS;
4108 return opOK;
4109 }
4110 if (RHS.getCategory() == fcNaN) {
4111 Out = RHS;
4112 return opOK;
4113 }
4114 if ((LHS.getCategory() == fcZero && RHS.getCategory() == fcInfinity) ||
4115 (LHS.getCategory() == fcInfinity && RHS.getCategory() == fcZero)) {
4116 Out.makeNaN(false, false, nullptr);
4117 return opOK;
4118 }
4119 if (LHS.getCategory() == fcZero || LHS.getCategory() == fcInfinity) {
4120 Out = LHS;
4121 return opOK;
4122 }
4123 if (RHS.getCategory() == fcZero || RHS.getCategory() == fcInfinity) {
4124 Out = RHS;
4125 return opOK;
4126 }
4127 assert(LHS.getCategory() == fcNormal && RHS.getCategory() == fcNormal &&
4128 "Special cases not handled exhaustively");
4129
4130 int Status = opOK;
4131 APFloat A = Floats[0], B = Floats[1], C = RHS.Floats[0], D = RHS.Floats[1];
4132 // t = a * c
4133 APFloat T = A;
4134 Status |= T.multiply(C, RM);
4135 if (!T.isFiniteNonZero()) {
4136 Floats[0] = T;
Tim Shen7117e692017-01-26 00:11:07 +00004137 Floats[1].makeZero(/* Neg = */ false);
Tim Shen7f127622017-01-24 00:19:45 +00004138 return (opStatus)Status;
4139 }
4140
4141 // tau = fmsub(a, c, t), that is -fmadd(-a, c, t).
4142 APFloat Tau = A;
4143 T.changeSign();
4144 Status |= Tau.fusedMultiplyAdd(C, T, RM);
4145 T.changeSign();
4146 {
4147 // v = a * d
4148 APFloat V = A;
4149 Status |= V.multiply(D, RM);
4150 // w = b * c
4151 APFloat W = B;
4152 Status |= W.multiply(C, RM);
4153 Status |= V.add(W, RM);
4154 // tau += v + w
4155 Status |= Tau.add(V, RM);
4156 }
4157 // u = t + tau
4158 APFloat U = T;
4159 Status |= U.add(Tau, RM);
4160
4161 Floats[0] = U;
4162 if (!U.isFinite()) {
Tim Shen7117e692017-01-26 00:11:07 +00004163 Floats[1].makeZero(/* Neg = */ false);
Tim Shen7f127622017-01-24 00:19:45 +00004164 } else {
4165 // Floats[1] = (t - u) + tau
4166 Status |= T.subtract(U, RM);
4167 Status |= T.add(Tau, RM);
4168 Floats[1] = T;
4169 }
4170 return (opStatus)Status;
Tim Shenfd1e5aa2017-01-23 22:39:35 +00004171}
4172
4173APFloat::opStatus DoubleAPFloat::divide(const DoubleAPFloat &RHS,
4174 APFloat::roundingMode RM) {
4175 assert(Semantics == &semPPCDoubleDouble && "Unexpected Semantics");
4176 APFloat Tmp(semPPCDoubleDoubleLegacy, bitcastToAPInt());
4177 auto Ret =
4178 Tmp.divide(APFloat(semPPCDoubleDoubleLegacy, RHS.bitcastToAPInt()), RM);
4179 *this = DoubleAPFloat(semPPCDoubleDouble, Tmp.bitcastToAPInt());
4180 return Ret;
4181}
4182
4183APFloat::opStatus DoubleAPFloat::remainder(const DoubleAPFloat &RHS) {
4184 assert(Semantics == &semPPCDoubleDouble && "Unexpected Semantics");
4185 APFloat Tmp(semPPCDoubleDoubleLegacy, bitcastToAPInt());
4186 auto Ret =
4187 Tmp.remainder(APFloat(semPPCDoubleDoubleLegacy, RHS.bitcastToAPInt()));
4188 *this = DoubleAPFloat(semPPCDoubleDouble, Tmp.bitcastToAPInt());
4189 return Ret;
4190}
4191
4192APFloat::opStatus DoubleAPFloat::mod(const DoubleAPFloat &RHS) {
4193 assert(Semantics == &semPPCDoubleDouble && "Unexpected Semantics");
4194 APFloat Tmp(semPPCDoubleDoubleLegacy, bitcastToAPInt());
4195 auto Ret = Tmp.mod(APFloat(semPPCDoubleDoubleLegacy, RHS.bitcastToAPInt()));
4196 *this = DoubleAPFloat(semPPCDoubleDouble, Tmp.bitcastToAPInt());
4197 return Ret;
4198}
4199
4200APFloat::opStatus
4201DoubleAPFloat::fusedMultiplyAdd(const DoubleAPFloat &Multiplicand,
4202 const DoubleAPFloat &Addend,
4203 APFloat::roundingMode RM) {
4204 assert(Semantics == &semPPCDoubleDouble && "Unexpected Semantics");
4205 APFloat Tmp(semPPCDoubleDoubleLegacy, bitcastToAPInt());
4206 auto Ret = Tmp.fusedMultiplyAdd(
4207 APFloat(semPPCDoubleDoubleLegacy, Multiplicand.bitcastToAPInt()),
4208 APFloat(semPPCDoubleDoubleLegacy, Addend.bitcastToAPInt()), RM);
4209 *this = DoubleAPFloat(semPPCDoubleDouble, Tmp.bitcastToAPInt());
4210 return Ret;
4211}
4212
4213APFloat::opStatus DoubleAPFloat::roundToIntegral(APFloat::roundingMode RM) {
4214 assert(Semantics == &semPPCDoubleDouble && "Unexpected Semantics");
4215 APFloat Tmp(semPPCDoubleDoubleLegacy, bitcastToAPInt());
4216 auto Ret = Tmp.roundToIntegral(RM);
4217 *this = DoubleAPFloat(semPPCDoubleDouble, Tmp.bitcastToAPInt());
4218 return Ret;
4219}
4220
Tim Shen44bde892016-12-12 21:59:30 +00004221void DoubleAPFloat::changeSign() {
4222 Floats[0].changeSign();
4223 Floats[1].changeSign();
4224}
4225
4226APFloat::cmpResult
4227DoubleAPFloat::compareAbsoluteValue(const DoubleAPFloat &RHS) const {
4228 auto Result = Floats[0].compareAbsoluteValue(RHS.Floats[0]);
4229 if (Result != cmpEqual)
4230 return Result;
4231 Result = Floats[1].compareAbsoluteValue(RHS.Floats[1]);
4232 if (Result == cmpLessThan || Result == cmpGreaterThan) {
4233 auto Against = Floats[0].isNegative() ^ Floats[1].isNegative();
4234 auto RHSAgainst = RHS.Floats[0].isNegative() ^ RHS.Floats[1].isNegative();
4235 if (Against && !RHSAgainst)
4236 return cmpLessThan;
4237 if (!Against && RHSAgainst)
4238 return cmpGreaterThan;
4239 if (!Against && !RHSAgainst)
4240 return Result;
4241 if (Against && RHSAgainst)
4242 return (cmpResult)(cmpLessThan + cmpGreaterThan - Result);
4243 }
4244 return Result;
4245}
4246
4247APFloat::fltCategory DoubleAPFloat::getCategory() const {
4248 return Floats[0].getCategory();
4249}
4250
4251bool DoubleAPFloat::isNegative() const { return Floats[0].isNegative(); }
4252
4253void DoubleAPFloat::makeInf(bool Neg) {
4254 Floats[0].makeInf(Neg);
Tim Shen7117e692017-01-26 00:11:07 +00004255 Floats[1].makeZero(/* Neg = */ false);
Tim Shen44bde892016-12-12 21:59:30 +00004256}
4257
Tim Shenfd1e5aa2017-01-23 22:39:35 +00004258void DoubleAPFloat::makeZero(bool Neg) {
4259 Floats[0].makeZero(Neg);
Tim Shen7117e692017-01-26 00:11:07 +00004260 Floats[1].makeZero(/* Neg = */ false);
Tim Shenfd1e5aa2017-01-23 22:39:35 +00004261}
4262
4263void DoubleAPFloat::makeLargest(bool Neg) {
4264 assert(Semantics == &semPPCDoubleDouble && "Unexpected Semantics");
4265 Floats[0] = APFloat(semIEEEdouble, APInt(64, 0x7fefffffffffffffull));
4266 Floats[1] = APFloat(semIEEEdouble, APInt(64, 0x7c8ffffffffffffeull));
4267 if (Neg)
4268 changeSign();
4269}
4270
4271void DoubleAPFloat::makeSmallest(bool Neg) {
4272 assert(Semantics == &semPPCDoubleDouble && "Unexpected Semantics");
4273 Floats[0].makeSmallest(Neg);
Tim Shen7117e692017-01-26 00:11:07 +00004274 Floats[1].makeZero(/* Neg = */ false);
Tim Shenfd1e5aa2017-01-23 22:39:35 +00004275}
4276
4277void DoubleAPFloat::makeSmallestNormalized(bool Neg) {
4278 assert(Semantics == &semPPCDoubleDouble && "Unexpected Semantics");
4279 Floats[0] = APFloat(semIEEEdouble, APInt(64, 0x0360000000000000ull));
4280 if (Neg)
4281 Floats[0].changeSign();
Tim Shen7117e692017-01-26 00:11:07 +00004282 Floats[1].makeZero(/* Neg = */ false);
Tim Shenfd1e5aa2017-01-23 22:39:35 +00004283}
4284
Tim Shen44bde892016-12-12 21:59:30 +00004285void DoubleAPFloat::makeNaN(bool SNaN, bool Neg, const APInt *fill) {
4286 Floats[0].makeNaN(SNaN, Neg, fill);
Tim Shen7117e692017-01-26 00:11:07 +00004287 Floats[1].makeZero(/* Neg = */ false);
Tim Shen44bde892016-12-12 21:59:30 +00004288}
4289
Tim Shenfd1e5aa2017-01-23 22:39:35 +00004290APFloat::cmpResult DoubleAPFloat::compare(const DoubleAPFloat &RHS) const {
4291 auto Result = Floats[0].compare(RHS.Floats[0]);
Tim Shen7117e692017-01-26 00:11:07 +00004292 // |Float[0]| > |Float[1]|
Tim Shenfd1e5aa2017-01-23 22:39:35 +00004293 if (Result == APFloat::cmpEqual)
4294 return Floats[1].compare(RHS.Floats[1]);
4295 return Result;
4296}
4297
4298bool DoubleAPFloat::bitwiseIsEqual(const DoubleAPFloat &RHS) const {
4299 return Floats[0].bitwiseIsEqual(RHS.Floats[0]) &&
4300 Floats[1].bitwiseIsEqual(RHS.Floats[1]);
4301}
4302
4303hash_code hash_value(const DoubleAPFloat &Arg) {
4304 if (Arg.Floats)
4305 return hash_combine(hash_value(Arg.Floats[0]), hash_value(Arg.Floats[1]));
4306 return hash_combine(Arg.Semantics);
4307}
4308
4309APInt DoubleAPFloat::bitcastToAPInt() const {
4310 assert(Semantics == &semPPCDoubleDouble && "Unexpected Semantics");
4311 uint64_t Data[] = {
4312 Floats[0].bitcastToAPInt().getRawData()[0],
4313 Floats[1].bitcastToAPInt().getRawData()[0],
4314 };
4315 return APInt(128, 2, Data);
4316}
4317
4318APFloat::opStatus DoubleAPFloat::convertFromString(StringRef S,
4319 roundingMode RM) {
4320 assert(Semantics == &semPPCDoubleDouble && "Unexpected Semantics");
4321 APFloat Tmp(semPPCDoubleDoubleLegacy);
4322 auto Ret = Tmp.convertFromString(S, RM);
4323 *this = DoubleAPFloat(semPPCDoubleDouble, Tmp.bitcastToAPInt());
4324 return Ret;
4325}
4326
4327APFloat::opStatus DoubleAPFloat::next(bool nextDown) {
4328 assert(Semantics == &semPPCDoubleDouble && "Unexpected Semantics");
4329 APFloat Tmp(semPPCDoubleDoubleLegacy, bitcastToAPInt());
4330 auto Ret = Tmp.next(nextDown);
4331 *this = DoubleAPFloat(semPPCDoubleDouble, Tmp.bitcastToAPInt());
4332 return Ret;
4333}
4334
Simon Pilgrim00b34992017-03-20 14:40:12 +00004335APFloat::opStatus
4336DoubleAPFloat::convertToInteger(MutableArrayRef<integerPart> Input,
4337 unsigned int Width, bool IsSigned,
4338 roundingMode RM, bool *IsExact) const {
Tim Shenfd1e5aa2017-01-23 22:39:35 +00004339 assert(Semantics == &semPPCDoubleDouble && "Unexpected Semantics");
4340 return APFloat(semPPCDoubleDoubleLegacy, bitcastToAPInt())
4341 .convertToInteger(Input, Width, IsSigned, RM, IsExact);
4342}
4343
4344APFloat::opStatus DoubleAPFloat::convertFromAPInt(const APInt &Input,
4345 bool IsSigned,
4346 roundingMode RM) {
4347 assert(Semantics == &semPPCDoubleDouble && "Unexpected Semantics");
4348 APFloat Tmp(semPPCDoubleDoubleLegacy);
4349 auto Ret = Tmp.convertFromAPInt(Input, IsSigned, RM);
4350 *this = DoubleAPFloat(semPPCDoubleDouble, Tmp.bitcastToAPInt());
4351 return Ret;
4352}
4353
4354APFloat::opStatus
4355DoubleAPFloat::convertFromSignExtendedInteger(const integerPart *Input,
4356 unsigned int InputSize,
4357 bool IsSigned, roundingMode RM) {
4358 assert(Semantics == &semPPCDoubleDouble && "Unexpected Semantics");
4359 APFloat Tmp(semPPCDoubleDoubleLegacy);
4360 auto Ret = Tmp.convertFromSignExtendedInteger(Input, InputSize, IsSigned, RM);
4361 *this = DoubleAPFloat(semPPCDoubleDouble, Tmp.bitcastToAPInt());
4362 return Ret;
4363}
4364
4365APFloat::opStatus
4366DoubleAPFloat::convertFromZeroExtendedInteger(const integerPart *Input,
4367 unsigned int InputSize,
4368 bool IsSigned, roundingMode RM) {
4369 assert(Semantics == &semPPCDoubleDouble && "Unexpected Semantics");
4370 APFloat Tmp(semPPCDoubleDoubleLegacy);
4371 auto Ret = Tmp.convertFromZeroExtendedInteger(Input, InputSize, IsSigned, RM);
4372 *this = DoubleAPFloat(semPPCDoubleDouble, Tmp.bitcastToAPInt());
4373 return Ret;
4374}
4375
4376unsigned int DoubleAPFloat::convertToHexString(char *DST,
4377 unsigned int HexDigits,
4378 bool UpperCase,
4379 roundingMode RM) const {
4380 assert(Semantics == &semPPCDoubleDouble && "Unexpected Semantics");
4381 return APFloat(semPPCDoubleDoubleLegacy, bitcastToAPInt())
4382 .convertToHexString(DST, HexDigits, UpperCase, RM);
4383}
4384
4385bool DoubleAPFloat::isDenormal() const {
4386 return getCategory() == fcNormal &&
4387 (Floats[0].isDenormal() || Floats[1].isDenormal() ||
Tim Shen7117e692017-01-26 00:11:07 +00004388 // (double)(Hi + Lo) == Hi defines a normal number.
Tim Shenfd1e5aa2017-01-23 22:39:35 +00004389 Floats[0].compare(Floats[0] + Floats[1]) != cmpEqual);
4390}
4391
4392bool DoubleAPFloat::isSmallest() const {
4393 if (getCategory() != fcNormal)
4394 return false;
4395 DoubleAPFloat Tmp(*this);
4396 Tmp.makeSmallest(this->isNegative());
4397 return Tmp.compare(*this) == cmpEqual;
4398}
4399
4400bool DoubleAPFloat::isLargest() const {
4401 if (getCategory() != fcNormal)
4402 return false;
4403 DoubleAPFloat Tmp(*this);
4404 Tmp.makeLargest(this->isNegative());
4405 return Tmp.compare(*this) == cmpEqual;
4406}
4407
4408bool DoubleAPFloat::isInteger() const {
4409 assert(Semantics == &semPPCDoubleDouble && "Unexpected Semantics");
Davide Italiano5a2530d2017-08-21 16:51:54 +00004410 return Floats[0].isInteger() && Floats[1].isInteger();
Tim Shenfd1e5aa2017-01-23 22:39:35 +00004411}
4412
4413void DoubleAPFloat::toString(SmallVectorImpl<char> &Str,
4414 unsigned FormatPrecision,
Serguei Katkov3a46eb42017-04-21 02:52:17 +00004415 unsigned FormatMaxPadding,
4416 bool TruncateZero) const {
Tim Shenfd1e5aa2017-01-23 22:39:35 +00004417 assert(Semantics == &semPPCDoubleDouble && "Unexpected Semantics");
4418 APFloat(semPPCDoubleDoubleLegacy, bitcastToAPInt())
Serguei Katkov3a46eb42017-04-21 02:52:17 +00004419 .toString(Str, FormatPrecision, FormatMaxPadding, TruncateZero);
Tim Shenfd1e5aa2017-01-23 22:39:35 +00004420}
4421
4422bool DoubleAPFloat::getExactInverse(APFloat *inv) const {
4423 assert(Semantics == &semPPCDoubleDouble && "Unexpected Semantics");
4424 APFloat Tmp(semPPCDoubleDoubleLegacy, bitcastToAPInt());
4425 if (!inv)
4426 return Tmp.getExactInverse(nullptr);
4427 APFloat Inv(semPPCDoubleDoubleLegacy);
4428 auto Ret = Tmp.getExactInverse(&Inv);
4429 *inv = APFloat(semPPCDoubleDouble, Inv.bitcastToAPInt());
4430 return Ret;
4431}
4432
4433DoubleAPFloat scalbn(DoubleAPFloat Arg, int Exp, APFloat::roundingMode RM) {
4434 assert(Arg.Semantics == &semPPCDoubleDouble && "Unexpected Semantics");
4435 return DoubleAPFloat(semPPCDoubleDouble, scalbn(Arg.Floats[0], Exp, RM),
4436 scalbn(Arg.Floats[1], Exp, RM));
4437}
4438
4439DoubleAPFloat frexp(const DoubleAPFloat &Arg, int &Exp,
4440 APFloat::roundingMode RM) {
4441 assert(Arg.Semantics == &semPPCDoubleDouble && "Unexpected Semantics");
4442 APFloat First = frexp(Arg.Floats[0], Exp, RM);
4443 APFloat Second = Arg.Floats[1];
4444 if (Arg.getCategory() == APFloat::fcNormal)
4445 Second = scalbn(Second, -Exp, RM);
4446 return DoubleAPFloat(semPPCDoubleDouble, std::move(First), std::move(Second));
4447}
4448
Tim Shen85de51d2016-10-25 19:55:59 +00004449} // End detail namespace
4450
Tim Shen398f90f2016-11-06 07:38:37 +00004451APFloat::Storage::Storage(IEEEFloat F, const fltSemantics &Semantics) {
4452 if (usesLayout<IEEEFloat>(Semantics)) {
4453 new (&IEEE) IEEEFloat(std::move(F));
Tim Shen7b57ac42016-12-21 02:39:21 +00004454 return;
4455 }
4456 if (usesLayout<DoubleAPFloat>(Semantics)) {
Nick Desaulniers7ddd6942019-06-07 19:51:22 +00004457 const fltSemantics& S = F.getSemantics();
Simon Pilgrim2dd6a0c2019-05-15 13:03:10 +00004458 new (&Double)
Nick Desaulniers7ddd6942019-06-07 19:51:22 +00004459 DoubleAPFloat(Semantics, APFloat(std::move(F), S),
Simon Pilgrim2dd6a0c2019-05-15 13:03:10 +00004460 APFloat(semIEEEdouble));
Tim Shen7b57ac42016-12-21 02:39:21 +00004461 return;
Tim Shen398f90f2016-11-06 07:38:37 +00004462 }
Tim Shen7b57ac42016-12-21 02:39:21 +00004463 llvm_unreachable("Unexpected semantics");
Tim Shen398f90f2016-11-06 07:38:37 +00004464}
4465
Tim Shen85de51d2016-10-25 19:55:59 +00004466APFloat::opStatus APFloat::convertFromString(StringRef Str, roundingMode RM) {
Tim Shen601ba8c2017-01-27 02:11:07 +00004467 APFLOAT_DISPATCH_ON_SEMANTICS(convertFromString(Str, RM));
Tim Shen85de51d2016-10-25 19:55:59 +00004468}
4469
Tim Shenfd1e5aa2017-01-23 22:39:35 +00004470hash_code hash_value(const APFloat &Arg) {
4471 if (APFloat::usesLayout<detail::IEEEFloat>(Arg.getSemantics()))
4472 return hash_value(Arg.U.IEEE);
4473 if (APFloat::usesLayout<detail::DoubleAPFloat>(Arg.getSemantics()))
4474 return hash_value(Arg.U.Double);
4475 llvm_unreachable("Unexpected semantics");
4476}
Tim Shen85de51d2016-10-25 19:55:59 +00004477
4478APFloat::APFloat(const fltSemantics &Semantics, StringRef S)
Tim Shen139a58f2016-10-27 22:52:40 +00004479 : APFloat(Semantics) {
4480 convertFromString(S, rmNearestTiesToEven);
4481}
4482
4483APFloat::opStatus APFloat::convert(const fltSemantics &ToSemantics,
4484 roundingMode RM, bool *losesInfo) {
Sven van Haastregt5ad5c3c2018-05-11 09:45:42 +00004485 if (&getSemantics() == &ToSemantics) {
4486 *losesInfo = false;
Tim Shen139a58f2016-10-27 22:52:40 +00004487 return opOK;
Sven van Haastregt5ad5c3c2018-05-11 09:45:42 +00004488 }
Tim Shen139a58f2016-10-27 22:52:40 +00004489 if (usesLayout<IEEEFloat>(getSemantics()) &&
Tim Shen7b57ac42016-12-21 02:39:21 +00004490 usesLayout<IEEEFloat>(ToSemantics))
Tim Shen139a58f2016-10-27 22:52:40 +00004491 return U.IEEE.convert(ToSemantics, RM, losesInfo);
Tim Shen7b57ac42016-12-21 02:39:21 +00004492 if (usesLayout<IEEEFloat>(getSemantics()) &&
4493 usesLayout<DoubleAPFloat>(ToSemantics)) {
Stephan Bergmann17c7f702016-12-14 11:57:17 +00004494 assert(&ToSemantics == &semPPCDoubleDouble);
Tim Shenfd1e5aa2017-01-23 22:39:35 +00004495 auto Ret = U.IEEE.convert(semPPCDoubleDoubleLegacy, RM, losesInfo);
4496 *this = APFloat(ToSemantics, U.IEEE.bitcastToAPInt());
Tim Shen139a58f2016-10-27 22:52:40 +00004497 return Ret;
Tim Shen7b57ac42016-12-21 02:39:21 +00004498 }
4499 if (usesLayout<DoubleAPFloat>(getSemantics()) &&
4500 usesLayout<IEEEFloat>(ToSemantics)) {
Tim Shen139a58f2016-10-27 22:52:40 +00004501 auto Ret = getIEEE().convert(ToSemantics, RM, losesInfo);
Tim Shen398f90f2016-11-06 07:38:37 +00004502 *this = APFloat(std::move(getIEEE()), ToSemantics);
Tim Shen139a58f2016-10-27 22:52:40 +00004503 return Ret;
Tim Shen139a58f2016-10-27 22:52:40 +00004504 }
Tim Shen7b57ac42016-12-21 02:39:21 +00004505 llvm_unreachable("Unexpected semantics");
Tim Shen139a58f2016-10-27 22:52:40 +00004506}
Tim Shen85de51d2016-10-25 19:55:59 +00004507
Tim Shen398f90f2016-11-06 07:38:37 +00004508APFloat APFloat::getAllOnesValue(unsigned BitWidth, bool isIEEE) {
4509 if (isIEEE) {
4510 switch (BitWidth) {
4511 case 16:
Stephan Bergmann17c7f702016-12-14 11:57:17 +00004512 return APFloat(semIEEEhalf, APInt::getAllOnesValue(BitWidth));
Tim Shen398f90f2016-11-06 07:38:37 +00004513 case 32:
Stephan Bergmann17c7f702016-12-14 11:57:17 +00004514 return APFloat(semIEEEsingle, APInt::getAllOnesValue(BitWidth));
Tim Shen398f90f2016-11-06 07:38:37 +00004515 case 64:
Stephan Bergmann17c7f702016-12-14 11:57:17 +00004516 return APFloat(semIEEEdouble, APInt::getAllOnesValue(BitWidth));
Tim Shen398f90f2016-11-06 07:38:37 +00004517 case 80:
Stephan Bergmann17c7f702016-12-14 11:57:17 +00004518 return APFloat(semX87DoubleExtended, APInt::getAllOnesValue(BitWidth));
Tim Shen398f90f2016-11-06 07:38:37 +00004519 case 128:
Stephan Bergmann17c7f702016-12-14 11:57:17 +00004520 return APFloat(semIEEEquad, APInt::getAllOnesValue(BitWidth));
Tim Shen398f90f2016-11-06 07:38:37 +00004521 default:
4522 llvm_unreachable("Unknown floating bit width");
4523 }
4524 } else {
4525 assert(BitWidth == 128);
Stephan Bergmann17c7f702016-12-14 11:57:17 +00004526 return APFloat(semPPCDoubleDouble, APInt::getAllOnesValue(BitWidth));
Tim Shen398f90f2016-11-06 07:38:37 +00004527 }
4528}
4529
Tim Shen44bde892016-12-12 21:59:30 +00004530void APFloat::print(raw_ostream &OS) const {
4531 SmallVector<char, 16> Buffer;
4532 toString(Buffer);
4533 OS << Buffer << "\n";
4534}
4535
Aaron Ballman615eb472017-10-15 14:32:27 +00004536#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Matthias Braun8c209aa2017-01-28 02:02:38 +00004537LLVM_DUMP_METHOD void APFloat::dump() const { print(dbgs()); }
4538#endif
Tim Shen44bde892016-12-12 21:59:30 +00004539
Tim Shenfd1e5aa2017-01-23 22:39:35 +00004540void APFloat::Profile(FoldingSetNodeID &NID) const {
4541 NID.Add(bitcastToAPInt());
4542}
4543
4544/* Same as convertToInteger(integerPart*, ...), except the result is returned in
4545 an APSInt, whose initial bit-width and signed-ness are used to determine the
4546 precision of the conversion.
4547 */
4548APFloat::opStatus APFloat::convertToInteger(APSInt &result,
4549 roundingMode rounding_mode,
4550 bool *isExact) const {
4551 unsigned bitWidth = result.getBitWidth();
4552 SmallVector<uint64_t, 4> parts(result.getNumWords());
Simon Pilgrim00b34992017-03-20 14:40:12 +00004553 opStatus status = convertToInteger(parts, bitWidth, result.isSigned(),
Tim Shenfd1e5aa2017-01-23 22:39:35 +00004554 rounding_mode, isExact);
4555 // Keeps the original signed-ness.
4556 result = APInt(bitWidth, parts);
4557 return status;
4558}
4559
Tim Shen85de51d2016-10-25 19:55:59 +00004560} // End llvm namespace
Tim Shen601ba8c2017-01-27 02:11:07 +00004561
4562#undef APFLOAT_DISPATCH_ON_SEMANTICS