blob: b9b323c4242826176685eee547857b58325639e7 [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"
Chris Lattnerfad86b02008-08-17 07:19:36 +000020#include <cstring>
Chris Lattnerb39cdde2007-08-20 22:49:32 +000021
22using namespace llvm;
23
24#define convolve(lhs, rhs) ((lhs) * 4 + (rhs))
25
Neil Bootha30b0ee2007-10-03 22:26:02 +000026/* Assumed in hexadecimal significand parsing, and conversion to
27 hexadecimal strings. */
Chris Lattner9f17eb02008-08-17 04:58:58 +000028#define COMPILE_TIME_ASSERT(cond) extern int CTAssert[(cond) ? 1 : -1]
Chris Lattnerb39cdde2007-08-20 22:49:32 +000029COMPILE_TIME_ASSERT(integerPartWidth % 4 == 0);
30
31namespace llvm {
32
33 /* Represents floating point arithmetic semantics. */
34 struct fltSemantics {
35 /* The largest E such that 2^E is representable; this matches the
36 definition of IEEE 754. */
37 exponent_t maxExponent;
38
39 /* The smallest E such that 2^E is a normalized number; this
40 matches the definition of IEEE 754. */
41 exponent_t minExponent;
42
43 /* Number of bits in the significand. This includes the integer
44 bit. */
Neil Booth7a951ca2007-10-12 15:33:27 +000045 unsigned int precision;
Neil Boothcaf19d72007-10-14 10:29:28 +000046
47 /* True if arithmetic is supported. */
48 unsigned int arithmeticOK;
Chris Lattnerb39cdde2007-08-20 22:49:32 +000049 };
50
Chris Lattnercc4287a2009-10-16 02:13:51 +000051 const fltSemantics APFloat::IEEEhalf = { 15, -14, 11, true };
Neil Boothcaf19d72007-10-14 10:29:28 +000052 const fltSemantics APFloat::IEEEsingle = { 127, -126, 24, true };
53 const fltSemantics APFloat::IEEEdouble = { 1023, -1022, 53, true };
54 const fltSemantics APFloat::IEEEquad = { 16383, -16382, 113, true };
55 const fltSemantics APFloat::x87DoubleExtended = { 16383, -16382, 64, true };
56 const fltSemantics APFloat::Bogus = { 0, 0, 0, true };
Dale Johannesena471c2e2007-10-11 18:07:22 +000057
58 // The PowerPC format consists of two doubles. It does not map cleanly
59 // onto the usual format above. For now only storage of constants of
60 // this type is supported, no arithmetic.
Neil Boothcaf19d72007-10-14 10:29:28 +000061 const fltSemantics APFloat::PPCDoubleDouble = { 1023, -1022, 106, false };
Neil Booth96c74712007-10-12 16:02:31 +000062
63 /* A tight upper bound on number of parts required to hold the value
64 pow(5, power) is
65
Neil Booth686700e2007-10-15 15:00:55 +000066 power * 815 / (351 * integerPartWidth) + 1
Neil Booth96c74712007-10-12 16:02:31 +000067
68 However, whilst the result may require only this many parts,
69 because we are multiplying two values to get it, the
70 multiplication may require an extra part with the excess part
71 being zero (consider the trivial case of 1 * 1, tcFullMultiply
72 requires two parts to hold the single-part result). So we add an
73 extra one to guarantee enough space whilst multiplying. */
74 const unsigned int maxExponent = 16383;
75 const unsigned int maxPrecision = 113;
76 const unsigned int maxPowerOfFiveExponent = maxExponent + maxPrecision - 1;
Neil Booth686700e2007-10-15 15:00:55 +000077 const unsigned int maxPowerOfFiveParts = 2 + ((maxPowerOfFiveExponent * 815)
78 / (351 * integerPartWidth));
Chris Lattnerb39cdde2007-08-20 22:49:32 +000079}
80
Chris Lattnere213f3f2009-03-12 23:59:55 +000081/* A bunch of private, handy routines. */
Chris Lattnerb39cdde2007-08-20 22:49:32 +000082
Chris Lattnere213f3f2009-03-12 23:59:55 +000083static inline unsigned int
84partCountForBits(unsigned int bits)
85{
86 return ((bits) + integerPartWidth - 1) / integerPartWidth;
87}
Chris Lattnerb39cdde2007-08-20 22:49:32 +000088
Chris Lattnere213f3f2009-03-12 23:59:55 +000089/* Returns 0U-9U. Return values >= 10U are not digits. */
90static inline unsigned int
91decDigitValue(unsigned int c)
92{
93 return c - '0';
94}
Chris Lattnerb39cdde2007-08-20 22:49:32 +000095
Chris Lattnere213f3f2009-03-12 23:59:55 +000096static unsigned int
97hexDigitValue(unsigned int c)
98{
99 unsigned int r;
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000100
Chris Lattnere213f3f2009-03-12 23:59:55 +0000101 r = c - '0';
102 if(r <= 9)
103 return r;
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000104
Chris Lattnere213f3f2009-03-12 23:59:55 +0000105 r = c - 'A';
106 if(r <= 5)
107 return r + 10;
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000108
Chris Lattnere213f3f2009-03-12 23:59:55 +0000109 r = c - 'a';
110 if(r <= 5)
111 return r + 10;
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000112
Chris Lattnere213f3f2009-03-12 23:59:55 +0000113 return -1U;
114}
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000115
Chris Lattnere213f3f2009-03-12 23:59:55 +0000116static inline void
117assertArithmeticOK(const llvm::fltSemantics &semantics) {
118 assert(semantics.arithmeticOK
119 && "Compile-time arithmetic does not support these semantics");
120}
Neil Boothcaf19d72007-10-14 10:29:28 +0000121
Chris Lattnere213f3f2009-03-12 23:59:55 +0000122/* Return the value of a decimal exponent of the form
123 [+-]ddddddd.
Neil Booth1870f292007-10-14 10:16:12 +0000124
Chris Lattnere213f3f2009-03-12 23:59:55 +0000125 If the exponent overflows, returns a large exponent with the
126 appropriate sign. */
127static int
Erick Tryzelaara15d8902009-08-16 23:36:19 +0000128readExponent(StringRef::iterator begin, StringRef::iterator end)
Chris Lattnere213f3f2009-03-12 23:59:55 +0000129{
130 bool isNegative;
131 unsigned int absExponent;
132 const unsigned int overlargeExponent = 24000; /* FIXME. */
Erick Tryzelaara15d8902009-08-16 23:36:19 +0000133 StringRef::iterator p = begin;
134
135 assert(p != end && "Exponent has no digits");
Neil Booth1870f292007-10-14 10:16:12 +0000136
Chris Lattnere213f3f2009-03-12 23:59:55 +0000137 isNegative = (*p == '-');
Erick Tryzelaara15d8902009-08-16 23:36:19 +0000138 if (*p == '-' || *p == '+') {
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000139 p++;
Erick Tryzelaara15d8902009-08-16 23:36:19 +0000140 assert(p != end && "Exponent has no digits");
141 }
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000142
Chris Lattnere213f3f2009-03-12 23:59:55 +0000143 absExponent = decDigitValue(*p++);
Erick Tryzelaara15d8902009-08-16 23:36:19 +0000144 assert(absExponent < 10U && "Invalid character in exponent");
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000145
Erick Tryzelaara15d8902009-08-16 23:36:19 +0000146 for (; p != end; ++p) {
Chris Lattnere213f3f2009-03-12 23:59:55 +0000147 unsigned int value;
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000148
Chris Lattnere213f3f2009-03-12 23:59:55 +0000149 value = decDigitValue(*p);
Erick Tryzelaara15d8902009-08-16 23:36:19 +0000150 assert(value < 10U && "Invalid character in exponent");
Chris Lattnere213f3f2009-03-12 23:59:55 +0000151
Chris Lattnere213f3f2009-03-12 23:59:55 +0000152 value += absExponent * 10;
153 if (absExponent >= overlargeExponent) {
154 absExponent = overlargeExponent;
155 break;
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000156 }
Chris Lattnere213f3f2009-03-12 23:59:55 +0000157 absExponent = value;
158 }
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000159
Erick Tryzelaara15d8902009-08-16 23:36:19 +0000160 assert(p == end && "Invalid exponent in exponent");
161
Chris Lattnere213f3f2009-03-12 23:59:55 +0000162 if (isNegative)
163 return -(int) absExponent;
164 else
165 return (int) absExponent;
166}
167
168/* This is ugly and needs cleaning up, but I don't immediately see
169 how whilst remaining safe. */
170static int
Erick Tryzelaara15d8902009-08-16 23:36:19 +0000171totalExponent(StringRef::iterator p, StringRef::iterator end,
172 int exponentAdjustment)
Chris Lattnere213f3f2009-03-12 23:59:55 +0000173{
174 int unsignedExponent;
175 bool negative, overflow;
176 int exponent;
177
Erick Tryzelaarc78b33b2009-08-20 23:30:43 +0000178 assert(p != end && "Exponent has no digits");
179
Chris Lattnere213f3f2009-03-12 23:59:55 +0000180 negative = *p == '-';
Erick Tryzelaarc78b33b2009-08-20 23:30:43 +0000181 if(*p == '-' || *p == '+') {
Chris Lattnere213f3f2009-03-12 23:59:55 +0000182 p++;
Erick Tryzelaarc78b33b2009-08-20 23:30:43 +0000183 assert(p != end && "Exponent has no digits");
184 }
Chris Lattnere213f3f2009-03-12 23:59:55 +0000185
186 unsignedExponent = 0;
187 overflow = false;
Erick Tryzelaara15d8902009-08-16 23:36:19 +0000188 for(; p != end; ++p) {
Chris Lattnere213f3f2009-03-12 23:59:55 +0000189 unsigned int value;
190
191 value = decDigitValue(*p);
Erick Tryzelaara15d8902009-08-16 23:36:19 +0000192 assert(value < 10U && "Invalid character in exponent");
Chris Lattnere213f3f2009-03-12 23:59:55 +0000193
Chris Lattnere213f3f2009-03-12 23:59:55 +0000194 unsignedExponent = unsignedExponent * 10 + value;
195 if(unsignedExponent > 65535)
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000196 overflow = true;
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000197 }
198
Chris Lattnere213f3f2009-03-12 23:59:55 +0000199 if(exponentAdjustment > 65535 || exponentAdjustment < -65536)
200 overflow = true;
201
202 if(!overflow) {
203 exponent = unsignedExponent;
204 if(negative)
205 exponent = -exponent;
206 exponent += exponentAdjustment;
207 if(exponent > 65535 || exponent < -65536)
208 overflow = true;
209 }
210
211 if(overflow)
212 exponent = negative ? -65536: 65535;
213
214 return exponent;
215}
216
Erick Tryzelaara15d8902009-08-16 23:36:19 +0000217static StringRef::iterator
218skipLeadingZeroesAndAnyDot(StringRef::iterator begin, StringRef::iterator end,
219 StringRef::iterator *dot)
Chris Lattnere213f3f2009-03-12 23:59:55 +0000220{
Erick Tryzelaara15d8902009-08-16 23:36:19 +0000221 StringRef::iterator p = begin;
222 *dot = end;
223 while(*p == '0' && p != end)
Chris Lattnere213f3f2009-03-12 23:59:55 +0000224 p++;
225
226 if(*p == '.') {
227 *dot = p++;
Erick Tryzelaara15d8902009-08-16 23:36:19 +0000228
Erick Tryzelaarc78b33b2009-08-20 23:30:43 +0000229 assert(end - begin != 1 && "Significand has no digits");
Erick Tryzelaara15d8902009-08-16 23:36:19 +0000230
231 while(*p == '0' && p != end)
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000232 p++;
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000233 }
234
Chris Lattnere213f3f2009-03-12 23:59:55 +0000235 return p;
236}
Neil Booth1870f292007-10-14 10:16:12 +0000237
Chris Lattnere213f3f2009-03-12 23:59:55 +0000238/* Given a normal decimal floating point number of the form
Neil Booth1870f292007-10-14 10:16:12 +0000239
Chris Lattnere213f3f2009-03-12 23:59:55 +0000240 dddd.dddd[eE][+-]ddd
Neil Booth686700e2007-10-15 15:00:55 +0000241
Chris Lattnere213f3f2009-03-12 23:59:55 +0000242 where the decimal point and exponent are optional, fill out the
243 structure D. Exponent is appropriate if the significand is
244 treated as an integer, and normalizedExponent if the significand
245 is taken to have the decimal point after a single leading
246 non-zero digit.
Neil Booth1870f292007-10-14 10:16:12 +0000247
Chris Lattnere213f3f2009-03-12 23:59:55 +0000248 If the value is zero, V->firstSigDigit points to a non-digit, and
249 the return exponent is zero.
250*/
251struct decimalInfo {
252 const char *firstSigDigit;
253 const char *lastSigDigit;
254 int exponent;
255 int normalizedExponent;
256};
Neil Booth1870f292007-10-14 10:16:12 +0000257
Chris Lattnere213f3f2009-03-12 23:59:55 +0000258static void
Erick Tryzelaara15d8902009-08-16 23:36:19 +0000259interpretDecimal(StringRef::iterator begin, StringRef::iterator end,
260 decimalInfo *D)
Chris Lattnere213f3f2009-03-12 23:59:55 +0000261{
Erick Tryzelaara15d8902009-08-16 23:36:19 +0000262 StringRef::iterator dot = end;
263 StringRef::iterator p = skipLeadingZeroesAndAnyDot (begin, end, &dot);
Neil Booth1870f292007-10-14 10:16:12 +0000264
Chris Lattnere213f3f2009-03-12 23:59:55 +0000265 D->firstSigDigit = p;
266 D->exponent = 0;
267 D->normalizedExponent = 0;
268
Erick Tryzelaara15d8902009-08-16 23:36:19 +0000269 for (; p != end; ++p) {
Chris Lattnere213f3f2009-03-12 23:59:55 +0000270 if (*p == '.') {
Erick Tryzelaarc78b33b2009-08-20 23:30:43 +0000271 assert(dot == end && "String contains multiple dots");
Chris Lattnere213f3f2009-03-12 23:59:55 +0000272 dot = p++;
Erick Tryzelaara15d8902009-08-16 23:36:19 +0000273 if (p == end)
274 break;
Neil Booth1870f292007-10-14 10:16:12 +0000275 }
Chris Lattnere213f3f2009-03-12 23:59:55 +0000276 if (decDigitValue(*p) >= 10U)
277 break;
Chris Lattnere213f3f2009-03-12 23:59:55 +0000278 }
Neil Booth1870f292007-10-14 10:16:12 +0000279
Erick Tryzelaara15d8902009-08-16 23:36:19 +0000280 if (p != end) {
Erick Tryzelaarc78b33b2009-08-20 23:30:43 +0000281 assert((*p == 'e' || *p == 'E') && "Invalid character in significand");
282 assert(p != begin && "Significand has no digits");
283 assert((dot == end || p - begin != 1) && "Significand has no digits");
Erick Tryzelaara15d8902009-08-16 23:36:19 +0000284
285 /* p points to the first non-digit in the string */
Erick Tryzelaarc78b33b2009-08-20 23:30:43 +0000286 D->exponent = readExponent(p + 1, end);
Neil Booth1870f292007-10-14 10:16:12 +0000287
Chris Lattnere213f3f2009-03-12 23:59:55 +0000288 /* Implied decimal point? */
Erick Tryzelaara15d8902009-08-16 23:36:19 +0000289 if (dot == end)
Chris Lattnere213f3f2009-03-12 23:59:55 +0000290 dot = p;
Erick Tryzelaara15d8902009-08-16 23:36:19 +0000291 }
Neil Booth1870f292007-10-14 10:16:12 +0000292
Erick Tryzelaara15d8902009-08-16 23:36:19 +0000293 /* If number is all zeroes accept any exponent. */
294 if (p != D->firstSigDigit) {
Chris Lattnere213f3f2009-03-12 23:59:55 +0000295 /* Drop insignificant trailing zeroes. */
Erick Tryzelaara15d8902009-08-16 23:36:19 +0000296 if (p != begin) {
Neil Booth1870f292007-10-14 10:16:12 +0000297 do
Erick Tryzelaara15d8902009-08-16 23:36:19 +0000298 do
299 p--;
300 while (p != begin && *p == '0');
301 while (p != begin && *p == '.');
302 }
Neil Booth1870f292007-10-14 10:16:12 +0000303
Chris Lattnere213f3f2009-03-12 23:59:55 +0000304 /* Adjust the exponents for any decimal point. */
305 D->exponent += static_cast<exponent_t>((dot - p) - (dot > p));
306 D->normalizedExponent = (D->exponent +
307 static_cast<exponent_t>((p - D->firstSigDigit)
308 - (dot > D->firstSigDigit && dot < p)));
Neil Booth1870f292007-10-14 10:16:12 +0000309 }
310
Chris Lattnere213f3f2009-03-12 23:59:55 +0000311 D->lastSigDigit = p;
312}
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000313
Chris Lattnere213f3f2009-03-12 23:59:55 +0000314/* Return the trailing fraction of a hexadecimal number.
315 DIGITVALUE is the first hex digit of the fraction, P points to
316 the next digit. */
317static lostFraction
Erick Tryzelaara15d8902009-08-16 23:36:19 +0000318trailingHexadecimalFraction(StringRef::iterator p, StringRef::iterator end,
319 unsigned int digitValue)
Chris Lattnere213f3f2009-03-12 23:59:55 +0000320{
321 unsigned int hexDigit;
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000322
Chris Lattnere213f3f2009-03-12 23:59:55 +0000323 /* If the first trailing digit isn't 0 or 8 we can work out the
324 fraction immediately. */
325 if(digitValue > 8)
326 return lfMoreThanHalf;
327 else if(digitValue < 8 && digitValue > 0)
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000328 return lfLessThanHalf;
Chris Lattnere213f3f2009-03-12 23:59:55 +0000329
330 /* Otherwise we need to find the first non-zero digit. */
331 while(*p == '0')
332 p++;
333
Erick Tryzelaara15d8902009-08-16 23:36:19 +0000334 assert(p != end && "Invalid trailing hexadecimal fraction!");
335
Chris Lattnere213f3f2009-03-12 23:59:55 +0000336 hexDigit = hexDigitValue(*p);
337
338 /* If we ran off the end it is exactly zero or one-half, otherwise
339 a little more. */
340 if(hexDigit == -1U)
341 return digitValue == 0 ? lfExactlyZero: lfExactlyHalf;
342 else
343 return digitValue == 0 ? lfLessThanHalf: lfMoreThanHalf;
344}
345
346/* Return the fraction lost were a bignum truncated losing the least
347 significant BITS bits. */
348static lostFraction
349lostFractionThroughTruncation(const integerPart *parts,
350 unsigned int partCount,
351 unsigned int bits)
352{
353 unsigned int lsb;
354
355 lsb = APInt::tcLSB(parts, partCount);
356
357 /* Note this is guaranteed true if bits == 0, or LSB == -1U. */
358 if(bits <= lsb)
359 return lfExactlyZero;
360 if(bits == lsb + 1)
361 return lfExactlyHalf;
362 if(bits <= partCount * integerPartWidth
363 && APInt::tcExtractBit(parts, bits - 1))
364 return lfMoreThanHalf;
365
366 return lfLessThanHalf;
367}
368
369/* Shift DST right BITS bits noting lost fraction. */
370static lostFraction
371shiftRight(integerPart *dst, unsigned int parts, unsigned int bits)
372{
373 lostFraction lost_fraction;
374
375 lost_fraction = lostFractionThroughTruncation(dst, parts, bits);
376
377 APInt::tcShiftRight(dst, parts, bits);
378
379 return lost_fraction;
380}
381
382/* Combine the effect of two lost fractions. */
383static lostFraction
384combineLostFractions(lostFraction moreSignificant,
385 lostFraction lessSignificant)
386{
387 if(lessSignificant != lfExactlyZero) {
388 if(moreSignificant == lfExactlyZero)
389 moreSignificant = lfLessThanHalf;
390 else if(moreSignificant == lfExactlyHalf)
391 moreSignificant = lfMoreThanHalf;
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000392 }
393
Chris Lattnere213f3f2009-03-12 23:59:55 +0000394 return moreSignificant;
395}
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000396
Chris Lattnere213f3f2009-03-12 23:59:55 +0000397/* The error from the true value, in half-ulps, on multiplying two
398 floating point numbers, which differ from the value they
399 approximate by at most HUE1 and HUE2 half-ulps, is strictly less
400 than the returned value.
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000401
Chris Lattnere213f3f2009-03-12 23:59:55 +0000402 See "How to Read Floating Point Numbers Accurately" by William D
403 Clinger. */
404static unsigned int
405HUerrBound(bool inexactMultiply, unsigned int HUerr1, unsigned int HUerr2)
406{
407 assert(HUerr1 < 2 || HUerr2 < 2 || (HUerr1 + HUerr2 < 8));
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000408
Chris Lattnere213f3f2009-03-12 23:59:55 +0000409 if (HUerr1 + HUerr2 == 0)
410 return inexactMultiply * 2; /* <= inexactMultiply half-ulps. */
411 else
412 return inexactMultiply + 2 * (HUerr1 + HUerr2);
413}
Neil Bootha30b0ee2007-10-03 22:26:02 +0000414
Chris Lattnere213f3f2009-03-12 23:59:55 +0000415/* The number of ulps from the boundary (zero, or half if ISNEAREST)
416 when the least significant BITS are truncated. BITS cannot be
417 zero. */
418static integerPart
419ulpsFromBoundary(const integerPart *parts, unsigned int bits, bool isNearest)
420{
421 unsigned int count, partBits;
422 integerPart part, boundary;
Neil Booth33d4c922007-10-07 08:51:21 +0000423
Evan Cheng99ebfa52009-10-27 21:35:42 +0000424 assert(bits != 0);
Neil Bootha30b0ee2007-10-03 22:26:02 +0000425
Chris Lattnere213f3f2009-03-12 23:59:55 +0000426 bits--;
427 count = bits / integerPartWidth;
428 partBits = bits % integerPartWidth + 1;
Neil Booth96c74712007-10-12 16:02:31 +0000429
Chris Lattnere213f3f2009-03-12 23:59:55 +0000430 part = parts[count] & (~(integerPart) 0 >> (integerPartWidth - partBits));
Neil Booth96c74712007-10-12 16:02:31 +0000431
Chris Lattnere213f3f2009-03-12 23:59:55 +0000432 if (isNearest)
433 boundary = (integerPart) 1 << (partBits - 1);
434 else
435 boundary = 0;
436
437 if (count == 0) {
438 if (part - boundary <= boundary - part)
439 return part - boundary;
Neil Booth96c74712007-10-12 16:02:31 +0000440 else
Chris Lattnere213f3f2009-03-12 23:59:55 +0000441 return boundary - part;
Neil Booth96c74712007-10-12 16:02:31 +0000442 }
443
Chris Lattnere213f3f2009-03-12 23:59:55 +0000444 if (part == boundary) {
445 while (--count)
446 if (parts[count])
447 return ~(integerPart) 0; /* A lot. */
Neil Booth96c74712007-10-12 16:02:31 +0000448
Chris Lattnere213f3f2009-03-12 23:59:55 +0000449 return parts[0];
450 } else if (part == boundary - 1) {
451 while (--count)
452 if (~parts[count])
453 return ~(integerPart) 0; /* A lot. */
Neil Booth96c74712007-10-12 16:02:31 +0000454
Chris Lattnere213f3f2009-03-12 23:59:55 +0000455 return -parts[0];
456 }
Neil Booth96c74712007-10-12 16:02:31 +0000457
Chris Lattnere213f3f2009-03-12 23:59:55 +0000458 return ~(integerPart) 0; /* A lot. */
459}
Neil Booth96c74712007-10-12 16:02:31 +0000460
Chris Lattnere213f3f2009-03-12 23:59:55 +0000461/* Place pow(5, power) in DST, and return the number of parts used.
462 DST must be at least one part larger than size of the answer. */
463static unsigned int
464powerOf5(integerPart *dst, unsigned int power)
465{
466 static const integerPart firstEightPowers[] = { 1, 5, 25, 125, 625, 3125,
467 15625, 78125 };
Chris Lattneree167a72009-03-13 00:24:01 +0000468 integerPart pow5s[maxPowerOfFiveParts * 2 + 5];
469 pow5s[0] = 78125 * 5;
470
Chris Lattner807926a2009-03-13 00:03:51 +0000471 unsigned int partsCount[16] = { 1 };
Chris Lattnere213f3f2009-03-12 23:59:55 +0000472 integerPart scratch[maxPowerOfFiveParts], *p1, *p2, *pow5;
473 unsigned int result;
Chris Lattnere213f3f2009-03-12 23:59:55 +0000474 assert(power <= maxExponent);
475
476 p1 = dst;
477 p2 = scratch;
478
479 *p1 = firstEightPowers[power & 7];
480 power >>= 3;
481
482 result = 1;
483 pow5 = pow5s;
484
485 for (unsigned int n = 0; power; power >>= 1, n++) {
486 unsigned int pc;
487
488 pc = partsCount[n];
489
490 /* Calculate pow(5,pow(2,n+3)) if we haven't yet. */
491 if (pc == 0) {
492 pc = partsCount[n - 1];
493 APInt::tcFullMultiply(pow5, pow5 - pc, pow5 - pc, pc, pc);
494 pc *= 2;
495 if (pow5[pc - 1] == 0)
496 pc--;
497 partsCount[n] = pc;
Neil Booth96c74712007-10-12 16:02:31 +0000498 }
499
Chris Lattnere213f3f2009-03-12 23:59:55 +0000500 if (power & 1) {
501 integerPart *tmp;
Neil Booth96c74712007-10-12 16:02:31 +0000502
Chris Lattnere213f3f2009-03-12 23:59:55 +0000503 APInt::tcFullMultiply(p2, p1, pow5, result, pc);
504 result += pc;
505 if (p2[result - 1] == 0)
506 result--;
Neil Booth96c74712007-10-12 16:02:31 +0000507
Chris Lattnere213f3f2009-03-12 23:59:55 +0000508 /* Now result is in p1 with partsCount parts and p2 is scratch
509 space. */
510 tmp = p1, p1 = p2, p2 = tmp;
Neil Booth96c74712007-10-12 16:02:31 +0000511 }
512
Chris Lattnere213f3f2009-03-12 23:59:55 +0000513 pow5 += pc;
Neil Booth96c74712007-10-12 16:02:31 +0000514 }
515
Chris Lattnere213f3f2009-03-12 23:59:55 +0000516 if (p1 != dst)
517 APInt::tcAssign(dst, p1, result);
Neil Booth96c74712007-10-12 16:02:31 +0000518
Chris Lattnere213f3f2009-03-12 23:59:55 +0000519 return result;
520}
Neil Booth96c74712007-10-12 16:02:31 +0000521
Chris Lattnere213f3f2009-03-12 23:59:55 +0000522/* Zero at the end to avoid modular arithmetic when adding one; used
523 when rounding up during hexadecimal output. */
524static const char hexDigitsLower[] = "0123456789abcdef0";
525static const char hexDigitsUpper[] = "0123456789ABCDEF0";
526static const char infinityL[] = "infinity";
527static const char infinityU[] = "INFINITY";
528static const char NaNL[] = "nan";
529static const char NaNU[] = "NAN";
Neil Booth96c74712007-10-12 16:02:31 +0000530
Chris Lattnere213f3f2009-03-12 23:59:55 +0000531/* Write out an integerPart in hexadecimal, starting with the most
532 significant nibble. Write out exactly COUNT hexdigits, return
533 COUNT. */
534static unsigned int
535partAsHex (char *dst, integerPart part, unsigned int count,
536 const char *hexDigitChars)
537{
538 unsigned int result = count;
Neil Booth96c74712007-10-12 16:02:31 +0000539
Evan Cheng99ebfa52009-10-27 21:35:42 +0000540 assert(count != 0 && count <= integerPartWidth / 4);
Neil Booth96c74712007-10-12 16:02:31 +0000541
Chris Lattnere213f3f2009-03-12 23:59:55 +0000542 part >>= (integerPartWidth - 4 * count);
543 while (count--) {
544 dst[count] = hexDigitChars[part & 0xf];
545 part >>= 4;
Neil Booth96c74712007-10-12 16:02:31 +0000546 }
547
Chris Lattnere213f3f2009-03-12 23:59:55 +0000548 return result;
549}
Neil Bootha30b0ee2007-10-03 22:26:02 +0000550
Chris Lattnere213f3f2009-03-12 23:59:55 +0000551/* Write out an unsigned decimal integer. */
552static char *
553writeUnsignedDecimal (char *dst, unsigned int n)
554{
555 char buff[40], *p;
Neil Bootha30b0ee2007-10-03 22:26:02 +0000556
Chris Lattnere213f3f2009-03-12 23:59:55 +0000557 p = buff;
558 do
559 *p++ = '0' + n % 10;
560 while (n /= 10);
Neil Bootha30b0ee2007-10-03 22:26:02 +0000561
Chris Lattnere213f3f2009-03-12 23:59:55 +0000562 do
563 *dst++ = *--p;
564 while (p != buff);
Neil Bootha30b0ee2007-10-03 22:26:02 +0000565
Chris Lattnere213f3f2009-03-12 23:59:55 +0000566 return dst;
567}
Neil Bootha30b0ee2007-10-03 22:26:02 +0000568
Chris Lattnere213f3f2009-03-12 23:59:55 +0000569/* Write out a signed decimal integer. */
570static char *
571writeSignedDecimal (char *dst, int value)
572{
573 if (value < 0) {
574 *dst++ = '-';
575 dst = writeUnsignedDecimal(dst, -(unsigned) value);
576 } else
577 dst = writeUnsignedDecimal(dst, value);
Neil Bootha30b0ee2007-10-03 22:26:02 +0000578
Chris Lattnere213f3f2009-03-12 23:59:55 +0000579 return dst;
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000580}
581
582/* Constructors. */
583void
584APFloat::initialize(const fltSemantics *ourSemantics)
585{
586 unsigned int count;
587
588 semantics = ourSemantics;
589 count = partCount();
590 if(count > 1)
591 significand.parts = new integerPart[count];
592}
593
594void
595APFloat::freeSignificand()
596{
597 if(partCount() > 1)
598 delete [] significand.parts;
599}
600
601void
602APFloat::assign(const APFloat &rhs)
603{
604 assert(semantics == rhs.semantics);
605
606 sign = rhs.sign;
607 category = rhs.category;
608 exponent = rhs.exponent;
Dale Johannesena471c2e2007-10-11 18:07:22 +0000609 sign2 = rhs.sign2;
610 exponent2 = rhs.exponent2;
Dale Johanneseneaf08942007-08-31 04:03:46 +0000611 if(category == fcNormal || category == fcNaN)
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000612 copySignificand(rhs);
613}
614
615void
616APFloat::copySignificand(const APFloat &rhs)
617{
Dale Johanneseneaf08942007-08-31 04:03:46 +0000618 assert(category == fcNormal || category == fcNaN);
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000619 assert(rhs.partCount() >= partCount());
620
621 APInt::tcAssign(significandParts(), rhs.significandParts(),
Neil Booth4f881702007-09-26 21:33:42 +0000622 partCount());
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000623}
624
Neil Boothe5e01942007-10-14 10:39:51 +0000625/* Make this number a NaN, with an arbitrary but deterministic value
Dale Johannesen541ed9f2009-01-21 20:32:55 +0000626 for the significand. If double or longer, this is a signalling NaN,
Mike Stumpc5ca7132009-05-30 03:49:43 +0000627 which may not be ideal. If float, this is QNaN(0). */
Neil Boothe5e01942007-10-14 10:39:51 +0000628void
Mike Stumpc5ca7132009-05-30 03:49:43 +0000629APFloat::makeNaN(unsigned type)
Neil Boothe5e01942007-10-14 10:39:51 +0000630{
631 category = fcNaN;
Mike Stumpc5ca7132009-05-30 03:49:43 +0000632 // FIXME: Add double and long double support for QNaN(0).
633 if (semantics->precision == 24 && semantics->maxExponent == 127) {
634 type |= 0x7fc00000U;
635 type &= ~0x80000000U;
636 } else
637 type = ~0U;
638 APInt::tcSet(significandParts(), type, partCount());
Neil Boothe5e01942007-10-14 10:39:51 +0000639}
640
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000641APFloat &
642APFloat::operator=(const APFloat &rhs)
643{
644 if(this != &rhs) {
645 if(semantics != rhs.semantics) {
646 freeSignificand();
647 initialize(rhs.semantics);
648 }
649 assign(rhs);
650 }
651
652 return *this;
653}
654
Dale Johannesen343e7702007-08-24 00:56:33 +0000655bool
Dale Johannesen12595d72007-08-24 22:09:56 +0000656APFloat::bitwiseIsEqual(const APFloat &rhs) const {
Dale Johannesen343e7702007-08-24 00:56:33 +0000657 if (this == &rhs)
658 return true;
659 if (semantics != rhs.semantics ||
Dale Johanneseneaf08942007-08-31 04:03:46 +0000660 category != rhs.category ||
661 sign != rhs.sign)
Dale Johannesen343e7702007-08-24 00:56:33 +0000662 return false;
Dan Gohmanb10abe12008-01-29 12:08:20 +0000663 if (semantics==(const llvm::fltSemantics*)&PPCDoubleDouble &&
Dale Johannesena471c2e2007-10-11 18:07:22 +0000664 sign2 != rhs.sign2)
665 return false;
Dale Johanneseneaf08942007-08-31 04:03:46 +0000666 if (category==fcZero || category==fcInfinity)
Dale Johannesen343e7702007-08-24 00:56:33 +0000667 return true;
Dale Johanneseneaf08942007-08-31 04:03:46 +0000668 else if (category==fcNormal && exponent!=rhs.exponent)
669 return false;
Dan Gohmanb10abe12008-01-29 12:08:20 +0000670 else if (semantics==(const llvm::fltSemantics*)&PPCDoubleDouble &&
Dale Johannesena471c2e2007-10-11 18:07:22 +0000671 exponent2!=rhs.exponent2)
672 return false;
Dale Johannesen343e7702007-08-24 00:56:33 +0000673 else {
Dale Johannesen343e7702007-08-24 00:56:33 +0000674 int i= partCount();
675 const integerPart* p=significandParts();
676 const integerPart* q=rhs.significandParts();
677 for (; i>0; i--, p++, q++) {
678 if (*p != *q)
679 return false;
680 }
681 return true;
682 }
683}
684
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000685APFloat::APFloat(const fltSemantics &ourSemantics, integerPart value)
686{
Neil Boothcaf19d72007-10-14 10:29:28 +0000687 assertArithmeticOK(ourSemantics);
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000688 initialize(&ourSemantics);
689 sign = 0;
690 zeroSignificand();
691 exponent = ourSemantics.precision - 1;
692 significandParts()[0] = value;
693 normalize(rmNearestTiesToEven, lfExactlyZero);
694}
695
Chris Lattnerd7bd78e2009-09-17 01:08:43 +0000696APFloat::APFloat(const fltSemantics &ourSemantics) {
697 assertArithmeticOK(ourSemantics);
698 initialize(&ourSemantics);
699 category = fcZero;
700 sign = false;
701}
702
703
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000704APFloat::APFloat(const fltSemantics &ourSemantics,
Mike Stumpc5ca7132009-05-30 03:49:43 +0000705 fltCategory ourCategory, bool negative, unsigned type)
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000706{
Neil Boothcaf19d72007-10-14 10:29:28 +0000707 assertArithmeticOK(ourSemantics);
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000708 initialize(&ourSemantics);
709 category = ourCategory;
710 sign = negative;
Mike Stumpc5ca7132009-05-30 03:49:43 +0000711 if (category == fcNormal)
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000712 category = fcZero;
Neil Boothe5e01942007-10-14 10:39:51 +0000713 else if (ourCategory == fcNaN)
Mike Stumpc5ca7132009-05-30 03:49:43 +0000714 makeNaN(type);
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000715}
716
Erick Tryzelaara15d8902009-08-16 23:36:19 +0000717APFloat::APFloat(const fltSemantics &ourSemantics, const StringRef& text)
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000718{
Neil Boothcaf19d72007-10-14 10:29:28 +0000719 assertArithmeticOK(ourSemantics);
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000720 initialize(&ourSemantics);
721 convertFromString(text, rmNearestTiesToEven);
722}
723
724APFloat::APFloat(const APFloat &rhs)
725{
726 initialize(rhs.semantics);
727 assign(rhs);
728}
729
730APFloat::~APFloat()
731{
732 freeSignificand();
733}
734
Ted Kremenek1f801fa2008-02-11 17:24:50 +0000735// Profile - This method 'profiles' an APFloat for use with FoldingSet.
736void APFloat::Profile(FoldingSetNodeID& ID) const {
Dale Johannesen7111b022008-10-09 18:53:47 +0000737 ID.Add(bitcastToAPInt());
Ted Kremenek1f801fa2008-02-11 17:24:50 +0000738}
739
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000740unsigned int
741APFloat::partCount() const
742{
Dale Johannesena72a5a02007-09-20 23:47:58 +0000743 return partCountForBits(semantics->precision + 1);
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000744}
745
746unsigned int
747APFloat::semanticsPrecision(const fltSemantics &semantics)
748{
749 return semantics.precision;
750}
751
752const integerPart *
753APFloat::significandParts() const
754{
755 return const_cast<APFloat *>(this)->significandParts();
756}
757
758integerPart *
759APFloat::significandParts()
760{
Dale Johanneseneaf08942007-08-31 04:03:46 +0000761 assert(category == fcNormal || category == fcNaN);
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000762
Evan Cheng99ebfa52009-10-27 21:35:42 +0000763 if (partCount() > 1)
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000764 return significand.parts;
765 else
766 return &significand.part;
767}
768
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000769void
770APFloat::zeroSignificand()
771{
772 category = fcNormal;
773 APInt::tcSet(significandParts(), 0, partCount());
774}
775
776/* Increment an fcNormal floating point number's significand. */
777void
778APFloat::incrementSignificand()
779{
780 integerPart carry;
781
782 carry = APInt::tcIncrement(significandParts(), partCount());
783
784 /* Our callers should never cause us to overflow. */
785 assert(carry == 0);
786}
787
788/* Add the significand of the RHS. Returns the carry flag. */
789integerPart
790APFloat::addSignificand(const APFloat &rhs)
791{
792 integerPart *parts;
793
794 parts = significandParts();
795
796 assert(semantics == rhs.semantics);
797 assert(exponent == rhs.exponent);
798
799 return APInt::tcAdd(parts, rhs.significandParts(), 0, partCount());
800}
801
802/* Subtract the significand of the RHS with a borrow flag. Returns
803 the borrow flag. */
804integerPart
805APFloat::subtractSignificand(const APFloat &rhs, integerPart borrow)
806{
807 integerPart *parts;
808
809 parts = significandParts();
810
811 assert(semantics == rhs.semantics);
812 assert(exponent == rhs.exponent);
813
814 return APInt::tcSubtract(parts, rhs.significandParts(), borrow,
Neil Booth4f881702007-09-26 21:33:42 +0000815 partCount());
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000816}
817
818/* Multiply the significand of the RHS. If ADDEND is non-NULL, add it
819 on to the full-precision result of the multiplication. Returns the
820 lost fraction. */
821lostFraction
822APFloat::multiplySignificand(const APFloat &rhs, const APFloat *addend)
823{
Neil Booth4f881702007-09-26 21:33:42 +0000824 unsigned int omsb; // One, not zero, based MSB.
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000825 unsigned int partsCount, newPartsCount, precision;
826 integerPart *lhsSignificand;
827 integerPart scratch[4];
828 integerPart *fullSignificand;
829 lostFraction lost_fraction;
Dale Johannesen23a98552008-10-09 23:00:39 +0000830 bool ignored;
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000831
832 assert(semantics == rhs.semantics);
833
834 precision = semantics->precision;
835 newPartsCount = partCountForBits(precision * 2);
836
837 if(newPartsCount > 4)
838 fullSignificand = new integerPart[newPartsCount];
839 else
840 fullSignificand = scratch;
841
842 lhsSignificand = significandParts();
843 partsCount = partCount();
844
845 APInt::tcFullMultiply(fullSignificand, lhsSignificand,
Neil Booth978661d2007-10-06 00:24:48 +0000846 rhs.significandParts(), partsCount, partsCount);
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000847
848 lost_fraction = lfExactlyZero;
849 omsb = APInt::tcMSB(fullSignificand, newPartsCount) + 1;
850 exponent += rhs.exponent;
851
852 if(addend) {
853 Significand savedSignificand = significand;
854 const fltSemantics *savedSemantics = semantics;
855 fltSemantics extendedSemantics;
856 opStatus status;
857 unsigned int extendedPrecision;
858
859 /* Normalize our MSB. */
860 extendedPrecision = precision + precision - 1;
861 if(omsb != extendedPrecision)
862 {
Neil Booth4f881702007-09-26 21:33:42 +0000863 APInt::tcShiftLeft(fullSignificand, newPartsCount,
864 extendedPrecision - omsb);
865 exponent -= extendedPrecision - omsb;
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000866 }
867
868 /* Create new semantics. */
869 extendedSemantics = *semantics;
870 extendedSemantics.precision = extendedPrecision;
871
872 if(newPartsCount == 1)
873 significand.part = fullSignificand[0];
874 else
875 significand.parts = fullSignificand;
876 semantics = &extendedSemantics;
877
878 APFloat extendedAddend(*addend);
Dale Johannesen23a98552008-10-09 23:00:39 +0000879 status = extendedAddend.convert(extendedSemantics, rmTowardZero, &ignored);
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000880 assert(status == opOK);
881 lost_fraction = addOrSubtractSignificand(extendedAddend, false);
882
883 /* Restore our state. */
884 if(newPartsCount == 1)
885 fullSignificand[0] = significand.part;
886 significand = savedSignificand;
887 semantics = savedSemantics;
888
889 omsb = APInt::tcMSB(fullSignificand, newPartsCount) + 1;
890 }
891
892 exponent -= (precision - 1);
893
894 if(omsb > precision) {
895 unsigned int bits, significantParts;
896 lostFraction lf;
897
898 bits = omsb - precision;
899 significantParts = partCountForBits(omsb);
900 lf = shiftRight(fullSignificand, significantParts, bits);
901 lost_fraction = combineLostFractions(lf, lost_fraction);
902 exponent += bits;
903 }
904
905 APInt::tcAssign(lhsSignificand, fullSignificand, partsCount);
906
907 if(newPartsCount > 4)
908 delete [] fullSignificand;
909
910 return lost_fraction;
911}
912
913/* Multiply the significands of LHS and RHS to DST. */
914lostFraction
915APFloat::divideSignificand(const APFloat &rhs)
916{
917 unsigned int bit, i, partsCount;
918 const integerPart *rhsSignificand;
919 integerPart *lhsSignificand, *dividend, *divisor;
920 integerPart scratch[4];
921 lostFraction lost_fraction;
922
923 assert(semantics == rhs.semantics);
924
925 lhsSignificand = significandParts();
926 rhsSignificand = rhs.significandParts();
927 partsCount = partCount();
928
929 if(partsCount > 2)
930 dividend = new integerPart[partsCount * 2];
931 else
932 dividend = scratch;
933
934 divisor = dividend + partsCount;
935
936 /* Copy the dividend and divisor as they will be modified in-place. */
937 for(i = 0; i < partsCount; i++) {
938 dividend[i] = lhsSignificand[i];
939 divisor[i] = rhsSignificand[i];
940 lhsSignificand[i] = 0;
941 }
942
943 exponent -= rhs.exponent;
944
945 unsigned int precision = semantics->precision;
946
947 /* Normalize the divisor. */
948 bit = precision - APInt::tcMSB(divisor, partsCount) - 1;
949 if(bit) {
950 exponent += bit;
951 APInt::tcShiftLeft(divisor, partsCount, bit);
952 }
953
954 /* Normalize the dividend. */
955 bit = precision - APInt::tcMSB(dividend, partsCount) - 1;
956 if(bit) {
957 exponent -= bit;
958 APInt::tcShiftLeft(dividend, partsCount, bit);
959 }
960
Neil Booth96c74712007-10-12 16:02:31 +0000961 /* Ensure the dividend >= divisor initially for the loop below.
962 Incidentally, this means that the division loop below is
963 guaranteed to set the integer bit to one. */
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000964 if(APInt::tcCompare(dividend, divisor, partsCount) < 0) {
965 exponent--;
966 APInt::tcShiftLeft(dividend, partsCount, 1);
967 assert(APInt::tcCompare(dividend, divisor, partsCount) >= 0);
968 }
969
970 /* Long division. */
971 for(bit = precision; bit; bit -= 1) {
972 if(APInt::tcCompare(dividend, divisor, partsCount) >= 0) {
973 APInt::tcSubtract(dividend, divisor, 0, partsCount);
974 APInt::tcSetBit(lhsSignificand, bit - 1);
975 }
976
977 APInt::tcShiftLeft(dividend, partsCount, 1);
978 }
979
980 /* Figure out the lost fraction. */
981 int cmp = APInt::tcCompare(dividend, divisor, partsCount);
982
983 if(cmp > 0)
984 lost_fraction = lfMoreThanHalf;
985 else if(cmp == 0)
986 lost_fraction = lfExactlyHalf;
987 else if(APInt::tcIsZero(dividend, partsCount))
988 lost_fraction = lfExactlyZero;
989 else
990 lost_fraction = lfLessThanHalf;
991
992 if(partsCount > 2)
993 delete [] dividend;
994
995 return lost_fraction;
996}
997
998unsigned int
999APFloat::significandMSB() const
1000{
1001 return APInt::tcMSB(significandParts(), partCount());
1002}
1003
1004unsigned int
1005APFloat::significandLSB() const
1006{
1007 return APInt::tcLSB(significandParts(), partCount());
1008}
1009
1010/* Note that a zero result is NOT normalized to fcZero. */
1011lostFraction
1012APFloat::shiftSignificandRight(unsigned int bits)
1013{
1014 /* Our exponent should not overflow. */
1015 assert((exponent_t) (exponent + bits) >= exponent);
1016
1017 exponent += bits;
1018
1019 return shiftRight(significandParts(), partCount(), bits);
1020}
1021
1022/* Shift the significand left BITS bits, subtract BITS from its exponent. */
1023void
1024APFloat::shiftSignificandLeft(unsigned int bits)
1025{
1026 assert(bits < semantics->precision);
1027
1028 if(bits) {
1029 unsigned int partsCount = partCount();
1030
1031 APInt::tcShiftLeft(significandParts(), partsCount, bits);
1032 exponent -= bits;
1033
1034 assert(!APInt::tcIsZero(significandParts(), partsCount));
1035 }
1036}
1037
1038APFloat::cmpResult
1039APFloat::compareAbsoluteValue(const APFloat &rhs) const
1040{
1041 int compare;
1042
1043 assert(semantics == rhs.semantics);
1044 assert(category == fcNormal);
1045 assert(rhs.category == fcNormal);
1046
1047 compare = exponent - rhs.exponent;
1048
1049 /* If exponents are equal, do an unsigned bignum comparison of the
1050 significands. */
1051 if(compare == 0)
1052 compare = APInt::tcCompare(significandParts(), rhs.significandParts(),
Neil Booth4f881702007-09-26 21:33:42 +00001053 partCount());
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001054
1055 if(compare > 0)
1056 return cmpGreaterThan;
1057 else if(compare < 0)
1058 return cmpLessThan;
1059 else
1060 return cmpEqual;
1061}
1062
1063/* Handle overflow. Sign is preserved. We either become infinity or
1064 the largest finite number. */
1065APFloat::opStatus
1066APFloat::handleOverflow(roundingMode rounding_mode)
1067{
1068 /* Infinity? */
1069 if(rounding_mode == rmNearestTiesToEven
1070 || rounding_mode == rmNearestTiesToAway
1071 || (rounding_mode == rmTowardPositive && !sign)
1072 || (rounding_mode == rmTowardNegative && sign))
1073 {
1074 category = fcInfinity;
1075 return (opStatus) (opOverflow | opInexact);
1076 }
1077
1078 /* Otherwise we become the largest finite number. */
1079 category = fcNormal;
1080 exponent = semantics->maxExponent;
1081 APInt::tcSetLeastSignificantBits(significandParts(), partCount(),
Neil Booth4f881702007-09-26 21:33:42 +00001082 semantics->precision);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001083
1084 return opInexact;
1085}
1086
Neil Boothb7dea4c2007-10-03 15:16:41 +00001087/* Returns TRUE if, when truncating the current number, with BIT the
1088 new LSB, with the given lost fraction and rounding mode, the result
1089 would need to be rounded away from zero (i.e., by increasing the
1090 signficand). This routine must work for fcZero of both signs, and
1091 fcNormal numbers. */
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001092bool
1093APFloat::roundAwayFromZero(roundingMode rounding_mode,
Neil Boothb7dea4c2007-10-03 15:16:41 +00001094 lostFraction lost_fraction,
1095 unsigned int bit) const
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001096{
Dale Johanneseneaf08942007-08-31 04:03:46 +00001097 /* NaNs and infinities should not have lost fractions. */
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001098 assert(category == fcNormal || category == fcZero);
1099
Neil Boothb7dea4c2007-10-03 15:16:41 +00001100 /* Current callers never pass this so we don't handle it. */
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001101 assert(lost_fraction != lfExactlyZero);
1102
Mike Stumpf3dc0c02009-05-13 23:23:20 +00001103 switch (rounding_mode) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001104 default:
Torok Edwinc23197a2009-07-14 16:55:14 +00001105 llvm_unreachable(0);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001106
1107 case rmNearestTiesToAway:
1108 return lost_fraction == lfExactlyHalf || lost_fraction == lfMoreThanHalf;
1109
1110 case rmNearestTiesToEven:
1111 if(lost_fraction == lfMoreThanHalf)
1112 return true;
1113
1114 /* Our zeroes don't have a significand to test. */
1115 if(lost_fraction == lfExactlyHalf && category != fcZero)
Neil Boothb7dea4c2007-10-03 15:16:41 +00001116 return APInt::tcExtractBit(significandParts(), bit);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001117
1118 return false;
1119
1120 case rmTowardZero:
1121 return false;
1122
1123 case rmTowardPositive:
1124 return sign == false;
1125
1126 case rmTowardNegative:
1127 return sign == true;
1128 }
1129}
1130
1131APFloat::opStatus
1132APFloat::normalize(roundingMode rounding_mode,
Neil Booth4f881702007-09-26 21:33:42 +00001133 lostFraction lost_fraction)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001134{
Neil Booth4f881702007-09-26 21:33:42 +00001135 unsigned int omsb; /* One, not zero, based MSB. */
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001136 int exponentChange;
1137
1138 if(category != fcNormal)
1139 return opOK;
1140
1141 /* Before rounding normalize the exponent of fcNormal numbers. */
1142 omsb = significandMSB() + 1;
1143
1144 if(omsb) {
1145 /* OMSB is numbered from 1. We want to place it in the integer
1146 bit numbered PRECISON if possible, with a compensating change in
1147 the exponent. */
1148 exponentChange = omsb - semantics->precision;
1149
1150 /* If the resulting exponent is too high, overflow according to
1151 the rounding mode. */
1152 if(exponent + exponentChange > semantics->maxExponent)
1153 return handleOverflow(rounding_mode);
1154
1155 /* Subnormal numbers have exponent minExponent, and their MSB
1156 is forced based on that. */
1157 if(exponent + exponentChange < semantics->minExponent)
1158 exponentChange = semantics->minExponent - exponent;
1159
1160 /* Shifting left is easy as we don't lose precision. */
1161 if(exponentChange < 0) {
1162 assert(lost_fraction == lfExactlyZero);
1163
1164 shiftSignificandLeft(-exponentChange);
1165
1166 return opOK;
1167 }
1168
1169 if(exponentChange > 0) {
1170 lostFraction lf;
1171
1172 /* Shift right and capture any new lost fraction. */
1173 lf = shiftSignificandRight(exponentChange);
1174
1175 lost_fraction = combineLostFractions(lf, lost_fraction);
1176
1177 /* Keep OMSB up-to-date. */
1178 if(omsb > (unsigned) exponentChange)
Neil Booth96c74712007-10-12 16:02:31 +00001179 omsb -= exponentChange;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001180 else
Neil Booth4f881702007-09-26 21:33:42 +00001181 omsb = 0;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001182 }
1183 }
1184
1185 /* Now round the number according to rounding_mode given the lost
1186 fraction. */
1187
1188 /* As specified in IEEE 754, since we do not trap we do not report
1189 underflow for exact results. */
1190 if(lost_fraction == lfExactlyZero) {
1191 /* Canonicalize zeroes. */
1192 if(omsb == 0)
1193 category = fcZero;
1194
1195 return opOK;
1196 }
1197
1198 /* Increment the significand if we're rounding away from zero. */
Neil Boothb7dea4c2007-10-03 15:16:41 +00001199 if(roundAwayFromZero(rounding_mode, lost_fraction, 0)) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001200 if(omsb == 0)
1201 exponent = semantics->minExponent;
1202
1203 incrementSignificand();
1204 omsb = significandMSB() + 1;
1205
1206 /* Did the significand increment overflow? */
1207 if(omsb == (unsigned) semantics->precision + 1) {
1208 /* Renormalize by incrementing the exponent and shifting our
Neil Booth4f881702007-09-26 21:33:42 +00001209 significand right one. However if we already have the
1210 maximum exponent we overflow to infinity. */
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001211 if(exponent == semantics->maxExponent) {
Neil Booth4f881702007-09-26 21:33:42 +00001212 category = fcInfinity;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001213
Neil Booth4f881702007-09-26 21:33:42 +00001214 return (opStatus) (opOverflow | opInexact);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001215 }
1216
1217 shiftSignificandRight(1);
1218
1219 return opInexact;
1220 }
1221 }
1222
1223 /* The normal case - we were and are not denormal, and any
1224 significand increment above didn't overflow. */
1225 if(omsb == semantics->precision)
1226 return opInexact;
1227
1228 /* We have a non-zero denormal. */
1229 assert(omsb < semantics->precision);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001230
1231 /* Canonicalize zeroes. */
1232 if(omsb == 0)
1233 category = fcZero;
1234
1235 /* The fcZero case is a denormal that underflowed to zero. */
1236 return (opStatus) (opUnderflow | opInexact);
1237}
1238
1239APFloat::opStatus
1240APFloat::addOrSubtractSpecials(const APFloat &rhs, bool subtract)
1241{
Mike Stumpf3dc0c02009-05-13 23:23:20 +00001242 switch (convolve(category, rhs.category)) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001243 default:
Torok Edwinc23197a2009-07-14 16:55:14 +00001244 llvm_unreachable(0);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001245
Dale Johanneseneaf08942007-08-31 04:03:46 +00001246 case convolve(fcNaN, fcZero):
1247 case convolve(fcNaN, fcNormal):
1248 case convolve(fcNaN, fcInfinity):
1249 case convolve(fcNaN, fcNaN):
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001250 case convolve(fcNormal, fcZero):
1251 case convolve(fcInfinity, fcNormal):
1252 case convolve(fcInfinity, fcZero):
1253 return opOK;
1254
Dale Johanneseneaf08942007-08-31 04:03:46 +00001255 case convolve(fcZero, fcNaN):
1256 case convolve(fcNormal, fcNaN):
1257 case convolve(fcInfinity, fcNaN):
1258 category = fcNaN;
1259 copySignificand(rhs);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001260 return opOK;
1261
1262 case convolve(fcNormal, fcInfinity):
1263 case convolve(fcZero, fcInfinity):
1264 category = fcInfinity;
1265 sign = rhs.sign ^ subtract;
1266 return opOK;
1267
1268 case convolve(fcZero, fcNormal):
1269 assign(rhs);
1270 sign = rhs.sign ^ subtract;
1271 return opOK;
1272
1273 case convolve(fcZero, fcZero):
1274 /* Sign depends on rounding mode; handled by caller. */
1275 return opOK;
1276
1277 case convolve(fcInfinity, fcInfinity):
1278 /* Differently signed infinities can only be validly
1279 subtracted. */
Cedric Venetaff9c272009-02-14 16:06:42 +00001280 if(((sign ^ rhs.sign)!=0) != subtract) {
Neil Boothe5e01942007-10-14 10:39:51 +00001281 makeNaN();
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001282 return opInvalidOp;
1283 }
1284
1285 return opOK;
1286
1287 case convolve(fcNormal, fcNormal):
1288 return opDivByZero;
1289 }
1290}
1291
1292/* Add or subtract two normal numbers. */
1293lostFraction
1294APFloat::addOrSubtractSignificand(const APFloat &rhs, bool subtract)
1295{
1296 integerPart carry;
1297 lostFraction lost_fraction;
1298 int bits;
1299
1300 /* Determine if the operation on the absolute values is effectively
1301 an addition or subtraction. */
Hartmut Kaiser8df77a92007-10-25 23:15:31 +00001302 subtract ^= (sign ^ rhs.sign) ? true : false;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001303
1304 /* Are we bigger exponent-wise than the RHS? */
1305 bits = exponent - rhs.exponent;
1306
1307 /* Subtraction is more subtle than one might naively expect. */
1308 if(subtract) {
1309 APFloat temp_rhs(rhs);
1310 bool reverse;
1311
Chris Lattnerada530b2007-08-24 03:02:34 +00001312 if (bits == 0) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001313 reverse = compareAbsoluteValue(temp_rhs) == cmpLessThan;
1314 lost_fraction = lfExactlyZero;
Chris Lattnerada530b2007-08-24 03:02:34 +00001315 } else if (bits > 0) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001316 lost_fraction = temp_rhs.shiftSignificandRight(bits - 1);
1317 shiftSignificandLeft(1);
1318 reverse = false;
Chris Lattnerada530b2007-08-24 03:02:34 +00001319 } else {
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001320 lost_fraction = shiftSignificandRight(-bits - 1);
1321 temp_rhs.shiftSignificandLeft(1);
1322 reverse = true;
1323 }
1324
Chris Lattnerada530b2007-08-24 03:02:34 +00001325 if (reverse) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001326 carry = temp_rhs.subtractSignificand
Neil Booth4f881702007-09-26 21:33:42 +00001327 (*this, lost_fraction != lfExactlyZero);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001328 copySignificand(temp_rhs);
1329 sign = !sign;
1330 } else {
1331 carry = subtractSignificand
Neil Booth4f881702007-09-26 21:33:42 +00001332 (temp_rhs, lost_fraction != lfExactlyZero);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001333 }
1334
1335 /* Invert the lost fraction - it was on the RHS and
1336 subtracted. */
1337 if(lost_fraction == lfLessThanHalf)
1338 lost_fraction = lfMoreThanHalf;
1339 else if(lost_fraction == lfMoreThanHalf)
1340 lost_fraction = lfLessThanHalf;
1341
1342 /* The code above is intended to ensure that no borrow is
1343 necessary. */
1344 assert(!carry);
1345 } else {
1346 if(bits > 0) {
1347 APFloat temp_rhs(rhs);
1348
1349 lost_fraction = temp_rhs.shiftSignificandRight(bits);
1350 carry = addSignificand(temp_rhs);
1351 } else {
1352 lost_fraction = shiftSignificandRight(-bits);
1353 carry = addSignificand(rhs);
1354 }
1355
1356 /* We have a guard bit; generating a carry cannot happen. */
1357 assert(!carry);
1358 }
1359
1360 return lost_fraction;
1361}
1362
1363APFloat::opStatus
1364APFloat::multiplySpecials(const APFloat &rhs)
1365{
Mike Stumpf3dc0c02009-05-13 23:23:20 +00001366 switch (convolve(category, rhs.category)) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001367 default:
Torok Edwinc23197a2009-07-14 16:55:14 +00001368 llvm_unreachable(0);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001369
Dale Johanneseneaf08942007-08-31 04:03:46 +00001370 case convolve(fcNaN, fcZero):
1371 case convolve(fcNaN, fcNormal):
1372 case convolve(fcNaN, fcInfinity):
1373 case convolve(fcNaN, fcNaN):
1374 return opOK;
1375
1376 case convolve(fcZero, fcNaN):
1377 case convolve(fcNormal, fcNaN):
1378 case convolve(fcInfinity, fcNaN):
1379 category = fcNaN;
1380 copySignificand(rhs);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001381 return opOK;
1382
1383 case convolve(fcNormal, fcInfinity):
1384 case convolve(fcInfinity, fcNormal):
1385 case convolve(fcInfinity, fcInfinity):
1386 category = fcInfinity;
1387 return opOK;
1388
1389 case convolve(fcZero, fcNormal):
1390 case convolve(fcNormal, fcZero):
1391 case convolve(fcZero, fcZero):
1392 category = fcZero;
1393 return opOK;
1394
1395 case convolve(fcZero, fcInfinity):
1396 case convolve(fcInfinity, fcZero):
Neil Boothe5e01942007-10-14 10:39:51 +00001397 makeNaN();
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001398 return opInvalidOp;
1399
1400 case convolve(fcNormal, fcNormal):
1401 return opOK;
1402 }
1403}
1404
1405APFloat::opStatus
1406APFloat::divideSpecials(const APFloat &rhs)
1407{
Mike Stumpf3dc0c02009-05-13 23:23:20 +00001408 switch (convolve(category, rhs.category)) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001409 default:
Torok Edwinc23197a2009-07-14 16:55:14 +00001410 llvm_unreachable(0);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001411
Dale Johanneseneaf08942007-08-31 04:03:46 +00001412 case convolve(fcNaN, fcZero):
1413 case convolve(fcNaN, fcNormal):
1414 case convolve(fcNaN, fcInfinity):
1415 case convolve(fcNaN, fcNaN):
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001416 case convolve(fcInfinity, fcZero):
1417 case convolve(fcInfinity, fcNormal):
1418 case convolve(fcZero, fcInfinity):
1419 case convolve(fcZero, fcNormal):
1420 return opOK;
1421
Dale Johanneseneaf08942007-08-31 04:03:46 +00001422 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 category = fcZero;
1431 return opOK;
1432
1433 case convolve(fcNormal, fcZero):
1434 category = fcInfinity;
1435 return opDivByZero;
1436
1437 case convolve(fcInfinity, fcInfinity):
1438 case convolve(fcZero, fcZero):
Neil Boothe5e01942007-10-14 10:39:51 +00001439 makeNaN();
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001440 return opInvalidOp;
1441
1442 case convolve(fcNormal, fcNormal):
1443 return opOK;
1444 }
1445}
1446
Dale Johannesened6af242009-01-21 00:35:19 +00001447APFloat::opStatus
1448APFloat::modSpecials(const APFloat &rhs)
1449{
Mike Stumpf3dc0c02009-05-13 23:23:20 +00001450 switch (convolve(category, rhs.category)) {
Dale Johannesened6af242009-01-21 00:35:19 +00001451 default:
Torok Edwinc23197a2009-07-14 16:55:14 +00001452 llvm_unreachable(0);
Dale Johannesened6af242009-01-21 00:35:19 +00001453
1454 case convolve(fcNaN, fcZero):
1455 case convolve(fcNaN, fcNormal):
1456 case convolve(fcNaN, fcInfinity):
1457 case convolve(fcNaN, fcNaN):
1458 case convolve(fcZero, fcInfinity):
1459 case convolve(fcZero, fcNormal):
1460 case convolve(fcNormal, fcInfinity):
1461 return opOK;
1462
1463 case convolve(fcZero, fcNaN):
1464 case convolve(fcNormal, fcNaN):
1465 case convolve(fcInfinity, fcNaN):
1466 category = fcNaN;
1467 copySignificand(rhs);
1468 return opOK;
1469
1470 case convolve(fcNormal, fcZero):
1471 case convolve(fcInfinity, fcZero):
1472 case convolve(fcInfinity, fcNormal):
1473 case convolve(fcInfinity, fcInfinity):
1474 case convolve(fcZero, fcZero):
1475 makeNaN();
1476 return opInvalidOp;
1477
1478 case convolve(fcNormal, fcNormal):
1479 return opOK;
1480 }
1481}
1482
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001483/* Change sign. */
1484void
1485APFloat::changeSign()
1486{
1487 /* Look mummy, this one's easy. */
1488 sign = !sign;
1489}
1490
Dale Johannesene15c2db2007-08-31 23:35:31 +00001491void
1492APFloat::clearSign()
1493{
1494 /* So is this one. */
1495 sign = 0;
1496}
1497
1498void
1499APFloat::copySign(const APFloat &rhs)
1500{
1501 /* And this one. */
1502 sign = rhs.sign;
1503}
1504
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001505/* Normalized addition or subtraction. */
1506APFloat::opStatus
1507APFloat::addOrSubtract(const APFloat &rhs, roundingMode rounding_mode,
Neil Booth4f881702007-09-26 21:33:42 +00001508 bool subtract)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001509{
1510 opStatus fs;
1511
Neil Boothcaf19d72007-10-14 10:29:28 +00001512 assertArithmeticOK(*semantics);
1513
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001514 fs = addOrSubtractSpecials(rhs, subtract);
1515
1516 /* This return code means it was not a simple case. */
1517 if(fs == opDivByZero) {
1518 lostFraction lost_fraction;
1519
1520 lost_fraction = addOrSubtractSignificand(rhs, subtract);
1521 fs = normalize(rounding_mode, lost_fraction);
1522
1523 /* Can only be zero if we lost no fraction. */
1524 assert(category != fcZero || lost_fraction == lfExactlyZero);
1525 }
1526
1527 /* If two numbers add (exactly) to zero, IEEE 754 decrees it is a
1528 positive zero unless rounding to minus infinity, except that
1529 adding two like-signed zeroes gives that zero. */
1530 if(category == fcZero) {
1531 if(rhs.category != fcZero || (sign == rhs.sign) == subtract)
1532 sign = (rounding_mode == rmTowardNegative);
1533 }
1534
1535 return fs;
1536}
1537
1538/* Normalized addition. */
1539APFloat::opStatus
1540APFloat::add(const APFloat &rhs, roundingMode rounding_mode)
1541{
1542 return addOrSubtract(rhs, rounding_mode, false);
1543}
1544
1545/* Normalized subtraction. */
1546APFloat::opStatus
1547APFloat::subtract(const APFloat &rhs, roundingMode rounding_mode)
1548{
1549 return addOrSubtract(rhs, rounding_mode, true);
1550}
1551
1552/* Normalized multiply. */
1553APFloat::opStatus
1554APFloat::multiply(const APFloat &rhs, roundingMode rounding_mode)
1555{
1556 opStatus fs;
1557
Neil Boothcaf19d72007-10-14 10:29:28 +00001558 assertArithmeticOK(*semantics);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001559 sign ^= rhs.sign;
1560 fs = multiplySpecials(rhs);
1561
1562 if(category == fcNormal) {
1563 lostFraction lost_fraction = multiplySignificand(rhs, 0);
1564 fs = normalize(rounding_mode, lost_fraction);
1565 if(lost_fraction != lfExactlyZero)
1566 fs = (opStatus) (fs | opInexact);
1567 }
1568
1569 return fs;
1570}
1571
1572/* Normalized divide. */
1573APFloat::opStatus
1574APFloat::divide(const APFloat &rhs, roundingMode rounding_mode)
1575{
1576 opStatus fs;
1577
Neil Boothcaf19d72007-10-14 10:29:28 +00001578 assertArithmeticOK(*semantics);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001579 sign ^= rhs.sign;
1580 fs = divideSpecials(rhs);
1581
1582 if(category == fcNormal) {
1583 lostFraction lost_fraction = divideSignificand(rhs);
1584 fs = normalize(rounding_mode, lost_fraction);
1585 if(lost_fraction != lfExactlyZero)
1586 fs = (opStatus) (fs | opInexact);
1587 }
1588
1589 return fs;
1590}
1591
Dale Johannesen24b66a82009-01-20 18:35:05 +00001592/* Normalized remainder. This is not currently correct in all cases. */
1593APFloat::opStatus
1594APFloat::remainder(const APFloat &rhs)
1595{
1596 opStatus fs;
1597 APFloat V = *this;
1598 unsigned int origSign = sign;
1599
1600 assertArithmeticOK(*semantics);
1601 fs = V.divide(rhs, rmNearestTiesToEven);
1602 if (fs == opDivByZero)
1603 return fs;
1604
1605 int parts = partCount();
1606 integerPart *x = new integerPart[parts];
1607 bool ignored;
1608 fs = V.convertToInteger(x, parts * integerPartWidth, true,
1609 rmNearestTiesToEven, &ignored);
1610 if (fs==opInvalidOp)
1611 return fs;
1612
1613 fs = V.convertFromZeroExtendedInteger(x, parts * integerPartWidth, true,
1614 rmNearestTiesToEven);
1615 assert(fs==opOK); // should always work
1616
1617 fs = V.multiply(rhs, rmNearestTiesToEven);
1618 assert(fs==opOK || fs==opInexact); // should not overflow or underflow
1619
1620 fs = subtract(V, rmNearestTiesToEven);
1621 assert(fs==opOK || fs==opInexact); // likewise
1622
1623 if (isZero())
1624 sign = origSign; // IEEE754 requires this
1625 delete[] x;
1626 return fs;
1627}
1628
1629/* Normalized llvm frem (C fmod).
1630 This is not currently correct in all cases. */
Dale Johannesene15c2db2007-08-31 23:35:31 +00001631APFloat::opStatus
1632APFloat::mod(const APFloat &rhs, roundingMode rounding_mode)
1633{
1634 opStatus fs;
Neil Boothcaf19d72007-10-14 10:29:28 +00001635 assertArithmeticOK(*semantics);
Dale Johannesened6af242009-01-21 00:35:19 +00001636 fs = modSpecials(rhs);
Dale Johannesene15c2db2007-08-31 23:35:31 +00001637
Dale Johannesened6af242009-01-21 00:35:19 +00001638 if (category == fcNormal && rhs.category == fcNormal) {
1639 APFloat V = *this;
1640 unsigned int origSign = sign;
Dale Johannesene15c2db2007-08-31 23:35:31 +00001641
Dale Johannesened6af242009-01-21 00:35:19 +00001642 fs = V.divide(rhs, rmNearestTiesToEven);
1643 if (fs == opDivByZero)
1644 return fs;
Dale Johannesen58c2e4c2007-09-05 20:39:49 +00001645
Dale Johannesened6af242009-01-21 00:35:19 +00001646 int parts = partCount();
1647 integerPart *x = new integerPart[parts];
1648 bool ignored;
1649 fs = V.convertToInteger(x, parts * integerPartWidth, true,
1650 rmTowardZero, &ignored);
1651 if (fs==opInvalidOp)
1652 return fs;
Dale Johannesen58c2e4c2007-09-05 20:39:49 +00001653
Dale Johannesened6af242009-01-21 00:35:19 +00001654 fs = V.convertFromZeroExtendedInteger(x, parts * integerPartWidth, true,
1655 rmNearestTiesToEven);
1656 assert(fs==opOK); // should always work
Dale Johannesen58c2e4c2007-09-05 20:39:49 +00001657
Dale Johannesened6af242009-01-21 00:35:19 +00001658 fs = V.multiply(rhs, rounding_mode);
1659 assert(fs==opOK || fs==opInexact); // should not overflow or underflow
1660
1661 fs = subtract(V, rounding_mode);
1662 assert(fs==opOK || fs==opInexact); // likewise
1663
1664 if (isZero())
1665 sign = origSign; // IEEE754 requires this
1666 delete[] x;
1667 }
Dale Johannesene15c2db2007-08-31 23:35:31 +00001668 return fs;
1669}
1670
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001671/* Normalized fused-multiply-add. */
1672APFloat::opStatus
1673APFloat::fusedMultiplyAdd(const APFloat &multiplicand,
Neil Booth4f881702007-09-26 21:33:42 +00001674 const APFloat &addend,
1675 roundingMode rounding_mode)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001676{
1677 opStatus fs;
1678
Neil Boothcaf19d72007-10-14 10:29:28 +00001679 assertArithmeticOK(*semantics);
1680
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001681 /* Post-multiplication sign, before addition. */
1682 sign ^= multiplicand.sign;
1683
1684 /* If and only if all arguments are normal do we need to do an
1685 extended-precision calculation. */
1686 if(category == fcNormal
1687 && multiplicand.category == fcNormal
1688 && addend.category == fcNormal) {
1689 lostFraction lost_fraction;
1690
1691 lost_fraction = multiplySignificand(multiplicand, &addend);
1692 fs = normalize(rounding_mode, lost_fraction);
1693 if(lost_fraction != lfExactlyZero)
1694 fs = (opStatus) (fs | opInexact);
1695
1696 /* If two numbers add (exactly) to zero, IEEE 754 decrees it is a
1697 positive zero unless rounding to minus infinity, except that
1698 adding two like-signed zeroes gives that zero. */
1699 if(category == fcZero && sign != addend.sign)
1700 sign = (rounding_mode == rmTowardNegative);
1701 } else {
1702 fs = multiplySpecials(multiplicand);
1703
1704 /* FS can only be opOK or opInvalidOp. There is no more work
1705 to do in the latter case. The IEEE-754R standard says it is
1706 implementation-defined in this case whether, if ADDEND is a
Dale Johanneseneaf08942007-08-31 04:03:46 +00001707 quiet NaN, we raise invalid op; this implementation does so.
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001708
1709 If we need to do the addition we can do so with normal
1710 precision. */
1711 if(fs == opOK)
1712 fs = addOrSubtract(addend, rounding_mode, false);
1713 }
1714
1715 return fs;
1716}
1717
1718/* Comparison requires normalized numbers. */
1719APFloat::cmpResult
1720APFloat::compare(const APFloat &rhs) const
1721{
1722 cmpResult result;
1723
Neil Boothcaf19d72007-10-14 10:29:28 +00001724 assertArithmeticOK(*semantics);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001725 assert(semantics == rhs.semantics);
1726
Mike Stumpf3dc0c02009-05-13 23:23:20 +00001727 switch (convolve(category, rhs.category)) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001728 default:
Torok Edwinc23197a2009-07-14 16:55:14 +00001729 llvm_unreachable(0);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001730
Dale Johanneseneaf08942007-08-31 04:03:46 +00001731 case convolve(fcNaN, fcZero):
1732 case convolve(fcNaN, fcNormal):
1733 case convolve(fcNaN, fcInfinity):
1734 case convolve(fcNaN, fcNaN):
1735 case convolve(fcZero, fcNaN):
1736 case convolve(fcNormal, fcNaN):
1737 case convolve(fcInfinity, fcNaN):
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001738 return cmpUnordered;
1739
1740 case convolve(fcInfinity, fcNormal):
1741 case convolve(fcInfinity, fcZero):
1742 case convolve(fcNormal, fcZero):
1743 if(sign)
1744 return cmpLessThan;
1745 else
1746 return cmpGreaterThan;
1747
1748 case convolve(fcNormal, fcInfinity):
1749 case convolve(fcZero, fcInfinity):
1750 case convolve(fcZero, fcNormal):
1751 if(rhs.sign)
1752 return cmpGreaterThan;
1753 else
1754 return cmpLessThan;
1755
1756 case convolve(fcInfinity, fcInfinity):
1757 if(sign == rhs.sign)
1758 return cmpEqual;
1759 else if(sign)
1760 return cmpLessThan;
1761 else
1762 return cmpGreaterThan;
1763
1764 case convolve(fcZero, fcZero):
1765 return cmpEqual;
1766
1767 case convolve(fcNormal, fcNormal):
1768 break;
1769 }
1770
1771 /* Two normal numbers. Do they have the same sign? */
1772 if(sign != rhs.sign) {
1773 if(sign)
1774 result = cmpLessThan;
1775 else
1776 result = cmpGreaterThan;
1777 } else {
1778 /* Compare absolute values; invert result if negative. */
1779 result = compareAbsoluteValue(rhs);
1780
1781 if(sign) {
1782 if(result == cmpLessThan)
Neil Booth4f881702007-09-26 21:33:42 +00001783 result = cmpGreaterThan;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001784 else if(result == cmpGreaterThan)
Neil Booth4f881702007-09-26 21:33:42 +00001785 result = cmpLessThan;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001786 }
1787 }
1788
1789 return result;
1790}
1791
Dale Johannesen23a98552008-10-09 23:00:39 +00001792/// APFloat::convert - convert a value of one floating point type to another.
1793/// The return value corresponds to the IEEE754 exceptions. *losesInfo
1794/// records whether the transformation lost information, i.e. whether
1795/// converting the result back to the original type will produce the
1796/// original value (this is almost the same as return value==fsOK, but there
1797/// are edge cases where this is not so).
1798
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001799APFloat::opStatus
1800APFloat::convert(const fltSemantics &toSemantics,
Dale Johannesen23a98552008-10-09 23:00:39 +00001801 roundingMode rounding_mode, bool *losesInfo)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001802{
Neil Boothc8db43d2007-09-22 02:56:19 +00001803 lostFraction lostFraction;
1804 unsigned int newPartCount, oldPartCount;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001805 opStatus fs;
Neil Booth4f881702007-09-26 21:33:42 +00001806
Neil Boothcaf19d72007-10-14 10:29:28 +00001807 assertArithmeticOK(*semantics);
Dale Johannesen79f82f92008-04-20 01:34:03 +00001808 assertArithmeticOK(toSemantics);
Neil Boothc8db43d2007-09-22 02:56:19 +00001809 lostFraction = lfExactlyZero;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001810 newPartCount = partCountForBits(toSemantics.precision + 1);
Neil Boothc8db43d2007-09-22 02:56:19 +00001811 oldPartCount = partCount();
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001812
Neil Boothc8db43d2007-09-22 02:56:19 +00001813 /* Handle storage complications. If our new form is wider,
1814 re-allocate our bit pattern into wider storage. If it is
1815 narrower, we ignore the excess parts, but if narrowing to a
Dale Johannesen902ff942007-09-25 17:25:00 +00001816 single part we need to free the old storage.
1817 Be careful not to reference significandParts for zeroes
1818 and infinities, since it aborts. */
Neil Boothc8db43d2007-09-22 02:56:19 +00001819 if (newPartCount > oldPartCount) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001820 integerPart *newParts;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001821 newParts = new integerPart[newPartCount];
1822 APInt::tcSet(newParts, 0, newPartCount);
Dale Johannesen902ff942007-09-25 17:25:00 +00001823 if (category==fcNormal || category==fcNaN)
1824 APInt::tcAssign(newParts, significandParts(), oldPartCount);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001825 freeSignificand();
1826 significand.parts = newParts;
Neil Boothc8db43d2007-09-22 02:56:19 +00001827 } else if (newPartCount < oldPartCount) {
1828 /* Capture any lost fraction through truncation of parts so we get
1829 correct rounding whilst normalizing. */
Dale Johannesen902ff942007-09-25 17:25:00 +00001830 if (category==fcNormal)
1831 lostFraction = lostFractionThroughTruncation
1832 (significandParts(), oldPartCount, toSemantics.precision);
1833 if (newPartCount == 1) {
1834 integerPart newPart = 0;
Neil Booth4f881702007-09-26 21:33:42 +00001835 if (category==fcNormal || category==fcNaN)
Dale Johannesen902ff942007-09-25 17:25:00 +00001836 newPart = significandParts()[0];
1837 freeSignificand();
1838 significand.part = newPart;
1839 }
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001840 }
1841
1842 if(category == fcNormal) {
1843 /* Re-interpret our bit-pattern. */
1844 exponent += toSemantics.precision - semantics->precision;
1845 semantics = &toSemantics;
Neil Boothc8db43d2007-09-22 02:56:19 +00001846 fs = normalize(rounding_mode, lostFraction);
Dale Johannesen23a98552008-10-09 23:00:39 +00001847 *losesInfo = (fs != opOK);
Dale Johannesen902ff942007-09-25 17:25:00 +00001848 } else if (category == fcNaN) {
1849 int shift = toSemantics.precision - semantics->precision;
Dale Johannesenb63fa052008-01-31 18:34:01 +00001850 // Do this now so significandParts gets the right answer
Dale Johannesen2df5eec2008-10-06 22:59:10 +00001851 const fltSemantics *oldSemantics = semantics;
Dale Johannesenb63fa052008-01-31 18:34:01 +00001852 semantics = &toSemantics;
Dale Johannesen23a98552008-10-09 23:00:39 +00001853 *losesInfo = false;
Dale Johannesen902ff942007-09-25 17:25:00 +00001854 // No normalization here, just truncate
1855 if (shift>0)
1856 APInt::tcShiftLeft(significandParts(), newPartCount, shift);
Dale Johannesen2df5eec2008-10-06 22:59:10 +00001857 else if (shift < 0) {
1858 unsigned ushift = -shift;
Dale Johannesen23a98552008-10-09 23:00:39 +00001859 // Figure out if we are losing information. This happens
Dale Johannesen2df5eec2008-10-06 22:59:10 +00001860 // if are shifting out something other than 0s, or if the x87 long
1861 // double input did not have its integer bit set (pseudo-NaN), or if the
1862 // x87 long double input did not have its QNan bit set (because the x87
1863 // hardware sets this bit when converting a lower-precision NaN to
1864 // x87 long double).
1865 if (APInt::tcLSB(significandParts(), newPartCount) < ushift)
Dale Johannesen23a98552008-10-09 23:00:39 +00001866 *losesInfo = true;
Dale Johannesen2df5eec2008-10-06 22:59:10 +00001867 if (oldSemantics == &APFloat::x87DoubleExtended &&
1868 (!(*significandParts() & 0x8000000000000000ULL) ||
1869 !(*significandParts() & 0x4000000000000000ULL)))
Dale Johannesen23a98552008-10-09 23:00:39 +00001870 *losesInfo = true;
Dale Johannesen2df5eec2008-10-06 22:59:10 +00001871 APInt::tcShiftRight(significandParts(), newPartCount, ushift);
1872 }
Dale Johannesen902ff942007-09-25 17:25:00 +00001873 // gcc forces the Quiet bit on, which means (float)(double)(float_sNan)
1874 // does not give you back the same bits. This is dubious, and we
1875 // don't currently do it. You're really supposed to get
1876 // an invalid operation signal at runtime, but nobody does that.
Dale Johannesen23a98552008-10-09 23:00:39 +00001877 fs = opOK;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001878 } else {
1879 semantics = &toSemantics;
1880 fs = opOK;
Dale Johannesen23a98552008-10-09 23:00:39 +00001881 *losesInfo = false;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001882 }
1883
1884 return fs;
1885}
1886
1887/* Convert a floating point number to an integer according to the
1888 rounding mode. If the rounded integer value is out of range this
Neil Boothee7ae382007-11-01 22:43:37 +00001889 returns an invalid operation exception and the contents of the
1890 destination parts are unspecified. If the rounded value is in
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001891 range but the floating point number is not the exact integer, the C
1892 standard doesn't require an inexact exception to be raised. IEEE
1893 854 does require it so we do that.
1894
1895 Note that for conversions to integer type the C standard requires
1896 round-to-zero to always be used. */
1897APFloat::opStatus
Neil Boothee7ae382007-11-01 22:43:37 +00001898APFloat::convertToSignExtendedInteger(integerPart *parts, unsigned int width,
1899 bool isSigned,
Dale Johannesen23a98552008-10-09 23:00:39 +00001900 roundingMode rounding_mode,
1901 bool *isExact) const
Neil Boothee7ae382007-11-01 22:43:37 +00001902{
1903 lostFraction lost_fraction;
1904 const integerPart *src;
1905 unsigned int dstPartsCount, truncatedBits;
1906
Evan Cheng794a7db2008-11-26 01:11:57 +00001907 assertArithmeticOK(*semantics);
Neil Boothe3d936a2007-11-02 15:10:05 +00001908
Dale Johannesen23a98552008-10-09 23:00:39 +00001909 *isExact = false;
1910
Neil Boothee7ae382007-11-01 22:43:37 +00001911 /* Handle the three special cases first. */
1912 if(category == fcInfinity || category == fcNaN)
1913 return opInvalidOp;
1914
1915 dstPartsCount = partCountForBits(width);
1916
1917 if(category == fcZero) {
1918 APInt::tcSet(parts, 0, dstPartsCount);
Dale Johannesene4a42452008-10-07 00:40:01 +00001919 // Negative zero can't be represented as an int.
Dale Johannesen23a98552008-10-09 23:00:39 +00001920 *isExact = !sign;
1921 return opOK;
Neil Boothee7ae382007-11-01 22:43:37 +00001922 }
1923
1924 src = significandParts();
1925
1926 /* Step 1: place our absolute value, with any fraction truncated, in
1927 the destination. */
1928 if (exponent < 0) {
1929 /* Our absolute value is less than one; truncate everything. */
1930 APInt::tcSet(parts, 0, dstPartsCount);
Dale Johannesen1f54f582009-01-19 21:17:05 +00001931 /* For exponent -1 the integer bit represents .5, look at that.
1932 For smaller exponents leftmost truncated bit is 0. */
1933 truncatedBits = semantics->precision -1U - exponent;
Neil Boothee7ae382007-11-01 22:43:37 +00001934 } else {
1935 /* We want the most significant (exponent + 1) bits; the rest are
1936 truncated. */
1937 unsigned int bits = exponent + 1U;
1938
1939 /* Hopelessly large in magnitude? */
1940 if (bits > width)
1941 return opInvalidOp;
1942
1943 if (bits < semantics->precision) {
1944 /* We truncate (semantics->precision - bits) bits. */
1945 truncatedBits = semantics->precision - bits;
1946 APInt::tcExtract(parts, dstPartsCount, src, bits, truncatedBits);
1947 } else {
1948 /* We want at least as many bits as are available. */
1949 APInt::tcExtract(parts, dstPartsCount, src, semantics->precision, 0);
1950 APInt::tcShiftLeft(parts, dstPartsCount, bits - semantics->precision);
1951 truncatedBits = 0;
1952 }
1953 }
1954
1955 /* Step 2: work out any lost fraction, and increment the absolute
1956 value if we would round away from zero. */
1957 if (truncatedBits) {
1958 lost_fraction = lostFractionThroughTruncation(src, partCount(),
1959 truncatedBits);
1960 if (lost_fraction != lfExactlyZero
1961 && roundAwayFromZero(rounding_mode, lost_fraction, truncatedBits)) {
1962 if (APInt::tcIncrement(parts, dstPartsCount))
1963 return opInvalidOp; /* Overflow. */
1964 }
1965 } else {
1966 lost_fraction = lfExactlyZero;
1967 }
1968
1969 /* Step 3: check if we fit in the destination. */
1970 unsigned int omsb = APInt::tcMSB(parts, dstPartsCount) + 1;
1971
1972 if (sign) {
1973 if (!isSigned) {
1974 /* Negative numbers cannot be represented as unsigned. */
1975 if (omsb != 0)
1976 return opInvalidOp;
1977 } else {
1978 /* It takes omsb bits to represent the unsigned integer value.
1979 We lose a bit for the sign, but care is needed as the
1980 maximally negative integer is a special case. */
1981 if (omsb == width && APInt::tcLSB(parts, dstPartsCount) + 1 != omsb)
1982 return opInvalidOp;
1983
1984 /* This case can happen because of rounding. */
1985 if (omsb > width)
1986 return opInvalidOp;
1987 }
1988
1989 APInt::tcNegate (parts, dstPartsCount);
1990 } else {
1991 if (omsb >= width + !isSigned)
1992 return opInvalidOp;
1993 }
1994
Dale Johannesen23a98552008-10-09 23:00:39 +00001995 if (lost_fraction == lfExactlyZero) {
1996 *isExact = true;
Neil Boothee7ae382007-11-01 22:43:37 +00001997 return opOK;
Dale Johannesen23a98552008-10-09 23:00:39 +00001998 } else
Neil Boothee7ae382007-11-01 22:43:37 +00001999 return opInexact;
2000}
2001
2002/* Same as convertToSignExtendedInteger, except we provide
2003 deterministic values in case of an invalid operation exception,
2004 namely zero for NaNs and the minimal or maximal value respectively
Dale Johannesen23a98552008-10-09 23:00:39 +00002005 for underflow or overflow.
2006 The *isExact output tells whether the result is exact, in the sense
2007 that converting it back to the original floating point type produces
2008 the original value. This is almost equivalent to result==opOK,
2009 except for negative zeroes.
2010*/
Neil Boothee7ae382007-11-01 22:43:37 +00002011APFloat::opStatus
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002012APFloat::convertToInteger(integerPart *parts, unsigned int width,
Neil Booth4f881702007-09-26 21:33:42 +00002013 bool isSigned,
Dale Johannesen23a98552008-10-09 23:00:39 +00002014 roundingMode rounding_mode, bool *isExact) const
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002015{
Neil Boothee7ae382007-11-01 22:43:37 +00002016 opStatus fs;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002017
Dale Johannesen23a98552008-10-09 23:00:39 +00002018 fs = convertToSignExtendedInteger(parts, width, isSigned, rounding_mode,
2019 isExact);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002020
Neil Boothee7ae382007-11-01 22:43:37 +00002021 if (fs == opInvalidOp) {
2022 unsigned int bits, dstPartsCount;
2023
2024 dstPartsCount = partCountForBits(width);
2025
2026 if (category == fcNaN)
2027 bits = 0;
2028 else if (sign)
2029 bits = isSigned;
2030 else
2031 bits = width - isSigned;
2032
2033 APInt::tcSetLeastSignificantBits(parts, dstPartsCount, bits);
2034 if (sign && isSigned)
2035 APInt::tcShiftLeft(parts, dstPartsCount, width - 1);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002036 }
2037
Neil Boothee7ae382007-11-01 22:43:37 +00002038 return fs;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002039}
2040
Neil Booth643ce592007-10-07 12:07:53 +00002041/* Convert an unsigned integer SRC to a floating point number,
2042 rounding according to ROUNDING_MODE. The sign of the floating
2043 point number is not modified. */
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002044APFloat::opStatus
Neil Booth643ce592007-10-07 12:07:53 +00002045APFloat::convertFromUnsignedParts(const integerPart *src,
2046 unsigned int srcCount,
2047 roundingMode rounding_mode)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002048{
Neil Booth5477f852007-10-08 14:39:42 +00002049 unsigned int omsb, precision, dstCount;
Neil Booth643ce592007-10-07 12:07:53 +00002050 integerPart *dst;
Neil Booth5477f852007-10-08 14:39:42 +00002051 lostFraction lost_fraction;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002052
Neil Boothcaf19d72007-10-14 10:29:28 +00002053 assertArithmeticOK(*semantics);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002054 category = fcNormal;
Neil Booth5477f852007-10-08 14:39:42 +00002055 omsb = APInt::tcMSB(src, srcCount) + 1;
Neil Booth643ce592007-10-07 12:07:53 +00002056 dst = significandParts();
2057 dstCount = partCount();
Neil Booth5477f852007-10-08 14:39:42 +00002058 precision = semantics->precision;
Neil Booth643ce592007-10-07 12:07:53 +00002059
Neil Booth5477f852007-10-08 14:39:42 +00002060 /* We want the most significant PRECISON bits of SRC. There may not
2061 be that many; extract what we can. */
2062 if (precision <= omsb) {
2063 exponent = omsb - 1;
Neil Booth643ce592007-10-07 12:07:53 +00002064 lost_fraction = lostFractionThroughTruncation(src, srcCount,
Neil Booth5477f852007-10-08 14:39:42 +00002065 omsb - precision);
2066 APInt::tcExtract(dst, dstCount, src, precision, omsb - precision);
2067 } else {
2068 exponent = precision - 1;
2069 lost_fraction = lfExactlyZero;
2070 APInt::tcExtract(dst, dstCount, src, omsb, 0);
Neil Booth643ce592007-10-07 12:07:53 +00002071 }
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002072
2073 return normalize(rounding_mode, lost_fraction);
2074}
2075
Dan Gohman93c276e2008-02-29 01:26:11 +00002076APFloat::opStatus
2077APFloat::convertFromAPInt(const APInt &Val,
2078 bool isSigned,
2079 roundingMode rounding_mode)
2080{
2081 unsigned int partCount = Val.getNumWords();
2082 APInt api = Val;
2083
2084 sign = false;
2085 if (isSigned && api.isNegative()) {
2086 sign = true;
2087 api = -api;
2088 }
2089
2090 return convertFromUnsignedParts(api.getRawData(), partCount, rounding_mode);
2091}
2092
Neil Boothf16c5952007-10-07 12:15:41 +00002093/* Convert a two's complement integer SRC to a floating point number,
2094 rounding according to ROUNDING_MODE. ISSIGNED is true if the
2095 integer is signed, in which case it must be sign-extended. */
2096APFloat::opStatus
2097APFloat::convertFromSignExtendedInteger(const integerPart *src,
2098 unsigned int srcCount,
2099 bool isSigned,
2100 roundingMode rounding_mode)
2101{
2102 opStatus status;
2103
Neil Boothcaf19d72007-10-14 10:29:28 +00002104 assertArithmeticOK(*semantics);
Neil Boothf16c5952007-10-07 12:15:41 +00002105 if (isSigned
2106 && APInt::tcExtractBit(src, srcCount * integerPartWidth - 1)) {
2107 integerPart *copy;
2108
2109 /* If we're signed and negative negate a copy. */
2110 sign = true;
2111 copy = new integerPart[srcCount];
2112 APInt::tcAssign(copy, src, srcCount);
2113 APInt::tcNegate(copy, srcCount);
2114 status = convertFromUnsignedParts(copy, srcCount, rounding_mode);
2115 delete [] copy;
2116 } else {
2117 sign = false;
2118 status = convertFromUnsignedParts(src, srcCount, rounding_mode);
2119 }
2120
2121 return status;
2122}
2123
Neil Boothccf596a2007-10-07 11:45:55 +00002124/* FIXME: should this just take a const APInt reference? */
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002125APFloat::opStatus
Neil Boothccf596a2007-10-07 11:45:55 +00002126APFloat::convertFromZeroExtendedInteger(const integerPart *parts,
2127 unsigned int width, bool isSigned,
2128 roundingMode rounding_mode)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002129{
Dale Johannesen910993e2007-09-21 22:09:37 +00002130 unsigned int partCount = partCountForBits(width);
Dale Johannesen910993e2007-09-21 22:09:37 +00002131 APInt api = APInt(width, partCount, parts);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002132
2133 sign = false;
Dale Johannesencce23a42007-09-30 18:17:01 +00002134 if(isSigned && APInt::tcExtractBit(parts, width - 1)) {
2135 sign = true;
2136 api = -api;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002137 }
2138
Neil Booth7a7bc0f2007-10-07 12:10:57 +00002139 return convertFromUnsignedParts(api.getRawData(), partCount, rounding_mode);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002140}
2141
2142APFloat::opStatus
Erick Tryzelaara15d8902009-08-16 23:36:19 +00002143APFloat::convertFromHexadecimalString(const StringRef &s,
Neil Booth4f881702007-09-26 21:33:42 +00002144 roundingMode rounding_mode)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002145{
Erick Tryzelaarf8bc8012009-08-18 18:20:37 +00002146 lostFraction lost_fraction = lfExactlyZero;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002147 integerPart *significand;
2148 unsigned int bitPos, partsCount;
Erick Tryzelaara15d8902009-08-16 23:36:19 +00002149 StringRef::iterator dot, firstSignificantDigit;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002150
2151 zeroSignificand();
2152 exponent = 0;
2153 category = fcNormal;
2154
2155 significand = significandParts();
2156 partsCount = partCount();
2157 bitPos = partsCount * integerPartWidth;
2158
Neil Booth33d4c922007-10-07 08:51:21 +00002159 /* Skip leading zeroes and any (hexa)decimal point. */
Erick Tryzelaarc78b33b2009-08-20 23:30:43 +00002160 StringRef::iterator begin = s.begin();
2161 StringRef::iterator end = s.end();
2162 StringRef::iterator p = skipLeadingZeroesAndAnyDot(begin, end, &dot);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002163 firstSignificantDigit = p;
2164
Erick Tryzelaarc78b33b2009-08-20 23:30:43 +00002165 for(; p != end;) {
Dale Johannesen386f3e92008-05-14 22:53:25 +00002166 integerPart hex_value;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002167
2168 if(*p == '.') {
Erick Tryzelaarc78b33b2009-08-20 23:30:43 +00002169 assert(dot == end && "String contains multiple dots");
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002170 dot = p++;
Erick Tryzelaarc78b33b2009-08-20 23:30:43 +00002171 if (p == end) {
2172 break;
2173 }
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002174 }
2175
2176 hex_value = hexDigitValue(*p);
2177 if(hex_value == -1U) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002178 break;
2179 }
2180
2181 p++;
2182
Erick Tryzelaarc78b33b2009-08-20 23:30:43 +00002183 if (p == end) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002184 break;
Erick Tryzelaara15d8902009-08-16 23:36:19 +00002185 } else {
2186 /* Store the number whilst 4-bit nibbles remain. */
2187 if(bitPos) {
2188 bitPos -= 4;
2189 hex_value <<= bitPos % integerPartWidth;
2190 significand[bitPos / integerPartWidth] |= hex_value;
2191 } else {
Erick Tryzelaarc78b33b2009-08-20 23:30:43 +00002192 lost_fraction = trailingHexadecimalFraction(p, end, hex_value);
2193 while(p != end && hexDigitValue(*p) != -1U)
Erick Tryzelaara15d8902009-08-16 23:36:19 +00002194 p++;
2195 break;
2196 }
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002197 }
2198 }
2199
2200 /* Hex floats require an exponent but not a hexadecimal point. */
Erick Tryzelaarc78b33b2009-08-20 23:30:43 +00002201 assert(p != end && "Hex strings require an exponent");
2202 assert((*p == 'p' || *p == 'P') && "Invalid character in significand");
2203 assert(p != begin && "Significand has no digits");
2204 assert((dot == end || p - begin != 1) && "Significand has no digits");
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002205
2206 /* Ignore the exponent if we are zero. */
2207 if(p != firstSignificantDigit) {
2208 int expAdjustment;
2209
2210 /* Implicit hexadecimal point? */
Erick Tryzelaarc78b33b2009-08-20 23:30:43 +00002211 if (dot == end)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002212 dot = p;
2213
2214 /* Calculate the exponent adjustment implicit in the number of
2215 significant digits. */
Evan Cheng48e8c802008-05-02 21:15:08 +00002216 expAdjustment = static_cast<int>(dot - firstSignificantDigit);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002217 if(expAdjustment < 0)
2218 expAdjustment++;
2219 expAdjustment = expAdjustment * 4 - 1;
2220
2221 /* Adjust for writing the significand starting at the most
2222 significant nibble. */
2223 expAdjustment += semantics->precision;
2224 expAdjustment -= partsCount * integerPartWidth;
2225
2226 /* Adjust for the given exponent. */
Erick Tryzelaarc78b33b2009-08-20 23:30:43 +00002227 exponent = totalExponent(p + 1, end, expAdjustment);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002228 }
2229
2230 return normalize(rounding_mode, lost_fraction);
2231}
2232
2233APFloat::opStatus
Neil Booth96c74712007-10-12 16:02:31 +00002234APFloat::roundSignificandWithExponent(const integerPart *decSigParts,
2235 unsigned sigPartCount, int exp,
2236 roundingMode rounding_mode)
2237{
2238 unsigned int parts, pow5PartCount;
Neil Boothcaf19d72007-10-14 10:29:28 +00002239 fltSemantics calcSemantics = { 32767, -32767, 0, true };
Neil Booth96c74712007-10-12 16:02:31 +00002240 integerPart pow5Parts[maxPowerOfFiveParts];
2241 bool isNearest;
2242
2243 isNearest = (rounding_mode == rmNearestTiesToEven
2244 || rounding_mode == rmNearestTiesToAway);
2245
2246 parts = partCountForBits(semantics->precision + 11);
2247
2248 /* Calculate pow(5, abs(exp)). */
2249 pow5PartCount = powerOf5(pow5Parts, exp >= 0 ? exp: -exp);
2250
2251 for (;; parts *= 2) {
2252 opStatus sigStatus, powStatus;
2253 unsigned int excessPrecision, truncatedBits;
2254
2255 calcSemantics.precision = parts * integerPartWidth - 1;
2256 excessPrecision = calcSemantics.precision - semantics->precision;
2257 truncatedBits = excessPrecision;
2258
2259 APFloat decSig(calcSemantics, fcZero, sign);
2260 APFloat pow5(calcSemantics, fcZero, false);
2261
2262 sigStatus = decSig.convertFromUnsignedParts(decSigParts, sigPartCount,
2263 rmNearestTiesToEven);
2264 powStatus = pow5.convertFromUnsignedParts(pow5Parts, pow5PartCount,
2265 rmNearestTiesToEven);
2266 /* Add exp, as 10^n = 5^n * 2^n. */
2267 decSig.exponent += exp;
2268
2269 lostFraction calcLostFraction;
Evan Cheng48e8c802008-05-02 21:15:08 +00002270 integerPart HUerr, HUdistance;
2271 unsigned int powHUerr;
Neil Booth96c74712007-10-12 16:02:31 +00002272
2273 if (exp >= 0) {
2274 /* multiplySignificand leaves the precision-th bit set to 1. */
2275 calcLostFraction = decSig.multiplySignificand(pow5, NULL);
2276 powHUerr = powStatus != opOK;
2277 } else {
2278 calcLostFraction = decSig.divideSignificand(pow5);
2279 /* Denormal numbers have less precision. */
2280 if (decSig.exponent < semantics->minExponent) {
2281 excessPrecision += (semantics->minExponent - decSig.exponent);
2282 truncatedBits = excessPrecision;
2283 if (excessPrecision > calcSemantics.precision)
2284 excessPrecision = calcSemantics.precision;
2285 }
2286 /* Extra half-ulp lost in reciprocal of exponent. */
Evan Cheng48e8c802008-05-02 21:15:08 +00002287 powHUerr = (powStatus == opOK && calcLostFraction == lfExactlyZero) ? 0:2;
Neil Booth96c74712007-10-12 16:02:31 +00002288 }
2289
2290 /* Both multiplySignificand and divideSignificand return the
2291 result with the integer bit set. */
Evan Cheng99ebfa52009-10-27 21:35:42 +00002292 assert(APInt::tcExtractBit
2293 (decSig.significandParts(), calcSemantics.precision - 1) == 1);
Neil Booth96c74712007-10-12 16:02:31 +00002294
2295 HUerr = HUerrBound(calcLostFraction != lfExactlyZero, sigStatus != opOK,
2296 powHUerr);
2297 HUdistance = 2 * ulpsFromBoundary(decSig.significandParts(),
2298 excessPrecision, isNearest);
2299
2300 /* Are we guaranteed to round correctly if we truncate? */
2301 if (HUdistance >= HUerr) {
2302 APInt::tcExtract(significandParts(), partCount(), decSig.significandParts(),
2303 calcSemantics.precision - excessPrecision,
2304 excessPrecision);
2305 /* Take the exponent of decSig. If we tcExtract-ed less bits
2306 above we must adjust our exponent to compensate for the
2307 implicit right shift. */
2308 exponent = (decSig.exponent + semantics->precision
2309 - (calcSemantics.precision - excessPrecision));
2310 calcLostFraction = lostFractionThroughTruncation(decSig.significandParts(),
2311 decSig.partCount(),
2312 truncatedBits);
2313 return normalize(rounding_mode, calcLostFraction);
2314 }
2315 }
2316}
2317
2318APFloat::opStatus
Erick Tryzelaara15d8902009-08-16 23:36:19 +00002319APFloat::convertFromDecimalString(const StringRef &str, roundingMode rounding_mode)
Neil Booth96c74712007-10-12 16:02:31 +00002320{
Neil Booth1870f292007-10-14 10:16:12 +00002321 decimalInfo D;
Neil Booth96c74712007-10-12 16:02:31 +00002322 opStatus fs;
2323
Neil Booth1870f292007-10-14 10:16:12 +00002324 /* Scan the text. */
Erick Tryzelaara15d8902009-08-16 23:36:19 +00002325 StringRef::iterator p = str.begin();
2326 interpretDecimal(p, str.end(), &D);
Neil Booth96c74712007-10-12 16:02:31 +00002327
Neil Booth686700e2007-10-15 15:00:55 +00002328 /* Handle the quick cases. First the case of no significant digits,
2329 i.e. zero, and then exponents that are obviously too large or too
2330 small. Writing L for log 10 / log 2, a number d.ddddd*10^exp
2331 definitely overflows if
2332
2333 (exp - 1) * L >= maxExponent
2334
2335 and definitely underflows to zero where
2336
2337 (exp + 1) * L <= minExponent - precision
2338
2339 With integer arithmetic the tightest bounds for L are
2340
2341 93/28 < L < 196/59 [ numerator <= 256 ]
2342 42039/12655 < L < 28738/8651 [ numerator <= 65536 ]
2343 */
2344
Neil Boothcc233592007-12-05 13:06:04 +00002345 if (decDigitValue(*D.firstSigDigit) >= 10U) {
Neil Booth96c74712007-10-12 16:02:31 +00002346 category = fcZero;
2347 fs = opOK;
Neil Booth686700e2007-10-15 15:00:55 +00002348 } else if ((D.normalizedExponent + 1) * 28738
2349 <= 8651 * (semantics->minExponent - (int) semantics->precision)) {
2350 /* Underflow to zero and round. */
2351 zeroSignificand();
2352 fs = normalize(rounding_mode, lfLessThanHalf);
2353 } else if ((D.normalizedExponent - 1) * 42039
2354 >= 12655 * semantics->maxExponent) {
2355 /* Overflow and round. */
2356 fs = handleOverflow(rounding_mode);
Neil Booth96c74712007-10-12 16:02:31 +00002357 } else {
Neil Booth1870f292007-10-14 10:16:12 +00002358 integerPart *decSignificand;
2359 unsigned int partCount;
Neil Booth96c74712007-10-12 16:02:31 +00002360
Neil Booth1870f292007-10-14 10:16:12 +00002361 /* A tight upper bound on number of bits required to hold an
Neil Booth686700e2007-10-15 15:00:55 +00002362 N-digit decimal integer is N * 196 / 59. Allocate enough space
Neil Booth1870f292007-10-14 10:16:12 +00002363 to hold the full significand, and an extra part required by
2364 tcMultiplyPart. */
Evan Cheng48e8c802008-05-02 21:15:08 +00002365 partCount = static_cast<unsigned int>(D.lastSigDigit - D.firstSigDigit) + 1;
Neil Booth686700e2007-10-15 15:00:55 +00002366 partCount = partCountForBits(1 + 196 * partCount / 59);
Neil Booth1870f292007-10-14 10:16:12 +00002367 decSignificand = new integerPart[partCount + 1];
2368 partCount = 0;
Neil Booth96c74712007-10-12 16:02:31 +00002369
Neil Booth1870f292007-10-14 10:16:12 +00002370 /* Convert to binary efficiently - we do almost all multiplication
2371 in an integerPart. When this would overflow do we do a single
2372 bignum multiplication, and then revert again to multiplication
2373 in an integerPart. */
2374 do {
2375 integerPart decValue, val, multiplier;
2376
2377 val = 0;
2378 multiplier = 1;
2379
2380 do {
Erick Tryzelaara15d8902009-08-16 23:36:19 +00002381 if (*p == '.') {
Neil Booth1870f292007-10-14 10:16:12 +00002382 p++;
Erick Tryzelaara15d8902009-08-16 23:36:19 +00002383 if (p == str.end()) {
2384 break;
2385 }
2386 }
Neil Booth1870f292007-10-14 10:16:12 +00002387 decValue = decDigitValue(*p++);
Erick Tryzelaarc78b33b2009-08-20 23:30:43 +00002388 assert(decValue < 10U && "Invalid character in significand");
Neil Booth1870f292007-10-14 10:16:12 +00002389 multiplier *= 10;
2390 val = val * 10 + decValue;
2391 /* The maximum number that can be multiplied by ten with any
2392 digit added without overflowing an integerPart. */
2393 } while (p <= D.lastSigDigit && multiplier <= (~ (integerPart) 0 - 9) / 10);
2394
2395 /* Multiply out the current part. */
2396 APInt::tcMultiplyPart(decSignificand, decSignificand, multiplier, val,
2397 partCount, partCount + 1, false);
2398
2399 /* If we used another part (likely but not guaranteed), increase
2400 the count. */
2401 if (decSignificand[partCount])
2402 partCount++;
2403 } while (p <= D.lastSigDigit);
Neil Booth96c74712007-10-12 16:02:31 +00002404
Neil Booth43a4b282007-11-01 22:51:07 +00002405 category = fcNormal;
Neil Booth96c74712007-10-12 16:02:31 +00002406 fs = roundSignificandWithExponent(decSignificand, partCount,
Neil Booth1870f292007-10-14 10:16:12 +00002407 D.exponent, rounding_mode);
Neil Booth96c74712007-10-12 16:02:31 +00002408
Neil Booth1870f292007-10-14 10:16:12 +00002409 delete [] decSignificand;
2410 }
Neil Booth96c74712007-10-12 16:02:31 +00002411
2412 return fs;
2413}
2414
2415APFloat::opStatus
Erick Tryzelaara15d8902009-08-16 23:36:19 +00002416APFloat::convertFromString(const StringRef &str, roundingMode rounding_mode)
Neil Booth4f881702007-09-26 21:33:42 +00002417{
Neil Boothcaf19d72007-10-14 10:29:28 +00002418 assertArithmeticOK(*semantics);
Erick Tryzelaara15d8902009-08-16 23:36:19 +00002419 assert(!str.empty() && "Invalid string length");
Neil Boothcaf19d72007-10-14 10:29:28 +00002420
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002421 /* Handle a leading minus sign. */
Erick Tryzelaara15d8902009-08-16 23:36:19 +00002422 StringRef::iterator p = str.begin();
2423 size_t slen = str.size();
Erick Tryzelaarc78b33b2009-08-20 23:30:43 +00002424 sign = *p == '-' ? 1 : 0;
2425 if(*p == '-' || *p == '+') {
Erick Tryzelaara15d8902009-08-16 23:36:19 +00002426 p++;
2427 slen--;
Erick Tryzelaarc78b33b2009-08-20 23:30:43 +00002428 assert(slen && "String has no digits");
Erick Tryzelaara15d8902009-08-16 23:36:19 +00002429 }
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002430
Erick Tryzelaara15d8902009-08-16 23:36:19 +00002431 if(slen >= 2 && p[0] == '0' && (p[1] == 'x' || p[1] == 'X')) {
2432 assert(slen - 2 && "Invalid string");
Erick Tryzelaarc78b33b2009-08-20 23:30:43 +00002433 return convertFromHexadecimalString(StringRef(p + 2, slen - 2),
Erick Tryzelaara15d8902009-08-16 23:36:19 +00002434 rounding_mode);
2435 }
Bill Wendlingb7c0d942008-11-27 08:00:12 +00002436
Erick Tryzelaarc78b33b2009-08-20 23:30:43 +00002437 return convertFromDecimalString(StringRef(p, slen), rounding_mode);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002438}
Dale Johannesen343e7702007-08-24 00:56:33 +00002439
Neil Bootha30b0ee2007-10-03 22:26:02 +00002440/* Write out a hexadecimal representation of the floating point value
2441 to DST, which must be of sufficient size, in the C99 form
2442 [-]0xh.hhhhp[+-]d. Return the number of characters written,
2443 excluding the terminating NUL.
2444
2445 If UPPERCASE, the output is in upper case, otherwise in lower case.
2446
2447 HEXDIGITS digits appear altogether, rounding the value if
2448 necessary. If HEXDIGITS is 0, the minimal precision to display the
2449 number precisely is used instead. If nothing would appear after
2450 the decimal point it is suppressed.
2451
2452 The decimal exponent is always printed and has at least one digit.
2453 Zero values display an exponent of zero. Infinities and NaNs
2454 appear as "infinity" or "nan" respectively.
2455
2456 The above rules are as specified by C99. There is ambiguity about
2457 what the leading hexadecimal digit should be. This implementation
2458 uses whatever is necessary so that the exponent is displayed as
2459 stored. This implies the exponent will fall within the IEEE format
2460 range, and the leading hexadecimal digit will be 0 (for denormals),
2461 1 (normal numbers) or 2 (normal numbers rounded-away-from-zero with
2462 any other digits zero).
2463*/
2464unsigned int
2465APFloat::convertToHexString(char *dst, unsigned int hexDigits,
2466 bool upperCase, roundingMode rounding_mode) const
2467{
2468 char *p;
2469
Neil Boothcaf19d72007-10-14 10:29:28 +00002470 assertArithmeticOK(*semantics);
2471
Neil Bootha30b0ee2007-10-03 22:26:02 +00002472 p = dst;
2473 if (sign)
2474 *dst++ = '-';
2475
2476 switch (category) {
2477 case fcInfinity:
2478 memcpy (dst, upperCase ? infinityU: infinityL, sizeof infinityU - 1);
2479 dst += sizeof infinityL - 1;
2480 break;
2481
2482 case fcNaN:
2483 memcpy (dst, upperCase ? NaNU: NaNL, sizeof NaNU - 1);
2484 dst += sizeof NaNU - 1;
2485 break;
2486
2487 case fcZero:
2488 *dst++ = '0';
2489 *dst++ = upperCase ? 'X': 'x';
2490 *dst++ = '0';
2491 if (hexDigits > 1) {
2492 *dst++ = '.';
2493 memset (dst, '0', hexDigits - 1);
2494 dst += hexDigits - 1;
2495 }
2496 *dst++ = upperCase ? 'P': 'p';
2497 *dst++ = '0';
2498 break;
2499
2500 case fcNormal:
2501 dst = convertNormalToHexString (dst, hexDigits, upperCase, rounding_mode);
2502 break;
2503 }
2504
2505 *dst = 0;
2506
Evan Cheng48e8c802008-05-02 21:15:08 +00002507 return static_cast<unsigned int>(dst - p);
Neil Bootha30b0ee2007-10-03 22:26:02 +00002508}
2509
2510/* Does the hard work of outputting the correctly rounded hexadecimal
2511 form of a normal floating point number with the specified number of
2512 hexadecimal digits. If HEXDIGITS is zero the minimum number of
2513 digits necessary to print the value precisely is output. */
2514char *
2515APFloat::convertNormalToHexString(char *dst, unsigned int hexDigits,
2516 bool upperCase,
2517 roundingMode rounding_mode) const
2518{
2519 unsigned int count, valueBits, shift, partsCount, outputDigits;
2520 const char *hexDigitChars;
2521 const integerPart *significand;
2522 char *p;
2523 bool roundUp;
2524
2525 *dst++ = '0';
2526 *dst++ = upperCase ? 'X': 'x';
2527
2528 roundUp = false;
2529 hexDigitChars = upperCase ? hexDigitsUpper: hexDigitsLower;
2530
2531 significand = significandParts();
2532 partsCount = partCount();
2533
2534 /* +3 because the first digit only uses the single integer bit, so
2535 we have 3 virtual zero most-significant-bits. */
2536 valueBits = semantics->precision + 3;
2537 shift = integerPartWidth - valueBits % integerPartWidth;
2538
2539 /* The natural number of digits required ignoring trailing
2540 insignificant zeroes. */
2541 outputDigits = (valueBits - significandLSB () + 3) / 4;
2542
2543 /* hexDigits of zero means use the required number for the
2544 precision. Otherwise, see if we are truncating. If we are,
Neil Booth978661d2007-10-06 00:24:48 +00002545 find out if we need to round away from zero. */
Neil Bootha30b0ee2007-10-03 22:26:02 +00002546 if (hexDigits) {
2547 if (hexDigits < outputDigits) {
2548 /* We are dropping non-zero bits, so need to check how to round.
2549 "bits" is the number of dropped bits. */
2550 unsigned int bits;
2551 lostFraction fraction;
2552
2553 bits = valueBits - hexDigits * 4;
2554 fraction = lostFractionThroughTruncation (significand, partsCount, bits);
2555 roundUp = roundAwayFromZero(rounding_mode, fraction, bits);
2556 }
2557 outputDigits = hexDigits;
2558 }
2559
2560 /* Write the digits consecutively, and start writing in the location
2561 of the hexadecimal point. We move the most significant digit
2562 left and add the hexadecimal point later. */
2563 p = ++dst;
2564
2565 count = (valueBits + integerPartWidth - 1) / integerPartWidth;
2566
2567 while (outputDigits && count) {
2568 integerPart part;
2569
2570 /* Put the most significant integerPartWidth bits in "part". */
2571 if (--count == partsCount)
2572 part = 0; /* An imaginary higher zero part. */
2573 else
2574 part = significand[count] << shift;
2575
2576 if (count && shift)
2577 part |= significand[count - 1] >> (integerPartWidth - shift);
2578
2579 /* Convert as much of "part" to hexdigits as we can. */
2580 unsigned int curDigits = integerPartWidth / 4;
2581
2582 if (curDigits > outputDigits)
2583 curDigits = outputDigits;
2584 dst += partAsHex (dst, part, curDigits, hexDigitChars);
2585 outputDigits -= curDigits;
2586 }
2587
2588 if (roundUp) {
2589 char *q = dst;
2590
2591 /* Note that hexDigitChars has a trailing '0'. */
2592 do {
2593 q--;
2594 *q = hexDigitChars[hexDigitValue (*q) + 1];
Neil Booth978661d2007-10-06 00:24:48 +00002595 } while (*q == '0');
Evan Cheng99ebfa52009-10-27 21:35:42 +00002596 assert(q >= p);
Neil Bootha30b0ee2007-10-03 22:26:02 +00002597 } else {
2598 /* Add trailing zeroes. */
2599 memset (dst, '0', outputDigits);
2600 dst += outputDigits;
2601 }
2602
2603 /* Move the most significant digit to before the point, and if there
2604 is something after the decimal point add it. This must come
2605 after rounding above. */
2606 p[-1] = p[0];
2607 if (dst -1 == p)
2608 dst--;
2609 else
2610 p[0] = '.';
2611
2612 /* Finally output the exponent. */
2613 *dst++ = upperCase ? 'P': 'p';
2614
Neil Booth92f7e8d2007-10-06 07:29:25 +00002615 return writeSignedDecimal (dst, exponent);
Neil Bootha30b0ee2007-10-03 22:26:02 +00002616}
2617
Dale Johannesen343e7702007-08-24 00:56:33 +00002618// For good performance it is desirable for different APFloats
2619// to produce different integers.
2620uint32_t
Neil Booth4f881702007-09-26 21:33:42 +00002621APFloat::getHashValue() const
2622{
Dale Johannesen343e7702007-08-24 00:56:33 +00002623 if (category==fcZero) return sign<<8 | semantics->precision ;
2624 else if (category==fcInfinity) return sign<<9 | semantics->precision;
Dale Johanneseneaf08942007-08-31 04:03:46 +00002625 else if (category==fcNaN) return 1<<10 | semantics->precision;
Dale Johannesen343e7702007-08-24 00:56:33 +00002626 else {
2627 uint32_t hash = sign<<11 | semantics->precision | exponent<<12;
2628 const integerPart* p = significandParts();
2629 for (int i=partCount(); i>0; i--, p++)
Evan Cheng48e8c802008-05-02 21:15:08 +00002630 hash ^= ((uint32_t)*p) ^ (uint32_t)((*p)>>32);
Dale Johannesen343e7702007-08-24 00:56:33 +00002631 return hash;
2632 }
2633}
2634
2635// Conversion from APFloat to/from host float/double. It may eventually be
2636// possible to eliminate these and have everybody deal with APFloats, but that
2637// will take a while. This approach will not easily extend to long double.
Dale Johannesena72a5a02007-09-20 23:47:58 +00002638// Current implementation requires integerPartWidth==64, which is correct at
2639// the moment but could be made more general.
Dale Johannesen343e7702007-08-24 00:56:33 +00002640
Dale Johannesen58c2e4c2007-09-05 20:39:49 +00002641// Denormals have exponent minExponent in APFloat, but minExponent-1 in
Dale Johannesena72a5a02007-09-20 23:47:58 +00002642// the actual IEEE respresentations. We compensate for that here.
Dale Johannesen58c2e4c2007-09-05 20:39:49 +00002643
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002644APInt
Neil Booth4f881702007-09-26 21:33:42 +00002645APFloat::convertF80LongDoubleAPFloatToAPInt() const
2646{
Dan Gohmanb10abe12008-01-29 12:08:20 +00002647 assert(semantics == (const llvm::fltSemantics*)&x87DoubleExtended);
Evan Cheng99ebfa52009-10-27 21:35:42 +00002648 assert(partCount()==2);
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002649
2650 uint64_t myexponent, mysignificand;
2651
2652 if (category==fcNormal) {
2653 myexponent = exponent+16383; //bias
Dale Johannesena72a5a02007-09-20 23:47:58 +00002654 mysignificand = significandParts()[0];
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002655 if (myexponent==1 && !(mysignificand & 0x8000000000000000ULL))
2656 myexponent = 0; // denormal
2657 } else if (category==fcZero) {
2658 myexponent = 0;
2659 mysignificand = 0;
2660 } else if (category==fcInfinity) {
2661 myexponent = 0x7fff;
2662 mysignificand = 0x8000000000000000ULL;
Chris Lattnera11ef822007-10-06 06:13:42 +00002663 } else {
2664 assert(category == fcNaN && "Unknown category");
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002665 myexponent = 0x7fff;
Dale Johannesena72a5a02007-09-20 23:47:58 +00002666 mysignificand = significandParts()[0];
Chris Lattnera11ef822007-10-06 06:13:42 +00002667 }
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002668
2669 uint64_t words[2];
Dale Johannesen1b25cb22009-03-23 21:16:53 +00002670 words[0] = mysignificand;
2671 words[1] = ((uint64_t)(sign & 1) << 15) |
2672 (myexponent & 0x7fffLL);
Chris Lattnera11ef822007-10-06 06:13:42 +00002673 return APInt(80, 2, words);
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002674}
2675
2676APInt
Dale Johannesena471c2e2007-10-11 18:07:22 +00002677APFloat::convertPPCDoubleDoubleAPFloatToAPInt() const
2678{
Dan Gohmanb10abe12008-01-29 12:08:20 +00002679 assert(semantics == (const llvm::fltSemantics*)&PPCDoubleDouble);
Evan Cheng99ebfa52009-10-27 21:35:42 +00002680 assert(partCount()==2);
Dale Johannesena471c2e2007-10-11 18:07:22 +00002681
2682 uint64_t myexponent, mysignificand, myexponent2, mysignificand2;
2683
2684 if (category==fcNormal) {
2685 myexponent = exponent + 1023; //bias
2686 myexponent2 = exponent2 + 1023;
2687 mysignificand = significandParts()[0];
2688 mysignificand2 = significandParts()[1];
2689 if (myexponent==1 && !(mysignificand & 0x10000000000000LL))
2690 myexponent = 0; // denormal
2691 if (myexponent2==1 && !(mysignificand2 & 0x10000000000000LL))
2692 myexponent2 = 0; // denormal
2693 } else if (category==fcZero) {
2694 myexponent = 0;
2695 mysignificand = 0;
2696 myexponent2 = 0;
2697 mysignificand2 = 0;
2698 } else if (category==fcInfinity) {
2699 myexponent = 0x7ff;
2700 myexponent2 = 0;
2701 mysignificand = 0;
2702 mysignificand2 = 0;
2703 } else {
2704 assert(category == fcNaN && "Unknown category");
2705 myexponent = 0x7ff;
2706 mysignificand = significandParts()[0];
2707 myexponent2 = exponent2;
2708 mysignificand2 = significandParts()[1];
2709 }
2710
2711 uint64_t words[2];
Evan Cheng48e8c802008-05-02 21:15:08 +00002712 words[0] = ((uint64_t)(sign & 1) << 63) |
Dale Johannesena471c2e2007-10-11 18:07:22 +00002713 ((myexponent & 0x7ff) << 52) |
2714 (mysignificand & 0xfffffffffffffLL);
Evan Cheng48e8c802008-05-02 21:15:08 +00002715 words[1] = ((uint64_t)(sign2 & 1) << 63) |
Dale Johannesena471c2e2007-10-11 18:07:22 +00002716 ((myexponent2 & 0x7ff) << 52) |
2717 (mysignificand2 & 0xfffffffffffffLL);
2718 return APInt(128, 2, words);
2719}
2720
2721APInt
Anton Korobeynikov7e844f12009-08-21 22:10:30 +00002722APFloat::convertQuadrupleAPFloatToAPInt() const
2723{
2724 assert(semantics == (const llvm::fltSemantics*)&IEEEquad);
Evan Cheng99ebfa52009-10-27 21:35:42 +00002725 assert(partCount()==2);
Anton Korobeynikov7e844f12009-08-21 22:10:30 +00002726
2727 uint64_t myexponent, mysignificand, mysignificand2;
2728
2729 if (category==fcNormal) {
2730 myexponent = exponent+16383; //bias
2731 mysignificand = significandParts()[0];
2732 mysignificand2 = significandParts()[1];
2733 if (myexponent==1 && !(mysignificand2 & 0x1000000000000LL))
2734 myexponent = 0; // denormal
2735 } else if (category==fcZero) {
2736 myexponent = 0;
2737 mysignificand = mysignificand2 = 0;
2738 } else if (category==fcInfinity) {
2739 myexponent = 0x7fff;
2740 mysignificand = mysignificand2 = 0;
2741 } else {
2742 assert(category == fcNaN && "Unknown category!");
2743 myexponent = 0x7fff;
2744 mysignificand = significandParts()[0];
2745 mysignificand2 = significandParts()[1];
2746 }
2747
2748 uint64_t words[2];
2749 words[0] = mysignificand;
2750 words[1] = ((uint64_t)(sign & 1) << 63) |
2751 ((myexponent & 0x7fff) << 48) |
Anton Korobeynikov4755e992009-08-21 23:09:47 +00002752 (mysignificand2 & 0xffffffffffffLL);
Anton Korobeynikov7e844f12009-08-21 22:10:30 +00002753
2754 return APInt(128, 2, words);
2755}
2756
2757APInt
Neil Booth4f881702007-09-26 21:33:42 +00002758APFloat::convertDoubleAPFloatToAPInt() const
2759{
Dan Gohmancb648f92007-09-14 20:08:19 +00002760 assert(semantics == (const llvm::fltSemantics*)&IEEEdouble);
Evan Cheng99ebfa52009-10-27 21:35:42 +00002761 assert(partCount()==1);
Dale Johannesen343e7702007-08-24 00:56:33 +00002762
Dale Johanneseneaf08942007-08-31 04:03:46 +00002763 uint64_t myexponent, mysignificand;
Dale Johannesen343e7702007-08-24 00:56:33 +00002764
2765 if (category==fcNormal) {
Dale Johannesen343e7702007-08-24 00:56:33 +00002766 myexponent = exponent+1023; //bias
Dale Johannesen58c2e4c2007-09-05 20:39:49 +00002767 mysignificand = *significandParts();
2768 if (myexponent==1 && !(mysignificand & 0x10000000000000LL))
2769 myexponent = 0; // denormal
Dale Johannesen343e7702007-08-24 00:56:33 +00002770 } else if (category==fcZero) {
Dale Johannesen343e7702007-08-24 00:56:33 +00002771 myexponent = 0;
2772 mysignificand = 0;
2773 } else if (category==fcInfinity) {
Dale Johannesen343e7702007-08-24 00:56:33 +00002774 myexponent = 0x7ff;
2775 mysignificand = 0;
Chris Lattnera11ef822007-10-06 06:13:42 +00002776 } else {
2777 assert(category == fcNaN && "Unknown category!");
Dale Johannesen343e7702007-08-24 00:56:33 +00002778 myexponent = 0x7ff;
Dale Johanneseneaf08942007-08-31 04:03:46 +00002779 mysignificand = *significandParts();
Chris Lattnera11ef822007-10-06 06:13:42 +00002780 }
Dale Johannesen343e7702007-08-24 00:56:33 +00002781
Evan Cheng48e8c802008-05-02 21:15:08 +00002782 return APInt(64, ((((uint64_t)(sign & 1) << 63) |
Chris Lattnera11ef822007-10-06 06:13:42 +00002783 ((myexponent & 0x7ff) << 52) |
2784 (mysignificand & 0xfffffffffffffLL))));
Dale Johannesen343e7702007-08-24 00:56:33 +00002785}
2786
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002787APInt
Neil Booth4f881702007-09-26 21:33:42 +00002788APFloat::convertFloatAPFloatToAPInt() const
2789{
Dan Gohmancb648f92007-09-14 20:08:19 +00002790 assert(semantics == (const llvm::fltSemantics*)&IEEEsingle);
Evan Cheng99ebfa52009-10-27 21:35:42 +00002791 assert(partCount()==1);
Neil Booth4f881702007-09-26 21:33:42 +00002792
Dale Johanneseneaf08942007-08-31 04:03:46 +00002793 uint32_t myexponent, mysignificand;
Dale Johannesen343e7702007-08-24 00:56:33 +00002794
2795 if (category==fcNormal) {
Dale Johannesen343e7702007-08-24 00:56:33 +00002796 myexponent = exponent+127; //bias
Evan Cheng48e8c802008-05-02 21:15:08 +00002797 mysignificand = (uint32_t)*significandParts();
Dale Johannesend0763b92007-11-17 01:02:27 +00002798 if (myexponent == 1 && !(mysignificand & 0x800000))
Dale Johannesen58c2e4c2007-09-05 20:39:49 +00002799 myexponent = 0; // denormal
Dale Johannesen343e7702007-08-24 00:56:33 +00002800 } else if (category==fcZero) {
Dale Johannesen343e7702007-08-24 00:56:33 +00002801 myexponent = 0;
2802 mysignificand = 0;
2803 } else if (category==fcInfinity) {
Dale Johannesen343e7702007-08-24 00:56:33 +00002804 myexponent = 0xff;
2805 mysignificand = 0;
Chris Lattnera11ef822007-10-06 06:13:42 +00002806 } else {
2807 assert(category == fcNaN && "Unknown category!");
Dale Johannesen58c2e4c2007-09-05 20:39:49 +00002808 myexponent = 0xff;
Evan Cheng48e8c802008-05-02 21:15:08 +00002809 mysignificand = (uint32_t)*significandParts();
Chris Lattnera11ef822007-10-06 06:13:42 +00002810 }
Dale Johannesen343e7702007-08-24 00:56:33 +00002811
Chris Lattnera11ef822007-10-06 06:13:42 +00002812 return APInt(32, (((sign&1) << 31) | ((myexponent&0xff) << 23) |
2813 (mysignificand & 0x7fffff)));
Dale Johannesen343e7702007-08-24 00:56:33 +00002814}
2815
Chris Lattnercc4287a2009-10-16 02:13:51 +00002816APInt
2817APFloat::convertHalfAPFloatToAPInt() const
2818{
2819 assert(semantics == (const llvm::fltSemantics*)&IEEEhalf);
Evan Cheng99ebfa52009-10-27 21:35:42 +00002820 assert(partCount()==1);
Chris Lattnercc4287a2009-10-16 02:13:51 +00002821
2822 uint32_t myexponent, mysignificand;
2823
2824 if (category==fcNormal) {
2825 myexponent = exponent+15; //bias
2826 mysignificand = (uint32_t)*significandParts();
2827 if (myexponent == 1 && !(mysignificand & 0x400))
2828 myexponent = 0; // denormal
2829 } else if (category==fcZero) {
2830 myexponent = 0;
2831 mysignificand = 0;
2832 } else if (category==fcInfinity) {
Dale Johannesena223aed2009-10-23 04:02:51 +00002833 myexponent = 0x1f;
Chris Lattnercc4287a2009-10-16 02:13:51 +00002834 mysignificand = 0;
2835 } else {
2836 assert(category == fcNaN && "Unknown category!");
Dale Johannesena223aed2009-10-23 04:02:51 +00002837 myexponent = 0x1f;
Chris Lattnercc4287a2009-10-16 02:13:51 +00002838 mysignificand = (uint32_t)*significandParts();
2839 }
2840
2841 return APInt(16, (((sign&1) << 15) | ((myexponent&0x1f) << 10) |
2842 (mysignificand & 0x3ff)));
2843}
2844
Dale Johannesena471c2e2007-10-11 18:07:22 +00002845// This function creates an APInt that is just a bit map of the floating
2846// point constant as it would appear in memory. It is not a conversion,
2847// and treating the result as a normal integer is unlikely to be useful.
2848
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002849APInt
Dale Johannesen7111b022008-10-09 18:53:47 +00002850APFloat::bitcastToAPInt() const
Neil Booth4f881702007-09-26 21:33:42 +00002851{
Chris Lattnercc4287a2009-10-16 02:13:51 +00002852 if (semantics == (const llvm::fltSemantics*)&IEEEhalf)
2853 return convertHalfAPFloatToAPInt();
2854
Dan Gohmanb10abe12008-01-29 12:08:20 +00002855 if (semantics == (const llvm::fltSemantics*)&IEEEsingle)
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002856 return convertFloatAPFloatToAPInt();
Anton Korobeynikov7e844f12009-08-21 22:10:30 +00002857
Dan Gohmanb10abe12008-01-29 12:08:20 +00002858 if (semantics == (const llvm::fltSemantics*)&IEEEdouble)
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002859 return convertDoubleAPFloatToAPInt();
Neil Booth4f881702007-09-26 21:33:42 +00002860
Anton Korobeynikov7e844f12009-08-21 22:10:30 +00002861 if (semantics == (const llvm::fltSemantics*)&IEEEquad)
2862 return convertQuadrupleAPFloatToAPInt();
2863
Dan Gohmanb10abe12008-01-29 12:08:20 +00002864 if (semantics == (const llvm::fltSemantics*)&PPCDoubleDouble)
Dale Johannesena471c2e2007-10-11 18:07:22 +00002865 return convertPPCDoubleDoubleAPFloatToAPInt();
2866
Dan Gohmanb10abe12008-01-29 12:08:20 +00002867 assert(semantics == (const llvm::fltSemantics*)&x87DoubleExtended &&
Chris Lattnera11ef822007-10-06 06:13:42 +00002868 "unknown format!");
2869 return convertF80LongDoubleAPFloatToAPInt();
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002870}
2871
Neil Booth4f881702007-09-26 21:33:42 +00002872float
2873APFloat::convertToFloat() const
2874{
Chris Lattnerad785002009-09-24 21:44:20 +00002875 assert(semantics == (const llvm::fltSemantics*)&IEEEsingle &&
2876 "Float semantics are not IEEEsingle");
Dale Johannesen7111b022008-10-09 18:53:47 +00002877 APInt api = bitcastToAPInt();
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002878 return api.bitsToFloat();
2879}
2880
Neil Booth4f881702007-09-26 21:33:42 +00002881double
2882APFloat::convertToDouble() const
2883{
Chris Lattnerad785002009-09-24 21:44:20 +00002884 assert(semantics == (const llvm::fltSemantics*)&IEEEdouble &&
2885 "Float semantics are not IEEEdouble");
Dale Johannesen7111b022008-10-09 18:53:47 +00002886 APInt api = bitcastToAPInt();
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002887 return api.bitsToDouble();
2888}
2889
Dale Johannesend3d8ce32008-10-06 18:22:29 +00002890/// Integer bit is explicit in this format. Intel hardware (387 and later)
2891/// does not support these bit patterns:
2892/// exponent = all 1's, integer bit 0, significand 0 ("pseudoinfinity")
2893/// exponent = all 1's, integer bit 0, significand nonzero ("pseudoNaN")
2894/// exponent = 0, integer bit 1 ("pseudodenormal")
2895/// exponent!=0 nor all 1's, integer bit 0 ("unnormal")
2896/// At the moment, the first two are treated as NaNs, the second two as Normal.
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002897void
Neil Booth4f881702007-09-26 21:33:42 +00002898APFloat::initFromF80LongDoubleAPInt(const APInt &api)
2899{
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002900 assert(api.getBitWidth()==80);
2901 uint64_t i1 = api.getRawData()[0];
2902 uint64_t i2 = api.getRawData()[1];
Dale Johannesen1b25cb22009-03-23 21:16:53 +00002903 uint64_t myexponent = (i2 & 0x7fff);
2904 uint64_t mysignificand = i1;
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002905
2906 initialize(&APFloat::x87DoubleExtended);
Dale Johannesena72a5a02007-09-20 23:47:58 +00002907 assert(partCount()==2);
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002908
Dale Johannesen1b25cb22009-03-23 21:16:53 +00002909 sign = static_cast<unsigned int>(i2>>15);
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002910 if (myexponent==0 && mysignificand==0) {
2911 // exponent, significand meaningless
2912 category = fcZero;
2913 } else if (myexponent==0x7fff && mysignificand==0x8000000000000000ULL) {
2914 // exponent, significand meaningless
2915 category = fcInfinity;
2916 } else if (myexponent==0x7fff && mysignificand!=0x8000000000000000ULL) {
2917 // exponent meaningless
2918 category = fcNaN;
Dale Johannesena72a5a02007-09-20 23:47:58 +00002919 significandParts()[0] = mysignificand;
2920 significandParts()[1] = 0;
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002921 } else {
2922 category = fcNormal;
2923 exponent = myexponent - 16383;
Dale Johannesena72a5a02007-09-20 23:47:58 +00002924 significandParts()[0] = mysignificand;
2925 significandParts()[1] = 0;
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002926 if (myexponent==0) // denormal
2927 exponent = -16382;
Neil Booth4f881702007-09-26 21:33:42 +00002928 }
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002929}
2930
2931void
Dale Johannesena471c2e2007-10-11 18:07:22 +00002932APFloat::initFromPPCDoubleDoubleAPInt(const APInt &api)
2933{
2934 assert(api.getBitWidth()==128);
2935 uint64_t i1 = api.getRawData()[0];
2936 uint64_t i2 = api.getRawData()[1];
2937 uint64_t myexponent = (i1 >> 52) & 0x7ff;
2938 uint64_t mysignificand = i1 & 0xfffffffffffffLL;
2939 uint64_t myexponent2 = (i2 >> 52) & 0x7ff;
2940 uint64_t mysignificand2 = i2 & 0xfffffffffffffLL;
2941
2942 initialize(&APFloat::PPCDoubleDouble);
2943 assert(partCount()==2);
2944
Evan Cheng48e8c802008-05-02 21:15:08 +00002945 sign = static_cast<unsigned int>(i1>>63);
2946 sign2 = static_cast<unsigned int>(i2>>63);
Dale Johannesena471c2e2007-10-11 18:07:22 +00002947 if (myexponent==0 && mysignificand==0) {
2948 // exponent, significand meaningless
2949 // exponent2 and significand2 are required to be 0; we don't check
2950 category = fcZero;
2951 } else if (myexponent==0x7ff && mysignificand==0) {
2952 // exponent, significand meaningless
2953 // exponent2 and significand2 are required to be 0; we don't check
2954 category = fcInfinity;
2955 } else if (myexponent==0x7ff && mysignificand!=0) {
2956 // exponent meaningless. So is the whole second word, but keep it
2957 // for determinism.
2958 category = fcNaN;
2959 exponent2 = myexponent2;
2960 significandParts()[0] = mysignificand;
2961 significandParts()[1] = mysignificand2;
2962 } else {
2963 category = fcNormal;
2964 // Note there is no category2; the second word is treated as if it is
2965 // fcNormal, although it might be something else considered by itself.
2966 exponent = myexponent - 1023;
2967 exponent2 = myexponent2 - 1023;
2968 significandParts()[0] = mysignificand;
2969 significandParts()[1] = mysignificand2;
2970 if (myexponent==0) // denormal
2971 exponent = -1022;
2972 else
2973 significandParts()[0] |= 0x10000000000000LL; // integer bit
2974 if (myexponent2==0)
2975 exponent2 = -1022;
2976 else
2977 significandParts()[1] |= 0x10000000000000LL; // integer bit
2978 }
2979}
2980
2981void
Anton Korobeynikov7e844f12009-08-21 22:10:30 +00002982APFloat::initFromQuadrupleAPInt(const APInt &api)
2983{
2984 assert(api.getBitWidth()==128);
2985 uint64_t i1 = api.getRawData()[0];
2986 uint64_t i2 = api.getRawData()[1];
2987 uint64_t myexponent = (i2 >> 48) & 0x7fff;
2988 uint64_t mysignificand = i1;
2989 uint64_t mysignificand2 = i2 & 0xffffffffffffLL;
2990
2991 initialize(&APFloat::IEEEquad);
2992 assert(partCount()==2);
2993
2994 sign = static_cast<unsigned int>(i2>>63);
2995 if (myexponent==0 &&
2996 (mysignificand==0 && mysignificand2==0)) {
2997 // exponent, significand meaningless
2998 category = fcZero;
2999 } else if (myexponent==0x7fff &&
3000 (mysignificand==0 && mysignificand2==0)) {
3001 // exponent, significand meaningless
3002 category = fcInfinity;
3003 } else if (myexponent==0x7fff &&
3004 (mysignificand!=0 || mysignificand2 !=0)) {
3005 // exponent meaningless
3006 category = fcNaN;
3007 significandParts()[0] = mysignificand;
3008 significandParts()[1] = mysignificand2;
3009 } else {
3010 category = fcNormal;
3011 exponent = myexponent - 16383;
3012 significandParts()[0] = mysignificand;
3013 significandParts()[1] = mysignificand2;
3014 if (myexponent==0) // denormal
3015 exponent = -16382;
3016 else
3017 significandParts()[1] |= 0x1000000000000LL; // integer bit
3018 }
3019}
3020
3021void
Neil Booth4f881702007-09-26 21:33:42 +00003022APFloat::initFromDoubleAPInt(const APInt &api)
3023{
Dale Johannesen3f6eb742007-09-11 18:32:33 +00003024 assert(api.getBitWidth()==64);
3025 uint64_t i = *api.getRawData();
Dale Johannesend3b51fd2007-08-24 05:08:11 +00003026 uint64_t myexponent = (i >> 52) & 0x7ff;
3027 uint64_t mysignificand = i & 0xfffffffffffffLL;
3028
Dale Johannesen343e7702007-08-24 00:56:33 +00003029 initialize(&APFloat::IEEEdouble);
Dale Johannesen343e7702007-08-24 00:56:33 +00003030 assert(partCount()==1);
3031
Evan Cheng48e8c802008-05-02 21:15:08 +00003032 sign = static_cast<unsigned int>(i>>63);
Dale Johannesen343e7702007-08-24 00:56:33 +00003033 if (myexponent==0 && mysignificand==0) {
3034 // exponent, significand meaningless
3035 category = fcZero;
Dale Johannesen343e7702007-08-24 00:56:33 +00003036 } else if (myexponent==0x7ff && mysignificand==0) {
3037 // exponent, significand meaningless
3038 category = fcInfinity;
Dale Johanneseneaf08942007-08-31 04:03:46 +00003039 } else if (myexponent==0x7ff && mysignificand!=0) {
3040 // exponent meaningless
3041 category = fcNaN;
3042 *significandParts() = mysignificand;
Dale Johannesen343e7702007-08-24 00:56:33 +00003043 } else {
Dale Johannesen343e7702007-08-24 00:56:33 +00003044 category = fcNormal;
3045 exponent = myexponent - 1023;
Dale Johannesen58c2e4c2007-09-05 20:39:49 +00003046 *significandParts() = mysignificand;
3047 if (myexponent==0) // denormal
3048 exponent = -1022;
3049 else
3050 *significandParts() |= 0x10000000000000LL; // integer bit
Neil Booth4f881702007-09-26 21:33:42 +00003051 }
Dale Johannesen343e7702007-08-24 00:56:33 +00003052}
3053
Dale Johannesen3f6eb742007-09-11 18:32:33 +00003054void
Neil Booth4f881702007-09-26 21:33:42 +00003055APFloat::initFromFloatAPInt(const APInt & api)
3056{
Dale Johannesen3f6eb742007-09-11 18:32:33 +00003057 assert(api.getBitWidth()==32);
3058 uint32_t i = (uint32_t)*api.getRawData();
Dale Johannesend3b51fd2007-08-24 05:08:11 +00003059 uint32_t myexponent = (i >> 23) & 0xff;
3060 uint32_t mysignificand = i & 0x7fffff;
3061
Dale Johannesen343e7702007-08-24 00:56:33 +00003062 initialize(&APFloat::IEEEsingle);
Dale Johannesen343e7702007-08-24 00:56:33 +00003063 assert(partCount()==1);
3064
Dale Johanneseneaf08942007-08-31 04:03:46 +00003065 sign = i >> 31;
Dale Johannesen343e7702007-08-24 00:56:33 +00003066 if (myexponent==0 && mysignificand==0) {
3067 // exponent, significand meaningless
3068 category = fcZero;
Dale Johannesen343e7702007-08-24 00:56:33 +00003069 } else if (myexponent==0xff && mysignificand==0) {
3070 // exponent, significand meaningless
3071 category = fcInfinity;
Dale Johannesen902ff942007-09-25 17:25:00 +00003072 } else if (myexponent==0xff && mysignificand!=0) {
Dale Johannesen343e7702007-08-24 00:56:33 +00003073 // sign, exponent, significand meaningless
Dale Johanneseneaf08942007-08-31 04:03:46 +00003074 category = fcNaN;
3075 *significandParts() = mysignificand;
Dale Johannesen343e7702007-08-24 00:56:33 +00003076 } else {
3077 category = fcNormal;
Dale Johannesen343e7702007-08-24 00:56:33 +00003078 exponent = myexponent - 127; //bias
Dale Johannesen58c2e4c2007-09-05 20:39:49 +00003079 *significandParts() = mysignificand;
3080 if (myexponent==0) // denormal
3081 exponent = -126;
3082 else
3083 *significandParts() |= 0x800000; // integer bit
Dale Johannesen343e7702007-08-24 00:56:33 +00003084 }
3085}
Dale Johannesen3f6eb742007-09-11 18:32:33 +00003086
Chris Lattnercc4287a2009-10-16 02:13:51 +00003087void
3088APFloat::initFromHalfAPInt(const APInt & api)
3089{
3090 assert(api.getBitWidth()==16);
3091 uint32_t i = (uint32_t)*api.getRawData();
Dale Johannesena223aed2009-10-23 04:02:51 +00003092 uint32_t myexponent = (i >> 10) & 0x1f;
Chris Lattnercc4287a2009-10-16 02:13:51 +00003093 uint32_t mysignificand = i & 0x3ff;
3094
3095 initialize(&APFloat::IEEEhalf);
3096 assert(partCount()==1);
3097
3098 sign = i >> 15;
3099 if (myexponent==0 && mysignificand==0) {
3100 // exponent, significand meaningless
3101 category = fcZero;
3102 } else if (myexponent==0x1f && mysignificand==0) {
3103 // exponent, significand meaningless
3104 category = fcInfinity;
3105 } else if (myexponent==0x1f && mysignificand!=0) {
3106 // sign, exponent, significand meaningless
3107 category = fcNaN;
3108 *significandParts() = mysignificand;
3109 } else {
3110 category = fcNormal;
3111 exponent = myexponent - 15; //bias
3112 *significandParts() = mysignificand;
3113 if (myexponent==0) // denormal
3114 exponent = -14;
3115 else
3116 *significandParts() |= 0x400; // integer bit
3117 }
3118}
3119
Dale Johannesen3f6eb742007-09-11 18:32:33 +00003120/// Treat api as containing the bits of a floating point number. Currently
Dale Johannesena471c2e2007-10-11 18:07:22 +00003121/// we infer the floating point type from the size of the APInt. The
3122/// isIEEE argument distinguishes between PPC128 and IEEE128 (not meaningful
3123/// when the size is anything else).
Dale Johannesen3f6eb742007-09-11 18:32:33 +00003124void
Dale Johannesena471c2e2007-10-11 18:07:22 +00003125APFloat::initFromAPInt(const APInt& api, bool isIEEE)
Neil Booth4f881702007-09-26 21:33:42 +00003126{
Chris Lattnercc4287a2009-10-16 02:13:51 +00003127 if (api.getBitWidth() == 16)
3128 return initFromHalfAPInt(api);
3129 else if (api.getBitWidth() == 32)
Dale Johannesen3f6eb742007-09-11 18:32:33 +00003130 return initFromFloatAPInt(api);
3131 else if (api.getBitWidth()==64)
3132 return initFromDoubleAPInt(api);
3133 else if (api.getBitWidth()==80)
3134 return initFromF80LongDoubleAPInt(api);
Anton Korobeynikov7e844f12009-08-21 22:10:30 +00003135 else if (api.getBitWidth()==128)
3136 return (isIEEE ?
3137 initFromQuadrupleAPInt(api) : initFromPPCDoubleDoubleAPInt(api));
Dale Johannesen3f6eb742007-09-11 18:32:33 +00003138 else
Torok Edwinc23197a2009-07-14 16:55:14 +00003139 llvm_unreachable(0);
Dale Johannesen3f6eb742007-09-11 18:32:33 +00003140}
3141
Dale Johannesena471c2e2007-10-11 18:07:22 +00003142APFloat::APFloat(const APInt& api, bool isIEEE)
Neil Booth4f881702007-09-26 21:33:42 +00003143{
Dale Johannesena471c2e2007-10-11 18:07:22 +00003144 initFromAPInt(api, isIEEE);
Dale Johannesen3f6eb742007-09-11 18:32:33 +00003145}
3146
Neil Booth4f881702007-09-26 21:33:42 +00003147APFloat::APFloat(float f)
3148{
Dale Johannesen3f6eb742007-09-11 18:32:33 +00003149 APInt api = APInt(32, 0);
3150 initFromAPInt(api.floatToBits(f));
3151}
3152
Neil Booth4f881702007-09-26 21:33:42 +00003153APFloat::APFloat(double d)
3154{
Dale Johannesen3f6eb742007-09-11 18:32:33 +00003155 APInt api = APInt(64, 0);
3156 initFromAPInt(api.doubleToBits(d));
3157}