blob: b87ddf9c95b58e404f5deb5f2b3e7b6e033ec9c2 [file] [log] [blame]
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001//===-- APFloat.cpp - Implement APFloat class -----------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-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 Lattnerb39cdde2007-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 Lattner36d26c22007-12-08 19:00:03 +000015#include "llvm/ADT/APFloat.h"
Erick Tryzelaara15d8902009-08-16 23:36:19 +000016#include "llvm/ADT/StringRef.h"
Ted Kremenek1f801fa2008-02-11 17:24:50 +000017#include "llvm/ADT/FoldingSet.h"
Torok Edwinc25e7582009-07-11 20:10:48 +000018#include "llvm/Support/ErrorHandling.h"
Dale Johannesend3b51fd2007-08-24 05:08:11 +000019#include "llvm/Support/MathExtras.h"
John McCall8b3f3302010-02-26 22:20:41 +000020#include <limits.h>
Chris Lattnerfad86b02008-08-17 07:19:36 +000021#include <cstring>
Chris Lattnerb39cdde2007-08-20 22:49:32 +000022
23using namespace llvm;
24
25#define convolve(lhs, rhs) ((lhs) * 4 + (rhs))
26
Neil Bootha30b0ee2007-10-03 22:26:02 +000027/* Assumed in hexadecimal significand parsing, and conversion to
28 hexadecimal strings. */
Chris Lattner9f17eb02008-08-17 04:58:58 +000029#define COMPILE_TIME_ASSERT(cond) extern int CTAssert[(cond) ? 1 : -1]
Chris Lattnerb39cdde2007-08-20 22:49:32 +000030COMPILE_TIME_ASSERT(integerPartWidth % 4 == 0);
31
32namespace llvm {
33
34 /* Represents floating point arithmetic semantics. */
35 struct fltSemantics {
36 /* The largest E such that 2^E is representable; this matches the
37 definition of IEEE 754. */
38 exponent_t maxExponent;
39
40 /* The smallest E such that 2^E is a normalized number; this
41 matches the definition of IEEE 754. */
42 exponent_t minExponent;
43
44 /* Number of bits in the significand. This includes the integer
45 bit. */
Neil Booth7a951ca2007-10-12 15:33:27 +000046 unsigned int precision;
Neil Boothcaf19d72007-10-14 10:29:28 +000047
48 /* True if arithmetic is supported. */
49 unsigned int arithmeticOK;
Chris Lattnerb39cdde2007-08-20 22:49:32 +000050 };
51
Chris Lattnercc4287a2009-10-16 02:13:51 +000052 const fltSemantics APFloat::IEEEhalf = { 15, -14, 11, true };
Neil Boothcaf19d72007-10-14 10:29:28 +000053 const fltSemantics APFloat::IEEEsingle = { 127, -126, 24, true };
54 const fltSemantics APFloat::IEEEdouble = { 1023, -1022, 53, true };
55 const fltSemantics APFloat::IEEEquad = { 16383, -16382, 113, true };
56 const fltSemantics APFloat::x87DoubleExtended = { 16383, -16382, 64, true };
57 const fltSemantics APFloat::Bogus = { 0, 0, 0, true };
Dale Johannesena471c2e2007-10-11 18:07:22 +000058
59 // The PowerPC format consists of two doubles. It does not map cleanly
60 // onto the usual format above. For now only storage of constants of
61 // this type is supported, no arithmetic.
Neil Boothcaf19d72007-10-14 10:29:28 +000062 const fltSemantics APFloat::PPCDoubleDouble = { 1023, -1022, 106, false };
Neil Booth96c74712007-10-12 16:02:31 +000063
64 /* A tight upper bound on number of parts required to hold the value
65 pow(5, power) is
66
Neil Booth686700e2007-10-15 15:00:55 +000067 power * 815 / (351 * integerPartWidth) + 1
Dan Gohman16e02092010-03-24 19:38:02 +000068
Neil Booth96c74712007-10-12 16:02:31 +000069 However, whilst the result may require only this many parts,
70 because we are multiplying two values to get it, the
71 multiplication may require an extra part with the excess part
72 being zero (consider the trivial case of 1 * 1, tcFullMultiply
73 requires two parts to hold the single-part result). So we add an
74 extra one to guarantee enough space whilst multiplying. */
75 const unsigned int maxExponent = 16383;
76 const unsigned int maxPrecision = 113;
77 const unsigned int maxPowerOfFiveExponent = maxExponent + maxPrecision - 1;
Neil Booth686700e2007-10-15 15:00:55 +000078 const unsigned int maxPowerOfFiveParts = 2 + ((maxPowerOfFiveExponent * 815)
79 / (351 * integerPartWidth));
Chris Lattnerb39cdde2007-08-20 22:49:32 +000080}
81
Chris Lattnere213f3f2009-03-12 23:59:55 +000082/* A bunch of private, handy routines. */
Chris Lattnerb39cdde2007-08-20 22:49:32 +000083
Chris Lattnere213f3f2009-03-12 23:59:55 +000084static inline unsigned int
85partCountForBits(unsigned int bits)
86{
87 return ((bits) + integerPartWidth - 1) / integerPartWidth;
88}
Chris Lattnerb39cdde2007-08-20 22:49:32 +000089
Chris Lattnere213f3f2009-03-12 23:59:55 +000090/* Returns 0U-9U. Return values >= 10U are not digits. */
91static inline unsigned int
92decDigitValue(unsigned int c)
93{
94 return c - '0';
95}
Chris Lattnerb39cdde2007-08-20 22:49:32 +000096
Chris Lattnere213f3f2009-03-12 23:59:55 +000097static unsigned int
98hexDigitValue(unsigned int c)
99{
100 unsigned int r;
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000101
Chris Lattnere213f3f2009-03-12 23:59:55 +0000102 r = c - '0';
Dan Gohman16e02092010-03-24 19:38:02 +0000103 if (r <= 9)
Chris Lattnere213f3f2009-03-12 23:59:55 +0000104 return r;
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000105
Chris Lattnere213f3f2009-03-12 23:59:55 +0000106 r = c - 'A';
Dan Gohman16e02092010-03-24 19:38:02 +0000107 if (r <= 5)
Chris Lattnere213f3f2009-03-12 23:59:55 +0000108 return r + 10;
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000109
Chris Lattnere213f3f2009-03-12 23:59:55 +0000110 r = c - 'a';
Dan Gohman16e02092010-03-24 19:38:02 +0000111 if (r <= 5)
Chris Lattnere213f3f2009-03-12 23:59:55 +0000112 return r + 10;
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000113
Chris Lattnere213f3f2009-03-12 23:59:55 +0000114 return -1U;
115}
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000116
Chris Lattnere213f3f2009-03-12 23:59:55 +0000117static inline void
118assertArithmeticOK(const llvm::fltSemantics &semantics) {
Dan Gohman16e02092010-03-24 19:38:02 +0000119 assert(semantics.arithmeticOK &&
120 "Compile-time arithmetic does not support these semantics");
Chris Lattnere213f3f2009-03-12 23:59:55 +0000121}
Neil Boothcaf19d72007-10-14 10:29:28 +0000122
Chris Lattnere213f3f2009-03-12 23:59:55 +0000123/* Return the value of a decimal exponent of the form
124 [+-]ddddddd.
Neil Booth1870f292007-10-14 10:16:12 +0000125
Chris Lattnere213f3f2009-03-12 23:59:55 +0000126 If the exponent overflows, returns a large exponent with the
127 appropriate sign. */
128static int
Erick Tryzelaara15d8902009-08-16 23:36:19 +0000129readExponent(StringRef::iterator begin, StringRef::iterator end)
Chris Lattnere213f3f2009-03-12 23:59:55 +0000130{
131 bool isNegative;
132 unsigned int absExponent;
133 const unsigned int overlargeExponent = 24000; /* FIXME. */
Erick Tryzelaara15d8902009-08-16 23:36:19 +0000134 StringRef::iterator p = begin;
135
136 assert(p != end && "Exponent has no digits");
Neil Booth1870f292007-10-14 10:16:12 +0000137
Chris Lattnere213f3f2009-03-12 23:59:55 +0000138 isNegative = (*p == '-');
Erick Tryzelaara15d8902009-08-16 23:36:19 +0000139 if (*p == '-' || *p == '+') {
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000140 p++;
Erick Tryzelaara15d8902009-08-16 23:36:19 +0000141 assert(p != end && "Exponent has no digits");
142 }
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000143
Chris Lattnere213f3f2009-03-12 23:59:55 +0000144 absExponent = decDigitValue(*p++);
Erick Tryzelaara15d8902009-08-16 23:36:19 +0000145 assert(absExponent < 10U && "Invalid character in exponent");
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000146
Erick Tryzelaara15d8902009-08-16 23:36:19 +0000147 for (; p != end; ++p) {
Chris Lattnere213f3f2009-03-12 23:59:55 +0000148 unsigned int value;
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000149
Chris Lattnere213f3f2009-03-12 23:59:55 +0000150 value = decDigitValue(*p);
Erick Tryzelaara15d8902009-08-16 23:36:19 +0000151 assert(value < 10U && "Invalid character in exponent");
Chris Lattnere213f3f2009-03-12 23:59:55 +0000152
Chris Lattnere213f3f2009-03-12 23:59:55 +0000153 value += absExponent * 10;
154 if (absExponent >= overlargeExponent) {
155 absExponent = overlargeExponent;
Dale Johannesenb1508d12010-08-19 17:58:35 +0000156 p = end; /* outwit assert below */
Chris Lattnere213f3f2009-03-12 23:59:55 +0000157 break;
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000158 }
Chris Lattnere213f3f2009-03-12 23:59:55 +0000159 absExponent = value;
160 }
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000161
Erick Tryzelaara15d8902009-08-16 23:36:19 +0000162 assert(p == end && "Invalid exponent in exponent");
163
Chris Lattnere213f3f2009-03-12 23:59:55 +0000164 if (isNegative)
165 return -(int) absExponent;
166 else
167 return (int) absExponent;
168}
169
170/* This is ugly and needs cleaning up, but I don't immediately see
171 how whilst remaining safe. */
172static int
Erick Tryzelaara15d8902009-08-16 23:36:19 +0000173totalExponent(StringRef::iterator p, StringRef::iterator end,
174 int exponentAdjustment)
Chris Lattnere213f3f2009-03-12 23:59:55 +0000175{
176 int unsignedExponent;
177 bool negative, overflow;
178 int exponent;
179
Erick Tryzelaarc78b33b2009-08-20 23:30:43 +0000180 assert(p != end && "Exponent has no digits");
181
Chris Lattnere213f3f2009-03-12 23:59:55 +0000182 negative = *p == '-';
Dan Gohman16e02092010-03-24 19:38:02 +0000183 if (*p == '-' || *p == '+') {
Chris Lattnere213f3f2009-03-12 23:59:55 +0000184 p++;
Erick Tryzelaarc78b33b2009-08-20 23:30:43 +0000185 assert(p != end && "Exponent has no digits");
186 }
Chris Lattnere213f3f2009-03-12 23:59:55 +0000187
188 unsignedExponent = 0;
189 overflow = false;
Dan Gohman16e02092010-03-24 19:38:02 +0000190 for (; p != end; ++p) {
Chris Lattnere213f3f2009-03-12 23:59:55 +0000191 unsigned int value;
192
193 value = decDigitValue(*p);
Erick Tryzelaara15d8902009-08-16 23:36:19 +0000194 assert(value < 10U && "Invalid character in exponent");
Chris Lattnere213f3f2009-03-12 23:59:55 +0000195
Chris Lattnere213f3f2009-03-12 23:59:55 +0000196 unsignedExponent = unsignedExponent * 10 + value;
Dan Gohman16e02092010-03-24 19:38:02 +0000197 if (unsignedExponent > 65535)
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000198 overflow = true;
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000199 }
200
Dan Gohman16e02092010-03-24 19:38:02 +0000201 if (exponentAdjustment > 65535 || exponentAdjustment < -65536)
Chris Lattnere213f3f2009-03-12 23:59:55 +0000202 overflow = true;
203
Dan Gohman16e02092010-03-24 19:38:02 +0000204 if (!overflow) {
Chris Lattnere213f3f2009-03-12 23:59:55 +0000205 exponent = unsignedExponent;
Dan Gohman16e02092010-03-24 19:38:02 +0000206 if (negative)
Chris Lattnere213f3f2009-03-12 23:59:55 +0000207 exponent = -exponent;
208 exponent += exponentAdjustment;
Dan Gohman16e02092010-03-24 19:38:02 +0000209 if (exponent > 65535 || exponent < -65536)
Chris Lattnere213f3f2009-03-12 23:59:55 +0000210 overflow = true;
211 }
212
Dan Gohman16e02092010-03-24 19:38:02 +0000213 if (overflow)
Chris Lattnere213f3f2009-03-12 23:59:55 +0000214 exponent = negative ? -65536: 65535;
215
216 return exponent;
217}
218
Erick Tryzelaara15d8902009-08-16 23:36:19 +0000219static StringRef::iterator
220skipLeadingZeroesAndAnyDot(StringRef::iterator begin, StringRef::iterator end,
221 StringRef::iterator *dot)
Chris Lattnere213f3f2009-03-12 23:59:55 +0000222{
Erick Tryzelaara15d8902009-08-16 23:36:19 +0000223 StringRef::iterator p = begin;
224 *dot = end;
Dan Gohman16e02092010-03-24 19:38:02 +0000225 while (*p == '0' && p != end)
Chris Lattnere213f3f2009-03-12 23:59:55 +0000226 p++;
227
Dan Gohman16e02092010-03-24 19:38:02 +0000228 if (*p == '.') {
Chris Lattnere213f3f2009-03-12 23:59:55 +0000229 *dot = p++;
Erick Tryzelaara15d8902009-08-16 23:36:19 +0000230
Erick Tryzelaarc78b33b2009-08-20 23:30:43 +0000231 assert(end - begin != 1 && "Significand has no digits");
Erick Tryzelaara15d8902009-08-16 23:36:19 +0000232
Dan Gohman16e02092010-03-24 19:38:02 +0000233 while (*p == '0' && p != end)
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000234 p++;
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000235 }
236
Chris Lattnere213f3f2009-03-12 23:59:55 +0000237 return p;
238}
Neil Booth1870f292007-10-14 10:16:12 +0000239
Chris Lattnere213f3f2009-03-12 23:59:55 +0000240/* Given a normal decimal floating point number of the form
Neil Booth1870f292007-10-14 10:16:12 +0000241
Chris Lattnere213f3f2009-03-12 23:59:55 +0000242 dddd.dddd[eE][+-]ddd
Neil Booth686700e2007-10-15 15:00:55 +0000243
Chris Lattnere213f3f2009-03-12 23:59:55 +0000244 where the decimal point and exponent are optional, fill out the
245 structure D. Exponent is appropriate if the significand is
246 treated as an integer, and normalizedExponent if the significand
247 is taken to have the decimal point after a single leading
248 non-zero digit.
Neil Booth1870f292007-10-14 10:16:12 +0000249
Chris Lattnere213f3f2009-03-12 23:59:55 +0000250 If the value is zero, V->firstSigDigit points to a non-digit, and
251 the return exponent is zero.
252*/
253struct decimalInfo {
254 const char *firstSigDigit;
255 const char *lastSigDigit;
256 int exponent;
257 int normalizedExponent;
258};
Neil Booth1870f292007-10-14 10:16:12 +0000259
Chris Lattnere213f3f2009-03-12 23:59:55 +0000260static void
Erick Tryzelaara15d8902009-08-16 23:36:19 +0000261interpretDecimal(StringRef::iterator begin, StringRef::iterator end,
262 decimalInfo *D)
Chris Lattnere213f3f2009-03-12 23:59:55 +0000263{
Erick Tryzelaara15d8902009-08-16 23:36:19 +0000264 StringRef::iterator dot = end;
265 StringRef::iterator p = skipLeadingZeroesAndAnyDot (begin, end, &dot);
Neil Booth1870f292007-10-14 10:16:12 +0000266
Chris Lattnere213f3f2009-03-12 23:59:55 +0000267 D->firstSigDigit = p;
268 D->exponent = 0;
269 D->normalizedExponent = 0;
270
Erick Tryzelaara15d8902009-08-16 23:36:19 +0000271 for (; p != end; ++p) {
Chris Lattnere213f3f2009-03-12 23:59:55 +0000272 if (*p == '.') {
Erick Tryzelaarc78b33b2009-08-20 23:30:43 +0000273 assert(dot == end && "String contains multiple dots");
Chris Lattnere213f3f2009-03-12 23:59:55 +0000274 dot = p++;
Erick Tryzelaara15d8902009-08-16 23:36:19 +0000275 if (p == end)
276 break;
Neil Booth1870f292007-10-14 10:16:12 +0000277 }
Chris Lattnere213f3f2009-03-12 23:59:55 +0000278 if (decDigitValue(*p) >= 10U)
279 break;
Chris Lattnere213f3f2009-03-12 23:59:55 +0000280 }
Neil Booth1870f292007-10-14 10:16:12 +0000281
Erick Tryzelaara15d8902009-08-16 23:36:19 +0000282 if (p != end) {
Erick Tryzelaarc78b33b2009-08-20 23:30:43 +0000283 assert((*p == 'e' || *p == 'E') && "Invalid character in significand");
284 assert(p != begin && "Significand has no digits");
285 assert((dot == end || p - begin != 1) && "Significand has no digits");
Erick Tryzelaara15d8902009-08-16 23:36:19 +0000286
287 /* p points to the first non-digit in the string */
Erick Tryzelaarc78b33b2009-08-20 23:30:43 +0000288 D->exponent = readExponent(p + 1, end);
Neil Booth1870f292007-10-14 10:16:12 +0000289
Chris Lattnere213f3f2009-03-12 23:59:55 +0000290 /* Implied decimal point? */
Erick Tryzelaara15d8902009-08-16 23:36:19 +0000291 if (dot == end)
Chris Lattnere213f3f2009-03-12 23:59:55 +0000292 dot = p;
Erick Tryzelaara15d8902009-08-16 23:36:19 +0000293 }
Neil Booth1870f292007-10-14 10:16:12 +0000294
Erick Tryzelaara15d8902009-08-16 23:36:19 +0000295 /* If number is all zeroes accept any exponent. */
296 if (p != D->firstSigDigit) {
Chris Lattnere213f3f2009-03-12 23:59:55 +0000297 /* Drop insignificant trailing zeroes. */
Erick Tryzelaara15d8902009-08-16 23:36:19 +0000298 if (p != begin) {
Neil Booth1870f292007-10-14 10:16:12 +0000299 do
Erick Tryzelaara15d8902009-08-16 23:36:19 +0000300 do
301 p--;
302 while (p != begin && *p == '0');
303 while (p != begin && *p == '.');
304 }
Neil Booth1870f292007-10-14 10:16:12 +0000305
Chris Lattnere213f3f2009-03-12 23:59:55 +0000306 /* Adjust the exponents for any decimal point. */
307 D->exponent += static_cast<exponent_t>((dot - p) - (dot > p));
308 D->normalizedExponent = (D->exponent +
309 static_cast<exponent_t>((p - D->firstSigDigit)
310 - (dot > D->firstSigDigit && dot < p)));
Neil Booth1870f292007-10-14 10:16:12 +0000311 }
312
Chris Lattnere213f3f2009-03-12 23:59:55 +0000313 D->lastSigDigit = p;
314}
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000315
Chris Lattnere213f3f2009-03-12 23:59:55 +0000316/* Return the trailing fraction of a hexadecimal number.
317 DIGITVALUE is the first hex digit of the fraction, P points to
318 the next digit. */
319static lostFraction
Erick Tryzelaara15d8902009-08-16 23:36:19 +0000320trailingHexadecimalFraction(StringRef::iterator p, StringRef::iterator end,
321 unsigned int digitValue)
Chris Lattnere213f3f2009-03-12 23:59:55 +0000322{
323 unsigned int hexDigit;
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000324
Chris Lattnere213f3f2009-03-12 23:59:55 +0000325 /* If the first trailing digit isn't 0 or 8 we can work out the
326 fraction immediately. */
Dan Gohman16e02092010-03-24 19:38:02 +0000327 if (digitValue > 8)
Chris Lattnere213f3f2009-03-12 23:59:55 +0000328 return lfMoreThanHalf;
Dan Gohman16e02092010-03-24 19:38:02 +0000329 else if (digitValue < 8 && digitValue > 0)
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000330 return lfLessThanHalf;
Chris Lattnere213f3f2009-03-12 23:59:55 +0000331
332 /* Otherwise we need to find the first non-zero digit. */
Dan Gohman16e02092010-03-24 19:38:02 +0000333 while (*p == '0')
Chris Lattnere213f3f2009-03-12 23:59:55 +0000334 p++;
335
Erick Tryzelaara15d8902009-08-16 23:36:19 +0000336 assert(p != end && "Invalid trailing hexadecimal fraction!");
337
Chris Lattnere213f3f2009-03-12 23:59:55 +0000338 hexDigit = hexDigitValue(*p);
339
340 /* If we ran off the end it is exactly zero or one-half, otherwise
341 a little more. */
Dan Gohman16e02092010-03-24 19:38:02 +0000342 if (hexDigit == -1U)
Chris Lattnere213f3f2009-03-12 23:59:55 +0000343 return digitValue == 0 ? lfExactlyZero: lfExactlyHalf;
344 else
345 return digitValue == 0 ? lfLessThanHalf: lfMoreThanHalf;
346}
347
348/* Return the fraction lost were a bignum truncated losing the least
349 significant BITS bits. */
350static lostFraction
351lostFractionThroughTruncation(const integerPart *parts,
352 unsigned int partCount,
353 unsigned int bits)
354{
355 unsigned int lsb;
356
357 lsb = APInt::tcLSB(parts, partCount);
358
359 /* Note this is guaranteed true if bits == 0, or LSB == -1U. */
Dan Gohman16e02092010-03-24 19:38:02 +0000360 if (bits <= lsb)
Chris Lattnere213f3f2009-03-12 23:59:55 +0000361 return lfExactlyZero;
Dan Gohman16e02092010-03-24 19:38:02 +0000362 if (bits == lsb + 1)
Chris Lattnere213f3f2009-03-12 23:59:55 +0000363 return lfExactlyHalf;
Dan Gohman16e02092010-03-24 19:38:02 +0000364 if (bits <= partCount * integerPartWidth &&
365 APInt::tcExtractBit(parts, bits - 1))
Chris Lattnere213f3f2009-03-12 23:59:55 +0000366 return lfMoreThanHalf;
367
368 return lfLessThanHalf;
369}
370
371/* Shift DST right BITS bits noting lost fraction. */
372static lostFraction
373shiftRight(integerPart *dst, unsigned int parts, unsigned int bits)
374{
375 lostFraction lost_fraction;
376
377 lost_fraction = lostFractionThroughTruncation(dst, parts, bits);
378
379 APInt::tcShiftRight(dst, parts, bits);
380
381 return lost_fraction;
382}
383
384/* Combine the effect of two lost fractions. */
385static lostFraction
386combineLostFractions(lostFraction moreSignificant,
387 lostFraction lessSignificant)
388{
Dan Gohman16e02092010-03-24 19:38:02 +0000389 if (lessSignificant != lfExactlyZero) {
390 if (moreSignificant == lfExactlyZero)
Chris Lattnere213f3f2009-03-12 23:59:55 +0000391 moreSignificant = lfLessThanHalf;
Dan Gohman16e02092010-03-24 19:38:02 +0000392 else if (moreSignificant == lfExactlyHalf)
Chris Lattnere213f3f2009-03-12 23:59:55 +0000393 moreSignificant = lfMoreThanHalf;
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000394 }
395
Chris Lattnere213f3f2009-03-12 23:59:55 +0000396 return moreSignificant;
397}
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000398
Chris Lattnere213f3f2009-03-12 23:59:55 +0000399/* The error from the true value, in half-ulps, on multiplying two
400 floating point numbers, which differ from the value they
401 approximate by at most HUE1 and HUE2 half-ulps, is strictly less
402 than the returned value.
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000403
Chris Lattnere213f3f2009-03-12 23:59:55 +0000404 See "How to Read Floating Point Numbers Accurately" by William D
405 Clinger. */
406static unsigned int
407HUerrBound(bool inexactMultiply, unsigned int HUerr1, unsigned int HUerr2)
408{
409 assert(HUerr1 < 2 || HUerr2 < 2 || (HUerr1 + HUerr2 < 8));
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000410
Chris Lattnere213f3f2009-03-12 23:59:55 +0000411 if (HUerr1 + HUerr2 == 0)
412 return inexactMultiply * 2; /* <= inexactMultiply half-ulps. */
413 else
414 return inexactMultiply + 2 * (HUerr1 + HUerr2);
415}
Neil Bootha30b0ee2007-10-03 22:26:02 +0000416
Chris Lattnere213f3f2009-03-12 23:59:55 +0000417/* The number of ulps from the boundary (zero, or half if ISNEAREST)
418 when the least significant BITS are truncated. BITS cannot be
419 zero. */
420static integerPart
421ulpsFromBoundary(const integerPart *parts, unsigned int bits, bool isNearest)
422{
423 unsigned int count, partBits;
424 integerPart part, boundary;
Neil Booth33d4c922007-10-07 08:51:21 +0000425
Evan Cheng99ebfa52009-10-27 21:35:42 +0000426 assert(bits != 0);
Neil Bootha30b0ee2007-10-03 22:26:02 +0000427
Chris Lattnere213f3f2009-03-12 23:59:55 +0000428 bits--;
429 count = bits / integerPartWidth;
430 partBits = bits % integerPartWidth + 1;
Neil Booth96c74712007-10-12 16:02:31 +0000431
Chris Lattnere213f3f2009-03-12 23:59:55 +0000432 part = parts[count] & (~(integerPart) 0 >> (integerPartWidth - partBits));
Neil Booth96c74712007-10-12 16:02:31 +0000433
Chris Lattnere213f3f2009-03-12 23:59:55 +0000434 if (isNearest)
435 boundary = (integerPart) 1 << (partBits - 1);
436 else
437 boundary = 0;
438
439 if (count == 0) {
440 if (part - boundary <= boundary - part)
441 return part - boundary;
Neil Booth96c74712007-10-12 16:02:31 +0000442 else
Chris Lattnere213f3f2009-03-12 23:59:55 +0000443 return boundary - part;
Neil Booth96c74712007-10-12 16:02:31 +0000444 }
445
Chris Lattnere213f3f2009-03-12 23:59:55 +0000446 if (part == boundary) {
447 while (--count)
448 if (parts[count])
449 return ~(integerPart) 0; /* A lot. */
Neil Booth96c74712007-10-12 16:02:31 +0000450
Chris Lattnere213f3f2009-03-12 23:59:55 +0000451 return parts[0];
452 } else if (part == boundary - 1) {
453 while (--count)
454 if (~parts[count])
455 return ~(integerPart) 0; /* A lot. */
Neil Booth96c74712007-10-12 16:02:31 +0000456
Chris Lattnere213f3f2009-03-12 23:59:55 +0000457 return -parts[0];
458 }
Neil Booth96c74712007-10-12 16:02:31 +0000459
Chris Lattnere213f3f2009-03-12 23:59:55 +0000460 return ~(integerPart) 0; /* A lot. */
461}
Neil Booth96c74712007-10-12 16:02:31 +0000462
Chris Lattnere213f3f2009-03-12 23:59:55 +0000463/* Place pow(5, power) in DST, and return the number of parts used.
464 DST must be at least one part larger than size of the answer. */
465static unsigned int
466powerOf5(integerPart *dst, unsigned int power)
467{
468 static const integerPart firstEightPowers[] = { 1, 5, 25, 125, 625, 3125,
469 15625, 78125 };
Chris Lattneree167a72009-03-13 00:24:01 +0000470 integerPart pow5s[maxPowerOfFiveParts * 2 + 5];
471 pow5s[0] = 78125 * 5;
Dan Gohman16e02092010-03-24 19:38:02 +0000472
Chris Lattner807926a2009-03-13 00:03:51 +0000473 unsigned int partsCount[16] = { 1 };
Chris Lattnere213f3f2009-03-12 23:59:55 +0000474 integerPart scratch[maxPowerOfFiveParts], *p1, *p2, *pow5;
475 unsigned int result;
Chris Lattnere213f3f2009-03-12 23:59:55 +0000476 assert(power <= maxExponent);
477
478 p1 = dst;
479 p2 = scratch;
480
481 *p1 = firstEightPowers[power & 7];
482 power >>= 3;
483
484 result = 1;
485 pow5 = pow5s;
486
487 for (unsigned int n = 0; power; power >>= 1, n++) {
488 unsigned int pc;
489
490 pc = partsCount[n];
491
492 /* Calculate pow(5,pow(2,n+3)) if we haven't yet. */
493 if (pc == 0) {
494 pc = partsCount[n - 1];
495 APInt::tcFullMultiply(pow5, pow5 - pc, pow5 - pc, pc, pc);
496 pc *= 2;
497 if (pow5[pc - 1] == 0)
498 pc--;
499 partsCount[n] = pc;
Neil Booth96c74712007-10-12 16:02:31 +0000500 }
501
Chris Lattnere213f3f2009-03-12 23:59:55 +0000502 if (power & 1) {
503 integerPart *tmp;
Neil Booth96c74712007-10-12 16:02:31 +0000504
Chris Lattnere213f3f2009-03-12 23:59:55 +0000505 APInt::tcFullMultiply(p2, p1, pow5, result, pc);
506 result += pc;
507 if (p2[result - 1] == 0)
508 result--;
Neil Booth96c74712007-10-12 16:02:31 +0000509
Chris Lattnere213f3f2009-03-12 23:59:55 +0000510 /* Now result is in p1 with partsCount parts and p2 is scratch
511 space. */
512 tmp = p1, p1 = p2, p2 = tmp;
Neil Booth96c74712007-10-12 16:02:31 +0000513 }
514
Chris Lattnere213f3f2009-03-12 23:59:55 +0000515 pow5 += pc;
Neil Booth96c74712007-10-12 16:02:31 +0000516 }
517
Chris Lattnere213f3f2009-03-12 23:59:55 +0000518 if (p1 != dst)
519 APInt::tcAssign(dst, p1, result);
Neil Booth96c74712007-10-12 16:02:31 +0000520
Chris Lattnere213f3f2009-03-12 23:59:55 +0000521 return result;
522}
Neil Booth96c74712007-10-12 16:02:31 +0000523
Chris Lattnere213f3f2009-03-12 23:59:55 +0000524/* Zero at the end to avoid modular arithmetic when adding one; used
525 when rounding up during hexadecimal output. */
526static const char hexDigitsLower[] = "0123456789abcdef0";
527static const char hexDigitsUpper[] = "0123456789ABCDEF0";
528static const char infinityL[] = "infinity";
529static const char infinityU[] = "INFINITY";
530static const char NaNL[] = "nan";
531static const char NaNU[] = "NAN";
Neil Booth96c74712007-10-12 16:02:31 +0000532
Chris Lattnere213f3f2009-03-12 23:59:55 +0000533/* Write out an integerPart in hexadecimal, starting with the most
534 significant nibble. Write out exactly COUNT hexdigits, return
535 COUNT. */
536static unsigned int
537partAsHex (char *dst, integerPart part, unsigned int count,
538 const char *hexDigitChars)
539{
540 unsigned int result = count;
Neil Booth96c74712007-10-12 16:02:31 +0000541
Evan Cheng99ebfa52009-10-27 21:35:42 +0000542 assert(count != 0 && count <= integerPartWidth / 4);
Neil Booth96c74712007-10-12 16:02:31 +0000543
Chris Lattnere213f3f2009-03-12 23:59:55 +0000544 part >>= (integerPartWidth - 4 * count);
545 while (count--) {
546 dst[count] = hexDigitChars[part & 0xf];
547 part >>= 4;
Neil Booth96c74712007-10-12 16:02:31 +0000548 }
549
Chris Lattnere213f3f2009-03-12 23:59:55 +0000550 return result;
551}
Neil Bootha30b0ee2007-10-03 22:26:02 +0000552
Chris Lattnere213f3f2009-03-12 23:59:55 +0000553/* Write out an unsigned decimal integer. */
554static char *
555writeUnsignedDecimal (char *dst, unsigned int n)
556{
557 char buff[40], *p;
Neil Bootha30b0ee2007-10-03 22:26:02 +0000558
Chris Lattnere213f3f2009-03-12 23:59:55 +0000559 p = buff;
560 do
561 *p++ = '0' + n % 10;
562 while (n /= 10);
Neil Bootha30b0ee2007-10-03 22:26:02 +0000563
Chris Lattnere213f3f2009-03-12 23:59:55 +0000564 do
565 *dst++ = *--p;
566 while (p != buff);
Neil Bootha30b0ee2007-10-03 22:26:02 +0000567
Chris Lattnere213f3f2009-03-12 23:59:55 +0000568 return dst;
569}
Neil Bootha30b0ee2007-10-03 22:26:02 +0000570
Chris Lattnere213f3f2009-03-12 23:59:55 +0000571/* Write out a signed decimal integer. */
572static char *
573writeSignedDecimal (char *dst, int value)
574{
575 if (value < 0) {
576 *dst++ = '-';
577 dst = writeUnsignedDecimal(dst, -(unsigned) value);
578 } else
579 dst = writeUnsignedDecimal(dst, value);
Neil Bootha30b0ee2007-10-03 22:26:02 +0000580
Chris Lattnere213f3f2009-03-12 23:59:55 +0000581 return dst;
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000582}
583
584/* Constructors. */
585void
586APFloat::initialize(const fltSemantics *ourSemantics)
587{
588 unsigned int count;
589
590 semantics = ourSemantics;
591 count = partCount();
Dan Gohman16e02092010-03-24 19:38:02 +0000592 if (count > 1)
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000593 significand.parts = new integerPart[count];
594}
595
596void
597APFloat::freeSignificand()
598{
Dan Gohman16e02092010-03-24 19:38:02 +0000599 if (partCount() > 1)
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000600 delete [] significand.parts;
601}
602
603void
604APFloat::assign(const APFloat &rhs)
605{
606 assert(semantics == rhs.semantics);
607
608 sign = rhs.sign;
609 category = rhs.category;
610 exponent = rhs.exponent;
Dale Johannesena471c2e2007-10-11 18:07:22 +0000611 sign2 = rhs.sign2;
612 exponent2 = rhs.exponent2;
Dan Gohman16e02092010-03-24 19:38:02 +0000613 if (category == fcNormal || category == fcNaN)
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000614 copySignificand(rhs);
615}
616
617void
618APFloat::copySignificand(const APFloat &rhs)
619{
Dale Johanneseneaf08942007-08-31 04:03:46 +0000620 assert(category == fcNormal || category == fcNaN);
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000621 assert(rhs.partCount() >= partCount());
622
623 APInt::tcAssign(significandParts(), rhs.significandParts(),
Neil Booth4f881702007-09-26 21:33:42 +0000624 partCount());
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000625}
626
Neil Boothe5e01942007-10-14 10:39:51 +0000627/* Make this number a NaN, with an arbitrary but deterministic value
Dale Johannesen541ed9f2009-01-21 20:32:55 +0000628 for the significand. If double or longer, this is a signalling NaN,
Mike Stumpc5ca7132009-05-30 03:49:43 +0000629 which may not be ideal. If float, this is QNaN(0). */
John McCalle12b7382010-02-28 02:51:25 +0000630void APFloat::makeNaN(bool SNaN, bool Negative, const APInt *fill)
Neil Boothe5e01942007-10-14 10:39:51 +0000631{
632 category = fcNaN;
John McCalle12b7382010-02-28 02:51:25 +0000633 sign = Negative;
634
John McCall165e96b2010-02-28 12:49:50 +0000635 integerPart *significand = significandParts();
636 unsigned numParts = partCount();
637
John McCalle12b7382010-02-28 02:51:25 +0000638 // Set the significand bits to the fill.
John McCall165e96b2010-02-28 12:49:50 +0000639 if (!fill || fill->getNumWords() < numParts)
640 APInt::tcSet(significand, 0, numParts);
641 if (fill) {
John McCalld44c6cc2010-03-01 18:38:45 +0000642 APInt::tcAssign(significand, fill->getRawData(),
643 std::min(fill->getNumWords(), numParts));
John McCall165e96b2010-02-28 12:49:50 +0000644
645 // Zero out the excess bits of the significand.
646 unsigned bitsToPreserve = semantics->precision - 1;
647 unsigned part = bitsToPreserve / 64;
648 bitsToPreserve %= 64;
649 significand[part] &= ((1ULL << bitsToPreserve) - 1);
650 for (part++; part != numParts; ++part)
651 significand[part] = 0;
652 }
653
654 unsigned QNaNBit = semantics->precision - 2;
John McCalle12b7382010-02-28 02:51:25 +0000655
656 if (SNaN) {
657 // We always have to clear the QNaN bit to make it an SNaN.
John McCall165e96b2010-02-28 12:49:50 +0000658 APInt::tcClearBit(significand, QNaNBit);
John McCalle12b7382010-02-28 02:51:25 +0000659
660 // If there are no bits set in the payload, we have to set
661 // *something* to make it a NaN instead of an infinity;
662 // conventionally, this is the next bit down from the QNaN bit.
John McCall165e96b2010-02-28 12:49:50 +0000663 if (APInt::tcIsZero(significand, numParts))
664 APInt::tcSetBit(significand, QNaNBit - 1);
John McCalle12b7382010-02-28 02:51:25 +0000665 } else {
666 // We always have to set the QNaN bit to make it a QNaN.
John McCall165e96b2010-02-28 12:49:50 +0000667 APInt::tcSetBit(significand, QNaNBit);
John McCalle12b7382010-02-28 02:51:25 +0000668 }
John McCall165e96b2010-02-28 12:49:50 +0000669
670 // For x87 extended precision, we want to make a NaN, not a
671 // pseudo-NaN. Maybe we should expose the ability to make
672 // pseudo-NaNs?
673 if (semantics == &APFloat::x87DoubleExtended)
674 APInt::tcSetBit(significand, QNaNBit + 1);
John McCalle12b7382010-02-28 02:51:25 +0000675}
676
677APFloat APFloat::makeNaN(const fltSemantics &Sem, bool SNaN, bool Negative,
678 const APInt *fill) {
679 APFloat value(Sem, uninitialized);
680 value.makeNaN(SNaN, Negative, fill);
681 return value;
Neil Boothe5e01942007-10-14 10:39:51 +0000682}
683
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000684APFloat &
685APFloat::operator=(const APFloat &rhs)
686{
Dan Gohman16e02092010-03-24 19:38:02 +0000687 if (this != &rhs) {
688 if (semantics != rhs.semantics) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000689 freeSignificand();
690 initialize(rhs.semantics);
691 }
692 assign(rhs);
693 }
694
695 return *this;
696}
697
Dale Johannesen343e7702007-08-24 00:56:33 +0000698bool
Dale Johannesen12595d72007-08-24 22:09:56 +0000699APFloat::bitwiseIsEqual(const APFloat &rhs) const {
Dale Johannesen343e7702007-08-24 00:56:33 +0000700 if (this == &rhs)
701 return true;
702 if (semantics != rhs.semantics ||
Dale Johanneseneaf08942007-08-31 04:03:46 +0000703 category != rhs.category ||
704 sign != rhs.sign)
Dale Johannesen343e7702007-08-24 00:56:33 +0000705 return false;
Dan Gohmanb10abe12008-01-29 12:08:20 +0000706 if (semantics==(const llvm::fltSemantics*)&PPCDoubleDouble &&
Dale Johannesena471c2e2007-10-11 18:07:22 +0000707 sign2 != rhs.sign2)
708 return false;
Dale Johanneseneaf08942007-08-31 04:03:46 +0000709 if (category==fcZero || category==fcInfinity)
Dale Johannesen343e7702007-08-24 00:56:33 +0000710 return true;
Dale Johanneseneaf08942007-08-31 04:03:46 +0000711 else if (category==fcNormal && exponent!=rhs.exponent)
712 return false;
Dan Gohmanb10abe12008-01-29 12:08:20 +0000713 else if (semantics==(const llvm::fltSemantics*)&PPCDoubleDouble &&
Dale Johannesena471c2e2007-10-11 18:07:22 +0000714 exponent2!=rhs.exponent2)
715 return false;
Dale Johannesen343e7702007-08-24 00:56:33 +0000716 else {
Dale Johannesen343e7702007-08-24 00:56:33 +0000717 int i= partCount();
718 const integerPart* p=significandParts();
719 const integerPart* q=rhs.significandParts();
720 for (; i>0; i--, p++, q++) {
721 if (*p != *q)
722 return false;
723 }
724 return true;
725 }
726}
727
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000728APFloat::APFloat(const fltSemantics &ourSemantics, integerPart value)
729{
Neil Boothcaf19d72007-10-14 10:29:28 +0000730 assertArithmeticOK(ourSemantics);
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000731 initialize(&ourSemantics);
732 sign = 0;
733 zeroSignificand();
734 exponent = ourSemantics.precision - 1;
735 significandParts()[0] = value;
736 normalize(rmNearestTiesToEven, lfExactlyZero);
737}
738
Chris Lattnerd7bd78e2009-09-17 01:08:43 +0000739APFloat::APFloat(const fltSemantics &ourSemantics) {
740 assertArithmeticOK(ourSemantics);
741 initialize(&ourSemantics);
742 category = fcZero;
743 sign = false;
744}
745
John McCalle12b7382010-02-28 02:51:25 +0000746APFloat::APFloat(const fltSemantics &ourSemantics, uninitializedTag tag) {
747 assertArithmeticOK(ourSemantics);
748 // Allocates storage if necessary but does not initialize it.
749 initialize(&ourSemantics);
750}
Chris Lattnerd7bd78e2009-09-17 01:08:43 +0000751
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000752APFloat::APFloat(const fltSemantics &ourSemantics,
John McCalle12b7382010-02-28 02:51:25 +0000753 fltCategory ourCategory, bool negative)
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000754{
Neil Boothcaf19d72007-10-14 10:29:28 +0000755 assertArithmeticOK(ourSemantics);
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000756 initialize(&ourSemantics);
757 category = ourCategory;
758 sign = negative;
Mike Stumpc5ca7132009-05-30 03:49:43 +0000759 if (category == fcNormal)
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000760 category = fcZero;
Neil Boothe5e01942007-10-14 10:39:51 +0000761 else if (ourCategory == fcNaN)
John McCalle12b7382010-02-28 02:51:25 +0000762 makeNaN();
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000763}
764
Benjamin Kramer38e59892010-07-14 22:38:02 +0000765APFloat::APFloat(const fltSemantics &ourSemantics, StringRef text)
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000766{
Neil Boothcaf19d72007-10-14 10:29:28 +0000767 assertArithmeticOK(ourSemantics);
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000768 initialize(&ourSemantics);
769 convertFromString(text, rmNearestTiesToEven);
770}
771
772APFloat::APFloat(const APFloat &rhs)
773{
774 initialize(rhs.semantics);
775 assign(rhs);
776}
777
778APFloat::~APFloat()
779{
780 freeSignificand();
781}
782
Ted Kremenek1f801fa2008-02-11 17:24:50 +0000783// Profile - This method 'profiles' an APFloat for use with FoldingSet.
784void APFloat::Profile(FoldingSetNodeID& ID) const {
Dale Johannesen7111b022008-10-09 18:53:47 +0000785 ID.Add(bitcastToAPInt());
Ted Kremenek1f801fa2008-02-11 17:24:50 +0000786}
787
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000788unsigned int
789APFloat::partCount() const
790{
Dale Johannesena72a5a02007-09-20 23:47:58 +0000791 return partCountForBits(semantics->precision + 1);
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000792}
793
794unsigned int
795APFloat::semanticsPrecision(const fltSemantics &semantics)
796{
797 return semantics.precision;
798}
799
800const integerPart *
801APFloat::significandParts() const
802{
803 return const_cast<APFloat *>(this)->significandParts();
804}
805
806integerPart *
807APFloat::significandParts()
808{
Dale Johanneseneaf08942007-08-31 04:03:46 +0000809 assert(category == fcNormal || category == fcNaN);
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000810
Evan Cheng99ebfa52009-10-27 21:35:42 +0000811 if (partCount() > 1)
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000812 return significand.parts;
813 else
814 return &significand.part;
815}
816
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000817void
818APFloat::zeroSignificand()
819{
820 category = fcNormal;
821 APInt::tcSet(significandParts(), 0, partCount());
822}
823
824/* Increment an fcNormal floating point number's significand. */
825void
826APFloat::incrementSignificand()
827{
828 integerPart carry;
829
830 carry = APInt::tcIncrement(significandParts(), partCount());
831
832 /* Our callers should never cause us to overflow. */
833 assert(carry == 0);
834}
835
836/* Add the significand of the RHS. Returns the carry flag. */
837integerPart
838APFloat::addSignificand(const APFloat &rhs)
839{
840 integerPart *parts;
841
842 parts = significandParts();
843
844 assert(semantics == rhs.semantics);
845 assert(exponent == rhs.exponent);
846
847 return APInt::tcAdd(parts, rhs.significandParts(), 0, partCount());
848}
849
850/* Subtract the significand of the RHS with a borrow flag. Returns
851 the borrow flag. */
852integerPart
853APFloat::subtractSignificand(const APFloat &rhs, integerPart borrow)
854{
855 integerPart *parts;
856
857 parts = significandParts();
858
859 assert(semantics == rhs.semantics);
860 assert(exponent == rhs.exponent);
861
862 return APInt::tcSubtract(parts, rhs.significandParts(), borrow,
Neil Booth4f881702007-09-26 21:33:42 +0000863 partCount());
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000864}
865
866/* Multiply the significand of the RHS. If ADDEND is non-NULL, add it
867 on to the full-precision result of the multiplication. Returns the
868 lost fraction. */
869lostFraction
870APFloat::multiplySignificand(const APFloat &rhs, const APFloat *addend)
871{
Neil Booth4f881702007-09-26 21:33:42 +0000872 unsigned int omsb; // One, not zero, based MSB.
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000873 unsigned int partsCount, newPartsCount, precision;
874 integerPart *lhsSignificand;
875 integerPart scratch[4];
876 integerPart *fullSignificand;
877 lostFraction lost_fraction;
Dale Johannesen23a98552008-10-09 23:00:39 +0000878 bool ignored;
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000879
880 assert(semantics == rhs.semantics);
881
882 precision = semantics->precision;
883 newPartsCount = partCountForBits(precision * 2);
884
Dan Gohman16e02092010-03-24 19:38:02 +0000885 if (newPartsCount > 4)
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000886 fullSignificand = new integerPart[newPartsCount];
887 else
888 fullSignificand = scratch;
889
890 lhsSignificand = significandParts();
891 partsCount = partCount();
892
893 APInt::tcFullMultiply(fullSignificand, lhsSignificand,
Neil Booth978661d2007-10-06 00:24:48 +0000894 rhs.significandParts(), partsCount, partsCount);
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000895
896 lost_fraction = lfExactlyZero;
897 omsb = APInt::tcMSB(fullSignificand, newPartsCount) + 1;
898 exponent += rhs.exponent;
899
Dan Gohman16e02092010-03-24 19:38:02 +0000900 if (addend) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000901 Significand savedSignificand = significand;
902 const fltSemantics *savedSemantics = semantics;
903 fltSemantics extendedSemantics;
904 opStatus status;
905 unsigned int extendedPrecision;
906
907 /* Normalize our MSB. */
908 extendedPrecision = precision + precision - 1;
Dan Gohman16e02092010-03-24 19:38:02 +0000909 if (omsb != extendedPrecision) {
910 APInt::tcShiftLeft(fullSignificand, newPartsCount,
911 extendedPrecision - omsb);
912 exponent -= extendedPrecision - omsb;
913 }
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000914
915 /* Create new semantics. */
916 extendedSemantics = *semantics;
917 extendedSemantics.precision = extendedPrecision;
918
Dan Gohman16e02092010-03-24 19:38:02 +0000919 if (newPartsCount == 1)
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000920 significand.part = fullSignificand[0];
921 else
922 significand.parts = fullSignificand;
923 semantics = &extendedSemantics;
924
925 APFloat extendedAddend(*addend);
Dale Johannesen23a98552008-10-09 23:00:39 +0000926 status = extendedAddend.convert(extendedSemantics, rmTowardZero, &ignored);
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000927 assert(status == opOK);
928 lost_fraction = addOrSubtractSignificand(extendedAddend, false);
929
930 /* Restore our state. */
Dan Gohman16e02092010-03-24 19:38:02 +0000931 if (newPartsCount == 1)
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000932 fullSignificand[0] = significand.part;
933 significand = savedSignificand;
934 semantics = savedSemantics;
935
936 omsb = APInt::tcMSB(fullSignificand, newPartsCount) + 1;
937 }
938
939 exponent -= (precision - 1);
940
Dan Gohman16e02092010-03-24 19:38:02 +0000941 if (omsb > precision) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000942 unsigned int bits, significantParts;
943 lostFraction lf;
944
945 bits = omsb - precision;
946 significantParts = partCountForBits(omsb);
947 lf = shiftRight(fullSignificand, significantParts, bits);
948 lost_fraction = combineLostFractions(lf, lost_fraction);
949 exponent += bits;
950 }
951
952 APInt::tcAssign(lhsSignificand, fullSignificand, partsCount);
953
Dan Gohman16e02092010-03-24 19:38:02 +0000954 if (newPartsCount > 4)
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000955 delete [] fullSignificand;
956
957 return lost_fraction;
958}
959
960/* Multiply the significands of LHS and RHS to DST. */
961lostFraction
962APFloat::divideSignificand(const APFloat &rhs)
963{
964 unsigned int bit, i, partsCount;
965 const integerPart *rhsSignificand;
966 integerPart *lhsSignificand, *dividend, *divisor;
967 integerPart scratch[4];
968 lostFraction lost_fraction;
969
970 assert(semantics == rhs.semantics);
971
972 lhsSignificand = significandParts();
973 rhsSignificand = rhs.significandParts();
974 partsCount = partCount();
975
Dan Gohman16e02092010-03-24 19:38:02 +0000976 if (partsCount > 2)
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000977 dividend = new integerPart[partsCount * 2];
978 else
979 dividend = scratch;
980
981 divisor = dividend + partsCount;
982
983 /* Copy the dividend and divisor as they will be modified in-place. */
Dan Gohman16e02092010-03-24 19:38:02 +0000984 for (i = 0; i < partsCount; i++) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000985 dividend[i] = lhsSignificand[i];
986 divisor[i] = rhsSignificand[i];
987 lhsSignificand[i] = 0;
988 }
989
990 exponent -= rhs.exponent;
991
992 unsigned int precision = semantics->precision;
993
994 /* Normalize the divisor. */
995 bit = precision - APInt::tcMSB(divisor, partsCount) - 1;
Dan Gohman16e02092010-03-24 19:38:02 +0000996 if (bit) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000997 exponent += bit;
998 APInt::tcShiftLeft(divisor, partsCount, bit);
999 }
1000
1001 /* Normalize the dividend. */
1002 bit = precision - APInt::tcMSB(dividend, partsCount) - 1;
Dan Gohman16e02092010-03-24 19:38:02 +00001003 if (bit) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001004 exponent -= bit;
1005 APInt::tcShiftLeft(dividend, partsCount, bit);
1006 }
1007
Neil Booth96c74712007-10-12 16:02:31 +00001008 /* Ensure the dividend >= divisor initially for the loop below.
1009 Incidentally, this means that the division loop below is
1010 guaranteed to set the integer bit to one. */
Dan Gohman16e02092010-03-24 19:38:02 +00001011 if (APInt::tcCompare(dividend, divisor, partsCount) < 0) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001012 exponent--;
1013 APInt::tcShiftLeft(dividend, partsCount, 1);
1014 assert(APInt::tcCompare(dividend, divisor, partsCount) >= 0);
1015 }
1016
1017 /* Long division. */
Dan Gohman16e02092010-03-24 19:38:02 +00001018 for (bit = precision; bit; bit -= 1) {
1019 if (APInt::tcCompare(dividend, divisor, partsCount) >= 0) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001020 APInt::tcSubtract(dividend, divisor, 0, partsCount);
1021 APInt::tcSetBit(lhsSignificand, bit - 1);
1022 }
1023
1024 APInt::tcShiftLeft(dividend, partsCount, 1);
1025 }
1026
1027 /* Figure out the lost fraction. */
1028 int cmp = APInt::tcCompare(dividend, divisor, partsCount);
1029
Dan Gohman16e02092010-03-24 19:38:02 +00001030 if (cmp > 0)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001031 lost_fraction = lfMoreThanHalf;
Dan Gohman16e02092010-03-24 19:38:02 +00001032 else if (cmp == 0)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001033 lost_fraction = lfExactlyHalf;
Dan Gohman16e02092010-03-24 19:38:02 +00001034 else if (APInt::tcIsZero(dividend, partsCount))
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001035 lost_fraction = lfExactlyZero;
1036 else
1037 lost_fraction = lfLessThanHalf;
1038
Dan Gohman16e02092010-03-24 19:38:02 +00001039 if (partsCount > 2)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001040 delete [] dividend;
1041
1042 return lost_fraction;
1043}
1044
1045unsigned int
1046APFloat::significandMSB() const
1047{
1048 return APInt::tcMSB(significandParts(), partCount());
1049}
1050
1051unsigned int
1052APFloat::significandLSB() const
1053{
1054 return APInt::tcLSB(significandParts(), partCount());
1055}
1056
1057/* Note that a zero result is NOT normalized to fcZero. */
1058lostFraction
1059APFloat::shiftSignificandRight(unsigned int bits)
1060{
1061 /* Our exponent should not overflow. */
1062 assert((exponent_t) (exponent + bits) >= exponent);
1063
1064 exponent += bits;
1065
1066 return shiftRight(significandParts(), partCount(), bits);
1067}
1068
1069/* Shift the significand left BITS bits, subtract BITS from its exponent. */
1070void
1071APFloat::shiftSignificandLeft(unsigned int bits)
1072{
1073 assert(bits < semantics->precision);
1074
Dan Gohman16e02092010-03-24 19:38:02 +00001075 if (bits) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001076 unsigned int partsCount = partCount();
1077
1078 APInt::tcShiftLeft(significandParts(), partsCount, bits);
1079 exponent -= bits;
1080
1081 assert(!APInt::tcIsZero(significandParts(), partsCount));
1082 }
1083}
1084
1085APFloat::cmpResult
1086APFloat::compareAbsoluteValue(const APFloat &rhs) const
1087{
1088 int compare;
1089
1090 assert(semantics == rhs.semantics);
1091 assert(category == fcNormal);
1092 assert(rhs.category == fcNormal);
1093
1094 compare = exponent - rhs.exponent;
1095
1096 /* If exponents are equal, do an unsigned bignum comparison of the
1097 significands. */
Dan Gohman16e02092010-03-24 19:38:02 +00001098 if (compare == 0)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001099 compare = APInt::tcCompare(significandParts(), rhs.significandParts(),
Neil Booth4f881702007-09-26 21:33:42 +00001100 partCount());
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001101
Dan Gohman16e02092010-03-24 19:38:02 +00001102 if (compare > 0)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001103 return cmpGreaterThan;
Dan Gohman16e02092010-03-24 19:38:02 +00001104 else if (compare < 0)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001105 return cmpLessThan;
1106 else
1107 return cmpEqual;
1108}
1109
1110/* Handle overflow. Sign is preserved. We either become infinity or
1111 the largest finite number. */
1112APFloat::opStatus
1113APFloat::handleOverflow(roundingMode rounding_mode)
1114{
1115 /* Infinity? */
Dan Gohman16e02092010-03-24 19:38:02 +00001116 if (rounding_mode == rmNearestTiesToEven ||
1117 rounding_mode == rmNearestTiesToAway ||
1118 (rounding_mode == rmTowardPositive && !sign) ||
1119 (rounding_mode == rmTowardNegative && sign)) {
1120 category = fcInfinity;
1121 return (opStatus) (opOverflow | opInexact);
1122 }
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001123
1124 /* Otherwise we become the largest finite number. */
1125 category = fcNormal;
1126 exponent = semantics->maxExponent;
1127 APInt::tcSetLeastSignificantBits(significandParts(), partCount(),
Neil Booth4f881702007-09-26 21:33:42 +00001128 semantics->precision);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001129
1130 return opInexact;
1131}
1132
Neil Boothb7dea4c2007-10-03 15:16:41 +00001133/* Returns TRUE if, when truncating the current number, with BIT the
1134 new LSB, with the given lost fraction and rounding mode, the result
1135 would need to be rounded away from zero (i.e., by increasing the
1136 signficand). This routine must work for fcZero of both signs, and
1137 fcNormal numbers. */
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001138bool
1139APFloat::roundAwayFromZero(roundingMode rounding_mode,
Neil Boothb7dea4c2007-10-03 15:16:41 +00001140 lostFraction lost_fraction,
1141 unsigned int bit) const
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001142{
Dale Johanneseneaf08942007-08-31 04:03:46 +00001143 /* NaNs and infinities should not have lost fractions. */
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001144 assert(category == fcNormal || category == fcZero);
1145
Neil Boothb7dea4c2007-10-03 15:16:41 +00001146 /* Current callers never pass this so we don't handle it. */
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001147 assert(lost_fraction != lfExactlyZero);
1148
Mike Stumpf3dc0c02009-05-13 23:23:20 +00001149 switch (rounding_mode) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001150 default:
Torok Edwinc23197a2009-07-14 16:55:14 +00001151 llvm_unreachable(0);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001152
1153 case rmNearestTiesToAway:
1154 return lost_fraction == lfExactlyHalf || lost_fraction == lfMoreThanHalf;
1155
1156 case rmNearestTiesToEven:
Dan Gohman16e02092010-03-24 19:38:02 +00001157 if (lost_fraction == lfMoreThanHalf)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001158 return true;
1159
1160 /* Our zeroes don't have a significand to test. */
Dan Gohman16e02092010-03-24 19:38:02 +00001161 if (lost_fraction == lfExactlyHalf && category != fcZero)
Neil Boothb7dea4c2007-10-03 15:16:41 +00001162 return APInt::tcExtractBit(significandParts(), bit);
Chris Lattnerb39cdde2007-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 }
1175}
1176
1177APFloat::opStatus
1178APFloat::normalize(roundingMode rounding_mode,
Neil Booth4f881702007-09-26 21:33:42 +00001179 lostFraction lost_fraction)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001180{
Neil Booth4f881702007-09-26 21:33:42 +00001181 unsigned int omsb; /* One, not zero, based MSB. */
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001182 int exponentChange;
1183
Dan Gohman16e02092010-03-24 19:38:02 +00001184 if (category != fcNormal)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001185 return opOK;
1186
1187 /* Before rounding normalize the exponent of fcNormal numbers. */
1188 omsb = significandMSB() + 1;
1189
Dan Gohman16e02092010-03-24 19:38:02 +00001190 if (omsb) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001191 /* OMSB is numbered from 1. We want to place it in the integer
1192 bit numbered PRECISON if possible, with a compensating change in
1193 the exponent. */
1194 exponentChange = omsb - semantics->precision;
1195
1196 /* If the resulting exponent is too high, overflow according to
1197 the rounding mode. */
Dan Gohman16e02092010-03-24 19:38:02 +00001198 if (exponent + exponentChange > semantics->maxExponent)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001199 return handleOverflow(rounding_mode);
1200
1201 /* Subnormal numbers have exponent minExponent, and their MSB
1202 is forced based on that. */
Dan Gohman16e02092010-03-24 19:38:02 +00001203 if (exponent + exponentChange < semantics->minExponent)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001204 exponentChange = semantics->minExponent - exponent;
1205
1206 /* Shifting left is easy as we don't lose precision. */
Dan Gohman16e02092010-03-24 19:38:02 +00001207 if (exponentChange < 0) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001208 assert(lost_fraction == lfExactlyZero);
1209
1210 shiftSignificandLeft(-exponentChange);
1211
1212 return opOK;
1213 }
1214
Dan Gohman16e02092010-03-24 19:38:02 +00001215 if (exponentChange > 0) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001216 lostFraction lf;
1217
1218 /* Shift right and capture any new lost fraction. */
1219 lf = shiftSignificandRight(exponentChange);
1220
1221 lost_fraction = combineLostFractions(lf, lost_fraction);
1222
1223 /* Keep OMSB up-to-date. */
Dan Gohman16e02092010-03-24 19:38:02 +00001224 if (omsb > (unsigned) exponentChange)
Neil Booth96c74712007-10-12 16:02:31 +00001225 omsb -= exponentChange;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001226 else
Neil Booth4f881702007-09-26 21:33:42 +00001227 omsb = 0;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001228 }
1229 }
1230
1231 /* Now round the number according to rounding_mode given the lost
1232 fraction. */
1233
1234 /* As specified in IEEE 754, since we do not trap we do not report
1235 underflow for exact results. */
Dan Gohman16e02092010-03-24 19:38:02 +00001236 if (lost_fraction == lfExactlyZero) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001237 /* Canonicalize zeroes. */
Dan Gohman16e02092010-03-24 19:38:02 +00001238 if (omsb == 0)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001239 category = fcZero;
1240
1241 return opOK;
1242 }
1243
1244 /* Increment the significand if we're rounding away from zero. */
Dan Gohman16e02092010-03-24 19:38:02 +00001245 if (roundAwayFromZero(rounding_mode, lost_fraction, 0)) {
1246 if (omsb == 0)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001247 exponent = semantics->minExponent;
1248
1249 incrementSignificand();
1250 omsb = significandMSB() + 1;
1251
1252 /* Did the significand increment overflow? */
Dan Gohman16e02092010-03-24 19:38:02 +00001253 if (omsb == (unsigned) semantics->precision + 1) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001254 /* Renormalize by incrementing the exponent and shifting our
Neil Booth4f881702007-09-26 21:33:42 +00001255 significand right one. However if we already have the
1256 maximum exponent we overflow to infinity. */
Dan Gohman16e02092010-03-24 19:38:02 +00001257 if (exponent == semantics->maxExponent) {
Neil Booth4f881702007-09-26 21:33:42 +00001258 category = fcInfinity;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001259
Neil Booth4f881702007-09-26 21:33:42 +00001260 return (opStatus) (opOverflow | opInexact);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001261 }
1262
1263 shiftSignificandRight(1);
1264
1265 return opInexact;
1266 }
1267 }
1268
1269 /* The normal case - we were and are not denormal, and any
1270 significand increment above didn't overflow. */
Dan Gohman16e02092010-03-24 19:38:02 +00001271 if (omsb == semantics->precision)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001272 return opInexact;
1273
1274 /* We have a non-zero denormal. */
1275 assert(omsb < semantics->precision);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001276
1277 /* Canonicalize zeroes. */
Dan Gohman16e02092010-03-24 19:38:02 +00001278 if (omsb == 0)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001279 category = fcZero;
1280
1281 /* The fcZero case is a denormal that underflowed to zero. */
1282 return (opStatus) (opUnderflow | opInexact);
1283}
1284
1285APFloat::opStatus
1286APFloat::addOrSubtractSpecials(const APFloat &rhs, bool subtract)
1287{
Mike Stumpf3dc0c02009-05-13 23:23:20 +00001288 switch (convolve(category, rhs.category)) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001289 default:
Torok Edwinc23197a2009-07-14 16:55:14 +00001290 llvm_unreachable(0);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001291
Dale Johanneseneaf08942007-08-31 04:03:46 +00001292 case convolve(fcNaN, fcZero):
1293 case convolve(fcNaN, fcNormal):
1294 case convolve(fcNaN, fcInfinity):
1295 case convolve(fcNaN, fcNaN):
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001296 case convolve(fcNormal, fcZero):
1297 case convolve(fcInfinity, fcNormal):
1298 case convolve(fcInfinity, fcZero):
1299 return opOK;
1300
Dale Johanneseneaf08942007-08-31 04:03:46 +00001301 case convolve(fcZero, fcNaN):
1302 case convolve(fcNormal, fcNaN):
1303 case convolve(fcInfinity, fcNaN):
1304 category = fcNaN;
1305 copySignificand(rhs);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001306 return opOK;
1307
1308 case convolve(fcNormal, fcInfinity):
1309 case convolve(fcZero, fcInfinity):
1310 category = fcInfinity;
1311 sign = rhs.sign ^ subtract;
1312 return opOK;
1313
1314 case convolve(fcZero, fcNormal):
1315 assign(rhs);
1316 sign = rhs.sign ^ subtract;
1317 return opOK;
1318
1319 case convolve(fcZero, fcZero):
1320 /* Sign depends on rounding mode; handled by caller. */
1321 return opOK;
1322
1323 case convolve(fcInfinity, fcInfinity):
1324 /* Differently signed infinities can only be validly
1325 subtracted. */
Dan Gohman16e02092010-03-24 19:38:02 +00001326 if (((sign ^ rhs.sign)!=0) != subtract) {
Neil Boothe5e01942007-10-14 10:39:51 +00001327 makeNaN();
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001328 return opInvalidOp;
1329 }
1330
1331 return opOK;
1332
1333 case convolve(fcNormal, fcNormal):
1334 return opDivByZero;
1335 }
1336}
1337
1338/* Add or subtract two normal numbers. */
1339lostFraction
1340APFloat::addOrSubtractSignificand(const APFloat &rhs, bool subtract)
1341{
1342 integerPart carry;
1343 lostFraction lost_fraction;
1344 int bits;
1345
1346 /* Determine if the operation on the absolute values is effectively
1347 an addition or subtraction. */
Hartmut Kaiser8df77a92007-10-25 23:15:31 +00001348 subtract ^= (sign ^ rhs.sign) ? true : false;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001349
1350 /* Are we bigger exponent-wise than the RHS? */
1351 bits = exponent - rhs.exponent;
1352
1353 /* Subtraction is more subtle than one might naively expect. */
Dan Gohman16e02092010-03-24 19:38:02 +00001354 if (subtract) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001355 APFloat temp_rhs(rhs);
1356 bool reverse;
1357
Chris Lattnerada530b2007-08-24 03:02:34 +00001358 if (bits == 0) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001359 reverse = compareAbsoluteValue(temp_rhs) == cmpLessThan;
1360 lost_fraction = lfExactlyZero;
Chris Lattnerada530b2007-08-24 03:02:34 +00001361 } else if (bits > 0) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001362 lost_fraction = temp_rhs.shiftSignificandRight(bits - 1);
1363 shiftSignificandLeft(1);
1364 reverse = false;
Chris Lattnerada530b2007-08-24 03:02:34 +00001365 } else {
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001366 lost_fraction = shiftSignificandRight(-bits - 1);
1367 temp_rhs.shiftSignificandLeft(1);
1368 reverse = true;
1369 }
1370
Chris Lattnerada530b2007-08-24 03:02:34 +00001371 if (reverse) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001372 carry = temp_rhs.subtractSignificand
Neil Booth4f881702007-09-26 21:33:42 +00001373 (*this, lost_fraction != lfExactlyZero);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001374 copySignificand(temp_rhs);
1375 sign = !sign;
1376 } else {
1377 carry = subtractSignificand
Neil Booth4f881702007-09-26 21:33:42 +00001378 (temp_rhs, lost_fraction != lfExactlyZero);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001379 }
1380
1381 /* Invert the lost fraction - it was on the RHS and
1382 subtracted. */
Dan Gohman16e02092010-03-24 19:38:02 +00001383 if (lost_fraction == lfLessThanHalf)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001384 lost_fraction = lfMoreThanHalf;
Dan Gohman16e02092010-03-24 19:38:02 +00001385 else if (lost_fraction == lfMoreThanHalf)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001386 lost_fraction = lfLessThanHalf;
1387
1388 /* The code above is intended to ensure that no borrow is
1389 necessary. */
1390 assert(!carry);
1391 } else {
Dan Gohman16e02092010-03-24 19:38:02 +00001392 if (bits > 0) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001393 APFloat temp_rhs(rhs);
1394
1395 lost_fraction = temp_rhs.shiftSignificandRight(bits);
1396 carry = addSignificand(temp_rhs);
1397 } else {
1398 lost_fraction = shiftSignificandRight(-bits);
1399 carry = addSignificand(rhs);
1400 }
1401
1402 /* We have a guard bit; generating a carry cannot happen. */
1403 assert(!carry);
1404 }
1405
1406 return lost_fraction;
1407}
1408
1409APFloat::opStatus
1410APFloat::multiplySpecials(const APFloat &rhs)
1411{
Mike Stumpf3dc0c02009-05-13 23:23:20 +00001412 switch (convolve(category, rhs.category)) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001413 default:
Torok Edwinc23197a2009-07-14 16:55:14 +00001414 llvm_unreachable(0);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001415
Dale Johanneseneaf08942007-08-31 04:03:46 +00001416 case convolve(fcNaN, fcZero):
1417 case convolve(fcNaN, fcNormal):
1418 case convolve(fcNaN, fcInfinity):
1419 case convolve(fcNaN, fcNaN):
1420 return opOK;
1421
1422 case convolve(fcZero, fcNaN):
1423 case convolve(fcNormal, fcNaN):
1424 case convolve(fcInfinity, fcNaN):
1425 category = fcNaN;
1426 copySignificand(rhs);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001427 return opOK;
1428
1429 case convolve(fcNormal, fcInfinity):
1430 case convolve(fcInfinity, fcNormal):
1431 case convolve(fcInfinity, fcInfinity):
1432 category = fcInfinity;
1433 return opOK;
1434
1435 case convolve(fcZero, fcNormal):
1436 case convolve(fcNormal, fcZero):
1437 case convolve(fcZero, fcZero):
1438 category = fcZero;
1439 return opOK;
1440
1441 case convolve(fcZero, fcInfinity):
1442 case convolve(fcInfinity, fcZero):
Neil Boothe5e01942007-10-14 10:39:51 +00001443 makeNaN();
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001444 return opInvalidOp;
1445
1446 case convolve(fcNormal, fcNormal):
1447 return opOK;
1448 }
1449}
1450
1451APFloat::opStatus
1452APFloat::divideSpecials(const APFloat &rhs)
1453{
Mike Stumpf3dc0c02009-05-13 23:23:20 +00001454 switch (convolve(category, rhs.category)) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001455 default:
Torok Edwinc23197a2009-07-14 16:55:14 +00001456 llvm_unreachable(0);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001457
Dale Johanneseneaf08942007-08-31 04:03:46 +00001458 case convolve(fcNaN, fcZero):
1459 case convolve(fcNaN, fcNormal):
1460 case convolve(fcNaN, fcInfinity):
1461 case convolve(fcNaN, fcNaN):
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001462 case convolve(fcInfinity, fcZero):
1463 case convolve(fcInfinity, fcNormal):
1464 case convolve(fcZero, fcInfinity):
1465 case convolve(fcZero, fcNormal):
1466 return opOK;
1467
Dale Johanneseneaf08942007-08-31 04:03:46 +00001468 case convolve(fcZero, fcNaN):
1469 case convolve(fcNormal, fcNaN):
1470 case convolve(fcInfinity, fcNaN):
1471 category = fcNaN;
1472 copySignificand(rhs);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001473 return opOK;
1474
1475 case convolve(fcNormal, fcInfinity):
1476 category = fcZero;
1477 return opOK;
1478
1479 case convolve(fcNormal, fcZero):
1480 category = fcInfinity;
1481 return opDivByZero;
1482
1483 case convolve(fcInfinity, fcInfinity):
1484 case convolve(fcZero, fcZero):
Neil Boothe5e01942007-10-14 10:39:51 +00001485 makeNaN();
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001486 return opInvalidOp;
1487
1488 case convolve(fcNormal, fcNormal):
1489 return opOK;
1490 }
1491}
1492
Dale Johannesened6af242009-01-21 00:35:19 +00001493APFloat::opStatus
1494APFloat::modSpecials(const APFloat &rhs)
1495{
Mike Stumpf3dc0c02009-05-13 23:23:20 +00001496 switch (convolve(category, rhs.category)) {
Dale Johannesened6af242009-01-21 00:35:19 +00001497 default:
Torok Edwinc23197a2009-07-14 16:55:14 +00001498 llvm_unreachable(0);
Dale Johannesened6af242009-01-21 00:35:19 +00001499
1500 case convolve(fcNaN, fcZero):
1501 case convolve(fcNaN, fcNormal):
1502 case convolve(fcNaN, fcInfinity):
1503 case convolve(fcNaN, fcNaN):
1504 case convolve(fcZero, fcInfinity):
1505 case convolve(fcZero, fcNormal):
1506 case convolve(fcNormal, fcInfinity):
1507 return opOK;
1508
1509 case convolve(fcZero, fcNaN):
1510 case convolve(fcNormal, fcNaN):
1511 case convolve(fcInfinity, fcNaN):
1512 category = fcNaN;
1513 copySignificand(rhs);
1514 return opOK;
1515
1516 case convolve(fcNormal, fcZero):
1517 case convolve(fcInfinity, fcZero):
1518 case convolve(fcInfinity, fcNormal):
1519 case convolve(fcInfinity, fcInfinity):
1520 case convolve(fcZero, fcZero):
1521 makeNaN();
1522 return opInvalidOp;
1523
1524 case convolve(fcNormal, fcNormal):
1525 return opOK;
1526 }
1527}
1528
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001529/* Change sign. */
1530void
1531APFloat::changeSign()
1532{
1533 /* Look mummy, this one's easy. */
1534 sign = !sign;
1535}
1536
Dale Johannesene15c2db2007-08-31 23:35:31 +00001537void
1538APFloat::clearSign()
1539{
1540 /* So is this one. */
1541 sign = 0;
1542}
1543
1544void
1545APFloat::copySign(const APFloat &rhs)
1546{
1547 /* And this one. */
1548 sign = rhs.sign;
1549}
1550
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001551/* Normalized addition or subtraction. */
1552APFloat::opStatus
1553APFloat::addOrSubtract(const APFloat &rhs, roundingMode rounding_mode,
Neil Booth4f881702007-09-26 21:33:42 +00001554 bool subtract)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001555{
1556 opStatus fs;
1557
Neil Boothcaf19d72007-10-14 10:29:28 +00001558 assertArithmeticOK(*semantics);
1559
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001560 fs = addOrSubtractSpecials(rhs, subtract);
1561
1562 /* This return code means it was not a simple case. */
Dan Gohman16e02092010-03-24 19:38:02 +00001563 if (fs == opDivByZero) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001564 lostFraction lost_fraction;
1565
1566 lost_fraction = addOrSubtractSignificand(rhs, subtract);
1567 fs = normalize(rounding_mode, lost_fraction);
1568
1569 /* Can only be zero if we lost no fraction. */
1570 assert(category != fcZero || lost_fraction == lfExactlyZero);
1571 }
1572
1573 /* If two numbers add (exactly) to zero, IEEE 754 decrees it is a
1574 positive zero unless rounding to minus infinity, except that
1575 adding two like-signed zeroes gives that zero. */
Dan Gohman16e02092010-03-24 19:38:02 +00001576 if (category == fcZero) {
1577 if (rhs.category != fcZero || (sign == rhs.sign) == subtract)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001578 sign = (rounding_mode == rmTowardNegative);
1579 }
1580
1581 return fs;
1582}
1583
1584/* Normalized addition. */
1585APFloat::opStatus
1586APFloat::add(const APFloat &rhs, roundingMode rounding_mode)
1587{
1588 return addOrSubtract(rhs, rounding_mode, false);
1589}
1590
1591/* Normalized subtraction. */
1592APFloat::opStatus
1593APFloat::subtract(const APFloat &rhs, roundingMode rounding_mode)
1594{
1595 return addOrSubtract(rhs, rounding_mode, true);
1596}
1597
1598/* Normalized multiply. */
1599APFloat::opStatus
1600APFloat::multiply(const APFloat &rhs, roundingMode rounding_mode)
1601{
1602 opStatus fs;
1603
Neil Boothcaf19d72007-10-14 10:29:28 +00001604 assertArithmeticOK(*semantics);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001605 sign ^= rhs.sign;
1606 fs = multiplySpecials(rhs);
1607
Dan Gohman16e02092010-03-24 19:38:02 +00001608 if (category == fcNormal) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001609 lostFraction lost_fraction = multiplySignificand(rhs, 0);
1610 fs = normalize(rounding_mode, lost_fraction);
Dan Gohman16e02092010-03-24 19:38:02 +00001611 if (lost_fraction != lfExactlyZero)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001612 fs = (opStatus) (fs | opInexact);
1613 }
1614
1615 return fs;
1616}
1617
1618/* Normalized divide. */
1619APFloat::opStatus
1620APFloat::divide(const APFloat &rhs, roundingMode rounding_mode)
1621{
1622 opStatus fs;
1623
Neil Boothcaf19d72007-10-14 10:29:28 +00001624 assertArithmeticOK(*semantics);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001625 sign ^= rhs.sign;
1626 fs = divideSpecials(rhs);
1627
Dan Gohman16e02092010-03-24 19:38:02 +00001628 if (category == fcNormal) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001629 lostFraction lost_fraction = divideSignificand(rhs);
1630 fs = normalize(rounding_mode, lost_fraction);
Dan Gohman16e02092010-03-24 19:38:02 +00001631 if (lost_fraction != lfExactlyZero)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001632 fs = (opStatus) (fs | opInexact);
1633 }
1634
1635 return fs;
1636}
1637
Dale Johannesen24b66a82009-01-20 18:35:05 +00001638/* Normalized remainder. This is not currently correct in all cases. */
1639APFloat::opStatus
1640APFloat::remainder(const APFloat &rhs)
1641{
1642 opStatus fs;
1643 APFloat V = *this;
1644 unsigned int origSign = sign;
1645
1646 assertArithmeticOK(*semantics);
1647 fs = V.divide(rhs, rmNearestTiesToEven);
1648 if (fs == opDivByZero)
1649 return fs;
1650
1651 int parts = partCount();
1652 integerPart *x = new integerPart[parts];
1653 bool ignored;
1654 fs = V.convertToInteger(x, parts * integerPartWidth, true,
1655 rmNearestTiesToEven, &ignored);
1656 if (fs==opInvalidOp)
1657 return fs;
1658
1659 fs = V.convertFromZeroExtendedInteger(x, parts * integerPartWidth, true,
1660 rmNearestTiesToEven);
1661 assert(fs==opOK); // should always work
1662
1663 fs = V.multiply(rhs, rmNearestTiesToEven);
1664 assert(fs==opOK || fs==opInexact); // should not overflow or underflow
1665
1666 fs = subtract(V, rmNearestTiesToEven);
1667 assert(fs==opOK || fs==opInexact); // likewise
1668
1669 if (isZero())
1670 sign = origSign; // IEEE754 requires this
1671 delete[] x;
1672 return fs;
1673}
1674
Dan Gohman16e02092010-03-24 19:38:02 +00001675/* Normalized llvm frem (C fmod).
Dale Johannesen24b66a82009-01-20 18:35:05 +00001676 This is not currently correct in all cases. */
Dale Johannesene15c2db2007-08-31 23:35:31 +00001677APFloat::opStatus
1678APFloat::mod(const APFloat &rhs, roundingMode rounding_mode)
1679{
1680 opStatus fs;
Neil Boothcaf19d72007-10-14 10:29:28 +00001681 assertArithmeticOK(*semantics);
Dale Johannesened6af242009-01-21 00:35:19 +00001682 fs = modSpecials(rhs);
Dale Johannesene15c2db2007-08-31 23:35:31 +00001683
Dale Johannesened6af242009-01-21 00:35:19 +00001684 if (category == fcNormal && rhs.category == fcNormal) {
1685 APFloat V = *this;
1686 unsigned int origSign = sign;
Dale Johannesene15c2db2007-08-31 23:35:31 +00001687
Dale Johannesened6af242009-01-21 00:35:19 +00001688 fs = V.divide(rhs, rmNearestTiesToEven);
1689 if (fs == opDivByZero)
1690 return fs;
Dale Johannesen58c2e4c2007-09-05 20:39:49 +00001691
Dale Johannesened6af242009-01-21 00:35:19 +00001692 int parts = partCount();
1693 integerPart *x = new integerPart[parts];
1694 bool ignored;
1695 fs = V.convertToInteger(x, parts * integerPartWidth, true,
1696 rmTowardZero, &ignored);
1697 if (fs==opInvalidOp)
1698 return fs;
Dale Johannesen58c2e4c2007-09-05 20:39:49 +00001699
Dale Johannesened6af242009-01-21 00:35:19 +00001700 fs = V.convertFromZeroExtendedInteger(x, parts * integerPartWidth, true,
1701 rmNearestTiesToEven);
1702 assert(fs==opOK); // should always work
Dale Johannesen58c2e4c2007-09-05 20:39:49 +00001703
Dale Johannesened6af242009-01-21 00:35:19 +00001704 fs = V.multiply(rhs, rounding_mode);
1705 assert(fs==opOK || fs==opInexact); // should not overflow or underflow
1706
1707 fs = subtract(V, rounding_mode);
1708 assert(fs==opOK || fs==opInexact); // likewise
1709
1710 if (isZero())
1711 sign = origSign; // IEEE754 requires this
1712 delete[] x;
1713 }
Dale Johannesene15c2db2007-08-31 23:35:31 +00001714 return fs;
1715}
1716
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001717/* Normalized fused-multiply-add. */
1718APFloat::opStatus
1719APFloat::fusedMultiplyAdd(const APFloat &multiplicand,
Neil Booth4f881702007-09-26 21:33:42 +00001720 const APFloat &addend,
1721 roundingMode rounding_mode)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001722{
1723 opStatus fs;
1724
Neil Boothcaf19d72007-10-14 10:29:28 +00001725 assertArithmeticOK(*semantics);
1726
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001727 /* Post-multiplication sign, before addition. */
1728 sign ^= multiplicand.sign;
1729
1730 /* If and only if all arguments are normal do we need to do an
1731 extended-precision calculation. */
Dan Gohman16e02092010-03-24 19:38:02 +00001732 if (category == fcNormal &&
1733 multiplicand.category == fcNormal &&
1734 addend.category == fcNormal) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001735 lostFraction lost_fraction;
1736
1737 lost_fraction = multiplySignificand(multiplicand, &addend);
1738 fs = normalize(rounding_mode, lost_fraction);
Dan Gohman16e02092010-03-24 19:38:02 +00001739 if (lost_fraction != lfExactlyZero)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001740 fs = (opStatus) (fs | opInexact);
1741
1742 /* If two numbers add (exactly) to zero, IEEE 754 decrees it is a
1743 positive zero unless rounding to minus infinity, except that
1744 adding two like-signed zeroes gives that zero. */
Dan Gohman16e02092010-03-24 19:38:02 +00001745 if (category == fcZero && sign != addend.sign)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001746 sign = (rounding_mode == rmTowardNegative);
1747 } else {
1748 fs = multiplySpecials(multiplicand);
1749
1750 /* FS can only be opOK or opInvalidOp. There is no more work
1751 to do in the latter case. The IEEE-754R standard says it is
1752 implementation-defined in this case whether, if ADDEND is a
Dale Johanneseneaf08942007-08-31 04:03:46 +00001753 quiet NaN, we raise invalid op; this implementation does so.
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001754
1755 If we need to do the addition we can do so with normal
1756 precision. */
Dan Gohman16e02092010-03-24 19:38:02 +00001757 if (fs == opOK)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001758 fs = addOrSubtract(addend, rounding_mode, false);
1759 }
1760
1761 return fs;
1762}
1763
1764/* Comparison requires normalized numbers. */
1765APFloat::cmpResult
1766APFloat::compare(const APFloat &rhs) const
1767{
1768 cmpResult result;
1769
Neil Boothcaf19d72007-10-14 10:29:28 +00001770 assertArithmeticOK(*semantics);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001771 assert(semantics == rhs.semantics);
1772
Mike Stumpf3dc0c02009-05-13 23:23:20 +00001773 switch (convolve(category, rhs.category)) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001774 default:
Torok Edwinc23197a2009-07-14 16:55:14 +00001775 llvm_unreachable(0);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001776
Dale Johanneseneaf08942007-08-31 04:03:46 +00001777 case convolve(fcNaN, fcZero):
1778 case convolve(fcNaN, fcNormal):
1779 case convolve(fcNaN, fcInfinity):
1780 case convolve(fcNaN, fcNaN):
1781 case convolve(fcZero, fcNaN):
1782 case convolve(fcNormal, fcNaN):
1783 case convolve(fcInfinity, fcNaN):
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001784 return cmpUnordered;
1785
1786 case convolve(fcInfinity, fcNormal):
1787 case convolve(fcInfinity, fcZero):
1788 case convolve(fcNormal, fcZero):
Dan Gohman16e02092010-03-24 19:38:02 +00001789 if (sign)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001790 return cmpLessThan;
1791 else
1792 return cmpGreaterThan;
1793
1794 case convolve(fcNormal, fcInfinity):
1795 case convolve(fcZero, fcInfinity):
1796 case convolve(fcZero, fcNormal):
Dan Gohman16e02092010-03-24 19:38:02 +00001797 if (rhs.sign)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001798 return cmpGreaterThan;
1799 else
1800 return cmpLessThan;
1801
1802 case convolve(fcInfinity, fcInfinity):
Dan Gohman16e02092010-03-24 19:38:02 +00001803 if (sign == rhs.sign)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001804 return cmpEqual;
Dan Gohman16e02092010-03-24 19:38:02 +00001805 else if (sign)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001806 return cmpLessThan;
1807 else
1808 return cmpGreaterThan;
1809
1810 case convolve(fcZero, fcZero):
1811 return cmpEqual;
1812
1813 case convolve(fcNormal, fcNormal):
1814 break;
1815 }
1816
1817 /* Two normal numbers. Do they have the same sign? */
Dan Gohman16e02092010-03-24 19:38:02 +00001818 if (sign != rhs.sign) {
1819 if (sign)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001820 result = cmpLessThan;
1821 else
1822 result = cmpGreaterThan;
1823 } else {
1824 /* Compare absolute values; invert result if negative. */
1825 result = compareAbsoluteValue(rhs);
1826
Dan Gohman16e02092010-03-24 19:38:02 +00001827 if (sign) {
1828 if (result == cmpLessThan)
Neil Booth4f881702007-09-26 21:33:42 +00001829 result = cmpGreaterThan;
Dan Gohman16e02092010-03-24 19:38:02 +00001830 else if (result == cmpGreaterThan)
Neil Booth4f881702007-09-26 21:33:42 +00001831 result = cmpLessThan;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001832 }
1833 }
1834
1835 return result;
1836}
1837
Dale Johannesen23a98552008-10-09 23:00:39 +00001838/// APFloat::convert - convert a value of one floating point type to another.
1839/// The return value corresponds to the IEEE754 exceptions. *losesInfo
1840/// records whether the transformation lost information, i.e. whether
1841/// converting the result back to the original type will produce the
1842/// original value (this is almost the same as return value==fsOK, but there
1843/// are edge cases where this is not so).
1844
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001845APFloat::opStatus
1846APFloat::convert(const fltSemantics &toSemantics,
Dale Johannesen23a98552008-10-09 23:00:39 +00001847 roundingMode rounding_mode, bool *losesInfo)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001848{
Neil Boothc8db43d2007-09-22 02:56:19 +00001849 lostFraction lostFraction;
1850 unsigned int newPartCount, oldPartCount;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001851 opStatus fs;
Neil Booth4f881702007-09-26 21:33:42 +00001852
Neil Boothcaf19d72007-10-14 10:29:28 +00001853 assertArithmeticOK(*semantics);
Dale Johannesen79f82f92008-04-20 01:34:03 +00001854 assertArithmeticOK(toSemantics);
Neil Boothc8db43d2007-09-22 02:56:19 +00001855 lostFraction = lfExactlyZero;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001856 newPartCount = partCountForBits(toSemantics.precision + 1);
Neil Boothc8db43d2007-09-22 02:56:19 +00001857 oldPartCount = partCount();
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001858
Neil Boothc8db43d2007-09-22 02:56:19 +00001859 /* Handle storage complications. If our new form is wider,
1860 re-allocate our bit pattern into wider storage. If it is
1861 narrower, we ignore the excess parts, but if narrowing to a
Dale Johannesen902ff942007-09-25 17:25:00 +00001862 single part we need to free the old storage.
1863 Be careful not to reference significandParts for zeroes
1864 and infinities, since it aborts. */
Neil Boothc8db43d2007-09-22 02:56:19 +00001865 if (newPartCount > oldPartCount) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001866 integerPart *newParts;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001867 newParts = new integerPart[newPartCount];
1868 APInt::tcSet(newParts, 0, newPartCount);
Dale Johannesen902ff942007-09-25 17:25:00 +00001869 if (category==fcNormal || category==fcNaN)
1870 APInt::tcAssign(newParts, significandParts(), oldPartCount);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001871 freeSignificand();
1872 significand.parts = newParts;
Neil Boothc8db43d2007-09-22 02:56:19 +00001873 } else if (newPartCount < oldPartCount) {
1874 /* Capture any lost fraction through truncation of parts so we get
1875 correct rounding whilst normalizing. */
Dale Johannesen902ff942007-09-25 17:25:00 +00001876 if (category==fcNormal)
1877 lostFraction = lostFractionThroughTruncation
1878 (significandParts(), oldPartCount, toSemantics.precision);
1879 if (newPartCount == 1) {
1880 integerPart newPart = 0;
Neil Booth4f881702007-09-26 21:33:42 +00001881 if (category==fcNormal || category==fcNaN)
Dale Johannesen902ff942007-09-25 17:25:00 +00001882 newPart = significandParts()[0];
1883 freeSignificand();
1884 significand.part = newPart;
1885 }
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001886 }
1887
Dan Gohman16e02092010-03-24 19:38:02 +00001888 if (category == fcNormal) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001889 /* Re-interpret our bit-pattern. */
1890 exponent += toSemantics.precision - semantics->precision;
1891 semantics = &toSemantics;
Neil Boothc8db43d2007-09-22 02:56:19 +00001892 fs = normalize(rounding_mode, lostFraction);
Dale Johannesen23a98552008-10-09 23:00:39 +00001893 *losesInfo = (fs != opOK);
Dale Johannesen902ff942007-09-25 17:25:00 +00001894 } else if (category == fcNaN) {
1895 int shift = toSemantics.precision - semantics->precision;
Dale Johannesenb63fa052008-01-31 18:34:01 +00001896 // Do this now so significandParts gets the right answer
Dale Johannesen2df5eec2008-10-06 22:59:10 +00001897 const fltSemantics *oldSemantics = semantics;
Dale Johannesenb63fa052008-01-31 18:34:01 +00001898 semantics = &toSemantics;
Dale Johannesen23a98552008-10-09 23:00:39 +00001899 *losesInfo = false;
Dale Johannesen902ff942007-09-25 17:25:00 +00001900 // No normalization here, just truncate
1901 if (shift>0)
1902 APInt::tcShiftLeft(significandParts(), newPartCount, shift);
Dale Johannesen2df5eec2008-10-06 22:59:10 +00001903 else if (shift < 0) {
1904 unsigned ushift = -shift;
Dale Johannesen23a98552008-10-09 23:00:39 +00001905 // Figure out if we are losing information. This happens
Dale Johannesen2df5eec2008-10-06 22:59:10 +00001906 // if are shifting out something other than 0s, or if the x87 long
1907 // double input did not have its integer bit set (pseudo-NaN), or if the
1908 // x87 long double input did not have its QNan bit set (because the x87
1909 // hardware sets this bit when converting a lower-precision NaN to
1910 // x87 long double).
1911 if (APInt::tcLSB(significandParts(), newPartCount) < ushift)
Dale Johannesen23a98552008-10-09 23:00:39 +00001912 *losesInfo = true;
Dan Gohman16e02092010-03-24 19:38:02 +00001913 if (oldSemantics == &APFloat::x87DoubleExtended &&
Dale Johannesen2df5eec2008-10-06 22:59:10 +00001914 (!(*significandParts() & 0x8000000000000000ULL) ||
1915 !(*significandParts() & 0x4000000000000000ULL)))
Dale Johannesen23a98552008-10-09 23:00:39 +00001916 *losesInfo = true;
Dale Johannesen2df5eec2008-10-06 22:59:10 +00001917 APInt::tcShiftRight(significandParts(), newPartCount, ushift);
1918 }
Dale Johannesen902ff942007-09-25 17:25:00 +00001919 // gcc forces the Quiet bit on, which means (float)(double)(float_sNan)
1920 // does not give you back the same bits. This is dubious, and we
1921 // don't currently do it. You're really supposed to get
1922 // an invalid operation signal at runtime, but nobody does that.
Dale Johannesen23a98552008-10-09 23:00:39 +00001923 fs = opOK;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001924 } else {
1925 semantics = &toSemantics;
1926 fs = opOK;
Dale Johannesen23a98552008-10-09 23:00:39 +00001927 *losesInfo = false;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001928 }
1929
1930 return fs;
1931}
1932
1933/* Convert a floating point number to an integer according to the
1934 rounding mode. If the rounded integer value is out of range this
Neil Boothee7ae382007-11-01 22:43:37 +00001935 returns an invalid operation exception and the contents of the
1936 destination parts are unspecified. If the rounded value is in
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001937 range but the floating point number is not the exact integer, the C
1938 standard doesn't require an inexact exception to be raised. IEEE
1939 854 does require it so we do that.
1940
1941 Note that for conversions to integer type the C standard requires
1942 round-to-zero to always be used. */
1943APFloat::opStatus
Neil Boothee7ae382007-11-01 22:43:37 +00001944APFloat::convertToSignExtendedInteger(integerPart *parts, unsigned int width,
1945 bool isSigned,
Dale Johannesen23a98552008-10-09 23:00:39 +00001946 roundingMode rounding_mode,
1947 bool *isExact) const
Neil Boothee7ae382007-11-01 22:43:37 +00001948{
1949 lostFraction lost_fraction;
1950 const integerPart *src;
1951 unsigned int dstPartsCount, truncatedBits;
1952
Evan Cheng794a7db2008-11-26 01:11:57 +00001953 assertArithmeticOK(*semantics);
Neil Boothe3d936a2007-11-02 15:10:05 +00001954
Dale Johannesen23a98552008-10-09 23:00:39 +00001955 *isExact = false;
1956
Neil Boothee7ae382007-11-01 22:43:37 +00001957 /* Handle the three special cases first. */
Dan Gohman16e02092010-03-24 19:38:02 +00001958 if (category == fcInfinity || category == fcNaN)
Neil Boothee7ae382007-11-01 22:43:37 +00001959 return opInvalidOp;
1960
1961 dstPartsCount = partCountForBits(width);
1962
Dan Gohman16e02092010-03-24 19:38:02 +00001963 if (category == fcZero) {
Neil Boothee7ae382007-11-01 22:43:37 +00001964 APInt::tcSet(parts, 0, dstPartsCount);
Dale Johannesene4a42452008-10-07 00:40:01 +00001965 // Negative zero can't be represented as an int.
Dale Johannesen23a98552008-10-09 23:00:39 +00001966 *isExact = !sign;
1967 return opOK;
Neil Boothee7ae382007-11-01 22:43:37 +00001968 }
1969
1970 src = significandParts();
1971
1972 /* Step 1: place our absolute value, with any fraction truncated, in
1973 the destination. */
1974 if (exponent < 0) {
1975 /* Our absolute value is less than one; truncate everything. */
1976 APInt::tcSet(parts, 0, dstPartsCount);
Dale Johannesen1f54f582009-01-19 21:17:05 +00001977 /* For exponent -1 the integer bit represents .5, look at that.
1978 For smaller exponents leftmost truncated bit is 0. */
1979 truncatedBits = semantics->precision -1U - exponent;
Neil Boothee7ae382007-11-01 22:43:37 +00001980 } else {
1981 /* We want the most significant (exponent + 1) bits; the rest are
1982 truncated. */
1983 unsigned int bits = exponent + 1U;
1984
1985 /* Hopelessly large in magnitude? */
1986 if (bits > width)
1987 return opInvalidOp;
1988
1989 if (bits < semantics->precision) {
1990 /* We truncate (semantics->precision - bits) bits. */
1991 truncatedBits = semantics->precision - bits;
1992 APInt::tcExtract(parts, dstPartsCount, src, bits, truncatedBits);
1993 } else {
1994 /* We want at least as many bits as are available. */
1995 APInt::tcExtract(parts, dstPartsCount, src, semantics->precision, 0);
1996 APInt::tcShiftLeft(parts, dstPartsCount, bits - semantics->precision);
1997 truncatedBits = 0;
1998 }
1999 }
2000
2001 /* Step 2: work out any lost fraction, and increment the absolute
2002 value if we would round away from zero. */
2003 if (truncatedBits) {
2004 lost_fraction = lostFractionThroughTruncation(src, partCount(),
2005 truncatedBits);
Dan Gohman16e02092010-03-24 19:38:02 +00002006 if (lost_fraction != lfExactlyZero &&
2007 roundAwayFromZero(rounding_mode, lost_fraction, truncatedBits)) {
Neil Boothee7ae382007-11-01 22:43:37 +00002008 if (APInt::tcIncrement(parts, dstPartsCount))
2009 return opInvalidOp; /* Overflow. */
2010 }
2011 } else {
2012 lost_fraction = lfExactlyZero;
2013 }
2014
2015 /* Step 3: check if we fit in the destination. */
2016 unsigned int omsb = APInt::tcMSB(parts, dstPartsCount) + 1;
2017
2018 if (sign) {
2019 if (!isSigned) {
2020 /* Negative numbers cannot be represented as unsigned. */
2021 if (omsb != 0)
2022 return opInvalidOp;
2023 } else {
2024 /* It takes omsb bits to represent the unsigned integer value.
2025 We lose a bit for the sign, but care is needed as the
2026 maximally negative integer is a special case. */
2027 if (omsb == width && APInt::tcLSB(parts, dstPartsCount) + 1 != omsb)
2028 return opInvalidOp;
2029
2030 /* This case can happen because of rounding. */
2031 if (omsb > width)
2032 return opInvalidOp;
2033 }
2034
2035 APInt::tcNegate (parts, dstPartsCount);
2036 } else {
2037 if (omsb >= width + !isSigned)
2038 return opInvalidOp;
2039 }
2040
Dale Johannesen23a98552008-10-09 23:00:39 +00002041 if (lost_fraction == lfExactlyZero) {
2042 *isExact = true;
Neil Boothee7ae382007-11-01 22:43:37 +00002043 return opOK;
Dale Johannesen23a98552008-10-09 23:00:39 +00002044 } else
Neil Boothee7ae382007-11-01 22:43:37 +00002045 return opInexact;
2046}
2047
2048/* Same as convertToSignExtendedInteger, except we provide
2049 deterministic values in case of an invalid operation exception,
2050 namely zero for NaNs and the minimal or maximal value respectively
Dale Johannesen23a98552008-10-09 23:00:39 +00002051 for underflow or overflow.
2052 The *isExact output tells whether the result is exact, in the sense
2053 that converting it back to the original floating point type produces
2054 the original value. This is almost equivalent to result==opOK,
2055 except for negative zeroes.
2056*/
Neil Boothee7ae382007-11-01 22:43:37 +00002057APFloat::opStatus
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002058APFloat::convertToInteger(integerPart *parts, unsigned int width,
Neil Booth4f881702007-09-26 21:33:42 +00002059 bool isSigned,
Dale Johannesen23a98552008-10-09 23:00:39 +00002060 roundingMode rounding_mode, bool *isExact) const
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002061{
Neil Boothee7ae382007-11-01 22:43:37 +00002062 opStatus fs;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002063
Dan Gohman16e02092010-03-24 19:38:02 +00002064 fs = convertToSignExtendedInteger(parts, width, isSigned, rounding_mode,
Dale Johannesen23a98552008-10-09 23:00:39 +00002065 isExact);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002066
Neil Boothee7ae382007-11-01 22:43:37 +00002067 if (fs == opInvalidOp) {
2068 unsigned int bits, dstPartsCount;
2069
2070 dstPartsCount = partCountForBits(width);
2071
2072 if (category == fcNaN)
2073 bits = 0;
2074 else if (sign)
2075 bits = isSigned;
2076 else
2077 bits = width - isSigned;
2078
2079 APInt::tcSetLeastSignificantBits(parts, dstPartsCount, bits);
2080 if (sign && isSigned)
2081 APInt::tcShiftLeft(parts, dstPartsCount, width - 1);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002082 }
2083
Neil Boothee7ae382007-11-01 22:43:37 +00002084 return fs;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002085}
2086
Neil Booth643ce592007-10-07 12:07:53 +00002087/* Convert an unsigned integer SRC to a floating point number,
2088 rounding according to ROUNDING_MODE. The sign of the floating
2089 point number is not modified. */
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002090APFloat::opStatus
Neil Booth643ce592007-10-07 12:07:53 +00002091APFloat::convertFromUnsignedParts(const integerPart *src,
2092 unsigned int srcCount,
2093 roundingMode rounding_mode)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002094{
Neil Booth5477f852007-10-08 14:39:42 +00002095 unsigned int omsb, precision, dstCount;
Neil Booth643ce592007-10-07 12:07:53 +00002096 integerPart *dst;
Neil Booth5477f852007-10-08 14:39:42 +00002097 lostFraction lost_fraction;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002098
Neil Boothcaf19d72007-10-14 10:29:28 +00002099 assertArithmeticOK(*semantics);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002100 category = fcNormal;
Neil Booth5477f852007-10-08 14:39:42 +00002101 omsb = APInt::tcMSB(src, srcCount) + 1;
Neil Booth643ce592007-10-07 12:07:53 +00002102 dst = significandParts();
2103 dstCount = partCount();
Neil Booth5477f852007-10-08 14:39:42 +00002104 precision = semantics->precision;
Neil Booth643ce592007-10-07 12:07:53 +00002105
Neil Booth5477f852007-10-08 14:39:42 +00002106 /* We want the most significant PRECISON bits of SRC. There may not
2107 be that many; extract what we can. */
2108 if (precision <= omsb) {
2109 exponent = omsb - 1;
Neil Booth643ce592007-10-07 12:07:53 +00002110 lost_fraction = lostFractionThroughTruncation(src, srcCount,
Neil Booth5477f852007-10-08 14:39:42 +00002111 omsb - precision);
2112 APInt::tcExtract(dst, dstCount, src, precision, omsb - precision);
2113 } else {
2114 exponent = precision - 1;
2115 lost_fraction = lfExactlyZero;
2116 APInt::tcExtract(dst, dstCount, src, omsb, 0);
Neil Booth643ce592007-10-07 12:07:53 +00002117 }
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002118
2119 return normalize(rounding_mode, lost_fraction);
2120}
2121
Dan Gohman93c276e2008-02-29 01:26:11 +00002122APFloat::opStatus
2123APFloat::convertFromAPInt(const APInt &Val,
2124 bool isSigned,
2125 roundingMode rounding_mode)
2126{
2127 unsigned int partCount = Val.getNumWords();
2128 APInt api = Val;
2129
2130 sign = false;
2131 if (isSigned && api.isNegative()) {
2132 sign = true;
2133 api = -api;
2134 }
2135
2136 return convertFromUnsignedParts(api.getRawData(), partCount, rounding_mode);
2137}
2138
Neil Boothf16c5952007-10-07 12:15:41 +00002139/* Convert a two's complement integer SRC to a floating point number,
2140 rounding according to ROUNDING_MODE. ISSIGNED is true if the
2141 integer is signed, in which case it must be sign-extended. */
2142APFloat::opStatus
2143APFloat::convertFromSignExtendedInteger(const integerPart *src,
2144 unsigned int srcCount,
2145 bool isSigned,
2146 roundingMode rounding_mode)
2147{
2148 opStatus status;
2149
Neil Boothcaf19d72007-10-14 10:29:28 +00002150 assertArithmeticOK(*semantics);
Dan Gohman16e02092010-03-24 19:38:02 +00002151 if (isSigned &&
2152 APInt::tcExtractBit(src, srcCount * integerPartWidth - 1)) {
Neil Boothf16c5952007-10-07 12:15:41 +00002153 integerPart *copy;
2154
2155 /* If we're signed and negative negate a copy. */
2156 sign = true;
2157 copy = new integerPart[srcCount];
2158 APInt::tcAssign(copy, src, srcCount);
2159 APInt::tcNegate(copy, srcCount);
2160 status = convertFromUnsignedParts(copy, srcCount, rounding_mode);
2161 delete [] copy;
2162 } else {
2163 sign = false;
2164 status = convertFromUnsignedParts(src, srcCount, rounding_mode);
2165 }
2166
2167 return status;
2168}
2169
Neil Boothccf596a2007-10-07 11:45:55 +00002170/* FIXME: should this just take a const APInt reference? */
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002171APFloat::opStatus
Neil Boothccf596a2007-10-07 11:45:55 +00002172APFloat::convertFromZeroExtendedInteger(const integerPart *parts,
2173 unsigned int width, bool isSigned,
2174 roundingMode rounding_mode)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002175{
Dale Johannesen910993e2007-09-21 22:09:37 +00002176 unsigned int partCount = partCountForBits(width);
Dale Johannesen910993e2007-09-21 22:09:37 +00002177 APInt api = APInt(width, partCount, parts);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002178
2179 sign = false;
Dan Gohman16e02092010-03-24 19:38:02 +00002180 if (isSigned && APInt::tcExtractBit(parts, width - 1)) {
Dale Johannesencce23a42007-09-30 18:17:01 +00002181 sign = true;
2182 api = -api;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002183 }
2184
Neil Booth7a7bc0f2007-10-07 12:10:57 +00002185 return convertFromUnsignedParts(api.getRawData(), partCount, rounding_mode);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002186}
2187
2188APFloat::opStatus
Benjamin Kramer38e59892010-07-14 22:38:02 +00002189APFloat::convertFromHexadecimalString(StringRef s, roundingMode rounding_mode)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002190{
Erick Tryzelaarf8bc8012009-08-18 18:20:37 +00002191 lostFraction lost_fraction = lfExactlyZero;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002192 integerPart *significand;
2193 unsigned int bitPos, partsCount;
Erick Tryzelaara15d8902009-08-16 23:36:19 +00002194 StringRef::iterator dot, firstSignificantDigit;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002195
2196 zeroSignificand();
2197 exponent = 0;
2198 category = fcNormal;
2199
2200 significand = significandParts();
2201 partsCount = partCount();
2202 bitPos = partsCount * integerPartWidth;
2203
Neil Booth33d4c922007-10-07 08:51:21 +00002204 /* Skip leading zeroes and any (hexa)decimal point. */
Erick Tryzelaarc78b33b2009-08-20 23:30:43 +00002205 StringRef::iterator begin = s.begin();
2206 StringRef::iterator end = s.end();
2207 StringRef::iterator p = skipLeadingZeroesAndAnyDot(begin, end, &dot);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002208 firstSignificantDigit = p;
2209
Dan Gohman16e02092010-03-24 19:38:02 +00002210 for (; p != end;) {
Dale Johannesen386f3e92008-05-14 22:53:25 +00002211 integerPart hex_value;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002212
Dan Gohman16e02092010-03-24 19:38:02 +00002213 if (*p == '.') {
Erick Tryzelaarc78b33b2009-08-20 23:30:43 +00002214 assert(dot == end && "String contains multiple dots");
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002215 dot = p++;
Erick Tryzelaarc78b33b2009-08-20 23:30:43 +00002216 if (p == end) {
2217 break;
2218 }
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002219 }
2220
2221 hex_value = hexDigitValue(*p);
Dan Gohman16e02092010-03-24 19:38:02 +00002222 if (hex_value == -1U) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002223 break;
2224 }
2225
2226 p++;
2227
Erick Tryzelaarc78b33b2009-08-20 23:30:43 +00002228 if (p == end) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002229 break;
Erick Tryzelaara15d8902009-08-16 23:36:19 +00002230 } else {
2231 /* Store the number whilst 4-bit nibbles remain. */
Dan Gohman16e02092010-03-24 19:38:02 +00002232 if (bitPos) {
Erick Tryzelaara15d8902009-08-16 23:36:19 +00002233 bitPos -= 4;
2234 hex_value <<= bitPos % integerPartWidth;
2235 significand[bitPos / integerPartWidth] |= hex_value;
2236 } else {
Erick Tryzelaarc78b33b2009-08-20 23:30:43 +00002237 lost_fraction = trailingHexadecimalFraction(p, end, hex_value);
Dan Gohman16e02092010-03-24 19:38:02 +00002238 while (p != end && hexDigitValue(*p) != -1U)
Erick Tryzelaara15d8902009-08-16 23:36:19 +00002239 p++;
2240 break;
2241 }
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002242 }
2243 }
2244
2245 /* Hex floats require an exponent but not a hexadecimal point. */
Erick Tryzelaarc78b33b2009-08-20 23:30:43 +00002246 assert(p != end && "Hex strings require an exponent");
2247 assert((*p == 'p' || *p == 'P') && "Invalid character in significand");
2248 assert(p != begin && "Significand has no digits");
2249 assert((dot == end || p - begin != 1) && "Significand has no digits");
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002250
2251 /* Ignore the exponent if we are zero. */
Dan Gohman16e02092010-03-24 19:38:02 +00002252 if (p != firstSignificantDigit) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002253 int expAdjustment;
2254
2255 /* Implicit hexadecimal point? */
Erick Tryzelaarc78b33b2009-08-20 23:30:43 +00002256 if (dot == end)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002257 dot = p;
2258
2259 /* Calculate the exponent adjustment implicit in the number of
2260 significant digits. */
Evan Cheng48e8c802008-05-02 21:15:08 +00002261 expAdjustment = static_cast<int>(dot - firstSignificantDigit);
Dan Gohman16e02092010-03-24 19:38:02 +00002262 if (expAdjustment < 0)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002263 expAdjustment++;
2264 expAdjustment = expAdjustment * 4 - 1;
2265
2266 /* Adjust for writing the significand starting at the most
2267 significant nibble. */
2268 expAdjustment += semantics->precision;
2269 expAdjustment -= partsCount * integerPartWidth;
2270
2271 /* Adjust for the given exponent. */
Erick Tryzelaarc78b33b2009-08-20 23:30:43 +00002272 exponent = totalExponent(p + 1, end, expAdjustment);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002273 }
2274
2275 return normalize(rounding_mode, lost_fraction);
2276}
2277
2278APFloat::opStatus
Neil Booth96c74712007-10-12 16:02:31 +00002279APFloat::roundSignificandWithExponent(const integerPart *decSigParts,
2280 unsigned sigPartCount, int exp,
2281 roundingMode rounding_mode)
2282{
2283 unsigned int parts, pow5PartCount;
Neil Boothcaf19d72007-10-14 10:29:28 +00002284 fltSemantics calcSemantics = { 32767, -32767, 0, true };
Neil Booth96c74712007-10-12 16:02:31 +00002285 integerPart pow5Parts[maxPowerOfFiveParts];
2286 bool isNearest;
2287
Dan Gohman16e02092010-03-24 19:38:02 +00002288 isNearest = (rounding_mode == rmNearestTiesToEven ||
2289 rounding_mode == rmNearestTiesToAway);
Neil Booth96c74712007-10-12 16:02:31 +00002290
2291 parts = partCountForBits(semantics->precision + 11);
2292
2293 /* Calculate pow(5, abs(exp)). */
2294 pow5PartCount = powerOf5(pow5Parts, exp >= 0 ? exp: -exp);
2295
2296 for (;; parts *= 2) {
2297 opStatus sigStatus, powStatus;
2298 unsigned int excessPrecision, truncatedBits;
2299
2300 calcSemantics.precision = parts * integerPartWidth - 1;
2301 excessPrecision = calcSemantics.precision - semantics->precision;
2302 truncatedBits = excessPrecision;
2303
2304 APFloat decSig(calcSemantics, fcZero, sign);
2305 APFloat pow5(calcSemantics, fcZero, false);
2306
2307 sigStatus = decSig.convertFromUnsignedParts(decSigParts, sigPartCount,
2308 rmNearestTiesToEven);
2309 powStatus = pow5.convertFromUnsignedParts(pow5Parts, pow5PartCount,
2310 rmNearestTiesToEven);
2311 /* Add exp, as 10^n = 5^n * 2^n. */
2312 decSig.exponent += exp;
2313
2314 lostFraction calcLostFraction;
Evan Cheng48e8c802008-05-02 21:15:08 +00002315 integerPart HUerr, HUdistance;
2316 unsigned int powHUerr;
Neil Booth96c74712007-10-12 16:02:31 +00002317
2318 if (exp >= 0) {
2319 /* multiplySignificand leaves the precision-th bit set to 1. */
2320 calcLostFraction = decSig.multiplySignificand(pow5, NULL);
2321 powHUerr = powStatus != opOK;
2322 } else {
2323 calcLostFraction = decSig.divideSignificand(pow5);
2324 /* Denormal numbers have less precision. */
2325 if (decSig.exponent < semantics->minExponent) {
2326 excessPrecision += (semantics->minExponent - decSig.exponent);
2327 truncatedBits = excessPrecision;
2328 if (excessPrecision > calcSemantics.precision)
2329 excessPrecision = calcSemantics.precision;
2330 }
2331 /* Extra half-ulp lost in reciprocal of exponent. */
Evan Cheng48e8c802008-05-02 21:15:08 +00002332 powHUerr = (powStatus == opOK && calcLostFraction == lfExactlyZero) ? 0:2;
Neil Booth96c74712007-10-12 16:02:31 +00002333 }
2334
2335 /* Both multiplySignificand and divideSignificand return the
2336 result with the integer bit set. */
Evan Cheng99ebfa52009-10-27 21:35:42 +00002337 assert(APInt::tcExtractBit
2338 (decSig.significandParts(), calcSemantics.precision - 1) == 1);
Neil Booth96c74712007-10-12 16:02:31 +00002339
2340 HUerr = HUerrBound(calcLostFraction != lfExactlyZero, sigStatus != opOK,
2341 powHUerr);
2342 HUdistance = 2 * ulpsFromBoundary(decSig.significandParts(),
2343 excessPrecision, isNearest);
2344
2345 /* Are we guaranteed to round correctly if we truncate? */
2346 if (HUdistance >= HUerr) {
2347 APInt::tcExtract(significandParts(), partCount(), decSig.significandParts(),
2348 calcSemantics.precision - excessPrecision,
2349 excessPrecision);
2350 /* Take the exponent of decSig. If we tcExtract-ed less bits
2351 above we must adjust our exponent to compensate for the
2352 implicit right shift. */
2353 exponent = (decSig.exponent + semantics->precision
2354 - (calcSemantics.precision - excessPrecision));
2355 calcLostFraction = lostFractionThroughTruncation(decSig.significandParts(),
2356 decSig.partCount(),
2357 truncatedBits);
2358 return normalize(rounding_mode, calcLostFraction);
2359 }
2360 }
2361}
2362
2363APFloat::opStatus
Benjamin Kramer38e59892010-07-14 22:38:02 +00002364APFloat::convertFromDecimalString(StringRef str, roundingMode rounding_mode)
Neil Booth96c74712007-10-12 16:02:31 +00002365{
Neil Booth1870f292007-10-14 10:16:12 +00002366 decimalInfo D;
Neil Booth96c74712007-10-12 16:02:31 +00002367 opStatus fs;
2368
Neil Booth1870f292007-10-14 10:16:12 +00002369 /* Scan the text. */
Erick Tryzelaara15d8902009-08-16 23:36:19 +00002370 StringRef::iterator p = str.begin();
2371 interpretDecimal(p, str.end(), &D);
Neil Booth96c74712007-10-12 16:02:31 +00002372
Neil Booth686700e2007-10-15 15:00:55 +00002373 /* Handle the quick cases. First the case of no significant digits,
2374 i.e. zero, and then exponents that are obviously too large or too
2375 small. Writing L for log 10 / log 2, a number d.ddddd*10^exp
2376 definitely overflows if
2377
2378 (exp - 1) * L >= maxExponent
2379
2380 and definitely underflows to zero where
2381
2382 (exp + 1) * L <= minExponent - precision
2383
2384 With integer arithmetic the tightest bounds for L are
2385
2386 93/28 < L < 196/59 [ numerator <= 256 ]
2387 42039/12655 < L < 28738/8651 [ numerator <= 65536 ]
2388 */
2389
Neil Boothcc233592007-12-05 13:06:04 +00002390 if (decDigitValue(*D.firstSigDigit) >= 10U) {
Neil Booth96c74712007-10-12 16:02:31 +00002391 category = fcZero;
2392 fs = opOK;
John McCall8b3f3302010-02-26 22:20:41 +00002393
2394 /* Check whether the normalized exponent is high enough to overflow
2395 max during the log-rebasing in the max-exponent check below. */
2396 } else if (D.normalizedExponent - 1 > INT_MAX / 42039) {
2397 fs = handleOverflow(rounding_mode);
2398
2399 /* If it wasn't, then it also wasn't high enough to overflow max
2400 during the log-rebasing in the min-exponent check. Check that it
2401 won't overflow min in either check, then perform the min-exponent
2402 check. */
2403 } else if (D.normalizedExponent - 1 < INT_MIN / 42039 ||
2404 (D.normalizedExponent + 1) * 28738 <=
2405 8651 * (semantics->minExponent - (int) semantics->precision)) {
Neil Booth686700e2007-10-15 15:00:55 +00002406 /* Underflow to zero and round. */
2407 zeroSignificand();
2408 fs = normalize(rounding_mode, lfLessThanHalf);
John McCall8b3f3302010-02-26 22:20:41 +00002409
2410 /* We can finally safely perform the max-exponent check. */
Neil Booth686700e2007-10-15 15:00:55 +00002411 } else if ((D.normalizedExponent - 1) * 42039
2412 >= 12655 * semantics->maxExponent) {
2413 /* Overflow and round. */
2414 fs = handleOverflow(rounding_mode);
Neil Booth96c74712007-10-12 16:02:31 +00002415 } else {
Neil Booth1870f292007-10-14 10:16:12 +00002416 integerPart *decSignificand;
2417 unsigned int partCount;
Neil Booth96c74712007-10-12 16:02:31 +00002418
Neil Booth1870f292007-10-14 10:16:12 +00002419 /* A tight upper bound on number of bits required to hold an
Neil Booth686700e2007-10-15 15:00:55 +00002420 N-digit decimal integer is N * 196 / 59. Allocate enough space
Neil Booth1870f292007-10-14 10:16:12 +00002421 to hold the full significand, and an extra part required by
2422 tcMultiplyPart. */
Evan Cheng48e8c802008-05-02 21:15:08 +00002423 partCount = static_cast<unsigned int>(D.lastSigDigit - D.firstSigDigit) + 1;
Neil Booth686700e2007-10-15 15:00:55 +00002424 partCount = partCountForBits(1 + 196 * partCount / 59);
Neil Booth1870f292007-10-14 10:16:12 +00002425 decSignificand = new integerPart[partCount + 1];
2426 partCount = 0;
Neil Booth96c74712007-10-12 16:02:31 +00002427
Neil Booth1870f292007-10-14 10:16:12 +00002428 /* Convert to binary efficiently - we do almost all multiplication
2429 in an integerPart. When this would overflow do we do a single
2430 bignum multiplication, and then revert again to multiplication
2431 in an integerPart. */
2432 do {
2433 integerPart decValue, val, multiplier;
2434
2435 val = 0;
2436 multiplier = 1;
2437
2438 do {
Erick Tryzelaara15d8902009-08-16 23:36:19 +00002439 if (*p == '.') {
Neil Booth1870f292007-10-14 10:16:12 +00002440 p++;
Erick Tryzelaara15d8902009-08-16 23:36:19 +00002441 if (p == str.end()) {
2442 break;
2443 }
2444 }
Neil Booth1870f292007-10-14 10:16:12 +00002445 decValue = decDigitValue(*p++);
Erick Tryzelaarc78b33b2009-08-20 23:30:43 +00002446 assert(decValue < 10U && "Invalid character in significand");
Neil Booth1870f292007-10-14 10:16:12 +00002447 multiplier *= 10;
2448 val = val * 10 + decValue;
2449 /* The maximum number that can be multiplied by ten with any
2450 digit added without overflowing an integerPart. */
2451 } while (p <= D.lastSigDigit && multiplier <= (~ (integerPart) 0 - 9) / 10);
2452
2453 /* Multiply out the current part. */
2454 APInt::tcMultiplyPart(decSignificand, decSignificand, multiplier, val,
2455 partCount, partCount + 1, false);
2456
2457 /* If we used another part (likely but not guaranteed), increase
2458 the count. */
2459 if (decSignificand[partCount])
2460 partCount++;
2461 } while (p <= D.lastSigDigit);
Neil Booth96c74712007-10-12 16:02:31 +00002462
Neil Booth43a4b282007-11-01 22:51:07 +00002463 category = fcNormal;
Neil Booth96c74712007-10-12 16:02:31 +00002464 fs = roundSignificandWithExponent(decSignificand, partCount,
Neil Booth1870f292007-10-14 10:16:12 +00002465 D.exponent, rounding_mode);
Neil Booth96c74712007-10-12 16:02:31 +00002466
Neil Booth1870f292007-10-14 10:16:12 +00002467 delete [] decSignificand;
2468 }
Neil Booth96c74712007-10-12 16:02:31 +00002469
2470 return fs;
2471}
2472
2473APFloat::opStatus
Benjamin Kramer38e59892010-07-14 22:38:02 +00002474APFloat::convertFromString(StringRef str, roundingMode rounding_mode)
Neil Booth4f881702007-09-26 21:33:42 +00002475{
Neil Boothcaf19d72007-10-14 10:29:28 +00002476 assertArithmeticOK(*semantics);
Erick Tryzelaara15d8902009-08-16 23:36:19 +00002477 assert(!str.empty() && "Invalid string length");
Neil Boothcaf19d72007-10-14 10:29:28 +00002478
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002479 /* Handle a leading minus sign. */
Erick Tryzelaara15d8902009-08-16 23:36:19 +00002480 StringRef::iterator p = str.begin();
2481 size_t slen = str.size();
Erick Tryzelaarc78b33b2009-08-20 23:30:43 +00002482 sign = *p == '-' ? 1 : 0;
Dan Gohman16e02092010-03-24 19:38:02 +00002483 if (*p == '-' || *p == '+') {
Erick Tryzelaara15d8902009-08-16 23:36:19 +00002484 p++;
2485 slen--;
Erick Tryzelaarc78b33b2009-08-20 23:30:43 +00002486 assert(slen && "String has no digits");
Erick Tryzelaara15d8902009-08-16 23:36:19 +00002487 }
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002488
Dan Gohman16e02092010-03-24 19:38:02 +00002489 if (slen >= 2 && p[0] == '0' && (p[1] == 'x' || p[1] == 'X')) {
Erick Tryzelaara15d8902009-08-16 23:36:19 +00002490 assert(slen - 2 && "Invalid string");
Erick Tryzelaarc78b33b2009-08-20 23:30:43 +00002491 return convertFromHexadecimalString(StringRef(p + 2, slen - 2),
Erick Tryzelaara15d8902009-08-16 23:36:19 +00002492 rounding_mode);
2493 }
Bill Wendlingb7c0d942008-11-27 08:00:12 +00002494
Erick Tryzelaarc78b33b2009-08-20 23:30:43 +00002495 return convertFromDecimalString(StringRef(p, slen), rounding_mode);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002496}
Dale Johannesen343e7702007-08-24 00:56:33 +00002497
Neil Bootha30b0ee2007-10-03 22:26:02 +00002498/* Write out a hexadecimal representation of the floating point value
2499 to DST, which must be of sufficient size, in the C99 form
2500 [-]0xh.hhhhp[+-]d. Return the number of characters written,
2501 excluding the terminating NUL.
2502
2503 If UPPERCASE, the output is in upper case, otherwise in lower case.
2504
2505 HEXDIGITS digits appear altogether, rounding the value if
2506 necessary. If HEXDIGITS is 0, the minimal precision to display the
2507 number precisely is used instead. If nothing would appear after
2508 the decimal point it is suppressed.
2509
2510 The decimal exponent is always printed and has at least one digit.
2511 Zero values display an exponent of zero. Infinities and NaNs
2512 appear as "infinity" or "nan" respectively.
2513
2514 The above rules are as specified by C99. There is ambiguity about
2515 what the leading hexadecimal digit should be. This implementation
2516 uses whatever is necessary so that the exponent is displayed as
2517 stored. This implies the exponent will fall within the IEEE format
2518 range, and the leading hexadecimal digit will be 0 (for denormals),
2519 1 (normal numbers) or 2 (normal numbers rounded-away-from-zero with
2520 any other digits zero).
2521*/
2522unsigned int
2523APFloat::convertToHexString(char *dst, unsigned int hexDigits,
2524 bool upperCase, roundingMode rounding_mode) const
2525{
2526 char *p;
2527
Neil Boothcaf19d72007-10-14 10:29:28 +00002528 assertArithmeticOK(*semantics);
2529
Neil Bootha30b0ee2007-10-03 22:26:02 +00002530 p = dst;
2531 if (sign)
2532 *dst++ = '-';
2533
2534 switch (category) {
2535 case fcInfinity:
2536 memcpy (dst, upperCase ? infinityU: infinityL, sizeof infinityU - 1);
2537 dst += sizeof infinityL - 1;
2538 break;
2539
2540 case fcNaN:
2541 memcpy (dst, upperCase ? NaNU: NaNL, sizeof NaNU - 1);
2542 dst += sizeof NaNU - 1;
2543 break;
2544
2545 case fcZero:
2546 *dst++ = '0';
2547 *dst++ = upperCase ? 'X': 'x';
2548 *dst++ = '0';
2549 if (hexDigits > 1) {
2550 *dst++ = '.';
2551 memset (dst, '0', hexDigits - 1);
2552 dst += hexDigits - 1;
2553 }
2554 *dst++ = upperCase ? 'P': 'p';
2555 *dst++ = '0';
2556 break;
2557
2558 case fcNormal:
2559 dst = convertNormalToHexString (dst, hexDigits, upperCase, rounding_mode);
2560 break;
2561 }
2562
2563 *dst = 0;
2564
Evan Cheng48e8c802008-05-02 21:15:08 +00002565 return static_cast<unsigned int>(dst - p);
Neil Bootha30b0ee2007-10-03 22:26:02 +00002566}
2567
2568/* Does the hard work of outputting the correctly rounded hexadecimal
2569 form of a normal floating point number with the specified number of
2570 hexadecimal digits. If HEXDIGITS is zero the minimum number of
2571 digits necessary to print the value precisely is output. */
2572char *
2573APFloat::convertNormalToHexString(char *dst, unsigned int hexDigits,
2574 bool upperCase,
2575 roundingMode rounding_mode) const
2576{
2577 unsigned int count, valueBits, shift, partsCount, outputDigits;
2578 const char *hexDigitChars;
2579 const integerPart *significand;
2580 char *p;
2581 bool roundUp;
2582
2583 *dst++ = '0';
2584 *dst++ = upperCase ? 'X': 'x';
2585
2586 roundUp = false;
2587 hexDigitChars = upperCase ? hexDigitsUpper: hexDigitsLower;
2588
2589 significand = significandParts();
2590 partsCount = partCount();
2591
2592 /* +3 because the first digit only uses the single integer bit, so
2593 we have 3 virtual zero most-significant-bits. */
2594 valueBits = semantics->precision + 3;
2595 shift = integerPartWidth - valueBits % integerPartWidth;
2596
2597 /* The natural number of digits required ignoring trailing
2598 insignificant zeroes. */
2599 outputDigits = (valueBits - significandLSB () + 3) / 4;
2600
2601 /* hexDigits of zero means use the required number for the
2602 precision. Otherwise, see if we are truncating. If we are,
Neil Booth978661d2007-10-06 00:24:48 +00002603 find out if we need to round away from zero. */
Neil Bootha30b0ee2007-10-03 22:26:02 +00002604 if (hexDigits) {
2605 if (hexDigits < outputDigits) {
2606 /* We are dropping non-zero bits, so need to check how to round.
2607 "bits" is the number of dropped bits. */
2608 unsigned int bits;
2609 lostFraction fraction;
2610
2611 bits = valueBits - hexDigits * 4;
2612 fraction = lostFractionThroughTruncation (significand, partsCount, bits);
2613 roundUp = roundAwayFromZero(rounding_mode, fraction, bits);
2614 }
2615 outputDigits = hexDigits;
2616 }
2617
2618 /* Write the digits consecutively, and start writing in the location
2619 of the hexadecimal point. We move the most significant digit
2620 left and add the hexadecimal point later. */
2621 p = ++dst;
2622
2623 count = (valueBits + integerPartWidth - 1) / integerPartWidth;
2624
2625 while (outputDigits && count) {
2626 integerPart part;
2627
2628 /* Put the most significant integerPartWidth bits in "part". */
2629 if (--count == partsCount)
2630 part = 0; /* An imaginary higher zero part. */
2631 else
2632 part = significand[count] << shift;
2633
2634 if (count && shift)
2635 part |= significand[count - 1] >> (integerPartWidth - shift);
2636
2637 /* Convert as much of "part" to hexdigits as we can. */
2638 unsigned int curDigits = integerPartWidth / 4;
2639
2640 if (curDigits > outputDigits)
2641 curDigits = outputDigits;
2642 dst += partAsHex (dst, part, curDigits, hexDigitChars);
2643 outputDigits -= curDigits;
2644 }
2645
2646 if (roundUp) {
2647 char *q = dst;
2648
2649 /* Note that hexDigitChars has a trailing '0'. */
2650 do {
2651 q--;
2652 *q = hexDigitChars[hexDigitValue (*q) + 1];
Neil Booth978661d2007-10-06 00:24:48 +00002653 } while (*q == '0');
Evan Cheng99ebfa52009-10-27 21:35:42 +00002654 assert(q >= p);
Neil Bootha30b0ee2007-10-03 22:26:02 +00002655 } else {
2656 /* Add trailing zeroes. */
2657 memset (dst, '0', outputDigits);
2658 dst += outputDigits;
2659 }
2660
2661 /* Move the most significant digit to before the point, and if there
2662 is something after the decimal point add it. This must come
2663 after rounding above. */
2664 p[-1] = p[0];
2665 if (dst -1 == p)
2666 dst--;
2667 else
2668 p[0] = '.';
2669
2670 /* Finally output the exponent. */
2671 *dst++ = upperCase ? 'P': 'p';
2672
Neil Booth92f7e8d2007-10-06 07:29:25 +00002673 return writeSignedDecimal (dst, exponent);
Neil Bootha30b0ee2007-10-03 22:26:02 +00002674}
2675
Dale Johannesen343e7702007-08-24 00:56:33 +00002676// For good performance it is desirable for different APFloats
2677// to produce different integers.
2678uint32_t
Neil Booth4f881702007-09-26 21:33:42 +00002679APFloat::getHashValue() const
2680{
Dale Johannesen343e7702007-08-24 00:56:33 +00002681 if (category==fcZero) return sign<<8 | semantics->precision ;
2682 else if (category==fcInfinity) return sign<<9 | semantics->precision;
Dale Johanneseneaf08942007-08-31 04:03:46 +00002683 else if (category==fcNaN) return 1<<10 | semantics->precision;
Dale Johannesen343e7702007-08-24 00:56:33 +00002684 else {
2685 uint32_t hash = sign<<11 | semantics->precision | exponent<<12;
2686 const integerPart* p = significandParts();
2687 for (int i=partCount(); i>0; i--, p++)
Evan Cheng48e8c802008-05-02 21:15:08 +00002688 hash ^= ((uint32_t)*p) ^ (uint32_t)((*p)>>32);
Dale Johannesen343e7702007-08-24 00:56:33 +00002689 return hash;
2690 }
2691}
2692
2693// Conversion from APFloat to/from host float/double. It may eventually be
2694// possible to eliminate these and have everybody deal with APFloats, but that
2695// will take a while. This approach will not easily extend to long double.
Dale Johannesena72a5a02007-09-20 23:47:58 +00002696// Current implementation requires integerPartWidth==64, which is correct at
2697// the moment but could be made more general.
Dale Johannesen343e7702007-08-24 00:56:33 +00002698
Dale Johannesen58c2e4c2007-09-05 20:39:49 +00002699// Denormals have exponent minExponent in APFloat, but minExponent-1 in
Dale Johannesena72a5a02007-09-20 23:47:58 +00002700// the actual IEEE respresentations. We compensate for that here.
Dale Johannesen58c2e4c2007-09-05 20:39:49 +00002701
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002702APInt
Neil Booth4f881702007-09-26 21:33:42 +00002703APFloat::convertF80LongDoubleAPFloatToAPInt() const
2704{
Dan Gohmanb10abe12008-01-29 12:08:20 +00002705 assert(semantics == (const llvm::fltSemantics*)&x87DoubleExtended);
Evan Cheng99ebfa52009-10-27 21:35:42 +00002706 assert(partCount()==2);
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002707
2708 uint64_t myexponent, mysignificand;
2709
2710 if (category==fcNormal) {
2711 myexponent = exponent+16383; //bias
Dale Johannesena72a5a02007-09-20 23:47:58 +00002712 mysignificand = significandParts()[0];
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002713 if (myexponent==1 && !(mysignificand & 0x8000000000000000ULL))
2714 myexponent = 0; // denormal
2715 } else if (category==fcZero) {
2716 myexponent = 0;
2717 mysignificand = 0;
2718 } else if (category==fcInfinity) {
2719 myexponent = 0x7fff;
2720 mysignificand = 0x8000000000000000ULL;
Chris Lattnera11ef822007-10-06 06:13:42 +00002721 } else {
2722 assert(category == fcNaN && "Unknown category");
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002723 myexponent = 0x7fff;
Dale Johannesena72a5a02007-09-20 23:47:58 +00002724 mysignificand = significandParts()[0];
Chris Lattnera11ef822007-10-06 06:13:42 +00002725 }
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002726
2727 uint64_t words[2];
Dale Johannesen1b25cb22009-03-23 21:16:53 +00002728 words[0] = mysignificand;
2729 words[1] = ((uint64_t)(sign & 1) << 15) |
2730 (myexponent & 0x7fffLL);
Chris Lattnera11ef822007-10-06 06:13:42 +00002731 return APInt(80, 2, words);
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002732}
2733
2734APInt
Dale Johannesena471c2e2007-10-11 18:07:22 +00002735APFloat::convertPPCDoubleDoubleAPFloatToAPInt() const
2736{
Dan Gohmanb10abe12008-01-29 12:08:20 +00002737 assert(semantics == (const llvm::fltSemantics*)&PPCDoubleDouble);
Evan Cheng99ebfa52009-10-27 21:35:42 +00002738 assert(partCount()==2);
Dale Johannesena471c2e2007-10-11 18:07:22 +00002739
2740 uint64_t myexponent, mysignificand, myexponent2, mysignificand2;
2741
2742 if (category==fcNormal) {
2743 myexponent = exponent + 1023; //bias
2744 myexponent2 = exponent2 + 1023;
2745 mysignificand = significandParts()[0];
2746 mysignificand2 = significandParts()[1];
2747 if (myexponent==1 && !(mysignificand & 0x10000000000000LL))
2748 myexponent = 0; // denormal
2749 if (myexponent2==1 && !(mysignificand2 & 0x10000000000000LL))
2750 myexponent2 = 0; // denormal
2751 } else if (category==fcZero) {
2752 myexponent = 0;
2753 mysignificand = 0;
2754 myexponent2 = 0;
2755 mysignificand2 = 0;
2756 } else if (category==fcInfinity) {
2757 myexponent = 0x7ff;
2758 myexponent2 = 0;
2759 mysignificand = 0;
2760 mysignificand2 = 0;
2761 } else {
2762 assert(category == fcNaN && "Unknown category");
2763 myexponent = 0x7ff;
2764 mysignificand = significandParts()[0];
2765 myexponent2 = exponent2;
2766 mysignificand2 = significandParts()[1];
2767 }
2768
2769 uint64_t words[2];
Evan Cheng48e8c802008-05-02 21:15:08 +00002770 words[0] = ((uint64_t)(sign & 1) << 63) |
Dale Johannesena471c2e2007-10-11 18:07:22 +00002771 ((myexponent & 0x7ff) << 52) |
2772 (mysignificand & 0xfffffffffffffLL);
Evan Cheng48e8c802008-05-02 21:15:08 +00002773 words[1] = ((uint64_t)(sign2 & 1) << 63) |
Dale Johannesena471c2e2007-10-11 18:07:22 +00002774 ((myexponent2 & 0x7ff) << 52) |
2775 (mysignificand2 & 0xfffffffffffffLL);
2776 return APInt(128, 2, words);
2777}
2778
2779APInt
Anton Korobeynikov7e844f12009-08-21 22:10:30 +00002780APFloat::convertQuadrupleAPFloatToAPInt() const
2781{
2782 assert(semantics == (const llvm::fltSemantics*)&IEEEquad);
Evan Cheng99ebfa52009-10-27 21:35:42 +00002783 assert(partCount()==2);
Anton Korobeynikov7e844f12009-08-21 22:10:30 +00002784
2785 uint64_t myexponent, mysignificand, mysignificand2;
2786
2787 if (category==fcNormal) {
2788 myexponent = exponent+16383; //bias
2789 mysignificand = significandParts()[0];
2790 mysignificand2 = significandParts()[1];
2791 if (myexponent==1 && !(mysignificand2 & 0x1000000000000LL))
2792 myexponent = 0; // denormal
2793 } else if (category==fcZero) {
2794 myexponent = 0;
2795 mysignificand = mysignificand2 = 0;
2796 } else if (category==fcInfinity) {
2797 myexponent = 0x7fff;
2798 mysignificand = mysignificand2 = 0;
2799 } else {
2800 assert(category == fcNaN && "Unknown category!");
2801 myexponent = 0x7fff;
2802 mysignificand = significandParts()[0];
2803 mysignificand2 = significandParts()[1];
2804 }
2805
2806 uint64_t words[2];
2807 words[0] = mysignificand;
2808 words[1] = ((uint64_t)(sign & 1) << 63) |
2809 ((myexponent & 0x7fff) << 48) |
Anton Korobeynikov4755e992009-08-21 23:09:47 +00002810 (mysignificand2 & 0xffffffffffffLL);
Anton Korobeynikov7e844f12009-08-21 22:10:30 +00002811
2812 return APInt(128, 2, words);
2813}
2814
2815APInt
Neil Booth4f881702007-09-26 21:33:42 +00002816APFloat::convertDoubleAPFloatToAPInt() const
2817{
Dan Gohmancb648f92007-09-14 20:08:19 +00002818 assert(semantics == (const llvm::fltSemantics*)&IEEEdouble);
Evan Cheng99ebfa52009-10-27 21:35:42 +00002819 assert(partCount()==1);
Dale Johannesen343e7702007-08-24 00:56:33 +00002820
Dale Johanneseneaf08942007-08-31 04:03:46 +00002821 uint64_t myexponent, mysignificand;
Dale Johannesen343e7702007-08-24 00:56:33 +00002822
2823 if (category==fcNormal) {
Dale Johannesen343e7702007-08-24 00:56:33 +00002824 myexponent = exponent+1023; //bias
Dale Johannesen58c2e4c2007-09-05 20:39:49 +00002825 mysignificand = *significandParts();
2826 if (myexponent==1 && !(mysignificand & 0x10000000000000LL))
2827 myexponent = 0; // denormal
Dale Johannesen343e7702007-08-24 00:56:33 +00002828 } else if (category==fcZero) {
Dale Johannesen343e7702007-08-24 00:56:33 +00002829 myexponent = 0;
2830 mysignificand = 0;
2831 } else if (category==fcInfinity) {
Dale Johannesen343e7702007-08-24 00:56:33 +00002832 myexponent = 0x7ff;
2833 mysignificand = 0;
Chris Lattnera11ef822007-10-06 06:13:42 +00002834 } else {
2835 assert(category == fcNaN && "Unknown category!");
Dale Johannesen343e7702007-08-24 00:56:33 +00002836 myexponent = 0x7ff;
Dale Johanneseneaf08942007-08-31 04:03:46 +00002837 mysignificand = *significandParts();
Chris Lattnera11ef822007-10-06 06:13:42 +00002838 }
Dale Johannesen343e7702007-08-24 00:56:33 +00002839
Evan Cheng48e8c802008-05-02 21:15:08 +00002840 return APInt(64, ((((uint64_t)(sign & 1) << 63) |
Chris Lattnera11ef822007-10-06 06:13:42 +00002841 ((myexponent & 0x7ff) << 52) |
2842 (mysignificand & 0xfffffffffffffLL))));
Dale Johannesen343e7702007-08-24 00:56:33 +00002843}
2844
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002845APInt
Neil Booth4f881702007-09-26 21:33:42 +00002846APFloat::convertFloatAPFloatToAPInt() const
2847{
Dan Gohmancb648f92007-09-14 20:08:19 +00002848 assert(semantics == (const llvm::fltSemantics*)&IEEEsingle);
Evan Cheng99ebfa52009-10-27 21:35:42 +00002849 assert(partCount()==1);
Neil Booth4f881702007-09-26 21:33:42 +00002850
Dale Johanneseneaf08942007-08-31 04:03:46 +00002851 uint32_t myexponent, mysignificand;
Dale Johannesen343e7702007-08-24 00:56:33 +00002852
2853 if (category==fcNormal) {
Dale Johannesen343e7702007-08-24 00:56:33 +00002854 myexponent = exponent+127; //bias
Evan Cheng48e8c802008-05-02 21:15:08 +00002855 mysignificand = (uint32_t)*significandParts();
Dale Johannesend0763b92007-11-17 01:02:27 +00002856 if (myexponent == 1 && !(mysignificand & 0x800000))
Dale Johannesen58c2e4c2007-09-05 20:39:49 +00002857 myexponent = 0; // denormal
Dale Johannesen343e7702007-08-24 00:56:33 +00002858 } else if (category==fcZero) {
Dale Johannesen343e7702007-08-24 00:56:33 +00002859 myexponent = 0;
2860 mysignificand = 0;
2861 } else if (category==fcInfinity) {
Dale Johannesen343e7702007-08-24 00:56:33 +00002862 myexponent = 0xff;
2863 mysignificand = 0;
Chris Lattnera11ef822007-10-06 06:13:42 +00002864 } else {
2865 assert(category == fcNaN && "Unknown category!");
Dale Johannesen58c2e4c2007-09-05 20:39:49 +00002866 myexponent = 0xff;
Evan Cheng48e8c802008-05-02 21:15:08 +00002867 mysignificand = (uint32_t)*significandParts();
Chris Lattnera11ef822007-10-06 06:13:42 +00002868 }
Dale Johannesen343e7702007-08-24 00:56:33 +00002869
Chris Lattnera11ef822007-10-06 06:13:42 +00002870 return APInt(32, (((sign&1) << 31) | ((myexponent&0xff) << 23) |
2871 (mysignificand & 0x7fffff)));
Dale Johannesen343e7702007-08-24 00:56:33 +00002872}
2873
Chris Lattnercc4287a2009-10-16 02:13:51 +00002874APInt
2875APFloat::convertHalfAPFloatToAPInt() const
2876{
2877 assert(semantics == (const llvm::fltSemantics*)&IEEEhalf);
Evan Cheng99ebfa52009-10-27 21:35:42 +00002878 assert(partCount()==1);
Chris Lattnercc4287a2009-10-16 02:13:51 +00002879
2880 uint32_t myexponent, mysignificand;
2881
2882 if (category==fcNormal) {
2883 myexponent = exponent+15; //bias
2884 mysignificand = (uint32_t)*significandParts();
2885 if (myexponent == 1 && !(mysignificand & 0x400))
2886 myexponent = 0; // denormal
2887 } else if (category==fcZero) {
2888 myexponent = 0;
2889 mysignificand = 0;
2890 } else if (category==fcInfinity) {
Dale Johannesena223aed2009-10-23 04:02:51 +00002891 myexponent = 0x1f;
Chris Lattnercc4287a2009-10-16 02:13:51 +00002892 mysignificand = 0;
2893 } else {
2894 assert(category == fcNaN && "Unknown category!");
Dale Johannesena223aed2009-10-23 04:02:51 +00002895 myexponent = 0x1f;
Chris Lattnercc4287a2009-10-16 02:13:51 +00002896 mysignificand = (uint32_t)*significandParts();
2897 }
2898
2899 return APInt(16, (((sign&1) << 15) | ((myexponent&0x1f) << 10) |
2900 (mysignificand & 0x3ff)));
2901}
2902
Dale Johannesena471c2e2007-10-11 18:07:22 +00002903// This function creates an APInt that is just a bit map of the floating
2904// point constant as it would appear in memory. It is not a conversion,
2905// and treating the result as a normal integer is unlikely to be useful.
2906
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002907APInt
Dale Johannesen7111b022008-10-09 18:53:47 +00002908APFloat::bitcastToAPInt() const
Neil Booth4f881702007-09-26 21:33:42 +00002909{
Chris Lattnercc4287a2009-10-16 02:13:51 +00002910 if (semantics == (const llvm::fltSemantics*)&IEEEhalf)
2911 return convertHalfAPFloatToAPInt();
2912
Dan Gohmanb10abe12008-01-29 12:08:20 +00002913 if (semantics == (const llvm::fltSemantics*)&IEEEsingle)
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002914 return convertFloatAPFloatToAPInt();
Anton Korobeynikov7e844f12009-08-21 22:10:30 +00002915
Dan Gohmanb10abe12008-01-29 12:08:20 +00002916 if (semantics == (const llvm::fltSemantics*)&IEEEdouble)
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002917 return convertDoubleAPFloatToAPInt();
Neil Booth4f881702007-09-26 21:33:42 +00002918
Anton Korobeynikov7e844f12009-08-21 22:10:30 +00002919 if (semantics == (const llvm::fltSemantics*)&IEEEquad)
2920 return convertQuadrupleAPFloatToAPInt();
2921
Dan Gohmanb10abe12008-01-29 12:08:20 +00002922 if (semantics == (const llvm::fltSemantics*)&PPCDoubleDouble)
Dale Johannesena471c2e2007-10-11 18:07:22 +00002923 return convertPPCDoubleDoubleAPFloatToAPInt();
2924
Dan Gohmanb10abe12008-01-29 12:08:20 +00002925 assert(semantics == (const llvm::fltSemantics*)&x87DoubleExtended &&
Chris Lattnera11ef822007-10-06 06:13:42 +00002926 "unknown format!");
2927 return convertF80LongDoubleAPFloatToAPInt();
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002928}
2929
Neil Booth4f881702007-09-26 21:33:42 +00002930float
2931APFloat::convertToFloat() const
2932{
Chris Lattnerad785002009-09-24 21:44:20 +00002933 assert(semantics == (const llvm::fltSemantics*)&IEEEsingle &&
2934 "Float semantics are not IEEEsingle");
Dale Johannesen7111b022008-10-09 18:53:47 +00002935 APInt api = bitcastToAPInt();
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002936 return api.bitsToFloat();
2937}
2938
Neil Booth4f881702007-09-26 21:33:42 +00002939double
2940APFloat::convertToDouble() const
2941{
Chris Lattnerad785002009-09-24 21:44:20 +00002942 assert(semantics == (const llvm::fltSemantics*)&IEEEdouble &&
2943 "Float semantics are not IEEEdouble");
Dale Johannesen7111b022008-10-09 18:53:47 +00002944 APInt api = bitcastToAPInt();
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002945 return api.bitsToDouble();
2946}
2947
Dale Johannesend3d8ce32008-10-06 18:22:29 +00002948/// Integer bit is explicit in this format. Intel hardware (387 and later)
2949/// does not support these bit patterns:
2950/// exponent = all 1's, integer bit 0, significand 0 ("pseudoinfinity")
2951/// exponent = all 1's, integer bit 0, significand nonzero ("pseudoNaN")
2952/// exponent = 0, integer bit 1 ("pseudodenormal")
2953/// exponent!=0 nor all 1's, integer bit 0 ("unnormal")
2954/// At the moment, the first two are treated as NaNs, the second two as Normal.
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002955void
Neil Booth4f881702007-09-26 21:33:42 +00002956APFloat::initFromF80LongDoubleAPInt(const APInt &api)
2957{
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002958 assert(api.getBitWidth()==80);
2959 uint64_t i1 = api.getRawData()[0];
2960 uint64_t i2 = api.getRawData()[1];
Dale Johannesen1b25cb22009-03-23 21:16:53 +00002961 uint64_t myexponent = (i2 & 0x7fff);
2962 uint64_t mysignificand = i1;
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002963
2964 initialize(&APFloat::x87DoubleExtended);
Dale Johannesena72a5a02007-09-20 23:47:58 +00002965 assert(partCount()==2);
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002966
Dale Johannesen1b25cb22009-03-23 21:16:53 +00002967 sign = static_cast<unsigned int>(i2>>15);
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002968 if (myexponent==0 && mysignificand==0) {
2969 // exponent, significand meaningless
2970 category = fcZero;
2971 } else if (myexponent==0x7fff && mysignificand==0x8000000000000000ULL) {
2972 // exponent, significand meaningless
2973 category = fcInfinity;
2974 } else if (myexponent==0x7fff && mysignificand!=0x8000000000000000ULL) {
2975 // exponent meaningless
2976 category = fcNaN;
Dale Johannesena72a5a02007-09-20 23:47:58 +00002977 significandParts()[0] = mysignificand;
2978 significandParts()[1] = 0;
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002979 } else {
2980 category = fcNormal;
2981 exponent = myexponent - 16383;
Dale Johannesena72a5a02007-09-20 23:47:58 +00002982 significandParts()[0] = mysignificand;
2983 significandParts()[1] = 0;
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002984 if (myexponent==0) // denormal
2985 exponent = -16382;
Neil Booth4f881702007-09-26 21:33:42 +00002986 }
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002987}
2988
2989void
Dale Johannesena471c2e2007-10-11 18:07:22 +00002990APFloat::initFromPPCDoubleDoubleAPInt(const APInt &api)
2991{
2992 assert(api.getBitWidth()==128);
2993 uint64_t i1 = api.getRawData()[0];
2994 uint64_t i2 = api.getRawData()[1];
2995 uint64_t myexponent = (i1 >> 52) & 0x7ff;
2996 uint64_t mysignificand = i1 & 0xfffffffffffffLL;
2997 uint64_t myexponent2 = (i2 >> 52) & 0x7ff;
2998 uint64_t mysignificand2 = i2 & 0xfffffffffffffLL;
2999
3000 initialize(&APFloat::PPCDoubleDouble);
3001 assert(partCount()==2);
3002
Evan Cheng48e8c802008-05-02 21:15:08 +00003003 sign = static_cast<unsigned int>(i1>>63);
3004 sign2 = static_cast<unsigned int>(i2>>63);
Dale Johannesena471c2e2007-10-11 18:07:22 +00003005 if (myexponent==0 && mysignificand==0) {
3006 // exponent, significand meaningless
3007 // exponent2 and significand2 are required to be 0; we don't check
3008 category = fcZero;
3009 } else if (myexponent==0x7ff && mysignificand==0) {
3010 // exponent, significand meaningless
3011 // exponent2 and significand2 are required to be 0; we don't check
3012 category = fcInfinity;
3013 } else if (myexponent==0x7ff && mysignificand!=0) {
Dan Gohman16e02092010-03-24 19:38:02 +00003014 // exponent meaningless. So is the whole second word, but keep it
Dale Johannesena471c2e2007-10-11 18:07:22 +00003015 // for determinism.
3016 category = fcNaN;
3017 exponent2 = myexponent2;
3018 significandParts()[0] = mysignificand;
3019 significandParts()[1] = mysignificand2;
3020 } else {
3021 category = fcNormal;
3022 // Note there is no category2; the second word is treated as if it is
3023 // fcNormal, although it might be something else considered by itself.
3024 exponent = myexponent - 1023;
3025 exponent2 = myexponent2 - 1023;
3026 significandParts()[0] = mysignificand;
3027 significandParts()[1] = mysignificand2;
3028 if (myexponent==0) // denormal
3029 exponent = -1022;
3030 else
3031 significandParts()[0] |= 0x10000000000000LL; // integer bit
Dan Gohman16e02092010-03-24 19:38:02 +00003032 if (myexponent2==0)
Dale Johannesena471c2e2007-10-11 18:07:22 +00003033 exponent2 = -1022;
3034 else
3035 significandParts()[1] |= 0x10000000000000LL; // integer bit
3036 }
3037}
3038
3039void
Anton Korobeynikov7e844f12009-08-21 22:10:30 +00003040APFloat::initFromQuadrupleAPInt(const APInt &api)
3041{
3042 assert(api.getBitWidth()==128);
3043 uint64_t i1 = api.getRawData()[0];
3044 uint64_t i2 = api.getRawData()[1];
3045 uint64_t myexponent = (i2 >> 48) & 0x7fff;
3046 uint64_t mysignificand = i1;
3047 uint64_t mysignificand2 = i2 & 0xffffffffffffLL;
3048
3049 initialize(&APFloat::IEEEquad);
3050 assert(partCount()==2);
3051
3052 sign = static_cast<unsigned int>(i2>>63);
3053 if (myexponent==0 &&
3054 (mysignificand==0 && mysignificand2==0)) {
3055 // exponent, significand meaningless
3056 category = fcZero;
3057 } else if (myexponent==0x7fff &&
3058 (mysignificand==0 && mysignificand2==0)) {
3059 // exponent, significand meaningless
3060 category = fcInfinity;
3061 } else if (myexponent==0x7fff &&
3062 (mysignificand!=0 || mysignificand2 !=0)) {
3063 // exponent meaningless
3064 category = fcNaN;
3065 significandParts()[0] = mysignificand;
3066 significandParts()[1] = mysignificand2;
3067 } else {
3068 category = fcNormal;
3069 exponent = myexponent - 16383;
3070 significandParts()[0] = mysignificand;
3071 significandParts()[1] = mysignificand2;
3072 if (myexponent==0) // denormal
3073 exponent = -16382;
3074 else
3075 significandParts()[1] |= 0x1000000000000LL; // integer bit
3076 }
3077}
3078
3079void
Neil Booth4f881702007-09-26 21:33:42 +00003080APFloat::initFromDoubleAPInt(const APInt &api)
3081{
Dale Johannesen3f6eb742007-09-11 18:32:33 +00003082 assert(api.getBitWidth()==64);
3083 uint64_t i = *api.getRawData();
Dale Johannesend3b51fd2007-08-24 05:08:11 +00003084 uint64_t myexponent = (i >> 52) & 0x7ff;
3085 uint64_t mysignificand = i & 0xfffffffffffffLL;
3086
Dale Johannesen343e7702007-08-24 00:56:33 +00003087 initialize(&APFloat::IEEEdouble);
Dale Johannesen343e7702007-08-24 00:56:33 +00003088 assert(partCount()==1);
3089
Evan Cheng48e8c802008-05-02 21:15:08 +00003090 sign = static_cast<unsigned int>(i>>63);
Dale Johannesen343e7702007-08-24 00:56:33 +00003091 if (myexponent==0 && mysignificand==0) {
3092 // exponent, significand meaningless
3093 category = fcZero;
Dale Johannesen343e7702007-08-24 00:56:33 +00003094 } else if (myexponent==0x7ff && mysignificand==0) {
3095 // exponent, significand meaningless
3096 category = fcInfinity;
Dale Johanneseneaf08942007-08-31 04:03:46 +00003097 } else if (myexponent==0x7ff && mysignificand!=0) {
3098 // exponent meaningless
3099 category = fcNaN;
3100 *significandParts() = mysignificand;
Dale Johannesen343e7702007-08-24 00:56:33 +00003101 } else {
Dale Johannesen343e7702007-08-24 00:56:33 +00003102 category = fcNormal;
3103 exponent = myexponent - 1023;
Dale Johannesen58c2e4c2007-09-05 20:39:49 +00003104 *significandParts() = mysignificand;
3105 if (myexponent==0) // denormal
3106 exponent = -1022;
3107 else
3108 *significandParts() |= 0x10000000000000LL; // integer bit
Neil Booth4f881702007-09-26 21:33:42 +00003109 }
Dale Johannesen343e7702007-08-24 00:56:33 +00003110}
3111
Dale Johannesen3f6eb742007-09-11 18:32:33 +00003112void
Neil Booth4f881702007-09-26 21:33:42 +00003113APFloat::initFromFloatAPInt(const APInt & api)
3114{
Dale Johannesen3f6eb742007-09-11 18:32:33 +00003115 assert(api.getBitWidth()==32);
3116 uint32_t i = (uint32_t)*api.getRawData();
Dale Johannesend3b51fd2007-08-24 05:08:11 +00003117 uint32_t myexponent = (i >> 23) & 0xff;
3118 uint32_t mysignificand = i & 0x7fffff;
3119
Dale Johannesen343e7702007-08-24 00:56:33 +00003120 initialize(&APFloat::IEEEsingle);
Dale Johannesen343e7702007-08-24 00:56:33 +00003121 assert(partCount()==1);
3122
Dale Johanneseneaf08942007-08-31 04:03:46 +00003123 sign = i >> 31;
Dale Johannesen343e7702007-08-24 00:56:33 +00003124 if (myexponent==0 && mysignificand==0) {
3125 // exponent, significand meaningless
3126 category = fcZero;
Dale Johannesen343e7702007-08-24 00:56:33 +00003127 } else if (myexponent==0xff && mysignificand==0) {
3128 // exponent, significand meaningless
3129 category = fcInfinity;
Dale Johannesen902ff942007-09-25 17:25:00 +00003130 } else if (myexponent==0xff && mysignificand!=0) {
Dale Johannesen343e7702007-08-24 00:56:33 +00003131 // sign, exponent, significand meaningless
Dale Johanneseneaf08942007-08-31 04:03:46 +00003132 category = fcNaN;
3133 *significandParts() = mysignificand;
Dale Johannesen343e7702007-08-24 00:56:33 +00003134 } else {
3135 category = fcNormal;
Dale Johannesen343e7702007-08-24 00:56:33 +00003136 exponent = myexponent - 127; //bias
Dale Johannesen58c2e4c2007-09-05 20:39:49 +00003137 *significandParts() = mysignificand;
3138 if (myexponent==0) // denormal
3139 exponent = -126;
3140 else
3141 *significandParts() |= 0x800000; // integer bit
Dale Johannesen343e7702007-08-24 00:56:33 +00003142 }
3143}
Dale Johannesen3f6eb742007-09-11 18:32:33 +00003144
Chris Lattnercc4287a2009-10-16 02:13:51 +00003145void
3146APFloat::initFromHalfAPInt(const APInt & api)
3147{
3148 assert(api.getBitWidth()==16);
3149 uint32_t i = (uint32_t)*api.getRawData();
Dale Johannesena223aed2009-10-23 04:02:51 +00003150 uint32_t myexponent = (i >> 10) & 0x1f;
Chris Lattnercc4287a2009-10-16 02:13:51 +00003151 uint32_t mysignificand = i & 0x3ff;
3152
3153 initialize(&APFloat::IEEEhalf);
3154 assert(partCount()==1);
3155
3156 sign = i >> 15;
3157 if (myexponent==0 && mysignificand==0) {
3158 // exponent, significand meaningless
3159 category = fcZero;
3160 } else if (myexponent==0x1f && mysignificand==0) {
3161 // exponent, significand meaningless
3162 category = fcInfinity;
3163 } else if (myexponent==0x1f && mysignificand!=0) {
3164 // sign, exponent, significand meaningless
3165 category = fcNaN;
3166 *significandParts() = mysignificand;
3167 } else {
3168 category = fcNormal;
3169 exponent = myexponent - 15; //bias
3170 *significandParts() = mysignificand;
3171 if (myexponent==0) // denormal
3172 exponent = -14;
3173 else
3174 *significandParts() |= 0x400; // integer bit
3175 }
3176}
3177
Dale Johannesen3f6eb742007-09-11 18:32:33 +00003178/// Treat api as containing the bits of a floating point number. Currently
Dale Johannesena471c2e2007-10-11 18:07:22 +00003179/// we infer the floating point type from the size of the APInt. The
3180/// isIEEE argument distinguishes between PPC128 and IEEE128 (not meaningful
3181/// when the size is anything else).
Dale Johannesen3f6eb742007-09-11 18:32:33 +00003182void
Dale Johannesena471c2e2007-10-11 18:07:22 +00003183APFloat::initFromAPInt(const APInt& api, bool isIEEE)
Neil Booth4f881702007-09-26 21:33:42 +00003184{
Chris Lattnercc4287a2009-10-16 02:13:51 +00003185 if (api.getBitWidth() == 16)
3186 return initFromHalfAPInt(api);
3187 else if (api.getBitWidth() == 32)
Dale Johannesen3f6eb742007-09-11 18:32:33 +00003188 return initFromFloatAPInt(api);
3189 else if (api.getBitWidth()==64)
3190 return initFromDoubleAPInt(api);
3191 else if (api.getBitWidth()==80)
3192 return initFromF80LongDoubleAPInt(api);
Anton Korobeynikov7e844f12009-08-21 22:10:30 +00003193 else if (api.getBitWidth()==128)
3194 return (isIEEE ?
3195 initFromQuadrupleAPInt(api) : initFromPPCDoubleDoubleAPInt(api));
Dale Johannesen3f6eb742007-09-11 18:32:33 +00003196 else
Torok Edwinc23197a2009-07-14 16:55:14 +00003197 llvm_unreachable(0);
Dale Johannesen3f6eb742007-09-11 18:32:33 +00003198}
3199
John McCall00e65de2009-12-24 08:56:26 +00003200APFloat APFloat::getLargest(const fltSemantics &Sem, bool Negative) {
3201 APFloat Val(Sem, fcNormal, Negative);
3202
3203 // We want (in interchange format):
3204 // sign = {Negative}
3205 // exponent = 1..10
3206 // significand = 1..1
3207
3208 Val.exponent = Sem.maxExponent; // unbiased
3209
3210 // 1-initialize all bits....
3211 Val.zeroSignificand();
3212 integerPart *significand = Val.significandParts();
3213 unsigned N = partCountForBits(Sem.precision);
3214 for (unsigned i = 0; i != N; ++i)
3215 significand[i] = ~((integerPart) 0);
3216
3217 // ...and then clear the top bits for internal consistency.
Dan Gohman16e02092010-03-24 19:38:02 +00003218 significand[N-1] &=
3219 (((integerPart) 1) << ((Sem.precision % integerPartWidth) - 1)) - 1;
John McCall00e65de2009-12-24 08:56:26 +00003220
3221 return Val;
3222}
3223
3224APFloat APFloat::getSmallest(const fltSemantics &Sem, bool Negative) {
3225 APFloat Val(Sem, fcNormal, Negative);
3226
3227 // We want (in interchange format):
3228 // sign = {Negative}
3229 // exponent = 0..0
3230 // significand = 0..01
3231
3232 Val.exponent = Sem.minExponent; // unbiased
3233 Val.zeroSignificand();
3234 Val.significandParts()[0] = 1;
3235 return Val;
3236}
3237
3238APFloat APFloat::getSmallestNormalized(const fltSemantics &Sem, bool Negative) {
3239 APFloat Val(Sem, fcNormal, Negative);
3240
3241 // We want (in interchange format):
3242 // sign = {Negative}
3243 // exponent = 0..0
3244 // significand = 10..0
3245
3246 Val.exponent = Sem.minExponent;
3247 Val.zeroSignificand();
Dan Gohman16e02092010-03-24 19:38:02 +00003248 Val.significandParts()[partCountForBits(Sem.precision)-1] |=
3249 (((integerPart) 1) << ((Sem.precision % integerPartWidth) - 1));
John McCall00e65de2009-12-24 08:56:26 +00003250
3251 return Val;
3252}
3253
Dale Johannesena471c2e2007-10-11 18:07:22 +00003254APFloat::APFloat(const APInt& api, bool isIEEE)
Neil Booth4f881702007-09-26 21:33:42 +00003255{
Dale Johannesena471c2e2007-10-11 18:07:22 +00003256 initFromAPInt(api, isIEEE);
Dale Johannesen3f6eb742007-09-11 18:32:33 +00003257}
3258
Neil Booth4f881702007-09-26 21:33:42 +00003259APFloat::APFloat(float f)
3260{
Dale Johannesen3f6eb742007-09-11 18:32:33 +00003261 APInt api = APInt(32, 0);
3262 initFromAPInt(api.floatToBits(f));
3263}
3264
Neil Booth4f881702007-09-26 21:33:42 +00003265APFloat::APFloat(double d)
3266{
Dale Johannesen3f6eb742007-09-11 18:32:33 +00003267 APInt api = APInt(64, 0);
3268 initFromAPInt(api.doubleToBits(d));
3269}
John McCall00e65de2009-12-24 08:56:26 +00003270
3271namespace {
3272 static void append(SmallVectorImpl<char> &Buffer,
3273 unsigned N, const char *Str) {
3274 unsigned Start = Buffer.size();
3275 Buffer.set_size(Start + N);
3276 memcpy(&Buffer[Start], Str, N);
3277 }
3278
3279 template <unsigned N>
3280 void append(SmallVectorImpl<char> &Buffer, const char (&Str)[N]) {
3281 append(Buffer, N, Str);
3282 }
3283
John McCall003a09c2009-12-24 12:16:56 +00003284 /// Removes data from the given significand until it is no more
3285 /// precise than is required for the desired precision.
3286 void AdjustToPrecision(APInt &significand,
3287 int &exp, unsigned FormatPrecision) {
3288 unsigned bits = significand.getActiveBits();
3289
3290 // 196/59 is a very slight overestimate of lg_2(10).
3291 unsigned bitsRequired = (FormatPrecision * 196 + 58) / 59;
3292
3293 if (bits <= bitsRequired) return;
3294
3295 unsigned tensRemovable = (bits - bitsRequired) * 59 / 196;
3296 if (!tensRemovable) return;
3297
3298 exp += tensRemovable;
3299
3300 APInt divisor(significand.getBitWidth(), 1);
3301 APInt powten(significand.getBitWidth(), 10);
3302 while (true) {
3303 if (tensRemovable & 1)
3304 divisor *= powten;
3305 tensRemovable >>= 1;
3306 if (!tensRemovable) break;
3307 powten *= powten;
3308 }
3309
3310 significand = significand.udiv(divisor);
3311
3312 // Truncate the significand down to its active bit count, but
3313 // don't try to drop below 32.
John McCall6a09aff2009-12-24 23:18:09 +00003314 unsigned newPrecision = std::max(32U, significand.getActiveBits());
John McCall003a09c2009-12-24 12:16:56 +00003315 significand.trunc(newPrecision);
3316 }
3317
3318
John McCall00e65de2009-12-24 08:56:26 +00003319 void AdjustToPrecision(SmallVectorImpl<char> &buffer,
3320 int &exp, unsigned FormatPrecision) {
3321 unsigned N = buffer.size();
3322 if (N <= FormatPrecision) return;
3323
3324 // The most significant figures are the last ones in the buffer.
3325 unsigned FirstSignificant = N - FormatPrecision;
3326
3327 // Round.
3328 // FIXME: this probably shouldn't use 'round half up'.
3329
3330 // Rounding down is just a truncation, except we also want to drop
3331 // trailing zeros from the new result.
3332 if (buffer[FirstSignificant - 1] < '5') {
3333 while (buffer[FirstSignificant] == '0')
3334 FirstSignificant++;
3335
3336 exp += FirstSignificant;
3337 buffer.erase(&buffer[0], &buffer[FirstSignificant]);
3338 return;
3339 }
3340
3341 // Rounding up requires a decimal add-with-carry. If we continue
3342 // the carry, the newly-introduced zeros will just be truncated.
3343 for (unsigned I = FirstSignificant; I != N; ++I) {
3344 if (buffer[I] == '9') {
3345 FirstSignificant++;
3346 } else {
3347 buffer[I]++;
3348 break;
3349 }
3350 }
3351
3352 // If we carried through, we have exactly one digit of precision.
3353 if (FirstSignificant == N) {
3354 exp += FirstSignificant;
3355 buffer.clear();
3356 buffer.push_back('1');
3357 return;
3358 }
3359
3360 exp += FirstSignificant;
3361 buffer.erase(&buffer[0], &buffer[FirstSignificant]);
3362 }
3363}
3364
3365void APFloat::toString(SmallVectorImpl<char> &Str,
3366 unsigned FormatPrecision,
Chris Lattner0ddda3b2010-03-06 19:20:13 +00003367 unsigned FormatMaxPadding) const {
John McCall00e65de2009-12-24 08:56:26 +00003368 switch (category) {
3369 case fcInfinity:
3370 if (isNegative())
3371 return append(Str, "-Inf");
3372 else
3373 return append(Str, "+Inf");
3374
3375 case fcNaN: return append(Str, "NaN");
3376
3377 case fcZero:
3378 if (isNegative())
3379 Str.push_back('-');
3380
3381 if (!FormatMaxPadding)
3382 append(Str, "0.0E+0");
3383 else
3384 Str.push_back('0');
3385 return;
3386
3387 case fcNormal:
3388 break;
3389 }
3390
3391 if (isNegative())
3392 Str.push_back('-');
3393
3394 // Decompose the number into an APInt and an exponent.
3395 int exp = exponent - ((int) semantics->precision - 1);
3396 APInt significand(semantics->precision,
3397 partCountForBits(semantics->precision),
3398 significandParts());
3399
John McCall6a09aff2009-12-24 23:18:09 +00003400 // Set FormatPrecision if zero. We want to do this before we
3401 // truncate trailing zeros, as those are part of the precision.
3402 if (!FormatPrecision) {
3403 // It's an interesting question whether to use the nominal
3404 // precision or the active precision here for denormals.
3405
3406 // FormatPrecision = ceil(significandBits / lg_2(10))
3407 FormatPrecision = (semantics->precision * 59 + 195) / 196;
3408 }
3409
John McCall00e65de2009-12-24 08:56:26 +00003410 // Ignore trailing binary zeros.
3411 int trailingZeros = significand.countTrailingZeros();
3412 exp += trailingZeros;
3413 significand = significand.lshr(trailingZeros);
3414
3415 // Change the exponent from 2^e to 10^e.
3416 if (exp == 0) {
3417 // Nothing to do.
3418 } else if (exp > 0) {
3419 // Just shift left.
3420 significand.zext(semantics->precision + exp);
3421 significand <<= exp;
3422 exp = 0;
3423 } else { /* exp < 0 */
3424 int texp = -exp;
3425
3426 // We transform this using the identity:
3427 // (N)(2^-e) == (N)(5^e)(10^-e)
3428 // This means we have to multiply N (the significand) by 5^e.
3429 // To avoid overflow, we have to operate on numbers large
3430 // enough to store N * 5^e:
3431 // log2(N * 5^e) == log2(N) + e * log2(5)
John McCall6a09aff2009-12-24 23:18:09 +00003432 // <= semantics->precision + e * 137 / 59
3433 // (log_2(5) ~ 2.321928 < 2.322034 ~ 137/59)
Dan Gohman16e02092010-03-24 19:38:02 +00003434
John McCall6a09aff2009-12-24 23:18:09 +00003435 unsigned precision = semantics->precision + 137 * texp / 59;
John McCall00e65de2009-12-24 08:56:26 +00003436
3437 // Multiply significand by 5^e.
3438 // N * 5^0101 == N * 5^(1*1) * 5^(0*2) * 5^(1*4) * 5^(0*8)
3439 significand.zext(precision);
3440 APInt five_to_the_i(precision, 5);
3441 while (true) {
3442 if (texp & 1) significand *= five_to_the_i;
Dan Gohman16e02092010-03-24 19:38:02 +00003443
John McCall00e65de2009-12-24 08:56:26 +00003444 texp >>= 1;
3445 if (!texp) break;
3446 five_to_the_i *= five_to_the_i;
3447 }
3448 }
3449
John McCall003a09c2009-12-24 12:16:56 +00003450 AdjustToPrecision(significand, exp, FormatPrecision);
3451
John McCall00e65de2009-12-24 08:56:26 +00003452 llvm::SmallVector<char, 256> buffer;
3453
3454 // Fill the buffer.
3455 unsigned precision = significand.getBitWidth();
3456 APInt ten(precision, 10);
3457 APInt digit(precision, 0);
3458
3459 bool inTrail = true;
3460 while (significand != 0) {
3461 // digit <- significand % 10
3462 // significand <- significand / 10
3463 APInt::udivrem(significand, ten, significand, digit);
3464
3465 unsigned d = digit.getZExtValue();
3466
3467 // Drop trailing zeros.
3468 if (inTrail && !d) exp++;
3469 else {
3470 buffer.push_back((char) ('0' + d));
3471 inTrail = false;
3472 }
3473 }
3474
3475 assert(!buffer.empty() && "no characters in buffer!");
3476
3477 // Drop down to FormatPrecision.
3478 // TODO: don't do more precise calculations above than are required.
3479 AdjustToPrecision(buffer, exp, FormatPrecision);
3480
3481 unsigned NDigits = buffer.size();
3482
John McCall6a09aff2009-12-24 23:18:09 +00003483 // Check whether we should use scientific notation.
John McCall00e65de2009-12-24 08:56:26 +00003484 bool FormatScientific;
3485 if (!FormatMaxPadding)
3486 FormatScientific = true;
3487 else {
John McCall00e65de2009-12-24 08:56:26 +00003488 if (exp >= 0) {
John McCall6a09aff2009-12-24 23:18:09 +00003489 // 765e3 --> 765000
3490 // ^^^
3491 // But we shouldn't make the number look more precise than it is.
3492 FormatScientific = ((unsigned) exp > FormatMaxPadding ||
3493 NDigits + (unsigned) exp > FormatPrecision);
John McCall00e65de2009-12-24 08:56:26 +00003494 } else {
John McCall6a09aff2009-12-24 23:18:09 +00003495 // Power of the most significant digit.
3496 int MSD = exp + (int) (NDigits - 1);
3497 if (MSD >= 0) {
John McCall00e65de2009-12-24 08:56:26 +00003498 // 765e-2 == 7.65
John McCall6a09aff2009-12-24 23:18:09 +00003499 FormatScientific = false;
John McCall00e65de2009-12-24 08:56:26 +00003500 } else {
3501 // 765e-5 == 0.00765
3502 // ^ ^^
John McCall6a09aff2009-12-24 23:18:09 +00003503 FormatScientific = ((unsigned) -MSD) > FormatMaxPadding;
John McCall00e65de2009-12-24 08:56:26 +00003504 }
3505 }
John McCall00e65de2009-12-24 08:56:26 +00003506 }
3507
3508 // Scientific formatting is pretty straightforward.
3509 if (FormatScientific) {
3510 exp += (NDigits - 1);
3511
3512 Str.push_back(buffer[NDigits-1]);
3513 Str.push_back('.');
3514 if (NDigits == 1)
3515 Str.push_back('0');
3516 else
3517 for (unsigned I = 1; I != NDigits; ++I)
3518 Str.push_back(buffer[NDigits-1-I]);
3519 Str.push_back('E');
3520
3521 Str.push_back(exp >= 0 ? '+' : '-');
3522 if (exp < 0) exp = -exp;
3523 SmallVector<char, 6> expbuf;
3524 do {
3525 expbuf.push_back((char) ('0' + (exp % 10)));
3526 exp /= 10;
3527 } while (exp);
3528 for (unsigned I = 0, E = expbuf.size(); I != E; ++I)
3529 Str.push_back(expbuf[E-1-I]);
3530 return;
3531 }
3532
3533 // Non-scientific, positive exponents.
3534 if (exp >= 0) {
3535 for (unsigned I = 0; I != NDigits; ++I)
3536 Str.push_back(buffer[NDigits-1-I]);
3537 for (unsigned I = 0; I != (unsigned) exp; ++I)
3538 Str.push_back('0');
3539 return;
3540 }
3541
3542 // Non-scientific, negative exponents.
3543
3544 // The number of digits to the left of the decimal point.
3545 int NWholeDigits = exp + (int) NDigits;
3546
3547 unsigned I = 0;
3548 if (NWholeDigits > 0) {
3549 for (; I != (unsigned) NWholeDigits; ++I)
3550 Str.push_back(buffer[NDigits-I-1]);
3551 Str.push_back('.');
3552 } else {
3553 unsigned NZeros = 1 + (unsigned) -NWholeDigits;
3554
3555 Str.push_back('0');
3556 Str.push_back('.');
3557 for (unsigned Z = 1; Z != NZeros; ++Z)
3558 Str.push_back('0');
3559 }
3560
3561 for (; I != NDigits; ++I)
3562 Str.push_back(buffer[NDigits-I-1]);
3563}