blob: 4f1b85431ccb768c692d45a2261ccf8ab5adb57b [file] [log] [blame]
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001//===-- APFloat.cpp - Implement APFloat class -----------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattnerb39cdde2007-08-20 22:49:32 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements a class to represent arbitrary precision floating
11// point values and provide a variety of arithmetic operations on them.
12//
13//===----------------------------------------------------------------------===//
14
Chris Lattner36d26c22007-12-08 19:00:03 +000015#include "llvm/ADT/APFloat.h"
Erick Tryzelaara15d8902009-08-16 23:36:19 +000016#include "llvm/ADT/StringRef.h"
Ted Kremenek1f801fa2008-02-11 17:24:50 +000017#include "llvm/ADT/FoldingSet.h"
Torok Edwinc25e7582009-07-11 20:10:48 +000018#include "llvm/Support/ErrorHandling.h"
Dale Johannesend3b51fd2007-08-24 05:08:11 +000019#include "llvm/Support/MathExtras.h"
John McCall8b3f3302010-02-26 22:20:41 +000020#include <limits.h>
Chris Lattnerfad86b02008-08-17 07:19:36 +000021#include <cstring>
Chris Lattnerb39cdde2007-08-20 22:49:32 +000022
23using namespace llvm;
24
25#define convolve(lhs, rhs) ((lhs) * 4 + (rhs))
26
Neil Bootha30b0ee2007-10-03 22:26:02 +000027/* Assumed in hexadecimal significand parsing, and conversion to
28 hexadecimal strings. */
Chris Lattner9f17eb02008-08-17 04:58:58 +000029#define COMPILE_TIME_ASSERT(cond) extern int CTAssert[(cond) ? 1 : -1]
Chris Lattnerb39cdde2007-08-20 22:49:32 +000030COMPILE_TIME_ASSERT(integerPartWidth % 4 == 0);
31
32namespace llvm {
33
34 /* Represents floating point arithmetic semantics. */
35 struct fltSemantics {
36 /* The largest E such that 2^E is representable; this matches the
37 definition of IEEE 754. */
38 exponent_t maxExponent;
39
40 /* The smallest E such that 2^E is a normalized number; this
41 matches the definition of IEEE 754. */
42 exponent_t minExponent;
43
44 /* Number of bits in the significand. This includes the integer
45 bit. */
Neil Booth7a951ca2007-10-12 15:33:27 +000046 unsigned int precision;
Neil Boothcaf19d72007-10-14 10:29:28 +000047
48 /* True if arithmetic is supported. */
49 unsigned int arithmeticOK;
Chris Lattnerb39cdde2007-08-20 22:49:32 +000050 };
51
Chris Lattnercc4287a2009-10-16 02:13:51 +000052 const fltSemantics APFloat::IEEEhalf = { 15, -14, 11, true };
Neil Boothcaf19d72007-10-14 10:29:28 +000053 const fltSemantics APFloat::IEEEsingle = { 127, -126, 24, true };
54 const fltSemantics APFloat::IEEEdouble = { 1023, -1022, 53, true };
55 const fltSemantics APFloat::IEEEquad = { 16383, -16382, 113, true };
56 const fltSemantics APFloat::x87DoubleExtended = { 16383, -16382, 64, true };
57 const fltSemantics APFloat::Bogus = { 0, 0, 0, true };
Dale Johannesena471c2e2007-10-11 18:07:22 +000058
59 // The PowerPC format consists of two doubles. It does not map cleanly
60 // onto the usual format above. For now only storage of constants of
61 // this type is supported, no arithmetic.
Neil Boothcaf19d72007-10-14 10:29:28 +000062 const fltSemantics APFloat::PPCDoubleDouble = { 1023, -1022, 106, false };
Neil Booth96c74712007-10-12 16:02:31 +000063
64 /* A tight upper bound on number of parts required to hold the value
65 pow(5, power) is
66
Neil Booth686700e2007-10-15 15:00:55 +000067 power * 815 / (351 * integerPartWidth) + 1
Neil Booth96c74712007-10-12 16:02:31 +000068
69 However, whilst the result may require only this many parts,
70 because we are multiplying two values to get it, the
71 multiplication may require an extra part with the excess part
72 being zero (consider the trivial case of 1 * 1, tcFullMultiply
73 requires two parts to hold the single-part result). So we add an
74 extra one to guarantee enough space whilst multiplying. */
75 const unsigned int maxExponent = 16383;
76 const unsigned int maxPrecision = 113;
77 const unsigned int maxPowerOfFiveExponent = maxExponent + maxPrecision - 1;
Neil Booth686700e2007-10-15 15:00:55 +000078 const unsigned int maxPowerOfFiveParts = 2 + ((maxPowerOfFiveExponent * 815)
79 / (351 * integerPartWidth));
Chris Lattnerb39cdde2007-08-20 22:49:32 +000080}
81
Chris Lattnere213f3f2009-03-12 23:59:55 +000082/* A bunch of private, handy routines. */
Chris Lattnerb39cdde2007-08-20 22:49:32 +000083
Chris Lattnere213f3f2009-03-12 23:59:55 +000084static inline unsigned int
85partCountForBits(unsigned int bits)
86{
87 return ((bits) + integerPartWidth - 1) / integerPartWidth;
88}
Chris Lattnerb39cdde2007-08-20 22:49:32 +000089
Chris Lattnere213f3f2009-03-12 23:59:55 +000090/* Returns 0U-9U. Return values >= 10U are not digits. */
91static inline unsigned int
92decDigitValue(unsigned int c)
93{
94 return c - '0';
95}
Chris Lattnerb39cdde2007-08-20 22:49:32 +000096
Chris Lattnere213f3f2009-03-12 23:59:55 +000097static unsigned int
98hexDigitValue(unsigned int c)
99{
100 unsigned int r;
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000101
Chris Lattnere213f3f2009-03-12 23:59:55 +0000102 r = c - '0';
103 if(r <= 9)
104 return r;
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000105
Chris Lattnere213f3f2009-03-12 23:59:55 +0000106 r = c - 'A';
107 if(r <= 5)
108 return r + 10;
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000109
Chris Lattnere213f3f2009-03-12 23:59:55 +0000110 r = c - 'a';
111 if(r <= 5)
112 return r + 10;
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000113
Chris Lattnere213f3f2009-03-12 23:59:55 +0000114 return -1U;
115}
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000116
Chris Lattnere213f3f2009-03-12 23:59:55 +0000117static inline void
118assertArithmeticOK(const llvm::fltSemantics &semantics) {
119 assert(semantics.arithmeticOK
120 && "Compile-time arithmetic does not support these semantics");
121}
Neil Boothcaf19d72007-10-14 10:29:28 +0000122
Chris Lattnere213f3f2009-03-12 23:59:55 +0000123/* Return the value of a decimal exponent of the form
124 [+-]ddddddd.
Neil Booth1870f292007-10-14 10:16:12 +0000125
Chris Lattnere213f3f2009-03-12 23:59:55 +0000126 If the exponent overflows, returns a large exponent with the
127 appropriate sign. */
128static int
Erick Tryzelaara15d8902009-08-16 23:36:19 +0000129readExponent(StringRef::iterator begin, StringRef::iterator end)
Chris Lattnere213f3f2009-03-12 23:59:55 +0000130{
131 bool isNegative;
132 unsigned int absExponent;
133 const unsigned int overlargeExponent = 24000; /* FIXME. */
Erick Tryzelaara15d8902009-08-16 23:36:19 +0000134 StringRef::iterator p = begin;
135
136 assert(p != end && "Exponent has no digits");
Neil Booth1870f292007-10-14 10:16:12 +0000137
Chris Lattnere213f3f2009-03-12 23:59:55 +0000138 isNegative = (*p == '-');
Erick Tryzelaara15d8902009-08-16 23:36:19 +0000139 if (*p == '-' || *p == '+') {
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000140 p++;
Erick Tryzelaara15d8902009-08-16 23:36:19 +0000141 assert(p != end && "Exponent has no digits");
142 }
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000143
Chris Lattnere213f3f2009-03-12 23:59:55 +0000144 absExponent = decDigitValue(*p++);
Erick Tryzelaara15d8902009-08-16 23:36:19 +0000145 assert(absExponent < 10U && "Invalid character in exponent");
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000146
Erick Tryzelaara15d8902009-08-16 23:36:19 +0000147 for (; p != end; ++p) {
Chris Lattnere213f3f2009-03-12 23:59:55 +0000148 unsigned int value;
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000149
Chris Lattnere213f3f2009-03-12 23:59:55 +0000150 value = decDigitValue(*p);
Erick Tryzelaara15d8902009-08-16 23:36:19 +0000151 assert(value < 10U && "Invalid character in exponent");
Chris Lattnere213f3f2009-03-12 23:59:55 +0000152
Chris Lattnere213f3f2009-03-12 23:59:55 +0000153 value += absExponent * 10;
154 if (absExponent >= overlargeExponent) {
155 absExponent = overlargeExponent;
156 break;
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000157 }
Chris Lattnere213f3f2009-03-12 23:59:55 +0000158 absExponent = value;
159 }
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000160
Erick Tryzelaara15d8902009-08-16 23:36:19 +0000161 assert(p == end && "Invalid exponent in exponent");
162
Chris Lattnere213f3f2009-03-12 23:59:55 +0000163 if (isNegative)
164 return -(int) absExponent;
165 else
166 return (int) absExponent;
167}
168
169/* This is ugly and needs cleaning up, but I don't immediately see
170 how whilst remaining safe. */
171static int
Erick Tryzelaara15d8902009-08-16 23:36:19 +0000172totalExponent(StringRef::iterator p, StringRef::iterator end,
173 int exponentAdjustment)
Chris Lattnere213f3f2009-03-12 23:59:55 +0000174{
175 int unsignedExponent;
176 bool negative, overflow;
177 int exponent;
178
Erick Tryzelaarc78b33b2009-08-20 23:30:43 +0000179 assert(p != end && "Exponent has no digits");
180
Chris Lattnere213f3f2009-03-12 23:59:55 +0000181 negative = *p == '-';
Erick Tryzelaarc78b33b2009-08-20 23:30:43 +0000182 if(*p == '-' || *p == '+') {
Chris Lattnere213f3f2009-03-12 23:59:55 +0000183 p++;
Erick Tryzelaarc78b33b2009-08-20 23:30:43 +0000184 assert(p != end && "Exponent has no digits");
185 }
Chris Lattnere213f3f2009-03-12 23:59:55 +0000186
187 unsignedExponent = 0;
188 overflow = false;
Erick Tryzelaara15d8902009-08-16 23:36:19 +0000189 for(; p != end; ++p) {
Chris Lattnere213f3f2009-03-12 23:59:55 +0000190 unsigned int value;
191
192 value = decDigitValue(*p);
Erick Tryzelaara15d8902009-08-16 23:36:19 +0000193 assert(value < 10U && "Invalid character in exponent");
Chris Lattnere213f3f2009-03-12 23:59:55 +0000194
Chris Lattnere213f3f2009-03-12 23:59:55 +0000195 unsignedExponent = unsignedExponent * 10 + value;
196 if(unsignedExponent > 65535)
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000197 overflow = true;
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000198 }
199
Chris Lattnere213f3f2009-03-12 23:59:55 +0000200 if(exponentAdjustment > 65535 || exponentAdjustment < -65536)
201 overflow = true;
202
203 if(!overflow) {
204 exponent = unsignedExponent;
205 if(negative)
206 exponent = -exponent;
207 exponent += exponentAdjustment;
208 if(exponent > 65535 || exponent < -65536)
209 overflow = true;
210 }
211
212 if(overflow)
213 exponent = negative ? -65536: 65535;
214
215 return exponent;
216}
217
Erick Tryzelaara15d8902009-08-16 23:36:19 +0000218static StringRef::iterator
219skipLeadingZeroesAndAnyDot(StringRef::iterator begin, StringRef::iterator end,
220 StringRef::iterator *dot)
Chris Lattnere213f3f2009-03-12 23:59:55 +0000221{
Erick Tryzelaara15d8902009-08-16 23:36:19 +0000222 StringRef::iterator p = begin;
223 *dot = end;
224 while(*p == '0' && p != end)
Chris Lattnere213f3f2009-03-12 23:59:55 +0000225 p++;
226
227 if(*p == '.') {
228 *dot = p++;
Erick Tryzelaara15d8902009-08-16 23:36:19 +0000229
Erick Tryzelaarc78b33b2009-08-20 23:30:43 +0000230 assert(end - begin != 1 && "Significand has no digits");
Erick Tryzelaara15d8902009-08-16 23:36:19 +0000231
232 while(*p == '0' && p != end)
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000233 p++;
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000234 }
235
Chris Lattnere213f3f2009-03-12 23:59:55 +0000236 return p;
237}
Neil Booth1870f292007-10-14 10:16:12 +0000238
Chris Lattnere213f3f2009-03-12 23:59:55 +0000239/* Given a normal decimal floating point number of the form
Neil Booth1870f292007-10-14 10:16:12 +0000240
Chris Lattnere213f3f2009-03-12 23:59:55 +0000241 dddd.dddd[eE][+-]ddd
Neil Booth686700e2007-10-15 15:00:55 +0000242
Chris Lattnere213f3f2009-03-12 23:59:55 +0000243 where the decimal point and exponent are optional, fill out the
244 structure D. Exponent is appropriate if the significand is
245 treated as an integer, and normalizedExponent if the significand
246 is taken to have the decimal point after a single leading
247 non-zero digit.
Neil Booth1870f292007-10-14 10:16:12 +0000248
Chris Lattnere213f3f2009-03-12 23:59:55 +0000249 If the value is zero, V->firstSigDigit points to a non-digit, and
250 the return exponent is zero.
251*/
252struct decimalInfo {
253 const char *firstSigDigit;
254 const char *lastSigDigit;
255 int exponent;
256 int normalizedExponent;
257};
Neil Booth1870f292007-10-14 10:16:12 +0000258
Chris Lattnere213f3f2009-03-12 23:59:55 +0000259static void
Erick Tryzelaara15d8902009-08-16 23:36:19 +0000260interpretDecimal(StringRef::iterator begin, StringRef::iterator end,
261 decimalInfo *D)
Chris Lattnere213f3f2009-03-12 23:59:55 +0000262{
Erick Tryzelaara15d8902009-08-16 23:36:19 +0000263 StringRef::iterator dot = end;
264 StringRef::iterator p = skipLeadingZeroesAndAnyDot (begin, end, &dot);
Neil Booth1870f292007-10-14 10:16:12 +0000265
Chris Lattnere213f3f2009-03-12 23:59:55 +0000266 D->firstSigDigit = p;
267 D->exponent = 0;
268 D->normalizedExponent = 0;
269
Erick Tryzelaara15d8902009-08-16 23:36:19 +0000270 for (; p != end; ++p) {
Chris Lattnere213f3f2009-03-12 23:59:55 +0000271 if (*p == '.') {
Erick Tryzelaarc78b33b2009-08-20 23:30:43 +0000272 assert(dot == end && "String contains multiple dots");
Chris Lattnere213f3f2009-03-12 23:59:55 +0000273 dot = p++;
Erick Tryzelaara15d8902009-08-16 23:36:19 +0000274 if (p == end)
275 break;
Neil Booth1870f292007-10-14 10:16:12 +0000276 }
Chris Lattnere213f3f2009-03-12 23:59:55 +0000277 if (decDigitValue(*p) >= 10U)
278 break;
Chris Lattnere213f3f2009-03-12 23:59:55 +0000279 }
Neil Booth1870f292007-10-14 10:16:12 +0000280
Erick Tryzelaara15d8902009-08-16 23:36:19 +0000281 if (p != end) {
Erick Tryzelaarc78b33b2009-08-20 23:30:43 +0000282 assert((*p == 'e' || *p == 'E') && "Invalid character in significand");
283 assert(p != begin && "Significand has no digits");
284 assert((dot == end || p - begin != 1) && "Significand has no digits");
Erick Tryzelaara15d8902009-08-16 23:36:19 +0000285
286 /* p points to the first non-digit in the string */
Erick Tryzelaarc78b33b2009-08-20 23:30:43 +0000287 D->exponent = readExponent(p + 1, end);
Neil Booth1870f292007-10-14 10:16:12 +0000288
Chris Lattnere213f3f2009-03-12 23:59:55 +0000289 /* Implied decimal point? */
Erick Tryzelaara15d8902009-08-16 23:36:19 +0000290 if (dot == end)
Chris Lattnere213f3f2009-03-12 23:59:55 +0000291 dot = p;
Erick Tryzelaara15d8902009-08-16 23:36:19 +0000292 }
Neil Booth1870f292007-10-14 10:16:12 +0000293
Erick Tryzelaara15d8902009-08-16 23:36:19 +0000294 /* If number is all zeroes accept any exponent. */
295 if (p != D->firstSigDigit) {
Chris Lattnere213f3f2009-03-12 23:59:55 +0000296 /* Drop insignificant trailing zeroes. */
Erick Tryzelaara15d8902009-08-16 23:36:19 +0000297 if (p != begin) {
Neil Booth1870f292007-10-14 10:16:12 +0000298 do
Erick Tryzelaara15d8902009-08-16 23:36:19 +0000299 do
300 p--;
301 while (p != begin && *p == '0');
302 while (p != begin && *p == '.');
303 }
Neil Booth1870f292007-10-14 10:16:12 +0000304
Chris Lattnere213f3f2009-03-12 23:59:55 +0000305 /* Adjust the exponents for any decimal point. */
306 D->exponent += static_cast<exponent_t>((dot - p) - (dot > p));
307 D->normalizedExponent = (D->exponent +
308 static_cast<exponent_t>((p - D->firstSigDigit)
309 - (dot > D->firstSigDigit && dot < p)));
Neil Booth1870f292007-10-14 10:16:12 +0000310 }
311
Chris Lattnere213f3f2009-03-12 23:59:55 +0000312 D->lastSigDigit = p;
313}
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000314
Chris Lattnere213f3f2009-03-12 23:59:55 +0000315/* Return the trailing fraction of a hexadecimal number.
316 DIGITVALUE is the first hex digit of the fraction, P points to
317 the next digit. */
318static lostFraction
Erick Tryzelaara15d8902009-08-16 23:36:19 +0000319trailingHexadecimalFraction(StringRef::iterator p, StringRef::iterator end,
320 unsigned int digitValue)
Chris Lattnere213f3f2009-03-12 23:59:55 +0000321{
322 unsigned int hexDigit;
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000323
Chris Lattnere213f3f2009-03-12 23:59:55 +0000324 /* If the first trailing digit isn't 0 or 8 we can work out the
325 fraction immediately. */
326 if(digitValue > 8)
327 return lfMoreThanHalf;
328 else if(digitValue < 8 && digitValue > 0)
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000329 return lfLessThanHalf;
Chris Lattnere213f3f2009-03-12 23:59:55 +0000330
331 /* Otherwise we need to find the first non-zero digit. */
332 while(*p == '0')
333 p++;
334
Erick Tryzelaara15d8902009-08-16 23:36:19 +0000335 assert(p != end && "Invalid trailing hexadecimal fraction!");
336
Chris Lattnere213f3f2009-03-12 23:59:55 +0000337 hexDigit = hexDigitValue(*p);
338
339 /* If we ran off the end it is exactly zero or one-half, otherwise
340 a little more. */
341 if(hexDigit == -1U)
342 return digitValue == 0 ? lfExactlyZero: lfExactlyHalf;
343 else
344 return digitValue == 0 ? lfLessThanHalf: lfMoreThanHalf;
345}
346
347/* Return the fraction lost were a bignum truncated losing the least
348 significant BITS bits. */
349static lostFraction
350lostFractionThroughTruncation(const integerPart *parts,
351 unsigned int partCount,
352 unsigned int bits)
353{
354 unsigned int lsb;
355
356 lsb = APInt::tcLSB(parts, partCount);
357
358 /* Note this is guaranteed true if bits == 0, or LSB == -1U. */
359 if(bits <= lsb)
360 return lfExactlyZero;
361 if(bits == lsb + 1)
362 return lfExactlyHalf;
363 if(bits <= partCount * integerPartWidth
364 && APInt::tcExtractBit(parts, bits - 1))
365 return lfMoreThanHalf;
366
367 return lfLessThanHalf;
368}
369
370/* Shift DST right BITS bits noting lost fraction. */
371static lostFraction
372shiftRight(integerPart *dst, unsigned int parts, unsigned int bits)
373{
374 lostFraction lost_fraction;
375
376 lost_fraction = lostFractionThroughTruncation(dst, parts, bits);
377
378 APInt::tcShiftRight(dst, parts, bits);
379
380 return lost_fraction;
381}
382
383/* Combine the effect of two lost fractions. */
384static lostFraction
385combineLostFractions(lostFraction moreSignificant,
386 lostFraction lessSignificant)
387{
388 if(lessSignificant != lfExactlyZero) {
389 if(moreSignificant == lfExactlyZero)
390 moreSignificant = lfLessThanHalf;
391 else if(moreSignificant == lfExactlyHalf)
392 moreSignificant = lfMoreThanHalf;
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000393 }
394
Chris Lattnere213f3f2009-03-12 23:59:55 +0000395 return moreSignificant;
396}
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000397
Chris Lattnere213f3f2009-03-12 23:59:55 +0000398/* The error from the true value, in half-ulps, on multiplying two
399 floating point numbers, which differ from the value they
400 approximate by at most HUE1 and HUE2 half-ulps, is strictly less
401 than the returned value.
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000402
Chris Lattnere213f3f2009-03-12 23:59:55 +0000403 See "How to Read Floating Point Numbers Accurately" by William D
404 Clinger. */
405static unsigned int
406HUerrBound(bool inexactMultiply, unsigned int HUerr1, unsigned int HUerr2)
407{
408 assert(HUerr1 < 2 || HUerr2 < 2 || (HUerr1 + HUerr2 < 8));
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000409
Chris Lattnere213f3f2009-03-12 23:59:55 +0000410 if (HUerr1 + HUerr2 == 0)
411 return inexactMultiply * 2; /* <= inexactMultiply half-ulps. */
412 else
413 return inexactMultiply + 2 * (HUerr1 + HUerr2);
414}
Neil Bootha30b0ee2007-10-03 22:26:02 +0000415
Chris Lattnere213f3f2009-03-12 23:59:55 +0000416/* The number of ulps from the boundary (zero, or half if ISNEAREST)
417 when the least significant BITS are truncated. BITS cannot be
418 zero. */
419static integerPart
420ulpsFromBoundary(const integerPart *parts, unsigned int bits, bool isNearest)
421{
422 unsigned int count, partBits;
423 integerPart part, boundary;
Neil Booth33d4c922007-10-07 08:51:21 +0000424
Evan Cheng99ebfa52009-10-27 21:35:42 +0000425 assert(bits != 0);
Neil Bootha30b0ee2007-10-03 22:26:02 +0000426
Chris Lattnere213f3f2009-03-12 23:59:55 +0000427 bits--;
428 count = bits / integerPartWidth;
429 partBits = bits % integerPartWidth + 1;
Neil Booth96c74712007-10-12 16:02:31 +0000430
Chris Lattnere213f3f2009-03-12 23:59:55 +0000431 part = parts[count] & (~(integerPart) 0 >> (integerPartWidth - partBits));
Neil Booth96c74712007-10-12 16:02:31 +0000432
Chris Lattnere213f3f2009-03-12 23:59:55 +0000433 if (isNearest)
434 boundary = (integerPart) 1 << (partBits - 1);
435 else
436 boundary = 0;
437
438 if (count == 0) {
439 if (part - boundary <= boundary - part)
440 return part - boundary;
Neil Booth96c74712007-10-12 16:02:31 +0000441 else
Chris Lattnere213f3f2009-03-12 23:59:55 +0000442 return boundary - part;
Neil Booth96c74712007-10-12 16:02:31 +0000443 }
444
Chris Lattnere213f3f2009-03-12 23:59:55 +0000445 if (part == boundary) {
446 while (--count)
447 if (parts[count])
448 return ~(integerPart) 0; /* A lot. */
Neil Booth96c74712007-10-12 16:02:31 +0000449
Chris Lattnere213f3f2009-03-12 23:59:55 +0000450 return parts[0];
451 } else if (part == boundary - 1) {
452 while (--count)
453 if (~parts[count])
454 return ~(integerPart) 0; /* A lot. */
Neil Booth96c74712007-10-12 16:02:31 +0000455
Chris Lattnere213f3f2009-03-12 23:59:55 +0000456 return -parts[0];
457 }
Neil Booth96c74712007-10-12 16:02:31 +0000458
Chris Lattnere213f3f2009-03-12 23:59:55 +0000459 return ~(integerPart) 0; /* A lot. */
460}
Neil Booth96c74712007-10-12 16:02:31 +0000461
Chris Lattnere213f3f2009-03-12 23:59:55 +0000462/* Place pow(5, power) in DST, and return the number of parts used.
463 DST must be at least one part larger than size of the answer. */
464static unsigned int
465powerOf5(integerPart *dst, unsigned int power)
466{
467 static const integerPart firstEightPowers[] = { 1, 5, 25, 125, 625, 3125,
468 15625, 78125 };
Chris Lattneree167a72009-03-13 00:24:01 +0000469 integerPart pow5s[maxPowerOfFiveParts * 2 + 5];
470 pow5s[0] = 78125 * 5;
471
Chris Lattner807926a2009-03-13 00:03:51 +0000472 unsigned int partsCount[16] = { 1 };
Chris Lattnere213f3f2009-03-12 23:59:55 +0000473 integerPart scratch[maxPowerOfFiveParts], *p1, *p2, *pow5;
474 unsigned int result;
Chris Lattnere213f3f2009-03-12 23:59:55 +0000475 assert(power <= maxExponent);
476
477 p1 = dst;
478 p2 = scratch;
479
480 *p1 = firstEightPowers[power & 7];
481 power >>= 3;
482
483 result = 1;
484 pow5 = pow5s;
485
486 for (unsigned int n = 0; power; power >>= 1, n++) {
487 unsigned int pc;
488
489 pc = partsCount[n];
490
491 /* Calculate pow(5,pow(2,n+3)) if we haven't yet. */
492 if (pc == 0) {
493 pc = partsCount[n - 1];
494 APInt::tcFullMultiply(pow5, pow5 - pc, pow5 - pc, pc, pc);
495 pc *= 2;
496 if (pow5[pc - 1] == 0)
497 pc--;
498 partsCount[n] = pc;
Neil Booth96c74712007-10-12 16:02:31 +0000499 }
500
Chris Lattnere213f3f2009-03-12 23:59:55 +0000501 if (power & 1) {
502 integerPart *tmp;
Neil Booth96c74712007-10-12 16:02:31 +0000503
Chris Lattnere213f3f2009-03-12 23:59:55 +0000504 APInt::tcFullMultiply(p2, p1, pow5, result, pc);
505 result += pc;
506 if (p2[result - 1] == 0)
507 result--;
Neil Booth96c74712007-10-12 16:02:31 +0000508
Chris Lattnere213f3f2009-03-12 23:59:55 +0000509 /* Now result is in p1 with partsCount parts and p2 is scratch
510 space. */
511 tmp = p1, p1 = p2, p2 = tmp;
Neil Booth96c74712007-10-12 16:02:31 +0000512 }
513
Chris Lattnere213f3f2009-03-12 23:59:55 +0000514 pow5 += pc;
Neil Booth96c74712007-10-12 16:02:31 +0000515 }
516
Chris Lattnere213f3f2009-03-12 23:59:55 +0000517 if (p1 != dst)
518 APInt::tcAssign(dst, p1, result);
Neil Booth96c74712007-10-12 16:02:31 +0000519
Chris Lattnere213f3f2009-03-12 23:59:55 +0000520 return result;
521}
Neil Booth96c74712007-10-12 16:02:31 +0000522
Chris Lattnere213f3f2009-03-12 23:59:55 +0000523/* Zero at the end to avoid modular arithmetic when adding one; used
524 when rounding up during hexadecimal output. */
525static const char hexDigitsLower[] = "0123456789abcdef0";
526static const char hexDigitsUpper[] = "0123456789ABCDEF0";
527static const char infinityL[] = "infinity";
528static const char infinityU[] = "INFINITY";
529static const char NaNL[] = "nan";
530static const char NaNU[] = "NAN";
Neil Booth96c74712007-10-12 16:02:31 +0000531
Chris Lattnere213f3f2009-03-12 23:59:55 +0000532/* Write out an integerPart in hexadecimal, starting with the most
533 significant nibble. Write out exactly COUNT hexdigits, return
534 COUNT. */
535static unsigned int
536partAsHex (char *dst, integerPart part, unsigned int count,
537 const char *hexDigitChars)
538{
539 unsigned int result = count;
Neil Booth96c74712007-10-12 16:02:31 +0000540
Evan Cheng99ebfa52009-10-27 21:35:42 +0000541 assert(count != 0 && count <= integerPartWidth / 4);
Neil Booth96c74712007-10-12 16:02:31 +0000542
Chris Lattnere213f3f2009-03-12 23:59:55 +0000543 part >>= (integerPartWidth - 4 * count);
544 while (count--) {
545 dst[count] = hexDigitChars[part & 0xf];
546 part >>= 4;
Neil Booth96c74712007-10-12 16:02:31 +0000547 }
548
Chris Lattnere213f3f2009-03-12 23:59:55 +0000549 return result;
550}
Neil Bootha30b0ee2007-10-03 22:26:02 +0000551
Chris Lattnere213f3f2009-03-12 23:59:55 +0000552/* Write out an unsigned decimal integer. */
553static char *
554writeUnsignedDecimal (char *dst, unsigned int n)
555{
556 char buff[40], *p;
Neil Bootha30b0ee2007-10-03 22:26:02 +0000557
Chris Lattnere213f3f2009-03-12 23:59:55 +0000558 p = buff;
559 do
560 *p++ = '0' + n % 10;
561 while (n /= 10);
Neil Bootha30b0ee2007-10-03 22:26:02 +0000562
Chris Lattnere213f3f2009-03-12 23:59:55 +0000563 do
564 *dst++ = *--p;
565 while (p != buff);
Neil Bootha30b0ee2007-10-03 22:26:02 +0000566
Chris Lattnere213f3f2009-03-12 23:59:55 +0000567 return dst;
568}
Neil Bootha30b0ee2007-10-03 22:26:02 +0000569
Chris Lattnere213f3f2009-03-12 23:59:55 +0000570/* Write out a signed decimal integer. */
571static char *
572writeSignedDecimal (char *dst, int value)
573{
574 if (value < 0) {
575 *dst++ = '-';
576 dst = writeUnsignedDecimal(dst, -(unsigned) value);
577 } else
578 dst = writeUnsignedDecimal(dst, value);
Neil Bootha30b0ee2007-10-03 22:26:02 +0000579
Chris Lattnere213f3f2009-03-12 23:59:55 +0000580 return dst;
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000581}
582
583/* Constructors. */
584void
585APFloat::initialize(const fltSemantics *ourSemantics)
586{
587 unsigned int count;
588
589 semantics = ourSemantics;
590 count = partCount();
591 if(count > 1)
592 significand.parts = new integerPart[count];
593}
594
595void
596APFloat::freeSignificand()
597{
598 if(partCount() > 1)
599 delete [] significand.parts;
600}
601
602void
603APFloat::assign(const APFloat &rhs)
604{
605 assert(semantics == rhs.semantics);
606
607 sign = rhs.sign;
608 category = rhs.category;
609 exponent = rhs.exponent;
Dale Johannesena471c2e2007-10-11 18:07:22 +0000610 sign2 = rhs.sign2;
611 exponent2 = rhs.exponent2;
Dale Johanneseneaf08942007-08-31 04:03:46 +0000612 if(category == fcNormal || category == fcNaN)
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000613 copySignificand(rhs);
614}
615
616void
617APFloat::copySignificand(const APFloat &rhs)
618{
Dale Johanneseneaf08942007-08-31 04:03:46 +0000619 assert(category == fcNormal || category == fcNaN);
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000620 assert(rhs.partCount() >= partCount());
621
622 APInt::tcAssign(significandParts(), rhs.significandParts(),
Neil Booth4f881702007-09-26 21:33:42 +0000623 partCount());
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000624}
625
Neil Boothe5e01942007-10-14 10:39:51 +0000626/* Make this number a NaN, with an arbitrary but deterministic value
Dale Johannesen541ed9f2009-01-21 20:32:55 +0000627 for the significand. If double or longer, this is a signalling NaN,
Mike Stumpc5ca7132009-05-30 03:49:43 +0000628 which may not be ideal. If float, this is QNaN(0). */
John McCalle12b7382010-02-28 02:51:25 +0000629void APFloat::makeNaN(bool SNaN, bool Negative, const APInt *fill)
Neil Boothe5e01942007-10-14 10:39:51 +0000630{
631 category = fcNaN;
John McCalle12b7382010-02-28 02:51:25 +0000632 sign = Negative;
633
634 // Set the significand bits to the fill.
635 if (!fill || fill->getNumWords() < partCount())
636 APInt::tcSet(significandParts(), 0, partCount());
637 if (fill)
638 APInt::tcAssign(significandParts(), fill->getRawData(), partCount());
639
640 if (SNaN) {
641 // We always have to clear the QNaN bit to make it an SNaN.
642 APInt::tcClearBit(significandParts(), semantics->precision - 2);
643
644 // If there are no bits set in the payload, we have to set
645 // *something* to make it a NaN instead of an infinity;
646 // conventionally, this is the next bit down from the QNaN bit.
647 if (APInt::tcIsZero(significandParts(), partCount()))
648 APInt::tcSetBit(significandParts(), semantics->precision - 3);
649 } else {
650 // We always have to set the QNaN bit to make it a QNaN.
651 APInt::tcSetBit(significandParts(), semantics->precision - 2);
652 }
653}
654
655APFloat APFloat::makeNaN(const fltSemantics &Sem, bool SNaN, bool Negative,
656 const APInt *fill) {
657 APFloat value(Sem, uninitialized);
658 value.makeNaN(SNaN, Negative, fill);
659 return value;
Neil Boothe5e01942007-10-14 10:39:51 +0000660}
661
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000662APFloat &
663APFloat::operator=(const APFloat &rhs)
664{
665 if(this != &rhs) {
666 if(semantics != rhs.semantics) {
667 freeSignificand();
668 initialize(rhs.semantics);
669 }
670 assign(rhs);
671 }
672
673 return *this;
674}
675
Dale Johannesen343e7702007-08-24 00:56:33 +0000676bool
Dale Johannesen12595d72007-08-24 22:09:56 +0000677APFloat::bitwiseIsEqual(const APFloat &rhs) const {
Dale Johannesen343e7702007-08-24 00:56:33 +0000678 if (this == &rhs)
679 return true;
680 if (semantics != rhs.semantics ||
Dale Johanneseneaf08942007-08-31 04:03:46 +0000681 category != rhs.category ||
682 sign != rhs.sign)
Dale Johannesen343e7702007-08-24 00:56:33 +0000683 return false;
Dan Gohmanb10abe12008-01-29 12:08:20 +0000684 if (semantics==(const llvm::fltSemantics*)&PPCDoubleDouble &&
Dale Johannesena471c2e2007-10-11 18:07:22 +0000685 sign2 != rhs.sign2)
686 return false;
Dale Johanneseneaf08942007-08-31 04:03:46 +0000687 if (category==fcZero || category==fcInfinity)
Dale Johannesen343e7702007-08-24 00:56:33 +0000688 return true;
Dale Johanneseneaf08942007-08-31 04:03:46 +0000689 else if (category==fcNormal && exponent!=rhs.exponent)
690 return false;
Dan Gohmanb10abe12008-01-29 12:08:20 +0000691 else if (semantics==(const llvm::fltSemantics*)&PPCDoubleDouble &&
Dale Johannesena471c2e2007-10-11 18:07:22 +0000692 exponent2!=rhs.exponent2)
693 return false;
Dale Johannesen343e7702007-08-24 00:56:33 +0000694 else {
Dale Johannesen343e7702007-08-24 00:56:33 +0000695 int i= partCount();
696 const integerPart* p=significandParts();
697 const integerPart* q=rhs.significandParts();
698 for (; i>0; i--, p++, q++) {
699 if (*p != *q)
700 return false;
701 }
702 return true;
703 }
704}
705
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000706APFloat::APFloat(const fltSemantics &ourSemantics, integerPart value)
707{
Neil Boothcaf19d72007-10-14 10:29:28 +0000708 assertArithmeticOK(ourSemantics);
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000709 initialize(&ourSemantics);
710 sign = 0;
711 zeroSignificand();
712 exponent = ourSemantics.precision - 1;
713 significandParts()[0] = value;
714 normalize(rmNearestTiesToEven, lfExactlyZero);
715}
716
Chris Lattnerd7bd78e2009-09-17 01:08:43 +0000717APFloat::APFloat(const fltSemantics &ourSemantics) {
718 assertArithmeticOK(ourSemantics);
719 initialize(&ourSemantics);
720 category = fcZero;
721 sign = false;
722}
723
John McCalle12b7382010-02-28 02:51:25 +0000724APFloat::APFloat(const fltSemantics &ourSemantics, uninitializedTag tag) {
725 assertArithmeticOK(ourSemantics);
726 // Allocates storage if necessary but does not initialize it.
727 initialize(&ourSemantics);
728}
Chris Lattnerd7bd78e2009-09-17 01:08:43 +0000729
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000730APFloat::APFloat(const fltSemantics &ourSemantics,
John McCalle12b7382010-02-28 02:51:25 +0000731 fltCategory ourCategory, bool negative)
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000732{
Neil Boothcaf19d72007-10-14 10:29:28 +0000733 assertArithmeticOK(ourSemantics);
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000734 initialize(&ourSemantics);
735 category = ourCategory;
736 sign = negative;
Mike Stumpc5ca7132009-05-30 03:49:43 +0000737 if (category == fcNormal)
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000738 category = fcZero;
Neil Boothe5e01942007-10-14 10:39:51 +0000739 else if (ourCategory == fcNaN)
John McCalle12b7382010-02-28 02:51:25 +0000740 makeNaN();
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000741}
742
Erick Tryzelaara15d8902009-08-16 23:36:19 +0000743APFloat::APFloat(const fltSemantics &ourSemantics, const StringRef& text)
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000744{
Neil Boothcaf19d72007-10-14 10:29:28 +0000745 assertArithmeticOK(ourSemantics);
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000746 initialize(&ourSemantics);
747 convertFromString(text, rmNearestTiesToEven);
748}
749
750APFloat::APFloat(const APFloat &rhs)
751{
752 initialize(rhs.semantics);
753 assign(rhs);
754}
755
756APFloat::~APFloat()
757{
758 freeSignificand();
759}
760
Ted Kremenek1f801fa2008-02-11 17:24:50 +0000761// Profile - This method 'profiles' an APFloat for use with FoldingSet.
762void APFloat::Profile(FoldingSetNodeID& ID) const {
Dale Johannesen7111b022008-10-09 18:53:47 +0000763 ID.Add(bitcastToAPInt());
Ted Kremenek1f801fa2008-02-11 17:24:50 +0000764}
765
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000766unsigned int
767APFloat::partCount() const
768{
Dale Johannesena72a5a02007-09-20 23:47:58 +0000769 return partCountForBits(semantics->precision + 1);
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000770}
771
772unsigned int
773APFloat::semanticsPrecision(const fltSemantics &semantics)
774{
775 return semantics.precision;
776}
777
778const integerPart *
779APFloat::significandParts() const
780{
781 return const_cast<APFloat *>(this)->significandParts();
782}
783
784integerPart *
785APFloat::significandParts()
786{
Dale Johanneseneaf08942007-08-31 04:03:46 +0000787 assert(category == fcNormal || category == fcNaN);
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000788
Evan Cheng99ebfa52009-10-27 21:35:42 +0000789 if (partCount() > 1)
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000790 return significand.parts;
791 else
792 return &significand.part;
793}
794
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000795void
796APFloat::zeroSignificand()
797{
798 category = fcNormal;
799 APInt::tcSet(significandParts(), 0, partCount());
800}
801
802/* Increment an fcNormal floating point number's significand. */
803void
804APFloat::incrementSignificand()
805{
806 integerPart carry;
807
808 carry = APInt::tcIncrement(significandParts(), partCount());
809
810 /* Our callers should never cause us to overflow. */
811 assert(carry == 0);
812}
813
814/* Add the significand of the RHS. Returns the carry flag. */
815integerPart
816APFloat::addSignificand(const APFloat &rhs)
817{
818 integerPart *parts;
819
820 parts = significandParts();
821
822 assert(semantics == rhs.semantics);
823 assert(exponent == rhs.exponent);
824
825 return APInt::tcAdd(parts, rhs.significandParts(), 0, partCount());
826}
827
828/* Subtract the significand of the RHS with a borrow flag. Returns
829 the borrow flag. */
830integerPart
831APFloat::subtractSignificand(const APFloat &rhs, integerPart borrow)
832{
833 integerPart *parts;
834
835 parts = significandParts();
836
837 assert(semantics == rhs.semantics);
838 assert(exponent == rhs.exponent);
839
840 return APInt::tcSubtract(parts, rhs.significandParts(), borrow,
Neil Booth4f881702007-09-26 21:33:42 +0000841 partCount());
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000842}
843
844/* Multiply the significand of the RHS. If ADDEND is non-NULL, add it
845 on to the full-precision result of the multiplication. Returns the
846 lost fraction. */
847lostFraction
848APFloat::multiplySignificand(const APFloat &rhs, const APFloat *addend)
849{
Neil Booth4f881702007-09-26 21:33:42 +0000850 unsigned int omsb; // One, not zero, based MSB.
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000851 unsigned int partsCount, newPartsCount, precision;
852 integerPart *lhsSignificand;
853 integerPart scratch[4];
854 integerPart *fullSignificand;
855 lostFraction lost_fraction;
Dale Johannesen23a98552008-10-09 23:00:39 +0000856 bool ignored;
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000857
858 assert(semantics == rhs.semantics);
859
860 precision = semantics->precision;
861 newPartsCount = partCountForBits(precision * 2);
862
863 if(newPartsCount > 4)
864 fullSignificand = new integerPart[newPartsCount];
865 else
866 fullSignificand = scratch;
867
868 lhsSignificand = significandParts();
869 partsCount = partCount();
870
871 APInt::tcFullMultiply(fullSignificand, lhsSignificand,
Neil Booth978661d2007-10-06 00:24:48 +0000872 rhs.significandParts(), partsCount, partsCount);
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000873
874 lost_fraction = lfExactlyZero;
875 omsb = APInt::tcMSB(fullSignificand, newPartsCount) + 1;
876 exponent += rhs.exponent;
877
878 if(addend) {
879 Significand savedSignificand = significand;
880 const fltSemantics *savedSemantics = semantics;
881 fltSemantics extendedSemantics;
882 opStatus status;
883 unsigned int extendedPrecision;
884
885 /* Normalize our MSB. */
886 extendedPrecision = precision + precision - 1;
887 if(omsb != extendedPrecision)
888 {
Neil Booth4f881702007-09-26 21:33:42 +0000889 APInt::tcShiftLeft(fullSignificand, newPartsCount,
890 extendedPrecision - omsb);
891 exponent -= extendedPrecision - omsb;
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000892 }
893
894 /* Create new semantics. */
895 extendedSemantics = *semantics;
896 extendedSemantics.precision = extendedPrecision;
897
898 if(newPartsCount == 1)
899 significand.part = fullSignificand[0];
900 else
901 significand.parts = fullSignificand;
902 semantics = &extendedSemantics;
903
904 APFloat extendedAddend(*addend);
Dale Johannesen23a98552008-10-09 23:00:39 +0000905 status = extendedAddend.convert(extendedSemantics, rmTowardZero, &ignored);
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000906 assert(status == opOK);
907 lost_fraction = addOrSubtractSignificand(extendedAddend, false);
908
909 /* Restore our state. */
910 if(newPartsCount == 1)
911 fullSignificand[0] = significand.part;
912 significand = savedSignificand;
913 semantics = savedSemantics;
914
915 omsb = APInt::tcMSB(fullSignificand, newPartsCount) + 1;
916 }
917
918 exponent -= (precision - 1);
919
920 if(omsb > precision) {
921 unsigned int bits, significantParts;
922 lostFraction lf;
923
924 bits = omsb - precision;
925 significantParts = partCountForBits(omsb);
926 lf = shiftRight(fullSignificand, significantParts, bits);
927 lost_fraction = combineLostFractions(lf, lost_fraction);
928 exponent += bits;
929 }
930
931 APInt::tcAssign(lhsSignificand, fullSignificand, partsCount);
932
933 if(newPartsCount > 4)
934 delete [] fullSignificand;
935
936 return lost_fraction;
937}
938
939/* Multiply the significands of LHS and RHS to DST. */
940lostFraction
941APFloat::divideSignificand(const APFloat &rhs)
942{
943 unsigned int bit, i, partsCount;
944 const integerPart *rhsSignificand;
945 integerPart *lhsSignificand, *dividend, *divisor;
946 integerPart scratch[4];
947 lostFraction lost_fraction;
948
949 assert(semantics == rhs.semantics);
950
951 lhsSignificand = significandParts();
952 rhsSignificand = rhs.significandParts();
953 partsCount = partCount();
954
955 if(partsCount > 2)
956 dividend = new integerPart[partsCount * 2];
957 else
958 dividend = scratch;
959
960 divisor = dividend + partsCount;
961
962 /* Copy the dividend and divisor as they will be modified in-place. */
963 for(i = 0; i < partsCount; i++) {
964 dividend[i] = lhsSignificand[i];
965 divisor[i] = rhsSignificand[i];
966 lhsSignificand[i] = 0;
967 }
968
969 exponent -= rhs.exponent;
970
971 unsigned int precision = semantics->precision;
972
973 /* Normalize the divisor. */
974 bit = precision - APInt::tcMSB(divisor, partsCount) - 1;
975 if(bit) {
976 exponent += bit;
977 APInt::tcShiftLeft(divisor, partsCount, bit);
978 }
979
980 /* Normalize the dividend. */
981 bit = precision - APInt::tcMSB(dividend, partsCount) - 1;
982 if(bit) {
983 exponent -= bit;
984 APInt::tcShiftLeft(dividend, partsCount, bit);
985 }
986
Neil Booth96c74712007-10-12 16:02:31 +0000987 /* Ensure the dividend >= divisor initially for the loop below.
988 Incidentally, this means that the division loop below is
989 guaranteed to set the integer bit to one. */
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000990 if(APInt::tcCompare(dividend, divisor, partsCount) < 0) {
991 exponent--;
992 APInt::tcShiftLeft(dividend, partsCount, 1);
993 assert(APInt::tcCompare(dividend, divisor, partsCount) >= 0);
994 }
995
996 /* Long division. */
997 for(bit = precision; bit; bit -= 1) {
998 if(APInt::tcCompare(dividend, divisor, partsCount) >= 0) {
999 APInt::tcSubtract(dividend, divisor, 0, partsCount);
1000 APInt::tcSetBit(lhsSignificand, bit - 1);
1001 }
1002
1003 APInt::tcShiftLeft(dividend, partsCount, 1);
1004 }
1005
1006 /* Figure out the lost fraction. */
1007 int cmp = APInt::tcCompare(dividend, divisor, partsCount);
1008
1009 if(cmp > 0)
1010 lost_fraction = lfMoreThanHalf;
1011 else if(cmp == 0)
1012 lost_fraction = lfExactlyHalf;
1013 else if(APInt::tcIsZero(dividend, partsCount))
1014 lost_fraction = lfExactlyZero;
1015 else
1016 lost_fraction = lfLessThanHalf;
1017
1018 if(partsCount > 2)
1019 delete [] dividend;
1020
1021 return lost_fraction;
1022}
1023
1024unsigned int
1025APFloat::significandMSB() const
1026{
1027 return APInt::tcMSB(significandParts(), partCount());
1028}
1029
1030unsigned int
1031APFloat::significandLSB() const
1032{
1033 return APInt::tcLSB(significandParts(), partCount());
1034}
1035
1036/* Note that a zero result is NOT normalized to fcZero. */
1037lostFraction
1038APFloat::shiftSignificandRight(unsigned int bits)
1039{
1040 /* Our exponent should not overflow. */
1041 assert((exponent_t) (exponent + bits) >= exponent);
1042
1043 exponent += bits;
1044
1045 return shiftRight(significandParts(), partCount(), bits);
1046}
1047
1048/* Shift the significand left BITS bits, subtract BITS from its exponent. */
1049void
1050APFloat::shiftSignificandLeft(unsigned int bits)
1051{
1052 assert(bits < semantics->precision);
1053
1054 if(bits) {
1055 unsigned int partsCount = partCount();
1056
1057 APInt::tcShiftLeft(significandParts(), partsCount, bits);
1058 exponent -= bits;
1059
1060 assert(!APInt::tcIsZero(significandParts(), partsCount));
1061 }
1062}
1063
1064APFloat::cmpResult
1065APFloat::compareAbsoluteValue(const APFloat &rhs) const
1066{
1067 int compare;
1068
1069 assert(semantics == rhs.semantics);
1070 assert(category == fcNormal);
1071 assert(rhs.category == fcNormal);
1072
1073 compare = exponent - rhs.exponent;
1074
1075 /* If exponents are equal, do an unsigned bignum comparison of the
1076 significands. */
1077 if(compare == 0)
1078 compare = APInt::tcCompare(significandParts(), rhs.significandParts(),
Neil Booth4f881702007-09-26 21:33:42 +00001079 partCount());
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001080
1081 if(compare > 0)
1082 return cmpGreaterThan;
1083 else if(compare < 0)
1084 return cmpLessThan;
1085 else
1086 return cmpEqual;
1087}
1088
1089/* Handle overflow. Sign is preserved. We either become infinity or
1090 the largest finite number. */
1091APFloat::opStatus
1092APFloat::handleOverflow(roundingMode rounding_mode)
1093{
1094 /* Infinity? */
1095 if(rounding_mode == rmNearestTiesToEven
1096 || rounding_mode == rmNearestTiesToAway
1097 || (rounding_mode == rmTowardPositive && !sign)
1098 || (rounding_mode == rmTowardNegative && sign))
1099 {
1100 category = fcInfinity;
1101 return (opStatus) (opOverflow | opInexact);
1102 }
1103
1104 /* Otherwise we become the largest finite number. */
1105 category = fcNormal;
1106 exponent = semantics->maxExponent;
1107 APInt::tcSetLeastSignificantBits(significandParts(), partCount(),
Neil Booth4f881702007-09-26 21:33:42 +00001108 semantics->precision);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001109
1110 return opInexact;
1111}
1112
Neil Boothb7dea4c2007-10-03 15:16:41 +00001113/* Returns TRUE if, when truncating the current number, with BIT the
1114 new LSB, with the given lost fraction and rounding mode, the result
1115 would need to be rounded away from zero (i.e., by increasing the
1116 signficand). This routine must work for fcZero of both signs, and
1117 fcNormal numbers. */
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001118bool
1119APFloat::roundAwayFromZero(roundingMode rounding_mode,
Neil Boothb7dea4c2007-10-03 15:16:41 +00001120 lostFraction lost_fraction,
1121 unsigned int bit) const
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001122{
Dale Johanneseneaf08942007-08-31 04:03:46 +00001123 /* NaNs and infinities should not have lost fractions. */
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001124 assert(category == fcNormal || category == fcZero);
1125
Neil Boothb7dea4c2007-10-03 15:16:41 +00001126 /* Current callers never pass this so we don't handle it. */
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001127 assert(lost_fraction != lfExactlyZero);
1128
Mike Stumpf3dc0c02009-05-13 23:23:20 +00001129 switch (rounding_mode) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001130 default:
Torok Edwinc23197a2009-07-14 16:55:14 +00001131 llvm_unreachable(0);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001132
1133 case rmNearestTiesToAway:
1134 return lost_fraction == lfExactlyHalf || lost_fraction == lfMoreThanHalf;
1135
1136 case rmNearestTiesToEven:
1137 if(lost_fraction == lfMoreThanHalf)
1138 return true;
1139
1140 /* Our zeroes don't have a significand to test. */
1141 if(lost_fraction == lfExactlyHalf && category != fcZero)
Neil Boothb7dea4c2007-10-03 15:16:41 +00001142 return APInt::tcExtractBit(significandParts(), bit);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001143
1144 return false;
1145
1146 case rmTowardZero:
1147 return false;
1148
1149 case rmTowardPositive:
1150 return sign == false;
1151
1152 case rmTowardNegative:
1153 return sign == true;
1154 }
1155}
1156
1157APFloat::opStatus
1158APFloat::normalize(roundingMode rounding_mode,
Neil Booth4f881702007-09-26 21:33:42 +00001159 lostFraction lost_fraction)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001160{
Neil Booth4f881702007-09-26 21:33:42 +00001161 unsigned int omsb; /* One, not zero, based MSB. */
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001162 int exponentChange;
1163
1164 if(category != fcNormal)
1165 return opOK;
1166
1167 /* Before rounding normalize the exponent of fcNormal numbers. */
1168 omsb = significandMSB() + 1;
1169
1170 if(omsb) {
1171 /* OMSB is numbered from 1. We want to place it in the integer
1172 bit numbered PRECISON if possible, with a compensating change in
1173 the exponent. */
1174 exponentChange = omsb - semantics->precision;
1175
1176 /* If the resulting exponent is too high, overflow according to
1177 the rounding mode. */
1178 if(exponent + exponentChange > semantics->maxExponent)
1179 return handleOverflow(rounding_mode);
1180
1181 /* Subnormal numbers have exponent minExponent, and their MSB
1182 is forced based on that. */
1183 if(exponent + exponentChange < semantics->minExponent)
1184 exponentChange = semantics->minExponent - exponent;
1185
1186 /* Shifting left is easy as we don't lose precision. */
1187 if(exponentChange < 0) {
1188 assert(lost_fraction == lfExactlyZero);
1189
1190 shiftSignificandLeft(-exponentChange);
1191
1192 return opOK;
1193 }
1194
1195 if(exponentChange > 0) {
1196 lostFraction lf;
1197
1198 /* Shift right and capture any new lost fraction. */
1199 lf = shiftSignificandRight(exponentChange);
1200
1201 lost_fraction = combineLostFractions(lf, lost_fraction);
1202
1203 /* Keep OMSB up-to-date. */
1204 if(omsb > (unsigned) exponentChange)
Neil Booth96c74712007-10-12 16:02:31 +00001205 omsb -= exponentChange;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001206 else
Neil Booth4f881702007-09-26 21:33:42 +00001207 omsb = 0;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001208 }
1209 }
1210
1211 /* Now round the number according to rounding_mode given the lost
1212 fraction. */
1213
1214 /* As specified in IEEE 754, since we do not trap we do not report
1215 underflow for exact results. */
1216 if(lost_fraction == lfExactlyZero) {
1217 /* Canonicalize zeroes. */
1218 if(omsb == 0)
1219 category = fcZero;
1220
1221 return opOK;
1222 }
1223
1224 /* Increment the significand if we're rounding away from zero. */
Neil Boothb7dea4c2007-10-03 15:16:41 +00001225 if(roundAwayFromZero(rounding_mode, lost_fraction, 0)) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001226 if(omsb == 0)
1227 exponent = semantics->minExponent;
1228
1229 incrementSignificand();
1230 omsb = significandMSB() + 1;
1231
1232 /* Did the significand increment overflow? */
1233 if(omsb == (unsigned) semantics->precision + 1) {
1234 /* Renormalize by incrementing the exponent and shifting our
Neil Booth4f881702007-09-26 21:33:42 +00001235 significand right one. However if we already have the
1236 maximum exponent we overflow to infinity. */
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001237 if(exponent == semantics->maxExponent) {
Neil Booth4f881702007-09-26 21:33:42 +00001238 category = fcInfinity;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001239
Neil Booth4f881702007-09-26 21:33:42 +00001240 return (opStatus) (opOverflow | opInexact);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001241 }
1242
1243 shiftSignificandRight(1);
1244
1245 return opInexact;
1246 }
1247 }
1248
1249 /* The normal case - we were and are not denormal, and any
1250 significand increment above didn't overflow. */
1251 if(omsb == semantics->precision)
1252 return opInexact;
1253
1254 /* We have a non-zero denormal. */
1255 assert(omsb < semantics->precision);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001256
1257 /* Canonicalize zeroes. */
1258 if(omsb == 0)
1259 category = fcZero;
1260
1261 /* The fcZero case is a denormal that underflowed to zero. */
1262 return (opStatus) (opUnderflow | opInexact);
1263}
1264
1265APFloat::opStatus
1266APFloat::addOrSubtractSpecials(const APFloat &rhs, bool subtract)
1267{
Mike Stumpf3dc0c02009-05-13 23:23:20 +00001268 switch (convolve(category, rhs.category)) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001269 default:
Torok Edwinc23197a2009-07-14 16:55:14 +00001270 llvm_unreachable(0);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001271
Dale Johanneseneaf08942007-08-31 04:03:46 +00001272 case convolve(fcNaN, fcZero):
1273 case convolve(fcNaN, fcNormal):
1274 case convolve(fcNaN, fcInfinity):
1275 case convolve(fcNaN, fcNaN):
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001276 case convolve(fcNormal, fcZero):
1277 case convolve(fcInfinity, fcNormal):
1278 case convolve(fcInfinity, fcZero):
1279 return opOK;
1280
Dale Johanneseneaf08942007-08-31 04:03:46 +00001281 case convolve(fcZero, fcNaN):
1282 case convolve(fcNormal, fcNaN):
1283 case convolve(fcInfinity, fcNaN):
1284 category = fcNaN;
1285 copySignificand(rhs);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001286 return opOK;
1287
1288 case convolve(fcNormal, fcInfinity):
1289 case convolve(fcZero, fcInfinity):
1290 category = fcInfinity;
1291 sign = rhs.sign ^ subtract;
1292 return opOK;
1293
1294 case convolve(fcZero, fcNormal):
1295 assign(rhs);
1296 sign = rhs.sign ^ subtract;
1297 return opOK;
1298
1299 case convolve(fcZero, fcZero):
1300 /* Sign depends on rounding mode; handled by caller. */
1301 return opOK;
1302
1303 case convolve(fcInfinity, fcInfinity):
1304 /* Differently signed infinities can only be validly
1305 subtracted. */
Cedric Venetaff9c272009-02-14 16:06:42 +00001306 if(((sign ^ rhs.sign)!=0) != subtract) {
Neil Boothe5e01942007-10-14 10:39:51 +00001307 makeNaN();
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001308 return opInvalidOp;
1309 }
1310
1311 return opOK;
1312
1313 case convolve(fcNormal, fcNormal):
1314 return opDivByZero;
1315 }
1316}
1317
1318/* Add or subtract two normal numbers. */
1319lostFraction
1320APFloat::addOrSubtractSignificand(const APFloat &rhs, bool subtract)
1321{
1322 integerPart carry;
1323 lostFraction lost_fraction;
1324 int bits;
1325
1326 /* Determine if the operation on the absolute values is effectively
1327 an addition or subtraction. */
Hartmut Kaiser8df77a92007-10-25 23:15:31 +00001328 subtract ^= (sign ^ rhs.sign) ? true : false;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001329
1330 /* Are we bigger exponent-wise than the RHS? */
1331 bits = exponent - rhs.exponent;
1332
1333 /* Subtraction is more subtle than one might naively expect. */
1334 if(subtract) {
1335 APFloat temp_rhs(rhs);
1336 bool reverse;
1337
Chris Lattnerada530b2007-08-24 03:02:34 +00001338 if (bits == 0) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001339 reverse = compareAbsoluteValue(temp_rhs) == cmpLessThan;
1340 lost_fraction = lfExactlyZero;
Chris Lattnerada530b2007-08-24 03:02:34 +00001341 } else if (bits > 0) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001342 lost_fraction = temp_rhs.shiftSignificandRight(bits - 1);
1343 shiftSignificandLeft(1);
1344 reverse = false;
Chris Lattnerada530b2007-08-24 03:02:34 +00001345 } else {
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001346 lost_fraction = shiftSignificandRight(-bits - 1);
1347 temp_rhs.shiftSignificandLeft(1);
1348 reverse = true;
1349 }
1350
Chris Lattnerada530b2007-08-24 03:02:34 +00001351 if (reverse) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001352 carry = temp_rhs.subtractSignificand
Neil Booth4f881702007-09-26 21:33:42 +00001353 (*this, lost_fraction != lfExactlyZero);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001354 copySignificand(temp_rhs);
1355 sign = !sign;
1356 } else {
1357 carry = subtractSignificand
Neil Booth4f881702007-09-26 21:33:42 +00001358 (temp_rhs, lost_fraction != lfExactlyZero);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001359 }
1360
1361 /* Invert the lost fraction - it was on the RHS and
1362 subtracted. */
1363 if(lost_fraction == lfLessThanHalf)
1364 lost_fraction = lfMoreThanHalf;
1365 else if(lost_fraction == lfMoreThanHalf)
1366 lost_fraction = lfLessThanHalf;
1367
1368 /* The code above is intended to ensure that no borrow is
1369 necessary. */
1370 assert(!carry);
1371 } else {
1372 if(bits > 0) {
1373 APFloat temp_rhs(rhs);
1374
1375 lost_fraction = temp_rhs.shiftSignificandRight(bits);
1376 carry = addSignificand(temp_rhs);
1377 } else {
1378 lost_fraction = shiftSignificandRight(-bits);
1379 carry = addSignificand(rhs);
1380 }
1381
1382 /* We have a guard bit; generating a carry cannot happen. */
1383 assert(!carry);
1384 }
1385
1386 return lost_fraction;
1387}
1388
1389APFloat::opStatus
1390APFloat::multiplySpecials(const APFloat &rhs)
1391{
Mike Stumpf3dc0c02009-05-13 23:23:20 +00001392 switch (convolve(category, rhs.category)) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001393 default:
Torok Edwinc23197a2009-07-14 16:55:14 +00001394 llvm_unreachable(0);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001395
Dale Johanneseneaf08942007-08-31 04:03:46 +00001396 case convolve(fcNaN, fcZero):
1397 case convolve(fcNaN, fcNormal):
1398 case convolve(fcNaN, fcInfinity):
1399 case convolve(fcNaN, fcNaN):
1400 return opOK;
1401
1402 case convolve(fcZero, fcNaN):
1403 case convolve(fcNormal, fcNaN):
1404 case convolve(fcInfinity, fcNaN):
1405 category = fcNaN;
1406 copySignificand(rhs);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001407 return opOK;
1408
1409 case convolve(fcNormal, fcInfinity):
1410 case convolve(fcInfinity, fcNormal):
1411 case convolve(fcInfinity, fcInfinity):
1412 category = fcInfinity;
1413 return opOK;
1414
1415 case convolve(fcZero, fcNormal):
1416 case convolve(fcNormal, fcZero):
1417 case convolve(fcZero, fcZero):
1418 category = fcZero;
1419 return opOK;
1420
1421 case convolve(fcZero, fcInfinity):
1422 case convolve(fcInfinity, fcZero):
Neil Boothe5e01942007-10-14 10:39:51 +00001423 makeNaN();
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001424 return opInvalidOp;
1425
1426 case convolve(fcNormal, fcNormal):
1427 return opOK;
1428 }
1429}
1430
1431APFloat::opStatus
1432APFloat::divideSpecials(const APFloat &rhs)
1433{
Mike Stumpf3dc0c02009-05-13 23:23:20 +00001434 switch (convolve(category, rhs.category)) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001435 default:
Torok Edwinc23197a2009-07-14 16:55:14 +00001436 llvm_unreachable(0);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001437
Dale Johanneseneaf08942007-08-31 04:03:46 +00001438 case convolve(fcNaN, fcZero):
1439 case convolve(fcNaN, fcNormal):
1440 case convolve(fcNaN, fcInfinity):
1441 case convolve(fcNaN, fcNaN):
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001442 case convolve(fcInfinity, fcZero):
1443 case convolve(fcInfinity, fcNormal):
1444 case convolve(fcZero, fcInfinity):
1445 case convolve(fcZero, fcNormal):
1446 return opOK;
1447
Dale Johanneseneaf08942007-08-31 04:03:46 +00001448 case convolve(fcZero, fcNaN):
1449 case convolve(fcNormal, fcNaN):
1450 case convolve(fcInfinity, fcNaN):
1451 category = fcNaN;
1452 copySignificand(rhs);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001453 return opOK;
1454
1455 case convolve(fcNormal, fcInfinity):
1456 category = fcZero;
1457 return opOK;
1458
1459 case convolve(fcNormal, fcZero):
1460 category = fcInfinity;
1461 return opDivByZero;
1462
1463 case convolve(fcInfinity, fcInfinity):
1464 case convolve(fcZero, fcZero):
Neil Boothe5e01942007-10-14 10:39:51 +00001465 makeNaN();
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001466 return opInvalidOp;
1467
1468 case convolve(fcNormal, fcNormal):
1469 return opOK;
1470 }
1471}
1472
Dale Johannesened6af242009-01-21 00:35:19 +00001473APFloat::opStatus
1474APFloat::modSpecials(const APFloat &rhs)
1475{
Mike Stumpf3dc0c02009-05-13 23:23:20 +00001476 switch (convolve(category, rhs.category)) {
Dale Johannesened6af242009-01-21 00:35:19 +00001477 default:
Torok Edwinc23197a2009-07-14 16:55:14 +00001478 llvm_unreachable(0);
Dale Johannesened6af242009-01-21 00:35:19 +00001479
1480 case convolve(fcNaN, fcZero):
1481 case convolve(fcNaN, fcNormal):
1482 case convolve(fcNaN, fcInfinity):
1483 case convolve(fcNaN, fcNaN):
1484 case convolve(fcZero, fcInfinity):
1485 case convolve(fcZero, fcNormal):
1486 case convolve(fcNormal, fcInfinity):
1487 return opOK;
1488
1489 case convolve(fcZero, fcNaN):
1490 case convolve(fcNormal, fcNaN):
1491 case convolve(fcInfinity, fcNaN):
1492 category = fcNaN;
1493 copySignificand(rhs);
1494 return opOK;
1495
1496 case convolve(fcNormal, fcZero):
1497 case convolve(fcInfinity, fcZero):
1498 case convolve(fcInfinity, fcNormal):
1499 case convolve(fcInfinity, fcInfinity):
1500 case convolve(fcZero, fcZero):
1501 makeNaN();
1502 return opInvalidOp;
1503
1504 case convolve(fcNormal, fcNormal):
1505 return opOK;
1506 }
1507}
1508
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001509/* Change sign. */
1510void
1511APFloat::changeSign()
1512{
1513 /* Look mummy, this one's easy. */
1514 sign = !sign;
1515}
1516
Dale Johannesene15c2db2007-08-31 23:35:31 +00001517void
1518APFloat::clearSign()
1519{
1520 /* So is this one. */
1521 sign = 0;
1522}
1523
1524void
1525APFloat::copySign(const APFloat &rhs)
1526{
1527 /* And this one. */
1528 sign = rhs.sign;
1529}
1530
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001531/* Normalized addition or subtraction. */
1532APFloat::opStatus
1533APFloat::addOrSubtract(const APFloat &rhs, roundingMode rounding_mode,
Neil Booth4f881702007-09-26 21:33:42 +00001534 bool subtract)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001535{
1536 opStatus fs;
1537
Neil Boothcaf19d72007-10-14 10:29:28 +00001538 assertArithmeticOK(*semantics);
1539
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001540 fs = addOrSubtractSpecials(rhs, subtract);
1541
1542 /* This return code means it was not a simple case. */
1543 if(fs == opDivByZero) {
1544 lostFraction lost_fraction;
1545
1546 lost_fraction = addOrSubtractSignificand(rhs, subtract);
1547 fs = normalize(rounding_mode, lost_fraction);
1548
1549 /* Can only be zero if we lost no fraction. */
1550 assert(category != fcZero || lost_fraction == lfExactlyZero);
1551 }
1552
1553 /* If two numbers add (exactly) to zero, IEEE 754 decrees it is a
1554 positive zero unless rounding to minus infinity, except that
1555 adding two like-signed zeroes gives that zero. */
1556 if(category == fcZero) {
1557 if(rhs.category != fcZero || (sign == rhs.sign) == subtract)
1558 sign = (rounding_mode == rmTowardNegative);
1559 }
1560
1561 return fs;
1562}
1563
1564/* Normalized addition. */
1565APFloat::opStatus
1566APFloat::add(const APFloat &rhs, roundingMode rounding_mode)
1567{
1568 return addOrSubtract(rhs, rounding_mode, false);
1569}
1570
1571/* Normalized subtraction. */
1572APFloat::opStatus
1573APFloat::subtract(const APFloat &rhs, roundingMode rounding_mode)
1574{
1575 return addOrSubtract(rhs, rounding_mode, true);
1576}
1577
1578/* Normalized multiply. */
1579APFloat::opStatus
1580APFloat::multiply(const APFloat &rhs, roundingMode rounding_mode)
1581{
1582 opStatus fs;
1583
Neil Boothcaf19d72007-10-14 10:29:28 +00001584 assertArithmeticOK(*semantics);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001585 sign ^= rhs.sign;
1586 fs = multiplySpecials(rhs);
1587
1588 if(category == fcNormal) {
1589 lostFraction lost_fraction = multiplySignificand(rhs, 0);
1590 fs = normalize(rounding_mode, lost_fraction);
1591 if(lost_fraction != lfExactlyZero)
1592 fs = (opStatus) (fs | opInexact);
1593 }
1594
1595 return fs;
1596}
1597
1598/* Normalized divide. */
1599APFloat::opStatus
1600APFloat::divide(const APFloat &rhs, roundingMode rounding_mode)
1601{
1602 opStatus fs;
1603
Neil Boothcaf19d72007-10-14 10:29:28 +00001604 assertArithmeticOK(*semantics);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001605 sign ^= rhs.sign;
1606 fs = divideSpecials(rhs);
1607
1608 if(category == fcNormal) {
1609 lostFraction lost_fraction = divideSignificand(rhs);
1610 fs = normalize(rounding_mode, lost_fraction);
1611 if(lost_fraction != lfExactlyZero)
1612 fs = (opStatus) (fs | opInexact);
1613 }
1614
1615 return fs;
1616}
1617
Dale Johannesen24b66a82009-01-20 18:35:05 +00001618/* Normalized remainder. This is not currently correct in all cases. */
1619APFloat::opStatus
1620APFloat::remainder(const APFloat &rhs)
1621{
1622 opStatus fs;
1623 APFloat V = *this;
1624 unsigned int origSign = sign;
1625
1626 assertArithmeticOK(*semantics);
1627 fs = V.divide(rhs, rmNearestTiesToEven);
1628 if (fs == opDivByZero)
1629 return fs;
1630
1631 int parts = partCount();
1632 integerPart *x = new integerPart[parts];
1633 bool ignored;
1634 fs = V.convertToInteger(x, parts * integerPartWidth, true,
1635 rmNearestTiesToEven, &ignored);
1636 if (fs==opInvalidOp)
1637 return fs;
1638
1639 fs = V.convertFromZeroExtendedInteger(x, parts * integerPartWidth, true,
1640 rmNearestTiesToEven);
1641 assert(fs==opOK); // should always work
1642
1643 fs = V.multiply(rhs, rmNearestTiesToEven);
1644 assert(fs==opOK || fs==opInexact); // should not overflow or underflow
1645
1646 fs = subtract(V, rmNearestTiesToEven);
1647 assert(fs==opOK || fs==opInexact); // likewise
1648
1649 if (isZero())
1650 sign = origSign; // IEEE754 requires this
1651 delete[] x;
1652 return fs;
1653}
1654
1655/* Normalized llvm frem (C fmod).
1656 This is not currently correct in all cases. */
Dale Johannesene15c2db2007-08-31 23:35:31 +00001657APFloat::opStatus
1658APFloat::mod(const APFloat &rhs, roundingMode rounding_mode)
1659{
1660 opStatus fs;
Neil Boothcaf19d72007-10-14 10:29:28 +00001661 assertArithmeticOK(*semantics);
Dale Johannesened6af242009-01-21 00:35:19 +00001662 fs = modSpecials(rhs);
Dale Johannesene15c2db2007-08-31 23:35:31 +00001663
Dale Johannesened6af242009-01-21 00:35:19 +00001664 if (category == fcNormal && rhs.category == fcNormal) {
1665 APFloat V = *this;
1666 unsigned int origSign = sign;
Dale Johannesene15c2db2007-08-31 23:35:31 +00001667
Dale Johannesened6af242009-01-21 00:35:19 +00001668 fs = V.divide(rhs, rmNearestTiesToEven);
1669 if (fs == opDivByZero)
1670 return fs;
Dale Johannesen58c2e4c2007-09-05 20:39:49 +00001671
Dale Johannesened6af242009-01-21 00:35:19 +00001672 int parts = partCount();
1673 integerPart *x = new integerPart[parts];
1674 bool ignored;
1675 fs = V.convertToInteger(x, parts * integerPartWidth, true,
1676 rmTowardZero, &ignored);
1677 if (fs==opInvalidOp)
1678 return fs;
Dale Johannesen58c2e4c2007-09-05 20:39:49 +00001679
Dale Johannesened6af242009-01-21 00:35:19 +00001680 fs = V.convertFromZeroExtendedInteger(x, parts * integerPartWidth, true,
1681 rmNearestTiesToEven);
1682 assert(fs==opOK); // should always work
Dale Johannesen58c2e4c2007-09-05 20:39:49 +00001683
Dale Johannesened6af242009-01-21 00:35:19 +00001684 fs = V.multiply(rhs, rounding_mode);
1685 assert(fs==opOK || fs==opInexact); // should not overflow or underflow
1686
1687 fs = subtract(V, rounding_mode);
1688 assert(fs==opOK || fs==opInexact); // likewise
1689
1690 if (isZero())
1691 sign = origSign; // IEEE754 requires this
1692 delete[] x;
1693 }
Dale Johannesene15c2db2007-08-31 23:35:31 +00001694 return fs;
1695}
1696
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001697/* Normalized fused-multiply-add. */
1698APFloat::opStatus
1699APFloat::fusedMultiplyAdd(const APFloat &multiplicand,
Neil Booth4f881702007-09-26 21:33:42 +00001700 const APFloat &addend,
1701 roundingMode rounding_mode)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001702{
1703 opStatus fs;
1704
Neil Boothcaf19d72007-10-14 10:29:28 +00001705 assertArithmeticOK(*semantics);
1706
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001707 /* Post-multiplication sign, before addition. */
1708 sign ^= multiplicand.sign;
1709
1710 /* If and only if all arguments are normal do we need to do an
1711 extended-precision calculation. */
1712 if(category == fcNormal
1713 && multiplicand.category == fcNormal
1714 && addend.category == fcNormal) {
1715 lostFraction lost_fraction;
1716
1717 lost_fraction = multiplySignificand(multiplicand, &addend);
1718 fs = normalize(rounding_mode, lost_fraction);
1719 if(lost_fraction != lfExactlyZero)
1720 fs = (opStatus) (fs | opInexact);
1721
1722 /* If two numbers add (exactly) to zero, IEEE 754 decrees it is a
1723 positive zero unless rounding to minus infinity, except that
1724 adding two like-signed zeroes gives that zero. */
1725 if(category == fcZero && sign != addend.sign)
1726 sign = (rounding_mode == rmTowardNegative);
1727 } else {
1728 fs = multiplySpecials(multiplicand);
1729
1730 /* FS can only be opOK or opInvalidOp. There is no more work
1731 to do in the latter case. The IEEE-754R standard says it is
1732 implementation-defined in this case whether, if ADDEND is a
Dale Johanneseneaf08942007-08-31 04:03:46 +00001733 quiet NaN, we raise invalid op; this implementation does so.
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001734
1735 If we need to do the addition we can do so with normal
1736 precision. */
1737 if(fs == opOK)
1738 fs = addOrSubtract(addend, rounding_mode, false);
1739 }
1740
1741 return fs;
1742}
1743
1744/* Comparison requires normalized numbers. */
1745APFloat::cmpResult
1746APFloat::compare(const APFloat &rhs) const
1747{
1748 cmpResult result;
1749
Neil Boothcaf19d72007-10-14 10:29:28 +00001750 assertArithmeticOK(*semantics);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001751 assert(semantics == rhs.semantics);
1752
Mike Stumpf3dc0c02009-05-13 23:23:20 +00001753 switch (convolve(category, rhs.category)) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001754 default:
Torok Edwinc23197a2009-07-14 16:55:14 +00001755 llvm_unreachable(0);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001756
Dale Johanneseneaf08942007-08-31 04:03:46 +00001757 case convolve(fcNaN, fcZero):
1758 case convolve(fcNaN, fcNormal):
1759 case convolve(fcNaN, fcInfinity):
1760 case convolve(fcNaN, fcNaN):
1761 case convolve(fcZero, fcNaN):
1762 case convolve(fcNormal, fcNaN):
1763 case convolve(fcInfinity, fcNaN):
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001764 return cmpUnordered;
1765
1766 case convolve(fcInfinity, fcNormal):
1767 case convolve(fcInfinity, fcZero):
1768 case convolve(fcNormal, fcZero):
1769 if(sign)
1770 return cmpLessThan;
1771 else
1772 return cmpGreaterThan;
1773
1774 case convolve(fcNormal, fcInfinity):
1775 case convolve(fcZero, fcInfinity):
1776 case convolve(fcZero, fcNormal):
1777 if(rhs.sign)
1778 return cmpGreaterThan;
1779 else
1780 return cmpLessThan;
1781
1782 case convolve(fcInfinity, fcInfinity):
1783 if(sign == rhs.sign)
1784 return cmpEqual;
1785 else if(sign)
1786 return cmpLessThan;
1787 else
1788 return cmpGreaterThan;
1789
1790 case convolve(fcZero, fcZero):
1791 return cmpEqual;
1792
1793 case convolve(fcNormal, fcNormal):
1794 break;
1795 }
1796
1797 /* Two normal numbers. Do they have the same sign? */
1798 if(sign != rhs.sign) {
1799 if(sign)
1800 result = cmpLessThan;
1801 else
1802 result = cmpGreaterThan;
1803 } else {
1804 /* Compare absolute values; invert result if negative. */
1805 result = compareAbsoluteValue(rhs);
1806
1807 if(sign) {
1808 if(result == cmpLessThan)
Neil Booth4f881702007-09-26 21:33:42 +00001809 result = cmpGreaterThan;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001810 else if(result == cmpGreaterThan)
Neil Booth4f881702007-09-26 21:33:42 +00001811 result = cmpLessThan;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001812 }
1813 }
1814
1815 return result;
1816}
1817
Dale Johannesen23a98552008-10-09 23:00:39 +00001818/// APFloat::convert - convert a value of one floating point type to another.
1819/// The return value corresponds to the IEEE754 exceptions. *losesInfo
1820/// records whether the transformation lost information, i.e. whether
1821/// converting the result back to the original type will produce the
1822/// original value (this is almost the same as return value==fsOK, but there
1823/// are edge cases where this is not so).
1824
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001825APFloat::opStatus
1826APFloat::convert(const fltSemantics &toSemantics,
Dale Johannesen23a98552008-10-09 23:00:39 +00001827 roundingMode rounding_mode, bool *losesInfo)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001828{
Neil Boothc8db43d2007-09-22 02:56:19 +00001829 lostFraction lostFraction;
1830 unsigned int newPartCount, oldPartCount;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001831 opStatus fs;
Neil Booth4f881702007-09-26 21:33:42 +00001832
Neil Boothcaf19d72007-10-14 10:29:28 +00001833 assertArithmeticOK(*semantics);
Dale Johannesen79f82f92008-04-20 01:34:03 +00001834 assertArithmeticOK(toSemantics);
Neil Boothc8db43d2007-09-22 02:56:19 +00001835 lostFraction = lfExactlyZero;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001836 newPartCount = partCountForBits(toSemantics.precision + 1);
Neil Boothc8db43d2007-09-22 02:56:19 +00001837 oldPartCount = partCount();
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001838
Neil Boothc8db43d2007-09-22 02:56:19 +00001839 /* Handle storage complications. If our new form is wider,
1840 re-allocate our bit pattern into wider storage. If it is
1841 narrower, we ignore the excess parts, but if narrowing to a
Dale Johannesen902ff942007-09-25 17:25:00 +00001842 single part we need to free the old storage.
1843 Be careful not to reference significandParts for zeroes
1844 and infinities, since it aborts. */
Neil Boothc8db43d2007-09-22 02:56:19 +00001845 if (newPartCount > oldPartCount) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001846 integerPart *newParts;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001847 newParts = new integerPart[newPartCount];
1848 APInt::tcSet(newParts, 0, newPartCount);
Dale Johannesen902ff942007-09-25 17:25:00 +00001849 if (category==fcNormal || category==fcNaN)
1850 APInt::tcAssign(newParts, significandParts(), oldPartCount);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001851 freeSignificand();
1852 significand.parts = newParts;
Neil Boothc8db43d2007-09-22 02:56:19 +00001853 } else if (newPartCount < oldPartCount) {
1854 /* Capture any lost fraction through truncation of parts so we get
1855 correct rounding whilst normalizing. */
Dale Johannesen902ff942007-09-25 17:25:00 +00001856 if (category==fcNormal)
1857 lostFraction = lostFractionThroughTruncation
1858 (significandParts(), oldPartCount, toSemantics.precision);
1859 if (newPartCount == 1) {
1860 integerPart newPart = 0;
Neil Booth4f881702007-09-26 21:33:42 +00001861 if (category==fcNormal || category==fcNaN)
Dale Johannesen902ff942007-09-25 17:25:00 +00001862 newPart = significandParts()[0];
1863 freeSignificand();
1864 significand.part = newPart;
1865 }
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001866 }
1867
1868 if(category == fcNormal) {
1869 /* Re-interpret our bit-pattern. */
1870 exponent += toSemantics.precision - semantics->precision;
1871 semantics = &toSemantics;
Neil Boothc8db43d2007-09-22 02:56:19 +00001872 fs = normalize(rounding_mode, lostFraction);
Dale Johannesen23a98552008-10-09 23:00:39 +00001873 *losesInfo = (fs != opOK);
Dale Johannesen902ff942007-09-25 17:25:00 +00001874 } else if (category == fcNaN) {
1875 int shift = toSemantics.precision - semantics->precision;
Dale Johannesenb63fa052008-01-31 18:34:01 +00001876 // Do this now so significandParts gets the right answer
Dale Johannesen2df5eec2008-10-06 22:59:10 +00001877 const fltSemantics *oldSemantics = semantics;
Dale Johannesenb63fa052008-01-31 18:34:01 +00001878 semantics = &toSemantics;
Dale Johannesen23a98552008-10-09 23:00:39 +00001879 *losesInfo = false;
Dale Johannesen902ff942007-09-25 17:25:00 +00001880 // No normalization here, just truncate
1881 if (shift>0)
1882 APInt::tcShiftLeft(significandParts(), newPartCount, shift);
Dale Johannesen2df5eec2008-10-06 22:59:10 +00001883 else if (shift < 0) {
1884 unsigned ushift = -shift;
Dale Johannesen23a98552008-10-09 23:00:39 +00001885 // Figure out if we are losing information. This happens
Dale Johannesen2df5eec2008-10-06 22:59:10 +00001886 // if are shifting out something other than 0s, or if the x87 long
1887 // double input did not have its integer bit set (pseudo-NaN), or if the
1888 // x87 long double input did not have its QNan bit set (because the x87
1889 // hardware sets this bit when converting a lower-precision NaN to
1890 // x87 long double).
1891 if (APInt::tcLSB(significandParts(), newPartCount) < ushift)
Dale Johannesen23a98552008-10-09 23:00:39 +00001892 *losesInfo = true;
Dale Johannesen2df5eec2008-10-06 22:59:10 +00001893 if (oldSemantics == &APFloat::x87DoubleExtended &&
1894 (!(*significandParts() & 0x8000000000000000ULL) ||
1895 !(*significandParts() & 0x4000000000000000ULL)))
Dale Johannesen23a98552008-10-09 23:00:39 +00001896 *losesInfo = true;
Dale Johannesen2df5eec2008-10-06 22:59:10 +00001897 APInt::tcShiftRight(significandParts(), newPartCount, ushift);
1898 }
Dale Johannesen902ff942007-09-25 17:25:00 +00001899 // gcc forces the Quiet bit on, which means (float)(double)(float_sNan)
1900 // does not give you back the same bits. This is dubious, and we
1901 // don't currently do it. You're really supposed to get
1902 // an invalid operation signal at runtime, but nobody does that.
Dale Johannesen23a98552008-10-09 23:00:39 +00001903 fs = opOK;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001904 } else {
1905 semantics = &toSemantics;
1906 fs = opOK;
Dale Johannesen23a98552008-10-09 23:00:39 +00001907 *losesInfo = false;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001908 }
1909
1910 return fs;
1911}
1912
1913/* Convert a floating point number to an integer according to the
1914 rounding mode. If the rounded integer value is out of range this
Neil Boothee7ae382007-11-01 22:43:37 +00001915 returns an invalid operation exception and the contents of the
1916 destination parts are unspecified. If the rounded value is in
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001917 range but the floating point number is not the exact integer, the C
1918 standard doesn't require an inexact exception to be raised. IEEE
1919 854 does require it so we do that.
1920
1921 Note that for conversions to integer type the C standard requires
1922 round-to-zero to always be used. */
1923APFloat::opStatus
Neil Boothee7ae382007-11-01 22:43:37 +00001924APFloat::convertToSignExtendedInteger(integerPart *parts, unsigned int width,
1925 bool isSigned,
Dale Johannesen23a98552008-10-09 23:00:39 +00001926 roundingMode rounding_mode,
1927 bool *isExact) const
Neil Boothee7ae382007-11-01 22:43:37 +00001928{
1929 lostFraction lost_fraction;
1930 const integerPart *src;
1931 unsigned int dstPartsCount, truncatedBits;
1932
Evan Cheng794a7db2008-11-26 01:11:57 +00001933 assertArithmeticOK(*semantics);
Neil Boothe3d936a2007-11-02 15:10:05 +00001934
Dale Johannesen23a98552008-10-09 23:00:39 +00001935 *isExact = false;
1936
Neil Boothee7ae382007-11-01 22:43:37 +00001937 /* Handle the three special cases first. */
1938 if(category == fcInfinity || category == fcNaN)
1939 return opInvalidOp;
1940
1941 dstPartsCount = partCountForBits(width);
1942
1943 if(category == fcZero) {
1944 APInt::tcSet(parts, 0, dstPartsCount);
Dale Johannesene4a42452008-10-07 00:40:01 +00001945 // Negative zero can't be represented as an int.
Dale Johannesen23a98552008-10-09 23:00:39 +00001946 *isExact = !sign;
1947 return opOK;
Neil Boothee7ae382007-11-01 22:43:37 +00001948 }
1949
1950 src = significandParts();
1951
1952 /* Step 1: place our absolute value, with any fraction truncated, in
1953 the destination. */
1954 if (exponent < 0) {
1955 /* Our absolute value is less than one; truncate everything. */
1956 APInt::tcSet(parts, 0, dstPartsCount);
Dale Johannesen1f54f582009-01-19 21:17:05 +00001957 /* For exponent -1 the integer bit represents .5, look at that.
1958 For smaller exponents leftmost truncated bit is 0. */
1959 truncatedBits = semantics->precision -1U - exponent;
Neil Boothee7ae382007-11-01 22:43:37 +00001960 } else {
1961 /* We want the most significant (exponent + 1) bits; the rest are
1962 truncated. */
1963 unsigned int bits = exponent + 1U;
1964
1965 /* Hopelessly large in magnitude? */
1966 if (bits > width)
1967 return opInvalidOp;
1968
1969 if (bits < semantics->precision) {
1970 /* We truncate (semantics->precision - bits) bits. */
1971 truncatedBits = semantics->precision - bits;
1972 APInt::tcExtract(parts, dstPartsCount, src, bits, truncatedBits);
1973 } else {
1974 /* We want at least as many bits as are available. */
1975 APInt::tcExtract(parts, dstPartsCount, src, semantics->precision, 0);
1976 APInt::tcShiftLeft(parts, dstPartsCount, bits - semantics->precision);
1977 truncatedBits = 0;
1978 }
1979 }
1980
1981 /* Step 2: work out any lost fraction, and increment the absolute
1982 value if we would round away from zero. */
1983 if (truncatedBits) {
1984 lost_fraction = lostFractionThroughTruncation(src, partCount(),
1985 truncatedBits);
1986 if (lost_fraction != lfExactlyZero
1987 && roundAwayFromZero(rounding_mode, lost_fraction, truncatedBits)) {
1988 if (APInt::tcIncrement(parts, dstPartsCount))
1989 return opInvalidOp; /* Overflow. */
1990 }
1991 } else {
1992 lost_fraction = lfExactlyZero;
1993 }
1994
1995 /* Step 3: check if we fit in the destination. */
1996 unsigned int omsb = APInt::tcMSB(parts, dstPartsCount) + 1;
1997
1998 if (sign) {
1999 if (!isSigned) {
2000 /* Negative numbers cannot be represented as unsigned. */
2001 if (omsb != 0)
2002 return opInvalidOp;
2003 } else {
2004 /* It takes omsb bits to represent the unsigned integer value.
2005 We lose a bit for the sign, but care is needed as the
2006 maximally negative integer is a special case. */
2007 if (omsb == width && APInt::tcLSB(parts, dstPartsCount) + 1 != omsb)
2008 return opInvalidOp;
2009
2010 /* This case can happen because of rounding. */
2011 if (omsb > width)
2012 return opInvalidOp;
2013 }
2014
2015 APInt::tcNegate (parts, dstPartsCount);
2016 } else {
2017 if (omsb >= width + !isSigned)
2018 return opInvalidOp;
2019 }
2020
Dale Johannesen23a98552008-10-09 23:00:39 +00002021 if (lost_fraction == lfExactlyZero) {
2022 *isExact = true;
Neil Boothee7ae382007-11-01 22:43:37 +00002023 return opOK;
Dale Johannesen23a98552008-10-09 23:00:39 +00002024 } else
Neil Boothee7ae382007-11-01 22:43:37 +00002025 return opInexact;
2026}
2027
2028/* Same as convertToSignExtendedInteger, except we provide
2029 deterministic values in case of an invalid operation exception,
2030 namely zero for NaNs and the minimal or maximal value respectively
Dale Johannesen23a98552008-10-09 23:00:39 +00002031 for underflow or overflow.
2032 The *isExact output tells whether the result is exact, in the sense
2033 that converting it back to the original floating point type produces
2034 the original value. This is almost equivalent to result==opOK,
2035 except for negative zeroes.
2036*/
Neil Boothee7ae382007-11-01 22:43:37 +00002037APFloat::opStatus
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002038APFloat::convertToInteger(integerPart *parts, unsigned int width,
Neil Booth4f881702007-09-26 21:33:42 +00002039 bool isSigned,
Dale Johannesen23a98552008-10-09 23:00:39 +00002040 roundingMode rounding_mode, bool *isExact) const
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002041{
Neil Boothee7ae382007-11-01 22:43:37 +00002042 opStatus fs;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002043
Dale Johannesen23a98552008-10-09 23:00:39 +00002044 fs = convertToSignExtendedInteger(parts, width, isSigned, rounding_mode,
2045 isExact);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002046
Neil Boothee7ae382007-11-01 22:43:37 +00002047 if (fs == opInvalidOp) {
2048 unsigned int bits, dstPartsCount;
2049
2050 dstPartsCount = partCountForBits(width);
2051
2052 if (category == fcNaN)
2053 bits = 0;
2054 else if (sign)
2055 bits = isSigned;
2056 else
2057 bits = width - isSigned;
2058
2059 APInt::tcSetLeastSignificantBits(parts, dstPartsCount, bits);
2060 if (sign && isSigned)
2061 APInt::tcShiftLeft(parts, dstPartsCount, width - 1);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002062 }
2063
Neil Boothee7ae382007-11-01 22:43:37 +00002064 return fs;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002065}
2066
Neil Booth643ce592007-10-07 12:07:53 +00002067/* Convert an unsigned integer SRC to a floating point number,
2068 rounding according to ROUNDING_MODE. The sign of the floating
2069 point number is not modified. */
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002070APFloat::opStatus
Neil Booth643ce592007-10-07 12:07:53 +00002071APFloat::convertFromUnsignedParts(const integerPart *src,
2072 unsigned int srcCount,
2073 roundingMode rounding_mode)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002074{
Neil Booth5477f852007-10-08 14:39:42 +00002075 unsigned int omsb, precision, dstCount;
Neil Booth643ce592007-10-07 12:07:53 +00002076 integerPart *dst;
Neil Booth5477f852007-10-08 14:39:42 +00002077 lostFraction lost_fraction;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002078
Neil Boothcaf19d72007-10-14 10:29:28 +00002079 assertArithmeticOK(*semantics);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002080 category = fcNormal;
Neil Booth5477f852007-10-08 14:39:42 +00002081 omsb = APInt::tcMSB(src, srcCount) + 1;
Neil Booth643ce592007-10-07 12:07:53 +00002082 dst = significandParts();
2083 dstCount = partCount();
Neil Booth5477f852007-10-08 14:39:42 +00002084 precision = semantics->precision;
Neil Booth643ce592007-10-07 12:07:53 +00002085
Neil Booth5477f852007-10-08 14:39:42 +00002086 /* We want the most significant PRECISON bits of SRC. There may not
2087 be that many; extract what we can. */
2088 if (precision <= omsb) {
2089 exponent = omsb - 1;
Neil Booth643ce592007-10-07 12:07:53 +00002090 lost_fraction = lostFractionThroughTruncation(src, srcCount,
Neil Booth5477f852007-10-08 14:39:42 +00002091 omsb - precision);
2092 APInt::tcExtract(dst, dstCount, src, precision, omsb - precision);
2093 } else {
2094 exponent = precision - 1;
2095 lost_fraction = lfExactlyZero;
2096 APInt::tcExtract(dst, dstCount, src, omsb, 0);
Neil Booth643ce592007-10-07 12:07:53 +00002097 }
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002098
2099 return normalize(rounding_mode, lost_fraction);
2100}
2101
Dan Gohman93c276e2008-02-29 01:26:11 +00002102APFloat::opStatus
2103APFloat::convertFromAPInt(const APInt &Val,
2104 bool isSigned,
2105 roundingMode rounding_mode)
2106{
2107 unsigned int partCount = Val.getNumWords();
2108 APInt api = Val;
2109
2110 sign = false;
2111 if (isSigned && api.isNegative()) {
2112 sign = true;
2113 api = -api;
2114 }
2115
2116 return convertFromUnsignedParts(api.getRawData(), partCount, rounding_mode);
2117}
2118
Neil Boothf16c5952007-10-07 12:15:41 +00002119/* Convert a two's complement integer SRC to a floating point number,
2120 rounding according to ROUNDING_MODE. ISSIGNED is true if the
2121 integer is signed, in which case it must be sign-extended. */
2122APFloat::opStatus
2123APFloat::convertFromSignExtendedInteger(const integerPart *src,
2124 unsigned int srcCount,
2125 bool isSigned,
2126 roundingMode rounding_mode)
2127{
2128 opStatus status;
2129
Neil Boothcaf19d72007-10-14 10:29:28 +00002130 assertArithmeticOK(*semantics);
Neil Boothf16c5952007-10-07 12:15:41 +00002131 if (isSigned
2132 && APInt::tcExtractBit(src, srcCount * integerPartWidth - 1)) {
2133 integerPart *copy;
2134
2135 /* If we're signed and negative negate a copy. */
2136 sign = true;
2137 copy = new integerPart[srcCount];
2138 APInt::tcAssign(copy, src, srcCount);
2139 APInt::tcNegate(copy, srcCount);
2140 status = convertFromUnsignedParts(copy, srcCount, rounding_mode);
2141 delete [] copy;
2142 } else {
2143 sign = false;
2144 status = convertFromUnsignedParts(src, srcCount, rounding_mode);
2145 }
2146
2147 return status;
2148}
2149
Neil Boothccf596a2007-10-07 11:45:55 +00002150/* FIXME: should this just take a const APInt reference? */
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002151APFloat::opStatus
Neil Boothccf596a2007-10-07 11:45:55 +00002152APFloat::convertFromZeroExtendedInteger(const integerPart *parts,
2153 unsigned int width, bool isSigned,
2154 roundingMode rounding_mode)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002155{
Dale Johannesen910993e2007-09-21 22:09:37 +00002156 unsigned int partCount = partCountForBits(width);
Dale Johannesen910993e2007-09-21 22:09:37 +00002157 APInt api = APInt(width, partCount, parts);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002158
2159 sign = false;
Dale Johannesencce23a42007-09-30 18:17:01 +00002160 if(isSigned && APInt::tcExtractBit(parts, width - 1)) {
2161 sign = true;
2162 api = -api;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002163 }
2164
Neil Booth7a7bc0f2007-10-07 12:10:57 +00002165 return convertFromUnsignedParts(api.getRawData(), partCount, rounding_mode);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002166}
2167
2168APFloat::opStatus
Erick Tryzelaara15d8902009-08-16 23:36:19 +00002169APFloat::convertFromHexadecimalString(const StringRef &s,
Neil Booth4f881702007-09-26 21:33:42 +00002170 roundingMode rounding_mode)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002171{
Erick Tryzelaarf8bc8012009-08-18 18:20:37 +00002172 lostFraction lost_fraction = lfExactlyZero;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002173 integerPart *significand;
2174 unsigned int bitPos, partsCount;
Erick Tryzelaara15d8902009-08-16 23:36:19 +00002175 StringRef::iterator dot, firstSignificantDigit;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002176
2177 zeroSignificand();
2178 exponent = 0;
2179 category = fcNormal;
2180
2181 significand = significandParts();
2182 partsCount = partCount();
2183 bitPos = partsCount * integerPartWidth;
2184
Neil Booth33d4c922007-10-07 08:51:21 +00002185 /* Skip leading zeroes and any (hexa)decimal point. */
Erick Tryzelaarc78b33b2009-08-20 23:30:43 +00002186 StringRef::iterator begin = s.begin();
2187 StringRef::iterator end = s.end();
2188 StringRef::iterator p = skipLeadingZeroesAndAnyDot(begin, end, &dot);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002189 firstSignificantDigit = p;
2190
Erick Tryzelaarc78b33b2009-08-20 23:30:43 +00002191 for(; p != end;) {
Dale Johannesen386f3e92008-05-14 22:53:25 +00002192 integerPart hex_value;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002193
2194 if(*p == '.') {
Erick Tryzelaarc78b33b2009-08-20 23:30:43 +00002195 assert(dot == end && "String contains multiple dots");
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002196 dot = p++;
Erick Tryzelaarc78b33b2009-08-20 23:30:43 +00002197 if (p == end) {
2198 break;
2199 }
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002200 }
2201
2202 hex_value = hexDigitValue(*p);
2203 if(hex_value == -1U) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002204 break;
2205 }
2206
2207 p++;
2208
Erick Tryzelaarc78b33b2009-08-20 23:30:43 +00002209 if (p == end) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002210 break;
Erick Tryzelaara15d8902009-08-16 23:36:19 +00002211 } else {
2212 /* Store the number whilst 4-bit nibbles remain. */
2213 if(bitPos) {
2214 bitPos -= 4;
2215 hex_value <<= bitPos % integerPartWidth;
2216 significand[bitPos / integerPartWidth] |= hex_value;
2217 } else {
Erick Tryzelaarc78b33b2009-08-20 23:30:43 +00002218 lost_fraction = trailingHexadecimalFraction(p, end, hex_value);
2219 while(p != end && hexDigitValue(*p) != -1U)
Erick Tryzelaara15d8902009-08-16 23:36:19 +00002220 p++;
2221 break;
2222 }
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002223 }
2224 }
2225
2226 /* Hex floats require an exponent but not a hexadecimal point. */
Erick Tryzelaarc78b33b2009-08-20 23:30:43 +00002227 assert(p != end && "Hex strings require an exponent");
2228 assert((*p == 'p' || *p == 'P') && "Invalid character in significand");
2229 assert(p != begin && "Significand has no digits");
2230 assert((dot == end || p - begin != 1) && "Significand has no digits");
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002231
2232 /* Ignore the exponent if we are zero. */
2233 if(p != firstSignificantDigit) {
2234 int expAdjustment;
2235
2236 /* Implicit hexadecimal point? */
Erick Tryzelaarc78b33b2009-08-20 23:30:43 +00002237 if (dot == end)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002238 dot = p;
2239
2240 /* Calculate the exponent adjustment implicit in the number of
2241 significant digits. */
Evan Cheng48e8c802008-05-02 21:15:08 +00002242 expAdjustment = static_cast<int>(dot - firstSignificantDigit);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002243 if(expAdjustment < 0)
2244 expAdjustment++;
2245 expAdjustment = expAdjustment * 4 - 1;
2246
2247 /* Adjust for writing the significand starting at the most
2248 significant nibble. */
2249 expAdjustment += semantics->precision;
2250 expAdjustment -= partsCount * integerPartWidth;
2251
2252 /* Adjust for the given exponent. */
Erick Tryzelaarc78b33b2009-08-20 23:30:43 +00002253 exponent = totalExponent(p + 1, end, expAdjustment);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002254 }
2255
2256 return normalize(rounding_mode, lost_fraction);
2257}
2258
2259APFloat::opStatus
Neil Booth96c74712007-10-12 16:02:31 +00002260APFloat::roundSignificandWithExponent(const integerPart *decSigParts,
2261 unsigned sigPartCount, int exp,
2262 roundingMode rounding_mode)
2263{
2264 unsigned int parts, pow5PartCount;
Neil Boothcaf19d72007-10-14 10:29:28 +00002265 fltSemantics calcSemantics = { 32767, -32767, 0, true };
Neil Booth96c74712007-10-12 16:02:31 +00002266 integerPart pow5Parts[maxPowerOfFiveParts];
2267 bool isNearest;
2268
2269 isNearest = (rounding_mode == rmNearestTiesToEven
2270 || rounding_mode == rmNearestTiesToAway);
2271
2272 parts = partCountForBits(semantics->precision + 11);
2273
2274 /* Calculate pow(5, abs(exp)). */
2275 pow5PartCount = powerOf5(pow5Parts, exp >= 0 ? exp: -exp);
2276
2277 for (;; parts *= 2) {
2278 opStatus sigStatus, powStatus;
2279 unsigned int excessPrecision, truncatedBits;
2280
2281 calcSemantics.precision = parts * integerPartWidth - 1;
2282 excessPrecision = calcSemantics.precision - semantics->precision;
2283 truncatedBits = excessPrecision;
2284
2285 APFloat decSig(calcSemantics, fcZero, sign);
2286 APFloat pow5(calcSemantics, fcZero, false);
2287
2288 sigStatus = decSig.convertFromUnsignedParts(decSigParts, sigPartCount,
2289 rmNearestTiesToEven);
2290 powStatus = pow5.convertFromUnsignedParts(pow5Parts, pow5PartCount,
2291 rmNearestTiesToEven);
2292 /* Add exp, as 10^n = 5^n * 2^n. */
2293 decSig.exponent += exp;
2294
2295 lostFraction calcLostFraction;
Evan Cheng48e8c802008-05-02 21:15:08 +00002296 integerPart HUerr, HUdistance;
2297 unsigned int powHUerr;
Neil Booth96c74712007-10-12 16:02:31 +00002298
2299 if (exp >= 0) {
2300 /* multiplySignificand leaves the precision-th bit set to 1. */
2301 calcLostFraction = decSig.multiplySignificand(pow5, NULL);
2302 powHUerr = powStatus != opOK;
2303 } else {
2304 calcLostFraction = decSig.divideSignificand(pow5);
2305 /* Denormal numbers have less precision. */
2306 if (decSig.exponent < semantics->minExponent) {
2307 excessPrecision += (semantics->minExponent - decSig.exponent);
2308 truncatedBits = excessPrecision;
2309 if (excessPrecision > calcSemantics.precision)
2310 excessPrecision = calcSemantics.precision;
2311 }
2312 /* Extra half-ulp lost in reciprocal of exponent. */
Evan Cheng48e8c802008-05-02 21:15:08 +00002313 powHUerr = (powStatus == opOK && calcLostFraction == lfExactlyZero) ? 0:2;
Neil Booth96c74712007-10-12 16:02:31 +00002314 }
2315
2316 /* Both multiplySignificand and divideSignificand return the
2317 result with the integer bit set. */
Evan Cheng99ebfa52009-10-27 21:35:42 +00002318 assert(APInt::tcExtractBit
2319 (decSig.significandParts(), calcSemantics.precision - 1) == 1);
Neil Booth96c74712007-10-12 16:02:31 +00002320
2321 HUerr = HUerrBound(calcLostFraction != lfExactlyZero, sigStatus != opOK,
2322 powHUerr);
2323 HUdistance = 2 * ulpsFromBoundary(decSig.significandParts(),
2324 excessPrecision, isNearest);
2325
2326 /* Are we guaranteed to round correctly if we truncate? */
2327 if (HUdistance >= HUerr) {
2328 APInt::tcExtract(significandParts(), partCount(), decSig.significandParts(),
2329 calcSemantics.precision - excessPrecision,
2330 excessPrecision);
2331 /* Take the exponent of decSig. If we tcExtract-ed less bits
2332 above we must adjust our exponent to compensate for the
2333 implicit right shift. */
2334 exponent = (decSig.exponent + semantics->precision
2335 - (calcSemantics.precision - excessPrecision));
2336 calcLostFraction = lostFractionThroughTruncation(decSig.significandParts(),
2337 decSig.partCount(),
2338 truncatedBits);
2339 return normalize(rounding_mode, calcLostFraction);
2340 }
2341 }
2342}
2343
2344APFloat::opStatus
Erick Tryzelaara15d8902009-08-16 23:36:19 +00002345APFloat::convertFromDecimalString(const StringRef &str, roundingMode rounding_mode)
Neil Booth96c74712007-10-12 16:02:31 +00002346{
Neil Booth1870f292007-10-14 10:16:12 +00002347 decimalInfo D;
Neil Booth96c74712007-10-12 16:02:31 +00002348 opStatus fs;
2349
Neil Booth1870f292007-10-14 10:16:12 +00002350 /* Scan the text. */
Erick Tryzelaara15d8902009-08-16 23:36:19 +00002351 StringRef::iterator p = str.begin();
2352 interpretDecimal(p, str.end(), &D);
Neil Booth96c74712007-10-12 16:02:31 +00002353
Neil Booth686700e2007-10-15 15:00:55 +00002354 /* Handle the quick cases. First the case of no significant digits,
2355 i.e. zero, and then exponents that are obviously too large or too
2356 small. Writing L for log 10 / log 2, a number d.ddddd*10^exp
2357 definitely overflows if
2358
2359 (exp - 1) * L >= maxExponent
2360
2361 and definitely underflows to zero where
2362
2363 (exp + 1) * L <= minExponent - precision
2364
2365 With integer arithmetic the tightest bounds for L are
2366
2367 93/28 < L < 196/59 [ numerator <= 256 ]
2368 42039/12655 < L < 28738/8651 [ numerator <= 65536 ]
2369 */
2370
Neil Boothcc233592007-12-05 13:06:04 +00002371 if (decDigitValue(*D.firstSigDigit) >= 10U) {
Neil Booth96c74712007-10-12 16:02:31 +00002372 category = fcZero;
2373 fs = opOK;
John McCall8b3f3302010-02-26 22:20:41 +00002374
2375 /* Check whether the normalized exponent is high enough to overflow
2376 max during the log-rebasing in the max-exponent check below. */
2377 } else if (D.normalizedExponent - 1 > INT_MAX / 42039) {
2378 fs = handleOverflow(rounding_mode);
2379
2380 /* If it wasn't, then it also wasn't high enough to overflow max
2381 during the log-rebasing in the min-exponent check. Check that it
2382 won't overflow min in either check, then perform the min-exponent
2383 check. */
2384 } else if (D.normalizedExponent - 1 < INT_MIN / 42039 ||
2385 (D.normalizedExponent + 1) * 28738 <=
2386 8651 * (semantics->minExponent - (int) semantics->precision)) {
Neil Booth686700e2007-10-15 15:00:55 +00002387 /* Underflow to zero and round. */
2388 zeroSignificand();
2389 fs = normalize(rounding_mode, lfLessThanHalf);
John McCall8b3f3302010-02-26 22:20:41 +00002390
2391 /* We can finally safely perform the max-exponent check. */
Neil Booth686700e2007-10-15 15:00:55 +00002392 } else if ((D.normalizedExponent - 1) * 42039
2393 >= 12655 * semantics->maxExponent) {
2394 /* Overflow and round. */
2395 fs = handleOverflow(rounding_mode);
Neil Booth96c74712007-10-12 16:02:31 +00002396 } else {
Neil Booth1870f292007-10-14 10:16:12 +00002397 integerPart *decSignificand;
2398 unsigned int partCount;
Neil Booth96c74712007-10-12 16:02:31 +00002399
Neil Booth1870f292007-10-14 10:16:12 +00002400 /* A tight upper bound on number of bits required to hold an
Neil Booth686700e2007-10-15 15:00:55 +00002401 N-digit decimal integer is N * 196 / 59. Allocate enough space
Neil Booth1870f292007-10-14 10:16:12 +00002402 to hold the full significand, and an extra part required by
2403 tcMultiplyPart. */
Evan Cheng48e8c802008-05-02 21:15:08 +00002404 partCount = static_cast<unsigned int>(D.lastSigDigit - D.firstSigDigit) + 1;
Neil Booth686700e2007-10-15 15:00:55 +00002405 partCount = partCountForBits(1 + 196 * partCount / 59);
Neil Booth1870f292007-10-14 10:16:12 +00002406 decSignificand = new integerPart[partCount + 1];
2407 partCount = 0;
Neil Booth96c74712007-10-12 16:02:31 +00002408
Neil Booth1870f292007-10-14 10:16:12 +00002409 /* Convert to binary efficiently - we do almost all multiplication
2410 in an integerPart. When this would overflow do we do a single
2411 bignum multiplication, and then revert again to multiplication
2412 in an integerPart. */
2413 do {
2414 integerPart decValue, val, multiplier;
2415
2416 val = 0;
2417 multiplier = 1;
2418
2419 do {
Erick Tryzelaara15d8902009-08-16 23:36:19 +00002420 if (*p == '.') {
Neil Booth1870f292007-10-14 10:16:12 +00002421 p++;
Erick Tryzelaara15d8902009-08-16 23:36:19 +00002422 if (p == str.end()) {
2423 break;
2424 }
2425 }
Neil Booth1870f292007-10-14 10:16:12 +00002426 decValue = decDigitValue(*p++);
Erick Tryzelaarc78b33b2009-08-20 23:30:43 +00002427 assert(decValue < 10U && "Invalid character in significand");
Neil Booth1870f292007-10-14 10:16:12 +00002428 multiplier *= 10;
2429 val = val * 10 + decValue;
2430 /* The maximum number that can be multiplied by ten with any
2431 digit added without overflowing an integerPart. */
2432 } while (p <= D.lastSigDigit && multiplier <= (~ (integerPart) 0 - 9) / 10);
2433
2434 /* Multiply out the current part. */
2435 APInt::tcMultiplyPart(decSignificand, decSignificand, multiplier, val,
2436 partCount, partCount + 1, false);
2437
2438 /* If we used another part (likely but not guaranteed), increase
2439 the count. */
2440 if (decSignificand[partCount])
2441 partCount++;
2442 } while (p <= D.lastSigDigit);
Neil Booth96c74712007-10-12 16:02:31 +00002443
Neil Booth43a4b282007-11-01 22:51:07 +00002444 category = fcNormal;
Neil Booth96c74712007-10-12 16:02:31 +00002445 fs = roundSignificandWithExponent(decSignificand, partCount,
Neil Booth1870f292007-10-14 10:16:12 +00002446 D.exponent, rounding_mode);
Neil Booth96c74712007-10-12 16:02:31 +00002447
Neil Booth1870f292007-10-14 10:16:12 +00002448 delete [] decSignificand;
2449 }
Neil Booth96c74712007-10-12 16:02:31 +00002450
2451 return fs;
2452}
2453
2454APFloat::opStatus
Erick Tryzelaara15d8902009-08-16 23:36:19 +00002455APFloat::convertFromString(const StringRef &str, roundingMode rounding_mode)
Neil Booth4f881702007-09-26 21:33:42 +00002456{
Neil Boothcaf19d72007-10-14 10:29:28 +00002457 assertArithmeticOK(*semantics);
Erick Tryzelaara15d8902009-08-16 23:36:19 +00002458 assert(!str.empty() && "Invalid string length");
Neil Boothcaf19d72007-10-14 10:29:28 +00002459
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002460 /* Handle a leading minus sign. */
Erick Tryzelaara15d8902009-08-16 23:36:19 +00002461 StringRef::iterator p = str.begin();
2462 size_t slen = str.size();
Erick Tryzelaarc78b33b2009-08-20 23:30:43 +00002463 sign = *p == '-' ? 1 : 0;
2464 if(*p == '-' || *p == '+') {
Erick Tryzelaara15d8902009-08-16 23:36:19 +00002465 p++;
2466 slen--;
Erick Tryzelaarc78b33b2009-08-20 23:30:43 +00002467 assert(slen && "String has no digits");
Erick Tryzelaara15d8902009-08-16 23:36:19 +00002468 }
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002469
Erick Tryzelaara15d8902009-08-16 23:36:19 +00002470 if(slen >= 2 && p[0] == '0' && (p[1] == 'x' || p[1] == 'X')) {
2471 assert(slen - 2 && "Invalid string");
Erick Tryzelaarc78b33b2009-08-20 23:30:43 +00002472 return convertFromHexadecimalString(StringRef(p + 2, slen - 2),
Erick Tryzelaara15d8902009-08-16 23:36:19 +00002473 rounding_mode);
2474 }
Bill Wendlingb7c0d942008-11-27 08:00:12 +00002475
Erick Tryzelaarc78b33b2009-08-20 23:30:43 +00002476 return convertFromDecimalString(StringRef(p, slen), rounding_mode);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002477}
Dale Johannesen343e7702007-08-24 00:56:33 +00002478
Neil Bootha30b0ee2007-10-03 22:26:02 +00002479/* Write out a hexadecimal representation of the floating point value
2480 to DST, which must be of sufficient size, in the C99 form
2481 [-]0xh.hhhhp[+-]d. Return the number of characters written,
2482 excluding the terminating NUL.
2483
2484 If UPPERCASE, the output is in upper case, otherwise in lower case.
2485
2486 HEXDIGITS digits appear altogether, rounding the value if
2487 necessary. If HEXDIGITS is 0, the minimal precision to display the
2488 number precisely is used instead. If nothing would appear after
2489 the decimal point it is suppressed.
2490
2491 The decimal exponent is always printed and has at least one digit.
2492 Zero values display an exponent of zero. Infinities and NaNs
2493 appear as "infinity" or "nan" respectively.
2494
2495 The above rules are as specified by C99. There is ambiguity about
2496 what the leading hexadecimal digit should be. This implementation
2497 uses whatever is necessary so that the exponent is displayed as
2498 stored. This implies the exponent will fall within the IEEE format
2499 range, and the leading hexadecimal digit will be 0 (for denormals),
2500 1 (normal numbers) or 2 (normal numbers rounded-away-from-zero with
2501 any other digits zero).
2502*/
2503unsigned int
2504APFloat::convertToHexString(char *dst, unsigned int hexDigits,
2505 bool upperCase, roundingMode rounding_mode) const
2506{
2507 char *p;
2508
Neil Boothcaf19d72007-10-14 10:29:28 +00002509 assertArithmeticOK(*semantics);
2510
Neil Bootha30b0ee2007-10-03 22:26:02 +00002511 p = dst;
2512 if (sign)
2513 *dst++ = '-';
2514
2515 switch (category) {
2516 case fcInfinity:
2517 memcpy (dst, upperCase ? infinityU: infinityL, sizeof infinityU - 1);
2518 dst += sizeof infinityL - 1;
2519 break;
2520
2521 case fcNaN:
2522 memcpy (dst, upperCase ? NaNU: NaNL, sizeof NaNU - 1);
2523 dst += sizeof NaNU - 1;
2524 break;
2525
2526 case fcZero:
2527 *dst++ = '0';
2528 *dst++ = upperCase ? 'X': 'x';
2529 *dst++ = '0';
2530 if (hexDigits > 1) {
2531 *dst++ = '.';
2532 memset (dst, '0', hexDigits - 1);
2533 dst += hexDigits - 1;
2534 }
2535 *dst++ = upperCase ? 'P': 'p';
2536 *dst++ = '0';
2537 break;
2538
2539 case fcNormal:
2540 dst = convertNormalToHexString (dst, hexDigits, upperCase, rounding_mode);
2541 break;
2542 }
2543
2544 *dst = 0;
2545
Evan Cheng48e8c802008-05-02 21:15:08 +00002546 return static_cast<unsigned int>(dst - p);
Neil Bootha30b0ee2007-10-03 22:26:02 +00002547}
2548
2549/* Does the hard work of outputting the correctly rounded hexadecimal
2550 form of a normal floating point number with the specified number of
2551 hexadecimal digits. If HEXDIGITS is zero the minimum number of
2552 digits necessary to print the value precisely is output. */
2553char *
2554APFloat::convertNormalToHexString(char *dst, unsigned int hexDigits,
2555 bool upperCase,
2556 roundingMode rounding_mode) const
2557{
2558 unsigned int count, valueBits, shift, partsCount, outputDigits;
2559 const char *hexDigitChars;
2560 const integerPart *significand;
2561 char *p;
2562 bool roundUp;
2563
2564 *dst++ = '0';
2565 *dst++ = upperCase ? 'X': 'x';
2566
2567 roundUp = false;
2568 hexDigitChars = upperCase ? hexDigitsUpper: hexDigitsLower;
2569
2570 significand = significandParts();
2571 partsCount = partCount();
2572
2573 /* +3 because the first digit only uses the single integer bit, so
2574 we have 3 virtual zero most-significant-bits. */
2575 valueBits = semantics->precision + 3;
2576 shift = integerPartWidth - valueBits % integerPartWidth;
2577
2578 /* The natural number of digits required ignoring trailing
2579 insignificant zeroes. */
2580 outputDigits = (valueBits - significandLSB () + 3) / 4;
2581
2582 /* hexDigits of zero means use the required number for the
2583 precision. Otherwise, see if we are truncating. If we are,
Neil Booth978661d2007-10-06 00:24:48 +00002584 find out if we need to round away from zero. */
Neil Bootha30b0ee2007-10-03 22:26:02 +00002585 if (hexDigits) {
2586 if (hexDigits < outputDigits) {
2587 /* We are dropping non-zero bits, so need to check how to round.
2588 "bits" is the number of dropped bits. */
2589 unsigned int bits;
2590 lostFraction fraction;
2591
2592 bits = valueBits - hexDigits * 4;
2593 fraction = lostFractionThroughTruncation (significand, partsCount, bits);
2594 roundUp = roundAwayFromZero(rounding_mode, fraction, bits);
2595 }
2596 outputDigits = hexDigits;
2597 }
2598
2599 /* Write the digits consecutively, and start writing in the location
2600 of the hexadecimal point. We move the most significant digit
2601 left and add the hexadecimal point later. */
2602 p = ++dst;
2603
2604 count = (valueBits + integerPartWidth - 1) / integerPartWidth;
2605
2606 while (outputDigits && count) {
2607 integerPart part;
2608
2609 /* Put the most significant integerPartWidth bits in "part". */
2610 if (--count == partsCount)
2611 part = 0; /* An imaginary higher zero part. */
2612 else
2613 part = significand[count] << shift;
2614
2615 if (count && shift)
2616 part |= significand[count - 1] >> (integerPartWidth - shift);
2617
2618 /* Convert as much of "part" to hexdigits as we can. */
2619 unsigned int curDigits = integerPartWidth / 4;
2620
2621 if (curDigits > outputDigits)
2622 curDigits = outputDigits;
2623 dst += partAsHex (dst, part, curDigits, hexDigitChars);
2624 outputDigits -= curDigits;
2625 }
2626
2627 if (roundUp) {
2628 char *q = dst;
2629
2630 /* Note that hexDigitChars has a trailing '0'. */
2631 do {
2632 q--;
2633 *q = hexDigitChars[hexDigitValue (*q) + 1];
Neil Booth978661d2007-10-06 00:24:48 +00002634 } while (*q == '0');
Evan Cheng99ebfa52009-10-27 21:35:42 +00002635 assert(q >= p);
Neil Bootha30b0ee2007-10-03 22:26:02 +00002636 } else {
2637 /* Add trailing zeroes. */
2638 memset (dst, '0', outputDigits);
2639 dst += outputDigits;
2640 }
2641
2642 /* Move the most significant digit to before the point, and if there
2643 is something after the decimal point add it. This must come
2644 after rounding above. */
2645 p[-1] = p[0];
2646 if (dst -1 == p)
2647 dst--;
2648 else
2649 p[0] = '.';
2650
2651 /* Finally output the exponent. */
2652 *dst++ = upperCase ? 'P': 'p';
2653
Neil Booth92f7e8d2007-10-06 07:29:25 +00002654 return writeSignedDecimal (dst, exponent);
Neil Bootha30b0ee2007-10-03 22:26:02 +00002655}
2656
Dale Johannesen343e7702007-08-24 00:56:33 +00002657// For good performance it is desirable for different APFloats
2658// to produce different integers.
2659uint32_t
Neil Booth4f881702007-09-26 21:33:42 +00002660APFloat::getHashValue() const
2661{
Dale Johannesen343e7702007-08-24 00:56:33 +00002662 if (category==fcZero) return sign<<8 | semantics->precision ;
2663 else if (category==fcInfinity) return sign<<9 | semantics->precision;
Dale Johanneseneaf08942007-08-31 04:03:46 +00002664 else if (category==fcNaN) return 1<<10 | semantics->precision;
Dale Johannesen343e7702007-08-24 00:56:33 +00002665 else {
2666 uint32_t hash = sign<<11 | semantics->precision | exponent<<12;
2667 const integerPart* p = significandParts();
2668 for (int i=partCount(); i>0; i--, p++)
Evan Cheng48e8c802008-05-02 21:15:08 +00002669 hash ^= ((uint32_t)*p) ^ (uint32_t)((*p)>>32);
Dale Johannesen343e7702007-08-24 00:56:33 +00002670 return hash;
2671 }
2672}
2673
2674// Conversion from APFloat to/from host float/double. It may eventually be
2675// possible to eliminate these and have everybody deal with APFloats, but that
2676// will take a while. This approach will not easily extend to long double.
Dale Johannesena72a5a02007-09-20 23:47:58 +00002677// Current implementation requires integerPartWidth==64, which is correct at
2678// the moment but could be made more general.
Dale Johannesen343e7702007-08-24 00:56:33 +00002679
Dale Johannesen58c2e4c2007-09-05 20:39:49 +00002680// Denormals have exponent minExponent in APFloat, but minExponent-1 in
Dale Johannesena72a5a02007-09-20 23:47:58 +00002681// the actual IEEE respresentations. We compensate for that here.
Dale Johannesen58c2e4c2007-09-05 20:39:49 +00002682
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002683APInt
Neil Booth4f881702007-09-26 21:33:42 +00002684APFloat::convertF80LongDoubleAPFloatToAPInt() const
2685{
Dan Gohmanb10abe12008-01-29 12:08:20 +00002686 assert(semantics == (const llvm::fltSemantics*)&x87DoubleExtended);
Evan Cheng99ebfa52009-10-27 21:35:42 +00002687 assert(partCount()==2);
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002688
2689 uint64_t myexponent, mysignificand;
2690
2691 if (category==fcNormal) {
2692 myexponent = exponent+16383; //bias
Dale Johannesena72a5a02007-09-20 23:47:58 +00002693 mysignificand = significandParts()[0];
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002694 if (myexponent==1 && !(mysignificand & 0x8000000000000000ULL))
2695 myexponent = 0; // denormal
2696 } else if (category==fcZero) {
2697 myexponent = 0;
2698 mysignificand = 0;
2699 } else if (category==fcInfinity) {
2700 myexponent = 0x7fff;
2701 mysignificand = 0x8000000000000000ULL;
Chris Lattnera11ef822007-10-06 06:13:42 +00002702 } else {
2703 assert(category == fcNaN && "Unknown category");
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002704 myexponent = 0x7fff;
Dale Johannesena72a5a02007-09-20 23:47:58 +00002705 mysignificand = significandParts()[0];
Chris Lattnera11ef822007-10-06 06:13:42 +00002706 }
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002707
2708 uint64_t words[2];
Dale Johannesen1b25cb22009-03-23 21:16:53 +00002709 words[0] = mysignificand;
2710 words[1] = ((uint64_t)(sign & 1) << 15) |
2711 (myexponent & 0x7fffLL);
Chris Lattnera11ef822007-10-06 06:13:42 +00002712 return APInt(80, 2, words);
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002713}
2714
2715APInt
Dale Johannesena471c2e2007-10-11 18:07:22 +00002716APFloat::convertPPCDoubleDoubleAPFloatToAPInt() const
2717{
Dan Gohmanb10abe12008-01-29 12:08:20 +00002718 assert(semantics == (const llvm::fltSemantics*)&PPCDoubleDouble);
Evan Cheng99ebfa52009-10-27 21:35:42 +00002719 assert(partCount()==2);
Dale Johannesena471c2e2007-10-11 18:07:22 +00002720
2721 uint64_t myexponent, mysignificand, myexponent2, mysignificand2;
2722
2723 if (category==fcNormal) {
2724 myexponent = exponent + 1023; //bias
2725 myexponent2 = exponent2 + 1023;
2726 mysignificand = significandParts()[0];
2727 mysignificand2 = significandParts()[1];
2728 if (myexponent==1 && !(mysignificand & 0x10000000000000LL))
2729 myexponent = 0; // denormal
2730 if (myexponent2==1 && !(mysignificand2 & 0x10000000000000LL))
2731 myexponent2 = 0; // denormal
2732 } else if (category==fcZero) {
2733 myexponent = 0;
2734 mysignificand = 0;
2735 myexponent2 = 0;
2736 mysignificand2 = 0;
2737 } else if (category==fcInfinity) {
2738 myexponent = 0x7ff;
2739 myexponent2 = 0;
2740 mysignificand = 0;
2741 mysignificand2 = 0;
2742 } else {
2743 assert(category == fcNaN && "Unknown category");
2744 myexponent = 0x7ff;
2745 mysignificand = significandParts()[0];
2746 myexponent2 = exponent2;
2747 mysignificand2 = significandParts()[1];
2748 }
2749
2750 uint64_t words[2];
Evan Cheng48e8c802008-05-02 21:15:08 +00002751 words[0] = ((uint64_t)(sign & 1) << 63) |
Dale Johannesena471c2e2007-10-11 18:07:22 +00002752 ((myexponent & 0x7ff) << 52) |
2753 (mysignificand & 0xfffffffffffffLL);
Evan Cheng48e8c802008-05-02 21:15:08 +00002754 words[1] = ((uint64_t)(sign2 & 1) << 63) |
Dale Johannesena471c2e2007-10-11 18:07:22 +00002755 ((myexponent2 & 0x7ff) << 52) |
2756 (mysignificand2 & 0xfffffffffffffLL);
2757 return APInt(128, 2, words);
2758}
2759
2760APInt
Anton Korobeynikov7e844f12009-08-21 22:10:30 +00002761APFloat::convertQuadrupleAPFloatToAPInt() const
2762{
2763 assert(semantics == (const llvm::fltSemantics*)&IEEEquad);
Evan Cheng99ebfa52009-10-27 21:35:42 +00002764 assert(partCount()==2);
Anton Korobeynikov7e844f12009-08-21 22:10:30 +00002765
2766 uint64_t myexponent, mysignificand, mysignificand2;
2767
2768 if (category==fcNormal) {
2769 myexponent = exponent+16383; //bias
2770 mysignificand = significandParts()[0];
2771 mysignificand2 = significandParts()[1];
2772 if (myexponent==1 && !(mysignificand2 & 0x1000000000000LL))
2773 myexponent = 0; // denormal
2774 } else if (category==fcZero) {
2775 myexponent = 0;
2776 mysignificand = mysignificand2 = 0;
2777 } else if (category==fcInfinity) {
2778 myexponent = 0x7fff;
2779 mysignificand = mysignificand2 = 0;
2780 } else {
2781 assert(category == fcNaN && "Unknown category!");
2782 myexponent = 0x7fff;
2783 mysignificand = significandParts()[0];
2784 mysignificand2 = significandParts()[1];
2785 }
2786
2787 uint64_t words[2];
2788 words[0] = mysignificand;
2789 words[1] = ((uint64_t)(sign & 1) << 63) |
2790 ((myexponent & 0x7fff) << 48) |
Anton Korobeynikov4755e992009-08-21 23:09:47 +00002791 (mysignificand2 & 0xffffffffffffLL);
Anton Korobeynikov7e844f12009-08-21 22:10:30 +00002792
2793 return APInt(128, 2, words);
2794}
2795
2796APInt
Neil Booth4f881702007-09-26 21:33:42 +00002797APFloat::convertDoubleAPFloatToAPInt() const
2798{
Dan Gohmancb648f92007-09-14 20:08:19 +00002799 assert(semantics == (const llvm::fltSemantics*)&IEEEdouble);
Evan Cheng99ebfa52009-10-27 21:35:42 +00002800 assert(partCount()==1);
Dale Johannesen343e7702007-08-24 00:56:33 +00002801
Dale Johanneseneaf08942007-08-31 04:03:46 +00002802 uint64_t myexponent, mysignificand;
Dale Johannesen343e7702007-08-24 00:56:33 +00002803
2804 if (category==fcNormal) {
Dale Johannesen343e7702007-08-24 00:56:33 +00002805 myexponent = exponent+1023; //bias
Dale Johannesen58c2e4c2007-09-05 20:39:49 +00002806 mysignificand = *significandParts();
2807 if (myexponent==1 && !(mysignificand & 0x10000000000000LL))
2808 myexponent = 0; // denormal
Dale Johannesen343e7702007-08-24 00:56:33 +00002809 } else if (category==fcZero) {
Dale Johannesen343e7702007-08-24 00:56:33 +00002810 myexponent = 0;
2811 mysignificand = 0;
2812 } else if (category==fcInfinity) {
Dale Johannesen343e7702007-08-24 00:56:33 +00002813 myexponent = 0x7ff;
2814 mysignificand = 0;
Chris Lattnera11ef822007-10-06 06:13:42 +00002815 } else {
2816 assert(category == fcNaN && "Unknown category!");
Dale Johannesen343e7702007-08-24 00:56:33 +00002817 myexponent = 0x7ff;
Dale Johanneseneaf08942007-08-31 04:03:46 +00002818 mysignificand = *significandParts();
Chris Lattnera11ef822007-10-06 06:13:42 +00002819 }
Dale Johannesen343e7702007-08-24 00:56:33 +00002820
Evan Cheng48e8c802008-05-02 21:15:08 +00002821 return APInt(64, ((((uint64_t)(sign & 1) << 63) |
Chris Lattnera11ef822007-10-06 06:13:42 +00002822 ((myexponent & 0x7ff) << 52) |
2823 (mysignificand & 0xfffffffffffffLL))));
Dale Johannesen343e7702007-08-24 00:56:33 +00002824}
2825
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002826APInt
Neil Booth4f881702007-09-26 21:33:42 +00002827APFloat::convertFloatAPFloatToAPInt() const
2828{
Dan Gohmancb648f92007-09-14 20:08:19 +00002829 assert(semantics == (const llvm::fltSemantics*)&IEEEsingle);
Evan Cheng99ebfa52009-10-27 21:35:42 +00002830 assert(partCount()==1);
Neil Booth4f881702007-09-26 21:33:42 +00002831
Dale Johanneseneaf08942007-08-31 04:03:46 +00002832 uint32_t myexponent, mysignificand;
Dale Johannesen343e7702007-08-24 00:56:33 +00002833
2834 if (category==fcNormal) {
Dale Johannesen343e7702007-08-24 00:56:33 +00002835 myexponent = exponent+127; //bias
Evan Cheng48e8c802008-05-02 21:15:08 +00002836 mysignificand = (uint32_t)*significandParts();
Dale Johannesend0763b92007-11-17 01:02:27 +00002837 if (myexponent == 1 && !(mysignificand & 0x800000))
Dale Johannesen58c2e4c2007-09-05 20:39:49 +00002838 myexponent = 0; // denormal
Dale Johannesen343e7702007-08-24 00:56:33 +00002839 } else if (category==fcZero) {
Dale Johannesen343e7702007-08-24 00:56:33 +00002840 myexponent = 0;
2841 mysignificand = 0;
2842 } else if (category==fcInfinity) {
Dale Johannesen343e7702007-08-24 00:56:33 +00002843 myexponent = 0xff;
2844 mysignificand = 0;
Chris Lattnera11ef822007-10-06 06:13:42 +00002845 } else {
2846 assert(category == fcNaN && "Unknown category!");
Dale Johannesen58c2e4c2007-09-05 20:39:49 +00002847 myexponent = 0xff;
Evan Cheng48e8c802008-05-02 21:15:08 +00002848 mysignificand = (uint32_t)*significandParts();
Chris Lattnera11ef822007-10-06 06:13:42 +00002849 }
Dale Johannesen343e7702007-08-24 00:56:33 +00002850
Chris Lattnera11ef822007-10-06 06:13:42 +00002851 return APInt(32, (((sign&1) << 31) | ((myexponent&0xff) << 23) |
2852 (mysignificand & 0x7fffff)));
Dale Johannesen343e7702007-08-24 00:56:33 +00002853}
2854
Chris Lattnercc4287a2009-10-16 02:13:51 +00002855APInt
2856APFloat::convertHalfAPFloatToAPInt() const
2857{
2858 assert(semantics == (const llvm::fltSemantics*)&IEEEhalf);
Evan Cheng99ebfa52009-10-27 21:35:42 +00002859 assert(partCount()==1);
Chris Lattnercc4287a2009-10-16 02:13:51 +00002860
2861 uint32_t myexponent, mysignificand;
2862
2863 if (category==fcNormal) {
2864 myexponent = exponent+15; //bias
2865 mysignificand = (uint32_t)*significandParts();
2866 if (myexponent == 1 && !(mysignificand & 0x400))
2867 myexponent = 0; // denormal
2868 } else if (category==fcZero) {
2869 myexponent = 0;
2870 mysignificand = 0;
2871 } else if (category==fcInfinity) {
Dale Johannesena223aed2009-10-23 04:02:51 +00002872 myexponent = 0x1f;
Chris Lattnercc4287a2009-10-16 02:13:51 +00002873 mysignificand = 0;
2874 } else {
2875 assert(category == fcNaN && "Unknown category!");
Dale Johannesena223aed2009-10-23 04:02:51 +00002876 myexponent = 0x1f;
Chris Lattnercc4287a2009-10-16 02:13:51 +00002877 mysignificand = (uint32_t)*significandParts();
2878 }
2879
2880 return APInt(16, (((sign&1) << 15) | ((myexponent&0x1f) << 10) |
2881 (mysignificand & 0x3ff)));
2882}
2883
Dale Johannesena471c2e2007-10-11 18:07:22 +00002884// This function creates an APInt that is just a bit map of the floating
2885// point constant as it would appear in memory. It is not a conversion,
2886// and treating the result as a normal integer is unlikely to be useful.
2887
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002888APInt
Dale Johannesen7111b022008-10-09 18:53:47 +00002889APFloat::bitcastToAPInt() const
Neil Booth4f881702007-09-26 21:33:42 +00002890{
Chris Lattnercc4287a2009-10-16 02:13:51 +00002891 if (semantics == (const llvm::fltSemantics*)&IEEEhalf)
2892 return convertHalfAPFloatToAPInt();
2893
Dan Gohmanb10abe12008-01-29 12:08:20 +00002894 if (semantics == (const llvm::fltSemantics*)&IEEEsingle)
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002895 return convertFloatAPFloatToAPInt();
Anton Korobeynikov7e844f12009-08-21 22:10:30 +00002896
Dan Gohmanb10abe12008-01-29 12:08:20 +00002897 if (semantics == (const llvm::fltSemantics*)&IEEEdouble)
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002898 return convertDoubleAPFloatToAPInt();
Neil Booth4f881702007-09-26 21:33:42 +00002899
Anton Korobeynikov7e844f12009-08-21 22:10:30 +00002900 if (semantics == (const llvm::fltSemantics*)&IEEEquad)
2901 return convertQuadrupleAPFloatToAPInt();
2902
Dan Gohmanb10abe12008-01-29 12:08:20 +00002903 if (semantics == (const llvm::fltSemantics*)&PPCDoubleDouble)
Dale Johannesena471c2e2007-10-11 18:07:22 +00002904 return convertPPCDoubleDoubleAPFloatToAPInt();
2905
Dan Gohmanb10abe12008-01-29 12:08:20 +00002906 assert(semantics == (const llvm::fltSemantics*)&x87DoubleExtended &&
Chris Lattnera11ef822007-10-06 06:13:42 +00002907 "unknown format!");
2908 return convertF80LongDoubleAPFloatToAPInt();
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002909}
2910
Neil Booth4f881702007-09-26 21:33:42 +00002911float
2912APFloat::convertToFloat() const
2913{
Chris Lattnerad785002009-09-24 21:44:20 +00002914 assert(semantics == (const llvm::fltSemantics*)&IEEEsingle &&
2915 "Float semantics are not IEEEsingle");
Dale Johannesen7111b022008-10-09 18:53:47 +00002916 APInt api = bitcastToAPInt();
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002917 return api.bitsToFloat();
2918}
2919
Neil Booth4f881702007-09-26 21:33:42 +00002920double
2921APFloat::convertToDouble() const
2922{
Chris Lattnerad785002009-09-24 21:44:20 +00002923 assert(semantics == (const llvm::fltSemantics*)&IEEEdouble &&
2924 "Float semantics are not IEEEdouble");
Dale Johannesen7111b022008-10-09 18:53:47 +00002925 APInt api = bitcastToAPInt();
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002926 return api.bitsToDouble();
2927}
2928
Dale Johannesend3d8ce32008-10-06 18:22:29 +00002929/// Integer bit is explicit in this format. Intel hardware (387 and later)
2930/// does not support these bit patterns:
2931/// exponent = all 1's, integer bit 0, significand 0 ("pseudoinfinity")
2932/// exponent = all 1's, integer bit 0, significand nonzero ("pseudoNaN")
2933/// exponent = 0, integer bit 1 ("pseudodenormal")
2934/// exponent!=0 nor all 1's, integer bit 0 ("unnormal")
2935/// At the moment, the first two are treated as NaNs, the second two as Normal.
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002936void
Neil Booth4f881702007-09-26 21:33:42 +00002937APFloat::initFromF80LongDoubleAPInt(const APInt &api)
2938{
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002939 assert(api.getBitWidth()==80);
2940 uint64_t i1 = api.getRawData()[0];
2941 uint64_t i2 = api.getRawData()[1];
Dale Johannesen1b25cb22009-03-23 21:16:53 +00002942 uint64_t myexponent = (i2 & 0x7fff);
2943 uint64_t mysignificand = i1;
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002944
2945 initialize(&APFloat::x87DoubleExtended);
Dale Johannesena72a5a02007-09-20 23:47:58 +00002946 assert(partCount()==2);
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002947
Dale Johannesen1b25cb22009-03-23 21:16:53 +00002948 sign = static_cast<unsigned int>(i2>>15);
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002949 if (myexponent==0 && mysignificand==0) {
2950 // exponent, significand meaningless
2951 category = fcZero;
2952 } else if (myexponent==0x7fff && mysignificand==0x8000000000000000ULL) {
2953 // exponent, significand meaningless
2954 category = fcInfinity;
2955 } else if (myexponent==0x7fff && mysignificand!=0x8000000000000000ULL) {
2956 // exponent meaningless
2957 category = fcNaN;
Dale Johannesena72a5a02007-09-20 23:47:58 +00002958 significandParts()[0] = mysignificand;
2959 significandParts()[1] = 0;
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002960 } else {
2961 category = fcNormal;
2962 exponent = myexponent - 16383;
Dale Johannesena72a5a02007-09-20 23:47:58 +00002963 significandParts()[0] = mysignificand;
2964 significandParts()[1] = 0;
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002965 if (myexponent==0) // denormal
2966 exponent = -16382;
Neil Booth4f881702007-09-26 21:33:42 +00002967 }
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002968}
2969
2970void
Dale Johannesena471c2e2007-10-11 18:07:22 +00002971APFloat::initFromPPCDoubleDoubleAPInt(const APInt &api)
2972{
2973 assert(api.getBitWidth()==128);
2974 uint64_t i1 = api.getRawData()[0];
2975 uint64_t i2 = api.getRawData()[1];
2976 uint64_t myexponent = (i1 >> 52) & 0x7ff;
2977 uint64_t mysignificand = i1 & 0xfffffffffffffLL;
2978 uint64_t myexponent2 = (i2 >> 52) & 0x7ff;
2979 uint64_t mysignificand2 = i2 & 0xfffffffffffffLL;
2980
2981 initialize(&APFloat::PPCDoubleDouble);
2982 assert(partCount()==2);
2983
Evan Cheng48e8c802008-05-02 21:15:08 +00002984 sign = static_cast<unsigned int>(i1>>63);
2985 sign2 = static_cast<unsigned int>(i2>>63);
Dale Johannesena471c2e2007-10-11 18:07:22 +00002986 if (myexponent==0 && mysignificand==0) {
2987 // exponent, significand meaningless
2988 // exponent2 and significand2 are required to be 0; we don't check
2989 category = fcZero;
2990 } else if (myexponent==0x7ff && mysignificand==0) {
2991 // exponent, significand meaningless
2992 // exponent2 and significand2 are required to be 0; we don't check
2993 category = fcInfinity;
2994 } else if (myexponent==0x7ff && mysignificand!=0) {
2995 // exponent meaningless. So is the whole second word, but keep it
2996 // for determinism.
2997 category = fcNaN;
2998 exponent2 = myexponent2;
2999 significandParts()[0] = mysignificand;
3000 significandParts()[1] = mysignificand2;
3001 } else {
3002 category = fcNormal;
3003 // Note there is no category2; the second word is treated as if it is
3004 // fcNormal, although it might be something else considered by itself.
3005 exponent = myexponent - 1023;
3006 exponent2 = myexponent2 - 1023;
3007 significandParts()[0] = mysignificand;
3008 significandParts()[1] = mysignificand2;
3009 if (myexponent==0) // denormal
3010 exponent = -1022;
3011 else
3012 significandParts()[0] |= 0x10000000000000LL; // integer bit
3013 if (myexponent2==0)
3014 exponent2 = -1022;
3015 else
3016 significandParts()[1] |= 0x10000000000000LL; // integer bit
3017 }
3018}
3019
3020void
Anton Korobeynikov7e844f12009-08-21 22:10:30 +00003021APFloat::initFromQuadrupleAPInt(const APInt &api)
3022{
3023 assert(api.getBitWidth()==128);
3024 uint64_t i1 = api.getRawData()[0];
3025 uint64_t i2 = api.getRawData()[1];
3026 uint64_t myexponent = (i2 >> 48) & 0x7fff;
3027 uint64_t mysignificand = i1;
3028 uint64_t mysignificand2 = i2 & 0xffffffffffffLL;
3029
3030 initialize(&APFloat::IEEEquad);
3031 assert(partCount()==2);
3032
3033 sign = static_cast<unsigned int>(i2>>63);
3034 if (myexponent==0 &&
3035 (mysignificand==0 && mysignificand2==0)) {
3036 // exponent, significand meaningless
3037 category = fcZero;
3038 } else if (myexponent==0x7fff &&
3039 (mysignificand==0 && mysignificand2==0)) {
3040 // exponent, significand meaningless
3041 category = fcInfinity;
3042 } else if (myexponent==0x7fff &&
3043 (mysignificand!=0 || mysignificand2 !=0)) {
3044 // exponent meaningless
3045 category = fcNaN;
3046 significandParts()[0] = mysignificand;
3047 significandParts()[1] = mysignificand2;
3048 } else {
3049 category = fcNormal;
3050 exponent = myexponent - 16383;
3051 significandParts()[0] = mysignificand;
3052 significandParts()[1] = mysignificand2;
3053 if (myexponent==0) // denormal
3054 exponent = -16382;
3055 else
3056 significandParts()[1] |= 0x1000000000000LL; // integer bit
3057 }
3058}
3059
3060void
Neil Booth4f881702007-09-26 21:33:42 +00003061APFloat::initFromDoubleAPInt(const APInt &api)
3062{
Dale Johannesen3f6eb742007-09-11 18:32:33 +00003063 assert(api.getBitWidth()==64);
3064 uint64_t i = *api.getRawData();
Dale Johannesend3b51fd2007-08-24 05:08:11 +00003065 uint64_t myexponent = (i >> 52) & 0x7ff;
3066 uint64_t mysignificand = i & 0xfffffffffffffLL;
3067
Dale Johannesen343e7702007-08-24 00:56:33 +00003068 initialize(&APFloat::IEEEdouble);
Dale Johannesen343e7702007-08-24 00:56:33 +00003069 assert(partCount()==1);
3070
Evan Cheng48e8c802008-05-02 21:15:08 +00003071 sign = static_cast<unsigned int>(i>>63);
Dale Johannesen343e7702007-08-24 00:56:33 +00003072 if (myexponent==0 && mysignificand==0) {
3073 // exponent, significand meaningless
3074 category = fcZero;
Dale Johannesen343e7702007-08-24 00:56:33 +00003075 } else if (myexponent==0x7ff && mysignificand==0) {
3076 // exponent, significand meaningless
3077 category = fcInfinity;
Dale Johanneseneaf08942007-08-31 04:03:46 +00003078 } else if (myexponent==0x7ff && mysignificand!=0) {
3079 // exponent meaningless
3080 category = fcNaN;
3081 *significandParts() = mysignificand;
Dale Johannesen343e7702007-08-24 00:56:33 +00003082 } else {
Dale Johannesen343e7702007-08-24 00:56:33 +00003083 category = fcNormal;
3084 exponent = myexponent - 1023;
Dale Johannesen58c2e4c2007-09-05 20:39:49 +00003085 *significandParts() = mysignificand;
3086 if (myexponent==0) // denormal
3087 exponent = -1022;
3088 else
3089 *significandParts() |= 0x10000000000000LL; // integer bit
Neil Booth4f881702007-09-26 21:33:42 +00003090 }
Dale Johannesen343e7702007-08-24 00:56:33 +00003091}
3092
Dale Johannesen3f6eb742007-09-11 18:32:33 +00003093void
Neil Booth4f881702007-09-26 21:33:42 +00003094APFloat::initFromFloatAPInt(const APInt & api)
3095{
Dale Johannesen3f6eb742007-09-11 18:32:33 +00003096 assert(api.getBitWidth()==32);
3097 uint32_t i = (uint32_t)*api.getRawData();
Dale Johannesend3b51fd2007-08-24 05:08:11 +00003098 uint32_t myexponent = (i >> 23) & 0xff;
3099 uint32_t mysignificand = i & 0x7fffff;
3100
Dale Johannesen343e7702007-08-24 00:56:33 +00003101 initialize(&APFloat::IEEEsingle);
Dale Johannesen343e7702007-08-24 00:56:33 +00003102 assert(partCount()==1);
3103
Dale Johanneseneaf08942007-08-31 04:03:46 +00003104 sign = i >> 31;
Dale Johannesen343e7702007-08-24 00:56:33 +00003105 if (myexponent==0 && mysignificand==0) {
3106 // exponent, significand meaningless
3107 category = fcZero;
Dale Johannesen343e7702007-08-24 00:56:33 +00003108 } else if (myexponent==0xff && mysignificand==0) {
3109 // exponent, significand meaningless
3110 category = fcInfinity;
Dale Johannesen902ff942007-09-25 17:25:00 +00003111 } else if (myexponent==0xff && mysignificand!=0) {
Dale Johannesen343e7702007-08-24 00:56:33 +00003112 // sign, exponent, significand meaningless
Dale Johanneseneaf08942007-08-31 04:03:46 +00003113 category = fcNaN;
3114 *significandParts() = mysignificand;
Dale Johannesen343e7702007-08-24 00:56:33 +00003115 } else {
3116 category = fcNormal;
Dale Johannesen343e7702007-08-24 00:56:33 +00003117 exponent = myexponent - 127; //bias
Dale Johannesen58c2e4c2007-09-05 20:39:49 +00003118 *significandParts() = mysignificand;
3119 if (myexponent==0) // denormal
3120 exponent = -126;
3121 else
3122 *significandParts() |= 0x800000; // integer bit
Dale Johannesen343e7702007-08-24 00:56:33 +00003123 }
3124}
Dale Johannesen3f6eb742007-09-11 18:32:33 +00003125
Chris Lattnercc4287a2009-10-16 02:13:51 +00003126void
3127APFloat::initFromHalfAPInt(const APInt & api)
3128{
3129 assert(api.getBitWidth()==16);
3130 uint32_t i = (uint32_t)*api.getRawData();
Dale Johannesena223aed2009-10-23 04:02:51 +00003131 uint32_t myexponent = (i >> 10) & 0x1f;
Chris Lattnercc4287a2009-10-16 02:13:51 +00003132 uint32_t mysignificand = i & 0x3ff;
3133
3134 initialize(&APFloat::IEEEhalf);
3135 assert(partCount()==1);
3136
3137 sign = i >> 15;
3138 if (myexponent==0 && mysignificand==0) {
3139 // exponent, significand meaningless
3140 category = fcZero;
3141 } else if (myexponent==0x1f && mysignificand==0) {
3142 // exponent, significand meaningless
3143 category = fcInfinity;
3144 } else if (myexponent==0x1f && mysignificand!=0) {
3145 // sign, exponent, significand meaningless
3146 category = fcNaN;
3147 *significandParts() = mysignificand;
3148 } else {
3149 category = fcNormal;
3150 exponent = myexponent - 15; //bias
3151 *significandParts() = mysignificand;
3152 if (myexponent==0) // denormal
3153 exponent = -14;
3154 else
3155 *significandParts() |= 0x400; // integer bit
3156 }
3157}
3158
Dale Johannesen3f6eb742007-09-11 18:32:33 +00003159/// Treat api as containing the bits of a floating point number. Currently
Dale Johannesena471c2e2007-10-11 18:07:22 +00003160/// we infer the floating point type from the size of the APInt. The
3161/// isIEEE argument distinguishes between PPC128 and IEEE128 (not meaningful
3162/// when the size is anything else).
Dale Johannesen3f6eb742007-09-11 18:32:33 +00003163void
Dale Johannesena471c2e2007-10-11 18:07:22 +00003164APFloat::initFromAPInt(const APInt& api, bool isIEEE)
Neil Booth4f881702007-09-26 21:33:42 +00003165{
Chris Lattnercc4287a2009-10-16 02:13:51 +00003166 if (api.getBitWidth() == 16)
3167 return initFromHalfAPInt(api);
3168 else if (api.getBitWidth() == 32)
Dale Johannesen3f6eb742007-09-11 18:32:33 +00003169 return initFromFloatAPInt(api);
3170 else if (api.getBitWidth()==64)
3171 return initFromDoubleAPInt(api);
3172 else if (api.getBitWidth()==80)
3173 return initFromF80LongDoubleAPInt(api);
Anton Korobeynikov7e844f12009-08-21 22:10:30 +00003174 else if (api.getBitWidth()==128)
3175 return (isIEEE ?
3176 initFromQuadrupleAPInt(api) : initFromPPCDoubleDoubleAPInt(api));
Dale Johannesen3f6eb742007-09-11 18:32:33 +00003177 else
Torok Edwinc23197a2009-07-14 16:55:14 +00003178 llvm_unreachable(0);
Dale Johannesen3f6eb742007-09-11 18:32:33 +00003179}
3180
John McCall00e65de2009-12-24 08:56:26 +00003181APFloat APFloat::getLargest(const fltSemantics &Sem, bool Negative) {
3182 APFloat Val(Sem, fcNormal, Negative);
3183
3184 // We want (in interchange format):
3185 // sign = {Negative}
3186 // exponent = 1..10
3187 // significand = 1..1
3188
3189 Val.exponent = Sem.maxExponent; // unbiased
3190
3191 // 1-initialize all bits....
3192 Val.zeroSignificand();
3193 integerPart *significand = Val.significandParts();
3194 unsigned N = partCountForBits(Sem.precision);
3195 for (unsigned i = 0; i != N; ++i)
3196 significand[i] = ~((integerPart) 0);
3197
3198 // ...and then clear the top bits for internal consistency.
3199 significand[N-1]
3200 &= (((integerPart) 1) << ((Sem.precision % integerPartWidth) - 1)) - 1;
3201
3202 return Val;
3203}
3204
3205APFloat APFloat::getSmallest(const fltSemantics &Sem, bool Negative) {
3206 APFloat Val(Sem, fcNormal, Negative);
3207
3208 // We want (in interchange format):
3209 // sign = {Negative}
3210 // exponent = 0..0
3211 // significand = 0..01
3212
3213 Val.exponent = Sem.minExponent; // unbiased
3214 Val.zeroSignificand();
3215 Val.significandParts()[0] = 1;
3216 return Val;
3217}
3218
3219APFloat APFloat::getSmallestNormalized(const fltSemantics &Sem, bool Negative) {
3220 APFloat Val(Sem, fcNormal, Negative);
3221
3222 // We want (in interchange format):
3223 // sign = {Negative}
3224 // exponent = 0..0
3225 // significand = 10..0
3226
3227 Val.exponent = Sem.minExponent;
3228 Val.zeroSignificand();
3229 Val.significandParts()[partCountForBits(Sem.precision)-1]
3230 |= (((integerPart) 1) << ((Sem.precision % integerPartWidth) - 1));
3231
3232 return Val;
3233}
3234
Dale Johannesena471c2e2007-10-11 18:07:22 +00003235APFloat::APFloat(const APInt& api, bool isIEEE)
Neil Booth4f881702007-09-26 21:33:42 +00003236{
Dale Johannesena471c2e2007-10-11 18:07:22 +00003237 initFromAPInt(api, isIEEE);
Dale Johannesen3f6eb742007-09-11 18:32:33 +00003238}
3239
Neil Booth4f881702007-09-26 21:33:42 +00003240APFloat::APFloat(float f)
3241{
Dale Johannesen3f6eb742007-09-11 18:32:33 +00003242 APInt api = APInt(32, 0);
3243 initFromAPInt(api.floatToBits(f));
3244}
3245
Neil Booth4f881702007-09-26 21:33:42 +00003246APFloat::APFloat(double d)
3247{
Dale Johannesen3f6eb742007-09-11 18:32:33 +00003248 APInt api = APInt(64, 0);
3249 initFromAPInt(api.doubleToBits(d));
3250}
John McCall00e65de2009-12-24 08:56:26 +00003251
3252namespace {
3253 static void append(SmallVectorImpl<char> &Buffer,
3254 unsigned N, const char *Str) {
3255 unsigned Start = Buffer.size();
3256 Buffer.set_size(Start + N);
3257 memcpy(&Buffer[Start], Str, N);
3258 }
3259
3260 template <unsigned N>
3261 void append(SmallVectorImpl<char> &Buffer, const char (&Str)[N]) {
3262 append(Buffer, N, Str);
3263 }
3264
John McCall003a09c2009-12-24 12:16:56 +00003265 /// Removes data from the given significand until it is no more
3266 /// precise than is required for the desired precision.
3267 void AdjustToPrecision(APInt &significand,
3268 int &exp, unsigned FormatPrecision) {
3269 unsigned bits = significand.getActiveBits();
3270
3271 // 196/59 is a very slight overestimate of lg_2(10).
3272 unsigned bitsRequired = (FormatPrecision * 196 + 58) / 59;
3273
3274 if (bits <= bitsRequired) return;
3275
3276 unsigned tensRemovable = (bits - bitsRequired) * 59 / 196;
3277 if (!tensRemovable) return;
3278
3279 exp += tensRemovable;
3280
3281 APInt divisor(significand.getBitWidth(), 1);
3282 APInt powten(significand.getBitWidth(), 10);
3283 while (true) {
3284 if (tensRemovable & 1)
3285 divisor *= powten;
3286 tensRemovable >>= 1;
3287 if (!tensRemovable) break;
3288 powten *= powten;
3289 }
3290
3291 significand = significand.udiv(divisor);
3292
3293 // Truncate the significand down to its active bit count, but
3294 // don't try to drop below 32.
John McCall6a09aff2009-12-24 23:18:09 +00003295 unsigned newPrecision = std::max(32U, significand.getActiveBits());
John McCall003a09c2009-12-24 12:16:56 +00003296 significand.trunc(newPrecision);
3297 }
3298
3299
John McCall00e65de2009-12-24 08:56:26 +00003300 void AdjustToPrecision(SmallVectorImpl<char> &buffer,
3301 int &exp, unsigned FormatPrecision) {
3302 unsigned N = buffer.size();
3303 if (N <= FormatPrecision) return;
3304
3305 // The most significant figures are the last ones in the buffer.
3306 unsigned FirstSignificant = N - FormatPrecision;
3307
3308 // Round.
3309 // FIXME: this probably shouldn't use 'round half up'.
3310
3311 // Rounding down is just a truncation, except we also want to drop
3312 // trailing zeros from the new result.
3313 if (buffer[FirstSignificant - 1] < '5') {
3314 while (buffer[FirstSignificant] == '0')
3315 FirstSignificant++;
3316
3317 exp += FirstSignificant;
3318 buffer.erase(&buffer[0], &buffer[FirstSignificant]);
3319 return;
3320 }
3321
3322 // Rounding up requires a decimal add-with-carry. If we continue
3323 // the carry, the newly-introduced zeros will just be truncated.
3324 for (unsigned I = FirstSignificant; I != N; ++I) {
3325 if (buffer[I] == '9') {
3326 FirstSignificant++;
3327 } else {
3328 buffer[I]++;
3329 break;
3330 }
3331 }
3332
3333 // If we carried through, we have exactly one digit of precision.
3334 if (FirstSignificant == N) {
3335 exp += FirstSignificant;
3336 buffer.clear();
3337 buffer.push_back('1');
3338 return;
3339 }
3340
3341 exp += FirstSignificant;
3342 buffer.erase(&buffer[0], &buffer[FirstSignificant]);
3343 }
3344}
3345
3346void APFloat::toString(SmallVectorImpl<char> &Str,
3347 unsigned FormatPrecision,
3348 unsigned FormatMaxPadding) {
3349 switch (category) {
3350 case fcInfinity:
3351 if (isNegative())
3352 return append(Str, "-Inf");
3353 else
3354 return append(Str, "+Inf");
3355
3356 case fcNaN: return append(Str, "NaN");
3357
3358 case fcZero:
3359 if (isNegative())
3360 Str.push_back('-');
3361
3362 if (!FormatMaxPadding)
3363 append(Str, "0.0E+0");
3364 else
3365 Str.push_back('0');
3366 return;
3367
3368 case fcNormal:
3369 break;
3370 }
3371
3372 if (isNegative())
3373 Str.push_back('-');
3374
3375 // Decompose the number into an APInt and an exponent.
3376 int exp = exponent - ((int) semantics->precision - 1);
3377 APInt significand(semantics->precision,
3378 partCountForBits(semantics->precision),
3379 significandParts());
3380
John McCall6a09aff2009-12-24 23:18:09 +00003381 // Set FormatPrecision if zero. We want to do this before we
3382 // truncate trailing zeros, as those are part of the precision.
3383 if (!FormatPrecision) {
3384 // It's an interesting question whether to use the nominal
3385 // precision or the active precision here for denormals.
3386
3387 // FormatPrecision = ceil(significandBits / lg_2(10))
3388 FormatPrecision = (semantics->precision * 59 + 195) / 196;
3389 }
3390
John McCall00e65de2009-12-24 08:56:26 +00003391 // Ignore trailing binary zeros.
3392 int trailingZeros = significand.countTrailingZeros();
3393 exp += trailingZeros;
3394 significand = significand.lshr(trailingZeros);
3395
3396 // Change the exponent from 2^e to 10^e.
3397 if (exp == 0) {
3398 // Nothing to do.
3399 } else if (exp > 0) {
3400 // Just shift left.
3401 significand.zext(semantics->precision + exp);
3402 significand <<= exp;
3403 exp = 0;
3404 } else { /* exp < 0 */
3405 int texp = -exp;
3406
3407 // We transform this using the identity:
3408 // (N)(2^-e) == (N)(5^e)(10^-e)
3409 // This means we have to multiply N (the significand) by 5^e.
3410 // To avoid overflow, we have to operate on numbers large
3411 // enough to store N * 5^e:
3412 // log2(N * 5^e) == log2(N) + e * log2(5)
John McCall6a09aff2009-12-24 23:18:09 +00003413 // <= semantics->precision + e * 137 / 59
3414 // (log_2(5) ~ 2.321928 < 2.322034 ~ 137/59)
3415
3416 unsigned precision = semantics->precision + 137 * texp / 59;
John McCall00e65de2009-12-24 08:56:26 +00003417
3418 // Multiply significand by 5^e.
3419 // N * 5^0101 == N * 5^(1*1) * 5^(0*2) * 5^(1*4) * 5^(0*8)
3420 significand.zext(precision);
3421 APInt five_to_the_i(precision, 5);
3422 while (true) {
3423 if (texp & 1) significand *= five_to_the_i;
3424
3425 texp >>= 1;
3426 if (!texp) break;
3427 five_to_the_i *= five_to_the_i;
3428 }
3429 }
3430
John McCall003a09c2009-12-24 12:16:56 +00003431 AdjustToPrecision(significand, exp, FormatPrecision);
3432
John McCall00e65de2009-12-24 08:56:26 +00003433 llvm::SmallVector<char, 256> buffer;
3434
3435 // Fill the buffer.
3436 unsigned precision = significand.getBitWidth();
3437 APInt ten(precision, 10);
3438 APInt digit(precision, 0);
3439
3440 bool inTrail = true;
3441 while (significand != 0) {
3442 // digit <- significand % 10
3443 // significand <- significand / 10
3444 APInt::udivrem(significand, ten, significand, digit);
3445
3446 unsigned d = digit.getZExtValue();
3447
3448 // Drop trailing zeros.
3449 if (inTrail && !d) exp++;
3450 else {
3451 buffer.push_back((char) ('0' + d));
3452 inTrail = false;
3453 }
3454 }
3455
3456 assert(!buffer.empty() && "no characters in buffer!");
3457
3458 // Drop down to FormatPrecision.
3459 // TODO: don't do more precise calculations above than are required.
3460 AdjustToPrecision(buffer, exp, FormatPrecision);
3461
3462 unsigned NDigits = buffer.size();
3463
John McCall6a09aff2009-12-24 23:18:09 +00003464 // Check whether we should use scientific notation.
John McCall00e65de2009-12-24 08:56:26 +00003465 bool FormatScientific;
3466 if (!FormatMaxPadding)
3467 FormatScientific = true;
3468 else {
John McCall00e65de2009-12-24 08:56:26 +00003469 if (exp >= 0) {
John McCall6a09aff2009-12-24 23:18:09 +00003470 // 765e3 --> 765000
3471 // ^^^
3472 // But we shouldn't make the number look more precise than it is.
3473 FormatScientific = ((unsigned) exp > FormatMaxPadding ||
3474 NDigits + (unsigned) exp > FormatPrecision);
John McCall00e65de2009-12-24 08:56:26 +00003475 } else {
John McCall6a09aff2009-12-24 23:18:09 +00003476 // Power of the most significant digit.
3477 int MSD = exp + (int) (NDigits - 1);
3478 if (MSD >= 0) {
John McCall00e65de2009-12-24 08:56:26 +00003479 // 765e-2 == 7.65
John McCall6a09aff2009-12-24 23:18:09 +00003480 FormatScientific = false;
John McCall00e65de2009-12-24 08:56:26 +00003481 } else {
3482 // 765e-5 == 0.00765
3483 // ^ ^^
John McCall6a09aff2009-12-24 23:18:09 +00003484 FormatScientific = ((unsigned) -MSD) > FormatMaxPadding;
John McCall00e65de2009-12-24 08:56:26 +00003485 }
3486 }
John McCall00e65de2009-12-24 08:56:26 +00003487 }
3488
3489 // Scientific formatting is pretty straightforward.
3490 if (FormatScientific) {
3491 exp += (NDigits - 1);
3492
3493 Str.push_back(buffer[NDigits-1]);
3494 Str.push_back('.');
3495 if (NDigits == 1)
3496 Str.push_back('0');
3497 else
3498 for (unsigned I = 1; I != NDigits; ++I)
3499 Str.push_back(buffer[NDigits-1-I]);
3500 Str.push_back('E');
3501
3502 Str.push_back(exp >= 0 ? '+' : '-');
3503 if (exp < 0) exp = -exp;
3504 SmallVector<char, 6> expbuf;
3505 do {
3506 expbuf.push_back((char) ('0' + (exp % 10)));
3507 exp /= 10;
3508 } while (exp);
3509 for (unsigned I = 0, E = expbuf.size(); I != E; ++I)
3510 Str.push_back(expbuf[E-1-I]);
3511 return;
3512 }
3513
3514 // Non-scientific, positive exponents.
3515 if (exp >= 0) {
3516 for (unsigned I = 0; I != NDigits; ++I)
3517 Str.push_back(buffer[NDigits-1-I]);
3518 for (unsigned I = 0; I != (unsigned) exp; ++I)
3519 Str.push_back('0');
3520 return;
3521 }
3522
3523 // Non-scientific, negative exponents.
3524
3525 // The number of digits to the left of the decimal point.
3526 int NWholeDigits = exp + (int) NDigits;
3527
3528 unsigned I = 0;
3529 if (NWholeDigits > 0) {
3530 for (; I != (unsigned) NWholeDigits; ++I)
3531 Str.push_back(buffer[NDigits-I-1]);
3532 Str.push_back('.');
3533 } else {
3534 unsigned NZeros = 1 + (unsigned) -NWholeDigits;
3535
3536 Str.push_back('0');
3537 Str.push_back('.');
3538 for (unsigned Z = 1; Z != NZeros; ++Z)
3539 Str.push_back('0');
3540 }
3541
3542 for (; I != NDigits; ++I)
3543 Str.push_back(buffer[NDigits-I-1]);
3544}