blob: 9435c41ff585107e9f95b96b3895aa4455080c4a [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"
19#include "llvm/ADT/StringRef.h"
Torok Edwin56d06592009-07-11 20:10:48 +000020#include "llvm/Support/ErrorHandling.h"
Dale Johannesen918c33c2007-08-24 05:08:11 +000021#include "llvm/Support/MathExtras.h"
John McCallb42cc682010-02-26 22:20:41 +000022#include <limits.h>
Chris Lattner17f71652008-08-17 07:19:36 +000023#include <cstring>
Chris Lattnerfe02c1f2007-08-20 22:49:32 +000024
25using namespace llvm;
26
27#define convolve(lhs, rhs) ((lhs) * 4 + (rhs))
28
Neil Booth8f1946f2007-10-03 22:26:02 +000029/* Assumed in hexadecimal significand parsing, and conversion to
30 hexadecimal strings. */
Chris Lattner8fcea672008-08-17 04:58:58 +000031#define COMPILE_TIME_ASSERT(cond) extern int CTAssert[(cond) ? 1 : -1]
Chris Lattnerfe02c1f2007-08-20 22:49:32 +000032COMPILE_TIME_ASSERT(integerPartWidth % 4 == 0);
33
34namespace llvm {
35
36 /* Represents floating point arithmetic semantics. */
37 struct fltSemantics {
38 /* The largest E such that 2^E is representable; this matches the
39 definition of IEEE 754. */
40 exponent_t maxExponent;
41
42 /* The smallest E such that 2^E is a normalized number; this
43 matches the definition of IEEE 754. */
44 exponent_t minExponent;
45
46 /* Number of bits in the significand. This includes the integer
47 bit. */
Neil Booth146fdb32007-10-12 15:33:27 +000048 unsigned int precision;
Neil Booth06077e72007-10-14 10:29:28 +000049
50 /* True if arithmetic is supported. */
51 unsigned int arithmeticOK;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +000052 };
53
Chris Lattner4794b2b2009-10-16 02:13:51 +000054 const fltSemantics APFloat::IEEEhalf = { 15, -14, 11, true };
Neil Booth06077e72007-10-14 10:29:28 +000055 const fltSemantics APFloat::IEEEsingle = { 127, -126, 24, true };
56 const fltSemantics APFloat::IEEEdouble = { 1023, -1022, 53, true };
57 const fltSemantics APFloat::IEEEquad = { 16383, -16382, 113, true };
58 const fltSemantics APFloat::x87DoubleExtended = { 16383, -16382, 64, true };
59 const fltSemantics APFloat::Bogus = { 0, 0, 0, true };
Dale Johannesen007aa372007-10-11 18:07:22 +000060
Ulrich Weigandd9f7e252012-10-29 18:09:01 +000061 /* The PowerPC format consists of two doubles. It does not map cleanly
62 onto the usual format above. It is approximated using twice the
63 mantissa bits. Note that for exponents near the double minimum,
64 we no longer can represent the full 106 mantissa bits, so those
65 will be treated as denormal numbers.
66
67 FIXME: While this approximation is equivalent to what GCC uses for
68 compile-time arithmetic on PPC double-double numbers, it is not able
69 to represent all possible values held by a PPC double-double number,
70 for example: (long double) 1.0 + (long double) 0x1p-106
71 Should this be replaced by a full emulation of PPC double-double? */
72 const fltSemantics APFloat::PPCDoubleDouble =
73 { 1023, -1022 + 53, 53 + 53, true };
Neil Boothb93d90e2007-10-12 16:02:31 +000074
75 /* A tight upper bound on number of parts required to hold the value
76 pow(5, power) is
77
Neil Booth91305512007-10-15 15:00:55 +000078 power * 815 / (351 * integerPartWidth) + 1
Dan Gohmanb452d4e2010-03-24 19:38:02 +000079
Neil Boothb93d90e2007-10-12 16:02:31 +000080 However, whilst the result may require only this many parts,
81 because we are multiplying two values to get it, the
82 multiplication may require an extra part with the excess part
83 being zero (consider the trivial case of 1 * 1, tcFullMultiply
84 requires two parts to hold the single-part result). So we add an
85 extra one to guarantee enough space whilst multiplying. */
86 const unsigned int maxExponent = 16383;
87 const unsigned int maxPrecision = 113;
88 const unsigned int maxPowerOfFiveExponent = maxExponent + maxPrecision - 1;
Neil Booth91305512007-10-15 15:00:55 +000089 const unsigned int maxPowerOfFiveParts = 2 + ((maxPowerOfFiveExponent * 815)
90 / (351 * integerPartWidth));
Chris Lattnerfe02c1f2007-08-20 22:49:32 +000091}
92
Chris Lattner91702092009-03-12 23:59:55 +000093/* A bunch of private, handy routines. */
Chris Lattnerfe02c1f2007-08-20 22:49:32 +000094
Chris Lattner91702092009-03-12 23:59:55 +000095static inline unsigned int
96partCountForBits(unsigned int bits)
97{
98 return ((bits) + integerPartWidth - 1) / integerPartWidth;
99}
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000100
Chris Lattner91702092009-03-12 23:59:55 +0000101/* Returns 0U-9U. Return values >= 10U are not digits. */
102static inline unsigned int
103decDigitValue(unsigned int c)
104{
105 return c - '0';
106}
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000107
Chris Lattner91702092009-03-12 23:59:55 +0000108static unsigned int
109hexDigitValue(unsigned int c)
110{
111 unsigned int r;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000112
Chris Lattner91702092009-03-12 23:59:55 +0000113 r = c - '0';
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000114 if (r <= 9)
Chris Lattner91702092009-03-12 23:59:55 +0000115 return r;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000116
Chris Lattner91702092009-03-12 23:59:55 +0000117 r = c - 'A';
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000118 if (r <= 5)
Chris Lattner91702092009-03-12 23:59:55 +0000119 return r + 10;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000120
Chris Lattner91702092009-03-12 23:59:55 +0000121 r = c - 'a';
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000122 if (r <= 5)
Chris Lattner91702092009-03-12 23:59:55 +0000123 return r + 10;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000124
Chris Lattner91702092009-03-12 23:59:55 +0000125 return -1U;
126}
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000127
Chris Lattner91702092009-03-12 23:59:55 +0000128static inline void
129assertArithmeticOK(const llvm::fltSemantics &semantics) {
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000130 assert(semantics.arithmeticOK &&
131 "Compile-time arithmetic does not support these semantics");
Chris Lattner91702092009-03-12 23:59:55 +0000132}
Neil Booth06077e72007-10-14 10:29:28 +0000133
Chris Lattner91702092009-03-12 23:59:55 +0000134/* Return the value of a decimal exponent of the form
135 [+-]ddddddd.
Neil Booth4ed401b2007-10-14 10:16:12 +0000136
Chris Lattner91702092009-03-12 23:59:55 +0000137 If the exponent overflows, returns a large exponent with the
138 appropriate sign. */
139static int
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000140readExponent(StringRef::iterator begin, StringRef::iterator end)
Chris Lattner91702092009-03-12 23:59:55 +0000141{
142 bool isNegative;
143 unsigned int absExponent;
144 const unsigned int overlargeExponent = 24000; /* FIXME. */
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000145 StringRef::iterator p = begin;
146
147 assert(p != end && "Exponent has no digits");
Neil Booth4ed401b2007-10-14 10:16:12 +0000148
Chris Lattner91702092009-03-12 23:59:55 +0000149 isNegative = (*p == '-');
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000150 if (*p == '-' || *p == '+') {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000151 p++;
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000152 assert(p != end && "Exponent has no digits");
153 }
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000154
Chris Lattner91702092009-03-12 23:59:55 +0000155 absExponent = decDigitValue(*p++);
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000156 assert(absExponent < 10U && "Invalid character in exponent");
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000157
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000158 for (; p != end; ++p) {
Chris Lattner91702092009-03-12 23:59:55 +0000159 unsigned int value;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000160
Chris Lattner91702092009-03-12 23:59:55 +0000161 value = decDigitValue(*p);
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000162 assert(value < 10U && "Invalid character in exponent");
Chris Lattner91702092009-03-12 23:59:55 +0000163
Chris Lattner91702092009-03-12 23:59:55 +0000164 value += absExponent * 10;
165 if (absExponent >= overlargeExponent) {
166 absExponent = overlargeExponent;
Dale Johannesen370c77c2010-08-19 17:58:35 +0000167 p = end; /* outwit assert below */
Chris Lattner91702092009-03-12 23:59:55 +0000168 break;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000169 }
Chris Lattner91702092009-03-12 23:59:55 +0000170 absExponent = value;
171 }
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000172
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000173 assert(p == end && "Invalid exponent in exponent");
174
Chris Lattner91702092009-03-12 23:59:55 +0000175 if (isNegative)
176 return -(int) absExponent;
177 else
178 return (int) absExponent;
179}
180
181/* This is ugly and needs cleaning up, but I don't immediately see
182 how whilst remaining safe. */
183static int
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000184totalExponent(StringRef::iterator p, StringRef::iterator end,
185 int exponentAdjustment)
Chris Lattner91702092009-03-12 23:59:55 +0000186{
187 int unsignedExponent;
188 bool negative, overflow;
Ted Kremenek3c4408c2011-01-23 17:05:06 +0000189 int exponent = 0;
Chris Lattner91702092009-03-12 23:59:55 +0000190
Erick Tryzelaarda666c82009-08-20 23:30:43 +0000191 assert(p != end && "Exponent has no digits");
192
Chris Lattner91702092009-03-12 23:59:55 +0000193 negative = *p == '-';
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000194 if (*p == '-' || *p == '+') {
Chris Lattner91702092009-03-12 23:59:55 +0000195 p++;
Erick Tryzelaarda666c82009-08-20 23:30:43 +0000196 assert(p != end && "Exponent has no digits");
197 }
Chris Lattner91702092009-03-12 23:59:55 +0000198
199 unsignedExponent = 0;
200 overflow = false;
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000201 for (; p != end; ++p) {
Chris Lattner91702092009-03-12 23:59:55 +0000202 unsigned int value;
203
204 value = decDigitValue(*p);
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000205 assert(value < 10U && "Invalid character in exponent");
Chris Lattner91702092009-03-12 23:59:55 +0000206
Chris Lattner91702092009-03-12 23:59:55 +0000207 unsignedExponent = unsignedExponent * 10 + value;
Richard Smith156d9202012-08-24 00:01:19 +0000208 if (unsignedExponent > 32767) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000209 overflow = true;
Richard Smith156d9202012-08-24 00:01:19 +0000210 break;
211 }
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000212 }
213
Abramo Bagnaraa41d7ae2011-01-06 16:55:14 +0000214 if (exponentAdjustment > 32767 || exponentAdjustment < -32768)
Chris Lattner91702092009-03-12 23:59:55 +0000215 overflow = true;
216
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000217 if (!overflow) {
Chris Lattner91702092009-03-12 23:59:55 +0000218 exponent = unsignedExponent;
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000219 if (negative)
Chris Lattner91702092009-03-12 23:59:55 +0000220 exponent = -exponent;
221 exponent += exponentAdjustment;
Abramo Bagnaraa41d7ae2011-01-06 16:55:14 +0000222 if (exponent > 32767 || exponent < -32768)
Chris Lattner91702092009-03-12 23:59:55 +0000223 overflow = true;
224 }
225
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000226 if (overflow)
Abramo Bagnaraa41d7ae2011-01-06 16:55:14 +0000227 exponent = negative ? -32768: 32767;
Chris Lattner91702092009-03-12 23:59:55 +0000228
229 return exponent;
230}
231
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000232static StringRef::iterator
233skipLeadingZeroesAndAnyDot(StringRef::iterator begin, StringRef::iterator end,
234 StringRef::iterator *dot)
Chris Lattner91702092009-03-12 23:59:55 +0000235{
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000236 StringRef::iterator p = begin;
237 *dot = end;
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000238 while (*p == '0' && p != end)
Chris Lattner91702092009-03-12 23:59:55 +0000239 p++;
240
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000241 if (*p == '.') {
Chris Lattner91702092009-03-12 23:59:55 +0000242 *dot = p++;
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000243
Erick Tryzelaarda666c82009-08-20 23:30:43 +0000244 assert(end - begin != 1 && "Significand has no digits");
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000245
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000246 while (*p == '0' && p != end)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000247 p++;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000248 }
249
Chris Lattner91702092009-03-12 23:59:55 +0000250 return p;
251}
Neil Booth4ed401b2007-10-14 10:16:12 +0000252
Chris Lattner91702092009-03-12 23:59:55 +0000253/* Given a normal decimal floating point number of the form
Neil Booth4ed401b2007-10-14 10:16:12 +0000254
Chris Lattner91702092009-03-12 23:59:55 +0000255 dddd.dddd[eE][+-]ddd
Neil Booth91305512007-10-15 15:00:55 +0000256
Chris Lattner91702092009-03-12 23:59:55 +0000257 where the decimal point and exponent are optional, fill out the
258 structure D. Exponent is appropriate if the significand is
259 treated as an integer, and normalizedExponent if the significand
260 is taken to have the decimal point after a single leading
261 non-zero digit.
Neil Booth4ed401b2007-10-14 10:16:12 +0000262
Chris Lattner91702092009-03-12 23:59:55 +0000263 If the value is zero, V->firstSigDigit points to a non-digit, and
264 the return exponent is zero.
265*/
266struct decimalInfo {
267 const char *firstSigDigit;
268 const char *lastSigDigit;
269 int exponent;
270 int normalizedExponent;
271};
Neil Booth4ed401b2007-10-14 10:16:12 +0000272
Chris Lattner91702092009-03-12 23:59:55 +0000273static void
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000274interpretDecimal(StringRef::iterator begin, StringRef::iterator end,
275 decimalInfo *D)
Chris Lattner91702092009-03-12 23:59:55 +0000276{
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000277 StringRef::iterator dot = end;
278 StringRef::iterator p = skipLeadingZeroesAndAnyDot (begin, end, &dot);
Neil Booth4ed401b2007-10-14 10:16:12 +0000279
Chris Lattner91702092009-03-12 23:59:55 +0000280 D->firstSigDigit = p;
281 D->exponent = 0;
282 D->normalizedExponent = 0;
283
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000284 for (; p != end; ++p) {
Chris Lattner91702092009-03-12 23:59:55 +0000285 if (*p == '.') {
Erick Tryzelaarda666c82009-08-20 23:30:43 +0000286 assert(dot == end && "String contains multiple dots");
Chris Lattner91702092009-03-12 23:59:55 +0000287 dot = p++;
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000288 if (p == end)
289 break;
Neil Booth4ed401b2007-10-14 10:16:12 +0000290 }
Chris Lattner91702092009-03-12 23:59:55 +0000291 if (decDigitValue(*p) >= 10U)
292 break;
Chris Lattner91702092009-03-12 23:59:55 +0000293 }
Neil Booth4ed401b2007-10-14 10:16:12 +0000294
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000295 if (p != end) {
Erick Tryzelaarda666c82009-08-20 23:30:43 +0000296 assert((*p == 'e' || *p == 'E') && "Invalid character in significand");
297 assert(p != begin && "Significand has no digits");
298 assert((dot == end || p - begin != 1) && "Significand has no digits");
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000299
300 /* p points to the first non-digit in the string */
Erick Tryzelaarda666c82009-08-20 23:30:43 +0000301 D->exponent = readExponent(p + 1, end);
Neil Booth4ed401b2007-10-14 10:16:12 +0000302
Chris Lattner91702092009-03-12 23:59:55 +0000303 /* Implied decimal point? */
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000304 if (dot == end)
Chris Lattner91702092009-03-12 23:59:55 +0000305 dot = p;
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000306 }
Neil Booth4ed401b2007-10-14 10:16:12 +0000307
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000308 /* If number is all zeroes accept any exponent. */
309 if (p != D->firstSigDigit) {
Chris Lattner91702092009-03-12 23:59:55 +0000310 /* Drop insignificant trailing zeroes. */
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000311 if (p != begin) {
Neil Booth4ed401b2007-10-14 10:16:12 +0000312 do
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000313 do
314 p--;
315 while (p != begin && *p == '0');
316 while (p != begin && *p == '.');
317 }
Neil Booth4ed401b2007-10-14 10:16:12 +0000318
Chris Lattner91702092009-03-12 23:59:55 +0000319 /* Adjust the exponents for any decimal point. */
320 D->exponent += static_cast<exponent_t>((dot - p) - (dot > p));
321 D->normalizedExponent = (D->exponent +
322 static_cast<exponent_t>((p - D->firstSigDigit)
323 - (dot > D->firstSigDigit && dot < p)));
Neil Booth4ed401b2007-10-14 10:16:12 +0000324 }
325
Chris Lattner91702092009-03-12 23:59:55 +0000326 D->lastSigDigit = p;
327}
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000328
Chris Lattner91702092009-03-12 23:59:55 +0000329/* Return the trailing fraction of a hexadecimal number.
330 DIGITVALUE is the first hex digit of the fraction, P points to
331 the next digit. */
332static lostFraction
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000333trailingHexadecimalFraction(StringRef::iterator p, StringRef::iterator end,
334 unsigned int digitValue)
Chris Lattner91702092009-03-12 23:59:55 +0000335{
336 unsigned int hexDigit;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000337
Chris Lattner91702092009-03-12 23:59:55 +0000338 /* If the first trailing digit isn't 0 or 8 we can work out the
339 fraction immediately. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000340 if (digitValue > 8)
Chris Lattner91702092009-03-12 23:59:55 +0000341 return lfMoreThanHalf;
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000342 else if (digitValue < 8 && digitValue > 0)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000343 return lfLessThanHalf;
Chris Lattner91702092009-03-12 23:59:55 +0000344
345 /* Otherwise we need to find the first non-zero digit. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000346 while (*p == '0')
Chris Lattner91702092009-03-12 23:59:55 +0000347 p++;
348
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000349 assert(p != end && "Invalid trailing hexadecimal fraction!");
350
Chris Lattner91702092009-03-12 23:59:55 +0000351 hexDigit = hexDigitValue(*p);
352
353 /* If we ran off the end it is exactly zero or one-half, otherwise
354 a little more. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000355 if (hexDigit == -1U)
Chris Lattner91702092009-03-12 23:59:55 +0000356 return digitValue == 0 ? lfExactlyZero: lfExactlyHalf;
357 else
358 return digitValue == 0 ? lfLessThanHalf: lfMoreThanHalf;
359}
360
361/* Return the fraction lost were a bignum truncated losing the least
362 significant BITS bits. */
363static lostFraction
364lostFractionThroughTruncation(const integerPart *parts,
365 unsigned int partCount,
366 unsigned int bits)
367{
368 unsigned int lsb;
369
370 lsb = APInt::tcLSB(parts, partCount);
371
372 /* Note this is guaranteed true if bits == 0, or LSB == -1U. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000373 if (bits <= lsb)
Chris Lattner91702092009-03-12 23:59:55 +0000374 return lfExactlyZero;
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000375 if (bits == lsb + 1)
Chris Lattner91702092009-03-12 23:59:55 +0000376 return lfExactlyHalf;
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000377 if (bits <= partCount * integerPartWidth &&
378 APInt::tcExtractBit(parts, bits - 1))
Chris Lattner91702092009-03-12 23:59:55 +0000379 return lfMoreThanHalf;
380
381 return lfLessThanHalf;
382}
383
384/* Shift DST right BITS bits noting lost fraction. */
385static lostFraction
386shiftRight(integerPart *dst, unsigned int parts, unsigned int bits)
387{
388 lostFraction lost_fraction;
389
390 lost_fraction = lostFractionThroughTruncation(dst, parts, bits);
391
392 APInt::tcShiftRight(dst, parts, bits);
393
394 return lost_fraction;
395}
396
397/* Combine the effect of two lost fractions. */
398static lostFraction
399combineLostFractions(lostFraction moreSignificant,
400 lostFraction lessSignificant)
401{
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000402 if (lessSignificant != lfExactlyZero) {
403 if (moreSignificant == lfExactlyZero)
Chris Lattner91702092009-03-12 23:59:55 +0000404 moreSignificant = lfLessThanHalf;
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000405 else if (moreSignificant == lfExactlyHalf)
Chris Lattner91702092009-03-12 23:59:55 +0000406 moreSignificant = lfMoreThanHalf;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000407 }
408
Chris Lattner91702092009-03-12 23:59:55 +0000409 return moreSignificant;
410}
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000411
Chris Lattner91702092009-03-12 23:59:55 +0000412/* The error from the true value, in half-ulps, on multiplying two
413 floating point numbers, which differ from the value they
414 approximate by at most HUE1 and HUE2 half-ulps, is strictly less
415 than the returned value.
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000416
Chris Lattner91702092009-03-12 23:59:55 +0000417 See "How to Read Floating Point Numbers Accurately" by William D
418 Clinger. */
419static unsigned int
420HUerrBound(bool inexactMultiply, unsigned int HUerr1, unsigned int HUerr2)
421{
422 assert(HUerr1 < 2 || HUerr2 < 2 || (HUerr1 + HUerr2 < 8));
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000423
Chris Lattner91702092009-03-12 23:59:55 +0000424 if (HUerr1 + HUerr2 == 0)
425 return inexactMultiply * 2; /* <= inexactMultiply half-ulps. */
426 else
427 return inexactMultiply + 2 * (HUerr1 + HUerr2);
428}
Neil Booth8f1946f2007-10-03 22:26:02 +0000429
Chris Lattner91702092009-03-12 23:59:55 +0000430/* The number of ulps from the boundary (zero, or half if ISNEAREST)
431 when the least significant BITS are truncated. BITS cannot be
432 zero. */
433static integerPart
434ulpsFromBoundary(const integerPart *parts, unsigned int bits, bool isNearest)
435{
436 unsigned int count, partBits;
437 integerPart part, boundary;
Neil Boothd3985922007-10-07 08:51:21 +0000438
Evan Cheng67c90212009-10-27 21:35:42 +0000439 assert(bits != 0);
Neil Booth8f1946f2007-10-03 22:26:02 +0000440
Chris Lattner91702092009-03-12 23:59:55 +0000441 bits--;
442 count = bits / integerPartWidth;
443 partBits = bits % integerPartWidth + 1;
Neil Boothb93d90e2007-10-12 16:02:31 +0000444
Chris Lattner91702092009-03-12 23:59:55 +0000445 part = parts[count] & (~(integerPart) 0 >> (integerPartWidth - partBits));
Neil Boothb93d90e2007-10-12 16:02:31 +0000446
Chris Lattner91702092009-03-12 23:59:55 +0000447 if (isNearest)
448 boundary = (integerPart) 1 << (partBits - 1);
449 else
450 boundary = 0;
451
452 if (count == 0) {
453 if (part - boundary <= boundary - part)
454 return part - boundary;
Neil Boothb93d90e2007-10-12 16:02:31 +0000455 else
Chris Lattner91702092009-03-12 23:59:55 +0000456 return boundary - part;
Neil Boothb93d90e2007-10-12 16:02:31 +0000457 }
458
Chris Lattner91702092009-03-12 23:59:55 +0000459 if (part == boundary) {
460 while (--count)
461 if (parts[count])
462 return ~(integerPart) 0; /* A lot. */
Neil Boothb93d90e2007-10-12 16:02:31 +0000463
Chris Lattner91702092009-03-12 23:59:55 +0000464 return parts[0];
465 } else if (part == boundary - 1) {
466 while (--count)
467 if (~parts[count])
468 return ~(integerPart) 0; /* A lot. */
Neil Boothb93d90e2007-10-12 16:02:31 +0000469
Chris Lattner91702092009-03-12 23:59:55 +0000470 return -parts[0];
471 }
Neil Boothb93d90e2007-10-12 16:02:31 +0000472
Chris Lattner91702092009-03-12 23:59:55 +0000473 return ~(integerPart) 0; /* A lot. */
474}
Neil Boothb93d90e2007-10-12 16:02:31 +0000475
Chris Lattner91702092009-03-12 23:59:55 +0000476/* Place pow(5, power) in DST, and return the number of parts used.
477 DST must be at least one part larger than size of the answer. */
478static unsigned int
479powerOf5(integerPart *dst, unsigned int power)
480{
481 static const integerPart firstEightPowers[] = { 1, 5, 25, 125, 625, 3125,
482 15625, 78125 };
Chris Lattnerb858c0e2009-03-13 00:24:01 +0000483 integerPart pow5s[maxPowerOfFiveParts * 2 + 5];
484 pow5s[0] = 78125 * 5;
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000485
Chris Lattner0bf18692009-03-13 00:03:51 +0000486 unsigned int partsCount[16] = { 1 };
Chris Lattner91702092009-03-12 23:59:55 +0000487 integerPart scratch[maxPowerOfFiveParts], *p1, *p2, *pow5;
488 unsigned int result;
Chris Lattner91702092009-03-12 23:59:55 +0000489 assert(power <= maxExponent);
490
491 p1 = dst;
492 p2 = scratch;
493
494 *p1 = firstEightPowers[power & 7];
495 power >>= 3;
496
497 result = 1;
498 pow5 = pow5s;
499
500 for (unsigned int n = 0; power; power >>= 1, n++) {
501 unsigned int pc;
502
503 pc = partsCount[n];
504
505 /* Calculate pow(5,pow(2,n+3)) if we haven't yet. */
506 if (pc == 0) {
507 pc = partsCount[n - 1];
508 APInt::tcFullMultiply(pow5, pow5 - pc, pow5 - pc, pc, pc);
509 pc *= 2;
510 if (pow5[pc - 1] == 0)
511 pc--;
512 partsCount[n] = pc;
Neil Boothb93d90e2007-10-12 16:02:31 +0000513 }
514
Chris Lattner91702092009-03-12 23:59:55 +0000515 if (power & 1) {
516 integerPart *tmp;
Neil Boothb93d90e2007-10-12 16:02:31 +0000517
Chris Lattner91702092009-03-12 23:59:55 +0000518 APInt::tcFullMultiply(p2, p1, pow5, result, pc);
519 result += pc;
520 if (p2[result - 1] == 0)
521 result--;
Neil Boothb93d90e2007-10-12 16:02:31 +0000522
Chris Lattner91702092009-03-12 23:59:55 +0000523 /* Now result is in p1 with partsCount parts and p2 is scratch
524 space. */
525 tmp = p1, p1 = p2, p2 = tmp;
Neil Boothb93d90e2007-10-12 16:02:31 +0000526 }
527
Chris Lattner91702092009-03-12 23:59:55 +0000528 pow5 += pc;
Neil Boothb93d90e2007-10-12 16:02:31 +0000529 }
530
Chris Lattner91702092009-03-12 23:59:55 +0000531 if (p1 != dst)
532 APInt::tcAssign(dst, p1, result);
Neil Boothb93d90e2007-10-12 16:02:31 +0000533
Chris Lattner91702092009-03-12 23:59:55 +0000534 return result;
535}
Neil Boothb93d90e2007-10-12 16:02:31 +0000536
Chris Lattner91702092009-03-12 23:59:55 +0000537/* Zero at the end to avoid modular arithmetic when adding one; used
538 when rounding up during hexadecimal output. */
539static const char hexDigitsLower[] = "0123456789abcdef0";
540static const char hexDigitsUpper[] = "0123456789ABCDEF0";
541static const char infinityL[] = "infinity";
542static const char infinityU[] = "INFINITY";
543static const char NaNL[] = "nan";
544static const char NaNU[] = "NAN";
Neil Boothb93d90e2007-10-12 16:02:31 +0000545
Chris Lattner91702092009-03-12 23:59:55 +0000546/* Write out an integerPart in hexadecimal, starting with the most
547 significant nibble. Write out exactly COUNT hexdigits, return
548 COUNT. */
549static unsigned int
550partAsHex (char *dst, integerPart part, unsigned int count,
551 const char *hexDigitChars)
552{
553 unsigned int result = count;
Neil Boothb93d90e2007-10-12 16:02:31 +0000554
Evan Cheng67c90212009-10-27 21:35:42 +0000555 assert(count != 0 && count <= integerPartWidth / 4);
Neil Boothb93d90e2007-10-12 16:02:31 +0000556
Chris Lattner91702092009-03-12 23:59:55 +0000557 part >>= (integerPartWidth - 4 * count);
558 while (count--) {
559 dst[count] = hexDigitChars[part & 0xf];
560 part >>= 4;
Neil Boothb93d90e2007-10-12 16:02:31 +0000561 }
562
Chris Lattner91702092009-03-12 23:59:55 +0000563 return result;
564}
Neil Booth8f1946f2007-10-03 22:26:02 +0000565
Chris Lattner91702092009-03-12 23:59:55 +0000566/* Write out an unsigned decimal integer. */
567static char *
568writeUnsignedDecimal (char *dst, unsigned int n)
569{
570 char buff[40], *p;
Neil Booth8f1946f2007-10-03 22:26:02 +0000571
Chris Lattner91702092009-03-12 23:59:55 +0000572 p = buff;
573 do
574 *p++ = '0' + n % 10;
575 while (n /= 10);
Neil Booth8f1946f2007-10-03 22:26:02 +0000576
Chris Lattner91702092009-03-12 23:59:55 +0000577 do
578 *dst++ = *--p;
579 while (p != buff);
Neil Booth8f1946f2007-10-03 22:26:02 +0000580
Chris Lattner91702092009-03-12 23:59:55 +0000581 return dst;
582}
Neil Booth8f1946f2007-10-03 22:26:02 +0000583
Chris Lattner91702092009-03-12 23:59:55 +0000584/* Write out a signed decimal integer. */
585static char *
586writeSignedDecimal (char *dst, int value)
587{
588 if (value < 0) {
589 *dst++ = '-';
590 dst = writeUnsignedDecimal(dst, -(unsigned) value);
591 } else
592 dst = writeUnsignedDecimal(dst, value);
Neil Booth8f1946f2007-10-03 22:26:02 +0000593
Chris Lattner91702092009-03-12 23:59:55 +0000594 return dst;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000595}
596
597/* Constructors. */
598void
599APFloat::initialize(const fltSemantics *ourSemantics)
600{
601 unsigned int count;
602
603 semantics = ourSemantics;
604 count = partCount();
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000605 if (count > 1)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000606 significand.parts = new integerPart[count];
607}
608
609void
610APFloat::freeSignificand()
611{
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000612 if (partCount() > 1)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000613 delete [] significand.parts;
614}
615
616void
617APFloat::assign(const APFloat &rhs)
618{
619 assert(semantics == rhs.semantics);
620
621 sign = rhs.sign;
622 category = rhs.category;
623 exponent = rhs.exponent;
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000624 if (category == fcNormal || category == fcNaN)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000625 copySignificand(rhs);
626}
627
628void
629APFloat::copySignificand(const APFloat &rhs)
630{
Dale Johannesen3cf889f2007-08-31 04:03:46 +0000631 assert(category == fcNormal || category == fcNaN);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000632 assert(rhs.partCount() >= partCount());
633
634 APInt::tcAssign(significandParts(), rhs.significandParts(),
Neil Booth9acbf5a2007-09-26 21:33:42 +0000635 partCount());
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000636}
637
Neil Booth5fe658b2007-10-14 10:39:51 +0000638/* Make this number a NaN, with an arbitrary but deterministic value
Dale Johannesen1f864982009-01-21 20:32:55 +0000639 for the significand. If double or longer, this is a signalling NaN,
Mike Stump799bf582009-05-30 03:49:43 +0000640 which may not be ideal. If float, this is QNaN(0). */
John McCalldcb9a7a2010-02-28 02:51:25 +0000641void APFloat::makeNaN(bool SNaN, bool Negative, const APInt *fill)
Neil Booth5fe658b2007-10-14 10:39:51 +0000642{
643 category = fcNaN;
John McCalldcb9a7a2010-02-28 02:51:25 +0000644 sign = Negative;
645
John McCallc12b1332010-02-28 12:49:50 +0000646 integerPart *significand = significandParts();
647 unsigned numParts = partCount();
648
John McCalldcb9a7a2010-02-28 02:51:25 +0000649 // Set the significand bits to the fill.
John McCallc12b1332010-02-28 12:49:50 +0000650 if (!fill || fill->getNumWords() < numParts)
651 APInt::tcSet(significand, 0, numParts);
652 if (fill) {
John McCallc6dbe302010-03-01 18:38:45 +0000653 APInt::tcAssign(significand, fill->getRawData(),
654 std::min(fill->getNumWords(), numParts));
John McCallc12b1332010-02-28 12:49:50 +0000655
656 // Zero out the excess bits of the significand.
657 unsigned bitsToPreserve = semantics->precision - 1;
658 unsigned part = bitsToPreserve / 64;
659 bitsToPreserve %= 64;
660 significand[part] &= ((1ULL << bitsToPreserve) - 1);
661 for (part++; part != numParts; ++part)
662 significand[part] = 0;
663 }
664
665 unsigned QNaNBit = semantics->precision - 2;
John McCalldcb9a7a2010-02-28 02:51:25 +0000666
667 if (SNaN) {
668 // We always have to clear the QNaN bit to make it an SNaN.
John McCallc12b1332010-02-28 12:49:50 +0000669 APInt::tcClearBit(significand, QNaNBit);
John McCalldcb9a7a2010-02-28 02:51:25 +0000670
671 // If there are no bits set in the payload, we have to set
672 // *something* to make it a NaN instead of an infinity;
673 // conventionally, this is the next bit down from the QNaN bit.
John McCallc12b1332010-02-28 12:49:50 +0000674 if (APInt::tcIsZero(significand, numParts))
675 APInt::tcSetBit(significand, QNaNBit - 1);
John McCalldcb9a7a2010-02-28 02:51:25 +0000676 } else {
677 // We always have to set the QNaN bit to make it a QNaN.
John McCallc12b1332010-02-28 12:49:50 +0000678 APInt::tcSetBit(significand, QNaNBit);
John McCalldcb9a7a2010-02-28 02:51:25 +0000679 }
John McCallc12b1332010-02-28 12:49:50 +0000680
681 // For x87 extended precision, we want to make a NaN, not a
682 // pseudo-NaN. Maybe we should expose the ability to make
683 // pseudo-NaNs?
684 if (semantics == &APFloat::x87DoubleExtended)
685 APInt::tcSetBit(significand, QNaNBit + 1);
John McCalldcb9a7a2010-02-28 02:51:25 +0000686}
687
688APFloat APFloat::makeNaN(const fltSemantics &Sem, bool SNaN, bool Negative,
689 const APInt *fill) {
690 APFloat value(Sem, uninitialized);
691 value.makeNaN(SNaN, Negative, fill);
692 return value;
Neil Booth5fe658b2007-10-14 10:39:51 +0000693}
694
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000695APFloat &
696APFloat::operator=(const APFloat &rhs)
697{
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000698 if (this != &rhs) {
699 if (semantics != rhs.semantics) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000700 freeSignificand();
701 initialize(rhs.semantics);
702 }
703 assign(rhs);
704 }
705
706 return *this;
707}
708
Dale Johannesena719a602007-08-24 00:56:33 +0000709bool
Dale Johannesenbdea32d2007-08-24 22:09:56 +0000710APFloat::bitwiseIsEqual(const APFloat &rhs) const {
Dale Johannesena719a602007-08-24 00:56:33 +0000711 if (this == &rhs)
712 return true;
713 if (semantics != rhs.semantics ||
Dale Johannesen3cf889f2007-08-31 04:03:46 +0000714 category != rhs.category ||
715 sign != rhs.sign)
Dale Johannesena719a602007-08-24 00:56:33 +0000716 return false;
Dale Johannesen3cf889f2007-08-31 04:03:46 +0000717 if (category==fcZero || category==fcInfinity)
Dale Johannesena719a602007-08-24 00:56:33 +0000718 return true;
Dale Johannesen3cf889f2007-08-31 04:03:46 +0000719 else if (category==fcNormal && exponent!=rhs.exponent)
720 return false;
Dale Johannesena719a602007-08-24 00:56:33 +0000721 else {
Dale Johannesena719a602007-08-24 00:56:33 +0000722 int i= partCount();
723 const integerPart* p=significandParts();
724 const integerPart* q=rhs.significandParts();
725 for (; i>0; i--, p++, q++) {
726 if (*p != *q)
727 return false;
728 }
729 return true;
730 }
731}
732
Ulrich Weigande1d62f92012-10-29 18:17:42 +0000733APFloat::APFloat(const fltSemantics &ourSemantics, integerPart value) {
Neil Booth06077e72007-10-14 10:29:28 +0000734 assertArithmeticOK(ourSemantics);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000735 initialize(&ourSemantics);
736 sign = 0;
737 zeroSignificand();
738 exponent = ourSemantics.precision - 1;
739 significandParts()[0] = value;
740 normalize(rmNearestTiesToEven, lfExactlyZero);
741}
742
Ulrich Weigande1d62f92012-10-29 18:17:42 +0000743APFloat::APFloat(const fltSemantics &ourSemantics) {
Chris Lattnerac6271e2009-09-17 01:08:43 +0000744 assertArithmeticOK(ourSemantics);
745 initialize(&ourSemantics);
746 category = fcZero;
747 sign = false;
748}
749
Ulrich Weigande1d62f92012-10-29 18:17:42 +0000750APFloat::APFloat(const fltSemantics &ourSemantics, uninitializedTag tag) {
John McCalldcb9a7a2010-02-28 02:51:25 +0000751 assertArithmeticOK(ourSemantics);
752 // Allocates storage if necessary but does not initialize it.
753 initialize(&ourSemantics);
754}
Chris Lattnerac6271e2009-09-17 01:08:43 +0000755
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000756APFloat::APFloat(const fltSemantics &ourSemantics,
Ulrich Weigande1d62f92012-10-29 18:17:42 +0000757 fltCategory ourCategory, bool negative) {
Neil Booth06077e72007-10-14 10:29:28 +0000758 assertArithmeticOK(ourSemantics);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000759 initialize(&ourSemantics);
760 category = ourCategory;
761 sign = negative;
Mike Stump799bf582009-05-30 03:49:43 +0000762 if (category == fcNormal)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000763 category = fcZero;
Neil Booth5fe658b2007-10-14 10:39:51 +0000764 else if (ourCategory == fcNaN)
John McCalldcb9a7a2010-02-28 02:51:25 +0000765 makeNaN();
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000766}
767
Ulrich Weigande1d62f92012-10-29 18:17:42 +0000768APFloat::APFloat(const fltSemantics &ourSemantics, StringRef text) {
Neil Booth06077e72007-10-14 10:29:28 +0000769 assertArithmeticOK(ourSemantics);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000770 initialize(&ourSemantics);
771 convertFromString(text, rmNearestTiesToEven);
772}
773
Ulrich Weigande1d62f92012-10-29 18:17:42 +0000774APFloat::APFloat(const APFloat &rhs) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000775 initialize(rhs.semantics);
776 assign(rhs);
777}
778
779APFloat::~APFloat()
780{
781 freeSignificand();
782}
783
Ted Kremenek6f30a072008-02-11 17:24:50 +0000784// Profile - This method 'profiles' an APFloat for use with FoldingSet.
785void APFloat::Profile(FoldingSetNodeID& ID) const {
Dale Johannesen54306fe2008-10-09 18:53:47 +0000786 ID.Add(bitcastToAPInt());
Ted Kremenek6f30a072008-02-11 17:24:50 +0000787}
788
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000789unsigned int
790APFloat::partCount() const
791{
Dale Johannesen146a0ea2007-09-20 23:47:58 +0000792 return partCountForBits(semantics->precision + 1);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000793}
794
795unsigned int
796APFloat::semanticsPrecision(const fltSemantics &semantics)
797{
798 return semantics.precision;
799}
800
801const integerPart *
802APFloat::significandParts() const
803{
804 return const_cast<APFloat *>(this)->significandParts();
805}
806
807integerPart *
808APFloat::significandParts()
809{
Dale Johannesen3cf889f2007-08-31 04:03:46 +0000810 assert(category == fcNormal || category == fcNaN);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000811
Evan Cheng67c90212009-10-27 21:35:42 +0000812 if (partCount() > 1)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000813 return significand.parts;
814 else
815 return &significand.part;
816}
817
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000818void
819APFloat::zeroSignificand()
820{
821 category = fcNormal;
822 APInt::tcSet(significandParts(), 0, partCount());
823}
824
825/* Increment an fcNormal floating point number's significand. */
826void
827APFloat::incrementSignificand()
828{
829 integerPart carry;
830
831 carry = APInt::tcIncrement(significandParts(), partCount());
832
833 /* Our callers should never cause us to overflow. */
834 assert(carry == 0);
Duncan Sandsa41634e2011-08-12 14:54:45 +0000835 (void)carry;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000836}
837
838/* Add the significand of the RHS. Returns the carry flag. */
839integerPart
840APFloat::addSignificand(const APFloat &rhs)
841{
842 integerPart *parts;
843
844 parts = significandParts();
845
846 assert(semantics == rhs.semantics);
847 assert(exponent == rhs.exponent);
848
849 return APInt::tcAdd(parts, rhs.significandParts(), 0, partCount());
850}
851
852/* Subtract the significand of the RHS with a borrow flag. Returns
853 the borrow flag. */
854integerPart
855APFloat::subtractSignificand(const APFloat &rhs, integerPart borrow)
856{
857 integerPart *parts;
858
859 parts = significandParts();
860
861 assert(semantics == rhs.semantics);
862 assert(exponent == rhs.exponent);
863
864 return APInt::tcSubtract(parts, rhs.significandParts(), borrow,
Neil Booth9acbf5a2007-09-26 21:33:42 +0000865 partCount());
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000866}
867
868/* Multiply the significand of the RHS. If ADDEND is non-NULL, add it
869 on to the full-precision result of the multiplication. Returns the
870 lost fraction. */
871lostFraction
872APFloat::multiplySignificand(const APFloat &rhs, const APFloat *addend)
873{
Neil Booth9acbf5a2007-09-26 21:33:42 +0000874 unsigned int omsb; // One, not zero, based MSB.
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000875 unsigned int partsCount, newPartsCount, precision;
876 integerPart *lhsSignificand;
877 integerPart scratch[4];
878 integerPart *fullSignificand;
879 lostFraction lost_fraction;
Dale Johannesen4f0bd682008-10-09 23:00:39 +0000880 bool ignored;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000881
882 assert(semantics == rhs.semantics);
883
884 precision = semantics->precision;
885 newPartsCount = partCountForBits(precision * 2);
886
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000887 if (newPartsCount > 4)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000888 fullSignificand = new integerPart[newPartsCount];
889 else
890 fullSignificand = scratch;
891
892 lhsSignificand = significandParts();
893 partsCount = partCount();
894
895 APInt::tcFullMultiply(fullSignificand, lhsSignificand,
Neil Booth0ea72a92007-10-06 00:24:48 +0000896 rhs.significandParts(), partsCount, partsCount);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000897
898 lost_fraction = lfExactlyZero;
899 omsb = APInt::tcMSB(fullSignificand, newPartsCount) + 1;
900 exponent += rhs.exponent;
901
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000902 if (addend) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000903 Significand savedSignificand = significand;
904 const fltSemantics *savedSemantics = semantics;
905 fltSemantics extendedSemantics;
906 opStatus status;
907 unsigned int extendedPrecision;
908
909 /* Normalize our MSB. */
910 extendedPrecision = precision + precision - 1;
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000911 if (omsb != extendedPrecision) {
912 APInt::tcShiftLeft(fullSignificand, newPartsCount,
913 extendedPrecision - omsb);
914 exponent -= extendedPrecision - omsb;
915 }
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000916
917 /* Create new semantics. */
918 extendedSemantics = *semantics;
919 extendedSemantics.precision = extendedPrecision;
920
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000921 if (newPartsCount == 1)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000922 significand.part = fullSignificand[0];
923 else
924 significand.parts = fullSignificand;
925 semantics = &extendedSemantics;
926
927 APFloat extendedAddend(*addend);
Dale Johannesen4f0bd682008-10-09 23:00:39 +0000928 status = extendedAddend.convert(extendedSemantics, rmTowardZero, &ignored);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000929 assert(status == opOK);
Duncan Sandsa41634e2011-08-12 14:54:45 +0000930 (void)status;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000931 lost_fraction = addOrSubtractSignificand(extendedAddend, false);
932
933 /* Restore our state. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000934 if (newPartsCount == 1)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000935 fullSignificand[0] = significand.part;
936 significand = savedSignificand;
937 semantics = savedSemantics;
938
939 omsb = APInt::tcMSB(fullSignificand, newPartsCount) + 1;
940 }
941
942 exponent -= (precision - 1);
943
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000944 if (omsb > precision) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000945 unsigned int bits, significantParts;
946 lostFraction lf;
947
948 bits = omsb - precision;
949 significantParts = partCountForBits(omsb);
950 lf = shiftRight(fullSignificand, significantParts, bits);
951 lost_fraction = combineLostFractions(lf, lost_fraction);
952 exponent += bits;
953 }
954
955 APInt::tcAssign(lhsSignificand, fullSignificand, partsCount);
956
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000957 if (newPartsCount > 4)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000958 delete [] fullSignificand;
959
960 return lost_fraction;
961}
962
963/* Multiply the significands of LHS and RHS to DST. */
964lostFraction
965APFloat::divideSignificand(const APFloat &rhs)
966{
967 unsigned int bit, i, partsCount;
968 const integerPart *rhsSignificand;
969 integerPart *lhsSignificand, *dividend, *divisor;
970 integerPart scratch[4];
971 lostFraction lost_fraction;
972
973 assert(semantics == rhs.semantics);
974
975 lhsSignificand = significandParts();
976 rhsSignificand = rhs.significandParts();
977 partsCount = partCount();
978
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000979 if (partsCount > 2)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000980 dividend = new integerPart[partsCount * 2];
981 else
982 dividend = scratch;
983
984 divisor = dividend + partsCount;
985
986 /* Copy the dividend and divisor as they will be modified in-place. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000987 for (i = 0; i < partsCount; i++) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000988 dividend[i] = lhsSignificand[i];
989 divisor[i] = rhsSignificand[i];
990 lhsSignificand[i] = 0;
991 }
992
993 exponent -= rhs.exponent;
994
995 unsigned int precision = semantics->precision;
996
997 /* Normalize the divisor. */
998 bit = precision - APInt::tcMSB(divisor, partsCount) - 1;
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000999 if (bit) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001000 exponent += bit;
1001 APInt::tcShiftLeft(divisor, partsCount, bit);
1002 }
1003
1004 /* Normalize the dividend. */
1005 bit = precision - APInt::tcMSB(dividend, partsCount) - 1;
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001006 if (bit) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001007 exponent -= bit;
1008 APInt::tcShiftLeft(dividend, partsCount, bit);
1009 }
1010
Neil Boothb93d90e2007-10-12 16:02:31 +00001011 /* Ensure the dividend >= divisor initially for the loop below.
1012 Incidentally, this means that the division loop below is
1013 guaranteed to set the integer bit to one. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001014 if (APInt::tcCompare(dividend, divisor, partsCount) < 0) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001015 exponent--;
1016 APInt::tcShiftLeft(dividend, partsCount, 1);
1017 assert(APInt::tcCompare(dividend, divisor, partsCount) >= 0);
1018 }
1019
1020 /* Long division. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001021 for (bit = precision; bit; bit -= 1) {
1022 if (APInt::tcCompare(dividend, divisor, partsCount) >= 0) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001023 APInt::tcSubtract(dividend, divisor, 0, partsCount);
1024 APInt::tcSetBit(lhsSignificand, bit - 1);
1025 }
1026
1027 APInt::tcShiftLeft(dividend, partsCount, 1);
1028 }
1029
1030 /* Figure out the lost fraction. */
1031 int cmp = APInt::tcCompare(dividend, divisor, partsCount);
1032
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001033 if (cmp > 0)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001034 lost_fraction = lfMoreThanHalf;
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001035 else if (cmp == 0)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001036 lost_fraction = lfExactlyHalf;
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001037 else if (APInt::tcIsZero(dividend, partsCount))
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001038 lost_fraction = lfExactlyZero;
1039 else
1040 lost_fraction = lfLessThanHalf;
1041
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001042 if (partsCount > 2)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001043 delete [] dividend;
1044
1045 return lost_fraction;
1046}
1047
1048unsigned int
1049APFloat::significandMSB() const
1050{
1051 return APInt::tcMSB(significandParts(), partCount());
1052}
1053
1054unsigned int
1055APFloat::significandLSB() const
1056{
1057 return APInt::tcLSB(significandParts(), partCount());
1058}
1059
1060/* Note that a zero result is NOT normalized to fcZero. */
1061lostFraction
1062APFloat::shiftSignificandRight(unsigned int bits)
1063{
1064 /* Our exponent should not overflow. */
1065 assert((exponent_t) (exponent + bits) >= exponent);
1066
1067 exponent += bits;
1068
1069 return shiftRight(significandParts(), partCount(), bits);
1070}
1071
1072/* Shift the significand left BITS bits, subtract BITS from its exponent. */
1073void
1074APFloat::shiftSignificandLeft(unsigned int bits)
1075{
1076 assert(bits < semantics->precision);
1077
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001078 if (bits) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001079 unsigned int partsCount = partCount();
1080
1081 APInt::tcShiftLeft(significandParts(), partsCount, bits);
1082 exponent -= bits;
1083
1084 assert(!APInt::tcIsZero(significandParts(), partsCount));
1085 }
1086}
1087
1088APFloat::cmpResult
1089APFloat::compareAbsoluteValue(const APFloat &rhs) const
1090{
1091 int compare;
1092
1093 assert(semantics == rhs.semantics);
1094 assert(category == fcNormal);
1095 assert(rhs.category == fcNormal);
1096
1097 compare = exponent - rhs.exponent;
1098
1099 /* If exponents are equal, do an unsigned bignum comparison of the
1100 significands. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001101 if (compare == 0)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001102 compare = APInt::tcCompare(significandParts(), rhs.significandParts(),
Neil Booth9acbf5a2007-09-26 21:33:42 +00001103 partCount());
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001104
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001105 if (compare > 0)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001106 return cmpGreaterThan;
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001107 else if (compare < 0)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001108 return cmpLessThan;
1109 else
1110 return cmpEqual;
1111}
1112
1113/* Handle overflow. Sign is preserved. We either become infinity or
1114 the largest finite number. */
1115APFloat::opStatus
1116APFloat::handleOverflow(roundingMode rounding_mode)
1117{
1118 /* Infinity? */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001119 if (rounding_mode == rmNearestTiesToEven ||
1120 rounding_mode == rmNearestTiesToAway ||
1121 (rounding_mode == rmTowardPositive && !sign) ||
1122 (rounding_mode == rmTowardNegative && sign)) {
1123 category = fcInfinity;
1124 return (opStatus) (opOverflow | opInexact);
1125 }
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001126
1127 /* Otherwise we become the largest finite number. */
1128 category = fcNormal;
1129 exponent = semantics->maxExponent;
1130 APInt::tcSetLeastSignificantBits(significandParts(), partCount(),
Neil Booth9acbf5a2007-09-26 21:33:42 +00001131 semantics->precision);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001132
1133 return opInexact;
1134}
1135
Neil Booth1ca1f802007-10-03 15:16:41 +00001136/* Returns TRUE if, when truncating the current number, with BIT the
1137 new LSB, with the given lost fraction and rounding mode, the result
1138 would need to be rounded away from zero (i.e., by increasing the
1139 signficand). This routine must work for fcZero of both signs, and
1140 fcNormal numbers. */
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001141bool
1142APFloat::roundAwayFromZero(roundingMode rounding_mode,
Neil Booth1ca1f802007-10-03 15:16:41 +00001143 lostFraction lost_fraction,
1144 unsigned int bit) const
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001145{
Dale Johannesen3cf889f2007-08-31 04:03:46 +00001146 /* NaNs and infinities should not have lost fractions. */
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001147 assert(category == fcNormal || category == fcZero);
1148
Neil Booth1ca1f802007-10-03 15:16:41 +00001149 /* Current callers never pass this so we don't handle it. */
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001150 assert(lost_fraction != lfExactlyZero);
1151
Mike Stump889285d2009-05-13 23:23:20 +00001152 switch (rounding_mode) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001153 case rmNearestTiesToAway:
1154 return lost_fraction == lfExactlyHalf || lost_fraction == lfMoreThanHalf;
1155
1156 case rmNearestTiesToEven:
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001157 if (lost_fraction == lfMoreThanHalf)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001158 return true;
1159
1160 /* Our zeroes don't have a significand to test. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001161 if (lost_fraction == lfExactlyHalf && category != fcZero)
Neil Booth1ca1f802007-10-03 15:16:41 +00001162 return APInt::tcExtractBit(significandParts(), bit);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001163
1164 return false;
1165
1166 case rmTowardZero:
1167 return false;
1168
1169 case rmTowardPositive:
1170 return sign == false;
1171
1172 case rmTowardNegative:
1173 return sign == true;
1174 }
Chandler Carruthf3e85022012-01-10 18:08:01 +00001175 llvm_unreachable("Invalid rounding mode found");
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001176}
1177
1178APFloat::opStatus
1179APFloat::normalize(roundingMode rounding_mode,
Neil Booth9acbf5a2007-09-26 21:33:42 +00001180 lostFraction lost_fraction)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001181{
Neil Booth9acbf5a2007-09-26 21:33:42 +00001182 unsigned int omsb; /* One, not zero, based MSB. */
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001183 int exponentChange;
1184
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001185 if (category != fcNormal)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001186 return opOK;
1187
1188 /* Before rounding normalize the exponent of fcNormal numbers. */
1189 omsb = significandMSB() + 1;
1190
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001191 if (omsb) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001192 /* OMSB is numbered from 1. We want to place it in the integer
Nick Lewyckyf66daac2011-10-03 21:30:08 +00001193 bit numbered PRECISION if possible, with a compensating change in
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001194 the exponent. */
1195 exponentChange = omsb - semantics->precision;
1196
1197 /* If the resulting exponent is too high, overflow according to
1198 the rounding mode. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001199 if (exponent + exponentChange > semantics->maxExponent)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001200 return handleOverflow(rounding_mode);
1201
1202 /* Subnormal numbers have exponent minExponent, and their MSB
1203 is forced based on that. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001204 if (exponent + exponentChange < semantics->minExponent)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001205 exponentChange = semantics->minExponent - exponent;
1206
1207 /* Shifting left is easy as we don't lose precision. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001208 if (exponentChange < 0) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001209 assert(lost_fraction == lfExactlyZero);
1210
1211 shiftSignificandLeft(-exponentChange);
1212
1213 return opOK;
1214 }
1215
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001216 if (exponentChange > 0) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001217 lostFraction lf;
1218
1219 /* Shift right and capture any new lost fraction. */
1220 lf = shiftSignificandRight(exponentChange);
1221
1222 lost_fraction = combineLostFractions(lf, lost_fraction);
1223
1224 /* Keep OMSB up-to-date. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001225 if (omsb > (unsigned) exponentChange)
Neil Boothb93d90e2007-10-12 16:02:31 +00001226 omsb -= exponentChange;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001227 else
Neil Booth9acbf5a2007-09-26 21:33:42 +00001228 omsb = 0;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001229 }
1230 }
1231
1232 /* Now round the number according to rounding_mode given the lost
1233 fraction. */
1234
1235 /* As specified in IEEE 754, since we do not trap we do not report
1236 underflow for exact results. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001237 if (lost_fraction == lfExactlyZero) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001238 /* Canonicalize zeroes. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001239 if (omsb == 0)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001240 category = fcZero;
1241
1242 return opOK;
1243 }
1244
1245 /* Increment the significand if we're rounding away from zero. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001246 if (roundAwayFromZero(rounding_mode, lost_fraction, 0)) {
1247 if (omsb == 0)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001248 exponent = semantics->minExponent;
1249
1250 incrementSignificand();
1251 omsb = significandMSB() + 1;
1252
1253 /* Did the significand increment overflow? */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001254 if (omsb == (unsigned) semantics->precision + 1) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001255 /* Renormalize by incrementing the exponent and shifting our
Neil Booth9acbf5a2007-09-26 21:33:42 +00001256 significand right one. However if we already have the
1257 maximum exponent we overflow to infinity. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001258 if (exponent == semantics->maxExponent) {
Neil Booth9acbf5a2007-09-26 21:33:42 +00001259 category = fcInfinity;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001260
Neil Booth9acbf5a2007-09-26 21:33:42 +00001261 return (opStatus) (opOverflow | opInexact);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001262 }
1263
1264 shiftSignificandRight(1);
1265
1266 return opInexact;
1267 }
1268 }
1269
1270 /* The normal case - we were and are not denormal, and any
1271 significand increment above didn't overflow. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001272 if (omsb == semantics->precision)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001273 return opInexact;
1274
1275 /* We have a non-zero denormal. */
1276 assert(omsb < semantics->precision);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001277
1278 /* Canonicalize zeroes. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001279 if (omsb == 0)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001280 category = fcZero;
1281
1282 /* The fcZero case is a denormal that underflowed to zero. */
1283 return (opStatus) (opUnderflow | opInexact);
1284}
1285
1286APFloat::opStatus
1287APFloat::addOrSubtractSpecials(const APFloat &rhs, bool subtract)
1288{
Mike Stump889285d2009-05-13 23:23:20 +00001289 switch (convolve(category, rhs.category)) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001290 default:
Torok Edwinfbcc6632009-07-14 16:55:14 +00001291 llvm_unreachable(0);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001292
Dale Johannesen3cf889f2007-08-31 04:03:46 +00001293 case convolve(fcNaN, fcZero):
1294 case convolve(fcNaN, fcNormal):
1295 case convolve(fcNaN, fcInfinity):
1296 case convolve(fcNaN, fcNaN):
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001297 case convolve(fcNormal, fcZero):
1298 case convolve(fcInfinity, fcNormal):
1299 case convolve(fcInfinity, fcZero):
1300 return opOK;
1301
Dale Johannesen3cf889f2007-08-31 04:03:46 +00001302 case convolve(fcZero, fcNaN):
1303 case convolve(fcNormal, fcNaN):
1304 case convolve(fcInfinity, fcNaN):
1305 category = fcNaN;
1306 copySignificand(rhs);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001307 return opOK;
1308
1309 case convolve(fcNormal, fcInfinity):
1310 case convolve(fcZero, fcInfinity):
1311 category = fcInfinity;
1312 sign = rhs.sign ^ subtract;
1313 return opOK;
1314
1315 case convolve(fcZero, fcNormal):
1316 assign(rhs);
1317 sign = rhs.sign ^ subtract;
1318 return opOK;
1319
1320 case convolve(fcZero, fcZero):
1321 /* Sign depends on rounding mode; handled by caller. */
1322 return opOK;
1323
1324 case convolve(fcInfinity, fcInfinity):
1325 /* Differently signed infinities can only be validly
1326 subtracted. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001327 if (((sign ^ rhs.sign)!=0) != subtract) {
Neil Booth5fe658b2007-10-14 10:39:51 +00001328 makeNaN();
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001329 return opInvalidOp;
1330 }
1331
1332 return opOK;
1333
1334 case convolve(fcNormal, fcNormal):
1335 return opDivByZero;
1336 }
1337}
1338
1339/* Add or subtract two normal numbers. */
1340lostFraction
1341APFloat::addOrSubtractSignificand(const APFloat &rhs, bool subtract)
1342{
1343 integerPart carry;
1344 lostFraction lost_fraction;
1345 int bits;
1346
1347 /* Determine if the operation on the absolute values is effectively
1348 an addition or subtraction. */
Hartmut Kaiserfc69d322007-10-25 23:15:31 +00001349 subtract ^= (sign ^ rhs.sign) ? true : false;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001350
1351 /* Are we bigger exponent-wise than the RHS? */
1352 bits = exponent - rhs.exponent;
1353
1354 /* Subtraction is more subtle than one might naively expect. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001355 if (subtract) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001356 APFloat temp_rhs(rhs);
1357 bool reverse;
1358
Chris Lattner3da18eb2007-08-24 03:02:34 +00001359 if (bits == 0) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001360 reverse = compareAbsoluteValue(temp_rhs) == cmpLessThan;
1361 lost_fraction = lfExactlyZero;
Chris Lattner3da18eb2007-08-24 03:02:34 +00001362 } else if (bits > 0) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001363 lost_fraction = temp_rhs.shiftSignificandRight(bits - 1);
1364 shiftSignificandLeft(1);
1365 reverse = false;
Chris Lattner3da18eb2007-08-24 03:02:34 +00001366 } else {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001367 lost_fraction = shiftSignificandRight(-bits - 1);
1368 temp_rhs.shiftSignificandLeft(1);
1369 reverse = true;
1370 }
1371
Chris Lattner3da18eb2007-08-24 03:02:34 +00001372 if (reverse) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001373 carry = temp_rhs.subtractSignificand
Neil Booth9acbf5a2007-09-26 21:33:42 +00001374 (*this, lost_fraction != lfExactlyZero);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001375 copySignificand(temp_rhs);
1376 sign = !sign;
1377 } else {
1378 carry = subtractSignificand
Neil Booth9acbf5a2007-09-26 21:33:42 +00001379 (temp_rhs, lost_fraction != lfExactlyZero);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001380 }
1381
1382 /* Invert the lost fraction - it was on the RHS and
1383 subtracted. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001384 if (lost_fraction == lfLessThanHalf)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001385 lost_fraction = lfMoreThanHalf;
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001386 else if (lost_fraction == lfMoreThanHalf)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001387 lost_fraction = lfLessThanHalf;
1388
1389 /* The code above is intended to ensure that no borrow is
1390 necessary. */
1391 assert(!carry);
Duncan Sandsa41634e2011-08-12 14:54:45 +00001392 (void)carry;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001393 } else {
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001394 if (bits > 0) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001395 APFloat temp_rhs(rhs);
1396
1397 lost_fraction = temp_rhs.shiftSignificandRight(bits);
1398 carry = addSignificand(temp_rhs);
1399 } else {
1400 lost_fraction = shiftSignificandRight(-bits);
1401 carry = addSignificand(rhs);
1402 }
1403
1404 /* We have a guard bit; generating a carry cannot happen. */
1405 assert(!carry);
Duncan Sandsa41634e2011-08-12 14:54:45 +00001406 (void)carry;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001407 }
1408
1409 return lost_fraction;
1410}
1411
1412APFloat::opStatus
1413APFloat::multiplySpecials(const APFloat &rhs)
1414{
Mike Stump889285d2009-05-13 23:23:20 +00001415 switch (convolve(category, rhs.category)) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001416 default:
Torok Edwinfbcc6632009-07-14 16:55:14 +00001417 llvm_unreachable(0);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001418
Dale Johannesen3cf889f2007-08-31 04:03:46 +00001419 case convolve(fcNaN, fcZero):
1420 case convolve(fcNaN, fcNormal):
1421 case convolve(fcNaN, fcInfinity):
1422 case convolve(fcNaN, fcNaN):
1423 return opOK;
1424
1425 case convolve(fcZero, fcNaN):
1426 case convolve(fcNormal, fcNaN):
1427 case convolve(fcInfinity, fcNaN):
1428 category = fcNaN;
1429 copySignificand(rhs);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001430 return opOK;
1431
1432 case convolve(fcNormal, fcInfinity):
1433 case convolve(fcInfinity, fcNormal):
1434 case convolve(fcInfinity, fcInfinity):
1435 category = fcInfinity;
1436 return opOK;
1437
1438 case convolve(fcZero, fcNormal):
1439 case convolve(fcNormal, fcZero):
1440 case convolve(fcZero, fcZero):
1441 category = fcZero;
1442 return opOK;
1443
1444 case convolve(fcZero, fcInfinity):
1445 case convolve(fcInfinity, fcZero):
Neil Booth5fe658b2007-10-14 10:39:51 +00001446 makeNaN();
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001447 return opInvalidOp;
1448
1449 case convolve(fcNormal, fcNormal):
1450 return opOK;
1451 }
1452}
1453
1454APFloat::opStatus
1455APFloat::divideSpecials(const APFloat &rhs)
1456{
Mike Stump889285d2009-05-13 23:23:20 +00001457 switch (convolve(category, rhs.category)) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001458 default:
Torok Edwinfbcc6632009-07-14 16:55:14 +00001459 llvm_unreachable(0);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001460
Dale Johannesen3cf889f2007-08-31 04:03:46 +00001461 case convolve(fcNaN, fcZero):
1462 case convolve(fcNaN, fcNormal):
1463 case convolve(fcNaN, fcInfinity):
1464 case convolve(fcNaN, fcNaN):
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001465 case convolve(fcInfinity, fcZero):
1466 case convolve(fcInfinity, fcNormal):
1467 case convolve(fcZero, fcInfinity):
1468 case convolve(fcZero, fcNormal):
1469 return opOK;
1470
Dale Johannesen3cf889f2007-08-31 04:03:46 +00001471 case convolve(fcZero, fcNaN):
1472 case convolve(fcNormal, fcNaN):
1473 case convolve(fcInfinity, fcNaN):
1474 category = fcNaN;
1475 copySignificand(rhs);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001476 return opOK;
1477
1478 case convolve(fcNormal, fcInfinity):
1479 category = fcZero;
1480 return opOK;
1481
1482 case convolve(fcNormal, fcZero):
1483 category = fcInfinity;
1484 return opDivByZero;
1485
1486 case convolve(fcInfinity, fcInfinity):
1487 case convolve(fcZero, fcZero):
Neil Booth5fe658b2007-10-14 10:39:51 +00001488 makeNaN();
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001489 return opInvalidOp;
1490
1491 case convolve(fcNormal, fcNormal):
1492 return opOK;
1493 }
1494}
1495
Dale Johannesenb5721632009-01-21 00:35:19 +00001496APFloat::opStatus
1497APFloat::modSpecials(const APFloat &rhs)
1498{
Mike Stump889285d2009-05-13 23:23:20 +00001499 switch (convolve(category, rhs.category)) {
Dale Johannesenb5721632009-01-21 00:35:19 +00001500 default:
Torok Edwinfbcc6632009-07-14 16:55:14 +00001501 llvm_unreachable(0);
Dale Johannesenb5721632009-01-21 00:35:19 +00001502
1503 case convolve(fcNaN, fcZero):
1504 case convolve(fcNaN, fcNormal):
1505 case convolve(fcNaN, fcInfinity):
1506 case convolve(fcNaN, fcNaN):
1507 case convolve(fcZero, fcInfinity):
1508 case convolve(fcZero, fcNormal):
1509 case convolve(fcNormal, fcInfinity):
1510 return opOK;
1511
1512 case convolve(fcZero, fcNaN):
1513 case convolve(fcNormal, fcNaN):
1514 case convolve(fcInfinity, fcNaN):
1515 category = fcNaN;
1516 copySignificand(rhs);
1517 return opOK;
1518
1519 case convolve(fcNormal, fcZero):
1520 case convolve(fcInfinity, fcZero):
1521 case convolve(fcInfinity, fcNormal):
1522 case convolve(fcInfinity, fcInfinity):
1523 case convolve(fcZero, fcZero):
1524 makeNaN();
1525 return opInvalidOp;
1526
1527 case convolve(fcNormal, fcNormal):
1528 return opOK;
1529 }
1530}
1531
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001532/* Change sign. */
1533void
1534APFloat::changeSign()
1535{
1536 /* Look mummy, this one's easy. */
1537 sign = !sign;
1538}
1539
Dale Johannesen689d17d2007-08-31 23:35:31 +00001540void
1541APFloat::clearSign()
1542{
1543 /* So is this one. */
1544 sign = 0;
1545}
1546
1547void
1548APFloat::copySign(const APFloat &rhs)
1549{
1550 /* And this one. */
1551 sign = rhs.sign;
1552}
1553
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001554/* Normalized addition or subtraction. */
1555APFloat::opStatus
1556APFloat::addOrSubtract(const APFloat &rhs, roundingMode rounding_mode,
Neil Booth9acbf5a2007-09-26 21:33:42 +00001557 bool subtract)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001558{
1559 opStatus fs;
1560
Neil Booth06077e72007-10-14 10:29:28 +00001561 assertArithmeticOK(*semantics);
1562
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001563 fs = addOrSubtractSpecials(rhs, subtract);
1564
1565 /* This return code means it was not a simple case. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001566 if (fs == opDivByZero) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001567 lostFraction lost_fraction;
1568
1569 lost_fraction = addOrSubtractSignificand(rhs, subtract);
1570 fs = normalize(rounding_mode, lost_fraction);
1571
1572 /* Can only be zero if we lost no fraction. */
1573 assert(category != fcZero || lost_fraction == lfExactlyZero);
1574 }
1575
1576 /* If two numbers add (exactly) to zero, IEEE 754 decrees it is a
1577 positive zero unless rounding to minus infinity, except that
1578 adding two like-signed zeroes gives that zero. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001579 if (category == fcZero) {
1580 if (rhs.category != fcZero || (sign == rhs.sign) == subtract)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001581 sign = (rounding_mode == rmTowardNegative);
1582 }
1583
1584 return fs;
1585}
1586
1587/* Normalized addition. */
1588APFloat::opStatus
1589APFloat::add(const APFloat &rhs, roundingMode rounding_mode)
1590{
1591 return addOrSubtract(rhs, rounding_mode, false);
1592}
1593
1594/* Normalized subtraction. */
1595APFloat::opStatus
1596APFloat::subtract(const APFloat &rhs, roundingMode rounding_mode)
1597{
1598 return addOrSubtract(rhs, rounding_mode, true);
1599}
1600
1601/* Normalized multiply. */
1602APFloat::opStatus
1603APFloat::multiply(const APFloat &rhs, roundingMode rounding_mode)
1604{
1605 opStatus fs;
1606
Neil Booth06077e72007-10-14 10:29:28 +00001607 assertArithmeticOK(*semantics);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001608 sign ^= rhs.sign;
1609 fs = multiplySpecials(rhs);
1610
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001611 if (category == fcNormal) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001612 lostFraction lost_fraction = multiplySignificand(rhs, 0);
1613 fs = normalize(rounding_mode, lost_fraction);
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001614 if (lost_fraction != lfExactlyZero)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001615 fs = (opStatus) (fs | opInexact);
1616 }
1617
1618 return fs;
1619}
1620
1621/* Normalized divide. */
1622APFloat::opStatus
1623APFloat::divide(const APFloat &rhs, roundingMode rounding_mode)
1624{
1625 opStatus fs;
1626
Neil Booth06077e72007-10-14 10:29:28 +00001627 assertArithmeticOK(*semantics);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001628 sign ^= rhs.sign;
1629 fs = divideSpecials(rhs);
1630
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001631 if (category == fcNormal) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001632 lostFraction lost_fraction = divideSignificand(rhs);
1633 fs = normalize(rounding_mode, lost_fraction);
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001634 if (lost_fraction != lfExactlyZero)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001635 fs = (opStatus) (fs | opInexact);
1636 }
1637
1638 return fs;
1639}
1640
Dale Johannesenfe750172009-01-20 18:35:05 +00001641/* Normalized remainder. This is not currently correct in all cases. */
1642APFloat::opStatus
1643APFloat::remainder(const APFloat &rhs)
1644{
1645 opStatus fs;
1646 APFloat V = *this;
1647 unsigned int origSign = sign;
1648
1649 assertArithmeticOK(*semantics);
1650 fs = V.divide(rhs, rmNearestTiesToEven);
1651 if (fs == opDivByZero)
1652 return fs;
1653
1654 int parts = partCount();
1655 integerPart *x = new integerPart[parts];
1656 bool ignored;
1657 fs = V.convertToInteger(x, parts * integerPartWidth, true,
1658 rmNearestTiesToEven, &ignored);
1659 if (fs==opInvalidOp)
1660 return fs;
1661
1662 fs = V.convertFromZeroExtendedInteger(x, parts * integerPartWidth, true,
1663 rmNearestTiesToEven);
1664 assert(fs==opOK); // should always work
1665
1666 fs = V.multiply(rhs, rmNearestTiesToEven);
1667 assert(fs==opOK || fs==opInexact); // should not overflow or underflow
1668
1669 fs = subtract(V, rmNearestTiesToEven);
1670 assert(fs==opOK || fs==opInexact); // likewise
1671
1672 if (isZero())
1673 sign = origSign; // IEEE754 requires this
1674 delete[] x;
1675 return fs;
1676}
1677
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001678/* Normalized llvm frem (C fmod).
Dale Johannesenfe750172009-01-20 18:35:05 +00001679 This is not currently correct in all cases. */
Dale Johannesen689d17d2007-08-31 23:35:31 +00001680APFloat::opStatus
1681APFloat::mod(const APFloat &rhs, roundingMode rounding_mode)
1682{
1683 opStatus fs;
Neil Booth06077e72007-10-14 10:29:28 +00001684 assertArithmeticOK(*semantics);
Dale Johannesenb5721632009-01-21 00:35:19 +00001685 fs = modSpecials(rhs);
Dale Johannesen689d17d2007-08-31 23:35:31 +00001686
Dale Johannesenb5721632009-01-21 00:35:19 +00001687 if (category == fcNormal && rhs.category == fcNormal) {
1688 APFloat V = *this;
1689 unsigned int origSign = sign;
Dale Johannesen689d17d2007-08-31 23:35:31 +00001690
Dale Johannesenb5721632009-01-21 00:35:19 +00001691 fs = V.divide(rhs, rmNearestTiesToEven);
1692 if (fs == opDivByZero)
1693 return fs;
Dale Johannesen728687c2007-09-05 20:39:49 +00001694
Dale Johannesenb5721632009-01-21 00:35:19 +00001695 int parts = partCount();
1696 integerPart *x = new integerPart[parts];
1697 bool ignored;
1698 fs = V.convertToInteger(x, parts * integerPartWidth, true,
1699 rmTowardZero, &ignored);
1700 if (fs==opInvalidOp)
1701 return fs;
Dale Johannesen728687c2007-09-05 20:39:49 +00001702
Dale Johannesenb5721632009-01-21 00:35:19 +00001703 fs = V.convertFromZeroExtendedInteger(x, parts * integerPartWidth, true,
1704 rmNearestTiesToEven);
1705 assert(fs==opOK); // should always work
Dale Johannesen728687c2007-09-05 20:39:49 +00001706
Dale Johannesenb5721632009-01-21 00:35:19 +00001707 fs = V.multiply(rhs, rounding_mode);
1708 assert(fs==opOK || fs==opInexact); // should not overflow or underflow
1709
1710 fs = subtract(V, rounding_mode);
1711 assert(fs==opOK || fs==opInexact); // likewise
1712
1713 if (isZero())
1714 sign = origSign; // IEEE754 requires this
1715 delete[] x;
1716 }
Dale Johannesen689d17d2007-08-31 23:35:31 +00001717 return fs;
1718}
1719
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001720/* Normalized fused-multiply-add. */
1721APFloat::opStatus
1722APFloat::fusedMultiplyAdd(const APFloat &multiplicand,
Neil Booth9acbf5a2007-09-26 21:33:42 +00001723 const APFloat &addend,
1724 roundingMode rounding_mode)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001725{
1726 opStatus fs;
1727
Neil Booth06077e72007-10-14 10:29:28 +00001728 assertArithmeticOK(*semantics);
1729
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001730 /* Post-multiplication sign, before addition. */
1731 sign ^= multiplicand.sign;
1732
1733 /* If and only if all arguments are normal do we need to do an
1734 extended-precision calculation. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001735 if (category == fcNormal &&
1736 multiplicand.category == fcNormal &&
1737 addend.category == fcNormal) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001738 lostFraction lost_fraction;
1739
1740 lost_fraction = multiplySignificand(multiplicand, &addend);
1741 fs = normalize(rounding_mode, lost_fraction);
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001742 if (lost_fraction != lfExactlyZero)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001743 fs = (opStatus) (fs | opInexact);
1744
1745 /* If two numbers add (exactly) to zero, IEEE 754 decrees it is a
1746 positive zero unless rounding to minus infinity, except that
1747 adding two like-signed zeroes gives that zero. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001748 if (category == fcZero && sign != addend.sign)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001749 sign = (rounding_mode == rmTowardNegative);
1750 } else {
1751 fs = multiplySpecials(multiplicand);
1752
1753 /* FS can only be opOK or opInvalidOp. There is no more work
1754 to do in the latter case. The IEEE-754R standard says it is
1755 implementation-defined in this case whether, if ADDEND is a
Dale Johannesen3cf889f2007-08-31 04:03:46 +00001756 quiet NaN, we raise invalid op; this implementation does so.
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001757
1758 If we need to do the addition we can do so with normal
1759 precision. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001760 if (fs == opOK)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001761 fs = addOrSubtract(addend, rounding_mode, false);
1762 }
1763
1764 return fs;
1765}
1766
Owen Andersona40319b2012-08-13 23:32:49 +00001767/* Rounding-mode corrrect round to integral value. */
1768APFloat::opStatus APFloat::roundToIntegral(roundingMode rounding_mode) {
1769 opStatus fs;
1770 assertArithmeticOK(*semantics);
1771
Owen Anderson352dfff2012-08-15 18:28:45 +00001772 // If the exponent is large enough, we know that this value is already
1773 // integral, and the arithmetic below would potentially cause it to saturate
1774 // to +/-Inf. Bail out early instead.
Benjamin Kramerc38fab22012-09-26 14:06:58 +00001775 if (category == fcNormal && exponent+1 >= (int)semanticsPrecision(*semantics))
Owen Anderson352dfff2012-08-15 18:28:45 +00001776 return opOK;
1777
Owen Andersona40319b2012-08-13 23:32:49 +00001778 // The algorithm here is quite simple: we add 2^(p-1), where p is the
1779 // precision of our format, and then subtract it back off again. The choice
1780 // of rounding modes for the addition/subtraction determines the rounding mode
1781 // for our integral rounding as well.
Owen Andersonbe7e2972012-08-15 16:42:53 +00001782 // NOTE: When the input value is negative, we do subtraction followed by
Owen Anderson1ff74b02012-08-15 05:39:46 +00001783 // addition instead.
Owen Anderson0b357222012-08-14 18:51:15 +00001784 APInt IntegerConstant(NextPowerOf2(semanticsPrecision(*semantics)), 1);
1785 IntegerConstant <<= semanticsPrecision(*semantics)-1;
Owen Andersona40319b2012-08-13 23:32:49 +00001786 APFloat MagicConstant(*semantics);
1787 fs = MagicConstant.convertFromAPInt(IntegerConstant, false,
1788 rmNearestTiesToEven);
Owen Anderson1ff74b02012-08-15 05:39:46 +00001789 MagicConstant.copySign(*this);
1790
Owen Andersona40319b2012-08-13 23:32:49 +00001791 if (fs != opOK)
1792 return fs;
1793
Owen Anderson1ff74b02012-08-15 05:39:46 +00001794 // Preserve the input sign so that we can handle 0.0/-0.0 cases correctly.
1795 bool inputSign = isNegative();
1796
Owen Andersona40319b2012-08-13 23:32:49 +00001797 fs = add(MagicConstant, rounding_mode);
1798 if (fs != opOK && fs != opInexact)
1799 return fs;
1800
1801 fs = subtract(MagicConstant, rounding_mode);
Owen Anderson1ff74b02012-08-15 05:39:46 +00001802
1803 // Restore the input sign.
1804 if (inputSign != isNegative())
1805 changeSign();
1806
Owen Andersona40319b2012-08-13 23:32:49 +00001807 return fs;
1808}
1809
1810
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001811/* Comparison requires normalized numbers. */
1812APFloat::cmpResult
1813APFloat::compare(const APFloat &rhs) const
1814{
1815 cmpResult result;
1816
Neil Booth06077e72007-10-14 10:29:28 +00001817 assertArithmeticOK(*semantics);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001818 assert(semantics == rhs.semantics);
1819
Mike Stump889285d2009-05-13 23:23:20 +00001820 switch (convolve(category, rhs.category)) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001821 default:
Torok Edwinfbcc6632009-07-14 16:55:14 +00001822 llvm_unreachable(0);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001823
Dale Johannesen3cf889f2007-08-31 04:03:46 +00001824 case convolve(fcNaN, fcZero):
1825 case convolve(fcNaN, fcNormal):
1826 case convolve(fcNaN, fcInfinity):
1827 case convolve(fcNaN, fcNaN):
1828 case convolve(fcZero, fcNaN):
1829 case convolve(fcNormal, fcNaN):
1830 case convolve(fcInfinity, fcNaN):
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001831 return cmpUnordered;
1832
1833 case convolve(fcInfinity, fcNormal):
1834 case convolve(fcInfinity, fcZero):
1835 case convolve(fcNormal, fcZero):
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001836 if (sign)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001837 return cmpLessThan;
1838 else
1839 return cmpGreaterThan;
1840
1841 case convolve(fcNormal, fcInfinity):
1842 case convolve(fcZero, fcInfinity):
1843 case convolve(fcZero, fcNormal):
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001844 if (rhs.sign)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001845 return cmpGreaterThan;
1846 else
1847 return cmpLessThan;
1848
1849 case convolve(fcInfinity, fcInfinity):
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001850 if (sign == rhs.sign)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001851 return cmpEqual;
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001852 else if (sign)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001853 return cmpLessThan;
1854 else
1855 return cmpGreaterThan;
1856
1857 case convolve(fcZero, fcZero):
1858 return cmpEqual;
1859
1860 case convolve(fcNormal, fcNormal):
1861 break;
1862 }
1863
1864 /* Two normal numbers. Do they have the same sign? */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001865 if (sign != rhs.sign) {
1866 if (sign)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001867 result = cmpLessThan;
1868 else
1869 result = cmpGreaterThan;
1870 } else {
1871 /* Compare absolute values; invert result if negative. */
1872 result = compareAbsoluteValue(rhs);
1873
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001874 if (sign) {
1875 if (result == cmpLessThan)
Neil Booth9acbf5a2007-09-26 21:33:42 +00001876 result = cmpGreaterThan;
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001877 else if (result == cmpGreaterThan)
Neil Booth9acbf5a2007-09-26 21:33:42 +00001878 result = cmpLessThan;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001879 }
1880 }
1881
1882 return result;
1883}
1884
Dale Johannesen4f0bd682008-10-09 23:00:39 +00001885/// APFloat::convert - convert a value of one floating point type to another.
1886/// The return value corresponds to the IEEE754 exceptions. *losesInfo
1887/// records whether the transformation lost information, i.e. whether
1888/// converting the result back to the original type will produce the
1889/// original value (this is almost the same as return value==fsOK, but there
1890/// are edge cases where this is not so).
1891
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001892APFloat::opStatus
1893APFloat::convert(const fltSemantics &toSemantics,
Dale Johannesen4f0bd682008-10-09 23:00:39 +00001894 roundingMode rounding_mode, bool *losesInfo)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001895{
Neil Bootha8d72692007-09-22 02:56:19 +00001896 lostFraction lostFraction;
1897 unsigned int newPartCount, oldPartCount;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001898 opStatus fs;
Eli Friedmana84ad7d2011-11-26 03:38:02 +00001899 int shift;
1900 const fltSemantics &fromSemantics = *semantics;
Neil Booth9acbf5a2007-09-26 21:33:42 +00001901
Eli Friedmana84ad7d2011-11-26 03:38:02 +00001902 assertArithmeticOK(fromSemantics);
Dale Johannesen64bbdb12008-04-20 01:34:03 +00001903 assertArithmeticOK(toSemantics);
Neil Bootha8d72692007-09-22 02:56:19 +00001904 lostFraction = lfExactlyZero;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001905 newPartCount = partCountForBits(toSemantics.precision + 1);
Neil Bootha8d72692007-09-22 02:56:19 +00001906 oldPartCount = partCount();
Eli Friedmana84ad7d2011-11-26 03:38:02 +00001907 shift = toSemantics.precision - fromSemantics.precision;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001908
Eli Friedmana84ad7d2011-11-26 03:38:02 +00001909 bool X86SpecialNan = false;
1910 if (&fromSemantics == &APFloat::x87DoubleExtended &&
1911 &toSemantics != &APFloat::x87DoubleExtended && category == fcNaN &&
1912 (!(*significandParts() & 0x8000000000000000ULL) ||
1913 !(*significandParts() & 0x4000000000000000ULL))) {
1914 // x86 has some unusual NaNs which cannot be represented in any other
1915 // format; note them here.
1916 X86SpecialNan = true;
1917 }
1918
1919 // If this is a truncation, perform the shift before we narrow the storage.
1920 if (shift < 0 && (category==fcNormal || category==fcNaN))
1921 lostFraction = shiftRight(significandParts(), oldPartCount, -shift);
1922
1923 // Fix the storage so it can hold to new value.
Neil Bootha8d72692007-09-22 02:56:19 +00001924 if (newPartCount > oldPartCount) {
Eli Friedmana84ad7d2011-11-26 03:38:02 +00001925 // The new type requires more storage; make it available.
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001926 integerPart *newParts;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001927 newParts = new integerPart[newPartCount];
1928 APInt::tcSet(newParts, 0, newPartCount);
Dale Johannesen4f55d9f2007-09-25 17:25:00 +00001929 if (category==fcNormal || category==fcNaN)
1930 APInt::tcAssign(newParts, significandParts(), oldPartCount);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001931 freeSignificand();
1932 significand.parts = newParts;
Eli Friedmana84ad7d2011-11-26 03:38:02 +00001933 } else if (newPartCount == 1 && oldPartCount != 1) {
1934 // Switch to built-in storage for a single part.
1935 integerPart newPart = 0;
1936 if (category==fcNormal || category==fcNaN)
1937 newPart = significandParts()[0];
1938 freeSignificand();
1939 significand.part = newPart;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001940 }
1941
Eli Friedmana84ad7d2011-11-26 03:38:02 +00001942 // Now that we have the right storage, switch the semantics.
1943 semantics = &toSemantics;
1944
1945 // If this is an extension, perform the shift now that the storage is
1946 // available.
1947 if (shift > 0 && (category==fcNormal || category==fcNaN))
1948 APInt::tcShiftLeft(significandParts(), newPartCount, shift);
1949
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001950 if (category == fcNormal) {
Neil Bootha8d72692007-09-22 02:56:19 +00001951 fs = normalize(rounding_mode, lostFraction);
Dale Johannesen4f0bd682008-10-09 23:00:39 +00001952 *losesInfo = (fs != opOK);
Dale Johannesen4f55d9f2007-09-25 17:25:00 +00001953 } else if (category == fcNaN) {
Eli Friedmana84ad7d2011-11-26 03:38:02 +00001954 *losesInfo = lostFraction != lfExactlyZero || X86SpecialNan;
Dale Johannesen4f55d9f2007-09-25 17:25:00 +00001955 // gcc forces the Quiet bit on, which means (float)(double)(float_sNan)
1956 // does not give you back the same bits. This is dubious, and we
1957 // don't currently do it. You're really supposed to get
1958 // an invalid operation signal at runtime, but nobody does that.
Dale Johannesen4f0bd682008-10-09 23:00:39 +00001959 fs = opOK;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001960 } else {
Dale Johannesen4f0bd682008-10-09 23:00:39 +00001961 *losesInfo = false;
Eli Friedman31f01162011-11-28 18:50:37 +00001962 fs = opOK;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001963 }
1964
1965 return fs;
1966}
1967
1968/* Convert a floating point number to an integer according to the
1969 rounding mode. If the rounded integer value is out of range this
Neil Booth618d0fc2007-11-01 22:43:37 +00001970 returns an invalid operation exception and the contents of the
1971 destination parts are unspecified. If the rounded value is in
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001972 range but the floating point number is not the exact integer, the C
1973 standard doesn't require an inexact exception to be raised. IEEE
1974 854 does require it so we do that.
1975
1976 Note that for conversions to integer type the C standard requires
1977 round-to-zero to always be used. */
1978APFloat::opStatus
Neil Booth618d0fc2007-11-01 22:43:37 +00001979APFloat::convertToSignExtendedInteger(integerPart *parts, unsigned int width,
1980 bool isSigned,
Dale Johannesen4f0bd682008-10-09 23:00:39 +00001981 roundingMode rounding_mode,
1982 bool *isExact) const
Neil Booth618d0fc2007-11-01 22:43:37 +00001983{
1984 lostFraction lost_fraction;
1985 const integerPart *src;
1986 unsigned int dstPartsCount, truncatedBits;
1987
Evan Cheng496b0422008-11-26 01:11:57 +00001988 assertArithmeticOK(*semantics);
Neil Booth758d0fd2007-11-02 15:10:05 +00001989
Dale Johannesen4f0bd682008-10-09 23:00:39 +00001990 *isExact = false;
1991
Neil Booth618d0fc2007-11-01 22:43:37 +00001992 /* Handle the three special cases first. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001993 if (category == fcInfinity || category == fcNaN)
Neil Booth618d0fc2007-11-01 22:43:37 +00001994 return opInvalidOp;
1995
1996 dstPartsCount = partCountForBits(width);
1997
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001998 if (category == fcZero) {
Neil Booth618d0fc2007-11-01 22:43:37 +00001999 APInt::tcSet(parts, 0, dstPartsCount);
Dale Johannesen7221af32008-10-07 00:40:01 +00002000 // Negative zero can't be represented as an int.
Dale Johannesen4f0bd682008-10-09 23:00:39 +00002001 *isExact = !sign;
2002 return opOK;
Neil Booth618d0fc2007-11-01 22:43:37 +00002003 }
2004
2005 src = significandParts();
2006
2007 /* Step 1: place our absolute value, with any fraction truncated, in
2008 the destination. */
2009 if (exponent < 0) {
2010 /* Our absolute value is less than one; truncate everything. */
2011 APInt::tcSet(parts, 0, dstPartsCount);
Dale Johannesen740e9872009-01-19 21:17:05 +00002012 /* For exponent -1 the integer bit represents .5, look at that.
2013 For smaller exponents leftmost truncated bit is 0. */
2014 truncatedBits = semantics->precision -1U - exponent;
Neil Booth618d0fc2007-11-01 22:43:37 +00002015 } else {
2016 /* We want the most significant (exponent + 1) bits; the rest are
2017 truncated. */
2018 unsigned int bits = exponent + 1U;
2019
2020 /* Hopelessly large in magnitude? */
2021 if (bits > width)
2022 return opInvalidOp;
2023
2024 if (bits < semantics->precision) {
2025 /* We truncate (semantics->precision - bits) bits. */
2026 truncatedBits = semantics->precision - bits;
2027 APInt::tcExtract(parts, dstPartsCount, src, bits, truncatedBits);
2028 } else {
2029 /* We want at least as many bits as are available. */
2030 APInt::tcExtract(parts, dstPartsCount, src, semantics->precision, 0);
2031 APInt::tcShiftLeft(parts, dstPartsCount, bits - semantics->precision);
2032 truncatedBits = 0;
2033 }
2034 }
2035
2036 /* Step 2: work out any lost fraction, and increment the absolute
2037 value if we would round away from zero. */
2038 if (truncatedBits) {
2039 lost_fraction = lostFractionThroughTruncation(src, partCount(),
2040 truncatedBits);
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002041 if (lost_fraction != lfExactlyZero &&
2042 roundAwayFromZero(rounding_mode, lost_fraction, truncatedBits)) {
Neil Booth618d0fc2007-11-01 22:43:37 +00002043 if (APInt::tcIncrement(parts, dstPartsCount))
2044 return opInvalidOp; /* Overflow. */
2045 }
2046 } else {
2047 lost_fraction = lfExactlyZero;
2048 }
2049
2050 /* Step 3: check if we fit in the destination. */
2051 unsigned int omsb = APInt::tcMSB(parts, dstPartsCount) + 1;
2052
2053 if (sign) {
2054 if (!isSigned) {
2055 /* Negative numbers cannot be represented as unsigned. */
2056 if (omsb != 0)
2057 return opInvalidOp;
2058 } else {
2059 /* It takes omsb bits to represent the unsigned integer value.
2060 We lose a bit for the sign, but care is needed as the
2061 maximally negative integer is a special case. */
2062 if (omsb == width && APInt::tcLSB(parts, dstPartsCount) + 1 != omsb)
2063 return opInvalidOp;
2064
2065 /* This case can happen because of rounding. */
2066 if (omsb > width)
2067 return opInvalidOp;
2068 }
2069
2070 APInt::tcNegate (parts, dstPartsCount);
2071 } else {
2072 if (omsb >= width + !isSigned)
2073 return opInvalidOp;
2074 }
2075
Dale Johannesen4f0bd682008-10-09 23:00:39 +00002076 if (lost_fraction == lfExactlyZero) {
2077 *isExact = true;
Neil Booth618d0fc2007-11-01 22:43:37 +00002078 return opOK;
Dale Johannesen4f0bd682008-10-09 23:00:39 +00002079 } else
Neil Booth618d0fc2007-11-01 22:43:37 +00002080 return opInexact;
2081}
2082
2083/* Same as convertToSignExtendedInteger, except we provide
2084 deterministic values in case of an invalid operation exception,
2085 namely zero for NaNs and the minimal or maximal value respectively
Dale Johannesen4f0bd682008-10-09 23:00:39 +00002086 for underflow or overflow.
2087 The *isExact output tells whether the result is exact, in the sense
2088 that converting it back to the original floating point type produces
2089 the original value. This is almost equivalent to result==opOK,
2090 except for negative zeroes.
2091*/
Neil Booth618d0fc2007-11-01 22:43:37 +00002092APFloat::opStatus
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002093APFloat::convertToInteger(integerPart *parts, unsigned int width,
Neil Booth9acbf5a2007-09-26 21:33:42 +00002094 bool isSigned,
Dale Johannesen4f0bd682008-10-09 23:00:39 +00002095 roundingMode rounding_mode, bool *isExact) const
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002096{
Neil Booth618d0fc2007-11-01 22:43:37 +00002097 opStatus fs;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002098
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002099 fs = convertToSignExtendedInteger(parts, width, isSigned, rounding_mode,
Dale Johannesen4f0bd682008-10-09 23:00:39 +00002100 isExact);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002101
Neil Booth618d0fc2007-11-01 22:43:37 +00002102 if (fs == opInvalidOp) {
2103 unsigned int bits, dstPartsCount;
2104
2105 dstPartsCount = partCountForBits(width);
2106
2107 if (category == fcNaN)
2108 bits = 0;
2109 else if (sign)
2110 bits = isSigned;
2111 else
2112 bits = width - isSigned;
2113
2114 APInt::tcSetLeastSignificantBits(parts, dstPartsCount, bits);
2115 if (sign && isSigned)
2116 APInt::tcShiftLeft(parts, dstPartsCount, width - 1);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002117 }
2118
Neil Booth618d0fc2007-11-01 22:43:37 +00002119 return fs;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002120}
2121
Jeffrey Yasskin03b81a22011-07-15 07:04:56 +00002122/* Same as convertToInteger(integerPart*, ...), except the result is returned in
2123 an APSInt, whose initial bit-width and signed-ness are used to determine the
2124 precision of the conversion.
2125 */
2126APFloat::opStatus
2127APFloat::convertToInteger(APSInt &result,
2128 roundingMode rounding_mode, bool *isExact) const
2129{
2130 unsigned bitWidth = result.getBitWidth();
2131 SmallVector<uint64_t, 4> parts(result.getNumWords());
2132 opStatus status = convertToInteger(
2133 parts.data(), bitWidth, result.isSigned(), rounding_mode, isExact);
2134 // Keeps the original signed-ness.
Jeffrey Yasskin7a162882011-07-18 21:45:40 +00002135 result = APInt(bitWidth, parts);
Jeffrey Yasskin03b81a22011-07-15 07:04:56 +00002136 return status;
2137}
2138
Neil Booth6c1c8582007-10-07 12:07:53 +00002139/* Convert an unsigned integer SRC to a floating point number,
2140 rounding according to ROUNDING_MODE. The sign of the floating
2141 point number is not modified. */
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002142APFloat::opStatus
Neil Booth6c1c8582007-10-07 12:07:53 +00002143APFloat::convertFromUnsignedParts(const integerPart *src,
2144 unsigned int srcCount,
2145 roundingMode rounding_mode)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002146{
Neil Booth49c6aab2007-10-08 14:39:42 +00002147 unsigned int omsb, precision, dstCount;
Neil Booth6c1c8582007-10-07 12:07:53 +00002148 integerPart *dst;
Neil Booth49c6aab2007-10-08 14:39:42 +00002149 lostFraction lost_fraction;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002150
Neil Booth06077e72007-10-14 10:29:28 +00002151 assertArithmeticOK(*semantics);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002152 category = fcNormal;
Neil Booth49c6aab2007-10-08 14:39:42 +00002153 omsb = APInt::tcMSB(src, srcCount) + 1;
Neil Booth6c1c8582007-10-07 12:07:53 +00002154 dst = significandParts();
2155 dstCount = partCount();
Neil Booth49c6aab2007-10-08 14:39:42 +00002156 precision = semantics->precision;
Neil Booth6c1c8582007-10-07 12:07:53 +00002157
Nick Lewyckyf66daac2011-10-03 21:30:08 +00002158 /* We want the most significant PRECISION bits of SRC. There may not
Neil Booth49c6aab2007-10-08 14:39:42 +00002159 be that many; extract what we can. */
2160 if (precision <= omsb) {
2161 exponent = omsb - 1;
Neil Booth6c1c8582007-10-07 12:07:53 +00002162 lost_fraction = lostFractionThroughTruncation(src, srcCount,
Neil Booth49c6aab2007-10-08 14:39:42 +00002163 omsb - precision);
2164 APInt::tcExtract(dst, dstCount, src, precision, omsb - precision);
2165 } else {
2166 exponent = precision - 1;
2167 lost_fraction = lfExactlyZero;
2168 APInt::tcExtract(dst, dstCount, src, omsb, 0);
Neil Booth6c1c8582007-10-07 12:07:53 +00002169 }
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002170
2171 return normalize(rounding_mode, lost_fraction);
2172}
2173
Dan Gohman35723eb2008-02-29 01:26:11 +00002174APFloat::opStatus
2175APFloat::convertFromAPInt(const APInt &Val,
2176 bool isSigned,
2177 roundingMode rounding_mode)
2178{
2179 unsigned int partCount = Val.getNumWords();
2180 APInt api = Val;
2181
2182 sign = false;
2183 if (isSigned && api.isNegative()) {
2184 sign = true;
2185 api = -api;
2186 }
2187
2188 return convertFromUnsignedParts(api.getRawData(), partCount, rounding_mode);
2189}
2190
Neil Booth03f58ab2007-10-07 12:15:41 +00002191/* Convert a two's complement integer SRC to a floating point number,
2192 rounding according to ROUNDING_MODE. ISSIGNED is true if the
2193 integer is signed, in which case it must be sign-extended. */
2194APFloat::opStatus
2195APFloat::convertFromSignExtendedInteger(const integerPart *src,
2196 unsigned int srcCount,
2197 bool isSigned,
2198 roundingMode rounding_mode)
2199{
2200 opStatus status;
2201
Neil Booth06077e72007-10-14 10:29:28 +00002202 assertArithmeticOK(*semantics);
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002203 if (isSigned &&
2204 APInt::tcExtractBit(src, srcCount * integerPartWidth - 1)) {
Neil Booth03f58ab2007-10-07 12:15:41 +00002205 integerPart *copy;
2206
2207 /* If we're signed and negative negate a copy. */
2208 sign = true;
2209 copy = new integerPart[srcCount];
2210 APInt::tcAssign(copy, src, srcCount);
2211 APInt::tcNegate(copy, srcCount);
2212 status = convertFromUnsignedParts(copy, srcCount, rounding_mode);
2213 delete [] copy;
2214 } else {
2215 sign = false;
2216 status = convertFromUnsignedParts(src, srcCount, rounding_mode);
2217 }
2218
2219 return status;
2220}
2221
Neil Booth5f009732007-10-07 11:45:55 +00002222/* FIXME: should this just take a const APInt reference? */
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002223APFloat::opStatus
Neil Booth5f009732007-10-07 11:45:55 +00002224APFloat::convertFromZeroExtendedInteger(const integerPart *parts,
2225 unsigned int width, bool isSigned,
2226 roundingMode rounding_mode)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002227{
Dale Johannesen42305122007-09-21 22:09:37 +00002228 unsigned int partCount = partCountForBits(width);
Jeffrey Yasskin7a162882011-07-18 21:45:40 +00002229 APInt api = APInt(width, makeArrayRef(parts, partCount));
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002230
2231 sign = false;
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002232 if (isSigned && APInt::tcExtractBit(parts, width - 1)) {
Dale Johannesen28a2c4a2007-09-30 18:17:01 +00002233 sign = true;
2234 api = -api;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002235 }
2236
Neil Boothba205222007-10-07 12:10:57 +00002237 return convertFromUnsignedParts(api.getRawData(), partCount, rounding_mode);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002238}
2239
2240APFloat::opStatus
Benjamin Kramer92d89982010-07-14 22:38:02 +00002241APFloat::convertFromHexadecimalString(StringRef s, roundingMode rounding_mode)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002242{
Erick Tryzelaara9680df2009-08-18 18:20:37 +00002243 lostFraction lost_fraction = lfExactlyZero;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002244 integerPart *significand;
2245 unsigned int bitPos, partsCount;
Erick Tryzelaar19f63b22009-08-16 23:36:19 +00002246 StringRef::iterator dot, firstSignificantDigit;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002247
2248 zeroSignificand();
2249 exponent = 0;
2250 category = fcNormal;
2251
2252 significand = significandParts();
2253 partsCount = partCount();
2254 bitPos = partsCount * integerPartWidth;
2255
Neil Boothd3985922007-10-07 08:51:21 +00002256 /* Skip leading zeroes and any (hexa)decimal point. */
Erick Tryzelaarda666c82009-08-20 23:30:43 +00002257 StringRef::iterator begin = s.begin();
2258 StringRef::iterator end = s.end();
2259 StringRef::iterator p = skipLeadingZeroesAndAnyDot(begin, end, &dot);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002260 firstSignificantDigit = p;
2261
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002262 for (; p != end;) {
Dale Johannesenfa483722008-05-14 22:53:25 +00002263 integerPart hex_value;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002264
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002265 if (*p == '.') {
Erick Tryzelaarda666c82009-08-20 23:30:43 +00002266 assert(dot == end && "String contains multiple dots");
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002267 dot = p++;
Erick Tryzelaarda666c82009-08-20 23:30:43 +00002268 if (p == end) {
2269 break;
2270 }
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002271 }
2272
2273 hex_value = hexDigitValue(*p);
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002274 if (hex_value == -1U) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002275 break;
2276 }
2277
2278 p++;
2279
Erick Tryzelaarda666c82009-08-20 23:30:43 +00002280 if (p == end) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002281 break;
Erick Tryzelaar19f63b22009-08-16 23:36:19 +00002282 } else {
2283 /* Store the number whilst 4-bit nibbles remain. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002284 if (bitPos) {
Erick Tryzelaar19f63b22009-08-16 23:36:19 +00002285 bitPos -= 4;
2286 hex_value <<= bitPos % integerPartWidth;
2287 significand[bitPos / integerPartWidth] |= hex_value;
2288 } else {
Erick Tryzelaarda666c82009-08-20 23:30:43 +00002289 lost_fraction = trailingHexadecimalFraction(p, end, hex_value);
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002290 while (p != end && hexDigitValue(*p) != -1U)
Erick Tryzelaar19f63b22009-08-16 23:36:19 +00002291 p++;
2292 break;
2293 }
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002294 }
2295 }
2296
2297 /* Hex floats require an exponent but not a hexadecimal point. */
Erick Tryzelaarda666c82009-08-20 23:30:43 +00002298 assert(p != end && "Hex strings require an exponent");
2299 assert((*p == 'p' || *p == 'P') && "Invalid character in significand");
2300 assert(p != begin && "Significand has no digits");
2301 assert((dot == end || p - begin != 1) && "Significand has no digits");
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002302
2303 /* Ignore the exponent if we are zero. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002304 if (p != firstSignificantDigit) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002305 int expAdjustment;
2306
2307 /* Implicit hexadecimal point? */
Erick Tryzelaarda666c82009-08-20 23:30:43 +00002308 if (dot == end)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002309 dot = p;
2310
2311 /* Calculate the exponent adjustment implicit in the number of
2312 significant digits. */
Evan Cheng82b9e962008-05-02 21:15:08 +00002313 expAdjustment = static_cast<int>(dot - firstSignificantDigit);
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002314 if (expAdjustment < 0)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002315 expAdjustment++;
2316 expAdjustment = expAdjustment * 4 - 1;
2317
2318 /* Adjust for writing the significand starting at the most
2319 significant nibble. */
2320 expAdjustment += semantics->precision;
2321 expAdjustment -= partsCount * integerPartWidth;
2322
2323 /* Adjust for the given exponent. */
Erick Tryzelaarda666c82009-08-20 23:30:43 +00002324 exponent = totalExponent(p + 1, end, expAdjustment);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002325 }
2326
2327 return normalize(rounding_mode, lost_fraction);
2328}
2329
2330APFloat::opStatus
Neil Boothb93d90e2007-10-12 16:02:31 +00002331APFloat::roundSignificandWithExponent(const integerPart *decSigParts,
2332 unsigned sigPartCount, int exp,
2333 roundingMode rounding_mode)
2334{
2335 unsigned int parts, pow5PartCount;
Neil Booth06077e72007-10-14 10:29:28 +00002336 fltSemantics calcSemantics = { 32767, -32767, 0, true };
Neil Boothb93d90e2007-10-12 16:02:31 +00002337 integerPart pow5Parts[maxPowerOfFiveParts];
2338 bool isNearest;
2339
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002340 isNearest = (rounding_mode == rmNearestTiesToEven ||
2341 rounding_mode == rmNearestTiesToAway);
Neil Boothb93d90e2007-10-12 16:02:31 +00002342
2343 parts = partCountForBits(semantics->precision + 11);
2344
2345 /* Calculate pow(5, abs(exp)). */
2346 pow5PartCount = powerOf5(pow5Parts, exp >= 0 ? exp: -exp);
2347
2348 for (;; parts *= 2) {
2349 opStatus sigStatus, powStatus;
2350 unsigned int excessPrecision, truncatedBits;
2351
2352 calcSemantics.precision = parts * integerPartWidth - 1;
2353 excessPrecision = calcSemantics.precision - semantics->precision;
2354 truncatedBits = excessPrecision;
2355
2356 APFloat decSig(calcSemantics, fcZero, sign);
2357 APFloat pow5(calcSemantics, fcZero, false);
2358
2359 sigStatus = decSig.convertFromUnsignedParts(decSigParts, sigPartCount,
2360 rmNearestTiesToEven);
2361 powStatus = pow5.convertFromUnsignedParts(pow5Parts, pow5PartCount,
2362 rmNearestTiesToEven);
2363 /* Add exp, as 10^n = 5^n * 2^n. */
2364 decSig.exponent += exp;
2365
2366 lostFraction calcLostFraction;
Evan Cheng82b9e962008-05-02 21:15:08 +00002367 integerPart HUerr, HUdistance;
2368 unsigned int powHUerr;
Neil Boothb93d90e2007-10-12 16:02:31 +00002369
2370 if (exp >= 0) {
2371 /* multiplySignificand leaves the precision-th bit set to 1. */
2372 calcLostFraction = decSig.multiplySignificand(pow5, NULL);
2373 powHUerr = powStatus != opOK;
2374 } else {
2375 calcLostFraction = decSig.divideSignificand(pow5);
2376 /* Denormal numbers have less precision. */
2377 if (decSig.exponent < semantics->minExponent) {
2378 excessPrecision += (semantics->minExponent - decSig.exponent);
2379 truncatedBits = excessPrecision;
2380 if (excessPrecision > calcSemantics.precision)
2381 excessPrecision = calcSemantics.precision;
2382 }
2383 /* Extra half-ulp lost in reciprocal of exponent. */
Evan Cheng82b9e962008-05-02 21:15:08 +00002384 powHUerr = (powStatus == opOK && calcLostFraction == lfExactlyZero) ? 0:2;
Neil Boothb93d90e2007-10-12 16:02:31 +00002385 }
2386
2387 /* Both multiplySignificand and divideSignificand return the
2388 result with the integer bit set. */
Evan Cheng67c90212009-10-27 21:35:42 +00002389 assert(APInt::tcExtractBit
2390 (decSig.significandParts(), calcSemantics.precision - 1) == 1);
Neil Boothb93d90e2007-10-12 16:02:31 +00002391
2392 HUerr = HUerrBound(calcLostFraction != lfExactlyZero, sigStatus != opOK,
2393 powHUerr);
2394 HUdistance = 2 * ulpsFromBoundary(decSig.significandParts(),
2395 excessPrecision, isNearest);
2396
2397 /* Are we guaranteed to round correctly if we truncate? */
2398 if (HUdistance >= HUerr) {
2399 APInt::tcExtract(significandParts(), partCount(), decSig.significandParts(),
2400 calcSemantics.precision - excessPrecision,
2401 excessPrecision);
2402 /* Take the exponent of decSig. If we tcExtract-ed less bits
2403 above we must adjust our exponent to compensate for the
2404 implicit right shift. */
2405 exponent = (decSig.exponent + semantics->precision
2406 - (calcSemantics.precision - excessPrecision));
2407 calcLostFraction = lostFractionThroughTruncation(decSig.significandParts(),
2408 decSig.partCount(),
2409 truncatedBits);
2410 return normalize(rounding_mode, calcLostFraction);
2411 }
2412 }
2413}
2414
2415APFloat::opStatus
Benjamin Kramer92d89982010-07-14 22:38:02 +00002416APFloat::convertFromDecimalString(StringRef str, roundingMode rounding_mode)
Neil Boothb93d90e2007-10-12 16:02:31 +00002417{
Neil Booth4ed401b2007-10-14 10:16:12 +00002418 decimalInfo D;
Neil Boothb93d90e2007-10-12 16:02:31 +00002419 opStatus fs;
2420
Neil Booth4ed401b2007-10-14 10:16:12 +00002421 /* Scan the text. */
Erick Tryzelaar19f63b22009-08-16 23:36:19 +00002422 StringRef::iterator p = str.begin();
2423 interpretDecimal(p, str.end(), &D);
Neil Boothb93d90e2007-10-12 16:02:31 +00002424
Neil Booth91305512007-10-15 15:00:55 +00002425 /* Handle the quick cases. First the case of no significant digits,
2426 i.e. zero, and then exponents that are obviously too large or too
2427 small. Writing L for log 10 / log 2, a number d.ddddd*10^exp
2428 definitely overflows if
2429
2430 (exp - 1) * L >= maxExponent
2431
2432 and definitely underflows to zero where
2433
2434 (exp + 1) * L <= minExponent - precision
2435
2436 With integer arithmetic the tightest bounds for L are
2437
2438 93/28 < L < 196/59 [ numerator <= 256 ]
2439 42039/12655 < L < 28738/8651 [ numerator <= 65536 ]
2440 */
2441
Neil Booth06f20ea2007-12-05 13:06:04 +00002442 if (decDigitValue(*D.firstSigDigit) >= 10U) {
Neil Boothb93d90e2007-10-12 16:02:31 +00002443 category = fcZero;
2444 fs = opOK;
John McCallb42cc682010-02-26 22:20:41 +00002445
2446 /* Check whether the normalized exponent is high enough to overflow
2447 max during the log-rebasing in the max-exponent check below. */
2448 } else if (D.normalizedExponent - 1 > INT_MAX / 42039) {
2449 fs = handleOverflow(rounding_mode);
2450
2451 /* If it wasn't, then it also wasn't high enough to overflow max
2452 during the log-rebasing in the min-exponent check. Check that it
2453 won't overflow min in either check, then perform the min-exponent
2454 check. */
2455 } else if (D.normalizedExponent - 1 < INT_MIN / 42039 ||
2456 (D.normalizedExponent + 1) * 28738 <=
2457 8651 * (semantics->minExponent - (int) semantics->precision)) {
Neil Booth91305512007-10-15 15:00:55 +00002458 /* Underflow to zero and round. */
2459 zeroSignificand();
2460 fs = normalize(rounding_mode, lfLessThanHalf);
John McCallb42cc682010-02-26 22:20:41 +00002461
2462 /* We can finally safely perform the max-exponent check. */
Neil Booth91305512007-10-15 15:00:55 +00002463 } else if ((D.normalizedExponent - 1) * 42039
2464 >= 12655 * semantics->maxExponent) {
2465 /* Overflow and round. */
2466 fs = handleOverflow(rounding_mode);
Neil Boothb93d90e2007-10-12 16:02:31 +00002467 } else {
Neil Booth4ed401b2007-10-14 10:16:12 +00002468 integerPart *decSignificand;
2469 unsigned int partCount;
Neil Boothb93d90e2007-10-12 16:02:31 +00002470
Neil Booth4ed401b2007-10-14 10:16:12 +00002471 /* A tight upper bound on number of bits required to hold an
Neil Booth91305512007-10-15 15:00:55 +00002472 N-digit decimal integer is N * 196 / 59. Allocate enough space
Neil Booth4ed401b2007-10-14 10:16:12 +00002473 to hold the full significand, and an extra part required by
2474 tcMultiplyPart. */
Evan Cheng82b9e962008-05-02 21:15:08 +00002475 partCount = static_cast<unsigned int>(D.lastSigDigit - D.firstSigDigit) + 1;
Neil Booth91305512007-10-15 15:00:55 +00002476 partCount = partCountForBits(1 + 196 * partCount / 59);
Neil Booth4ed401b2007-10-14 10:16:12 +00002477 decSignificand = new integerPart[partCount + 1];
2478 partCount = 0;
Neil Boothb93d90e2007-10-12 16:02:31 +00002479
Neil Booth4ed401b2007-10-14 10:16:12 +00002480 /* Convert to binary efficiently - we do almost all multiplication
2481 in an integerPart. When this would overflow do we do a single
2482 bignum multiplication, and then revert again to multiplication
2483 in an integerPart. */
2484 do {
2485 integerPart decValue, val, multiplier;
2486
2487 val = 0;
2488 multiplier = 1;
2489
2490 do {
Erick Tryzelaar19f63b22009-08-16 23:36:19 +00002491 if (*p == '.') {
Neil Booth4ed401b2007-10-14 10:16:12 +00002492 p++;
Erick Tryzelaar19f63b22009-08-16 23:36:19 +00002493 if (p == str.end()) {
2494 break;
2495 }
2496 }
Neil Booth4ed401b2007-10-14 10:16:12 +00002497 decValue = decDigitValue(*p++);
Erick Tryzelaarda666c82009-08-20 23:30:43 +00002498 assert(decValue < 10U && "Invalid character in significand");
Neil Booth4ed401b2007-10-14 10:16:12 +00002499 multiplier *= 10;
2500 val = val * 10 + decValue;
2501 /* The maximum number that can be multiplied by ten with any
2502 digit added without overflowing an integerPart. */
2503 } while (p <= D.lastSigDigit && multiplier <= (~ (integerPart) 0 - 9) / 10);
2504
2505 /* Multiply out the current part. */
2506 APInt::tcMultiplyPart(decSignificand, decSignificand, multiplier, val,
2507 partCount, partCount + 1, false);
2508
2509 /* If we used another part (likely but not guaranteed), increase
2510 the count. */
2511 if (decSignificand[partCount])
2512 partCount++;
2513 } while (p <= D.lastSigDigit);
Neil Boothb93d90e2007-10-12 16:02:31 +00002514
Neil Boothae077d22007-11-01 22:51:07 +00002515 category = fcNormal;
Neil Boothb93d90e2007-10-12 16:02:31 +00002516 fs = roundSignificandWithExponent(decSignificand, partCount,
Neil Booth4ed401b2007-10-14 10:16:12 +00002517 D.exponent, rounding_mode);
Neil Boothb93d90e2007-10-12 16:02:31 +00002518
Neil Booth4ed401b2007-10-14 10:16:12 +00002519 delete [] decSignificand;
2520 }
Neil Boothb93d90e2007-10-12 16:02:31 +00002521
2522 return fs;
2523}
2524
2525APFloat::opStatus
Benjamin Kramer92d89982010-07-14 22:38:02 +00002526APFloat::convertFromString(StringRef str, roundingMode rounding_mode)
Neil Booth9acbf5a2007-09-26 21:33:42 +00002527{
Neil Booth06077e72007-10-14 10:29:28 +00002528 assertArithmeticOK(*semantics);
Erick Tryzelaar19f63b22009-08-16 23:36:19 +00002529 assert(!str.empty() && "Invalid string length");
Neil Booth06077e72007-10-14 10:29:28 +00002530
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002531 /* Handle a leading minus sign. */
Erick Tryzelaar19f63b22009-08-16 23:36:19 +00002532 StringRef::iterator p = str.begin();
2533 size_t slen = str.size();
Erick Tryzelaarda666c82009-08-20 23:30:43 +00002534 sign = *p == '-' ? 1 : 0;
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002535 if (*p == '-' || *p == '+') {
Erick Tryzelaar19f63b22009-08-16 23:36:19 +00002536 p++;
2537 slen--;
Erick Tryzelaarda666c82009-08-20 23:30:43 +00002538 assert(slen && "String has no digits");
Erick Tryzelaar19f63b22009-08-16 23:36:19 +00002539 }
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002540
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002541 if (slen >= 2 && p[0] == '0' && (p[1] == 'x' || p[1] == 'X')) {
Erick Tryzelaar19f63b22009-08-16 23:36:19 +00002542 assert(slen - 2 && "Invalid string");
Erick Tryzelaarda666c82009-08-20 23:30:43 +00002543 return convertFromHexadecimalString(StringRef(p + 2, slen - 2),
Erick Tryzelaar19f63b22009-08-16 23:36:19 +00002544 rounding_mode);
2545 }
Bill Wendlingc6075402008-11-27 08:00:12 +00002546
Erick Tryzelaarda666c82009-08-20 23:30:43 +00002547 return convertFromDecimalString(StringRef(p, slen), rounding_mode);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002548}
Dale Johannesena719a602007-08-24 00:56:33 +00002549
Neil Booth8f1946f2007-10-03 22:26:02 +00002550/* Write out a hexadecimal representation of the floating point value
2551 to DST, which must be of sufficient size, in the C99 form
2552 [-]0xh.hhhhp[+-]d. Return the number of characters written,
2553 excluding the terminating NUL.
2554
2555 If UPPERCASE, the output is in upper case, otherwise in lower case.
2556
2557 HEXDIGITS digits appear altogether, rounding the value if
2558 necessary. If HEXDIGITS is 0, the minimal precision to display the
2559 number precisely is used instead. If nothing would appear after
2560 the decimal point it is suppressed.
2561
2562 The decimal exponent is always printed and has at least one digit.
2563 Zero values display an exponent of zero. Infinities and NaNs
2564 appear as "infinity" or "nan" respectively.
2565
2566 The above rules are as specified by C99. There is ambiguity about
2567 what the leading hexadecimal digit should be. This implementation
2568 uses whatever is necessary so that the exponent is displayed as
2569 stored. This implies the exponent will fall within the IEEE format
2570 range, and the leading hexadecimal digit will be 0 (for denormals),
2571 1 (normal numbers) or 2 (normal numbers rounded-away-from-zero with
2572 any other digits zero).
2573*/
2574unsigned int
2575APFloat::convertToHexString(char *dst, unsigned int hexDigits,
2576 bool upperCase, roundingMode rounding_mode) const
2577{
2578 char *p;
2579
Neil Booth06077e72007-10-14 10:29:28 +00002580 assertArithmeticOK(*semantics);
2581
Neil Booth8f1946f2007-10-03 22:26:02 +00002582 p = dst;
2583 if (sign)
2584 *dst++ = '-';
2585
2586 switch (category) {
2587 case fcInfinity:
2588 memcpy (dst, upperCase ? infinityU: infinityL, sizeof infinityU - 1);
2589 dst += sizeof infinityL - 1;
2590 break;
2591
2592 case fcNaN:
2593 memcpy (dst, upperCase ? NaNU: NaNL, sizeof NaNU - 1);
2594 dst += sizeof NaNU - 1;
2595 break;
2596
2597 case fcZero:
2598 *dst++ = '0';
2599 *dst++ = upperCase ? 'X': 'x';
2600 *dst++ = '0';
2601 if (hexDigits > 1) {
2602 *dst++ = '.';
2603 memset (dst, '0', hexDigits - 1);
2604 dst += hexDigits - 1;
2605 }
2606 *dst++ = upperCase ? 'P': 'p';
2607 *dst++ = '0';
2608 break;
2609
2610 case fcNormal:
2611 dst = convertNormalToHexString (dst, hexDigits, upperCase, rounding_mode);
2612 break;
2613 }
2614
2615 *dst = 0;
2616
Evan Cheng82b9e962008-05-02 21:15:08 +00002617 return static_cast<unsigned int>(dst - p);
Neil Booth8f1946f2007-10-03 22:26:02 +00002618}
2619
2620/* Does the hard work of outputting the correctly rounded hexadecimal
2621 form of a normal floating point number with the specified number of
2622 hexadecimal digits. If HEXDIGITS is zero the minimum number of
2623 digits necessary to print the value precisely is output. */
2624char *
2625APFloat::convertNormalToHexString(char *dst, unsigned int hexDigits,
2626 bool upperCase,
2627 roundingMode rounding_mode) const
2628{
2629 unsigned int count, valueBits, shift, partsCount, outputDigits;
2630 const char *hexDigitChars;
2631 const integerPart *significand;
2632 char *p;
2633 bool roundUp;
2634
2635 *dst++ = '0';
2636 *dst++ = upperCase ? 'X': 'x';
2637
2638 roundUp = false;
2639 hexDigitChars = upperCase ? hexDigitsUpper: hexDigitsLower;
2640
2641 significand = significandParts();
2642 partsCount = partCount();
2643
2644 /* +3 because the first digit only uses the single integer bit, so
2645 we have 3 virtual zero most-significant-bits. */
2646 valueBits = semantics->precision + 3;
2647 shift = integerPartWidth - valueBits % integerPartWidth;
2648
2649 /* The natural number of digits required ignoring trailing
2650 insignificant zeroes. */
2651 outputDigits = (valueBits - significandLSB () + 3) / 4;
2652
2653 /* hexDigits of zero means use the required number for the
2654 precision. Otherwise, see if we are truncating. If we are,
Neil Booth0ea72a92007-10-06 00:24:48 +00002655 find out if we need to round away from zero. */
Neil Booth8f1946f2007-10-03 22:26:02 +00002656 if (hexDigits) {
2657 if (hexDigits < outputDigits) {
2658 /* We are dropping non-zero bits, so need to check how to round.
2659 "bits" is the number of dropped bits. */
2660 unsigned int bits;
2661 lostFraction fraction;
2662
2663 bits = valueBits - hexDigits * 4;
2664 fraction = lostFractionThroughTruncation (significand, partsCount, bits);
2665 roundUp = roundAwayFromZero(rounding_mode, fraction, bits);
2666 }
2667 outputDigits = hexDigits;
2668 }
2669
2670 /* Write the digits consecutively, and start writing in the location
2671 of the hexadecimal point. We move the most significant digit
2672 left and add the hexadecimal point later. */
2673 p = ++dst;
2674
2675 count = (valueBits + integerPartWidth - 1) / integerPartWidth;
2676
2677 while (outputDigits && count) {
2678 integerPart part;
2679
2680 /* Put the most significant integerPartWidth bits in "part". */
2681 if (--count == partsCount)
2682 part = 0; /* An imaginary higher zero part. */
2683 else
2684 part = significand[count] << shift;
2685
2686 if (count && shift)
2687 part |= significand[count - 1] >> (integerPartWidth - shift);
2688
2689 /* Convert as much of "part" to hexdigits as we can. */
2690 unsigned int curDigits = integerPartWidth / 4;
2691
2692 if (curDigits > outputDigits)
2693 curDigits = outputDigits;
2694 dst += partAsHex (dst, part, curDigits, hexDigitChars);
2695 outputDigits -= curDigits;
2696 }
2697
2698 if (roundUp) {
2699 char *q = dst;
2700
2701 /* Note that hexDigitChars has a trailing '0'. */
2702 do {
2703 q--;
2704 *q = hexDigitChars[hexDigitValue (*q) + 1];
Neil Booth0ea72a92007-10-06 00:24:48 +00002705 } while (*q == '0');
Evan Cheng67c90212009-10-27 21:35:42 +00002706 assert(q >= p);
Neil Booth8f1946f2007-10-03 22:26:02 +00002707 } else {
2708 /* Add trailing zeroes. */
2709 memset (dst, '0', outputDigits);
2710 dst += outputDigits;
2711 }
2712
2713 /* Move the most significant digit to before the point, and if there
2714 is something after the decimal point add it. This must come
2715 after rounding above. */
2716 p[-1] = p[0];
2717 if (dst -1 == p)
2718 dst--;
2719 else
2720 p[0] = '.';
2721
2722 /* Finally output the exponent. */
2723 *dst++ = upperCase ? 'P': 'p';
2724
Neil Booth32897f52007-10-06 07:29:25 +00002725 return writeSignedDecimal (dst, exponent);
Neil Booth8f1946f2007-10-03 22:26:02 +00002726}
2727
Chandler Carruth71bd7d12012-03-04 12:02:57 +00002728hash_code llvm::hash_value(const APFloat &Arg) {
2729 if (Arg.category != APFloat::fcNormal)
2730 return hash_combine((uint8_t)Arg.category,
2731 // NaN has no sign, fix it at zero.
2732 Arg.isNaN() ? (uint8_t)0 : (uint8_t)Arg.sign,
2733 Arg.semantics->precision);
2734
2735 // Normal floats need their exponent and significand hashed.
2736 return hash_combine((uint8_t)Arg.category, (uint8_t)Arg.sign,
2737 Arg.semantics->precision, Arg.exponent,
2738 hash_combine_range(
2739 Arg.significandParts(),
2740 Arg.significandParts() + Arg.partCount()));
Dale Johannesena719a602007-08-24 00:56:33 +00002741}
2742
2743// Conversion from APFloat to/from host float/double. It may eventually be
2744// possible to eliminate these and have everybody deal with APFloats, but that
2745// will take a while. This approach will not easily extend to long double.
Dale Johannesen146a0ea2007-09-20 23:47:58 +00002746// Current implementation requires integerPartWidth==64, which is correct at
2747// the moment but could be made more general.
Dale Johannesena719a602007-08-24 00:56:33 +00002748
Dale Johannesen728687c2007-09-05 20:39:49 +00002749// Denormals have exponent minExponent in APFloat, but minExponent-1 in
Dale Johannesen146a0ea2007-09-20 23:47:58 +00002750// the actual IEEE respresentations. We compensate for that here.
Dale Johannesen728687c2007-09-05 20:39:49 +00002751
Dale Johannesen245dceb2007-09-11 18:32:33 +00002752APInt
Neil Booth9acbf5a2007-09-26 21:33:42 +00002753APFloat::convertF80LongDoubleAPFloatToAPInt() const
2754{
Dan Gohmanb456a152008-01-29 12:08:20 +00002755 assert(semantics == (const llvm::fltSemantics*)&x87DoubleExtended);
Evan Cheng67c90212009-10-27 21:35:42 +00002756 assert(partCount()==2);
Dale Johannesen245dceb2007-09-11 18:32:33 +00002757
2758 uint64_t myexponent, mysignificand;
2759
2760 if (category==fcNormal) {
2761 myexponent = exponent+16383; //bias
Dale Johannesen146a0ea2007-09-20 23:47:58 +00002762 mysignificand = significandParts()[0];
Dale Johannesen245dceb2007-09-11 18:32:33 +00002763 if (myexponent==1 && !(mysignificand & 0x8000000000000000ULL))
2764 myexponent = 0; // denormal
2765 } else if (category==fcZero) {
2766 myexponent = 0;
2767 mysignificand = 0;
2768 } else if (category==fcInfinity) {
2769 myexponent = 0x7fff;
2770 mysignificand = 0x8000000000000000ULL;
Chris Lattner2a9bcb92007-10-06 06:13:42 +00002771 } else {
2772 assert(category == fcNaN && "Unknown category");
Dale Johannesen245dceb2007-09-11 18:32:33 +00002773 myexponent = 0x7fff;
Dale Johannesen146a0ea2007-09-20 23:47:58 +00002774 mysignificand = significandParts()[0];
Chris Lattner2a9bcb92007-10-06 06:13:42 +00002775 }
Dale Johannesen245dceb2007-09-11 18:32:33 +00002776
2777 uint64_t words[2];
Dale Johannesen93eefa02009-03-23 21:16:53 +00002778 words[0] = mysignificand;
2779 words[1] = ((uint64_t)(sign & 1) << 15) |
2780 (myexponent & 0x7fffLL);
Jeffrey Yasskin7a162882011-07-18 21:45:40 +00002781 return APInt(80, words);
Dale Johannesen245dceb2007-09-11 18:32:33 +00002782}
2783
2784APInt
Dale Johannesen007aa372007-10-11 18:07:22 +00002785APFloat::convertPPCDoubleDoubleAPFloatToAPInt() const
2786{
Dan Gohmanb456a152008-01-29 12:08:20 +00002787 assert(semantics == (const llvm::fltSemantics*)&PPCDoubleDouble);
Evan Cheng67c90212009-10-27 21:35:42 +00002788 assert(partCount()==2);
Dale Johannesen007aa372007-10-11 18:07:22 +00002789
Ulrich Weigandd9f7e252012-10-29 18:09:01 +00002790 uint64_t words[2];
2791 opStatus fs;
2792 bool losesInfo;
Dale Johannesen007aa372007-10-11 18:07:22 +00002793
Ulrich Weigandd9f7e252012-10-29 18:09:01 +00002794 // Convert number to double. To avoid spurious underflows, we re-
2795 // normalize against the "double" minExponent first, and only *then*
2796 // truncate the mantissa. The result of that second conversion
2797 // may be inexact, but should never underflow.
2798 APFloat extended(*this);
2799 fltSemantics extendedSemantics = *semantics;
2800 extendedSemantics.minExponent = IEEEdouble.minExponent;
2801 fs = extended.convert(extendedSemantics, rmNearestTiesToEven, &losesInfo);
2802 assert(fs == opOK && !losesInfo);
2803 (void)fs;
2804
2805 APFloat u(extended);
2806 fs = u.convert(IEEEdouble, rmNearestTiesToEven, &losesInfo);
2807 assert(fs == opOK || fs == opInexact);
2808 (void)fs;
2809 words[0] = *u.convertDoubleAPFloatToAPInt().getRawData();
2810
2811 // If conversion was exact or resulted in a special case, we're done;
2812 // just set the second double to zero. Otherwise, re-convert back to
2813 // the extended format and compute the difference. This now should
2814 // convert exactly to double.
2815 if (u.category == fcNormal && losesInfo) {
2816 fs = u.convert(extendedSemantics, rmNearestTiesToEven, &losesInfo);
2817 assert(fs == opOK && !losesInfo);
2818 (void)fs;
2819
2820 APFloat v(extended);
2821 v.subtract(u, rmNearestTiesToEven);
2822 fs = v.convert(IEEEdouble, rmNearestTiesToEven, &losesInfo);
2823 assert(fs == opOK && !losesInfo);
2824 (void)fs;
2825 words[1] = *v.convertDoubleAPFloatToAPInt().getRawData();
Dale Johannesen007aa372007-10-11 18:07:22 +00002826 } else {
Ulrich Weigandd9f7e252012-10-29 18:09:01 +00002827 words[1] = 0;
Dale Johannesen007aa372007-10-11 18:07:22 +00002828 }
2829
Jeffrey Yasskin7a162882011-07-18 21:45:40 +00002830 return APInt(128, words);
Dale Johannesen007aa372007-10-11 18:07:22 +00002831}
2832
2833APInt
Anton Korobeynikov13e8c7e2009-08-21 22:10:30 +00002834APFloat::convertQuadrupleAPFloatToAPInt() const
2835{
2836 assert(semantics == (const llvm::fltSemantics*)&IEEEquad);
Evan Cheng67c90212009-10-27 21:35:42 +00002837 assert(partCount()==2);
Anton Korobeynikov13e8c7e2009-08-21 22:10:30 +00002838
2839 uint64_t myexponent, mysignificand, mysignificand2;
2840
2841 if (category==fcNormal) {
2842 myexponent = exponent+16383; //bias
2843 mysignificand = significandParts()[0];
2844 mysignificand2 = significandParts()[1];
2845 if (myexponent==1 && !(mysignificand2 & 0x1000000000000LL))
2846 myexponent = 0; // denormal
2847 } else if (category==fcZero) {
2848 myexponent = 0;
2849 mysignificand = mysignificand2 = 0;
2850 } else if (category==fcInfinity) {
2851 myexponent = 0x7fff;
2852 mysignificand = mysignificand2 = 0;
2853 } else {
2854 assert(category == fcNaN && "Unknown category!");
2855 myexponent = 0x7fff;
2856 mysignificand = significandParts()[0];
2857 mysignificand2 = significandParts()[1];
2858 }
2859
2860 uint64_t words[2];
2861 words[0] = mysignificand;
2862 words[1] = ((uint64_t)(sign & 1) << 63) |
2863 ((myexponent & 0x7fff) << 48) |
Anton Korobeynikov876955c2009-08-21 23:09:47 +00002864 (mysignificand2 & 0xffffffffffffLL);
Anton Korobeynikov13e8c7e2009-08-21 22:10:30 +00002865
Jeffrey Yasskin7a162882011-07-18 21:45:40 +00002866 return APInt(128, words);
Anton Korobeynikov13e8c7e2009-08-21 22:10:30 +00002867}
2868
2869APInt
Neil Booth9acbf5a2007-09-26 21:33:42 +00002870APFloat::convertDoubleAPFloatToAPInt() const
2871{
Dan Gohman58c468f2007-09-14 20:08:19 +00002872 assert(semantics == (const llvm::fltSemantics*)&IEEEdouble);
Evan Cheng67c90212009-10-27 21:35:42 +00002873 assert(partCount()==1);
Dale Johannesena719a602007-08-24 00:56:33 +00002874
Dale Johannesen3cf889f2007-08-31 04:03:46 +00002875 uint64_t myexponent, mysignificand;
Dale Johannesena719a602007-08-24 00:56:33 +00002876
2877 if (category==fcNormal) {
Dale Johannesena719a602007-08-24 00:56:33 +00002878 myexponent = exponent+1023; //bias
Dale Johannesen728687c2007-09-05 20:39:49 +00002879 mysignificand = *significandParts();
2880 if (myexponent==1 && !(mysignificand & 0x10000000000000LL))
2881 myexponent = 0; // denormal
Dale Johannesena719a602007-08-24 00:56:33 +00002882 } else if (category==fcZero) {
Dale Johannesena719a602007-08-24 00:56:33 +00002883 myexponent = 0;
2884 mysignificand = 0;
2885 } else if (category==fcInfinity) {
Dale Johannesena719a602007-08-24 00:56:33 +00002886 myexponent = 0x7ff;
2887 mysignificand = 0;
Chris Lattner2a9bcb92007-10-06 06:13:42 +00002888 } else {
2889 assert(category == fcNaN && "Unknown category!");
Dale Johannesena719a602007-08-24 00:56:33 +00002890 myexponent = 0x7ff;
Dale Johannesen3cf889f2007-08-31 04:03:46 +00002891 mysignificand = *significandParts();
Chris Lattner2a9bcb92007-10-06 06:13:42 +00002892 }
Dale Johannesena719a602007-08-24 00:56:33 +00002893
Evan Cheng82b9e962008-05-02 21:15:08 +00002894 return APInt(64, ((((uint64_t)(sign & 1) << 63) |
Chris Lattner2a9bcb92007-10-06 06:13:42 +00002895 ((myexponent & 0x7ff) << 52) |
2896 (mysignificand & 0xfffffffffffffLL))));
Dale Johannesena719a602007-08-24 00:56:33 +00002897}
2898
Dale Johannesen245dceb2007-09-11 18:32:33 +00002899APInt
Neil Booth9acbf5a2007-09-26 21:33:42 +00002900APFloat::convertFloatAPFloatToAPInt() const
2901{
Dan Gohman58c468f2007-09-14 20:08:19 +00002902 assert(semantics == (const llvm::fltSemantics*)&IEEEsingle);
Evan Cheng67c90212009-10-27 21:35:42 +00002903 assert(partCount()==1);
Neil Booth9acbf5a2007-09-26 21:33:42 +00002904
Dale Johannesen3cf889f2007-08-31 04:03:46 +00002905 uint32_t myexponent, mysignificand;
Dale Johannesena719a602007-08-24 00:56:33 +00002906
2907 if (category==fcNormal) {
Dale Johannesena719a602007-08-24 00:56:33 +00002908 myexponent = exponent+127; //bias
Evan Cheng82b9e962008-05-02 21:15:08 +00002909 mysignificand = (uint32_t)*significandParts();
Dale Johannesen06a10df2007-11-17 01:02:27 +00002910 if (myexponent == 1 && !(mysignificand & 0x800000))
Dale Johannesen728687c2007-09-05 20:39:49 +00002911 myexponent = 0; // denormal
Dale Johannesena719a602007-08-24 00:56:33 +00002912 } else if (category==fcZero) {
Dale Johannesena719a602007-08-24 00:56:33 +00002913 myexponent = 0;
2914 mysignificand = 0;
2915 } else if (category==fcInfinity) {
Dale Johannesena719a602007-08-24 00:56:33 +00002916 myexponent = 0xff;
2917 mysignificand = 0;
Chris Lattner2a9bcb92007-10-06 06:13:42 +00002918 } else {
2919 assert(category == fcNaN && "Unknown category!");
Dale Johannesen728687c2007-09-05 20:39:49 +00002920 myexponent = 0xff;
Evan Cheng82b9e962008-05-02 21:15:08 +00002921 mysignificand = (uint32_t)*significandParts();
Chris Lattner2a9bcb92007-10-06 06:13:42 +00002922 }
Dale Johannesena719a602007-08-24 00:56:33 +00002923
Chris Lattner2a9bcb92007-10-06 06:13:42 +00002924 return APInt(32, (((sign&1) << 31) | ((myexponent&0xff) << 23) |
2925 (mysignificand & 0x7fffff)));
Dale Johannesena719a602007-08-24 00:56:33 +00002926}
2927
Chris Lattner4794b2b2009-10-16 02:13:51 +00002928APInt
2929APFloat::convertHalfAPFloatToAPInt() const
2930{
2931 assert(semantics == (const llvm::fltSemantics*)&IEEEhalf);
Evan Cheng67c90212009-10-27 21:35:42 +00002932 assert(partCount()==1);
Chris Lattner4794b2b2009-10-16 02:13:51 +00002933
2934 uint32_t myexponent, mysignificand;
2935
2936 if (category==fcNormal) {
2937 myexponent = exponent+15; //bias
2938 mysignificand = (uint32_t)*significandParts();
2939 if (myexponent == 1 && !(mysignificand & 0x400))
2940 myexponent = 0; // denormal
2941 } else if (category==fcZero) {
2942 myexponent = 0;
2943 mysignificand = 0;
2944 } else if (category==fcInfinity) {
Dale Johannesen0d670b52009-10-23 04:02:51 +00002945 myexponent = 0x1f;
Chris Lattner4794b2b2009-10-16 02:13:51 +00002946 mysignificand = 0;
2947 } else {
2948 assert(category == fcNaN && "Unknown category!");
Dale Johannesen0d670b52009-10-23 04:02:51 +00002949 myexponent = 0x1f;
Chris Lattner4794b2b2009-10-16 02:13:51 +00002950 mysignificand = (uint32_t)*significandParts();
2951 }
2952
2953 return APInt(16, (((sign&1) << 15) | ((myexponent&0x1f) << 10) |
2954 (mysignificand & 0x3ff)));
2955}
2956
Dale Johannesen007aa372007-10-11 18:07:22 +00002957// This function creates an APInt that is just a bit map of the floating
2958// point constant as it would appear in memory. It is not a conversion,
2959// and treating the result as a normal integer is unlikely to be useful.
2960
Dale Johannesen245dceb2007-09-11 18:32:33 +00002961APInt
Dale Johannesen54306fe2008-10-09 18:53:47 +00002962APFloat::bitcastToAPInt() const
Neil Booth9acbf5a2007-09-26 21:33:42 +00002963{
Chris Lattner4794b2b2009-10-16 02:13:51 +00002964 if (semantics == (const llvm::fltSemantics*)&IEEEhalf)
2965 return convertHalfAPFloatToAPInt();
2966
Dan Gohmanb456a152008-01-29 12:08:20 +00002967 if (semantics == (const llvm::fltSemantics*)&IEEEsingle)
Dale Johannesen245dceb2007-09-11 18:32:33 +00002968 return convertFloatAPFloatToAPInt();
Anton Korobeynikov13e8c7e2009-08-21 22:10:30 +00002969
Dan Gohmanb456a152008-01-29 12:08:20 +00002970 if (semantics == (const llvm::fltSemantics*)&IEEEdouble)
Dale Johannesen245dceb2007-09-11 18:32:33 +00002971 return convertDoubleAPFloatToAPInt();
Neil Booth9acbf5a2007-09-26 21:33:42 +00002972
Anton Korobeynikov13e8c7e2009-08-21 22:10:30 +00002973 if (semantics == (const llvm::fltSemantics*)&IEEEquad)
2974 return convertQuadrupleAPFloatToAPInt();
2975
Dan Gohmanb456a152008-01-29 12:08:20 +00002976 if (semantics == (const llvm::fltSemantics*)&PPCDoubleDouble)
Dale Johannesen007aa372007-10-11 18:07:22 +00002977 return convertPPCDoubleDoubleAPFloatToAPInt();
2978
Dan Gohmanb456a152008-01-29 12:08:20 +00002979 assert(semantics == (const llvm::fltSemantics*)&x87DoubleExtended &&
Chris Lattner2a9bcb92007-10-06 06:13:42 +00002980 "unknown format!");
2981 return convertF80LongDoubleAPFloatToAPInt();
Dale Johannesen245dceb2007-09-11 18:32:33 +00002982}
2983
Neil Booth9acbf5a2007-09-26 21:33:42 +00002984float
2985APFloat::convertToFloat() const
2986{
Chris Lattner688f9912009-09-24 21:44:20 +00002987 assert(semantics == (const llvm::fltSemantics*)&IEEEsingle &&
2988 "Float semantics are not IEEEsingle");
Dale Johannesen54306fe2008-10-09 18:53:47 +00002989 APInt api = bitcastToAPInt();
Dale Johannesen245dceb2007-09-11 18:32:33 +00002990 return api.bitsToFloat();
2991}
2992
Neil Booth9acbf5a2007-09-26 21:33:42 +00002993double
2994APFloat::convertToDouble() const
2995{
Chris Lattner688f9912009-09-24 21:44:20 +00002996 assert(semantics == (const llvm::fltSemantics*)&IEEEdouble &&
2997 "Float semantics are not IEEEdouble");
Dale Johannesen54306fe2008-10-09 18:53:47 +00002998 APInt api = bitcastToAPInt();
Dale Johannesen245dceb2007-09-11 18:32:33 +00002999 return api.bitsToDouble();
3000}
3001
Dale Johannesenfff29952008-10-06 18:22:29 +00003002/// Integer bit is explicit in this format. Intel hardware (387 and later)
3003/// does not support these bit patterns:
3004/// exponent = all 1's, integer bit 0, significand 0 ("pseudoinfinity")
3005/// exponent = all 1's, integer bit 0, significand nonzero ("pseudoNaN")
3006/// exponent = 0, integer bit 1 ("pseudodenormal")
3007/// exponent!=0 nor all 1's, integer bit 0 ("unnormal")
3008/// At the moment, the first two are treated as NaNs, the second two as Normal.
Dale Johannesen245dceb2007-09-11 18:32:33 +00003009void
Neil Booth9acbf5a2007-09-26 21:33:42 +00003010APFloat::initFromF80LongDoubleAPInt(const APInt &api)
3011{
Dale Johannesen245dceb2007-09-11 18:32:33 +00003012 assert(api.getBitWidth()==80);
3013 uint64_t i1 = api.getRawData()[0];
3014 uint64_t i2 = api.getRawData()[1];
Dale Johannesen93eefa02009-03-23 21:16:53 +00003015 uint64_t myexponent = (i2 & 0x7fff);
3016 uint64_t mysignificand = i1;
Dale Johannesen245dceb2007-09-11 18:32:33 +00003017
3018 initialize(&APFloat::x87DoubleExtended);
Dale Johannesen146a0ea2007-09-20 23:47:58 +00003019 assert(partCount()==2);
Dale Johannesen245dceb2007-09-11 18:32:33 +00003020
Dale Johannesen93eefa02009-03-23 21:16:53 +00003021 sign = static_cast<unsigned int>(i2>>15);
Dale Johannesen245dceb2007-09-11 18:32:33 +00003022 if (myexponent==0 && mysignificand==0) {
3023 // exponent, significand meaningless
3024 category = fcZero;
3025 } else if (myexponent==0x7fff && mysignificand==0x8000000000000000ULL) {
3026 // exponent, significand meaningless
3027 category = fcInfinity;
3028 } else if (myexponent==0x7fff && mysignificand!=0x8000000000000000ULL) {
3029 // exponent meaningless
3030 category = fcNaN;
Dale Johannesen146a0ea2007-09-20 23:47:58 +00003031 significandParts()[0] = mysignificand;
3032 significandParts()[1] = 0;
Dale Johannesen245dceb2007-09-11 18:32:33 +00003033 } else {
3034 category = fcNormal;
3035 exponent = myexponent - 16383;
Dale Johannesen146a0ea2007-09-20 23:47:58 +00003036 significandParts()[0] = mysignificand;
3037 significandParts()[1] = 0;
Dale Johannesen245dceb2007-09-11 18:32:33 +00003038 if (myexponent==0) // denormal
3039 exponent = -16382;
Neil Booth9acbf5a2007-09-26 21:33:42 +00003040 }
Dale Johannesen245dceb2007-09-11 18:32:33 +00003041}
3042
3043void
Dale Johannesen007aa372007-10-11 18:07:22 +00003044APFloat::initFromPPCDoubleDoubleAPInt(const APInt &api)
3045{
3046 assert(api.getBitWidth()==128);
3047 uint64_t i1 = api.getRawData()[0];
3048 uint64_t i2 = api.getRawData()[1];
Ulrich Weigandd9f7e252012-10-29 18:09:01 +00003049 opStatus fs;
3050 bool losesInfo;
Dale Johannesen007aa372007-10-11 18:07:22 +00003051
Ulrich Weigandd9f7e252012-10-29 18:09:01 +00003052 // Get the first double and convert to our format.
3053 initFromDoubleAPInt(APInt(64, i1));
3054 fs = convert(PPCDoubleDouble, rmNearestTiesToEven, &losesInfo);
3055 assert(fs == opOK && !losesInfo);
3056 (void)fs;
Dale Johannesen007aa372007-10-11 18:07:22 +00003057
Ulrich Weigandd9f7e252012-10-29 18:09:01 +00003058 // Unless we have a special case, add in second double.
3059 if (category == fcNormal) {
3060 APFloat v(APInt(64, i2));
3061 fs = v.convert(PPCDoubleDouble, rmNearestTiesToEven, &losesInfo);
3062 assert(fs == opOK && !losesInfo);
3063 (void)fs;
3064
3065 add(v, rmNearestTiesToEven);
Dale Johannesen007aa372007-10-11 18:07:22 +00003066 }
3067}
3068
3069void
Anton Korobeynikov13e8c7e2009-08-21 22:10:30 +00003070APFloat::initFromQuadrupleAPInt(const APInt &api)
3071{
3072 assert(api.getBitWidth()==128);
3073 uint64_t i1 = api.getRawData()[0];
3074 uint64_t i2 = api.getRawData()[1];
3075 uint64_t myexponent = (i2 >> 48) & 0x7fff;
3076 uint64_t mysignificand = i1;
3077 uint64_t mysignificand2 = i2 & 0xffffffffffffLL;
3078
3079 initialize(&APFloat::IEEEquad);
3080 assert(partCount()==2);
3081
3082 sign = static_cast<unsigned int>(i2>>63);
3083 if (myexponent==0 &&
3084 (mysignificand==0 && mysignificand2==0)) {
3085 // exponent, significand meaningless
3086 category = fcZero;
3087 } else if (myexponent==0x7fff &&
3088 (mysignificand==0 && mysignificand2==0)) {
3089 // exponent, significand meaningless
3090 category = fcInfinity;
3091 } else if (myexponent==0x7fff &&
3092 (mysignificand!=0 || mysignificand2 !=0)) {
3093 // exponent meaningless
3094 category = fcNaN;
3095 significandParts()[0] = mysignificand;
3096 significandParts()[1] = mysignificand2;
3097 } else {
3098 category = fcNormal;
3099 exponent = myexponent - 16383;
3100 significandParts()[0] = mysignificand;
3101 significandParts()[1] = mysignificand2;
3102 if (myexponent==0) // denormal
3103 exponent = -16382;
3104 else
3105 significandParts()[1] |= 0x1000000000000LL; // integer bit
3106 }
3107}
3108
3109void
Neil Booth9acbf5a2007-09-26 21:33:42 +00003110APFloat::initFromDoubleAPInt(const APInt &api)
3111{
Dale Johannesen245dceb2007-09-11 18:32:33 +00003112 assert(api.getBitWidth()==64);
3113 uint64_t i = *api.getRawData();
Dale Johannesen918c33c2007-08-24 05:08:11 +00003114 uint64_t myexponent = (i >> 52) & 0x7ff;
3115 uint64_t mysignificand = i & 0xfffffffffffffLL;
3116
Dale Johannesena719a602007-08-24 00:56:33 +00003117 initialize(&APFloat::IEEEdouble);
Dale Johannesena719a602007-08-24 00:56:33 +00003118 assert(partCount()==1);
3119
Evan Cheng82b9e962008-05-02 21:15:08 +00003120 sign = static_cast<unsigned int>(i>>63);
Dale Johannesena719a602007-08-24 00:56:33 +00003121 if (myexponent==0 && mysignificand==0) {
3122 // exponent, significand meaningless
3123 category = fcZero;
Dale Johannesena719a602007-08-24 00:56:33 +00003124 } else if (myexponent==0x7ff && mysignificand==0) {
3125 // exponent, significand meaningless
3126 category = fcInfinity;
Dale Johannesen3cf889f2007-08-31 04:03:46 +00003127 } else if (myexponent==0x7ff && mysignificand!=0) {
3128 // exponent meaningless
3129 category = fcNaN;
3130 *significandParts() = mysignificand;
Dale Johannesena719a602007-08-24 00:56:33 +00003131 } else {
Dale Johannesena719a602007-08-24 00:56:33 +00003132 category = fcNormal;
3133 exponent = myexponent - 1023;
Dale Johannesen728687c2007-09-05 20:39:49 +00003134 *significandParts() = mysignificand;
3135 if (myexponent==0) // denormal
3136 exponent = -1022;
3137 else
3138 *significandParts() |= 0x10000000000000LL; // integer bit
Neil Booth9acbf5a2007-09-26 21:33:42 +00003139 }
Dale Johannesena719a602007-08-24 00:56:33 +00003140}
3141
Dale Johannesen245dceb2007-09-11 18:32:33 +00003142void
Neil Booth9acbf5a2007-09-26 21:33:42 +00003143APFloat::initFromFloatAPInt(const APInt & api)
3144{
Dale Johannesen245dceb2007-09-11 18:32:33 +00003145 assert(api.getBitWidth()==32);
3146 uint32_t i = (uint32_t)*api.getRawData();
Dale Johannesen918c33c2007-08-24 05:08:11 +00003147 uint32_t myexponent = (i >> 23) & 0xff;
3148 uint32_t mysignificand = i & 0x7fffff;
3149
Dale Johannesena719a602007-08-24 00:56:33 +00003150 initialize(&APFloat::IEEEsingle);
Dale Johannesena719a602007-08-24 00:56:33 +00003151 assert(partCount()==1);
3152
Dale Johannesen3cf889f2007-08-31 04:03:46 +00003153 sign = i >> 31;
Dale Johannesena719a602007-08-24 00:56:33 +00003154 if (myexponent==0 && mysignificand==0) {
3155 // exponent, significand meaningless
3156 category = fcZero;
Dale Johannesena719a602007-08-24 00:56:33 +00003157 } else if (myexponent==0xff && mysignificand==0) {
3158 // exponent, significand meaningless
3159 category = fcInfinity;
Dale Johannesen4f55d9f2007-09-25 17:25:00 +00003160 } else if (myexponent==0xff && mysignificand!=0) {
Dale Johannesena719a602007-08-24 00:56:33 +00003161 // sign, exponent, significand meaningless
Dale Johannesen3cf889f2007-08-31 04:03:46 +00003162 category = fcNaN;
3163 *significandParts() = mysignificand;
Dale Johannesena719a602007-08-24 00:56:33 +00003164 } else {
3165 category = fcNormal;
Dale Johannesena719a602007-08-24 00:56:33 +00003166 exponent = myexponent - 127; //bias
Dale Johannesen728687c2007-09-05 20:39:49 +00003167 *significandParts() = mysignificand;
3168 if (myexponent==0) // denormal
3169 exponent = -126;
3170 else
3171 *significandParts() |= 0x800000; // integer bit
Dale Johannesena719a602007-08-24 00:56:33 +00003172 }
3173}
Dale Johannesen245dceb2007-09-11 18:32:33 +00003174
Chris Lattner4794b2b2009-10-16 02:13:51 +00003175void
3176APFloat::initFromHalfAPInt(const APInt & api)
3177{
3178 assert(api.getBitWidth()==16);
3179 uint32_t i = (uint32_t)*api.getRawData();
Dale Johannesen0d670b52009-10-23 04:02:51 +00003180 uint32_t myexponent = (i >> 10) & 0x1f;
Chris Lattner4794b2b2009-10-16 02:13:51 +00003181 uint32_t mysignificand = i & 0x3ff;
3182
3183 initialize(&APFloat::IEEEhalf);
3184 assert(partCount()==1);
3185
3186 sign = i >> 15;
3187 if (myexponent==0 && mysignificand==0) {
3188 // exponent, significand meaningless
3189 category = fcZero;
3190 } else if (myexponent==0x1f && mysignificand==0) {
3191 // exponent, significand meaningless
3192 category = fcInfinity;
3193 } else if (myexponent==0x1f && mysignificand!=0) {
3194 // sign, exponent, significand meaningless
3195 category = fcNaN;
3196 *significandParts() = mysignificand;
3197 } else {
3198 category = fcNormal;
3199 exponent = myexponent - 15; //bias
3200 *significandParts() = mysignificand;
3201 if (myexponent==0) // denormal
3202 exponent = -14;
3203 else
3204 *significandParts() |= 0x400; // integer bit
3205 }
3206}
3207
Dale Johannesen245dceb2007-09-11 18:32:33 +00003208/// Treat api as containing the bits of a floating point number. Currently
Dale Johannesen007aa372007-10-11 18:07:22 +00003209/// we infer the floating point type from the size of the APInt. The
3210/// isIEEE argument distinguishes between PPC128 and IEEE128 (not meaningful
3211/// when the size is anything else).
Dale Johannesen245dceb2007-09-11 18:32:33 +00003212void
Dale Johannesen007aa372007-10-11 18:07:22 +00003213APFloat::initFromAPInt(const APInt& api, bool isIEEE)
Neil Booth9acbf5a2007-09-26 21:33:42 +00003214{
Chris Lattner4794b2b2009-10-16 02:13:51 +00003215 if (api.getBitWidth() == 16)
3216 return initFromHalfAPInt(api);
3217 else if (api.getBitWidth() == 32)
Dale Johannesen245dceb2007-09-11 18:32:33 +00003218 return initFromFloatAPInt(api);
3219 else if (api.getBitWidth()==64)
3220 return initFromDoubleAPInt(api);
3221 else if (api.getBitWidth()==80)
3222 return initFromF80LongDoubleAPInt(api);
Anton Korobeynikov13e8c7e2009-08-21 22:10:30 +00003223 else if (api.getBitWidth()==128)
3224 return (isIEEE ?
3225 initFromQuadrupleAPInt(api) : initFromPPCDoubleDoubleAPInt(api));
Dale Johannesen245dceb2007-09-11 18:32:33 +00003226 else
Torok Edwinfbcc6632009-07-14 16:55:14 +00003227 llvm_unreachable(0);
Dale Johannesen245dceb2007-09-11 18:32:33 +00003228}
3229
Nadav Rotem7cc6d122011-02-17 21:22:27 +00003230APFloat
3231APFloat::getAllOnesValue(unsigned BitWidth, bool isIEEE)
3232{
3233 return APFloat(APInt::getAllOnesValue(BitWidth), isIEEE);
3234}
3235
John McCall29b5c282009-12-24 08:56:26 +00003236APFloat APFloat::getLargest(const fltSemantics &Sem, bool Negative) {
3237 APFloat Val(Sem, fcNormal, Negative);
3238
3239 // We want (in interchange format):
3240 // sign = {Negative}
3241 // exponent = 1..10
3242 // significand = 1..1
3243
3244 Val.exponent = Sem.maxExponent; // unbiased
3245
3246 // 1-initialize all bits....
3247 Val.zeroSignificand();
3248 integerPart *significand = Val.significandParts();
3249 unsigned N = partCountForBits(Sem.precision);
3250 for (unsigned i = 0; i != N; ++i)
3251 significand[i] = ~((integerPart) 0);
3252
3253 // ...and then clear the top bits for internal consistency.
Eli Friedmanc5322012011-10-12 21:51:36 +00003254 if (Sem.precision % integerPartWidth != 0)
3255 significand[N-1] &=
3256 (((integerPart) 1) << (Sem.precision % integerPartWidth)) - 1;
John McCall29b5c282009-12-24 08:56:26 +00003257
3258 return Val;
3259}
3260
3261APFloat APFloat::getSmallest(const fltSemantics &Sem, bool Negative) {
3262 APFloat Val(Sem, fcNormal, Negative);
3263
3264 // We want (in interchange format):
3265 // sign = {Negative}
3266 // exponent = 0..0
3267 // significand = 0..01
3268
3269 Val.exponent = Sem.minExponent; // unbiased
3270 Val.zeroSignificand();
3271 Val.significandParts()[0] = 1;
3272 return Val;
3273}
3274
3275APFloat APFloat::getSmallestNormalized(const fltSemantics &Sem, bool Negative) {
3276 APFloat Val(Sem, fcNormal, Negative);
3277
3278 // We want (in interchange format):
3279 // sign = {Negative}
3280 // exponent = 0..0
3281 // significand = 10..0
3282
3283 Val.exponent = Sem.minExponent;
3284 Val.zeroSignificand();
Dan Gohmanb452d4e2010-03-24 19:38:02 +00003285 Val.significandParts()[partCountForBits(Sem.precision)-1] |=
Eli Friedmand4330422011-10-12 21:56:19 +00003286 (((integerPart) 1) << ((Sem.precision - 1) % integerPartWidth));
John McCall29b5c282009-12-24 08:56:26 +00003287
3288 return Val;
3289}
3290
Ulrich Weigande1d62f92012-10-29 18:17:42 +00003291APFloat::APFloat(const APInt& api, bool isIEEE) {
Dale Johannesen007aa372007-10-11 18:07:22 +00003292 initFromAPInt(api, isIEEE);
Dale Johannesen245dceb2007-09-11 18:32:33 +00003293}
3294
Ulrich Weigande1d62f92012-10-29 18:17:42 +00003295APFloat::APFloat(float f) {
Jay Foad3447fb02010-11-28 21:04:48 +00003296 initFromAPInt(APInt::floatToBits(f));
Dale Johannesen245dceb2007-09-11 18:32:33 +00003297}
3298
Ulrich Weigande1d62f92012-10-29 18:17:42 +00003299APFloat::APFloat(double d) {
Jay Foad3447fb02010-11-28 21:04:48 +00003300 initFromAPInt(APInt::doubleToBits(d));
Dale Johannesen245dceb2007-09-11 18:32:33 +00003301}
John McCall29b5c282009-12-24 08:56:26 +00003302
3303namespace {
David Blaikie70fdf722012-07-25 18:04:24 +00003304 void append(SmallVectorImpl<char> &Buffer, StringRef Str) {
3305 Buffer.append(Str.begin(), Str.end());
John McCall29b5c282009-12-24 08:56:26 +00003306 }
3307
John McCalle6212ace2009-12-24 12:16:56 +00003308 /// Removes data from the given significand until it is no more
3309 /// precise than is required for the desired precision.
3310 void AdjustToPrecision(APInt &significand,
3311 int &exp, unsigned FormatPrecision) {
3312 unsigned bits = significand.getActiveBits();
3313
3314 // 196/59 is a very slight overestimate of lg_2(10).
3315 unsigned bitsRequired = (FormatPrecision * 196 + 58) / 59;
3316
3317 if (bits <= bitsRequired) return;
3318
3319 unsigned tensRemovable = (bits - bitsRequired) * 59 / 196;
3320 if (!tensRemovable) return;
3321
3322 exp += tensRemovable;
3323
3324 APInt divisor(significand.getBitWidth(), 1);
3325 APInt powten(significand.getBitWidth(), 10);
3326 while (true) {
3327 if (tensRemovable & 1)
3328 divisor *= powten;
3329 tensRemovable >>= 1;
3330 if (!tensRemovable) break;
3331 powten *= powten;
3332 }
3333
3334 significand = significand.udiv(divisor);
3335
3336 // Truncate the significand down to its active bit count, but
3337 // don't try to drop below 32.
John McCalldd5044a2009-12-24 23:18:09 +00003338 unsigned newPrecision = std::max(32U, significand.getActiveBits());
Jay Foad583abbc2010-12-07 08:25:19 +00003339 significand = significand.trunc(newPrecision);
John McCalle6212ace2009-12-24 12:16:56 +00003340 }
3341
3342
John McCall29b5c282009-12-24 08:56:26 +00003343 void AdjustToPrecision(SmallVectorImpl<char> &buffer,
3344 int &exp, unsigned FormatPrecision) {
3345 unsigned N = buffer.size();
3346 if (N <= FormatPrecision) return;
3347
3348 // The most significant figures are the last ones in the buffer.
3349 unsigned FirstSignificant = N - FormatPrecision;
3350
3351 // Round.
3352 // FIXME: this probably shouldn't use 'round half up'.
3353
3354 // Rounding down is just a truncation, except we also want to drop
3355 // trailing zeros from the new result.
3356 if (buffer[FirstSignificant - 1] < '5') {
NAKAMURA Takumi5adeb932012-02-19 03:18:29 +00003357 while (FirstSignificant < N && buffer[FirstSignificant] == '0')
John McCall29b5c282009-12-24 08:56:26 +00003358 FirstSignificant++;
3359
3360 exp += FirstSignificant;
3361 buffer.erase(&buffer[0], &buffer[FirstSignificant]);
3362 return;
3363 }
3364
3365 // Rounding up requires a decimal add-with-carry. If we continue
3366 // the carry, the newly-introduced zeros will just be truncated.
3367 for (unsigned I = FirstSignificant; I != N; ++I) {
3368 if (buffer[I] == '9') {
3369 FirstSignificant++;
3370 } else {
3371 buffer[I]++;
3372 break;
3373 }
3374 }
3375
3376 // If we carried through, we have exactly one digit of precision.
3377 if (FirstSignificant == N) {
3378 exp += FirstSignificant;
3379 buffer.clear();
3380 buffer.push_back('1');
3381 return;
3382 }
3383
3384 exp += FirstSignificant;
3385 buffer.erase(&buffer[0], &buffer[FirstSignificant]);
3386 }
3387}
3388
3389void APFloat::toString(SmallVectorImpl<char> &Str,
3390 unsigned FormatPrecision,
Chris Lattner4c1e4db2010-03-06 19:20:13 +00003391 unsigned FormatMaxPadding) const {
John McCall29b5c282009-12-24 08:56:26 +00003392 switch (category) {
3393 case fcInfinity:
3394 if (isNegative())
3395 return append(Str, "-Inf");
3396 else
3397 return append(Str, "+Inf");
3398
3399 case fcNaN: return append(Str, "NaN");
3400
3401 case fcZero:
3402 if (isNegative())
3403 Str.push_back('-');
3404
3405 if (!FormatMaxPadding)
3406 append(Str, "0.0E+0");
3407 else
3408 Str.push_back('0');
3409 return;
3410
3411 case fcNormal:
3412 break;
3413 }
3414
3415 if (isNegative())
3416 Str.push_back('-');
3417
3418 // Decompose the number into an APInt and an exponent.
3419 int exp = exponent - ((int) semantics->precision - 1);
3420 APInt significand(semantics->precision,
Jeffrey Yasskin7a162882011-07-18 21:45:40 +00003421 makeArrayRef(significandParts(),
3422 partCountForBits(semantics->precision)));
John McCall29b5c282009-12-24 08:56:26 +00003423
John McCalldd5044a2009-12-24 23:18:09 +00003424 // Set FormatPrecision if zero. We want to do this before we
3425 // truncate trailing zeros, as those are part of the precision.
3426 if (!FormatPrecision) {
3427 // It's an interesting question whether to use the nominal
3428 // precision or the active precision here for denormals.
3429
3430 // FormatPrecision = ceil(significandBits / lg_2(10))
3431 FormatPrecision = (semantics->precision * 59 + 195) / 196;
3432 }
3433
John McCall29b5c282009-12-24 08:56:26 +00003434 // Ignore trailing binary zeros.
3435 int trailingZeros = significand.countTrailingZeros();
3436 exp += trailingZeros;
3437 significand = significand.lshr(trailingZeros);
3438
3439 // Change the exponent from 2^e to 10^e.
3440 if (exp == 0) {
3441 // Nothing to do.
3442 } else if (exp > 0) {
3443 // Just shift left.
Jay Foad583abbc2010-12-07 08:25:19 +00003444 significand = significand.zext(semantics->precision + exp);
John McCall29b5c282009-12-24 08:56:26 +00003445 significand <<= exp;
3446 exp = 0;
3447 } else { /* exp < 0 */
3448 int texp = -exp;
3449
3450 // We transform this using the identity:
3451 // (N)(2^-e) == (N)(5^e)(10^-e)
3452 // This means we have to multiply N (the significand) by 5^e.
3453 // To avoid overflow, we have to operate on numbers large
3454 // enough to store N * 5^e:
3455 // log2(N * 5^e) == log2(N) + e * log2(5)
John McCalldd5044a2009-12-24 23:18:09 +00003456 // <= semantics->precision + e * 137 / 59
3457 // (log_2(5) ~ 2.321928 < 2.322034 ~ 137/59)
Dan Gohmanb452d4e2010-03-24 19:38:02 +00003458
Eli Friedman19546412011-10-07 23:40:49 +00003459 unsigned precision = semantics->precision + (137 * texp + 136) / 59;
John McCall29b5c282009-12-24 08:56:26 +00003460
3461 // Multiply significand by 5^e.
3462 // N * 5^0101 == N * 5^(1*1) * 5^(0*2) * 5^(1*4) * 5^(0*8)
Jay Foad583abbc2010-12-07 08:25:19 +00003463 significand = significand.zext(precision);
John McCall29b5c282009-12-24 08:56:26 +00003464 APInt five_to_the_i(precision, 5);
3465 while (true) {
3466 if (texp & 1) significand *= five_to_the_i;
Dan Gohmanb452d4e2010-03-24 19:38:02 +00003467
John McCall29b5c282009-12-24 08:56:26 +00003468 texp >>= 1;
3469 if (!texp) break;
3470 five_to_the_i *= five_to_the_i;
3471 }
3472 }
3473
John McCalle6212ace2009-12-24 12:16:56 +00003474 AdjustToPrecision(significand, exp, FormatPrecision);
3475
John McCall29b5c282009-12-24 08:56:26 +00003476 llvm::SmallVector<char, 256> buffer;
3477
3478 // Fill the buffer.
3479 unsigned precision = significand.getBitWidth();
3480 APInt ten(precision, 10);
3481 APInt digit(precision, 0);
3482
3483 bool inTrail = true;
3484 while (significand != 0) {
3485 // digit <- significand % 10
3486 // significand <- significand / 10
3487 APInt::udivrem(significand, ten, significand, digit);
3488
3489 unsigned d = digit.getZExtValue();
3490
3491 // Drop trailing zeros.
3492 if (inTrail && !d) exp++;
3493 else {
3494 buffer.push_back((char) ('0' + d));
3495 inTrail = false;
3496 }
3497 }
3498
3499 assert(!buffer.empty() && "no characters in buffer!");
3500
3501 // Drop down to FormatPrecision.
3502 // TODO: don't do more precise calculations above than are required.
3503 AdjustToPrecision(buffer, exp, FormatPrecision);
3504
3505 unsigned NDigits = buffer.size();
3506
John McCalldd5044a2009-12-24 23:18:09 +00003507 // Check whether we should use scientific notation.
John McCall29b5c282009-12-24 08:56:26 +00003508 bool FormatScientific;
3509 if (!FormatMaxPadding)
3510 FormatScientific = true;
3511 else {
John McCall29b5c282009-12-24 08:56:26 +00003512 if (exp >= 0) {
John McCalldd5044a2009-12-24 23:18:09 +00003513 // 765e3 --> 765000
3514 // ^^^
3515 // But we shouldn't make the number look more precise than it is.
3516 FormatScientific = ((unsigned) exp > FormatMaxPadding ||
3517 NDigits + (unsigned) exp > FormatPrecision);
John McCall29b5c282009-12-24 08:56:26 +00003518 } else {
John McCalldd5044a2009-12-24 23:18:09 +00003519 // Power of the most significant digit.
3520 int MSD = exp + (int) (NDigits - 1);
3521 if (MSD >= 0) {
John McCall29b5c282009-12-24 08:56:26 +00003522 // 765e-2 == 7.65
John McCalldd5044a2009-12-24 23:18:09 +00003523 FormatScientific = false;
John McCall29b5c282009-12-24 08:56:26 +00003524 } else {
3525 // 765e-5 == 0.00765
3526 // ^ ^^
John McCalldd5044a2009-12-24 23:18:09 +00003527 FormatScientific = ((unsigned) -MSD) > FormatMaxPadding;
John McCall29b5c282009-12-24 08:56:26 +00003528 }
3529 }
John McCall29b5c282009-12-24 08:56:26 +00003530 }
3531
3532 // Scientific formatting is pretty straightforward.
3533 if (FormatScientific) {
3534 exp += (NDigits - 1);
3535
3536 Str.push_back(buffer[NDigits-1]);
3537 Str.push_back('.');
3538 if (NDigits == 1)
3539 Str.push_back('0');
3540 else
3541 for (unsigned I = 1; I != NDigits; ++I)
3542 Str.push_back(buffer[NDigits-1-I]);
3543 Str.push_back('E');
3544
3545 Str.push_back(exp >= 0 ? '+' : '-');
3546 if (exp < 0) exp = -exp;
3547 SmallVector<char, 6> expbuf;
3548 do {
3549 expbuf.push_back((char) ('0' + (exp % 10)));
3550 exp /= 10;
3551 } while (exp);
3552 for (unsigned I = 0, E = expbuf.size(); I != E; ++I)
3553 Str.push_back(expbuf[E-1-I]);
3554 return;
3555 }
3556
3557 // Non-scientific, positive exponents.
3558 if (exp >= 0) {
3559 for (unsigned I = 0; I != NDigits; ++I)
3560 Str.push_back(buffer[NDigits-1-I]);
3561 for (unsigned I = 0; I != (unsigned) exp; ++I)
3562 Str.push_back('0');
3563 return;
3564 }
3565
3566 // Non-scientific, negative exponents.
3567
3568 // The number of digits to the left of the decimal point.
3569 int NWholeDigits = exp + (int) NDigits;
3570
3571 unsigned I = 0;
3572 if (NWholeDigits > 0) {
3573 for (; I != (unsigned) NWholeDigits; ++I)
3574 Str.push_back(buffer[NDigits-I-1]);
3575 Str.push_back('.');
3576 } else {
3577 unsigned NZeros = 1 + (unsigned) -NWholeDigits;
3578
3579 Str.push_back('0');
3580 Str.push_back('.');
3581 for (unsigned Z = 1; Z != NZeros; ++Z)
3582 Str.push_back('0');
3583 }
3584
3585 for (; I != NDigits; ++I)
3586 Str.push_back(buffer[NDigits-I-1]);
3587}
Benjamin Kramer03fd6722011-03-30 15:42:27 +00003588
3589bool APFloat::getExactInverse(APFloat *inv) const {
Chris Lattner0ab5e2c2011-04-15 05:18:47 +00003590 // We can only guarantee the existence of an exact inverse for IEEE floats.
Benjamin Kramer03fd6722011-03-30 15:42:27 +00003591 if (semantics != &IEEEhalf && semantics != &IEEEsingle &&
3592 semantics != &IEEEdouble && semantics != &IEEEquad)
3593 return false;
3594
3595 // Special floats and denormals have no exact inverse.
3596 if (category != fcNormal)
3597 return false;
3598
3599 // Check that the number is a power of two by making sure that only the
3600 // integer bit is set in the significand.
3601 if (significandLSB() != semantics->precision - 1)
3602 return false;
3603
3604 // Get the inverse.
3605 APFloat reciprocal(*semantics, 1ULL);
3606 if (reciprocal.divide(*this, rmNearestTiesToEven) != opOK)
3607 return false;
3608
Benjamin Krameraf0ed952011-03-30 17:02:54 +00003609 // Avoid multiplication with a denormal, it is not safe on all platforms and
3610 // may be slower than a normal division.
3611 if (reciprocal.significandMSB() + 1 < reciprocal.semantics->precision)
3612 return false;
3613
3614 assert(reciprocal.category == fcNormal &&
3615 reciprocal.significandLSB() == reciprocal.semantics->precision - 1);
3616
Benjamin Kramer03fd6722011-03-30 15:42:27 +00003617 if (inv)
3618 *inv = reciprocal;
3619
3620 return true;
3621}