blob: 58f16233ebfc9d81d973d1a4aecb64b49c5253e2 [file] [log] [blame]
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001//===-- APFloat.cpp - Implement APFloat class -----------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattnerf3ebc3f2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements a class to represent arbitrary precision floating
11// point values and provide a variety of arithmetic operations on them.
12//
13//===----------------------------------------------------------------------===//
14
Chris Lattnere5256752007-12-08 19:00:03 +000015#include "llvm/ADT/APFloat.h"
Jeffrey Yasskin03b81a22011-07-15 07:04:56 +000016#include "llvm/ADT/APSInt.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"
Torok Edwin56d06592009-07-11 20:10:48 +000021#include "llvm/Support/ErrorHandling.h"
Dale Johannesen918c33c2007-08-24 05:08:11 +000022#include "llvm/Support/MathExtras.h"
Chris Lattner17f71652008-08-17 07:19:36 +000023#include <cstring>
Chandler Carruthed0881b2012-12-03 16:50:05 +000024#include <limits.h>
Chris Lattnerfe02c1f2007-08-20 22:49:32 +000025
26using namespace llvm;
27
Michael Gottesman9b877e12013-06-24 09:57:57 +000028/// A macro used to combine two fcCategory enums into one key which can be used
29/// in a switch statement to classify how the interaction of two APFloat's
30/// categories affects an operation.
31///
32/// TODO: If clang source code is ever allowed to use constexpr in its own
33/// codebase, change this into a static inline function.
34#define PackCategoriesIntoKey(_lhs, _rhs) ((_lhs) * 4 + (_rhs))
Chris Lattnerfe02c1f2007-08-20 22:49:32 +000035
Neil Booth8f1946f2007-10-03 22:26:02 +000036/* Assumed in hexadecimal significand parsing, and conversion to
37 hexadecimal strings. */
Chris Lattner8fcea672008-08-17 04:58:58 +000038#define COMPILE_TIME_ASSERT(cond) extern int CTAssert[(cond) ? 1 : -1]
Chris Lattnerfe02c1f2007-08-20 22:49:32 +000039COMPILE_TIME_ASSERT(integerPartWidth % 4 == 0);
40
41namespace llvm {
42
43 /* Represents floating point arithmetic semantics. */
44 struct fltSemantics {
45 /* The largest E such that 2^E is representable; this matches the
46 definition of IEEE 754. */
Michael Gottesman9dc98332013-06-24 04:06:23 +000047 APFloat::ExponentType maxExponent;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +000048
49 /* The smallest E such that 2^E is a normalized number; this
50 matches the definition of IEEE 754. */
Michael Gottesman9dc98332013-06-24 04:06:23 +000051 APFloat::ExponentType minExponent;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +000052
53 /* Number of bits in the significand. This includes the integer
54 bit. */
Neil Booth146fdb32007-10-12 15:33:27 +000055 unsigned int precision;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +000056 };
57
Ulrich Weigand908c9362012-10-29 18:18:44 +000058 const fltSemantics APFloat::IEEEhalf = { 15, -14, 11 };
59 const fltSemantics APFloat::IEEEsingle = { 127, -126, 24 };
60 const fltSemantics APFloat::IEEEdouble = { 1023, -1022, 53 };
61 const fltSemantics APFloat::IEEEquad = { 16383, -16382, 113 };
62 const fltSemantics APFloat::x87DoubleExtended = { 16383, -16382, 64 };
63 const fltSemantics APFloat::Bogus = { 0, 0, 0 };
Dale Johannesen007aa372007-10-11 18:07:22 +000064
Ulrich Weigandd9f7e252012-10-29 18:09:01 +000065 /* The PowerPC format consists of two doubles. It does not map cleanly
66 onto the usual format above. It is approximated using twice the
67 mantissa bits. Note that for exponents near the double minimum,
68 we no longer can represent the full 106 mantissa bits, so those
69 will be treated as denormal numbers.
70
71 FIXME: While this approximation is equivalent to what GCC uses for
72 compile-time arithmetic on PPC double-double numbers, it is not able
73 to represent all possible values held by a PPC double-double number,
74 for example: (long double) 1.0 + (long double) 0x1p-106
75 Should this be replaced by a full emulation of PPC double-double? */
Ulrich Weigand908c9362012-10-29 18:18:44 +000076 const fltSemantics APFloat::PPCDoubleDouble = { 1023, -1022 + 53, 53 + 53 };
Neil Boothb93d90e2007-10-12 16:02:31 +000077
78 /* A tight upper bound on number of parts required to hold the value
79 pow(5, power) is
80
Neil Booth91305512007-10-15 15:00:55 +000081 power * 815 / (351 * integerPartWidth) + 1
Dan Gohmanb452d4e2010-03-24 19:38:02 +000082
Neil Boothb93d90e2007-10-12 16:02:31 +000083 However, whilst the result may require only this many parts,
84 because we are multiplying two values to get it, the
85 multiplication may require an extra part with the excess part
86 being zero (consider the trivial case of 1 * 1, tcFullMultiply
87 requires two parts to hold the single-part result). So we add an
88 extra one to guarantee enough space whilst multiplying. */
89 const unsigned int maxExponent = 16383;
90 const unsigned int maxPrecision = 113;
91 const unsigned int maxPowerOfFiveExponent = maxExponent + maxPrecision - 1;
Neil Booth91305512007-10-15 15:00:55 +000092 const unsigned int maxPowerOfFiveParts = 2 + ((maxPowerOfFiveExponent * 815)
93 / (351 * integerPartWidth));
Chris Lattnerfe02c1f2007-08-20 22:49:32 +000094}
95
Chris Lattner91702092009-03-12 23:59:55 +000096/* A bunch of private, handy routines. */
Chris Lattnerfe02c1f2007-08-20 22:49:32 +000097
Chris Lattner91702092009-03-12 23:59:55 +000098static inline unsigned int
99partCountForBits(unsigned int bits)
100{
101 return ((bits) + integerPartWidth - 1) / integerPartWidth;
102}
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000103
Chris Lattner91702092009-03-12 23:59:55 +0000104/* Returns 0U-9U. Return values >= 10U are not digits. */
105static inline unsigned int
106decDigitValue(unsigned int c)
107{
108 return c - '0';
109}
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000110
Chris Lattner91702092009-03-12 23:59:55 +0000111/* Return the value of a decimal exponent of the form
112 [+-]ddddddd.
Neil Booth4ed401b2007-10-14 10:16:12 +0000113
Chris Lattner91702092009-03-12 23:59:55 +0000114 If the exponent overflows, returns a large exponent with the
115 appropriate sign. */
116static int
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000117readExponent(StringRef::iterator begin, StringRef::iterator end)
Chris Lattner91702092009-03-12 23:59:55 +0000118{
119 bool isNegative;
120 unsigned int absExponent;
121 const unsigned int overlargeExponent = 24000; /* FIXME. */
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000122 StringRef::iterator p = begin;
123
124 assert(p != end && "Exponent has no digits");
Neil Booth4ed401b2007-10-14 10:16:12 +0000125
Chris Lattner91702092009-03-12 23:59:55 +0000126 isNegative = (*p == '-');
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000127 if (*p == '-' || *p == '+') {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000128 p++;
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000129 assert(p != end && "Exponent has no digits");
130 }
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000131
Chris Lattner91702092009-03-12 23:59:55 +0000132 absExponent = decDigitValue(*p++);
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000133 assert(absExponent < 10U && "Invalid character in exponent");
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000134
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000135 for (; p != end; ++p) {
Chris Lattner91702092009-03-12 23:59:55 +0000136 unsigned int value;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000137
Chris Lattner91702092009-03-12 23:59:55 +0000138 value = decDigitValue(*p);
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000139 assert(value < 10U && "Invalid character in exponent");
Chris Lattner91702092009-03-12 23:59:55 +0000140
Chris Lattner91702092009-03-12 23:59:55 +0000141 value += absExponent * 10;
142 if (absExponent >= overlargeExponent) {
143 absExponent = overlargeExponent;
Dale Johannesen370c77c2010-08-19 17:58:35 +0000144 p = end; /* outwit assert below */
Chris Lattner91702092009-03-12 23:59:55 +0000145 break;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000146 }
Chris Lattner91702092009-03-12 23:59:55 +0000147 absExponent = value;
148 }
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000149
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000150 assert(p == end && "Invalid exponent in exponent");
151
Chris Lattner91702092009-03-12 23:59:55 +0000152 if (isNegative)
153 return -(int) absExponent;
154 else
155 return (int) absExponent;
156}
157
158/* This is ugly and needs cleaning up, but I don't immediately see
159 how whilst remaining safe. */
160static int
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000161totalExponent(StringRef::iterator p, StringRef::iterator end,
162 int exponentAdjustment)
Chris Lattner91702092009-03-12 23:59:55 +0000163{
164 int unsignedExponent;
165 bool negative, overflow;
Ted Kremenek3c4408c2011-01-23 17:05:06 +0000166 int exponent = 0;
Chris Lattner91702092009-03-12 23:59:55 +0000167
Erick Tryzelaarda666c82009-08-20 23:30:43 +0000168 assert(p != end && "Exponent has no digits");
169
Chris Lattner91702092009-03-12 23:59:55 +0000170 negative = *p == '-';
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000171 if (*p == '-' || *p == '+') {
Chris Lattner91702092009-03-12 23:59:55 +0000172 p++;
Erick Tryzelaarda666c82009-08-20 23:30:43 +0000173 assert(p != end && "Exponent has no digits");
174 }
Chris Lattner91702092009-03-12 23:59:55 +0000175
176 unsignedExponent = 0;
177 overflow = false;
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000178 for (; p != end; ++p) {
Chris Lattner91702092009-03-12 23:59:55 +0000179 unsigned int value;
180
181 value = decDigitValue(*p);
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000182 assert(value < 10U && "Invalid character in exponent");
Chris Lattner91702092009-03-12 23:59:55 +0000183
Chris Lattner91702092009-03-12 23:59:55 +0000184 unsignedExponent = unsignedExponent * 10 + value;
Richard Smith156d9202012-08-24 00:01:19 +0000185 if (unsignedExponent > 32767) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000186 overflow = true;
Richard Smith156d9202012-08-24 00:01:19 +0000187 break;
188 }
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000189 }
190
Abramo Bagnaraa41d7ae2011-01-06 16:55:14 +0000191 if (exponentAdjustment > 32767 || exponentAdjustment < -32768)
Chris Lattner91702092009-03-12 23:59:55 +0000192 overflow = true;
193
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000194 if (!overflow) {
Chris Lattner91702092009-03-12 23:59:55 +0000195 exponent = unsignedExponent;
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000196 if (negative)
Chris Lattner91702092009-03-12 23:59:55 +0000197 exponent = -exponent;
198 exponent += exponentAdjustment;
Abramo Bagnaraa41d7ae2011-01-06 16:55:14 +0000199 if (exponent > 32767 || exponent < -32768)
Chris Lattner91702092009-03-12 23:59:55 +0000200 overflow = true;
201 }
202
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000203 if (overflow)
Abramo Bagnaraa41d7ae2011-01-06 16:55:14 +0000204 exponent = negative ? -32768: 32767;
Chris Lattner91702092009-03-12 23:59:55 +0000205
206 return exponent;
207}
208
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000209static StringRef::iterator
210skipLeadingZeroesAndAnyDot(StringRef::iterator begin, StringRef::iterator end,
211 StringRef::iterator *dot)
Chris Lattner91702092009-03-12 23:59:55 +0000212{
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000213 StringRef::iterator p = begin;
214 *dot = end;
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000215 while (*p == '0' && p != end)
Chris Lattner91702092009-03-12 23:59:55 +0000216 p++;
217
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000218 if (*p == '.') {
Chris Lattner91702092009-03-12 23:59:55 +0000219 *dot = p++;
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000220
Erick Tryzelaarda666c82009-08-20 23:30:43 +0000221 assert(end - begin != 1 && "Significand has no digits");
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000222
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000223 while (*p == '0' && p != end)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000224 p++;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000225 }
226
Chris Lattner91702092009-03-12 23:59:55 +0000227 return p;
228}
Neil Booth4ed401b2007-10-14 10:16:12 +0000229
Chris Lattner91702092009-03-12 23:59:55 +0000230/* Given a normal decimal floating point number of the form
Neil Booth4ed401b2007-10-14 10:16:12 +0000231
Chris Lattner91702092009-03-12 23:59:55 +0000232 dddd.dddd[eE][+-]ddd
Neil Booth91305512007-10-15 15:00:55 +0000233
Chris Lattner91702092009-03-12 23:59:55 +0000234 where the decimal point and exponent are optional, fill out the
235 structure D. Exponent is appropriate if the significand is
236 treated as an integer, and normalizedExponent if the significand
237 is taken to have the decimal point after a single leading
238 non-zero digit.
Neil Booth4ed401b2007-10-14 10:16:12 +0000239
Chris Lattner91702092009-03-12 23:59:55 +0000240 If the value is zero, V->firstSigDigit points to a non-digit, and
241 the return exponent is zero.
242*/
243struct decimalInfo {
244 const char *firstSigDigit;
245 const char *lastSigDigit;
246 int exponent;
247 int normalizedExponent;
248};
Neil Booth4ed401b2007-10-14 10:16:12 +0000249
Chris Lattner91702092009-03-12 23:59:55 +0000250static void
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000251interpretDecimal(StringRef::iterator begin, StringRef::iterator end,
252 decimalInfo *D)
Chris Lattner91702092009-03-12 23:59:55 +0000253{
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000254 StringRef::iterator dot = end;
255 StringRef::iterator p = skipLeadingZeroesAndAnyDot (begin, end, &dot);
Neil Booth4ed401b2007-10-14 10:16:12 +0000256
Chris Lattner91702092009-03-12 23:59:55 +0000257 D->firstSigDigit = p;
258 D->exponent = 0;
259 D->normalizedExponent = 0;
260
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000261 for (; p != end; ++p) {
Chris Lattner91702092009-03-12 23:59:55 +0000262 if (*p == '.') {
Erick Tryzelaarda666c82009-08-20 23:30:43 +0000263 assert(dot == end && "String contains multiple dots");
Chris Lattner91702092009-03-12 23:59:55 +0000264 dot = p++;
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000265 if (p == end)
266 break;
Neil Booth4ed401b2007-10-14 10:16:12 +0000267 }
Chris Lattner91702092009-03-12 23:59:55 +0000268 if (decDigitValue(*p) >= 10U)
269 break;
Chris Lattner91702092009-03-12 23:59:55 +0000270 }
Neil Booth4ed401b2007-10-14 10:16:12 +0000271
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000272 if (p != end) {
Erick Tryzelaarda666c82009-08-20 23:30:43 +0000273 assert((*p == 'e' || *p == 'E') && "Invalid character in significand");
274 assert(p != begin && "Significand has no digits");
275 assert((dot == end || p - begin != 1) && "Significand has no digits");
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000276
277 /* p points to the first non-digit in the string */
Erick Tryzelaarda666c82009-08-20 23:30:43 +0000278 D->exponent = readExponent(p + 1, end);
Neil Booth4ed401b2007-10-14 10:16:12 +0000279
Chris Lattner91702092009-03-12 23:59:55 +0000280 /* Implied decimal point? */
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000281 if (dot == end)
Chris Lattner91702092009-03-12 23:59:55 +0000282 dot = p;
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000283 }
Neil Booth4ed401b2007-10-14 10:16:12 +0000284
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000285 /* If number is all zeroes accept any exponent. */
286 if (p != D->firstSigDigit) {
Chris Lattner91702092009-03-12 23:59:55 +0000287 /* Drop insignificant trailing zeroes. */
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000288 if (p != begin) {
Neil Booth4ed401b2007-10-14 10:16:12 +0000289 do
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000290 do
291 p--;
292 while (p != begin && *p == '0');
293 while (p != begin && *p == '.');
294 }
Neil Booth4ed401b2007-10-14 10:16:12 +0000295
Chris Lattner91702092009-03-12 23:59:55 +0000296 /* Adjust the exponents for any decimal point. */
Michael Gottesman9dc98332013-06-24 04:06:23 +0000297 D->exponent += static_cast<APFloat::ExponentType>((dot - p) - (dot > p));
Chris Lattner91702092009-03-12 23:59:55 +0000298 D->normalizedExponent = (D->exponent +
Michael Gottesman9dc98332013-06-24 04:06:23 +0000299 static_cast<APFloat::ExponentType>((p - D->firstSigDigit)
Chris Lattner91702092009-03-12 23:59:55 +0000300 - (dot > D->firstSigDigit && dot < p)));
Neil Booth4ed401b2007-10-14 10:16:12 +0000301 }
302
Chris Lattner91702092009-03-12 23:59:55 +0000303 D->lastSigDigit = p;
304}
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000305
Chris Lattner91702092009-03-12 23:59:55 +0000306/* Return the trailing fraction of a hexadecimal number.
307 DIGITVALUE is the first hex digit of the fraction, P points to
308 the next digit. */
309static lostFraction
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000310trailingHexadecimalFraction(StringRef::iterator p, StringRef::iterator end,
311 unsigned int digitValue)
Chris Lattner91702092009-03-12 23:59:55 +0000312{
313 unsigned int hexDigit;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000314
Chris Lattner91702092009-03-12 23:59:55 +0000315 /* If the first trailing digit isn't 0 or 8 we can work out the
316 fraction immediately. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000317 if (digitValue > 8)
Chris Lattner91702092009-03-12 23:59:55 +0000318 return lfMoreThanHalf;
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000319 else if (digitValue < 8 && digitValue > 0)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000320 return lfLessThanHalf;
Chris Lattner91702092009-03-12 23:59:55 +0000321
322 /* Otherwise we need to find the first non-zero digit. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000323 while (*p == '0')
Chris Lattner91702092009-03-12 23:59:55 +0000324 p++;
325
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000326 assert(p != end && "Invalid trailing hexadecimal fraction!");
327
Chris Lattner91702092009-03-12 23:59:55 +0000328 hexDigit = hexDigitValue(*p);
329
330 /* If we ran off the end it is exactly zero or one-half, otherwise
331 a little more. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000332 if (hexDigit == -1U)
Chris Lattner91702092009-03-12 23:59:55 +0000333 return digitValue == 0 ? lfExactlyZero: lfExactlyHalf;
334 else
335 return digitValue == 0 ? lfLessThanHalf: lfMoreThanHalf;
336}
337
338/* Return the fraction lost were a bignum truncated losing the least
339 significant BITS bits. */
340static lostFraction
341lostFractionThroughTruncation(const integerPart *parts,
342 unsigned int partCount,
343 unsigned int bits)
344{
345 unsigned int lsb;
346
347 lsb = APInt::tcLSB(parts, partCount);
348
349 /* Note this is guaranteed true if bits == 0, or LSB == -1U. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000350 if (bits <= lsb)
Chris Lattner91702092009-03-12 23:59:55 +0000351 return lfExactlyZero;
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000352 if (bits == lsb + 1)
Chris Lattner91702092009-03-12 23:59:55 +0000353 return lfExactlyHalf;
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000354 if (bits <= partCount * integerPartWidth &&
355 APInt::tcExtractBit(parts, bits - 1))
Chris Lattner91702092009-03-12 23:59:55 +0000356 return lfMoreThanHalf;
357
358 return lfLessThanHalf;
359}
360
361/* Shift DST right BITS bits noting lost fraction. */
362static lostFraction
363shiftRight(integerPart *dst, unsigned int parts, unsigned int bits)
364{
365 lostFraction lost_fraction;
366
367 lost_fraction = lostFractionThroughTruncation(dst, parts, bits);
368
369 APInt::tcShiftRight(dst, parts, bits);
370
371 return lost_fraction;
372}
373
374/* Combine the effect of two lost fractions. */
375static lostFraction
376combineLostFractions(lostFraction moreSignificant,
377 lostFraction lessSignificant)
378{
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000379 if (lessSignificant != lfExactlyZero) {
380 if (moreSignificant == lfExactlyZero)
Chris Lattner91702092009-03-12 23:59:55 +0000381 moreSignificant = lfLessThanHalf;
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000382 else if (moreSignificant == lfExactlyHalf)
Chris Lattner91702092009-03-12 23:59:55 +0000383 moreSignificant = lfMoreThanHalf;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000384 }
385
Chris Lattner91702092009-03-12 23:59:55 +0000386 return moreSignificant;
387}
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000388
Chris Lattner91702092009-03-12 23:59:55 +0000389/* The error from the true value, in half-ulps, on multiplying two
390 floating point numbers, which differ from the value they
391 approximate by at most HUE1 and HUE2 half-ulps, is strictly less
392 than the returned value.
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000393
Chris Lattner91702092009-03-12 23:59:55 +0000394 See "How to Read Floating Point Numbers Accurately" by William D
395 Clinger. */
396static unsigned int
397HUerrBound(bool inexactMultiply, unsigned int HUerr1, unsigned int HUerr2)
398{
399 assert(HUerr1 < 2 || HUerr2 < 2 || (HUerr1 + HUerr2 < 8));
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000400
Chris Lattner91702092009-03-12 23:59:55 +0000401 if (HUerr1 + HUerr2 == 0)
402 return inexactMultiply * 2; /* <= inexactMultiply half-ulps. */
403 else
404 return inexactMultiply + 2 * (HUerr1 + HUerr2);
405}
Neil Booth8f1946f2007-10-03 22:26:02 +0000406
Chris Lattner91702092009-03-12 23:59:55 +0000407/* The number of ulps from the boundary (zero, or half if ISNEAREST)
408 when the least significant BITS are truncated. BITS cannot be
409 zero. */
410static integerPart
411ulpsFromBoundary(const integerPart *parts, unsigned int bits, bool isNearest)
412{
413 unsigned int count, partBits;
414 integerPart part, boundary;
Neil Boothd3985922007-10-07 08:51:21 +0000415
Evan Cheng67c90212009-10-27 21:35:42 +0000416 assert(bits != 0);
Neil Booth8f1946f2007-10-03 22:26:02 +0000417
Chris Lattner91702092009-03-12 23:59:55 +0000418 bits--;
419 count = bits / integerPartWidth;
420 partBits = bits % integerPartWidth + 1;
Neil Boothb93d90e2007-10-12 16:02:31 +0000421
Chris Lattner91702092009-03-12 23:59:55 +0000422 part = parts[count] & (~(integerPart) 0 >> (integerPartWidth - partBits));
Neil Boothb93d90e2007-10-12 16:02:31 +0000423
Chris Lattner91702092009-03-12 23:59:55 +0000424 if (isNearest)
425 boundary = (integerPart) 1 << (partBits - 1);
426 else
427 boundary = 0;
428
429 if (count == 0) {
430 if (part - boundary <= boundary - part)
431 return part - boundary;
Neil Boothb93d90e2007-10-12 16:02:31 +0000432 else
Chris Lattner91702092009-03-12 23:59:55 +0000433 return boundary - part;
Neil Boothb93d90e2007-10-12 16:02:31 +0000434 }
435
Chris Lattner91702092009-03-12 23:59:55 +0000436 if (part == boundary) {
437 while (--count)
438 if (parts[count])
439 return ~(integerPart) 0; /* A lot. */
Neil Boothb93d90e2007-10-12 16:02:31 +0000440
Chris Lattner91702092009-03-12 23:59:55 +0000441 return parts[0];
442 } else if (part == boundary - 1) {
443 while (--count)
444 if (~parts[count])
445 return ~(integerPart) 0; /* A lot. */
Neil Boothb93d90e2007-10-12 16:02:31 +0000446
Chris Lattner91702092009-03-12 23:59:55 +0000447 return -parts[0];
448 }
Neil Boothb93d90e2007-10-12 16:02:31 +0000449
Chris Lattner91702092009-03-12 23:59:55 +0000450 return ~(integerPart) 0; /* A lot. */
451}
Neil Boothb93d90e2007-10-12 16:02:31 +0000452
Chris Lattner91702092009-03-12 23:59:55 +0000453/* Place pow(5, power) in DST, and return the number of parts used.
454 DST must be at least one part larger than size of the answer. */
455static unsigned int
456powerOf5(integerPart *dst, unsigned int power)
457{
458 static const integerPart firstEightPowers[] = { 1, 5, 25, 125, 625, 3125,
459 15625, 78125 };
Chris Lattnerb858c0e2009-03-13 00:24:01 +0000460 integerPart pow5s[maxPowerOfFiveParts * 2 + 5];
461 pow5s[0] = 78125 * 5;
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000462
Chris Lattner0bf18692009-03-13 00:03:51 +0000463 unsigned int partsCount[16] = { 1 };
Chris Lattner91702092009-03-12 23:59:55 +0000464 integerPart scratch[maxPowerOfFiveParts], *p1, *p2, *pow5;
465 unsigned int result;
Chris Lattner91702092009-03-12 23:59:55 +0000466 assert(power <= maxExponent);
467
468 p1 = dst;
469 p2 = scratch;
470
471 *p1 = firstEightPowers[power & 7];
472 power >>= 3;
473
474 result = 1;
475 pow5 = pow5s;
476
477 for (unsigned int n = 0; power; power >>= 1, n++) {
478 unsigned int pc;
479
480 pc = partsCount[n];
481
482 /* Calculate pow(5,pow(2,n+3)) if we haven't yet. */
483 if (pc == 0) {
484 pc = partsCount[n - 1];
485 APInt::tcFullMultiply(pow5, pow5 - pc, pow5 - pc, pc, pc);
486 pc *= 2;
487 if (pow5[pc - 1] == 0)
488 pc--;
489 partsCount[n] = pc;
Neil Boothb93d90e2007-10-12 16:02:31 +0000490 }
491
Chris Lattner91702092009-03-12 23:59:55 +0000492 if (power & 1) {
493 integerPart *tmp;
Neil Boothb93d90e2007-10-12 16:02:31 +0000494
Chris Lattner91702092009-03-12 23:59:55 +0000495 APInt::tcFullMultiply(p2, p1, pow5, result, pc);
496 result += pc;
497 if (p2[result - 1] == 0)
498 result--;
Neil Boothb93d90e2007-10-12 16:02:31 +0000499
Chris Lattner91702092009-03-12 23:59:55 +0000500 /* Now result is in p1 with partsCount parts and p2 is scratch
501 space. */
502 tmp = p1, p1 = p2, p2 = tmp;
Neil Boothb93d90e2007-10-12 16:02:31 +0000503 }
504
Chris Lattner91702092009-03-12 23:59:55 +0000505 pow5 += pc;
Neil Boothb93d90e2007-10-12 16:02:31 +0000506 }
507
Chris Lattner91702092009-03-12 23:59:55 +0000508 if (p1 != dst)
509 APInt::tcAssign(dst, p1, result);
Neil Boothb93d90e2007-10-12 16:02:31 +0000510
Chris Lattner91702092009-03-12 23:59:55 +0000511 return result;
512}
Neil Boothb93d90e2007-10-12 16:02:31 +0000513
Chris Lattner91702092009-03-12 23:59:55 +0000514/* Zero at the end to avoid modular arithmetic when adding one; used
515 when rounding up during hexadecimal output. */
516static const char hexDigitsLower[] = "0123456789abcdef0";
517static const char hexDigitsUpper[] = "0123456789ABCDEF0";
518static const char infinityL[] = "infinity";
519static const char infinityU[] = "INFINITY";
520static const char NaNL[] = "nan";
521static const char NaNU[] = "NAN";
Neil Boothb93d90e2007-10-12 16:02:31 +0000522
Chris Lattner91702092009-03-12 23:59:55 +0000523/* Write out an integerPart in hexadecimal, starting with the most
524 significant nibble. Write out exactly COUNT hexdigits, return
525 COUNT. */
526static unsigned int
527partAsHex (char *dst, integerPart part, unsigned int count,
528 const char *hexDigitChars)
529{
530 unsigned int result = count;
Neil Boothb93d90e2007-10-12 16:02:31 +0000531
Evan Cheng67c90212009-10-27 21:35:42 +0000532 assert(count != 0 && count <= integerPartWidth / 4);
Neil Boothb93d90e2007-10-12 16:02:31 +0000533
Chris Lattner91702092009-03-12 23:59:55 +0000534 part >>= (integerPartWidth - 4 * count);
535 while (count--) {
536 dst[count] = hexDigitChars[part & 0xf];
537 part >>= 4;
Neil Boothb93d90e2007-10-12 16:02:31 +0000538 }
539
Chris Lattner91702092009-03-12 23:59:55 +0000540 return result;
541}
Neil Booth8f1946f2007-10-03 22:26:02 +0000542
Chris Lattner91702092009-03-12 23:59:55 +0000543/* Write out an unsigned decimal integer. */
544static char *
545writeUnsignedDecimal (char *dst, unsigned int n)
546{
547 char buff[40], *p;
Neil Booth8f1946f2007-10-03 22:26:02 +0000548
Chris Lattner91702092009-03-12 23:59:55 +0000549 p = buff;
550 do
551 *p++ = '0' + n % 10;
552 while (n /= 10);
Neil Booth8f1946f2007-10-03 22:26:02 +0000553
Chris Lattner91702092009-03-12 23:59:55 +0000554 do
555 *dst++ = *--p;
556 while (p != buff);
Neil Booth8f1946f2007-10-03 22:26:02 +0000557
Chris Lattner91702092009-03-12 23:59:55 +0000558 return dst;
559}
Neil Booth8f1946f2007-10-03 22:26:02 +0000560
Chris Lattner91702092009-03-12 23:59:55 +0000561/* Write out a signed decimal integer. */
562static char *
563writeSignedDecimal (char *dst, int value)
564{
565 if (value < 0) {
566 *dst++ = '-';
567 dst = writeUnsignedDecimal(dst, -(unsigned) value);
568 } else
569 dst = writeUnsignedDecimal(dst, value);
Neil Booth8f1946f2007-10-03 22:26:02 +0000570
Chris Lattner91702092009-03-12 23:59:55 +0000571 return dst;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000572}
573
574/* Constructors. */
575void
576APFloat::initialize(const fltSemantics *ourSemantics)
577{
578 unsigned int count;
579
580 semantics = ourSemantics;
581 count = partCount();
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000582 if (count > 1)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000583 significand.parts = new integerPart[count];
584}
585
586void
587APFloat::freeSignificand()
588{
Manuel Klimekd0cf5b22013-06-03 13:03:05 +0000589 if (needsCleanup())
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000590 delete [] significand.parts;
591}
592
593void
594APFloat::assign(const APFloat &rhs)
595{
596 assert(semantics == rhs.semantics);
597
598 sign = rhs.sign;
599 category = rhs.category;
600 exponent = rhs.exponent;
Michael Gottesman8136c382013-06-26 23:17:28 +0000601 if (isFiniteNonZero() || category == fcNaN)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000602 copySignificand(rhs);
603}
604
605void
606APFloat::copySignificand(const APFloat &rhs)
607{
Michael Gottesman8136c382013-06-26 23:17:28 +0000608 assert(isFiniteNonZero() || category == fcNaN);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000609 assert(rhs.partCount() >= partCount());
610
611 APInt::tcAssign(significandParts(), rhs.significandParts(),
Neil Booth9acbf5a2007-09-26 21:33:42 +0000612 partCount());
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000613}
614
Neil Booth5fe658b2007-10-14 10:39:51 +0000615/* Make this number a NaN, with an arbitrary but deterministic value
Dale Johannesen1f864982009-01-21 20:32:55 +0000616 for the significand. If double or longer, this is a signalling NaN,
Mike Stump799bf582009-05-30 03:49:43 +0000617 which may not be ideal. If float, this is QNaN(0). */
John McCalldcb9a7a2010-02-28 02:51:25 +0000618void APFloat::makeNaN(bool SNaN, bool Negative, const APInt *fill)
Neil Booth5fe658b2007-10-14 10:39:51 +0000619{
620 category = fcNaN;
John McCalldcb9a7a2010-02-28 02:51:25 +0000621 sign = Negative;
622
John McCallc12b1332010-02-28 12:49:50 +0000623 integerPart *significand = significandParts();
624 unsigned numParts = partCount();
625
John McCalldcb9a7a2010-02-28 02:51:25 +0000626 // Set the significand bits to the fill.
John McCallc12b1332010-02-28 12:49:50 +0000627 if (!fill || fill->getNumWords() < numParts)
628 APInt::tcSet(significand, 0, numParts);
629 if (fill) {
John McCallc6dbe302010-03-01 18:38:45 +0000630 APInt::tcAssign(significand, fill->getRawData(),
631 std::min(fill->getNumWords(), numParts));
John McCallc12b1332010-02-28 12:49:50 +0000632
633 // Zero out the excess bits of the significand.
634 unsigned bitsToPreserve = semantics->precision - 1;
635 unsigned part = bitsToPreserve / 64;
636 bitsToPreserve %= 64;
637 significand[part] &= ((1ULL << bitsToPreserve) - 1);
638 for (part++; part != numParts; ++part)
639 significand[part] = 0;
640 }
641
642 unsigned QNaNBit = semantics->precision - 2;
John McCalldcb9a7a2010-02-28 02:51:25 +0000643
644 if (SNaN) {
645 // We always have to clear the QNaN bit to make it an SNaN.
John McCallc12b1332010-02-28 12:49:50 +0000646 APInt::tcClearBit(significand, QNaNBit);
John McCalldcb9a7a2010-02-28 02:51:25 +0000647
648 // If there are no bits set in the payload, we have to set
649 // *something* to make it a NaN instead of an infinity;
650 // conventionally, this is the next bit down from the QNaN bit.
John McCallc12b1332010-02-28 12:49:50 +0000651 if (APInt::tcIsZero(significand, numParts))
652 APInt::tcSetBit(significand, QNaNBit - 1);
John McCalldcb9a7a2010-02-28 02:51:25 +0000653 } else {
654 // We always have to set the QNaN bit to make it a QNaN.
John McCallc12b1332010-02-28 12:49:50 +0000655 APInt::tcSetBit(significand, QNaNBit);
John McCalldcb9a7a2010-02-28 02:51:25 +0000656 }
John McCallc12b1332010-02-28 12:49:50 +0000657
658 // For x87 extended precision, we want to make a NaN, not a
659 // pseudo-NaN. Maybe we should expose the ability to make
660 // pseudo-NaNs?
661 if (semantics == &APFloat::x87DoubleExtended)
662 APInt::tcSetBit(significand, QNaNBit + 1);
John McCalldcb9a7a2010-02-28 02:51:25 +0000663}
664
665APFloat APFloat::makeNaN(const fltSemantics &Sem, bool SNaN, bool Negative,
666 const APInt *fill) {
667 APFloat value(Sem, uninitialized);
668 value.makeNaN(SNaN, Negative, fill);
669 return value;
Neil Booth5fe658b2007-10-14 10:39:51 +0000670}
671
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000672APFloat &
673APFloat::operator=(const APFloat &rhs)
674{
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000675 if (this != &rhs) {
676 if (semantics != rhs.semantics) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000677 freeSignificand();
678 initialize(rhs.semantics);
679 }
680 assign(rhs);
681 }
682
683 return *this;
684}
685
Dale Johannesena719a602007-08-24 00:56:33 +0000686bool
Shuxin Yang4fb504f2013-01-07 18:59:35 +0000687APFloat::isDenormal() const {
Michael Gottesman3cb77ab2013-06-19 21:23:18 +0000688 return isFiniteNonZero() && (exponent == semantics->minExponent) &&
Shuxin Yang4fb504f2013-01-07 18:59:35 +0000689 (APInt::tcExtractBit(significandParts(),
690 semantics->precision - 1) == 0);
691}
692
693bool
Michael Gottesman0c622ea2013-05-30 18:07:13 +0000694APFloat::isSmallest() const {
695 // The smallest number by magnitude in our format will be the smallest
Michael Gottesmana7cc1242013-06-19 07:34:21 +0000696 // denormal, i.e. the floating point number with exponent being minimum
Michael Gottesman0c622ea2013-05-30 18:07:13 +0000697 // exponent and significand bitwise equal to 1 (i.e. with MSB equal to 0).
Michael Gottesman3cb77ab2013-06-19 21:23:18 +0000698 return isFiniteNonZero() && exponent == semantics->minExponent &&
Michael Gottesman0c622ea2013-05-30 18:07:13 +0000699 significandMSB() == 0;
700}
701
702bool APFloat::isSignificandAllOnes() const {
703 // Test if the significand excluding the integral bit is all ones. This allows
704 // us to test for binade boundaries.
705 const integerPart *Parts = significandParts();
706 const unsigned PartCount = partCount();
707 for (unsigned i = 0; i < PartCount - 1; i++)
708 if (~Parts[i])
709 return false;
710
711 // Set the unused high bits to all ones when we compare.
712 const unsigned NumHighBits =
713 PartCount*integerPartWidth - semantics->precision + 1;
714 assert(NumHighBits <= integerPartWidth && "Can not have more high bits to "
715 "fill than integerPartWidth");
716 const integerPart HighBitFill =
717 ~integerPart(0) << (integerPartWidth - NumHighBits);
718 if (~(Parts[PartCount - 1] | HighBitFill))
719 return false;
720
721 return true;
722}
723
724bool APFloat::isSignificandAllZeros() const {
725 // Test if the significand excluding the integral bit is all zeros. This
726 // allows us to test for binade boundaries.
727 const integerPart *Parts = significandParts();
728 const unsigned PartCount = partCount();
729
730 for (unsigned i = 0; i < PartCount - 1; i++)
731 if (Parts[i])
732 return false;
733
734 const unsigned NumHighBits =
735 PartCount*integerPartWidth - semantics->precision + 1;
736 assert(NumHighBits <= integerPartWidth && "Can not have more high bits to "
737 "clear than integerPartWidth");
738 const integerPart HighBitMask = ~integerPart(0) >> NumHighBits;
739
740 if (Parts[PartCount - 1] & HighBitMask)
741 return false;
742
743 return true;
744}
745
746bool
747APFloat::isLargest() const {
748 // The largest number by magnitude in our format will be the floating point
749 // number with maximum exponent and with significand that is all ones.
Michael Gottesman3cb77ab2013-06-19 21:23:18 +0000750 return isFiniteNonZero() && exponent == semantics->maxExponent
Michael Gottesman0c622ea2013-05-30 18:07:13 +0000751 && isSignificandAllOnes();
752}
753
754bool
Dale Johannesenbdea32d2007-08-24 22:09:56 +0000755APFloat::bitwiseIsEqual(const APFloat &rhs) const {
Dale Johannesena719a602007-08-24 00:56:33 +0000756 if (this == &rhs)
757 return true;
758 if (semantics != rhs.semantics ||
Dale Johannesen3cf889f2007-08-31 04:03:46 +0000759 category != rhs.category ||
760 sign != rhs.sign)
Dale Johannesena719a602007-08-24 00:56:33 +0000761 return false;
Dale Johannesen3cf889f2007-08-31 04:03:46 +0000762 if (category==fcZero || category==fcInfinity)
Dale Johannesena719a602007-08-24 00:56:33 +0000763 return true;
Michael Gottesman8136c382013-06-26 23:17:28 +0000764 else if (isFiniteNonZero() && exponent!=rhs.exponent)
Dale Johannesen3cf889f2007-08-31 04:03:46 +0000765 return false;
Dale Johannesena719a602007-08-24 00:56:33 +0000766 else {
Dale Johannesena719a602007-08-24 00:56:33 +0000767 int i= partCount();
768 const integerPart* p=significandParts();
769 const integerPart* q=rhs.significandParts();
770 for (; i>0; i--, p++, q++) {
771 if (*p != *q)
772 return false;
773 }
774 return true;
775 }
776}
777
Ulrich Weigande1d62f92012-10-29 18:17:42 +0000778APFloat::APFloat(const fltSemantics &ourSemantics, integerPart value) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000779 initialize(&ourSemantics);
780 sign = 0;
781 zeroSignificand();
782 exponent = ourSemantics.precision - 1;
783 significandParts()[0] = value;
784 normalize(rmNearestTiesToEven, lfExactlyZero);
785}
786
Ulrich Weigande1d62f92012-10-29 18:17:42 +0000787APFloat::APFloat(const fltSemantics &ourSemantics) {
Chris Lattnerac6271e2009-09-17 01:08:43 +0000788 initialize(&ourSemantics);
789 category = fcZero;
790 sign = false;
791}
792
Ulrich Weigande1d62f92012-10-29 18:17:42 +0000793APFloat::APFloat(const fltSemantics &ourSemantics, uninitializedTag tag) {
John McCalldcb9a7a2010-02-28 02:51:25 +0000794 // Allocates storage if necessary but does not initialize it.
795 initialize(&ourSemantics);
796}
Chris Lattnerac6271e2009-09-17 01:08:43 +0000797
Ulrich Weigande1d62f92012-10-29 18:17:42 +0000798APFloat::APFloat(const fltSemantics &ourSemantics, StringRef text) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000799 initialize(&ourSemantics);
800 convertFromString(text, rmNearestTiesToEven);
801}
802
Ulrich Weigande1d62f92012-10-29 18:17:42 +0000803APFloat::APFloat(const APFloat &rhs) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000804 initialize(rhs.semantics);
805 assign(rhs);
806}
807
808APFloat::~APFloat()
809{
810 freeSignificand();
811}
812
Ted Kremenek6f30a072008-02-11 17:24:50 +0000813// Profile - This method 'profiles' an APFloat for use with FoldingSet.
814void APFloat::Profile(FoldingSetNodeID& ID) const {
Dale Johannesen54306fe2008-10-09 18:53:47 +0000815 ID.Add(bitcastToAPInt());
Ted Kremenek6f30a072008-02-11 17:24:50 +0000816}
817
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000818unsigned int
819APFloat::partCount() const
820{
Dale Johannesen146a0ea2007-09-20 23:47:58 +0000821 return partCountForBits(semantics->precision + 1);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000822}
823
824unsigned int
825APFloat::semanticsPrecision(const fltSemantics &semantics)
826{
827 return semantics.precision;
828}
829
830const integerPart *
831APFloat::significandParts() const
832{
833 return const_cast<APFloat *>(this)->significandParts();
834}
835
836integerPart *
837APFloat::significandParts()
838{
Evan Cheng67c90212009-10-27 21:35:42 +0000839 if (partCount() > 1)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000840 return significand.parts;
841 else
842 return &significand.part;
843}
844
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000845void
846APFloat::zeroSignificand()
847{
848 category = fcNormal;
849 APInt::tcSet(significandParts(), 0, partCount());
850}
851
852/* Increment an fcNormal floating point number's significand. */
853void
854APFloat::incrementSignificand()
855{
856 integerPart carry;
857
858 carry = APInt::tcIncrement(significandParts(), partCount());
859
860 /* Our callers should never cause us to overflow. */
861 assert(carry == 0);
Duncan Sandsa41634e2011-08-12 14:54:45 +0000862 (void)carry;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000863}
864
865/* Add the significand of the RHS. Returns the carry flag. */
866integerPart
867APFloat::addSignificand(const APFloat &rhs)
868{
869 integerPart *parts;
870
871 parts = significandParts();
872
873 assert(semantics == rhs.semantics);
874 assert(exponent == rhs.exponent);
875
876 return APInt::tcAdd(parts, rhs.significandParts(), 0, partCount());
877}
878
879/* Subtract the significand of the RHS with a borrow flag. Returns
880 the borrow flag. */
881integerPart
882APFloat::subtractSignificand(const APFloat &rhs, integerPart borrow)
883{
884 integerPart *parts;
885
886 parts = significandParts();
887
888 assert(semantics == rhs.semantics);
889 assert(exponent == rhs.exponent);
890
891 return APInt::tcSubtract(parts, rhs.significandParts(), borrow,
Neil Booth9acbf5a2007-09-26 21:33:42 +0000892 partCount());
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000893}
894
895/* Multiply the significand of the RHS. If ADDEND is non-NULL, add it
896 on to the full-precision result of the multiplication. Returns the
897 lost fraction. */
898lostFraction
899APFloat::multiplySignificand(const APFloat &rhs, const APFloat *addend)
900{
Neil Booth9acbf5a2007-09-26 21:33:42 +0000901 unsigned int omsb; // One, not zero, based MSB.
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000902 unsigned int partsCount, newPartsCount, precision;
903 integerPart *lhsSignificand;
904 integerPart scratch[4];
905 integerPart *fullSignificand;
906 lostFraction lost_fraction;
Dale Johannesen4f0bd682008-10-09 23:00:39 +0000907 bool ignored;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000908
909 assert(semantics == rhs.semantics);
910
911 precision = semantics->precision;
912 newPartsCount = partCountForBits(precision * 2);
913
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000914 if (newPartsCount > 4)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000915 fullSignificand = new integerPart[newPartsCount];
916 else
917 fullSignificand = scratch;
918
919 lhsSignificand = significandParts();
920 partsCount = partCount();
921
922 APInt::tcFullMultiply(fullSignificand, lhsSignificand,
Neil Booth0ea72a92007-10-06 00:24:48 +0000923 rhs.significandParts(), partsCount, partsCount);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000924
925 lost_fraction = lfExactlyZero;
926 omsb = APInt::tcMSB(fullSignificand, newPartsCount) + 1;
927 exponent += rhs.exponent;
928
Shuxin Yangbbddbac2013-05-13 18:03:12 +0000929 // Assume the operands involved in the multiplication are single-precision
930 // FP, and the two multiplicants are:
931 // *this = a23 . a22 ... a0 * 2^e1
932 // rhs = b23 . b22 ... b0 * 2^e2
933 // the result of multiplication is:
934 // *this = c47 c46 . c45 ... c0 * 2^(e1+e2)
935 // Note that there are two significant bits at the left-hand side of the
936 // radix point. Move the radix point toward left by one bit, and adjust
937 // exponent accordingly.
938 exponent += 1;
939
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000940 if (addend) {
Shuxin Yangbbddbac2013-05-13 18:03:12 +0000941 // The intermediate result of the multiplication has "2 * precision"
942 // signicant bit; adjust the addend to be consistent with mul result.
943 //
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000944 Significand savedSignificand = significand;
945 const fltSemantics *savedSemantics = semantics;
946 fltSemantics extendedSemantics;
947 opStatus status;
948 unsigned int extendedPrecision;
949
950 /* Normalize our MSB. */
Shuxin Yangbbddbac2013-05-13 18:03:12 +0000951 extendedPrecision = 2 * precision;
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000952 if (omsb != extendedPrecision) {
Shuxin Yangbbddbac2013-05-13 18:03:12 +0000953 assert(extendedPrecision > omsb);
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000954 APInt::tcShiftLeft(fullSignificand, newPartsCount,
955 extendedPrecision - omsb);
956 exponent -= extendedPrecision - omsb;
957 }
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000958
959 /* Create new semantics. */
960 extendedSemantics = *semantics;
961 extendedSemantics.precision = extendedPrecision;
962
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000963 if (newPartsCount == 1)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000964 significand.part = fullSignificand[0];
965 else
966 significand.parts = fullSignificand;
967 semantics = &extendedSemantics;
968
969 APFloat extendedAddend(*addend);
Dale Johannesen4f0bd682008-10-09 23:00:39 +0000970 status = extendedAddend.convert(extendedSemantics, rmTowardZero, &ignored);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000971 assert(status == opOK);
Duncan Sandsa41634e2011-08-12 14:54:45 +0000972 (void)status;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000973 lost_fraction = addOrSubtractSignificand(extendedAddend, false);
974
975 /* Restore our state. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000976 if (newPartsCount == 1)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000977 fullSignificand[0] = significand.part;
978 significand = savedSignificand;
979 semantics = savedSemantics;
980
981 omsb = APInt::tcMSB(fullSignificand, newPartsCount) + 1;
982 }
983
Shuxin Yangbbddbac2013-05-13 18:03:12 +0000984 // Convert the result having "2 * precision" significant-bits back to the one
985 // having "precision" significant-bits. First, move the radix point from
986 // poision "2*precision - 1" to "precision - 1". The exponent need to be
987 // adjusted by "2*precision - 1" - "precision - 1" = "precision".
988 exponent -= precision;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000989
Shuxin Yangbbddbac2013-05-13 18:03:12 +0000990 // In case MSB resides at the left-hand side of radix point, shift the
991 // mantissa right by some amount to make sure the MSB reside right before
992 // the radix point (i.e. "MSB . rest-significant-bits").
993 //
994 // Note that the result is not normalized when "omsb < precision". So, the
995 // caller needs to call APFloat::normalize() if normalized value is expected.
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000996 if (omsb > precision) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000997 unsigned int bits, significantParts;
998 lostFraction lf;
999
1000 bits = omsb - precision;
1001 significantParts = partCountForBits(omsb);
1002 lf = shiftRight(fullSignificand, significantParts, bits);
1003 lost_fraction = combineLostFractions(lf, lost_fraction);
1004 exponent += bits;
1005 }
1006
1007 APInt::tcAssign(lhsSignificand, fullSignificand, partsCount);
1008
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001009 if (newPartsCount > 4)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001010 delete [] fullSignificand;
1011
1012 return lost_fraction;
1013}
1014
1015/* Multiply the significands of LHS and RHS to DST. */
1016lostFraction
1017APFloat::divideSignificand(const APFloat &rhs)
1018{
1019 unsigned int bit, i, partsCount;
1020 const integerPart *rhsSignificand;
1021 integerPart *lhsSignificand, *dividend, *divisor;
1022 integerPart scratch[4];
1023 lostFraction lost_fraction;
1024
1025 assert(semantics == rhs.semantics);
1026
1027 lhsSignificand = significandParts();
1028 rhsSignificand = rhs.significandParts();
1029 partsCount = partCount();
1030
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001031 if (partsCount > 2)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001032 dividend = new integerPart[partsCount * 2];
1033 else
1034 dividend = scratch;
1035
1036 divisor = dividend + partsCount;
1037
1038 /* Copy the dividend and divisor as they will be modified in-place. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001039 for (i = 0; i < partsCount; i++) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001040 dividend[i] = lhsSignificand[i];
1041 divisor[i] = rhsSignificand[i];
1042 lhsSignificand[i] = 0;
1043 }
1044
1045 exponent -= rhs.exponent;
1046
1047 unsigned int precision = semantics->precision;
1048
1049 /* Normalize the divisor. */
1050 bit = precision - APInt::tcMSB(divisor, partsCount) - 1;
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001051 if (bit) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001052 exponent += bit;
1053 APInt::tcShiftLeft(divisor, partsCount, bit);
1054 }
1055
1056 /* Normalize the dividend. */
1057 bit = precision - APInt::tcMSB(dividend, partsCount) - 1;
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001058 if (bit) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001059 exponent -= bit;
1060 APInt::tcShiftLeft(dividend, partsCount, bit);
1061 }
1062
Neil Boothb93d90e2007-10-12 16:02:31 +00001063 /* Ensure the dividend >= divisor initially for the loop below.
1064 Incidentally, this means that the division loop below is
1065 guaranteed to set the integer bit to one. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001066 if (APInt::tcCompare(dividend, divisor, partsCount) < 0) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001067 exponent--;
1068 APInt::tcShiftLeft(dividend, partsCount, 1);
1069 assert(APInt::tcCompare(dividend, divisor, partsCount) >= 0);
1070 }
1071
1072 /* Long division. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001073 for (bit = precision; bit; bit -= 1) {
1074 if (APInt::tcCompare(dividend, divisor, partsCount) >= 0) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001075 APInt::tcSubtract(dividend, divisor, 0, partsCount);
1076 APInt::tcSetBit(lhsSignificand, bit - 1);
1077 }
1078
1079 APInt::tcShiftLeft(dividend, partsCount, 1);
1080 }
1081
1082 /* Figure out the lost fraction. */
1083 int cmp = APInt::tcCompare(dividend, divisor, partsCount);
1084
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001085 if (cmp > 0)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001086 lost_fraction = lfMoreThanHalf;
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001087 else if (cmp == 0)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001088 lost_fraction = lfExactlyHalf;
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001089 else if (APInt::tcIsZero(dividend, partsCount))
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001090 lost_fraction = lfExactlyZero;
1091 else
1092 lost_fraction = lfLessThanHalf;
1093
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001094 if (partsCount > 2)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001095 delete [] dividend;
1096
1097 return lost_fraction;
1098}
1099
1100unsigned int
1101APFloat::significandMSB() const
1102{
1103 return APInt::tcMSB(significandParts(), partCount());
1104}
1105
1106unsigned int
1107APFloat::significandLSB() const
1108{
1109 return APInt::tcLSB(significandParts(), partCount());
1110}
1111
1112/* Note that a zero result is NOT normalized to fcZero. */
1113lostFraction
1114APFloat::shiftSignificandRight(unsigned int bits)
1115{
1116 /* Our exponent should not overflow. */
Michael Gottesman9dc98332013-06-24 04:06:23 +00001117 assert((ExponentType) (exponent + bits) >= exponent);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001118
1119 exponent += bits;
1120
1121 return shiftRight(significandParts(), partCount(), bits);
1122}
1123
1124/* Shift the significand left BITS bits, subtract BITS from its exponent. */
1125void
1126APFloat::shiftSignificandLeft(unsigned int bits)
1127{
1128 assert(bits < semantics->precision);
1129
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001130 if (bits) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001131 unsigned int partsCount = partCount();
1132
1133 APInt::tcShiftLeft(significandParts(), partsCount, bits);
1134 exponent -= bits;
1135
1136 assert(!APInt::tcIsZero(significandParts(), partsCount));
1137 }
1138}
1139
1140APFloat::cmpResult
1141APFloat::compareAbsoluteValue(const APFloat &rhs) const
1142{
1143 int compare;
1144
1145 assert(semantics == rhs.semantics);
Michael Gottesman8136c382013-06-26 23:17:28 +00001146 assert(isFiniteNonZero());
1147 assert(rhs.isFiniteNonZero());
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001148
1149 compare = exponent - rhs.exponent;
1150
1151 /* If exponents are equal, do an unsigned bignum comparison of the
1152 significands. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001153 if (compare == 0)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001154 compare = APInt::tcCompare(significandParts(), rhs.significandParts(),
Neil Booth9acbf5a2007-09-26 21:33:42 +00001155 partCount());
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001156
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001157 if (compare > 0)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001158 return cmpGreaterThan;
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001159 else if (compare < 0)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001160 return cmpLessThan;
1161 else
1162 return cmpEqual;
1163}
1164
1165/* Handle overflow. Sign is preserved. We either become infinity or
1166 the largest finite number. */
1167APFloat::opStatus
1168APFloat::handleOverflow(roundingMode rounding_mode)
1169{
1170 /* Infinity? */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001171 if (rounding_mode == rmNearestTiesToEven ||
1172 rounding_mode == rmNearestTiesToAway ||
1173 (rounding_mode == rmTowardPositive && !sign) ||
1174 (rounding_mode == rmTowardNegative && sign)) {
1175 category = fcInfinity;
1176 return (opStatus) (opOverflow | opInexact);
1177 }
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001178
1179 /* Otherwise we become the largest finite number. */
1180 category = fcNormal;
1181 exponent = semantics->maxExponent;
1182 APInt::tcSetLeastSignificantBits(significandParts(), partCount(),
Neil Booth9acbf5a2007-09-26 21:33:42 +00001183 semantics->precision);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001184
1185 return opInexact;
1186}
1187
Neil Booth1ca1f802007-10-03 15:16:41 +00001188/* Returns TRUE if, when truncating the current number, with BIT the
1189 new LSB, with the given lost fraction and rounding mode, the result
1190 would need to be rounded away from zero (i.e., by increasing the
1191 signficand). This routine must work for fcZero of both signs, and
1192 fcNormal numbers. */
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001193bool
1194APFloat::roundAwayFromZero(roundingMode rounding_mode,
Neil Booth1ca1f802007-10-03 15:16:41 +00001195 lostFraction lost_fraction,
1196 unsigned int bit) const
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001197{
Dale Johannesen3cf889f2007-08-31 04:03:46 +00001198 /* NaNs and infinities should not have lost fractions. */
Michael Gottesman8136c382013-06-26 23:17:28 +00001199 assert(isFiniteNonZero() || category == fcZero);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001200
Neil Booth1ca1f802007-10-03 15:16:41 +00001201 /* Current callers never pass this so we don't handle it. */
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001202 assert(lost_fraction != lfExactlyZero);
1203
Mike Stump889285d2009-05-13 23:23:20 +00001204 switch (rounding_mode) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001205 case rmNearestTiesToAway:
1206 return lost_fraction == lfExactlyHalf || lost_fraction == lfMoreThanHalf;
1207
1208 case rmNearestTiesToEven:
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001209 if (lost_fraction == lfMoreThanHalf)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001210 return true;
1211
1212 /* Our zeroes don't have a significand to test. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001213 if (lost_fraction == lfExactlyHalf && category != fcZero)
Neil Booth1ca1f802007-10-03 15:16:41 +00001214 return APInt::tcExtractBit(significandParts(), bit);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001215
1216 return false;
1217
1218 case rmTowardZero:
1219 return false;
1220
1221 case rmTowardPositive:
1222 return sign == false;
1223
1224 case rmTowardNegative:
1225 return sign == true;
1226 }
Chandler Carruthf3e85022012-01-10 18:08:01 +00001227 llvm_unreachable("Invalid rounding mode found");
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001228}
1229
1230APFloat::opStatus
1231APFloat::normalize(roundingMode rounding_mode,
Neil Booth9acbf5a2007-09-26 21:33:42 +00001232 lostFraction lost_fraction)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001233{
Neil Booth9acbf5a2007-09-26 21:33:42 +00001234 unsigned int omsb; /* One, not zero, based MSB. */
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001235 int exponentChange;
1236
Michael Gottesman8136c382013-06-26 23:17:28 +00001237 if (!isFiniteNonZero())
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001238 return opOK;
1239
1240 /* Before rounding normalize the exponent of fcNormal numbers. */
1241 omsb = significandMSB() + 1;
1242
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001243 if (omsb) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001244 /* OMSB is numbered from 1. We want to place it in the integer
Nick Lewyckyf66daac2011-10-03 21:30:08 +00001245 bit numbered PRECISION if possible, with a compensating change in
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001246 the exponent. */
1247 exponentChange = omsb - semantics->precision;
1248
1249 /* If the resulting exponent is too high, overflow according to
1250 the rounding mode. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001251 if (exponent + exponentChange > semantics->maxExponent)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001252 return handleOverflow(rounding_mode);
1253
1254 /* Subnormal numbers have exponent minExponent, and their MSB
1255 is forced based on that. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001256 if (exponent + exponentChange < semantics->minExponent)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001257 exponentChange = semantics->minExponent - exponent;
1258
1259 /* Shifting left is easy as we don't lose precision. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001260 if (exponentChange < 0) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001261 assert(lost_fraction == lfExactlyZero);
1262
1263 shiftSignificandLeft(-exponentChange);
1264
1265 return opOK;
1266 }
1267
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001268 if (exponentChange > 0) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001269 lostFraction lf;
1270
1271 /* Shift right and capture any new lost fraction. */
1272 lf = shiftSignificandRight(exponentChange);
1273
1274 lost_fraction = combineLostFractions(lf, lost_fraction);
1275
1276 /* Keep OMSB up-to-date. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001277 if (omsb > (unsigned) exponentChange)
Neil Boothb93d90e2007-10-12 16:02:31 +00001278 omsb -= exponentChange;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001279 else
Neil Booth9acbf5a2007-09-26 21:33:42 +00001280 omsb = 0;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001281 }
1282 }
1283
1284 /* Now round the number according to rounding_mode given the lost
1285 fraction. */
1286
1287 /* As specified in IEEE 754, since we do not trap we do not report
1288 underflow for exact results. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001289 if (lost_fraction == lfExactlyZero) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001290 /* Canonicalize zeroes. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001291 if (omsb == 0)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001292 category = fcZero;
1293
1294 return opOK;
1295 }
1296
1297 /* Increment the significand if we're rounding away from zero. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001298 if (roundAwayFromZero(rounding_mode, lost_fraction, 0)) {
1299 if (omsb == 0)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001300 exponent = semantics->minExponent;
1301
1302 incrementSignificand();
1303 omsb = significandMSB() + 1;
1304
1305 /* Did the significand increment overflow? */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001306 if (omsb == (unsigned) semantics->precision + 1) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001307 /* Renormalize by incrementing the exponent and shifting our
Neil Booth9acbf5a2007-09-26 21:33:42 +00001308 significand right one. However if we already have the
1309 maximum exponent we overflow to infinity. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001310 if (exponent == semantics->maxExponent) {
Neil Booth9acbf5a2007-09-26 21:33:42 +00001311 category = fcInfinity;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001312
Neil Booth9acbf5a2007-09-26 21:33:42 +00001313 return (opStatus) (opOverflow | opInexact);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001314 }
1315
1316 shiftSignificandRight(1);
1317
1318 return opInexact;
1319 }
1320 }
1321
1322 /* The normal case - we were and are not denormal, and any
1323 significand increment above didn't overflow. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001324 if (omsb == semantics->precision)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001325 return opInexact;
1326
1327 /* We have a non-zero denormal. */
1328 assert(omsb < semantics->precision);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001329
1330 /* Canonicalize zeroes. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001331 if (omsb == 0)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001332 category = fcZero;
1333
1334 /* The fcZero case is a denormal that underflowed to zero. */
1335 return (opStatus) (opUnderflow | opInexact);
1336}
1337
1338APFloat::opStatus
1339APFloat::addOrSubtractSpecials(const APFloat &rhs, bool subtract)
1340{
Michael Gottesman9b877e12013-06-24 09:57:57 +00001341 switch (PackCategoriesIntoKey(category, rhs.category)) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001342 default:
Torok Edwinfbcc6632009-07-14 16:55:14 +00001343 llvm_unreachable(0);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001344
Michael Gottesman9b877e12013-06-24 09:57:57 +00001345 case PackCategoriesIntoKey(fcNaN, fcZero):
1346 case PackCategoriesIntoKey(fcNaN, fcNormal):
1347 case PackCategoriesIntoKey(fcNaN, fcInfinity):
1348 case PackCategoriesIntoKey(fcNaN, fcNaN):
1349 case PackCategoriesIntoKey(fcNormal, fcZero):
1350 case PackCategoriesIntoKey(fcInfinity, fcNormal):
1351 case PackCategoriesIntoKey(fcInfinity, fcZero):
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001352 return opOK;
1353
Michael Gottesman9b877e12013-06-24 09:57:57 +00001354 case PackCategoriesIntoKey(fcZero, fcNaN):
1355 case PackCategoriesIntoKey(fcNormal, fcNaN):
1356 case PackCategoriesIntoKey(fcInfinity, fcNaN):
Dale Johannesen3cf889f2007-08-31 04:03:46 +00001357 category = fcNaN;
1358 copySignificand(rhs);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001359 return opOK;
1360
Michael Gottesman9b877e12013-06-24 09:57:57 +00001361 case PackCategoriesIntoKey(fcNormal, fcInfinity):
1362 case PackCategoriesIntoKey(fcZero, fcInfinity):
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001363 category = fcInfinity;
1364 sign = rhs.sign ^ subtract;
1365 return opOK;
1366
Michael Gottesman9b877e12013-06-24 09:57:57 +00001367 case PackCategoriesIntoKey(fcZero, fcNormal):
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001368 assign(rhs);
1369 sign = rhs.sign ^ subtract;
1370 return opOK;
1371
Michael Gottesman9b877e12013-06-24 09:57:57 +00001372 case PackCategoriesIntoKey(fcZero, fcZero):
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001373 /* Sign depends on rounding mode; handled by caller. */
1374 return opOK;
1375
Michael Gottesman9b877e12013-06-24 09:57:57 +00001376 case PackCategoriesIntoKey(fcInfinity, fcInfinity):
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001377 /* Differently signed infinities can only be validly
1378 subtracted. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001379 if (((sign ^ rhs.sign)!=0) != subtract) {
Neil Booth5fe658b2007-10-14 10:39:51 +00001380 makeNaN();
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001381 return opInvalidOp;
1382 }
1383
1384 return opOK;
1385
Michael Gottesman9b877e12013-06-24 09:57:57 +00001386 case PackCategoriesIntoKey(fcNormal, fcNormal):
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001387 return opDivByZero;
1388 }
1389}
1390
1391/* Add or subtract two normal numbers. */
1392lostFraction
1393APFloat::addOrSubtractSignificand(const APFloat &rhs, bool subtract)
1394{
1395 integerPart carry;
1396 lostFraction lost_fraction;
1397 int bits;
1398
1399 /* Determine if the operation on the absolute values is effectively
1400 an addition or subtraction. */
Hartmut Kaiserfc69d322007-10-25 23:15:31 +00001401 subtract ^= (sign ^ rhs.sign) ? true : false;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001402
1403 /* Are we bigger exponent-wise than the RHS? */
1404 bits = exponent - rhs.exponent;
1405
1406 /* Subtraction is more subtle than one might naively expect. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001407 if (subtract) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001408 APFloat temp_rhs(rhs);
1409 bool reverse;
1410
Chris Lattner3da18eb2007-08-24 03:02:34 +00001411 if (bits == 0) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001412 reverse = compareAbsoluteValue(temp_rhs) == cmpLessThan;
1413 lost_fraction = lfExactlyZero;
Chris Lattner3da18eb2007-08-24 03:02:34 +00001414 } else if (bits > 0) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001415 lost_fraction = temp_rhs.shiftSignificandRight(bits - 1);
1416 shiftSignificandLeft(1);
1417 reverse = false;
Chris Lattner3da18eb2007-08-24 03:02:34 +00001418 } else {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001419 lost_fraction = shiftSignificandRight(-bits - 1);
1420 temp_rhs.shiftSignificandLeft(1);
1421 reverse = true;
1422 }
1423
Chris Lattner3da18eb2007-08-24 03:02:34 +00001424 if (reverse) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001425 carry = temp_rhs.subtractSignificand
Neil Booth9acbf5a2007-09-26 21:33:42 +00001426 (*this, lost_fraction != lfExactlyZero);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001427 copySignificand(temp_rhs);
1428 sign = !sign;
1429 } else {
1430 carry = subtractSignificand
Neil Booth9acbf5a2007-09-26 21:33:42 +00001431 (temp_rhs, lost_fraction != lfExactlyZero);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001432 }
1433
1434 /* Invert the lost fraction - it was on the RHS and
1435 subtracted. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001436 if (lost_fraction == lfLessThanHalf)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001437 lost_fraction = lfMoreThanHalf;
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001438 else if (lost_fraction == lfMoreThanHalf)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001439 lost_fraction = lfLessThanHalf;
1440
1441 /* The code above is intended to ensure that no borrow is
1442 necessary. */
1443 assert(!carry);
Duncan Sandsa41634e2011-08-12 14:54:45 +00001444 (void)carry;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001445 } else {
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001446 if (bits > 0) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001447 APFloat temp_rhs(rhs);
1448
1449 lost_fraction = temp_rhs.shiftSignificandRight(bits);
1450 carry = addSignificand(temp_rhs);
1451 } else {
1452 lost_fraction = shiftSignificandRight(-bits);
1453 carry = addSignificand(rhs);
1454 }
1455
1456 /* We have a guard bit; generating a carry cannot happen. */
1457 assert(!carry);
Duncan Sandsa41634e2011-08-12 14:54:45 +00001458 (void)carry;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001459 }
1460
1461 return lost_fraction;
1462}
1463
1464APFloat::opStatus
1465APFloat::multiplySpecials(const APFloat &rhs)
1466{
Michael Gottesman9b877e12013-06-24 09:57:57 +00001467 switch (PackCategoriesIntoKey(category, rhs.category)) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001468 default:
Torok Edwinfbcc6632009-07-14 16:55:14 +00001469 llvm_unreachable(0);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001470
Michael Gottesman9b877e12013-06-24 09:57:57 +00001471 case PackCategoriesIntoKey(fcNaN, fcZero):
1472 case PackCategoriesIntoKey(fcNaN, fcNormal):
1473 case PackCategoriesIntoKey(fcNaN, fcInfinity):
1474 case PackCategoriesIntoKey(fcNaN, fcNaN):
Dale Johannesen3cf889f2007-08-31 04:03:46 +00001475 return opOK;
1476
Michael Gottesman9b877e12013-06-24 09:57:57 +00001477 case PackCategoriesIntoKey(fcZero, fcNaN):
1478 case PackCategoriesIntoKey(fcNormal, fcNaN):
1479 case PackCategoriesIntoKey(fcInfinity, fcNaN):
Dale Johannesen3cf889f2007-08-31 04:03:46 +00001480 category = fcNaN;
1481 copySignificand(rhs);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001482 return opOK;
1483
Michael Gottesman9b877e12013-06-24 09:57:57 +00001484 case PackCategoriesIntoKey(fcNormal, fcInfinity):
1485 case PackCategoriesIntoKey(fcInfinity, fcNormal):
1486 case PackCategoriesIntoKey(fcInfinity, fcInfinity):
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001487 category = fcInfinity;
1488 return opOK;
1489
Michael Gottesman9b877e12013-06-24 09:57:57 +00001490 case PackCategoriesIntoKey(fcZero, fcNormal):
1491 case PackCategoriesIntoKey(fcNormal, fcZero):
1492 case PackCategoriesIntoKey(fcZero, fcZero):
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001493 category = fcZero;
1494 return opOK;
1495
Michael Gottesman9b877e12013-06-24 09:57:57 +00001496 case PackCategoriesIntoKey(fcZero, fcInfinity):
1497 case PackCategoriesIntoKey(fcInfinity, fcZero):
Neil Booth5fe658b2007-10-14 10:39:51 +00001498 makeNaN();
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001499 return opInvalidOp;
1500
Michael Gottesman9b877e12013-06-24 09:57:57 +00001501 case PackCategoriesIntoKey(fcNormal, fcNormal):
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001502 return opOK;
1503 }
1504}
1505
1506APFloat::opStatus
1507APFloat::divideSpecials(const APFloat &rhs)
1508{
Michael Gottesman9b877e12013-06-24 09:57:57 +00001509 switch (PackCategoriesIntoKey(category, rhs.category)) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001510 default:
Torok Edwinfbcc6632009-07-14 16:55:14 +00001511 llvm_unreachable(0);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001512
Michael Gottesman9b877e12013-06-24 09:57:57 +00001513 case PackCategoriesIntoKey(fcNaN, fcZero):
1514 case PackCategoriesIntoKey(fcNaN, fcNormal):
1515 case PackCategoriesIntoKey(fcNaN, fcInfinity):
1516 case PackCategoriesIntoKey(fcNaN, fcNaN):
1517 case PackCategoriesIntoKey(fcInfinity, fcZero):
1518 case PackCategoriesIntoKey(fcInfinity, fcNormal):
1519 case PackCategoriesIntoKey(fcZero, fcInfinity):
1520 case PackCategoriesIntoKey(fcZero, fcNormal):
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001521 return opOK;
1522
Michael Gottesman9b877e12013-06-24 09:57:57 +00001523 case PackCategoriesIntoKey(fcZero, fcNaN):
1524 case PackCategoriesIntoKey(fcNormal, fcNaN):
1525 case PackCategoriesIntoKey(fcInfinity, fcNaN):
Dale Johannesen3cf889f2007-08-31 04:03:46 +00001526 category = fcNaN;
1527 copySignificand(rhs);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001528 return opOK;
1529
Michael Gottesman9b877e12013-06-24 09:57:57 +00001530 case PackCategoriesIntoKey(fcNormal, fcInfinity):
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001531 category = fcZero;
1532 return opOK;
1533
Michael Gottesman9b877e12013-06-24 09:57:57 +00001534 case PackCategoriesIntoKey(fcNormal, fcZero):
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001535 category = fcInfinity;
1536 return opDivByZero;
1537
Michael Gottesman9b877e12013-06-24 09:57:57 +00001538 case PackCategoriesIntoKey(fcInfinity, fcInfinity):
1539 case PackCategoriesIntoKey(fcZero, fcZero):
Neil Booth5fe658b2007-10-14 10:39:51 +00001540 makeNaN();
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001541 return opInvalidOp;
1542
Michael Gottesman9b877e12013-06-24 09:57:57 +00001543 case PackCategoriesIntoKey(fcNormal, fcNormal):
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001544 return opOK;
1545 }
1546}
1547
Dale Johannesenb5721632009-01-21 00:35:19 +00001548APFloat::opStatus
1549APFloat::modSpecials(const APFloat &rhs)
1550{
Michael Gottesman9b877e12013-06-24 09:57:57 +00001551 switch (PackCategoriesIntoKey(category, rhs.category)) {
Dale Johannesenb5721632009-01-21 00:35:19 +00001552 default:
Torok Edwinfbcc6632009-07-14 16:55:14 +00001553 llvm_unreachable(0);
Dale Johannesenb5721632009-01-21 00:35:19 +00001554
Michael Gottesman9b877e12013-06-24 09:57:57 +00001555 case PackCategoriesIntoKey(fcNaN, fcZero):
1556 case PackCategoriesIntoKey(fcNaN, fcNormal):
1557 case PackCategoriesIntoKey(fcNaN, fcInfinity):
1558 case PackCategoriesIntoKey(fcNaN, fcNaN):
1559 case PackCategoriesIntoKey(fcZero, fcInfinity):
1560 case PackCategoriesIntoKey(fcZero, fcNormal):
1561 case PackCategoriesIntoKey(fcNormal, fcInfinity):
Dale Johannesenb5721632009-01-21 00:35:19 +00001562 return opOK;
1563
Michael Gottesman9b877e12013-06-24 09:57:57 +00001564 case PackCategoriesIntoKey(fcZero, fcNaN):
1565 case PackCategoriesIntoKey(fcNormal, fcNaN):
1566 case PackCategoriesIntoKey(fcInfinity, fcNaN):
Dale Johannesenb5721632009-01-21 00:35:19 +00001567 category = fcNaN;
1568 copySignificand(rhs);
1569 return opOK;
1570
Michael Gottesman9b877e12013-06-24 09:57:57 +00001571 case PackCategoriesIntoKey(fcNormal, fcZero):
1572 case PackCategoriesIntoKey(fcInfinity, fcZero):
1573 case PackCategoriesIntoKey(fcInfinity, fcNormal):
1574 case PackCategoriesIntoKey(fcInfinity, fcInfinity):
1575 case PackCategoriesIntoKey(fcZero, fcZero):
Dale Johannesenb5721632009-01-21 00:35:19 +00001576 makeNaN();
1577 return opInvalidOp;
1578
Michael Gottesman9b877e12013-06-24 09:57:57 +00001579 case PackCategoriesIntoKey(fcNormal, fcNormal):
Dale Johannesenb5721632009-01-21 00:35:19 +00001580 return opOK;
1581 }
1582}
1583
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001584/* Change sign. */
1585void
1586APFloat::changeSign()
1587{
1588 /* Look mummy, this one's easy. */
1589 sign = !sign;
1590}
1591
Dale Johannesen689d17d2007-08-31 23:35:31 +00001592void
1593APFloat::clearSign()
1594{
1595 /* So is this one. */
1596 sign = 0;
1597}
1598
1599void
1600APFloat::copySign(const APFloat &rhs)
1601{
1602 /* And this one. */
1603 sign = rhs.sign;
1604}
1605
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001606/* Normalized addition or subtraction. */
1607APFloat::opStatus
1608APFloat::addOrSubtract(const APFloat &rhs, roundingMode rounding_mode,
Neil Booth9acbf5a2007-09-26 21:33:42 +00001609 bool subtract)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001610{
1611 opStatus fs;
1612
1613 fs = addOrSubtractSpecials(rhs, subtract);
1614
1615 /* This return code means it was not a simple case. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001616 if (fs == opDivByZero) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001617 lostFraction lost_fraction;
1618
1619 lost_fraction = addOrSubtractSignificand(rhs, subtract);
1620 fs = normalize(rounding_mode, lost_fraction);
1621
1622 /* Can only be zero if we lost no fraction. */
1623 assert(category != fcZero || lost_fraction == lfExactlyZero);
1624 }
1625
1626 /* If two numbers add (exactly) to zero, IEEE 754 decrees it is a
1627 positive zero unless rounding to minus infinity, except that
1628 adding two like-signed zeroes gives that zero. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001629 if (category == fcZero) {
1630 if (rhs.category != fcZero || (sign == rhs.sign) == subtract)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001631 sign = (rounding_mode == rmTowardNegative);
1632 }
1633
1634 return fs;
1635}
1636
1637/* Normalized addition. */
1638APFloat::opStatus
1639APFloat::add(const APFloat &rhs, roundingMode rounding_mode)
1640{
1641 return addOrSubtract(rhs, rounding_mode, false);
1642}
1643
1644/* Normalized subtraction. */
1645APFloat::opStatus
1646APFloat::subtract(const APFloat &rhs, roundingMode rounding_mode)
1647{
1648 return addOrSubtract(rhs, rounding_mode, true);
1649}
1650
1651/* Normalized multiply. */
1652APFloat::opStatus
1653APFloat::multiply(const APFloat &rhs, roundingMode rounding_mode)
1654{
1655 opStatus fs;
1656
1657 sign ^= rhs.sign;
1658 fs = multiplySpecials(rhs);
1659
Michael Gottesman8136c382013-06-26 23:17:28 +00001660 if (isFiniteNonZero()) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001661 lostFraction lost_fraction = multiplySignificand(rhs, 0);
1662 fs = normalize(rounding_mode, lost_fraction);
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001663 if (lost_fraction != lfExactlyZero)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001664 fs = (opStatus) (fs | opInexact);
1665 }
1666
1667 return fs;
1668}
1669
1670/* Normalized divide. */
1671APFloat::opStatus
1672APFloat::divide(const APFloat &rhs, roundingMode rounding_mode)
1673{
1674 opStatus fs;
1675
1676 sign ^= rhs.sign;
1677 fs = divideSpecials(rhs);
1678
Michael Gottesman8136c382013-06-26 23:17:28 +00001679 if (isFiniteNonZero()) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001680 lostFraction lost_fraction = divideSignificand(rhs);
1681 fs = normalize(rounding_mode, lost_fraction);
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001682 if (lost_fraction != lfExactlyZero)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001683 fs = (opStatus) (fs | opInexact);
1684 }
1685
1686 return fs;
1687}
1688
Dale Johannesenfe750172009-01-20 18:35:05 +00001689/* Normalized remainder. This is not currently correct in all cases. */
1690APFloat::opStatus
1691APFloat::remainder(const APFloat &rhs)
1692{
1693 opStatus fs;
1694 APFloat V = *this;
1695 unsigned int origSign = sign;
1696
Dale Johannesenfe750172009-01-20 18:35:05 +00001697 fs = V.divide(rhs, rmNearestTiesToEven);
1698 if (fs == opDivByZero)
1699 return fs;
1700
1701 int parts = partCount();
1702 integerPart *x = new integerPart[parts];
1703 bool ignored;
1704 fs = V.convertToInteger(x, parts * integerPartWidth, true,
1705 rmNearestTiesToEven, &ignored);
1706 if (fs==opInvalidOp)
1707 return fs;
1708
1709 fs = V.convertFromZeroExtendedInteger(x, parts * integerPartWidth, true,
1710 rmNearestTiesToEven);
1711 assert(fs==opOK); // should always work
1712
1713 fs = V.multiply(rhs, rmNearestTiesToEven);
1714 assert(fs==opOK || fs==opInexact); // should not overflow or underflow
1715
1716 fs = subtract(V, rmNearestTiesToEven);
1717 assert(fs==opOK || fs==opInexact); // likewise
1718
1719 if (isZero())
1720 sign = origSign; // IEEE754 requires this
1721 delete[] x;
1722 return fs;
1723}
1724
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001725/* Normalized llvm frem (C fmod).
Dale Johannesenfe750172009-01-20 18:35:05 +00001726 This is not currently correct in all cases. */
Dale Johannesen689d17d2007-08-31 23:35:31 +00001727APFloat::opStatus
1728APFloat::mod(const APFloat &rhs, roundingMode rounding_mode)
1729{
1730 opStatus fs;
Dale Johannesenb5721632009-01-21 00:35:19 +00001731 fs = modSpecials(rhs);
Dale Johannesen689d17d2007-08-31 23:35:31 +00001732
Michael Gottesman8136c382013-06-26 23:17:28 +00001733 if (isFiniteNonZero() && rhs.isFiniteNonZero()) {
Dale Johannesenb5721632009-01-21 00:35:19 +00001734 APFloat V = *this;
1735 unsigned int origSign = sign;
Dale Johannesen689d17d2007-08-31 23:35:31 +00001736
Dale Johannesenb5721632009-01-21 00:35:19 +00001737 fs = V.divide(rhs, rmNearestTiesToEven);
1738 if (fs == opDivByZero)
1739 return fs;
Dale Johannesen728687c2007-09-05 20:39:49 +00001740
Dale Johannesenb5721632009-01-21 00:35:19 +00001741 int parts = partCount();
1742 integerPart *x = new integerPart[parts];
1743 bool ignored;
1744 fs = V.convertToInteger(x, parts * integerPartWidth, true,
1745 rmTowardZero, &ignored);
1746 if (fs==opInvalidOp)
1747 return fs;
Dale Johannesen728687c2007-09-05 20:39:49 +00001748
Dale Johannesenb5721632009-01-21 00:35:19 +00001749 fs = V.convertFromZeroExtendedInteger(x, parts * integerPartWidth, true,
1750 rmNearestTiesToEven);
1751 assert(fs==opOK); // should always work
Dale Johannesen728687c2007-09-05 20:39:49 +00001752
Dale Johannesenb5721632009-01-21 00:35:19 +00001753 fs = V.multiply(rhs, rounding_mode);
1754 assert(fs==opOK || fs==opInexact); // should not overflow or underflow
1755
1756 fs = subtract(V, rounding_mode);
1757 assert(fs==opOK || fs==opInexact); // likewise
1758
1759 if (isZero())
1760 sign = origSign; // IEEE754 requires this
1761 delete[] x;
1762 }
Dale Johannesen689d17d2007-08-31 23:35:31 +00001763 return fs;
1764}
1765
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001766/* Normalized fused-multiply-add. */
1767APFloat::opStatus
1768APFloat::fusedMultiplyAdd(const APFloat &multiplicand,
Neil Booth9acbf5a2007-09-26 21:33:42 +00001769 const APFloat &addend,
1770 roundingMode rounding_mode)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001771{
1772 opStatus fs;
1773
1774 /* Post-multiplication sign, before addition. */
1775 sign ^= multiplicand.sign;
1776
1777 /* If and only if all arguments are normal do we need to do an
1778 extended-precision calculation. */
Michael Gottesman8136c382013-06-26 23:17:28 +00001779 if (isFiniteNonZero() &&
1780 multiplicand.isFiniteNonZero() &&
1781 addend.isFiniteNonZero()) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001782 lostFraction lost_fraction;
1783
1784 lost_fraction = multiplySignificand(multiplicand, &addend);
1785 fs = normalize(rounding_mode, lost_fraction);
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001786 if (lost_fraction != lfExactlyZero)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001787 fs = (opStatus) (fs | opInexact);
1788
1789 /* If two numbers add (exactly) to zero, IEEE 754 decrees it is a
1790 positive zero unless rounding to minus infinity, except that
1791 adding two like-signed zeroes gives that zero. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001792 if (category == fcZero && sign != addend.sign)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001793 sign = (rounding_mode == rmTowardNegative);
1794 } else {
1795 fs = multiplySpecials(multiplicand);
1796
1797 /* FS can only be opOK or opInvalidOp. There is no more work
1798 to do in the latter case. The IEEE-754R standard says it is
1799 implementation-defined in this case whether, if ADDEND is a
Dale Johannesen3cf889f2007-08-31 04:03:46 +00001800 quiet NaN, we raise invalid op; this implementation does so.
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001801
1802 If we need to do the addition we can do so with normal
1803 precision. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001804 if (fs == opOK)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001805 fs = addOrSubtract(addend, rounding_mode, false);
1806 }
1807
1808 return fs;
1809}
1810
Owen Andersona40319b2012-08-13 23:32:49 +00001811/* Rounding-mode corrrect round to integral value. */
1812APFloat::opStatus APFloat::roundToIntegral(roundingMode rounding_mode) {
1813 opStatus fs;
Owen Andersona40319b2012-08-13 23:32:49 +00001814
Owen Anderson352dfff2012-08-15 18:28:45 +00001815 // If the exponent is large enough, we know that this value is already
1816 // integral, and the arithmetic below would potentially cause it to saturate
1817 // to +/-Inf. Bail out early instead.
Michael Gottesman8136c382013-06-26 23:17:28 +00001818 if (isFiniteNonZero() && exponent+1 >= (int)semanticsPrecision(*semantics))
Owen Anderson352dfff2012-08-15 18:28:45 +00001819 return opOK;
1820
Owen Andersona40319b2012-08-13 23:32:49 +00001821 // The algorithm here is quite simple: we add 2^(p-1), where p is the
1822 // precision of our format, and then subtract it back off again. The choice
1823 // of rounding modes for the addition/subtraction determines the rounding mode
1824 // for our integral rounding as well.
Owen Andersonbe7e2972012-08-15 16:42:53 +00001825 // NOTE: When the input value is negative, we do subtraction followed by
Owen Anderson1ff74b02012-08-15 05:39:46 +00001826 // addition instead.
Owen Anderson0b357222012-08-14 18:51:15 +00001827 APInt IntegerConstant(NextPowerOf2(semanticsPrecision(*semantics)), 1);
1828 IntegerConstant <<= semanticsPrecision(*semantics)-1;
Owen Andersona40319b2012-08-13 23:32:49 +00001829 APFloat MagicConstant(*semantics);
1830 fs = MagicConstant.convertFromAPInt(IntegerConstant, false,
1831 rmNearestTiesToEven);
Owen Anderson1ff74b02012-08-15 05:39:46 +00001832 MagicConstant.copySign(*this);
1833
Owen Andersona40319b2012-08-13 23:32:49 +00001834 if (fs != opOK)
1835 return fs;
1836
Owen Anderson1ff74b02012-08-15 05:39:46 +00001837 // Preserve the input sign so that we can handle 0.0/-0.0 cases correctly.
1838 bool inputSign = isNegative();
1839
Owen Andersona40319b2012-08-13 23:32:49 +00001840 fs = add(MagicConstant, rounding_mode);
1841 if (fs != opOK && fs != opInexact)
1842 return fs;
1843
1844 fs = subtract(MagicConstant, rounding_mode);
Owen Anderson1ff74b02012-08-15 05:39:46 +00001845
1846 // Restore the input sign.
1847 if (inputSign != isNegative())
1848 changeSign();
1849
Owen Andersona40319b2012-08-13 23:32:49 +00001850 return fs;
1851}
1852
1853
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001854/* Comparison requires normalized numbers. */
1855APFloat::cmpResult
1856APFloat::compare(const APFloat &rhs) const
1857{
1858 cmpResult result;
1859
1860 assert(semantics == rhs.semantics);
1861
Michael Gottesman9b877e12013-06-24 09:57:57 +00001862 switch (PackCategoriesIntoKey(category, rhs.category)) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001863 default:
Torok Edwinfbcc6632009-07-14 16:55:14 +00001864 llvm_unreachable(0);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001865
Michael Gottesman9b877e12013-06-24 09:57:57 +00001866 case PackCategoriesIntoKey(fcNaN, fcZero):
1867 case PackCategoriesIntoKey(fcNaN, fcNormal):
1868 case PackCategoriesIntoKey(fcNaN, fcInfinity):
1869 case PackCategoriesIntoKey(fcNaN, fcNaN):
1870 case PackCategoriesIntoKey(fcZero, fcNaN):
1871 case PackCategoriesIntoKey(fcNormal, fcNaN):
1872 case PackCategoriesIntoKey(fcInfinity, fcNaN):
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001873 return cmpUnordered;
1874
Michael Gottesman9b877e12013-06-24 09:57:57 +00001875 case PackCategoriesIntoKey(fcInfinity, fcNormal):
1876 case PackCategoriesIntoKey(fcInfinity, fcZero):
1877 case PackCategoriesIntoKey(fcNormal, fcZero):
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001878 if (sign)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001879 return cmpLessThan;
1880 else
1881 return cmpGreaterThan;
1882
Michael Gottesman9b877e12013-06-24 09:57:57 +00001883 case PackCategoriesIntoKey(fcNormal, fcInfinity):
1884 case PackCategoriesIntoKey(fcZero, fcInfinity):
1885 case PackCategoriesIntoKey(fcZero, fcNormal):
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001886 if (rhs.sign)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001887 return cmpGreaterThan;
1888 else
1889 return cmpLessThan;
1890
Michael Gottesman9b877e12013-06-24 09:57:57 +00001891 case PackCategoriesIntoKey(fcInfinity, fcInfinity):
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001892 if (sign == rhs.sign)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001893 return cmpEqual;
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001894 else if (sign)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001895 return cmpLessThan;
1896 else
1897 return cmpGreaterThan;
1898
Michael Gottesman9b877e12013-06-24 09:57:57 +00001899 case PackCategoriesIntoKey(fcZero, fcZero):
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001900 return cmpEqual;
1901
Michael Gottesman9b877e12013-06-24 09:57:57 +00001902 case PackCategoriesIntoKey(fcNormal, fcNormal):
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001903 break;
1904 }
1905
1906 /* Two normal numbers. Do they have the same sign? */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001907 if (sign != rhs.sign) {
1908 if (sign)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001909 result = cmpLessThan;
1910 else
1911 result = cmpGreaterThan;
1912 } else {
1913 /* Compare absolute values; invert result if negative. */
1914 result = compareAbsoluteValue(rhs);
1915
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001916 if (sign) {
1917 if (result == cmpLessThan)
Neil Booth9acbf5a2007-09-26 21:33:42 +00001918 result = cmpGreaterThan;
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001919 else if (result == cmpGreaterThan)
Neil Booth9acbf5a2007-09-26 21:33:42 +00001920 result = cmpLessThan;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001921 }
1922 }
1923
1924 return result;
1925}
1926
Dale Johannesen4f0bd682008-10-09 23:00:39 +00001927/// APFloat::convert - convert a value of one floating point type to another.
1928/// The return value corresponds to the IEEE754 exceptions. *losesInfo
1929/// records whether the transformation lost information, i.e. whether
1930/// converting the result back to the original type will produce the
1931/// original value (this is almost the same as return value==fsOK, but there
1932/// are edge cases where this is not so).
1933
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001934APFloat::opStatus
1935APFloat::convert(const fltSemantics &toSemantics,
Dale Johannesen4f0bd682008-10-09 23:00:39 +00001936 roundingMode rounding_mode, bool *losesInfo)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001937{
Neil Bootha8d72692007-09-22 02:56:19 +00001938 lostFraction lostFraction;
1939 unsigned int newPartCount, oldPartCount;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001940 opStatus fs;
Eli Friedmana84ad7d2011-11-26 03:38:02 +00001941 int shift;
1942 const fltSemantics &fromSemantics = *semantics;
Neil Booth9acbf5a2007-09-26 21:33:42 +00001943
Neil Bootha8d72692007-09-22 02:56:19 +00001944 lostFraction = lfExactlyZero;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001945 newPartCount = partCountForBits(toSemantics.precision + 1);
Neil Bootha8d72692007-09-22 02:56:19 +00001946 oldPartCount = partCount();
Eli Friedmana84ad7d2011-11-26 03:38:02 +00001947 shift = toSemantics.precision - fromSemantics.precision;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001948
Eli Friedmana84ad7d2011-11-26 03:38:02 +00001949 bool X86SpecialNan = false;
1950 if (&fromSemantics == &APFloat::x87DoubleExtended &&
1951 &toSemantics != &APFloat::x87DoubleExtended && category == fcNaN &&
1952 (!(*significandParts() & 0x8000000000000000ULL) ||
1953 !(*significandParts() & 0x4000000000000000ULL))) {
1954 // x86 has some unusual NaNs which cannot be represented in any other
1955 // format; note them here.
1956 X86SpecialNan = true;
1957 }
1958
Ulrich Weigand1d4dbda2013-07-16 13:03:25 +00001959 // If this is a truncation of a denormal number, and the target semantics
1960 // has larger exponent range than the source semantics (this can happen
1961 // when truncating from PowerPC double-double to double format), the
1962 // right shift could lose result mantissa bits. Adjust exponent instead
1963 // of performing excessive shift.
1964 if (shift < 0 && isFiniteNonZero()) {
1965 int exponentChange = significandMSB() + 1 - fromSemantics.precision;
1966 if (exponent + exponentChange < toSemantics.minExponent)
1967 exponentChange = toSemantics.minExponent - exponent;
1968 if (exponentChange < shift)
1969 exponentChange = shift;
1970 if (exponentChange < 0) {
1971 shift -= exponentChange;
1972 exponent += exponentChange;
1973 }
1974 }
1975
Eli Friedmana84ad7d2011-11-26 03:38:02 +00001976 // If this is a truncation, perform the shift before we narrow the storage.
Michael Gottesman8136c382013-06-26 23:17:28 +00001977 if (shift < 0 && (isFiniteNonZero() || category==fcNaN))
Eli Friedmana84ad7d2011-11-26 03:38:02 +00001978 lostFraction = shiftRight(significandParts(), oldPartCount, -shift);
1979
1980 // Fix the storage so it can hold to new value.
Neil Bootha8d72692007-09-22 02:56:19 +00001981 if (newPartCount > oldPartCount) {
Eli Friedmana84ad7d2011-11-26 03:38:02 +00001982 // The new type requires more storage; make it available.
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001983 integerPart *newParts;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001984 newParts = new integerPart[newPartCount];
1985 APInt::tcSet(newParts, 0, newPartCount);
Michael Gottesman8136c382013-06-26 23:17:28 +00001986 if (isFiniteNonZero() || category==fcNaN)
Dale Johannesen4f55d9f2007-09-25 17:25:00 +00001987 APInt::tcAssign(newParts, significandParts(), oldPartCount);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001988 freeSignificand();
1989 significand.parts = newParts;
Eli Friedmana84ad7d2011-11-26 03:38:02 +00001990 } else if (newPartCount == 1 && oldPartCount != 1) {
1991 // Switch to built-in storage for a single part.
1992 integerPart newPart = 0;
Michael Gottesman8136c382013-06-26 23:17:28 +00001993 if (isFiniteNonZero() || category==fcNaN)
Eli Friedmana84ad7d2011-11-26 03:38:02 +00001994 newPart = significandParts()[0];
1995 freeSignificand();
1996 significand.part = newPart;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001997 }
1998
Eli Friedmana84ad7d2011-11-26 03:38:02 +00001999 // Now that we have the right storage, switch the semantics.
2000 semantics = &toSemantics;
2001
2002 // If this is an extension, perform the shift now that the storage is
2003 // available.
Michael Gottesman8136c382013-06-26 23:17:28 +00002004 if (shift > 0 && (isFiniteNonZero() || category==fcNaN))
Eli Friedmana84ad7d2011-11-26 03:38:02 +00002005 APInt::tcShiftLeft(significandParts(), newPartCount, shift);
2006
Michael Gottesman8136c382013-06-26 23:17:28 +00002007 if (isFiniteNonZero()) {
Neil Bootha8d72692007-09-22 02:56:19 +00002008 fs = normalize(rounding_mode, lostFraction);
Dale Johannesen4f0bd682008-10-09 23:00:39 +00002009 *losesInfo = (fs != opOK);
Dale Johannesen4f55d9f2007-09-25 17:25:00 +00002010 } else if (category == fcNaN) {
Eli Friedmana84ad7d2011-11-26 03:38:02 +00002011 *losesInfo = lostFraction != lfExactlyZero || X86SpecialNan;
Benjamin Kramerb361adb2013-01-25 17:01:00 +00002012
2013 // For x87 extended precision, we want to make a NaN, not a special NaN if
2014 // the input wasn't special either.
2015 if (!X86SpecialNan && semantics == &APFloat::x87DoubleExtended)
2016 APInt::tcSetBit(significandParts(), semantics->precision - 1);
2017
Dale Johannesen4f55d9f2007-09-25 17:25:00 +00002018 // gcc forces the Quiet bit on, which means (float)(double)(float_sNan)
2019 // does not give you back the same bits. This is dubious, and we
2020 // don't currently do it. You're really supposed to get
2021 // an invalid operation signal at runtime, but nobody does that.
Dale Johannesen4f0bd682008-10-09 23:00:39 +00002022 fs = opOK;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002023 } else {
Dale Johannesen4f0bd682008-10-09 23:00:39 +00002024 *losesInfo = false;
Eli Friedman31f01162011-11-28 18:50:37 +00002025 fs = opOK;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002026 }
2027
2028 return fs;
2029}
2030
2031/* Convert a floating point number to an integer according to the
2032 rounding mode. If the rounded integer value is out of range this
Neil Booth618d0fc2007-11-01 22:43:37 +00002033 returns an invalid operation exception and the contents of the
2034 destination parts are unspecified. If the rounded value is in
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002035 range but the floating point number is not the exact integer, the C
2036 standard doesn't require an inexact exception to be raised. IEEE
2037 854 does require it so we do that.
2038
2039 Note that for conversions to integer type the C standard requires
2040 round-to-zero to always be used. */
2041APFloat::opStatus
Neil Booth618d0fc2007-11-01 22:43:37 +00002042APFloat::convertToSignExtendedInteger(integerPart *parts, unsigned int width,
2043 bool isSigned,
Dale Johannesen4f0bd682008-10-09 23:00:39 +00002044 roundingMode rounding_mode,
2045 bool *isExact) const
Neil Booth618d0fc2007-11-01 22:43:37 +00002046{
2047 lostFraction lost_fraction;
2048 const integerPart *src;
2049 unsigned int dstPartsCount, truncatedBits;
2050
Dale Johannesen4f0bd682008-10-09 23:00:39 +00002051 *isExact = false;
2052
Neil Booth618d0fc2007-11-01 22:43:37 +00002053 /* Handle the three special cases first. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002054 if (category == fcInfinity || category == fcNaN)
Neil Booth618d0fc2007-11-01 22:43:37 +00002055 return opInvalidOp;
2056
2057 dstPartsCount = partCountForBits(width);
2058
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002059 if (category == fcZero) {
Neil Booth618d0fc2007-11-01 22:43:37 +00002060 APInt::tcSet(parts, 0, dstPartsCount);
Dale Johannesen7221af32008-10-07 00:40:01 +00002061 // Negative zero can't be represented as an int.
Dale Johannesen4f0bd682008-10-09 23:00:39 +00002062 *isExact = !sign;
2063 return opOK;
Neil Booth618d0fc2007-11-01 22:43:37 +00002064 }
2065
2066 src = significandParts();
2067
2068 /* Step 1: place our absolute value, with any fraction truncated, in
2069 the destination. */
2070 if (exponent < 0) {
2071 /* Our absolute value is less than one; truncate everything. */
2072 APInt::tcSet(parts, 0, dstPartsCount);
Dale Johannesen740e9872009-01-19 21:17:05 +00002073 /* For exponent -1 the integer bit represents .5, look at that.
2074 For smaller exponents leftmost truncated bit is 0. */
2075 truncatedBits = semantics->precision -1U - exponent;
Neil Booth618d0fc2007-11-01 22:43:37 +00002076 } else {
2077 /* We want the most significant (exponent + 1) bits; the rest are
2078 truncated. */
2079 unsigned int bits = exponent + 1U;
2080
2081 /* Hopelessly large in magnitude? */
2082 if (bits > width)
2083 return opInvalidOp;
2084
2085 if (bits < semantics->precision) {
2086 /* We truncate (semantics->precision - bits) bits. */
2087 truncatedBits = semantics->precision - bits;
2088 APInt::tcExtract(parts, dstPartsCount, src, bits, truncatedBits);
2089 } else {
2090 /* We want at least as many bits as are available. */
2091 APInt::tcExtract(parts, dstPartsCount, src, semantics->precision, 0);
2092 APInt::tcShiftLeft(parts, dstPartsCount, bits - semantics->precision);
2093 truncatedBits = 0;
2094 }
2095 }
2096
2097 /* Step 2: work out any lost fraction, and increment the absolute
2098 value if we would round away from zero. */
2099 if (truncatedBits) {
2100 lost_fraction = lostFractionThroughTruncation(src, partCount(),
2101 truncatedBits);
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002102 if (lost_fraction != lfExactlyZero &&
2103 roundAwayFromZero(rounding_mode, lost_fraction, truncatedBits)) {
Neil Booth618d0fc2007-11-01 22:43:37 +00002104 if (APInt::tcIncrement(parts, dstPartsCount))
2105 return opInvalidOp; /* Overflow. */
2106 }
2107 } else {
2108 lost_fraction = lfExactlyZero;
2109 }
2110
2111 /* Step 3: check if we fit in the destination. */
2112 unsigned int omsb = APInt::tcMSB(parts, dstPartsCount) + 1;
2113
2114 if (sign) {
2115 if (!isSigned) {
2116 /* Negative numbers cannot be represented as unsigned. */
2117 if (omsb != 0)
2118 return opInvalidOp;
2119 } else {
2120 /* It takes omsb bits to represent the unsigned integer value.
2121 We lose a bit for the sign, but care is needed as the
2122 maximally negative integer is a special case. */
2123 if (omsb == width && APInt::tcLSB(parts, dstPartsCount) + 1 != omsb)
2124 return opInvalidOp;
2125
2126 /* This case can happen because of rounding. */
2127 if (omsb > width)
2128 return opInvalidOp;
2129 }
2130
2131 APInt::tcNegate (parts, dstPartsCount);
2132 } else {
2133 if (omsb >= width + !isSigned)
2134 return opInvalidOp;
2135 }
2136
Dale Johannesen4f0bd682008-10-09 23:00:39 +00002137 if (lost_fraction == lfExactlyZero) {
2138 *isExact = true;
Neil Booth618d0fc2007-11-01 22:43:37 +00002139 return opOK;
Dale Johannesen4f0bd682008-10-09 23:00:39 +00002140 } else
Neil Booth618d0fc2007-11-01 22:43:37 +00002141 return opInexact;
2142}
2143
2144/* Same as convertToSignExtendedInteger, except we provide
2145 deterministic values in case of an invalid operation exception,
2146 namely zero for NaNs and the minimal or maximal value respectively
Dale Johannesen4f0bd682008-10-09 23:00:39 +00002147 for underflow or overflow.
2148 The *isExact output tells whether the result is exact, in the sense
2149 that converting it back to the original floating point type produces
2150 the original value. This is almost equivalent to result==opOK,
2151 except for negative zeroes.
2152*/
Neil Booth618d0fc2007-11-01 22:43:37 +00002153APFloat::opStatus
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002154APFloat::convertToInteger(integerPart *parts, unsigned int width,
Neil Booth9acbf5a2007-09-26 21:33:42 +00002155 bool isSigned,
Dale Johannesen4f0bd682008-10-09 23:00:39 +00002156 roundingMode rounding_mode, bool *isExact) const
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002157{
Neil Booth618d0fc2007-11-01 22:43:37 +00002158 opStatus fs;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002159
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002160 fs = convertToSignExtendedInteger(parts, width, isSigned, rounding_mode,
Dale Johannesen4f0bd682008-10-09 23:00:39 +00002161 isExact);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002162
Neil Booth618d0fc2007-11-01 22:43:37 +00002163 if (fs == opInvalidOp) {
2164 unsigned int bits, dstPartsCount;
2165
2166 dstPartsCount = partCountForBits(width);
2167
2168 if (category == fcNaN)
2169 bits = 0;
2170 else if (sign)
2171 bits = isSigned;
2172 else
2173 bits = width - isSigned;
2174
2175 APInt::tcSetLeastSignificantBits(parts, dstPartsCount, bits);
2176 if (sign && isSigned)
2177 APInt::tcShiftLeft(parts, dstPartsCount, width - 1);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002178 }
2179
Neil Booth618d0fc2007-11-01 22:43:37 +00002180 return fs;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002181}
2182
Jeffrey Yasskin03b81a22011-07-15 07:04:56 +00002183/* Same as convertToInteger(integerPart*, ...), except the result is returned in
2184 an APSInt, whose initial bit-width and signed-ness are used to determine the
2185 precision of the conversion.
2186 */
2187APFloat::opStatus
2188APFloat::convertToInteger(APSInt &result,
2189 roundingMode rounding_mode, bool *isExact) const
2190{
2191 unsigned bitWidth = result.getBitWidth();
2192 SmallVector<uint64_t, 4> parts(result.getNumWords());
2193 opStatus status = convertToInteger(
2194 parts.data(), bitWidth, result.isSigned(), rounding_mode, isExact);
2195 // Keeps the original signed-ness.
Jeffrey Yasskin7a162882011-07-18 21:45:40 +00002196 result = APInt(bitWidth, parts);
Jeffrey Yasskin03b81a22011-07-15 07:04:56 +00002197 return status;
2198}
2199
Neil Booth6c1c8582007-10-07 12:07:53 +00002200/* Convert an unsigned integer SRC to a floating point number,
2201 rounding according to ROUNDING_MODE. The sign of the floating
2202 point number is not modified. */
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002203APFloat::opStatus
Neil Booth6c1c8582007-10-07 12:07:53 +00002204APFloat::convertFromUnsignedParts(const integerPart *src,
2205 unsigned int srcCount,
2206 roundingMode rounding_mode)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002207{
Neil Booth49c6aab2007-10-08 14:39:42 +00002208 unsigned int omsb, precision, dstCount;
Neil Booth6c1c8582007-10-07 12:07:53 +00002209 integerPart *dst;
Neil Booth49c6aab2007-10-08 14:39:42 +00002210 lostFraction lost_fraction;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002211
2212 category = fcNormal;
Neil Booth49c6aab2007-10-08 14:39:42 +00002213 omsb = APInt::tcMSB(src, srcCount) + 1;
Neil Booth6c1c8582007-10-07 12:07:53 +00002214 dst = significandParts();
2215 dstCount = partCount();
Neil Booth49c6aab2007-10-08 14:39:42 +00002216 precision = semantics->precision;
Neil Booth6c1c8582007-10-07 12:07:53 +00002217
Nick Lewyckyf66daac2011-10-03 21:30:08 +00002218 /* We want the most significant PRECISION bits of SRC. There may not
Neil Booth49c6aab2007-10-08 14:39:42 +00002219 be that many; extract what we can. */
2220 if (precision <= omsb) {
2221 exponent = omsb - 1;
Neil Booth6c1c8582007-10-07 12:07:53 +00002222 lost_fraction = lostFractionThroughTruncation(src, srcCount,
Neil Booth49c6aab2007-10-08 14:39:42 +00002223 omsb - precision);
2224 APInt::tcExtract(dst, dstCount, src, precision, omsb - precision);
2225 } else {
2226 exponent = precision - 1;
2227 lost_fraction = lfExactlyZero;
2228 APInt::tcExtract(dst, dstCount, src, omsb, 0);
Neil Booth6c1c8582007-10-07 12:07:53 +00002229 }
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002230
2231 return normalize(rounding_mode, lost_fraction);
2232}
2233
Dan Gohman35723eb2008-02-29 01:26:11 +00002234APFloat::opStatus
2235APFloat::convertFromAPInt(const APInt &Val,
2236 bool isSigned,
2237 roundingMode rounding_mode)
2238{
2239 unsigned int partCount = Val.getNumWords();
2240 APInt api = Val;
2241
2242 sign = false;
2243 if (isSigned && api.isNegative()) {
2244 sign = true;
2245 api = -api;
2246 }
2247
2248 return convertFromUnsignedParts(api.getRawData(), partCount, rounding_mode);
2249}
2250
Neil Booth03f58ab2007-10-07 12:15:41 +00002251/* Convert a two's complement integer SRC to a floating point number,
2252 rounding according to ROUNDING_MODE. ISSIGNED is true if the
2253 integer is signed, in which case it must be sign-extended. */
2254APFloat::opStatus
2255APFloat::convertFromSignExtendedInteger(const integerPart *src,
2256 unsigned int srcCount,
2257 bool isSigned,
2258 roundingMode rounding_mode)
2259{
2260 opStatus status;
2261
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002262 if (isSigned &&
2263 APInt::tcExtractBit(src, srcCount * integerPartWidth - 1)) {
Neil Booth03f58ab2007-10-07 12:15:41 +00002264 integerPart *copy;
2265
2266 /* If we're signed and negative negate a copy. */
2267 sign = true;
2268 copy = new integerPart[srcCount];
2269 APInt::tcAssign(copy, src, srcCount);
2270 APInt::tcNegate(copy, srcCount);
2271 status = convertFromUnsignedParts(copy, srcCount, rounding_mode);
2272 delete [] copy;
2273 } else {
2274 sign = false;
2275 status = convertFromUnsignedParts(src, srcCount, rounding_mode);
2276 }
2277
2278 return status;
2279}
2280
Neil Booth5f009732007-10-07 11:45:55 +00002281/* FIXME: should this just take a const APInt reference? */
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002282APFloat::opStatus
Neil Booth5f009732007-10-07 11:45:55 +00002283APFloat::convertFromZeroExtendedInteger(const integerPart *parts,
2284 unsigned int width, bool isSigned,
2285 roundingMode rounding_mode)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002286{
Dale Johannesen42305122007-09-21 22:09:37 +00002287 unsigned int partCount = partCountForBits(width);
Jeffrey Yasskin7a162882011-07-18 21:45:40 +00002288 APInt api = APInt(width, makeArrayRef(parts, partCount));
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002289
2290 sign = false;
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002291 if (isSigned && APInt::tcExtractBit(parts, width - 1)) {
Dale Johannesen28a2c4a2007-09-30 18:17:01 +00002292 sign = true;
2293 api = -api;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002294 }
2295
Neil Boothba205222007-10-07 12:10:57 +00002296 return convertFromUnsignedParts(api.getRawData(), partCount, rounding_mode);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002297}
2298
2299APFloat::opStatus
Benjamin Kramer92d89982010-07-14 22:38:02 +00002300APFloat::convertFromHexadecimalString(StringRef s, roundingMode rounding_mode)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002301{
Erick Tryzelaara9680df2009-08-18 18:20:37 +00002302 lostFraction lost_fraction = lfExactlyZero;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002303 integerPart *significand;
2304 unsigned int bitPos, partsCount;
Erick Tryzelaar19f63b22009-08-16 23:36:19 +00002305 StringRef::iterator dot, firstSignificantDigit;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002306
2307 zeroSignificand();
2308 exponent = 0;
2309 category = fcNormal;
2310
2311 significand = significandParts();
2312 partsCount = partCount();
2313 bitPos = partsCount * integerPartWidth;
2314
Neil Boothd3985922007-10-07 08:51:21 +00002315 /* Skip leading zeroes and any (hexa)decimal point. */
Erick Tryzelaarda666c82009-08-20 23:30:43 +00002316 StringRef::iterator begin = s.begin();
2317 StringRef::iterator end = s.end();
2318 StringRef::iterator p = skipLeadingZeroesAndAnyDot(begin, end, &dot);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002319 firstSignificantDigit = p;
2320
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002321 for (; p != end;) {
Dale Johannesenfa483722008-05-14 22:53:25 +00002322 integerPart hex_value;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002323
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002324 if (*p == '.') {
Erick Tryzelaarda666c82009-08-20 23:30:43 +00002325 assert(dot == end && "String contains multiple dots");
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002326 dot = p++;
Erick Tryzelaarda666c82009-08-20 23:30:43 +00002327 if (p == end) {
2328 break;
2329 }
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002330 }
2331
2332 hex_value = hexDigitValue(*p);
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002333 if (hex_value == -1U) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002334 break;
2335 }
2336
2337 p++;
2338
Erick Tryzelaarda666c82009-08-20 23:30:43 +00002339 if (p == end) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002340 break;
Erick Tryzelaar19f63b22009-08-16 23:36:19 +00002341 } else {
2342 /* Store the number whilst 4-bit nibbles remain. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002343 if (bitPos) {
Erick Tryzelaar19f63b22009-08-16 23:36:19 +00002344 bitPos -= 4;
2345 hex_value <<= bitPos % integerPartWidth;
2346 significand[bitPos / integerPartWidth] |= hex_value;
2347 } else {
Erick Tryzelaarda666c82009-08-20 23:30:43 +00002348 lost_fraction = trailingHexadecimalFraction(p, end, hex_value);
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002349 while (p != end && hexDigitValue(*p) != -1U)
Erick Tryzelaar19f63b22009-08-16 23:36:19 +00002350 p++;
2351 break;
2352 }
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002353 }
2354 }
2355
2356 /* Hex floats require an exponent but not a hexadecimal point. */
Erick Tryzelaarda666c82009-08-20 23:30:43 +00002357 assert(p != end && "Hex strings require an exponent");
2358 assert((*p == 'p' || *p == 'P') && "Invalid character in significand");
2359 assert(p != begin && "Significand has no digits");
2360 assert((dot == end || p - begin != 1) && "Significand has no digits");
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002361
2362 /* Ignore the exponent if we are zero. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002363 if (p != firstSignificantDigit) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002364 int expAdjustment;
2365
2366 /* Implicit hexadecimal point? */
Erick Tryzelaarda666c82009-08-20 23:30:43 +00002367 if (dot == end)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002368 dot = p;
2369
2370 /* Calculate the exponent adjustment implicit in the number of
2371 significant digits. */
Evan Cheng82b9e962008-05-02 21:15:08 +00002372 expAdjustment = static_cast<int>(dot - firstSignificantDigit);
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002373 if (expAdjustment < 0)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002374 expAdjustment++;
2375 expAdjustment = expAdjustment * 4 - 1;
2376
2377 /* Adjust for writing the significand starting at the most
2378 significant nibble. */
2379 expAdjustment += semantics->precision;
2380 expAdjustment -= partsCount * integerPartWidth;
2381
2382 /* Adjust for the given exponent. */
Erick Tryzelaarda666c82009-08-20 23:30:43 +00002383 exponent = totalExponent(p + 1, end, expAdjustment);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002384 }
2385
2386 return normalize(rounding_mode, lost_fraction);
2387}
2388
2389APFloat::opStatus
Neil Boothb93d90e2007-10-12 16:02:31 +00002390APFloat::roundSignificandWithExponent(const integerPart *decSigParts,
2391 unsigned sigPartCount, int exp,
2392 roundingMode rounding_mode)
2393{
2394 unsigned int parts, pow5PartCount;
Ulrich Weigand908c9362012-10-29 18:18:44 +00002395 fltSemantics calcSemantics = { 32767, -32767, 0 };
Neil Boothb93d90e2007-10-12 16:02:31 +00002396 integerPart pow5Parts[maxPowerOfFiveParts];
2397 bool isNearest;
2398
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002399 isNearest = (rounding_mode == rmNearestTiesToEven ||
2400 rounding_mode == rmNearestTiesToAway);
Neil Boothb93d90e2007-10-12 16:02:31 +00002401
2402 parts = partCountForBits(semantics->precision + 11);
2403
2404 /* Calculate pow(5, abs(exp)). */
2405 pow5PartCount = powerOf5(pow5Parts, exp >= 0 ? exp: -exp);
2406
2407 for (;; parts *= 2) {
2408 opStatus sigStatus, powStatus;
2409 unsigned int excessPrecision, truncatedBits;
2410
2411 calcSemantics.precision = parts * integerPartWidth - 1;
2412 excessPrecision = calcSemantics.precision - semantics->precision;
2413 truncatedBits = excessPrecision;
2414
Michael Gottesman79b09672013-06-27 21:58:19 +00002415 APFloat decSig = APFloat::getZero(calcSemantics, sign);
2416 APFloat pow5(calcSemantics);
Neil Boothb93d90e2007-10-12 16:02:31 +00002417
2418 sigStatus = decSig.convertFromUnsignedParts(decSigParts, sigPartCount,
2419 rmNearestTiesToEven);
2420 powStatus = pow5.convertFromUnsignedParts(pow5Parts, pow5PartCount,
2421 rmNearestTiesToEven);
2422 /* Add exp, as 10^n = 5^n * 2^n. */
2423 decSig.exponent += exp;
2424
2425 lostFraction calcLostFraction;
Evan Cheng82b9e962008-05-02 21:15:08 +00002426 integerPart HUerr, HUdistance;
2427 unsigned int powHUerr;
Neil Boothb93d90e2007-10-12 16:02:31 +00002428
2429 if (exp >= 0) {
2430 /* multiplySignificand leaves the precision-th bit set to 1. */
2431 calcLostFraction = decSig.multiplySignificand(pow5, NULL);
2432 powHUerr = powStatus != opOK;
2433 } else {
2434 calcLostFraction = decSig.divideSignificand(pow5);
2435 /* Denormal numbers have less precision. */
2436 if (decSig.exponent < semantics->minExponent) {
2437 excessPrecision += (semantics->minExponent - decSig.exponent);
2438 truncatedBits = excessPrecision;
2439 if (excessPrecision > calcSemantics.precision)
2440 excessPrecision = calcSemantics.precision;
2441 }
2442 /* Extra half-ulp lost in reciprocal of exponent. */
Evan Cheng82b9e962008-05-02 21:15:08 +00002443 powHUerr = (powStatus == opOK && calcLostFraction == lfExactlyZero) ? 0:2;
Neil Boothb93d90e2007-10-12 16:02:31 +00002444 }
2445
2446 /* Both multiplySignificand and divideSignificand return the
2447 result with the integer bit set. */
Evan Cheng67c90212009-10-27 21:35:42 +00002448 assert(APInt::tcExtractBit
2449 (decSig.significandParts(), calcSemantics.precision - 1) == 1);
Neil Boothb93d90e2007-10-12 16:02:31 +00002450
2451 HUerr = HUerrBound(calcLostFraction != lfExactlyZero, sigStatus != opOK,
2452 powHUerr);
2453 HUdistance = 2 * ulpsFromBoundary(decSig.significandParts(),
2454 excessPrecision, isNearest);
2455
2456 /* Are we guaranteed to round correctly if we truncate? */
2457 if (HUdistance >= HUerr) {
2458 APInt::tcExtract(significandParts(), partCount(), decSig.significandParts(),
2459 calcSemantics.precision - excessPrecision,
2460 excessPrecision);
2461 /* Take the exponent of decSig. If we tcExtract-ed less bits
2462 above we must adjust our exponent to compensate for the
2463 implicit right shift. */
2464 exponent = (decSig.exponent + semantics->precision
2465 - (calcSemantics.precision - excessPrecision));
2466 calcLostFraction = lostFractionThroughTruncation(decSig.significandParts(),
2467 decSig.partCount(),
2468 truncatedBits);
2469 return normalize(rounding_mode, calcLostFraction);
2470 }
2471 }
2472}
2473
2474APFloat::opStatus
Benjamin Kramer92d89982010-07-14 22:38:02 +00002475APFloat::convertFromDecimalString(StringRef str, roundingMode rounding_mode)
Neil Boothb93d90e2007-10-12 16:02:31 +00002476{
Neil Booth4ed401b2007-10-14 10:16:12 +00002477 decimalInfo D;
Neil Boothb93d90e2007-10-12 16:02:31 +00002478 opStatus fs;
2479
Neil Booth4ed401b2007-10-14 10:16:12 +00002480 /* Scan the text. */
Erick Tryzelaar19f63b22009-08-16 23:36:19 +00002481 StringRef::iterator p = str.begin();
2482 interpretDecimal(p, str.end(), &D);
Neil Boothb93d90e2007-10-12 16:02:31 +00002483
Neil Booth91305512007-10-15 15:00:55 +00002484 /* Handle the quick cases. First the case of no significant digits,
2485 i.e. zero, and then exponents that are obviously too large or too
2486 small. Writing L for log 10 / log 2, a number d.ddddd*10^exp
2487 definitely overflows if
2488
2489 (exp - 1) * L >= maxExponent
2490
2491 and definitely underflows to zero where
2492
2493 (exp + 1) * L <= minExponent - precision
2494
2495 With integer arithmetic the tightest bounds for L are
2496
2497 93/28 < L < 196/59 [ numerator <= 256 ]
2498 42039/12655 < L < 28738/8651 [ numerator <= 65536 ]
2499 */
2500
Michael Gottesman228156c2013-07-01 23:54:08 +00002501 // Test if we have a zero number allowing for strings with no null terminators
2502 // and zero decimals with non-zero exponents.
2503 //
2504 // We computed firstSigDigit by ignoring all zeros and dots. Thus if
2505 // D->firstSigDigit equals str.end(), every digit must be a zero and there can
2506 // be at most one dot. On the other hand, if we have a zero with a non-zero
2507 // exponent, then we know that D.firstSigDigit will be non-numeric.
Michael Gottesman94d61952013-07-02 15:50:05 +00002508 if (D.firstSigDigit == str.end() || decDigitValue(*D.firstSigDigit) >= 10U) {
Neil Boothb93d90e2007-10-12 16:02:31 +00002509 category = fcZero;
2510 fs = opOK;
John McCallb42cc682010-02-26 22:20:41 +00002511
2512 /* Check whether the normalized exponent is high enough to overflow
2513 max during the log-rebasing in the max-exponent check below. */
2514 } else if (D.normalizedExponent - 1 > INT_MAX / 42039) {
2515 fs = handleOverflow(rounding_mode);
2516
2517 /* If it wasn't, then it also wasn't high enough to overflow max
2518 during the log-rebasing in the min-exponent check. Check that it
2519 won't overflow min in either check, then perform the min-exponent
2520 check. */
2521 } else if (D.normalizedExponent - 1 < INT_MIN / 42039 ||
2522 (D.normalizedExponent + 1) * 28738 <=
2523 8651 * (semantics->minExponent - (int) semantics->precision)) {
Neil Booth91305512007-10-15 15:00:55 +00002524 /* Underflow to zero and round. */
2525 zeroSignificand();
2526 fs = normalize(rounding_mode, lfLessThanHalf);
John McCallb42cc682010-02-26 22:20:41 +00002527
2528 /* We can finally safely perform the max-exponent check. */
Neil Booth91305512007-10-15 15:00:55 +00002529 } else if ((D.normalizedExponent - 1) * 42039
2530 >= 12655 * semantics->maxExponent) {
2531 /* Overflow and round. */
2532 fs = handleOverflow(rounding_mode);
Neil Boothb93d90e2007-10-12 16:02:31 +00002533 } else {
Neil Booth4ed401b2007-10-14 10:16:12 +00002534 integerPart *decSignificand;
2535 unsigned int partCount;
Neil Boothb93d90e2007-10-12 16:02:31 +00002536
Neil Booth4ed401b2007-10-14 10:16:12 +00002537 /* A tight upper bound on number of bits required to hold an
Neil Booth91305512007-10-15 15:00:55 +00002538 N-digit decimal integer is N * 196 / 59. Allocate enough space
Neil Booth4ed401b2007-10-14 10:16:12 +00002539 to hold the full significand, and an extra part required by
2540 tcMultiplyPart. */
Evan Cheng82b9e962008-05-02 21:15:08 +00002541 partCount = static_cast<unsigned int>(D.lastSigDigit - D.firstSigDigit) + 1;
Neil Booth91305512007-10-15 15:00:55 +00002542 partCount = partCountForBits(1 + 196 * partCount / 59);
Neil Booth4ed401b2007-10-14 10:16:12 +00002543 decSignificand = new integerPart[partCount + 1];
2544 partCount = 0;
Neil Boothb93d90e2007-10-12 16:02:31 +00002545
Neil Booth4ed401b2007-10-14 10:16:12 +00002546 /* Convert to binary efficiently - we do almost all multiplication
2547 in an integerPart. When this would overflow do we do a single
2548 bignum multiplication, and then revert again to multiplication
2549 in an integerPart. */
2550 do {
2551 integerPart decValue, val, multiplier;
2552
2553 val = 0;
2554 multiplier = 1;
2555
2556 do {
Erick Tryzelaar19f63b22009-08-16 23:36:19 +00002557 if (*p == '.') {
Neil Booth4ed401b2007-10-14 10:16:12 +00002558 p++;
Erick Tryzelaar19f63b22009-08-16 23:36:19 +00002559 if (p == str.end()) {
2560 break;
2561 }
2562 }
Neil Booth4ed401b2007-10-14 10:16:12 +00002563 decValue = decDigitValue(*p++);
Erick Tryzelaarda666c82009-08-20 23:30:43 +00002564 assert(decValue < 10U && "Invalid character in significand");
Neil Booth4ed401b2007-10-14 10:16:12 +00002565 multiplier *= 10;
2566 val = val * 10 + decValue;
2567 /* The maximum number that can be multiplied by ten with any
2568 digit added without overflowing an integerPart. */
2569 } while (p <= D.lastSigDigit && multiplier <= (~ (integerPart) 0 - 9) / 10);
2570
2571 /* Multiply out the current part. */
2572 APInt::tcMultiplyPart(decSignificand, decSignificand, multiplier, val,
2573 partCount, partCount + 1, false);
2574
2575 /* If we used another part (likely but not guaranteed), increase
2576 the count. */
2577 if (decSignificand[partCount])
2578 partCount++;
2579 } while (p <= D.lastSigDigit);
Neil Boothb93d90e2007-10-12 16:02:31 +00002580
Neil Boothae077d22007-11-01 22:51:07 +00002581 category = fcNormal;
Neil Boothb93d90e2007-10-12 16:02:31 +00002582 fs = roundSignificandWithExponent(decSignificand, partCount,
Neil Booth4ed401b2007-10-14 10:16:12 +00002583 D.exponent, rounding_mode);
Neil Boothb93d90e2007-10-12 16:02:31 +00002584
Neil Booth4ed401b2007-10-14 10:16:12 +00002585 delete [] decSignificand;
2586 }
Neil Boothb93d90e2007-10-12 16:02:31 +00002587
2588 return fs;
2589}
2590
Michael Gottesman40e8a182013-06-24 09:58:05 +00002591bool
2592APFloat::convertFromStringSpecials(StringRef str) {
2593 if (str.equals("inf") || str.equals("INFINITY")) {
2594 makeInf(false);
2595 return true;
2596 }
2597
2598 if (str.equals("-inf") || str.equals("-INFINITY")) {
2599 makeInf(true);
2600 return true;
2601 }
2602
2603 if (str.equals("nan") || str.equals("NaN")) {
2604 makeNaN(false, false);
2605 return true;
2606 }
2607
2608 if (str.equals("-nan") || str.equals("-NaN")) {
2609 makeNaN(false, true);
2610 return true;
2611 }
2612
2613 return false;
2614}
2615
Neil Boothb93d90e2007-10-12 16:02:31 +00002616APFloat::opStatus
Benjamin Kramer92d89982010-07-14 22:38:02 +00002617APFloat::convertFromString(StringRef str, roundingMode rounding_mode)
Neil Booth9acbf5a2007-09-26 21:33:42 +00002618{
Erick Tryzelaar19f63b22009-08-16 23:36:19 +00002619 assert(!str.empty() && "Invalid string length");
Neil Booth06077e72007-10-14 10:29:28 +00002620
Michael Gottesman40e8a182013-06-24 09:58:05 +00002621 // Handle special cases.
2622 if (convertFromStringSpecials(str))
2623 return opOK;
2624
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002625 /* Handle a leading minus sign. */
Erick Tryzelaar19f63b22009-08-16 23:36:19 +00002626 StringRef::iterator p = str.begin();
2627 size_t slen = str.size();
Erick Tryzelaarda666c82009-08-20 23:30:43 +00002628 sign = *p == '-' ? 1 : 0;
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002629 if (*p == '-' || *p == '+') {
Erick Tryzelaar19f63b22009-08-16 23:36:19 +00002630 p++;
2631 slen--;
Erick Tryzelaarda666c82009-08-20 23:30:43 +00002632 assert(slen && "String has no digits");
Erick Tryzelaar19f63b22009-08-16 23:36:19 +00002633 }
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002634
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002635 if (slen >= 2 && p[0] == '0' && (p[1] == 'x' || p[1] == 'X')) {
Erick Tryzelaar19f63b22009-08-16 23:36:19 +00002636 assert(slen - 2 && "Invalid string");
Erick Tryzelaarda666c82009-08-20 23:30:43 +00002637 return convertFromHexadecimalString(StringRef(p + 2, slen - 2),
Erick Tryzelaar19f63b22009-08-16 23:36:19 +00002638 rounding_mode);
2639 }
Bill Wendlingc6075402008-11-27 08:00:12 +00002640
Erick Tryzelaarda666c82009-08-20 23:30:43 +00002641 return convertFromDecimalString(StringRef(p, slen), rounding_mode);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002642}
Dale Johannesena719a602007-08-24 00:56:33 +00002643
Neil Booth8f1946f2007-10-03 22:26:02 +00002644/* Write out a hexadecimal representation of the floating point value
2645 to DST, which must be of sufficient size, in the C99 form
2646 [-]0xh.hhhhp[+-]d. Return the number of characters written,
2647 excluding the terminating NUL.
2648
2649 If UPPERCASE, the output is in upper case, otherwise in lower case.
2650
2651 HEXDIGITS digits appear altogether, rounding the value if
2652 necessary. If HEXDIGITS is 0, the minimal precision to display the
2653 number precisely is used instead. If nothing would appear after
2654 the decimal point it is suppressed.
2655
2656 The decimal exponent is always printed and has at least one digit.
2657 Zero values display an exponent of zero. Infinities and NaNs
2658 appear as "infinity" or "nan" respectively.
2659
2660 The above rules are as specified by C99. There is ambiguity about
2661 what the leading hexadecimal digit should be. This implementation
2662 uses whatever is necessary so that the exponent is displayed as
2663 stored. This implies the exponent will fall within the IEEE format
2664 range, and the leading hexadecimal digit will be 0 (for denormals),
2665 1 (normal numbers) or 2 (normal numbers rounded-away-from-zero with
2666 any other digits zero).
2667*/
2668unsigned int
2669APFloat::convertToHexString(char *dst, unsigned int hexDigits,
2670 bool upperCase, roundingMode rounding_mode) const
2671{
2672 char *p;
2673
2674 p = dst;
2675 if (sign)
2676 *dst++ = '-';
2677
2678 switch (category) {
2679 case fcInfinity:
2680 memcpy (dst, upperCase ? infinityU: infinityL, sizeof infinityU - 1);
2681 dst += sizeof infinityL - 1;
2682 break;
2683
2684 case fcNaN:
2685 memcpy (dst, upperCase ? NaNU: NaNL, sizeof NaNU - 1);
2686 dst += sizeof NaNU - 1;
2687 break;
2688
2689 case fcZero:
2690 *dst++ = '0';
2691 *dst++ = upperCase ? 'X': 'x';
2692 *dst++ = '0';
2693 if (hexDigits > 1) {
2694 *dst++ = '.';
2695 memset (dst, '0', hexDigits - 1);
2696 dst += hexDigits - 1;
2697 }
2698 *dst++ = upperCase ? 'P': 'p';
2699 *dst++ = '0';
2700 break;
2701
2702 case fcNormal:
2703 dst = convertNormalToHexString (dst, hexDigits, upperCase, rounding_mode);
2704 break;
2705 }
2706
2707 *dst = 0;
2708
Evan Cheng82b9e962008-05-02 21:15:08 +00002709 return static_cast<unsigned int>(dst - p);
Neil Booth8f1946f2007-10-03 22:26:02 +00002710}
2711
2712/* Does the hard work of outputting the correctly rounded hexadecimal
2713 form of a normal floating point number with the specified number of
2714 hexadecimal digits. If HEXDIGITS is zero the minimum number of
2715 digits necessary to print the value precisely is output. */
2716char *
2717APFloat::convertNormalToHexString(char *dst, unsigned int hexDigits,
2718 bool upperCase,
2719 roundingMode rounding_mode) const
2720{
2721 unsigned int count, valueBits, shift, partsCount, outputDigits;
2722 const char *hexDigitChars;
2723 const integerPart *significand;
2724 char *p;
2725 bool roundUp;
2726
2727 *dst++ = '0';
2728 *dst++ = upperCase ? 'X': 'x';
2729
2730 roundUp = false;
2731 hexDigitChars = upperCase ? hexDigitsUpper: hexDigitsLower;
2732
2733 significand = significandParts();
2734 partsCount = partCount();
2735
2736 /* +3 because the first digit only uses the single integer bit, so
2737 we have 3 virtual zero most-significant-bits. */
2738 valueBits = semantics->precision + 3;
2739 shift = integerPartWidth - valueBits % integerPartWidth;
2740
2741 /* The natural number of digits required ignoring trailing
2742 insignificant zeroes. */
2743 outputDigits = (valueBits - significandLSB () + 3) / 4;
2744
2745 /* hexDigits of zero means use the required number for the
2746 precision. Otherwise, see if we are truncating. If we are,
Neil Booth0ea72a92007-10-06 00:24:48 +00002747 find out if we need to round away from zero. */
Neil Booth8f1946f2007-10-03 22:26:02 +00002748 if (hexDigits) {
2749 if (hexDigits < outputDigits) {
2750 /* We are dropping non-zero bits, so need to check how to round.
2751 "bits" is the number of dropped bits. */
2752 unsigned int bits;
2753 lostFraction fraction;
2754
2755 bits = valueBits - hexDigits * 4;
2756 fraction = lostFractionThroughTruncation (significand, partsCount, bits);
2757 roundUp = roundAwayFromZero(rounding_mode, fraction, bits);
2758 }
2759 outputDigits = hexDigits;
2760 }
2761
2762 /* Write the digits consecutively, and start writing in the location
2763 of the hexadecimal point. We move the most significant digit
2764 left and add the hexadecimal point later. */
2765 p = ++dst;
2766
2767 count = (valueBits + integerPartWidth - 1) / integerPartWidth;
2768
2769 while (outputDigits && count) {
2770 integerPart part;
2771
2772 /* Put the most significant integerPartWidth bits in "part". */
2773 if (--count == partsCount)
2774 part = 0; /* An imaginary higher zero part. */
2775 else
2776 part = significand[count] << shift;
2777
2778 if (count && shift)
2779 part |= significand[count - 1] >> (integerPartWidth - shift);
2780
2781 /* Convert as much of "part" to hexdigits as we can. */
2782 unsigned int curDigits = integerPartWidth / 4;
2783
2784 if (curDigits > outputDigits)
2785 curDigits = outputDigits;
2786 dst += partAsHex (dst, part, curDigits, hexDigitChars);
2787 outputDigits -= curDigits;
2788 }
2789
2790 if (roundUp) {
2791 char *q = dst;
2792
2793 /* Note that hexDigitChars has a trailing '0'. */
2794 do {
2795 q--;
2796 *q = hexDigitChars[hexDigitValue (*q) + 1];
Neil Booth0ea72a92007-10-06 00:24:48 +00002797 } while (*q == '0');
Evan Cheng67c90212009-10-27 21:35:42 +00002798 assert(q >= p);
Neil Booth8f1946f2007-10-03 22:26:02 +00002799 } else {
2800 /* Add trailing zeroes. */
2801 memset (dst, '0', outputDigits);
2802 dst += outputDigits;
2803 }
2804
2805 /* Move the most significant digit to before the point, and if there
2806 is something after the decimal point add it. This must come
2807 after rounding above. */
2808 p[-1] = p[0];
2809 if (dst -1 == p)
2810 dst--;
2811 else
2812 p[0] = '.';
2813
2814 /* Finally output the exponent. */
2815 *dst++ = upperCase ? 'P': 'p';
2816
Neil Booth32897f52007-10-06 07:29:25 +00002817 return writeSignedDecimal (dst, exponent);
Neil Booth8f1946f2007-10-03 22:26:02 +00002818}
2819
Chandler Carruth71bd7d12012-03-04 12:02:57 +00002820hash_code llvm::hash_value(const APFloat &Arg) {
Michael Gottesman8136c382013-06-26 23:17:28 +00002821 if (!Arg.isFiniteNonZero())
Chandler Carruth71bd7d12012-03-04 12:02:57 +00002822 return hash_combine((uint8_t)Arg.category,
2823 // NaN has no sign, fix it at zero.
2824 Arg.isNaN() ? (uint8_t)0 : (uint8_t)Arg.sign,
2825 Arg.semantics->precision);
2826
2827 // Normal floats need their exponent and significand hashed.
2828 return hash_combine((uint8_t)Arg.category, (uint8_t)Arg.sign,
2829 Arg.semantics->precision, Arg.exponent,
2830 hash_combine_range(
2831 Arg.significandParts(),
2832 Arg.significandParts() + Arg.partCount()));
Dale Johannesena719a602007-08-24 00:56:33 +00002833}
2834
2835// Conversion from APFloat to/from host float/double. It may eventually be
2836// possible to eliminate these and have everybody deal with APFloats, but that
2837// will take a while. This approach will not easily extend to long double.
Dale Johannesen146a0ea2007-09-20 23:47:58 +00002838// Current implementation requires integerPartWidth==64, which is correct at
2839// the moment but could be made more general.
Dale Johannesena719a602007-08-24 00:56:33 +00002840
Dale Johannesen728687c2007-09-05 20:39:49 +00002841// Denormals have exponent minExponent in APFloat, but minExponent-1 in
Dale Johannesen146a0ea2007-09-20 23:47:58 +00002842// the actual IEEE respresentations. We compensate for that here.
Dale Johannesen728687c2007-09-05 20:39:49 +00002843
Dale Johannesen245dceb2007-09-11 18:32:33 +00002844APInt
Neil Booth9acbf5a2007-09-26 21:33:42 +00002845APFloat::convertF80LongDoubleAPFloatToAPInt() const
2846{
Dan Gohmanb456a152008-01-29 12:08:20 +00002847 assert(semantics == (const llvm::fltSemantics*)&x87DoubleExtended);
Evan Cheng67c90212009-10-27 21:35:42 +00002848 assert(partCount()==2);
Dale Johannesen245dceb2007-09-11 18:32:33 +00002849
2850 uint64_t myexponent, mysignificand;
2851
Michael Gottesman8136c382013-06-26 23:17:28 +00002852 if (isFiniteNonZero()) {
Dale Johannesen245dceb2007-09-11 18:32:33 +00002853 myexponent = exponent+16383; //bias
Dale Johannesen146a0ea2007-09-20 23:47:58 +00002854 mysignificand = significandParts()[0];
Dale Johannesen245dceb2007-09-11 18:32:33 +00002855 if (myexponent==1 && !(mysignificand & 0x8000000000000000ULL))
2856 myexponent = 0; // denormal
2857 } else if (category==fcZero) {
2858 myexponent = 0;
2859 mysignificand = 0;
2860 } else if (category==fcInfinity) {
2861 myexponent = 0x7fff;
2862 mysignificand = 0x8000000000000000ULL;
Chris Lattner2a9bcb92007-10-06 06:13:42 +00002863 } else {
2864 assert(category == fcNaN && "Unknown category");
Dale Johannesen245dceb2007-09-11 18:32:33 +00002865 myexponent = 0x7fff;
Dale Johannesen146a0ea2007-09-20 23:47:58 +00002866 mysignificand = significandParts()[0];
Chris Lattner2a9bcb92007-10-06 06:13:42 +00002867 }
Dale Johannesen245dceb2007-09-11 18:32:33 +00002868
2869 uint64_t words[2];
Dale Johannesen93eefa02009-03-23 21:16:53 +00002870 words[0] = mysignificand;
2871 words[1] = ((uint64_t)(sign & 1) << 15) |
2872 (myexponent & 0x7fffLL);
Jeffrey Yasskin7a162882011-07-18 21:45:40 +00002873 return APInt(80, words);
Dale Johannesen245dceb2007-09-11 18:32:33 +00002874}
2875
2876APInt
Dale Johannesen007aa372007-10-11 18:07:22 +00002877APFloat::convertPPCDoubleDoubleAPFloatToAPInt() const
2878{
Dan Gohmanb456a152008-01-29 12:08:20 +00002879 assert(semantics == (const llvm::fltSemantics*)&PPCDoubleDouble);
Evan Cheng67c90212009-10-27 21:35:42 +00002880 assert(partCount()==2);
Dale Johannesen007aa372007-10-11 18:07:22 +00002881
Ulrich Weigandd9f7e252012-10-29 18:09:01 +00002882 uint64_t words[2];
2883 opStatus fs;
2884 bool losesInfo;
Dale Johannesen007aa372007-10-11 18:07:22 +00002885
Ulrich Weigandd9f7e252012-10-29 18:09:01 +00002886 // Convert number to double. To avoid spurious underflows, we re-
2887 // normalize against the "double" minExponent first, and only *then*
2888 // truncate the mantissa. The result of that second conversion
2889 // may be inexact, but should never underflow.
Alexey Samsonov2b431d92012-11-30 22:27:54 +00002890 // Declare fltSemantics before APFloat that uses it (and
2891 // saves pointer to it) to ensure correct destruction order.
Ulrich Weigandd9f7e252012-10-29 18:09:01 +00002892 fltSemantics extendedSemantics = *semantics;
2893 extendedSemantics.minExponent = IEEEdouble.minExponent;
Alexey Samsonov2b431d92012-11-30 22:27:54 +00002894 APFloat extended(*this);
Ulrich Weigandd9f7e252012-10-29 18:09:01 +00002895 fs = extended.convert(extendedSemantics, rmNearestTiesToEven, &losesInfo);
2896 assert(fs == opOK && !losesInfo);
2897 (void)fs;
2898
2899 APFloat u(extended);
2900 fs = u.convert(IEEEdouble, rmNearestTiesToEven, &losesInfo);
2901 assert(fs == opOK || fs == opInexact);
2902 (void)fs;
2903 words[0] = *u.convertDoubleAPFloatToAPInt().getRawData();
2904
2905 // If conversion was exact or resulted in a special case, we're done;
2906 // just set the second double to zero. Otherwise, re-convert back to
2907 // the extended format and compute the difference. This now should
2908 // convert exactly to double.
Michael Gottesman8136c382013-06-26 23:17:28 +00002909 if (u.isFiniteNonZero() && losesInfo) {
Ulrich Weigandd9f7e252012-10-29 18:09:01 +00002910 fs = u.convert(extendedSemantics, rmNearestTiesToEven, &losesInfo);
2911 assert(fs == opOK && !losesInfo);
2912 (void)fs;
2913
2914 APFloat v(extended);
2915 v.subtract(u, rmNearestTiesToEven);
2916 fs = v.convert(IEEEdouble, rmNearestTiesToEven, &losesInfo);
2917 assert(fs == opOK && !losesInfo);
2918 (void)fs;
2919 words[1] = *v.convertDoubleAPFloatToAPInt().getRawData();
Dale Johannesen007aa372007-10-11 18:07:22 +00002920 } else {
Ulrich Weigandd9f7e252012-10-29 18:09:01 +00002921 words[1] = 0;
Dale Johannesen007aa372007-10-11 18:07:22 +00002922 }
2923
Jeffrey Yasskin7a162882011-07-18 21:45:40 +00002924 return APInt(128, words);
Dale Johannesen007aa372007-10-11 18:07:22 +00002925}
2926
2927APInt
Anton Korobeynikov13e8c7e2009-08-21 22:10:30 +00002928APFloat::convertQuadrupleAPFloatToAPInt() const
2929{
2930 assert(semantics == (const llvm::fltSemantics*)&IEEEquad);
Evan Cheng67c90212009-10-27 21:35:42 +00002931 assert(partCount()==2);
Anton Korobeynikov13e8c7e2009-08-21 22:10:30 +00002932
2933 uint64_t myexponent, mysignificand, mysignificand2;
2934
Michael Gottesman8136c382013-06-26 23:17:28 +00002935 if (isFiniteNonZero()) {
Anton Korobeynikov13e8c7e2009-08-21 22:10:30 +00002936 myexponent = exponent+16383; //bias
2937 mysignificand = significandParts()[0];
2938 mysignificand2 = significandParts()[1];
2939 if (myexponent==1 && !(mysignificand2 & 0x1000000000000LL))
2940 myexponent = 0; // denormal
2941 } else if (category==fcZero) {
2942 myexponent = 0;
2943 mysignificand = mysignificand2 = 0;
2944 } else if (category==fcInfinity) {
2945 myexponent = 0x7fff;
2946 mysignificand = mysignificand2 = 0;
2947 } else {
2948 assert(category == fcNaN && "Unknown category!");
2949 myexponent = 0x7fff;
2950 mysignificand = significandParts()[0];
2951 mysignificand2 = significandParts()[1];
2952 }
2953
2954 uint64_t words[2];
2955 words[0] = mysignificand;
2956 words[1] = ((uint64_t)(sign & 1) << 63) |
2957 ((myexponent & 0x7fff) << 48) |
Anton Korobeynikov876955c2009-08-21 23:09:47 +00002958 (mysignificand2 & 0xffffffffffffLL);
Anton Korobeynikov13e8c7e2009-08-21 22:10:30 +00002959
Jeffrey Yasskin7a162882011-07-18 21:45:40 +00002960 return APInt(128, words);
Anton Korobeynikov13e8c7e2009-08-21 22:10:30 +00002961}
2962
2963APInt
Neil Booth9acbf5a2007-09-26 21:33:42 +00002964APFloat::convertDoubleAPFloatToAPInt() const
2965{
Dan Gohman58c468f2007-09-14 20:08:19 +00002966 assert(semantics == (const llvm::fltSemantics*)&IEEEdouble);
Evan Cheng67c90212009-10-27 21:35:42 +00002967 assert(partCount()==1);
Dale Johannesena719a602007-08-24 00:56:33 +00002968
Dale Johannesen3cf889f2007-08-31 04:03:46 +00002969 uint64_t myexponent, mysignificand;
Dale Johannesena719a602007-08-24 00:56:33 +00002970
Michael Gottesman8136c382013-06-26 23:17:28 +00002971 if (isFiniteNonZero()) {
Dale Johannesena719a602007-08-24 00:56:33 +00002972 myexponent = exponent+1023; //bias
Dale Johannesen728687c2007-09-05 20:39:49 +00002973 mysignificand = *significandParts();
2974 if (myexponent==1 && !(mysignificand & 0x10000000000000LL))
2975 myexponent = 0; // denormal
Dale Johannesena719a602007-08-24 00:56:33 +00002976 } else if (category==fcZero) {
Dale Johannesena719a602007-08-24 00:56:33 +00002977 myexponent = 0;
2978 mysignificand = 0;
2979 } else if (category==fcInfinity) {
Dale Johannesena719a602007-08-24 00:56:33 +00002980 myexponent = 0x7ff;
2981 mysignificand = 0;
Chris Lattner2a9bcb92007-10-06 06:13:42 +00002982 } else {
2983 assert(category == fcNaN && "Unknown category!");
Dale Johannesena719a602007-08-24 00:56:33 +00002984 myexponent = 0x7ff;
Dale Johannesen3cf889f2007-08-31 04:03:46 +00002985 mysignificand = *significandParts();
Chris Lattner2a9bcb92007-10-06 06:13:42 +00002986 }
Dale Johannesena719a602007-08-24 00:56:33 +00002987
Evan Cheng82b9e962008-05-02 21:15:08 +00002988 return APInt(64, ((((uint64_t)(sign & 1) << 63) |
Chris Lattner2a9bcb92007-10-06 06:13:42 +00002989 ((myexponent & 0x7ff) << 52) |
2990 (mysignificand & 0xfffffffffffffLL))));
Dale Johannesena719a602007-08-24 00:56:33 +00002991}
2992
Dale Johannesen245dceb2007-09-11 18:32:33 +00002993APInt
Neil Booth9acbf5a2007-09-26 21:33:42 +00002994APFloat::convertFloatAPFloatToAPInt() const
2995{
Dan Gohman58c468f2007-09-14 20:08:19 +00002996 assert(semantics == (const llvm::fltSemantics*)&IEEEsingle);
Evan Cheng67c90212009-10-27 21:35:42 +00002997 assert(partCount()==1);
Neil Booth9acbf5a2007-09-26 21:33:42 +00002998
Dale Johannesen3cf889f2007-08-31 04:03:46 +00002999 uint32_t myexponent, mysignificand;
Dale Johannesena719a602007-08-24 00:56:33 +00003000
Michael Gottesman8136c382013-06-26 23:17:28 +00003001 if (isFiniteNonZero()) {
Dale Johannesena719a602007-08-24 00:56:33 +00003002 myexponent = exponent+127; //bias
Evan Cheng82b9e962008-05-02 21:15:08 +00003003 mysignificand = (uint32_t)*significandParts();
Dale Johannesen06a10df2007-11-17 01:02:27 +00003004 if (myexponent == 1 && !(mysignificand & 0x800000))
Dale Johannesen728687c2007-09-05 20:39:49 +00003005 myexponent = 0; // denormal
Dale Johannesena719a602007-08-24 00:56:33 +00003006 } else if (category==fcZero) {
Dale Johannesena719a602007-08-24 00:56:33 +00003007 myexponent = 0;
3008 mysignificand = 0;
3009 } else if (category==fcInfinity) {
Dale Johannesena719a602007-08-24 00:56:33 +00003010 myexponent = 0xff;
3011 mysignificand = 0;
Chris Lattner2a9bcb92007-10-06 06:13:42 +00003012 } else {
3013 assert(category == fcNaN && "Unknown category!");
Dale Johannesen728687c2007-09-05 20:39:49 +00003014 myexponent = 0xff;
Evan Cheng82b9e962008-05-02 21:15:08 +00003015 mysignificand = (uint32_t)*significandParts();
Chris Lattner2a9bcb92007-10-06 06:13:42 +00003016 }
Dale Johannesena719a602007-08-24 00:56:33 +00003017
Chris Lattner2a9bcb92007-10-06 06:13:42 +00003018 return APInt(32, (((sign&1) << 31) | ((myexponent&0xff) << 23) |
3019 (mysignificand & 0x7fffff)));
Dale Johannesena719a602007-08-24 00:56:33 +00003020}
3021
Chris Lattner4794b2b2009-10-16 02:13:51 +00003022APInt
3023APFloat::convertHalfAPFloatToAPInt() const
3024{
3025 assert(semantics == (const llvm::fltSemantics*)&IEEEhalf);
Evan Cheng67c90212009-10-27 21:35:42 +00003026 assert(partCount()==1);
Chris Lattner4794b2b2009-10-16 02:13:51 +00003027
3028 uint32_t myexponent, mysignificand;
3029
Michael Gottesman8136c382013-06-26 23:17:28 +00003030 if (isFiniteNonZero()) {
Chris Lattner4794b2b2009-10-16 02:13:51 +00003031 myexponent = exponent+15; //bias
3032 mysignificand = (uint32_t)*significandParts();
3033 if (myexponent == 1 && !(mysignificand & 0x400))
3034 myexponent = 0; // denormal
3035 } else if (category==fcZero) {
3036 myexponent = 0;
3037 mysignificand = 0;
3038 } else if (category==fcInfinity) {
Dale Johannesen0d670b52009-10-23 04:02:51 +00003039 myexponent = 0x1f;
Chris Lattner4794b2b2009-10-16 02:13:51 +00003040 mysignificand = 0;
3041 } else {
3042 assert(category == fcNaN && "Unknown category!");
Dale Johannesen0d670b52009-10-23 04:02:51 +00003043 myexponent = 0x1f;
Chris Lattner4794b2b2009-10-16 02:13:51 +00003044 mysignificand = (uint32_t)*significandParts();
3045 }
3046
3047 return APInt(16, (((sign&1) << 15) | ((myexponent&0x1f) << 10) |
3048 (mysignificand & 0x3ff)));
3049}
3050
Dale Johannesen007aa372007-10-11 18:07:22 +00003051// This function creates an APInt that is just a bit map of the floating
3052// point constant as it would appear in memory. It is not a conversion,
3053// and treating the result as a normal integer is unlikely to be useful.
3054
Dale Johannesen245dceb2007-09-11 18:32:33 +00003055APInt
Dale Johannesen54306fe2008-10-09 18:53:47 +00003056APFloat::bitcastToAPInt() const
Neil Booth9acbf5a2007-09-26 21:33:42 +00003057{
Chris Lattner4794b2b2009-10-16 02:13:51 +00003058 if (semantics == (const llvm::fltSemantics*)&IEEEhalf)
3059 return convertHalfAPFloatToAPInt();
3060
Dan Gohmanb456a152008-01-29 12:08:20 +00003061 if (semantics == (const llvm::fltSemantics*)&IEEEsingle)
Dale Johannesen245dceb2007-09-11 18:32:33 +00003062 return convertFloatAPFloatToAPInt();
Anton Korobeynikov13e8c7e2009-08-21 22:10:30 +00003063
Dan Gohmanb456a152008-01-29 12:08:20 +00003064 if (semantics == (const llvm::fltSemantics*)&IEEEdouble)
Dale Johannesen245dceb2007-09-11 18:32:33 +00003065 return convertDoubleAPFloatToAPInt();
Neil Booth9acbf5a2007-09-26 21:33:42 +00003066
Anton Korobeynikov13e8c7e2009-08-21 22:10:30 +00003067 if (semantics == (const llvm::fltSemantics*)&IEEEquad)
3068 return convertQuadrupleAPFloatToAPInt();
3069
Dan Gohmanb456a152008-01-29 12:08:20 +00003070 if (semantics == (const llvm::fltSemantics*)&PPCDoubleDouble)
Dale Johannesen007aa372007-10-11 18:07:22 +00003071 return convertPPCDoubleDoubleAPFloatToAPInt();
3072
Dan Gohmanb456a152008-01-29 12:08:20 +00003073 assert(semantics == (const llvm::fltSemantics*)&x87DoubleExtended &&
Chris Lattner2a9bcb92007-10-06 06:13:42 +00003074 "unknown format!");
3075 return convertF80LongDoubleAPFloatToAPInt();
Dale Johannesen245dceb2007-09-11 18:32:33 +00003076}
3077
Neil Booth9acbf5a2007-09-26 21:33:42 +00003078float
3079APFloat::convertToFloat() const
3080{
Chris Lattner688f9912009-09-24 21:44:20 +00003081 assert(semantics == (const llvm::fltSemantics*)&IEEEsingle &&
3082 "Float semantics are not IEEEsingle");
Dale Johannesen54306fe2008-10-09 18:53:47 +00003083 APInt api = bitcastToAPInt();
Dale Johannesen245dceb2007-09-11 18:32:33 +00003084 return api.bitsToFloat();
3085}
3086
Neil Booth9acbf5a2007-09-26 21:33:42 +00003087double
3088APFloat::convertToDouble() const
3089{
Chris Lattner688f9912009-09-24 21:44:20 +00003090 assert(semantics == (const llvm::fltSemantics*)&IEEEdouble &&
3091 "Float semantics are not IEEEdouble");
Dale Johannesen54306fe2008-10-09 18:53:47 +00003092 APInt api = bitcastToAPInt();
Dale Johannesen245dceb2007-09-11 18:32:33 +00003093 return api.bitsToDouble();
3094}
3095
Dale Johannesenfff29952008-10-06 18:22:29 +00003096/// Integer bit is explicit in this format. Intel hardware (387 and later)
3097/// does not support these bit patterns:
3098/// exponent = all 1's, integer bit 0, significand 0 ("pseudoinfinity")
3099/// exponent = all 1's, integer bit 0, significand nonzero ("pseudoNaN")
3100/// exponent = 0, integer bit 1 ("pseudodenormal")
3101/// exponent!=0 nor all 1's, integer bit 0 ("unnormal")
3102/// At the moment, the first two are treated as NaNs, the second two as Normal.
Dale Johannesen245dceb2007-09-11 18:32:33 +00003103void
Neil Booth9acbf5a2007-09-26 21:33:42 +00003104APFloat::initFromF80LongDoubleAPInt(const APInt &api)
3105{
Dale Johannesen245dceb2007-09-11 18:32:33 +00003106 assert(api.getBitWidth()==80);
3107 uint64_t i1 = api.getRawData()[0];
3108 uint64_t i2 = api.getRawData()[1];
Dale Johannesen93eefa02009-03-23 21:16:53 +00003109 uint64_t myexponent = (i2 & 0x7fff);
3110 uint64_t mysignificand = i1;
Dale Johannesen245dceb2007-09-11 18:32:33 +00003111
3112 initialize(&APFloat::x87DoubleExtended);
Dale Johannesen146a0ea2007-09-20 23:47:58 +00003113 assert(partCount()==2);
Dale Johannesen245dceb2007-09-11 18:32:33 +00003114
Dale Johannesen93eefa02009-03-23 21:16:53 +00003115 sign = static_cast<unsigned int>(i2>>15);
Dale Johannesen245dceb2007-09-11 18:32:33 +00003116 if (myexponent==0 && mysignificand==0) {
3117 // exponent, significand meaningless
3118 category = fcZero;
3119 } else if (myexponent==0x7fff && mysignificand==0x8000000000000000ULL) {
3120 // exponent, significand meaningless
3121 category = fcInfinity;
3122 } else if (myexponent==0x7fff && mysignificand!=0x8000000000000000ULL) {
3123 // exponent meaningless
3124 category = fcNaN;
Dale Johannesen146a0ea2007-09-20 23:47:58 +00003125 significandParts()[0] = mysignificand;
3126 significandParts()[1] = 0;
Dale Johannesen245dceb2007-09-11 18:32:33 +00003127 } else {
3128 category = fcNormal;
3129 exponent = myexponent - 16383;
Dale Johannesen146a0ea2007-09-20 23:47:58 +00003130 significandParts()[0] = mysignificand;
3131 significandParts()[1] = 0;
Dale Johannesen245dceb2007-09-11 18:32:33 +00003132 if (myexponent==0) // denormal
3133 exponent = -16382;
Neil Booth9acbf5a2007-09-26 21:33:42 +00003134 }
Dale Johannesen245dceb2007-09-11 18:32:33 +00003135}
3136
3137void
Dale Johannesen007aa372007-10-11 18:07:22 +00003138APFloat::initFromPPCDoubleDoubleAPInt(const APInt &api)
3139{
3140 assert(api.getBitWidth()==128);
3141 uint64_t i1 = api.getRawData()[0];
3142 uint64_t i2 = api.getRawData()[1];
Ulrich Weigandd9f7e252012-10-29 18:09:01 +00003143 opStatus fs;
3144 bool losesInfo;
Dale Johannesen007aa372007-10-11 18:07:22 +00003145
Ulrich Weigandd9f7e252012-10-29 18:09:01 +00003146 // Get the first double and convert to our format.
3147 initFromDoubleAPInt(APInt(64, i1));
3148 fs = convert(PPCDoubleDouble, rmNearestTiesToEven, &losesInfo);
3149 assert(fs == opOK && !losesInfo);
3150 (void)fs;
Dale Johannesen007aa372007-10-11 18:07:22 +00003151
Ulrich Weigandd9f7e252012-10-29 18:09:01 +00003152 // Unless we have a special case, add in second double.
Michael Gottesman8136c382013-06-26 23:17:28 +00003153 if (isFiniteNonZero()) {
Tim Northover29178a32013-01-22 09:46:31 +00003154 APFloat v(IEEEdouble, APInt(64, i2));
Ulrich Weigandd9f7e252012-10-29 18:09:01 +00003155 fs = v.convert(PPCDoubleDouble, rmNearestTiesToEven, &losesInfo);
3156 assert(fs == opOK && !losesInfo);
3157 (void)fs;
3158
3159 add(v, rmNearestTiesToEven);
Dale Johannesen007aa372007-10-11 18:07:22 +00003160 }
3161}
3162
3163void
Anton Korobeynikov13e8c7e2009-08-21 22:10:30 +00003164APFloat::initFromQuadrupleAPInt(const APInt &api)
3165{
3166 assert(api.getBitWidth()==128);
3167 uint64_t i1 = api.getRawData()[0];
3168 uint64_t i2 = api.getRawData()[1];
3169 uint64_t myexponent = (i2 >> 48) & 0x7fff;
3170 uint64_t mysignificand = i1;
3171 uint64_t mysignificand2 = i2 & 0xffffffffffffLL;
3172
3173 initialize(&APFloat::IEEEquad);
3174 assert(partCount()==2);
3175
3176 sign = static_cast<unsigned int>(i2>>63);
3177 if (myexponent==0 &&
3178 (mysignificand==0 && mysignificand2==0)) {
3179 // exponent, significand meaningless
3180 category = fcZero;
3181 } else if (myexponent==0x7fff &&
3182 (mysignificand==0 && mysignificand2==0)) {
3183 // exponent, significand meaningless
3184 category = fcInfinity;
3185 } else if (myexponent==0x7fff &&
3186 (mysignificand!=0 || mysignificand2 !=0)) {
3187 // exponent meaningless
3188 category = fcNaN;
3189 significandParts()[0] = mysignificand;
3190 significandParts()[1] = mysignificand2;
3191 } else {
3192 category = fcNormal;
3193 exponent = myexponent - 16383;
3194 significandParts()[0] = mysignificand;
3195 significandParts()[1] = mysignificand2;
3196 if (myexponent==0) // denormal
3197 exponent = -16382;
3198 else
3199 significandParts()[1] |= 0x1000000000000LL; // integer bit
3200 }
3201}
3202
3203void
Neil Booth9acbf5a2007-09-26 21:33:42 +00003204APFloat::initFromDoubleAPInt(const APInt &api)
3205{
Dale Johannesen245dceb2007-09-11 18:32:33 +00003206 assert(api.getBitWidth()==64);
3207 uint64_t i = *api.getRawData();
Dale Johannesen918c33c2007-08-24 05:08:11 +00003208 uint64_t myexponent = (i >> 52) & 0x7ff;
3209 uint64_t mysignificand = i & 0xfffffffffffffLL;
3210
Dale Johannesena719a602007-08-24 00:56:33 +00003211 initialize(&APFloat::IEEEdouble);
Dale Johannesena719a602007-08-24 00:56:33 +00003212 assert(partCount()==1);
3213
Evan Cheng82b9e962008-05-02 21:15:08 +00003214 sign = static_cast<unsigned int>(i>>63);
Dale Johannesena719a602007-08-24 00:56:33 +00003215 if (myexponent==0 && mysignificand==0) {
3216 // exponent, significand meaningless
3217 category = fcZero;
Dale Johannesena719a602007-08-24 00:56:33 +00003218 } else if (myexponent==0x7ff && mysignificand==0) {
3219 // exponent, significand meaningless
3220 category = fcInfinity;
Dale Johannesen3cf889f2007-08-31 04:03:46 +00003221 } else if (myexponent==0x7ff && mysignificand!=0) {
3222 // exponent meaningless
3223 category = fcNaN;
3224 *significandParts() = mysignificand;
Dale Johannesena719a602007-08-24 00:56:33 +00003225 } else {
Dale Johannesena719a602007-08-24 00:56:33 +00003226 category = fcNormal;
3227 exponent = myexponent - 1023;
Dale Johannesen728687c2007-09-05 20:39:49 +00003228 *significandParts() = mysignificand;
3229 if (myexponent==0) // denormal
3230 exponent = -1022;
3231 else
3232 *significandParts() |= 0x10000000000000LL; // integer bit
Neil Booth9acbf5a2007-09-26 21:33:42 +00003233 }
Dale Johannesena719a602007-08-24 00:56:33 +00003234}
3235
Dale Johannesen245dceb2007-09-11 18:32:33 +00003236void
Neil Booth9acbf5a2007-09-26 21:33:42 +00003237APFloat::initFromFloatAPInt(const APInt & api)
3238{
Dale Johannesen245dceb2007-09-11 18:32:33 +00003239 assert(api.getBitWidth()==32);
3240 uint32_t i = (uint32_t)*api.getRawData();
Dale Johannesen918c33c2007-08-24 05:08:11 +00003241 uint32_t myexponent = (i >> 23) & 0xff;
3242 uint32_t mysignificand = i & 0x7fffff;
3243
Dale Johannesena719a602007-08-24 00:56:33 +00003244 initialize(&APFloat::IEEEsingle);
Dale Johannesena719a602007-08-24 00:56:33 +00003245 assert(partCount()==1);
3246
Dale Johannesen3cf889f2007-08-31 04:03:46 +00003247 sign = i >> 31;
Dale Johannesena719a602007-08-24 00:56:33 +00003248 if (myexponent==0 && mysignificand==0) {
3249 // exponent, significand meaningless
3250 category = fcZero;
Dale Johannesena719a602007-08-24 00:56:33 +00003251 } else if (myexponent==0xff && mysignificand==0) {
3252 // exponent, significand meaningless
3253 category = fcInfinity;
Dale Johannesen4f55d9f2007-09-25 17:25:00 +00003254 } else if (myexponent==0xff && mysignificand!=0) {
Dale Johannesena719a602007-08-24 00:56:33 +00003255 // sign, exponent, significand meaningless
Dale Johannesen3cf889f2007-08-31 04:03:46 +00003256 category = fcNaN;
3257 *significandParts() = mysignificand;
Dale Johannesena719a602007-08-24 00:56:33 +00003258 } else {
3259 category = fcNormal;
Dale Johannesena719a602007-08-24 00:56:33 +00003260 exponent = myexponent - 127; //bias
Dale Johannesen728687c2007-09-05 20:39:49 +00003261 *significandParts() = mysignificand;
3262 if (myexponent==0) // denormal
3263 exponent = -126;
3264 else
3265 *significandParts() |= 0x800000; // integer bit
Dale Johannesena719a602007-08-24 00:56:33 +00003266 }
3267}
Dale Johannesen245dceb2007-09-11 18:32:33 +00003268
Chris Lattner4794b2b2009-10-16 02:13:51 +00003269void
3270APFloat::initFromHalfAPInt(const APInt & api)
3271{
3272 assert(api.getBitWidth()==16);
3273 uint32_t i = (uint32_t)*api.getRawData();
Dale Johannesen0d670b52009-10-23 04:02:51 +00003274 uint32_t myexponent = (i >> 10) & 0x1f;
Chris Lattner4794b2b2009-10-16 02:13:51 +00003275 uint32_t mysignificand = i & 0x3ff;
3276
3277 initialize(&APFloat::IEEEhalf);
3278 assert(partCount()==1);
3279
3280 sign = i >> 15;
3281 if (myexponent==0 && mysignificand==0) {
3282 // exponent, significand meaningless
3283 category = fcZero;
3284 } else if (myexponent==0x1f && mysignificand==0) {
3285 // exponent, significand meaningless
3286 category = fcInfinity;
3287 } else if (myexponent==0x1f && mysignificand!=0) {
3288 // sign, exponent, significand meaningless
3289 category = fcNaN;
3290 *significandParts() = mysignificand;
3291 } else {
3292 category = fcNormal;
3293 exponent = myexponent - 15; //bias
3294 *significandParts() = mysignificand;
3295 if (myexponent==0) // denormal
3296 exponent = -14;
3297 else
3298 *significandParts() |= 0x400; // integer bit
3299 }
3300}
3301
Dale Johannesen245dceb2007-09-11 18:32:33 +00003302/// Treat api as containing the bits of a floating point number. Currently
Dale Johannesen007aa372007-10-11 18:07:22 +00003303/// we infer the floating point type from the size of the APInt. The
3304/// isIEEE argument distinguishes between PPC128 and IEEE128 (not meaningful
3305/// when the size is anything else).
Dale Johannesen245dceb2007-09-11 18:32:33 +00003306void
Tim Northover29178a32013-01-22 09:46:31 +00003307APFloat::initFromAPInt(const fltSemantics* Sem, const APInt& api)
Neil Booth9acbf5a2007-09-26 21:33:42 +00003308{
Tim Northover29178a32013-01-22 09:46:31 +00003309 if (Sem == &IEEEhalf)
Chris Lattner4794b2b2009-10-16 02:13:51 +00003310 return initFromHalfAPInt(api);
Tim Northover29178a32013-01-22 09:46:31 +00003311 if (Sem == &IEEEsingle)
Dale Johannesen245dceb2007-09-11 18:32:33 +00003312 return initFromFloatAPInt(api);
Tim Northover29178a32013-01-22 09:46:31 +00003313 if (Sem == &IEEEdouble)
Dale Johannesen245dceb2007-09-11 18:32:33 +00003314 return initFromDoubleAPInt(api);
Tim Northover29178a32013-01-22 09:46:31 +00003315 if (Sem == &x87DoubleExtended)
Dale Johannesen245dceb2007-09-11 18:32:33 +00003316 return initFromF80LongDoubleAPInt(api);
Tim Northover29178a32013-01-22 09:46:31 +00003317 if (Sem == &IEEEquad)
3318 return initFromQuadrupleAPInt(api);
3319 if (Sem == &PPCDoubleDouble)
3320 return initFromPPCDoubleDoubleAPInt(api);
3321
3322 llvm_unreachable(0);
Dale Johannesen245dceb2007-09-11 18:32:33 +00003323}
3324
Nadav Rotem7cc6d122011-02-17 21:22:27 +00003325APFloat
3326APFloat::getAllOnesValue(unsigned BitWidth, bool isIEEE)
3327{
Tim Northover29178a32013-01-22 09:46:31 +00003328 switch (BitWidth) {
3329 case 16:
3330 return APFloat(IEEEhalf, APInt::getAllOnesValue(BitWidth));
3331 case 32:
3332 return APFloat(IEEEsingle, APInt::getAllOnesValue(BitWidth));
3333 case 64:
3334 return APFloat(IEEEdouble, APInt::getAllOnesValue(BitWidth));
3335 case 80:
3336 return APFloat(x87DoubleExtended, APInt::getAllOnesValue(BitWidth));
3337 case 128:
3338 if (isIEEE)
3339 return APFloat(IEEEquad, APInt::getAllOnesValue(BitWidth));
3340 return APFloat(PPCDoubleDouble, APInt::getAllOnesValue(BitWidth));
3341 default:
3342 llvm_unreachable("Unknown floating bit width");
3343 }
Nadav Rotem7cc6d122011-02-17 21:22:27 +00003344}
3345
Michael Gottesman0c622ea2013-05-30 18:07:13 +00003346/// Make this number the largest magnitude normal number in the given
3347/// semantics.
3348void APFloat::makeLargest(bool Negative) {
John McCall29b5c282009-12-24 08:56:26 +00003349 // We want (in interchange format):
3350 // sign = {Negative}
3351 // exponent = 1..10
3352 // significand = 1..1
Michael Gottesman0c622ea2013-05-30 18:07:13 +00003353 category = fcNormal;
3354 sign = Negative;
3355 exponent = semantics->maxExponent;
John McCall29b5c282009-12-24 08:56:26 +00003356
Michael Gottesman0c622ea2013-05-30 18:07:13 +00003357 // Use memset to set all but the highest integerPart to all ones.
3358 integerPart *significand = significandParts();
3359 unsigned PartCount = partCount();
3360 memset(significand, 0xFF, sizeof(integerPart)*(PartCount - 1));
John McCall29b5c282009-12-24 08:56:26 +00003361
Michael Gottesman0c622ea2013-05-30 18:07:13 +00003362 // Set the high integerPart especially setting all unused top bits for
3363 // internal consistency.
3364 const unsigned NumUnusedHighBits =
3365 PartCount*integerPartWidth - semantics->precision;
3366 significand[PartCount - 1] = ~integerPart(0) >> NumUnusedHighBits;
John McCall29b5c282009-12-24 08:56:26 +00003367}
3368
Michael Gottesman0c622ea2013-05-30 18:07:13 +00003369/// Make this number the smallest magnitude denormal number in the given
3370/// semantics.
3371void APFloat::makeSmallest(bool Negative) {
John McCall29b5c282009-12-24 08:56:26 +00003372 // We want (in interchange format):
3373 // sign = {Negative}
3374 // exponent = 0..0
3375 // significand = 0..01
Michael Gottesman0c622ea2013-05-30 18:07:13 +00003376 category = fcNormal;
3377 sign = Negative;
3378 exponent = semantics->minExponent;
3379 APInt::tcSet(significandParts(), 1, partCount());
3380}
John McCall29b5c282009-12-24 08:56:26 +00003381
Michael Gottesman0c622ea2013-05-30 18:07:13 +00003382
3383APFloat APFloat::getLargest(const fltSemantics &Sem, bool Negative) {
3384 // We want (in interchange format):
3385 // sign = {Negative}
3386 // exponent = 1..10
3387 // significand = 1..1
3388 APFloat Val(Sem, uninitialized);
3389 Val.makeLargest(Negative);
3390 return Val;
3391}
3392
3393APFloat APFloat::getSmallest(const fltSemantics &Sem, bool Negative) {
3394 // We want (in interchange format):
3395 // sign = {Negative}
3396 // exponent = 0..0
3397 // significand = 0..01
3398 APFloat Val(Sem, uninitialized);
3399 Val.makeSmallest(Negative);
John McCall29b5c282009-12-24 08:56:26 +00003400 return Val;
3401}
3402
3403APFloat APFloat::getSmallestNormalized(const fltSemantics &Sem, bool Negative) {
Michael Gottesman79b09672013-06-27 21:58:19 +00003404 APFloat Val(Sem, uninitialized);
John McCall29b5c282009-12-24 08:56:26 +00003405
3406 // We want (in interchange format):
3407 // sign = {Negative}
3408 // exponent = 0..0
3409 // significand = 10..0
3410
Michael Gottesmanccaf3322013-06-27 20:40:11 +00003411 Val.zeroSignificand();
Michael Gottesman79b09672013-06-27 21:58:19 +00003412 Val.sign = Negative;
3413 Val.exponent = Sem.minExponent;
Dan Gohmanb452d4e2010-03-24 19:38:02 +00003414 Val.significandParts()[partCountForBits(Sem.precision)-1] |=
Eli Friedmand4330422011-10-12 21:56:19 +00003415 (((integerPart) 1) << ((Sem.precision - 1) % integerPartWidth));
John McCall29b5c282009-12-24 08:56:26 +00003416
3417 return Val;
3418}
3419
Tim Northover29178a32013-01-22 09:46:31 +00003420APFloat::APFloat(const fltSemantics &Sem, const APInt &API) {
3421 initFromAPInt(&Sem, API);
Dale Johannesen245dceb2007-09-11 18:32:33 +00003422}
3423
Ulrich Weigande1d62f92012-10-29 18:17:42 +00003424APFloat::APFloat(float f) {
Tim Northover29178a32013-01-22 09:46:31 +00003425 initFromAPInt(&IEEEsingle, APInt::floatToBits(f));
Dale Johannesen245dceb2007-09-11 18:32:33 +00003426}
3427
Ulrich Weigande1d62f92012-10-29 18:17:42 +00003428APFloat::APFloat(double d) {
Tim Northover29178a32013-01-22 09:46:31 +00003429 initFromAPInt(&IEEEdouble, APInt::doubleToBits(d));
Dale Johannesen245dceb2007-09-11 18:32:33 +00003430}
John McCall29b5c282009-12-24 08:56:26 +00003431
3432namespace {
David Blaikie70fdf722012-07-25 18:04:24 +00003433 void append(SmallVectorImpl<char> &Buffer, StringRef Str) {
3434 Buffer.append(Str.begin(), Str.end());
John McCall29b5c282009-12-24 08:56:26 +00003435 }
3436
John McCalle6212ace2009-12-24 12:16:56 +00003437 /// Removes data from the given significand until it is no more
3438 /// precise than is required for the desired precision.
3439 void AdjustToPrecision(APInt &significand,
3440 int &exp, unsigned FormatPrecision) {
3441 unsigned bits = significand.getActiveBits();
3442
3443 // 196/59 is a very slight overestimate of lg_2(10).
3444 unsigned bitsRequired = (FormatPrecision * 196 + 58) / 59;
3445
3446 if (bits <= bitsRequired) return;
3447
3448 unsigned tensRemovable = (bits - bitsRequired) * 59 / 196;
3449 if (!tensRemovable) return;
3450
3451 exp += tensRemovable;
3452
3453 APInt divisor(significand.getBitWidth(), 1);
3454 APInt powten(significand.getBitWidth(), 10);
3455 while (true) {
3456 if (tensRemovable & 1)
3457 divisor *= powten;
3458 tensRemovable >>= 1;
3459 if (!tensRemovable) break;
3460 powten *= powten;
3461 }
3462
3463 significand = significand.udiv(divisor);
3464
Hao Liube99cc32013-03-20 01:46:36 +00003465 // Truncate the significand down to its active bit count.
3466 significand = significand.trunc(significand.getActiveBits());
John McCalle6212ace2009-12-24 12:16:56 +00003467 }
3468
3469
John McCall29b5c282009-12-24 08:56:26 +00003470 void AdjustToPrecision(SmallVectorImpl<char> &buffer,
3471 int &exp, unsigned FormatPrecision) {
3472 unsigned N = buffer.size();
3473 if (N <= FormatPrecision) return;
3474
3475 // The most significant figures are the last ones in the buffer.
3476 unsigned FirstSignificant = N - FormatPrecision;
3477
3478 // Round.
3479 // FIXME: this probably shouldn't use 'round half up'.
3480
3481 // Rounding down is just a truncation, except we also want to drop
3482 // trailing zeros from the new result.
3483 if (buffer[FirstSignificant - 1] < '5') {
NAKAMURA Takumi5adeb932012-02-19 03:18:29 +00003484 while (FirstSignificant < N && buffer[FirstSignificant] == '0')
John McCall29b5c282009-12-24 08:56:26 +00003485 FirstSignificant++;
3486
3487 exp += FirstSignificant;
3488 buffer.erase(&buffer[0], &buffer[FirstSignificant]);
3489 return;
3490 }
3491
3492 // Rounding up requires a decimal add-with-carry. If we continue
3493 // the carry, the newly-introduced zeros will just be truncated.
3494 for (unsigned I = FirstSignificant; I != N; ++I) {
3495 if (buffer[I] == '9') {
3496 FirstSignificant++;
3497 } else {
3498 buffer[I]++;
3499 break;
3500 }
3501 }
3502
3503 // If we carried through, we have exactly one digit of precision.
3504 if (FirstSignificant == N) {
3505 exp += FirstSignificant;
3506 buffer.clear();
3507 buffer.push_back('1');
3508 return;
3509 }
3510
3511 exp += FirstSignificant;
3512 buffer.erase(&buffer[0], &buffer[FirstSignificant]);
3513 }
3514}
3515
3516void APFloat::toString(SmallVectorImpl<char> &Str,
3517 unsigned FormatPrecision,
Chris Lattner4c1e4db2010-03-06 19:20:13 +00003518 unsigned FormatMaxPadding) const {
John McCall29b5c282009-12-24 08:56:26 +00003519 switch (category) {
3520 case fcInfinity:
3521 if (isNegative())
3522 return append(Str, "-Inf");
3523 else
3524 return append(Str, "+Inf");
3525
3526 case fcNaN: return append(Str, "NaN");
3527
3528 case fcZero:
3529 if (isNegative())
3530 Str.push_back('-');
3531
3532 if (!FormatMaxPadding)
3533 append(Str, "0.0E+0");
3534 else
3535 Str.push_back('0');
3536 return;
3537
3538 case fcNormal:
3539 break;
3540 }
3541
3542 if (isNegative())
3543 Str.push_back('-');
3544
3545 // Decompose the number into an APInt and an exponent.
3546 int exp = exponent - ((int) semantics->precision - 1);
3547 APInt significand(semantics->precision,
Jeffrey Yasskin7a162882011-07-18 21:45:40 +00003548 makeArrayRef(significandParts(),
3549 partCountForBits(semantics->precision)));
John McCall29b5c282009-12-24 08:56:26 +00003550
John McCalldd5044a2009-12-24 23:18:09 +00003551 // Set FormatPrecision if zero. We want to do this before we
3552 // truncate trailing zeros, as those are part of the precision.
3553 if (!FormatPrecision) {
3554 // It's an interesting question whether to use the nominal
3555 // precision or the active precision here for denormals.
3556
3557 // FormatPrecision = ceil(significandBits / lg_2(10))
3558 FormatPrecision = (semantics->precision * 59 + 195) / 196;
3559 }
3560
John McCall29b5c282009-12-24 08:56:26 +00003561 // Ignore trailing binary zeros.
3562 int trailingZeros = significand.countTrailingZeros();
3563 exp += trailingZeros;
3564 significand = significand.lshr(trailingZeros);
3565
3566 // Change the exponent from 2^e to 10^e.
3567 if (exp == 0) {
3568 // Nothing to do.
3569 } else if (exp > 0) {
3570 // Just shift left.
Jay Foad583abbc2010-12-07 08:25:19 +00003571 significand = significand.zext(semantics->precision + exp);
John McCall29b5c282009-12-24 08:56:26 +00003572 significand <<= exp;
3573 exp = 0;
3574 } else { /* exp < 0 */
3575 int texp = -exp;
3576
3577 // We transform this using the identity:
3578 // (N)(2^-e) == (N)(5^e)(10^-e)
3579 // This means we have to multiply N (the significand) by 5^e.
3580 // To avoid overflow, we have to operate on numbers large
3581 // enough to store N * 5^e:
3582 // log2(N * 5^e) == log2(N) + e * log2(5)
John McCalldd5044a2009-12-24 23:18:09 +00003583 // <= semantics->precision + e * 137 / 59
3584 // (log_2(5) ~ 2.321928 < 2.322034 ~ 137/59)
Dan Gohmanb452d4e2010-03-24 19:38:02 +00003585
Eli Friedman19546412011-10-07 23:40:49 +00003586 unsigned precision = semantics->precision + (137 * texp + 136) / 59;
John McCall29b5c282009-12-24 08:56:26 +00003587
3588 // Multiply significand by 5^e.
3589 // N * 5^0101 == N * 5^(1*1) * 5^(0*2) * 5^(1*4) * 5^(0*8)
Jay Foad583abbc2010-12-07 08:25:19 +00003590 significand = significand.zext(precision);
John McCall29b5c282009-12-24 08:56:26 +00003591 APInt five_to_the_i(precision, 5);
3592 while (true) {
3593 if (texp & 1) significand *= five_to_the_i;
Dan Gohmanb452d4e2010-03-24 19:38:02 +00003594
John McCall29b5c282009-12-24 08:56:26 +00003595 texp >>= 1;
3596 if (!texp) break;
3597 five_to_the_i *= five_to_the_i;
3598 }
3599 }
3600
John McCalle6212ace2009-12-24 12:16:56 +00003601 AdjustToPrecision(significand, exp, FormatPrecision);
3602
Dmitri Gribenko226fea52013-01-13 16:01:15 +00003603 SmallVector<char, 256> buffer;
John McCall29b5c282009-12-24 08:56:26 +00003604
3605 // Fill the buffer.
3606 unsigned precision = significand.getBitWidth();
3607 APInt ten(precision, 10);
3608 APInt digit(precision, 0);
3609
3610 bool inTrail = true;
3611 while (significand != 0) {
3612 // digit <- significand % 10
3613 // significand <- significand / 10
3614 APInt::udivrem(significand, ten, significand, digit);
3615
3616 unsigned d = digit.getZExtValue();
3617
3618 // Drop trailing zeros.
3619 if (inTrail && !d) exp++;
3620 else {
3621 buffer.push_back((char) ('0' + d));
3622 inTrail = false;
3623 }
3624 }
3625
3626 assert(!buffer.empty() && "no characters in buffer!");
3627
3628 // Drop down to FormatPrecision.
3629 // TODO: don't do more precise calculations above than are required.
3630 AdjustToPrecision(buffer, exp, FormatPrecision);
3631
3632 unsigned NDigits = buffer.size();
3633
John McCalldd5044a2009-12-24 23:18:09 +00003634 // Check whether we should use scientific notation.
John McCall29b5c282009-12-24 08:56:26 +00003635 bool FormatScientific;
3636 if (!FormatMaxPadding)
3637 FormatScientific = true;
3638 else {
John McCall29b5c282009-12-24 08:56:26 +00003639 if (exp >= 0) {
John McCalldd5044a2009-12-24 23:18:09 +00003640 // 765e3 --> 765000
3641 // ^^^
3642 // But we shouldn't make the number look more precise than it is.
3643 FormatScientific = ((unsigned) exp > FormatMaxPadding ||
3644 NDigits + (unsigned) exp > FormatPrecision);
John McCall29b5c282009-12-24 08:56:26 +00003645 } else {
John McCalldd5044a2009-12-24 23:18:09 +00003646 // Power of the most significant digit.
3647 int MSD = exp + (int) (NDigits - 1);
3648 if (MSD >= 0) {
John McCall29b5c282009-12-24 08:56:26 +00003649 // 765e-2 == 7.65
John McCalldd5044a2009-12-24 23:18:09 +00003650 FormatScientific = false;
John McCall29b5c282009-12-24 08:56:26 +00003651 } else {
3652 // 765e-5 == 0.00765
3653 // ^ ^^
John McCalldd5044a2009-12-24 23:18:09 +00003654 FormatScientific = ((unsigned) -MSD) > FormatMaxPadding;
John McCall29b5c282009-12-24 08:56:26 +00003655 }
3656 }
John McCall29b5c282009-12-24 08:56:26 +00003657 }
3658
3659 // Scientific formatting is pretty straightforward.
3660 if (FormatScientific) {
3661 exp += (NDigits - 1);
3662
3663 Str.push_back(buffer[NDigits-1]);
3664 Str.push_back('.');
3665 if (NDigits == 1)
3666 Str.push_back('0');
3667 else
3668 for (unsigned I = 1; I != NDigits; ++I)
3669 Str.push_back(buffer[NDigits-1-I]);
3670 Str.push_back('E');
3671
3672 Str.push_back(exp >= 0 ? '+' : '-');
3673 if (exp < 0) exp = -exp;
3674 SmallVector<char, 6> expbuf;
3675 do {
3676 expbuf.push_back((char) ('0' + (exp % 10)));
3677 exp /= 10;
3678 } while (exp);
3679 for (unsigned I = 0, E = expbuf.size(); I != E; ++I)
3680 Str.push_back(expbuf[E-1-I]);
3681 return;
3682 }
3683
3684 // Non-scientific, positive exponents.
3685 if (exp >= 0) {
3686 for (unsigned I = 0; I != NDigits; ++I)
3687 Str.push_back(buffer[NDigits-1-I]);
3688 for (unsigned I = 0; I != (unsigned) exp; ++I)
3689 Str.push_back('0');
3690 return;
3691 }
3692
3693 // Non-scientific, negative exponents.
3694
3695 // The number of digits to the left of the decimal point.
3696 int NWholeDigits = exp + (int) NDigits;
3697
3698 unsigned I = 0;
3699 if (NWholeDigits > 0) {
3700 for (; I != (unsigned) NWholeDigits; ++I)
3701 Str.push_back(buffer[NDigits-I-1]);
3702 Str.push_back('.');
3703 } else {
3704 unsigned NZeros = 1 + (unsigned) -NWholeDigits;
3705
3706 Str.push_back('0');
3707 Str.push_back('.');
3708 for (unsigned Z = 1; Z != NZeros; ++Z)
3709 Str.push_back('0');
3710 }
3711
3712 for (; I != NDigits; ++I)
3713 Str.push_back(buffer[NDigits-I-1]);
3714}
Benjamin Kramer03fd6722011-03-30 15:42:27 +00003715
3716bool APFloat::getExactInverse(APFloat *inv) const {
Benjamin Kramer03fd6722011-03-30 15:42:27 +00003717 // Special floats and denormals have no exact inverse.
Michael Gottesman8136c382013-06-26 23:17:28 +00003718 if (!isFiniteNonZero())
Benjamin Kramer03fd6722011-03-30 15:42:27 +00003719 return false;
3720
3721 // Check that the number is a power of two by making sure that only the
3722 // integer bit is set in the significand.
3723 if (significandLSB() != semantics->precision - 1)
3724 return false;
3725
3726 // Get the inverse.
3727 APFloat reciprocal(*semantics, 1ULL);
3728 if (reciprocal.divide(*this, rmNearestTiesToEven) != opOK)
3729 return false;
3730
Benjamin Krameraf0ed952011-03-30 17:02:54 +00003731 // Avoid multiplication with a denormal, it is not safe on all platforms and
3732 // may be slower than a normal division.
Benjamin Kramer6bef24f2013-06-01 11:26:33 +00003733 if (reciprocal.isDenormal())
Benjamin Krameraf0ed952011-03-30 17:02:54 +00003734 return false;
3735
Michael Gottesman8136c382013-06-26 23:17:28 +00003736 assert(reciprocal.isFiniteNonZero() &&
Benjamin Krameraf0ed952011-03-30 17:02:54 +00003737 reciprocal.significandLSB() == reciprocal.semantics->precision - 1);
3738
Benjamin Kramer03fd6722011-03-30 15:42:27 +00003739 if (inv)
3740 *inv = reciprocal;
3741
3742 return true;
3743}
Michael Gottesman0c622ea2013-05-30 18:07:13 +00003744
3745bool APFloat::isSignaling() const {
3746 if (!isNaN())
3747 return false;
3748
3749 // IEEE-754R 2008 6.2.1: A signaling NaN bit string should be encoded with the
3750 // first bit of the trailing significand being 0.
3751 return !APInt::tcExtractBit(significandParts(), semantics->precision - 2);
3752}
3753
3754/// IEEE-754R 2008 5.3.1: nextUp/nextDown.
3755///
3756/// *NOTE* since nextDown(x) = -nextUp(-x), we only implement nextUp with
3757/// appropriate sign switching before/after the computation.
3758APFloat::opStatus APFloat::next(bool nextDown) {
3759 // If we are performing nextDown, swap sign so we have -x.
3760 if (nextDown)
3761 changeSign();
3762
3763 // Compute nextUp(x)
3764 opStatus result = opOK;
3765
3766 // Handle each float category separately.
3767 switch (category) {
3768 case fcInfinity:
3769 // nextUp(+inf) = +inf
3770 if (!isNegative())
3771 break;
3772 // nextUp(-inf) = -getLargest()
3773 makeLargest(true);
3774 break;
3775 case fcNaN:
3776 // IEEE-754R 2008 6.2 Par 2: nextUp(sNaN) = qNaN. Set Invalid flag.
3777 // IEEE-754R 2008 6.2: nextUp(qNaN) = qNaN. Must be identity so we do not
3778 // change the payload.
3779 if (isSignaling()) {
3780 result = opInvalidOp;
3781 // For consistency, propogate the sign of the sNaN to the qNaN.
3782 makeNaN(false, isNegative(), 0);
3783 }
3784 break;
3785 case fcZero:
3786 // nextUp(pm 0) = +getSmallest()
3787 makeSmallest(false);
3788 break;
3789 case fcNormal:
3790 // nextUp(-getSmallest()) = -0
3791 if (isSmallest() && isNegative()) {
3792 APInt::tcSet(significandParts(), 0, partCount());
3793 category = fcZero;
3794 exponent = 0;
3795 break;
3796 }
3797
3798 // nextUp(getLargest()) == INFINITY
3799 if (isLargest() && !isNegative()) {
3800 APInt::tcSet(significandParts(), 0, partCount());
3801 category = fcInfinity;
3802 exponent = semantics->maxExponent + 1;
3803 break;
3804 }
3805
3806 // nextUp(normal) == normal + inc.
3807 if (isNegative()) {
3808 // If we are negative, we need to decrement the significand.
3809
3810 // We only cross a binade boundary that requires adjusting the exponent
3811 // if:
3812 // 1. exponent != semantics->minExponent. This implies we are not in the
3813 // smallest binade or are dealing with denormals.
3814 // 2. Our significand excluding the integral bit is all zeros.
3815 bool WillCrossBinadeBoundary =
3816 exponent != semantics->minExponent && isSignificandAllZeros();
3817
3818 // Decrement the significand.
3819 //
3820 // We always do this since:
3821 // 1. If we are dealing with a non binade decrement, by definition we
3822 // just decrement the significand.
3823 // 2. If we are dealing with a normal -> normal binade decrement, since
3824 // we have an explicit integral bit the fact that all bits but the
3825 // integral bit are zero implies that subtracting one will yield a
3826 // significand with 0 integral bit and 1 in all other spots. Thus we
3827 // must just adjust the exponent and set the integral bit to 1.
3828 // 3. If we are dealing with a normal -> denormal binade decrement,
3829 // since we set the integral bit to 0 when we represent denormals, we
3830 // just decrement the significand.
3831 integerPart *Parts = significandParts();
3832 APInt::tcDecrement(Parts, partCount());
3833
3834 if (WillCrossBinadeBoundary) {
3835 // Our result is a normal number. Do the following:
3836 // 1. Set the integral bit to 1.
3837 // 2. Decrement the exponent.
3838 APInt::tcSetBit(Parts, semantics->precision - 1);
3839 exponent--;
3840 }
3841 } else {
3842 // If we are positive, we need to increment the significand.
3843
3844 // We only cross a binade boundary that requires adjusting the exponent if
3845 // the input is not a denormal and all of said input's significand bits
3846 // are set. If all of said conditions are true: clear the significand, set
3847 // the integral bit to 1, and increment the exponent. If we have a
3848 // denormal always increment since moving denormals and the numbers in the
3849 // smallest normal binade have the same exponent in our representation.
3850 bool WillCrossBinadeBoundary = !isDenormal() && isSignificandAllOnes();
3851
3852 if (WillCrossBinadeBoundary) {
3853 integerPart *Parts = significandParts();
3854 APInt::tcSet(Parts, 0, partCount());
3855 APInt::tcSetBit(Parts, semantics->precision - 1);
3856 assert(exponent != semantics->maxExponent &&
3857 "We can not increment an exponent beyond the maxExponent allowed"
3858 " by the given floating point semantics.");
3859 exponent++;
3860 } else {
3861 incrementSignificand();
3862 }
3863 }
3864 break;
3865 }
3866
3867 // If we are performing nextDown, swap sign so we have -nextUp(-x)
3868 if (nextDown)
3869 changeSign();
3870
3871 return result;
3872}
Michael Gottesmanc4facdf2013-06-24 09:58:02 +00003873
3874void
3875APFloat::makeInf(bool Negative) {
3876 category = fcInfinity;
3877 sign = Negative;
3878 exponent = semantics->maxExponent + 1;
3879 APInt::tcSet(significandParts(), 0, partCount());
3880}
3881
3882void
3883APFloat::makeZero(bool Negative) {
3884 category = fcZero;
3885 sign = Negative;
3886 exponent = semantics->minExponent-1;
3887 APInt::tcSet(significandParts(), 0, partCount());
3888}