blob: 619f061862c481b0bc754e5711e141e30e833ea0 [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
John McCall165e96b2010-02-28 12:49:50 +0000634 integerPart *significand = significandParts();
635 unsigned numParts = partCount();
636
John McCalle12b7382010-02-28 02:51:25 +0000637 // Set the significand bits to the fill.
John McCall165e96b2010-02-28 12:49:50 +0000638 if (!fill || fill->getNumWords() < numParts)
639 APInt::tcSet(significand, 0, numParts);
640 if (fill) {
John McCalld44c6cc2010-03-01 18:38:45 +0000641 APInt::tcAssign(significand, fill->getRawData(),
642 std::min(fill->getNumWords(), numParts));
John McCall165e96b2010-02-28 12:49:50 +0000643
644 // Zero out the excess bits of the significand.
645 unsigned bitsToPreserve = semantics->precision - 1;
646 unsigned part = bitsToPreserve / 64;
647 bitsToPreserve %= 64;
648 significand[part] &= ((1ULL << bitsToPreserve) - 1);
649 for (part++; part != numParts; ++part)
650 significand[part] = 0;
651 }
652
653 unsigned QNaNBit = semantics->precision - 2;
John McCalle12b7382010-02-28 02:51:25 +0000654
655 if (SNaN) {
656 // We always have to clear the QNaN bit to make it an SNaN.
John McCall165e96b2010-02-28 12:49:50 +0000657 APInt::tcClearBit(significand, QNaNBit);
John McCalle12b7382010-02-28 02:51:25 +0000658
659 // If there are no bits set in the payload, we have to set
660 // *something* to make it a NaN instead of an infinity;
661 // conventionally, this is the next bit down from the QNaN bit.
John McCall165e96b2010-02-28 12:49:50 +0000662 if (APInt::tcIsZero(significand, numParts))
663 APInt::tcSetBit(significand, QNaNBit - 1);
John McCalle12b7382010-02-28 02:51:25 +0000664 } else {
665 // We always have to set the QNaN bit to make it a QNaN.
John McCall165e96b2010-02-28 12:49:50 +0000666 APInt::tcSetBit(significand, QNaNBit);
John McCalle12b7382010-02-28 02:51:25 +0000667 }
John McCall165e96b2010-02-28 12:49:50 +0000668
669 // For x87 extended precision, we want to make a NaN, not a
670 // pseudo-NaN. Maybe we should expose the ability to make
671 // pseudo-NaNs?
672 if (semantics == &APFloat::x87DoubleExtended)
673 APInt::tcSetBit(significand, QNaNBit + 1);
John McCalle12b7382010-02-28 02:51:25 +0000674}
675
676APFloat APFloat::makeNaN(const fltSemantics &Sem, bool SNaN, bool Negative,
677 const APInt *fill) {
678 APFloat value(Sem, uninitialized);
679 value.makeNaN(SNaN, Negative, fill);
680 return value;
Neil Boothe5e01942007-10-14 10:39:51 +0000681}
682
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000683APFloat &
684APFloat::operator=(const APFloat &rhs)
685{
686 if(this != &rhs) {
687 if(semantics != rhs.semantics) {
688 freeSignificand();
689 initialize(rhs.semantics);
690 }
691 assign(rhs);
692 }
693
694 return *this;
695}
696
Dale Johannesen343e7702007-08-24 00:56:33 +0000697bool
Dale Johannesen12595d72007-08-24 22:09:56 +0000698APFloat::bitwiseIsEqual(const APFloat &rhs) const {
Dale Johannesen343e7702007-08-24 00:56:33 +0000699 if (this == &rhs)
700 return true;
701 if (semantics != rhs.semantics ||
Dale Johanneseneaf08942007-08-31 04:03:46 +0000702 category != rhs.category ||
703 sign != rhs.sign)
Dale Johannesen343e7702007-08-24 00:56:33 +0000704 return false;
Dan Gohmanb10abe12008-01-29 12:08:20 +0000705 if (semantics==(const llvm::fltSemantics*)&PPCDoubleDouble &&
Dale Johannesena471c2e2007-10-11 18:07:22 +0000706 sign2 != rhs.sign2)
707 return false;
Dale Johanneseneaf08942007-08-31 04:03:46 +0000708 if (category==fcZero || category==fcInfinity)
Dale Johannesen343e7702007-08-24 00:56:33 +0000709 return true;
Dale Johanneseneaf08942007-08-31 04:03:46 +0000710 else if (category==fcNormal && exponent!=rhs.exponent)
711 return false;
Dan Gohmanb10abe12008-01-29 12:08:20 +0000712 else if (semantics==(const llvm::fltSemantics*)&PPCDoubleDouble &&
Dale Johannesena471c2e2007-10-11 18:07:22 +0000713 exponent2!=rhs.exponent2)
714 return false;
Dale Johannesen343e7702007-08-24 00:56:33 +0000715 else {
Dale Johannesen343e7702007-08-24 00:56:33 +0000716 int i= partCount();
717 const integerPart* p=significandParts();
718 const integerPart* q=rhs.significandParts();
719 for (; i>0; i--, p++, q++) {
720 if (*p != *q)
721 return false;
722 }
723 return true;
724 }
725}
726
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000727APFloat::APFloat(const fltSemantics &ourSemantics, integerPart value)
728{
Neil Boothcaf19d72007-10-14 10:29:28 +0000729 assertArithmeticOK(ourSemantics);
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000730 initialize(&ourSemantics);
731 sign = 0;
732 zeroSignificand();
733 exponent = ourSemantics.precision - 1;
734 significandParts()[0] = value;
735 normalize(rmNearestTiesToEven, lfExactlyZero);
736}
737
Chris Lattnerd7bd78e2009-09-17 01:08:43 +0000738APFloat::APFloat(const fltSemantics &ourSemantics) {
739 assertArithmeticOK(ourSemantics);
740 initialize(&ourSemantics);
741 category = fcZero;
742 sign = false;
743}
744
John McCalle12b7382010-02-28 02:51:25 +0000745APFloat::APFloat(const fltSemantics &ourSemantics, uninitializedTag tag) {
746 assertArithmeticOK(ourSemantics);
747 // Allocates storage if necessary but does not initialize it.
748 initialize(&ourSemantics);
749}
Chris Lattnerd7bd78e2009-09-17 01:08:43 +0000750
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000751APFloat::APFloat(const fltSemantics &ourSemantics,
John McCalle12b7382010-02-28 02:51:25 +0000752 fltCategory ourCategory, bool negative)
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000753{
Neil Boothcaf19d72007-10-14 10:29:28 +0000754 assertArithmeticOK(ourSemantics);
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000755 initialize(&ourSemantics);
756 category = ourCategory;
757 sign = negative;
Mike Stumpc5ca7132009-05-30 03:49:43 +0000758 if (category == fcNormal)
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000759 category = fcZero;
Neil Boothe5e01942007-10-14 10:39:51 +0000760 else if (ourCategory == fcNaN)
John McCalle12b7382010-02-28 02:51:25 +0000761 makeNaN();
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000762}
763
Erick Tryzelaara15d8902009-08-16 23:36:19 +0000764APFloat::APFloat(const fltSemantics &ourSemantics, const StringRef& text)
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000765{
Neil Boothcaf19d72007-10-14 10:29:28 +0000766 assertArithmeticOK(ourSemantics);
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000767 initialize(&ourSemantics);
768 convertFromString(text, rmNearestTiesToEven);
769}
770
771APFloat::APFloat(const APFloat &rhs)
772{
773 initialize(rhs.semantics);
774 assign(rhs);
775}
776
777APFloat::~APFloat()
778{
779 freeSignificand();
780}
781
Ted Kremenek1f801fa2008-02-11 17:24:50 +0000782// Profile - This method 'profiles' an APFloat for use with FoldingSet.
783void APFloat::Profile(FoldingSetNodeID& ID) const {
Dale Johannesen7111b022008-10-09 18:53:47 +0000784 ID.Add(bitcastToAPInt());
Ted Kremenek1f801fa2008-02-11 17:24:50 +0000785}
786
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000787unsigned int
788APFloat::partCount() const
789{
Dale Johannesena72a5a02007-09-20 23:47:58 +0000790 return partCountForBits(semantics->precision + 1);
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000791}
792
793unsigned int
794APFloat::semanticsPrecision(const fltSemantics &semantics)
795{
796 return semantics.precision;
797}
798
799const integerPart *
800APFloat::significandParts() const
801{
802 return const_cast<APFloat *>(this)->significandParts();
803}
804
805integerPart *
806APFloat::significandParts()
807{
Dale Johanneseneaf08942007-08-31 04:03:46 +0000808 assert(category == fcNormal || category == fcNaN);
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000809
Evan Cheng99ebfa52009-10-27 21:35:42 +0000810 if (partCount() > 1)
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000811 return significand.parts;
812 else
813 return &significand.part;
814}
815
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000816void
817APFloat::zeroSignificand()
818{
819 category = fcNormal;
820 APInt::tcSet(significandParts(), 0, partCount());
821}
822
823/* Increment an fcNormal floating point number's significand. */
824void
825APFloat::incrementSignificand()
826{
827 integerPart carry;
828
829 carry = APInt::tcIncrement(significandParts(), partCount());
830
831 /* Our callers should never cause us to overflow. */
832 assert(carry == 0);
833}
834
835/* Add the significand of the RHS. Returns the carry flag. */
836integerPart
837APFloat::addSignificand(const APFloat &rhs)
838{
839 integerPart *parts;
840
841 parts = significandParts();
842
843 assert(semantics == rhs.semantics);
844 assert(exponent == rhs.exponent);
845
846 return APInt::tcAdd(parts, rhs.significandParts(), 0, partCount());
847}
848
849/* Subtract the significand of the RHS with a borrow flag. Returns
850 the borrow flag. */
851integerPart
852APFloat::subtractSignificand(const APFloat &rhs, integerPart borrow)
853{
854 integerPart *parts;
855
856 parts = significandParts();
857
858 assert(semantics == rhs.semantics);
859 assert(exponent == rhs.exponent);
860
861 return APInt::tcSubtract(parts, rhs.significandParts(), borrow,
Neil Booth4f881702007-09-26 21:33:42 +0000862 partCount());
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000863}
864
865/* Multiply the significand of the RHS. If ADDEND is non-NULL, add it
866 on to the full-precision result of the multiplication. Returns the
867 lost fraction. */
868lostFraction
869APFloat::multiplySignificand(const APFloat &rhs, const APFloat *addend)
870{
Neil Booth4f881702007-09-26 21:33:42 +0000871 unsigned int omsb; // One, not zero, based MSB.
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000872 unsigned int partsCount, newPartsCount, precision;
873 integerPart *lhsSignificand;
874 integerPart scratch[4];
875 integerPart *fullSignificand;
876 lostFraction lost_fraction;
Dale Johannesen23a98552008-10-09 23:00:39 +0000877 bool ignored;
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000878
879 assert(semantics == rhs.semantics);
880
881 precision = semantics->precision;
882 newPartsCount = partCountForBits(precision * 2);
883
884 if(newPartsCount > 4)
885 fullSignificand = new integerPart[newPartsCount];
886 else
887 fullSignificand = scratch;
888
889 lhsSignificand = significandParts();
890 partsCount = partCount();
891
892 APInt::tcFullMultiply(fullSignificand, lhsSignificand,
Neil Booth978661d2007-10-06 00:24:48 +0000893 rhs.significandParts(), partsCount, partsCount);
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000894
895 lost_fraction = lfExactlyZero;
896 omsb = APInt::tcMSB(fullSignificand, newPartsCount) + 1;
897 exponent += rhs.exponent;
898
899 if(addend) {
900 Significand savedSignificand = significand;
901 const fltSemantics *savedSemantics = semantics;
902 fltSemantics extendedSemantics;
903 opStatus status;
904 unsigned int extendedPrecision;
905
906 /* Normalize our MSB. */
907 extendedPrecision = precision + precision - 1;
908 if(omsb != extendedPrecision)
909 {
Neil Booth4f881702007-09-26 21:33:42 +0000910 APInt::tcShiftLeft(fullSignificand, newPartsCount,
911 extendedPrecision - omsb);
912 exponent -= extendedPrecision - omsb;
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000913 }
914
915 /* Create new semantics. */
916 extendedSemantics = *semantics;
917 extendedSemantics.precision = extendedPrecision;
918
919 if(newPartsCount == 1)
920 significand.part = fullSignificand[0];
921 else
922 significand.parts = fullSignificand;
923 semantics = &extendedSemantics;
924
925 APFloat extendedAddend(*addend);
Dale Johannesen23a98552008-10-09 23:00:39 +0000926 status = extendedAddend.convert(extendedSemantics, rmTowardZero, &ignored);
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000927 assert(status == opOK);
928 lost_fraction = addOrSubtractSignificand(extendedAddend, false);
929
930 /* Restore our state. */
931 if(newPartsCount == 1)
932 fullSignificand[0] = significand.part;
933 significand = savedSignificand;
934 semantics = savedSemantics;
935
936 omsb = APInt::tcMSB(fullSignificand, newPartsCount) + 1;
937 }
938
939 exponent -= (precision - 1);
940
941 if(omsb > precision) {
942 unsigned int bits, significantParts;
943 lostFraction lf;
944
945 bits = omsb - precision;
946 significantParts = partCountForBits(omsb);
947 lf = shiftRight(fullSignificand, significantParts, bits);
948 lost_fraction = combineLostFractions(lf, lost_fraction);
949 exponent += bits;
950 }
951
952 APInt::tcAssign(lhsSignificand, fullSignificand, partsCount);
953
954 if(newPartsCount > 4)
955 delete [] fullSignificand;
956
957 return lost_fraction;
958}
959
960/* Multiply the significands of LHS and RHS to DST. */
961lostFraction
962APFloat::divideSignificand(const APFloat &rhs)
963{
964 unsigned int bit, i, partsCount;
965 const integerPart *rhsSignificand;
966 integerPart *lhsSignificand, *dividend, *divisor;
967 integerPart scratch[4];
968 lostFraction lost_fraction;
969
970 assert(semantics == rhs.semantics);
971
972 lhsSignificand = significandParts();
973 rhsSignificand = rhs.significandParts();
974 partsCount = partCount();
975
976 if(partsCount > 2)
977 dividend = new integerPart[partsCount * 2];
978 else
979 dividend = scratch;
980
981 divisor = dividend + partsCount;
982
983 /* Copy the dividend and divisor as they will be modified in-place. */
984 for(i = 0; i < partsCount; i++) {
985 dividend[i] = lhsSignificand[i];
986 divisor[i] = rhsSignificand[i];
987 lhsSignificand[i] = 0;
988 }
989
990 exponent -= rhs.exponent;
991
992 unsigned int precision = semantics->precision;
993
994 /* Normalize the divisor. */
995 bit = precision - APInt::tcMSB(divisor, partsCount) - 1;
996 if(bit) {
997 exponent += bit;
998 APInt::tcShiftLeft(divisor, partsCount, bit);
999 }
1000
1001 /* Normalize the dividend. */
1002 bit = precision - APInt::tcMSB(dividend, partsCount) - 1;
1003 if(bit) {
1004 exponent -= bit;
1005 APInt::tcShiftLeft(dividend, partsCount, bit);
1006 }
1007
Neil Booth96c74712007-10-12 16:02:31 +00001008 /* Ensure the dividend >= divisor initially for the loop below.
1009 Incidentally, this means that the division loop below is
1010 guaranteed to set the integer bit to one. */
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001011 if(APInt::tcCompare(dividend, divisor, partsCount) < 0) {
1012 exponent--;
1013 APInt::tcShiftLeft(dividend, partsCount, 1);
1014 assert(APInt::tcCompare(dividend, divisor, partsCount) >= 0);
1015 }
1016
1017 /* Long division. */
1018 for(bit = precision; bit; bit -= 1) {
1019 if(APInt::tcCompare(dividend, divisor, partsCount) >= 0) {
1020 APInt::tcSubtract(dividend, divisor, 0, partsCount);
1021 APInt::tcSetBit(lhsSignificand, bit - 1);
1022 }
1023
1024 APInt::tcShiftLeft(dividend, partsCount, 1);
1025 }
1026
1027 /* Figure out the lost fraction. */
1028 int cmp = APInt::tcCompare(dividend, divisor, partsCount);
1029
1030 if(cmp > 0)
1031 lost_fraction = lfMoreThanHalf;
1032 else if(cmp == 0)
1033 lost_fraction = lfExactlyHalf;
1034 else if(APInt::tcIsZero(dividend, partsCount))
1035 lost_fraction = lfExactlyZero;
1036 else
1037 lost_fraction = lfLessThanHalf;
1038
1039 if(partsCount > 2)
1040 delete [] dividend;
1041
1042 return lost_fraction;
1043}
1044
1045unsigned int
1046APFloat::significandMSB() const
1047{
1048 return APInt::tcMSB(significandParts(), partCount());
1049}
1050
1051unsigned int
1052APFloat::significandLSB() const
1053{
1054 return APInt::tcLSB(significandParts(), partCount());
1055}
1056
1057/* Note that a zero result is NOT normalized to fcZero. */
1058lostFraction
1059APFloat::shiftSignificandRight(unsigned int bits)
1060{
1061 /* Our exponent should not overflow. */
1062 assert((exponent_t) (exponent + bits) >= exponent);
1063
1064 exponent += bits;
1065
1066 return shiftRight(significandParts(), partCount(), bits);
1067}
1068
1069/* Shift the significand left BITS bits, subtract BITS from its exponent. */
1070void
1071APFloat::shiftSignificandLeft(unsigned int bits)
1072{
1073 assert(bits < semantics->precision);
1074
1075 if(bits) {
1076 unsigned int partsCount = partCount();
1077
1078 APInt::tcShiftLeft(significandParts(), partsCount, bits);
1079 exponent -= bits;
1080
1081 assert(!APInt::tcIsZero(significandParts(), partsCount));
1082 }
1083}
1084
1085APFloat::cmpResult
1086APFloat::compareAbsoluteValue(const APFloat &rhs) const
1087{
1088 int compare;
1089
1090 assert(semantics == rhs.semantics);
1091 assert(category == fcNormal);
1092 assert(rhs.category == fcNormal);
1093
1094 compare = exponent - rhs.exponent;
1095
1096 /* If exponents are equal, do an unsigned bignum comparison of the
1097 significands. */
1098 if(compare == 0)
1099 compare = APInt::tcCompare(significandParts(), rhs.significandParts(),
Neil Booth4f881702007-09-26 21:33:42 +00001100 partCount());
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001101
1102 if(compare > 0)
1103 return cmpGreaterThan;
1104 else if(compare < 0)
1105 return cmpLessThan;
1106 else
1107 return cmpEqual;
1108}
1109
1110/* Handle overflow. Sign is preserved. We either become infinity or
1111 the largest finite number. */
1112APFloat::opStatus
1113APFloat::handleOverflow(roundingMode rounding_mode)
1114{
1115 /* Infinity? */
1116 if(rounding_mode == rmNearestTiesToEven
1117 || rounding_mode == rmNearestTiesToAway
1118 || (rounding_mode == rmTowardPositive && !sign)
1119 || (rounding_mode == rmTowardNegative && sign))
1120 {
1121 category = fcInfinity;
1122 return (opStatus) (opOverflow | opInexact);
1123 }
1124
1125 /* Otherwise we become the largest finite number. */
1126 category = fcNormal;
1127 exponent = semantics->maxExponent;
1128 APInt::tcSetLeastSignificantBits(significandParts(), partCount(),
Neil Booth4f881702007-09-26 21:33:42 +00001129 semantics->precision);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001130
1131 return opInexact;
1132}
1133
Neil Boothb7dea4c2007-10-03 15:16:41 +00001134/* Returns TRUE if, when truncating the current number, with BIT the
1135 new LSB, with the given lost fraction and rounding mode, the result
1136 would need to be rounded away from zero (i.e., by increasing the
1137 signficand). This routine must work for fcZero of both signs, and
1138 fcNormal numbers. */
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001139bool
1140APFloat::roundAwayFromZero(roundingMode rounding_mode,
Neil Boothb7dea4c2007-10-03 15:16:41 +00001141 lostFraction lost_fraction,
1142 unsigned int bit) const
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001143{
Dale Johanneseneaf08942007-08-31 04:03:46 +00001144 /* NaNs and infinities should not have lost fractions. */
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001145 assert(category == fcNormal || category == fcZero);
1146
Neil Boothb7dea4c2007-10-03 15:16:41 +00001147 /* Current callers never pass this so we don't handle it. */
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001148 assert(lost_fraction != lfExactlyZero);
1149
Mike Stumpf3dc0c02009-05-13 23:23:20 +00001150 switch (rounding_mode) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001151 default:
Torok Edwinc23197a2009-07-14 16:55:14 +00001152 llvm_unreachable(0);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001153
1154 case rmNearestTiesToAway:
1155 return lost_fraction == lfExactlyHalf || lost_fraction == lfMoreThanHalf;
1156
1157 case rmNearestTiesToEven:
1158 if(lost_fraction == lfMoreThanHalf)
1159 return true;
1160
1161 /* Our zeroes don't have a significand to test. */
1162 if(lost_fraction == lfExactlyHalf && category != fcZero)
Neil Boothb7dea4c2007-10-03 15:16:41 +00001163 return APInt::tcExtractBit(significandParts(), bit);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001164
1165 return false;
1166
1167 case rmTowardZero:
1168 return false;
1169
1170 case rmTowardPositive:
1171 return sign == false;
1172
1173 case rmTowardNegative:
1174 return sign == true;
1175 }
1176}
1177
1178APFloat::opStatus
1179APFloat::normalize(roundingMode rounding_mode,
Neil Booth4f881702007-09-26 21:33:42 +00001180 lostFraction lost_fraction)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001181{
Neil Booth4f881702007-09-26 21:33:42 +00001182 unsigned int omsb; /* One, not zero, based MSB. */
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001183 int exponentChange;
1184
1185 if(category != fcNormal)
1186 return opOK;
1187
1188 /* Before rounding normalize the exponent of fcNormal numbers. */
1189 omsb = significandMSB() + 1;
1190
1191 if(omsb) {
1192 /* OMSB is numbered from 1. We want to place it in the integer
1193 bit numbered PRECISON if possible, with a compensating change in
1194 the exponent. */
1195 exponentChange = omsb - semantics->precision;
1196
1197 /* If the resulting exponent is too high, overflow according to
1198 the rounding mode. */
1199 if(exponent + exponentChange > semantics->maxExponent)
1200 return handleOverflow(rounding_mode);
1201
1202 /* Subnormal numbers have exponent minExponent, and their MSB
1203 is forced based on that. */
1204 if(exponent + exponentChange < semantics->minExponent)
1205 exponentChange = semantics->minExponent - exponent;
1206
1207 /* Shifting left is easy as we don't lose precision. */
1208 if(exponentChange < 0) {
1209 assert(lost_fraction == lfExactlyZero);
1210
1211 shiftSignificandLeft(-exponentChange);
1212
1213 return opOK;
1214 }
1215
1216 if(exponentChange > 0) {
1217 lostFraction lf;
1218
1219 /* Shift right and capture any new lost fraction. */
1220 lf = shiftSignificandRight(exponentChange);
1221
1222 lost_fraction = combineLostFractions(lf, lost_fraction);
1223
1224 /* Keep OMSB up-to-date. */
1225 if(omsb > (unsigned) exponentChange)
Neil Booth96c74712007-10-12 16:02:31 +00001226 omsb -= exponentChange;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001227 else
Neil Booth4f881702007-09-26 21:33:42 +00001228 omsb = 0;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001229 }
1230 }
1231
1232 /* Now round the number according to rounding_mode given the lost
1233 fraction. */
1234
1235 /* As specified in IEEE 754, since we do not trap we do not report
1236 underflow for exact results. */
1237 if(lost_fraction == lfExactlyZero) {
1238 /* Canonicalize zeroes. */
1239 if(omsb == 0)
1240 category = fcZero;
1241
1242 return opOK;
1243 }
1244
1245 /* Increment the significand if we're rounding away from zero. */
Neil Boothb7dea4c2007-10-03 15:16:41 +00001246 if(roundAwayFromZero(rounding_mode, lost_fraction, 0)) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001247 if(omsb == 0)
1248 exponent = semantics->minExponent;
1249
1250 incrementSignificand();
1251 omsb = significandMSB() + 1;
1252
1253 /* Did the significand increment overflow? */
1254 if(omsb == (unsigned) semantics->precision + 1) {
1255 /* Renormalize by incrementing the exponent and shifting our
Neil Booth4f881702007-09-26 21:33:42 +00001256 significand right one. However if we already have the
1257 maximum exponent we overflow to infinity. */
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001258 if(exponent == semantics->maxExponent) {
Neil Booth4f881702007-09-26 21:33:42 +00001259 category = fcInfinity;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001260
Neil Booth4f881702007-09-26 21:33:42 +00001261 return (opStatus) (opOverflow | opInexact);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001262 }
1263
1264 shiftSignificandRight(1);
1265
1266 return opInexact;
1267 }
1268 }
1269
1270 /* The normal case - we were and are not denormal, and any
1271 significand increment above didn't overflow. */
1272 if(omsb == semantics->precision)
1273 return opInexact;
1274
1275 /* We have a non-zero denormal. */
1276 assert(omsb < semantics->precision);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001277
1278 /* Canonicalize zeroes. */
1279 if(omsb == 0)
1280 category = fcZero;
1281
1282 /* The fcZero case is a denormal that underflowed to zero. */
1283 return (opStatus) (opUnderflow | opInexact);
1284}
1285
1286APFloat::opStatus
1287APFloat::addOrSubtractSpecials(const APFloat &rhs, bool subtract)
1288{
Mike Stumpf3dc0c02009-05-13 23:23:20 +00001289 switch (convolve(category, rhs.category)) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001290 default:
Torok Edwinc23197a2009-07-14 16:55:14 +00001291 llvm_unreachable(0);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001292
Dale Johanneseneaf08942007-08-31 04:03:46 +00001293 case convolve(fcNaN, fcZero):
1294 case convolve(fcNaN, fcNormal):
1295 case convolve(fcNaN, fcInfinity):
1296 case convolve(fcNaN, fcNaN):
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001297 case convolve(fcNormal, fcZero):
1298 case convolve(fcInfinity, fcNormal):
1299 case convolve(fcInfinity, fcZero):
1300 return opOK;
1301
Dale Johanneseneaf08942007-08-31 04:03:46 +00001302 case convolve(fcZero, fcNaN):
1303 case convolve(fcNormal, fcNaN):
1304 case convolve(fcInfinity, fcNaN):
1305 category = fcNaN;
1306 copySignificand(rhs);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001307 return opOK;
1308
1309 case convolve(fcNormal, fcInfinity):
1310 case convolve(fcZero, fcInfinity):
1311 category = fcInfinity;
1312 sign = rhs.sign ^ subtract;
1313 return opOK;
1314
1315 case convolve(fcZero, fcNormal):
1316 assign(rhs);
1317 sign = rhs.sign ^ subtract;
1318 return opOK;
1319
1320 case convolve(fcZero, fcZero):
1321 /* Sign depends on rounding mode; handled by caller. */
1322 return opOK;
1323
1324 case convolve(fcInfinity, fcInfinity):
1325 /* Differently signed infinities can only be validly
1326 subtracted. */
Cedric Venetaff9c272009-02-14 16:06:42 +00001327 if(((sign ^ rhs.sign)!=0) != subtract) {
Neil Boothe5e01942007-10-14 10:39:51 +00001328 makeNaN();
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001329 return opInvalidOp;
1330 }
1331
1332 return opOK;
1333
1334 case convolve(fcNormal, fcNormal):
1335 return opDivByZero;
1336 }
1337}
1338
1339/* Add or subtract two normal numbers. */
1340lostFraction
1341APFloat::addOrSubtractSignificand(const APFloat &rhs, bool subtract)
1342{
1343 integerPart carry;
1344 lostFraction lost_fraction;
1345 int bits;
1346
1347 /* Determine if the operation on the absolute values is effectively
1348 an addition or subtraction. */
Hartmut Kaiser8df77a92007-10-25 23:15:31 +00001349 subtract ^= (sign ^ rhs.sign) ? true : false;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001350
1351 /* Are we bigger exponent-wise than the RHS? */
1352 bits = exponent - rhs.exponent;
1353
1354 /* Subtraction is more subtle than one might naively expect. */
1355 if(subtract) {
1356 APFloat temp_rhs(rhs);
1357 bool reverse;
1358
Chris Lattnerada530b2007-08-24 03:02:34 +00001359 if (bits == 0) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001360 reverse = compareAbsoluteValue(temp_rhs) == cmpLessThan;
1361 lost_fraction = lfExactlyZero;
Chris Lattnerada530b2007-08-24 03:02:34 +00001362 } else if (bits > 0) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001363 lost_fraction = temp_rhs.shiftSignificandRight(bits - 1);
1364 shiftSignificandLeft(1);
1365 reverse = false;
Chris Lattnerada530b2007-08-24 03:02:34 +00001366 } else {
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001367 lost_fraction = shiftSignificandRight(-bits - 1);
1368 temp_rhs.shiftSignificandLeft(1);
1369 reverse = true;
1370 }
1371
Chris Lattnerada530b2007-08-24 03:02:34 +00001372 if (reverse) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001373 carry = temp_rhs.subtractSignificand
Neil Booth4f881702007-09-26 21:33:42 +00001374 (*this, lost_fraction != lfExactlyZero);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001375 copySignificand(temp_rhs);
1376 sign = !sign;
1377 } else {
1378 carry = subtractSignificand
Neil Booth4f881702007-09-26 21:33:42 +00001379 (temp_rhs, lost_fraction != lfExactlyZero);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001380 }
1381
1382 /* Invert the lost fraction - it was on the RHS and
1383 subtracted. */
1384 if(lost_fraction == lfLessThanHalf)
1385 lost_fraction = lfMoreThanHalf;
1386 else if(lost_fraction == lfMoreThanHalf)
1387 lost_fraction = lfLessThanHalf;
1388
1389 /* The code above is intended to ensure that no borrow is
1390 necessary. */
1391 assert(!carry);
1392 } else {
1393 if(bits > 0) {
1394 APFloat temp_rhs(rhs);
1395
1396 lost_fraction = temp_rhs.shiftSignificandRight(bits);
1397 carry = addSignificand(temp_rhs);
1398 } else {
1399 lost_fraction = shiftSignificandRight(-bits);
1400 carry = addSignificand(rhs);
1401 }
1402
1403 /* We have a guard bit; generating a carry cannot happen. */
1404 assert(!carry);
1405 }
1406
1407 return lost_fraction;
1408}
1409
1410APFloat::opStatus
1411APFloat::multiplySpecials(const APFloat &rhs)
1412{
Mike Stumpf3dc0c02009-05-13 23:23:20 +00001413 switch (convolve(category, rhs.category)) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001414 default:
Torok Edwinc23197a2009-07-14 16:55:14 +00001415 llvm_unreachable(0);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001416
Dale Johanneseneaf08942007-08-31 04:03:46 +00001417 case convolve(fcNaN, fcZero):
1418 case convolve(fcNaN, fcNormal):
1419 case convolve(fcNaN, fcInfinity):
1420 case convolve(fcNaN, fcNaN):
1421 return opOK;
1422
1423 case convolve(fcZero, fcNaN):
1424 case convolve(fcNormal, fcNaN):
1425 case convolve(fcInfinity, fcNaN):
1426 category = fcNaN;
1427 copySignificand(rhs);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001428 return opOK;
1429
1430 case convolve(fcNormal, fcInfinity):
1431 case convolve(fcInfinity, fcNormal):
1432 case convolve(fcInfinity, fcInfinity):
1433 category = fcInfinity;
1434 return opOK;
1435
1436 case convolve(fcZero, fcNormal):
1437 case convolve(fcNormal, fcZero):
1438 case convolve(fcZero, fcZero):
1439 category = fcZero;
1440 return opOK;
1441
1442 case convolve(fcZero, fcInfinity):
1443 case convolve(fcInfinity, fcZero):
Neil Boothe5e01942007-10-14 10:39:51 +00001444 makeNaN();
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001445 return opInvalidOp;
1446
1447 case convolve(fcNormal, fcNormal):
1448 return opOK;
1449 }
1450}
1451
1452APFloat::opStatus
1453APFloat::divideSpecials(const APFloat &rhs)
1454{
Mike Stumpf3dc0c02009-05-13 23:23:20 +00001455 switch (convolve(category, rhs.category)) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001456 default:
Torok Edwinc23197a2009-07-14 16:55:14 +00001457 llvm_unreachable(0);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001458
Dale Johanneseneaf08942007-08-31 04:03:46 +00001459 case convolve(fcNaN, fcZero):
1460 case convolve(fcNaN, fcNormal):
1461 case convolve(fcNaN, fcInfinity):
1462 case convolve(fcNaN, fcNaN):
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001463 case convolve(fcInfinity, fcZero):
1464 case convolve(fcInfinity, fcNormal):
1465 case convolve(fcZero, fcInfinity):
1466 case convolve(fcZero, fcNormal):
1467 return opOK;
1468
Dale Johanneseneaf08942007-08-31 04:03:46 +00001469 case convolve(fcZero, fcNaN):
1470 case convolve(fcNormal, fcNaN):
1471 case convolve(fcInfinity, fcNaN):
1472 category = fcNaN;
1473 copySignificand(rhs);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001474 return opOK;
1475
1476 case convolve(fcNormal, fcInfinity):
1477 category = fcZero;
1478 return opOK;
1479
1480 case convolve(fcNormal, fcZero):
1481 category = fcInfinity;
1482 return opDivByZero;
1483
1484 case convolve(fcInfinity, fcInfinity):
1485 case convolve(fcZero, fcZero):
Neil Boothe5e01942007-10-14 10:39:51 +00001486 makeNaN();
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001487 return opInvalidOp;
1488
1489 case convolve(fcNormal, fcNormal):
1490 return opOK;
1491 }
1492}
1493
Dale Johannesened6af242009-01-21 00:35:19 +00001494APFloat::opStatus
1495APFloat::modSpecials(const APFloat &rhs)
1496{
Mike Stumpf3dc0c02009-05-13 23:23:20 +00001497 switch (convolve(category, rhs.category)) {
Dale Johannesened6af242009-01-21 00:35:19 +00001498 default:
Torok Edwinc23197a2009-07-14 16:55:14 +00001499 llvm_unreachable(0);
Dale Johannesened6af242009-01-21 00:35:19 +00001500
1501 case convolve(fcNaN, fcZero):
1502 case convolve(fcNaN, fcNormal):
1503 case convolve(fcNaN, fcInfinity):
1504 case convolve(fcNaN, fcNaN):
1505 case convolve(fcZero, fcInfinity):
1506 case convolve(fcZero, fcNormal):
1507 case convolve(fcNormal, fcInfinity):
1508 return opOK;
1509
1510 case convolve(fcZero, fcNaN):
1511 case convolve(fcNormal, fcNaN):
1512 case convolve(fcInfinity, fcNaN):
1513 category = fcNaN;
1514 copySignificand(rhs);
1515 return opOK;
1516
1517 case convolve(fcNormal, fcZero):
1518 case convolve(fcInfinity, fcZero):
1519 case convolve(fcInfinity, fcNormal):
1520 case convolve(fcInfinity, fcInfinity):
1521 case convolve(fcZero, fcZero):
1522 makeNaN();
1523 return opInvalidOp;
1524
1525 case convolve(fcNormal, fcNormal):
1526 return opOK;
1527 }
1528}
1529
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001530/* Change sign. */
1531void
1532APFloat::changeSign()
1533{
1534 /* Look mummy, this one's easy. */
1535 sign = !sign;
1536}
1537
Dale Johannesene15c2db2007-08-31 23:35:31 +00001538void
1539APFloat::clearSign()
1540{
1541 /* So is this one. */
1542 sign = 0;
1543}
1544
1545void
1546APFloat::copySign(const APFloat &rhs)
1547{
1548 /* And this one. */
1549 sign = rhs.sign;
1550}
1551
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001552/* Normalized addition or subtraction. */
1553APFloat::opStatus
1554APFloat::addOrSubtract(const APFloat &rhs, roundingMode rounding_mode,
Neil Booth4f881702007-09-26 21:33:42 +00001555 bool subtract)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001556{
1557 opStatus fs;
1558
Neil Boothcaf19d72007-10-14 10:29:28 +00001559 assertArithmeticOK(*semantics);
1560
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001561 fs = addOrSubtractSpecials(rhs, subtract);
1562
1563 /* This return code means it was not a simple case. */
1564 if(fs == opDivByZero) {
1565 lostFraction lost_fraction;
1566
1567 lost_fraction = addOrSubtractSignificand(rhs, subtract);
1568 fs = normalize(rounding_mode, lost_fraction);
1569
1570 /* Can only be zero if we lost no fraction. */
1571 assert(category != fcZero || lost_fraction == lfExactlyZero);
1572 }
1573
1574 /* If two numbers add (exactly) to zero, IEEE 754 decrees it is a
1575 positive zero unless rounding to minus infinity, except that
1576 adding two like-signed zeroes gives that zero. */
1577 if(category == fcZero) {
1578 if(rhs.category != fcZero || (sign == rhs.sign) == subtract)
1579 sign = (rounding_mode == rmTowardNegative);
1580 }
1581
1582 return fs;
1583}
1584
1585/* Normalized addition. */
1586APFloat::opStatus
1587APFloat::add(const APFloat &rhs, roundingMode rounding_mode)
1588{
1589 return addOrSubtract(rhs, rounding_mode, false);
1590}
1591
1592/* Normalized subtraction. */
1593APFloat::opStatus
1594APFloat::subtract(const APFloat &rhs, roundingMode rounding_mode)
1595{
1596 return addOrSubtract(rhs, rounding_mode, true);
1597}
1598
1599/* Normalized multiply. */
1600APFloat::opStatus
1601APFloat::multiply(const APFloat &rhs, roundingMode rounding_mode)
1602{
1603 opStatus fs;
1604
Neil Boothcaf19d72007-10-14 10:29:28 +00001605 assertArithmeticOK(*semantics);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001606 sign ^= rhs.sign;
1607 fs = multiplySpecials(rhs);
1608
1609 if(category == fcNormal) {
1610 lostFraction lost_fraction = multiplySignificand(rhs, 0);
1611 fs = normalize(rounding_mode, lost_fraction);
1612 if(lost_fraction != lfExactlyZero)
1613 fs = (opStatus) (fs | opInexact);
1614 }
1615
1616 return fs;
1617}
1618
1619/* Normalized divide. */
1620APFloat::opStatus
1621APFloat::divide(const APFloat &rhs, roundingMode rounding_mode)
1622{
1623 opStatus fs;
1624
Neil Boothcaf19d72007-10-14 10:29:28 +00001625 assertArithmeticOK(*semantics);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001626 sign ^= rhs.sign;
1627 fs = divideSpecials(rhs);
1628
1629 if(category == fcNormal) {
1630 lostFraction lost_fraction = divideSignificand(rhs);
1631 fs = normalize(rounding_mode, lost_fraction);
1632 if(lost_fraction != lfExactlyZero)
1633 fs = (opStatus) (fs | opInexact);
1634 }
1635
1636 return fs;
1637}
1638
Dale Johannesen24b66a82009-01-20 18:35:05 +00001639/* Normalized remainder. This is not currently correct in all cases. */
1640APFloat::opStatus
1641APFloat::remainder(const APFloat &rhs)
1642{
1643 opStatus fs;
1644 APFloat V = *this;
1645 unsigned int origSign = sign;
1646
1647 assertArithmeticOK(*semantics);
1648 fs = V.divide(rhs, rmNearestTiesToEven);
1649 if (fs == opDivByZero)
1650 return fs;
1651
1652 int parts = partCount();
1653 integerPart *x = new integerPart[parts];
1654 bool ignored;
1655 fs = V.convertToInteger(x, parts * integerPartWidth, true,
1656 rmNearestTiesToEven, &ignored);
1657 if (fs==opInvalidOp)
1658 return fs;
1659
1660 fs = V.convertFromZeroExtendedInteger(x, parts * integerPartWidth, true,
1661 rmNearestTiesToEven);
1662 assert(fs==opOK); // should always work
1663
1664 fs = V.multiply(rhs, rmNearestTiesToEven);
1665 assert(fs==opOK || fs==opInexact); // should not overflow or underflow
1666
1667 fs = subtract(V, rmNearestTiesToEven);
1668 assert(fs==opOK || fs==opInexact); // likewise
1669
1670 if (isZero())
1671 sign = origSign; // IEEE754 requires this
1672 delete[] x;
1673 return fs;
1674}
1675
1676/* Normalized llvm frem (C fmod).
1677 This is not currently correct in all cases. */
Dale Johannesene15c2db2007-08-31 23:35:31 +00001678APFloat::opStatus
1679APFloat::mod(const APFloat &rhs, roundingMode rounding_mode)
1680{
1681 opStatus fs;
Neil Boothcaf19d72007-10-14 10:29:28 +00001682 assertArithmeticOK(*semantics);
Dale Johannesened6af242009-01-21 00:35:19 +00001683 fs = modSpecials(rhs);
Dale Johannesene15c2db2007-08-31 23:35:31 +00001684
Dale Johannesened6af242009-01-21 00:35:19 +00001685 if (category == fcNormal && rhs.category == fcNormal) {
1686 APFloat V = *this;
1687 unsigned int origSign = sign;
Dale Johannesene15c2db2007-08-31 23:35:31 +00001688
Dale Johannesened6af242009-01-21 00:35:19 +00001689 fs = V.divide(rhs, rmNearestTiesToEven);
1690 if (fs == opDivByZero)
1691 return fs;
Dale Johannesen58c2e4c2007-09-05 20:39:49 +00001692
Dale Johannesened6af242009-01-21 00:35:19 +00001693 int parts = partCount();
1694 integerPart *x = new integerPart[parts];
1695 bool ignored;
1696 fs = V.convertToInteger(x, parts * integerPartWidth, true,
1697 rmTowardZero, &ignored);
1698 if (fs==opInvalidOp)
1699 return fs;
Dale Johannesen58c2e4c2007-09-05 20:39:49 +00001700
Dale Johannesened6af242009-01-21 00:35:19 +00001701 fs = V.convertFromZeroExtendedInteger(x, parts * integerPartWidth, true,
1702 rmNearestTiesToEven);
1703 assert(fs==opOK); // should always work
Dale Johannesen58c2e4c2007-09-05 20:39:49 +00001704
Dale Johannesened6af242009-01-21 00:35:19 +00001705 fs = V.multiply(rhs, rounding_mode);
1706 assert(fs==opOK || fs==opInexact); // should not overflow or underflow
1707
1708 fs = subtract(V, rounding_mode);
1709 assert(fs==opOK || fs==opInexact); // likewise
1710
1711 if (isZero())
1712 sign = origSign; // IEEE754 requires this
1713 delete[] x;
1714 }
Dale Johannesene15c2db2007-08-31 23:35:31 +00001715 return fs;
1716}
1717
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001718/* Normalized fused-multiply-add. */
1719APFloat::opStatus
1720APFloat::fusedMultiplyAdd(const APFloat &multiplicand,
Neil Booth4f881702007-09-26 21:33:42 +00001721 const APFloat &addend,
1722 roundingMode rounding_mode)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001723{
1724 opStatus fs;
1725
Neil Boothcaf19d72007-10-14 10:29:28 +00001726 assertArithmeticOK(*semantics);
1727
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001728 /* Post-multiplication sign, before addition. */
1729 sign ^= multiplicand.sign;
1730
1731 /* If and only if all arguments are normal do we need to do an
1732 extended-precision calculation. */
1733 if(category == fcNormal
1734 && multiplicand.category == fcNormal
1735 && addend.category == fcNormal) {
1736 lostFraction lost_fraction;
1737
1738 lost_fraction = multiplySignificand(multiplicand, &addend);
1739 fs = normalize(rounding_mode, lost_fraction);
1740 if(lost_fraction != lfExactlyZero)
1741 fs = (opStatus) (fs | opInexact);
1742
1743 /* If two numbers add (exactly) to zero, IEEE 754 decrees it is a
1744 positive zero unless rounding to minus infinity, except that
1745 adding two like-signed zeroes gives that zero. */
1746 if(category == fcZero && sign != addend.sign)
1747 sign = (rounding_mode == rmTowardNegative);
1748 } else {
1749 fs = multiplySpecials(multiplicand);
1750
1751 /* FS can only be opOK or opInvalidOp. There is no more work
1752 to do in the latter case. The IEEE-754R standard says it is
1753 implementation-defined in this case whether, if ADDEND is a
Dale Johanneseneaf08942007-08-31 04:03:46 +00001754 quiet NaN, we raise invalid op; this implementation does so.
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001755
1756 If we need to do the addition we can do so with normal
1757 precision. */
1758 if(fs == opOK)
1759 fs = addOrSubtract(addend, rounding_mode, false);
1760 }
1761
1762 return fs;
1763}
1764
1765/* Comparison requires normalized numbers. */
1766APFloat::cmpResult
1767APFloat::compare(const APFloat &rhs) const
1768{
1769 cmpResult result;
1770
Neil Boothcaf19d72007-10-14 10:29:28 +00001771 assertArithmeticOK(*semantics);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001772 assert(semantics == rhs.semantics);
1773
Mike Stumpf3dc0c02009-05-13 23:23:20 +00001774 switch (convolve(category, rhs.category)) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001775 default:
Torok Edwinc23197a2009-07-14 16:55:14 +00001776 llvm_unreachable(0);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001777
Dale Johanneseneaf08942007-08-31 04:03:46 +00001778 case convolve(fcNaN, fcZero):
1779 case convolve(fcNaN, fcNormal):
1780 case convolve(fcNaN, fcInfinity):
1781 case convolve(fcNaN, fcNaN):
1782 case convolve(fcZero, fcNaN):
1783 case convolve(fcNormal, fcNaN):
1784 case convolve(fcInfinity, fcNaN):
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001785 return cmpUnordered;
1786
1787 case convolve(fcInfinity, fcNormal):
1788 case convolve(fcInfinity, fcZero):
1789 case convolve(fcNormal, fcZero):
1790 if(sign)
1791 return cmpLessThan;
1792 else
1793 return cmpGreaterThan;
1794
1795 case convolve(fcNormal, fcInfinity):
1796 case convolve(fcZero, fcInfinity):
1797 case convolve(fcZero, fcNormal):
1798 if(rhs.sign)
1799 return cmpGreaterThan;
1800 else
1801 return cmpLessThan;
1802
1803 case convolve(fcInfinity, fcInfinity):
1804 if(sign == rhs.sign)
1805 return cmpEqual;
1806 else if(sign)
1807 return cmpLessThan;
1808 else
1809 return cmpGreaterThan;
1810
1811 case convolve(fcZero, fcZero):
1812 return cmpEqual;
1813
1814 case convolve(fcNormal, fcNormal):
1815 break;
1816 }
1817
1818 /* Two normal numbers. Do they have the same sign? */
1819 if(sign != rhs.sign) {
1820 if(sign)
1821 result = cmpLessThan;
1822 else
1823 result = cmpGreaterThan;
1824 } else {
1825 /* Compare absolute values; invert result if negative. */
1826 result = compareAbsoluteValue(rhs);
1827
1828 if(sign) {
1829 if(result == cmpLessThan)
Neil Booth4f881702007-09-26 21:33:42 +00001830 result = cmpGreaterThan;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001831 else if(result == cmpGreaterThan)
Neil Booth4f881702007-09-26 21:33:42 +00001832 result = cmpLessThan;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001833 }
1834 }
1835
1836 return result;
1837}
1838
Dale Johannesen23a98552008-10-09 23:00:39 +00001839/// APFloat::convert - convert a value of one floating point type to another.
1840/// The return value corresponds to the IEEE754 exceptions. *losesInfo
1841/// records whether the transformation lost information, i.e. whether
1842/// converting the result back to the original type will produce the
1843/// original value (this is almost the same as return value==fsOK, but there
1844/// are edge cases where this is not so).
1845
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001846APFloat::opStatus
1847APFloat::convert(const fltSemantics &toSemantics,
Dale Johannesen23a98552008-10-09 23:00:39 +00001848 roundingMode rounding_mode, bool *losesInfo)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001849{
Neil Boothc8db43d2007-09-22 02:56:19 +00001850 lostFraction lostFraction;
1851 unsigned int newPartCount, oldPartCount;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001852 opStatus fs;
Neil Booth4f881702007-09-26 21:33:42 +00001853
Neil Boothcaf19d72007-10-14 10:29:28 +00001854 assertArithmeticOK(*semantics);
Dale Johannesen79f82f92008-04-20 01:34:03 +00001855 assertArithmeticOK(toSemantics);
Neil Boothc8db43d2007-09-22 02:56:19 +00001856 lostFraction = lfExactlyZero;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001857 newPartCount = partCountForBits(toSemantics.precision + 1);
Neil Boothc8db43d2007-09-22 02:56:19 +00001858 oldPartCount = partCount();
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001859
Neil Boothc8db43d2007-09-22 02:56:19 +00001860 /* Handle storage complications. If our new form is wider,
1861 re-allocate our bit pattern into wider storage. If it is
1862 narrower, we ignore the excess parts, but if narrowing to a
Dale Johannesen902ff942007-09-25 17:25:00 +00001863 single part we need to free the old storage.
1864 Be careful not to reference significandParts for zeroes
1865 and infinities, since it aborts. */
Neil Boothc8db43d2007-09-22 02:56:19 +00001866 if (newPartCount > oldPartCount) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001867 integerPart *newParts;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001868 newParts = new integerPart[newPartCount];
1869 APInt::tcSet(newParts, 0, newPartCount);
Dale Johannesen902ff942007-09-25 17:25:00 +00001870 if (category==fcNormal || category==fcNaN)
1871 APInt::tcAssign(newParts, significandParts(), oldPartCount);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001872 freeSignificand();
1873 significand.parts = newParts;
Neil Boothc8db43d2007-09-22 02:56:19 +00001874 } else if (newPartCount < oldPartCount) {
1875 /* Capture any lost fraction through truncation of parts so we get
1876 correct rounding whilst normalizing. */
Dale Johannesen902ff942007-09-25 17:25:00 +00001877 if (category==fcNormal)
1878 lostFraction = lostFractionThroughTruncation
1879 (significandParts(), oldPartCount, toSemantics.precision);
1880 if (newPartCount == 1) {
1881 integerPart newPart = 0;
Neil Booth4f881702007-09-26 21:33:42 +00001882 if (category==fcNormal || category==fcNaN)
Dale Johannesen902ff942007-09-25 17:25:00 +00001883 newPart = significandParts()[0];
1884 freeSignificand();
1885 significand.part = newPart;
1886 }
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001887 }
1888
1889 if(category == fcNormal) {
1890 /* Re-interpret our bit-pattern. */
1891 exponent += toSemantics.precision - semantics->precision;
1892 semantics = &toSemantics;
Neil Boothc8db43d2007-09-22 02:56:19 +00001893 fs = normalize(rounding_mode, lostFraction);
Dale Johannesen23a98552008-10-09 23:00:39 +00001894 *losesInfo = (fs != opOK);
Dale Johannesen902ff942007-09-25 17:25:00 +00001895 } else if (category == fcNaN) {
1896 int shift = toSemantics.precision - semantics->precision;
Dale Johannesenb63fa052008-01-31 18:34:01 +00001897 // Do this now so significandParts gets the right answer
Dale Johannesen2df5eec2008-10-06 22:59:10 +00001898 const fltSemantics *oldSemantics = semantics;
Dale Johannesenb63fa052008-01-31 18:34:01 +00001899 semantics = &toSemantics;
Dale Johannesen23a98552008-10-09 23:00:39 +00001900 *losesInfo = false;
Dale Johannesen902ff942007-09-25 17:25:00 +00001901 // No normalization here, just truncate
1902 if (shift>0)
1903 APInt::tcShiftLeft(significandParts(), newPartCount, shift);
Dale Johannesen2df5eec2008-10-06 22:59:10 +00001904 else if (shift < 0) {
1905 unsigned ushift = -shift;
Dale Johannesen23a98552008-10-09 23:00:39 +00001906 // Figure out if we are losing information. This happens
Dale Johannesen2df5eec2008-10-06 22:59:10 +00001907 // if are shifting out something other than 0s, or if the x87 long
1908 // double input did not have its integer bit set (pseudo-NaN), or if the
1909 // x87 long double input did not have its QNan bit set (because the x87
1910 // hardware sets this bit when converting a lower-precision NaN to
1911 // x87 long double).
1912 if (APInt::tcLSB(significandParts(), newPartCount) < ushift)
Dale Johannesen23a98552008-10-09 23:00:39 +00001913 *losesInfo = true;
Dale Johannesen2df5eec2008-10-06 22:59:10 +00001914 if (oldSemantics == &APFloat::x87DoubleExtended &&
1915 (!(*significandParts() & 0x8000000000000000ULL) ||
1916 !(*significandParts() & 0x4000000000000000ULL)))
Dale Johannesen23a98552008-10-09 23:00:39 +00001917 *losesInfo = true;
Dale Johannesen2df5eec2008-10-06 22:59:10 +00001918 APInt::tcShiftRight(significandParts(), newPartCount, ushift);
1919 }
Dale Johannesen902ff942007-09-25 17:25:00 +00001920 // gcc forces the Quiet bit on, which means (float)(double)(float_sNan)
1921 // does not give you back the same bits. This is dubious, and we
1922 // don't currently do it. You're really supposed to get
1923 // an invalid operation signal at runtime, but nobody does that.
Dale Johannesen23a98552008-10-09 23:00:39 +00001924 fs = opOK;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001925 } else {
1926 semantics = &toSemantics;
1927 fs = opOK;
Dale Johannesen23a98552008-10-09 23:00:39 +00001928 *losesInfo = false;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001929 }
1930
1931 return fs;
1932}
1933
1934/* Convert a floating point number to an integer according to the
1935 rounding mode. If the rounded integer value is out of range this
Neil Boothee7ae382007-11-01 22:43:37 +00001936 returns an invalid operation exception and the contents of the
1937 destination parts are unspecified. If the rounded value is in
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001938 range but the floating point number is not the exact integer, the C
1939 standard doesn't require an inexact exception to be raised. IEEE
1940 854 does require it so we do that.
1941
1942 Note that for conversions to integer type the C standard requires
1943 round-to-zero to always be used. */
1944APFloat::opStatus
Neil Boothee7ae382007-11-01 22:43:37 +00001945APFloat::convertToSignExtendedInteger(integerPart *parts, unsigned int width,
1946 bool isSigned,
Dale Johannesen23a98552008-10-09 23:00:39 +00001947 roundingMode rounding_mode,
1948 bool *isExact) const
Neil Boothee7ae382007-11-01 22:43:37 +00001949{
1950 lostFraction lost_fraction;
1951 const integerPart *src;
1952 unsigned int dstPartsCount, truncatedBits;
1953
Evan Cheng794a7db2008-11-26 01:11:57 +00001954 assertArithmeticOK(*semantics);
Neil Boothe3d936a2007-11-02 15:10:05 +00001955
Dale Johannesen23a98552008-10-09 23:00:39 +00001956 *isExact = false;
1957
Neil Boothee7ae382007-11-01 22:43:37 +00001958 /* Handle the three special cases first. */
1959 if(category == fcInfinity || category == fcNaN)
1960 return opInvalidOp;
1961
1962 dstPartsCount = partCountForBits(width);
1963
1964 if(category == fcZero) {
1965 APInt::tcSet(parts, 0, dstPartsCount);
Dale Johannesene4a42452008-10-07 00:40:01 +00001966 // Negative zero can't be represented as an int.
Dale Johannesen23a98552008-10-09 23:00:39 +00001967 *isExact = !sign;
1968 return opOK;
Neil Boothee7ae382007-11-01 22:43:37 +00001969 }
1970
1971 src = significandParts();
1972
1973 /* Step 1: place our absolute value, with any fraction truncated, in
1974 the destination. */
1975 if (exponent < 0) {
1976 /* Our absolute value is less than one; truncate everything. */
1977 APInt::tcSet(parts, 0, dstPartsCount);
Dale Johannesen1f54f582009-01-19 21:17:05 +00001978 /* For exponent -1 the integer bit represents .5, look at that.
1979 For smaller exponents leftmost truncated bit is 0. */
1980 truncatedBits = semantics->precision -1U - exponent;
Neil Boothee7ae382007-11-01 22:43:37 +00001981 } else {
1982 /* We want the most significant (exponent + 1) bits; the rest are
1983 truncated. */
1984 unsigned int bits = exponent + 1U;
1985
1986 /* Hopelessly large in magnitude? */
1987 if (bits > width)
1988 return opInvalidOp;
1989
1990 if (bits < semantics->precision) {
1991 /* We truncate (semantics->precision - bits) bits. */
1992 truncatedBits = semantics->precision - bits;
1993 APInt::tcExtract(parts, dstPartsCount, src, bits, truncatedBits);
1994 } else {
1995 /* We want at least as many bits as are available. */
1996 APInt::tcExtract(parts, dstPartsCount, src, semantics->precision, 0);
1997 APInt::tcShiftLeft(parts, dstPartsCount, bits - semantics->precision);
1998 truncatedBits = 0;
1999 }
2000 }
2001
2002 /* Step 2: work out any lost fraction, and increment the absolute
2003 value if we would round away from zero. */
2004 if (truncatedBits) {
2005 lost_fraction = lostFractionThroughTruncation(src, partCount(),
2006 truncatedBits);
2007 if (lost_fraction != lfExactlyZero
2008 && roundAwayFromZero(rounding_mode, lost_fraction, truncatedBits)) {
2009 if (APInt::tcIncrement(parts, dstPartsCount))
2010 return opInvalidOp; /* Overflow. */
2011 }
2012 } else {
2013 lost_fraction = lfExactlyZero;
2014 }
2015
2016 /* Step 3: check if we fit in the destination. */
2017 unsigned int omsb = APInt::tcMSB(parts, dstPartsCount) + 1;
2018
2019 if (sign) {
2020 if (!isSigned) {
2021 /* Negative numbers cannot be represented as unsigned. */
2022 if (omsb != 0)
2023 return opInvalidOp;
2024 } else {
2025 /* It takes omsb bits to represent the unsigned integer value.
2026 We lose a bit for the sign, but care is needed as the
2027 maximally negative integer is a special case. */
2028 if (omsb == width && APInt::tcLSB(parts, dstPartsCount) + 1 != omsb)
2029 return opInvalidOp;
2030
2031 /* This case can happen because of rounding. */
2032 if (omsb > width)
2033 return opInvalidOp;
2034 }
2035
2036 APInt::tcNegate (parts, dstPartsCount);
2037 } else {
2038 if (omsb >= width + !isSigned)
2039 return opInvalidOp;
2040 }
2041
Dale Johannesen23a98552008-10-09 23:00:39 +00002042 if (lost_fraction == lfExactlyZero) {
2043 *isExact = true;
Neil Boothee7ae382007-11-01 22:43:37 +00002044 return opOK;
Dale Johannesen23a98552008-10-09 23:00:39 +00002045 } else
Neil Boothee7ae382007-11-01 22:43:37 +00002046 return opInexact;
2047}
2048
2049/* Same as convertToSignExtendedInteger, except we provide
2050 deterministic values in case of an invalid operation exception,
2051 namely zero for NaNs and the minimal or maximal value respectively
Dale Johannesen23a98552008-10-09 23:00:39 +00002052 for underflow or overflow.
2053 The *isExact output tells whether the result is exact, in the sense
2054 that converting it back to the original floating point type produces
2055 the original value. This is almost equivalent to result==opOK,
2056 except for negative zeroes.
2057*/
Neil Boothee7ae382007-11-01 22:43:37 +00002058APFloat::opStatus
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002059APFloat::convertToInteger(integerPart *parts, unsigned int width,
Neil Booth4f881702007-09-26 21:33:42 +00002060 bool isSigned,
Dale Johannesen23a98552008-10-09 23:00:39 +00002061 roundingMode rounding_mode, bool *isExact) const
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002062{
Neil Boothee7ae382007-11-01 22:43:37 +00002063 opStatus fs;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002064
Dale Johannesen23a98552008-10-09 23:00:39 +00002065 fs = convertToSignExtendedInteger(parts, width, isSigned, rounding_mode,
2066 isExact);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002067
Neil Boothee7ae382007-11-01 22:43:37 +00002068 if (fs == opInvalidOp) {
2069 unsigned int bits, dstPartsCount;
2070
2071 dstPartsCount = partCountForBits(width);
2072
2073 if (category == fcNaN)
2074 bits = 0;
2075 else if (sign)
2076 bits = isSigned;
2077 else
2078 bits = width - isSigned;
2079
2080 APInt::tcSetLeastSignificantBits(parts, dstPartsCount, bits);
2081 if (sign && isSigned)
2082 APInt::tcShiftLeft(parts, dstPartsCount, width - 1);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002083 }
2084
Neil Boothee7ae382007-11-01 22:43:37 +00002085 return fs;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002086}
2087
Neil Booth643ce592007-10-07 12:07:53 +00002088/* Convert an unsigned integer SRC to a floating point number,
2089 rounding according to ROUNDING_MODE. The sign of the floating
2090 point number is not modified. */
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002091APFloat::opStatus
Neil Booth643ce592007-10-07 12:07:53 +00002092APFloat::convertFromUnsignedParts(const integerPart *src,
2093 unsigned int srcCount,
2094 roundingMode rounding_mode)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002095{
Neil Booth5477f852007-10-08 14:39:42 +00002096 unsigned int omsb, precision, dstCount;
Neil Booth643ce592007-10-07 12:07:53 +00002097 integerPart *dst;
Neil Booth5477f852007-10-08 14:39:42 +00002098 lostFraction lost_fraction;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002099
Neil Boothcaf19d72007-10-14 10:29:28 +00002100 assertArithmeticOK(*semantics);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002101 category = fcNormal;
Neil Booth5477f852007-10-08 14:39:42 +00002102 omsb = APInt::tcMSB(src, srcCount) + 1;
Neil Booth643ce592007-10-07 12:07:53 +00002103 dst = significandParts();
2104 dstCount = partCount();
Neil Booth5477f852007-10-08 14:39:42 +00002105 precision = semantics->precision;
Neil Booth643ce592007-10-07 12:07:53 +00002106
Neil Booth5477f852007-10-08 14:39:42 +00002107 /* We want the most significant PRECISON bits of SRC. There may not
2108 be that many; extract what we can. */
2109 if (precision <= omsb) {
2110 exponent = omsb - 1;
Neil Booth643ce592007-10-07 12:07:53 +00002111 lost_fraction = lostFractionThroughTruncation(src, srcCount,
Neil Booth5477f852007-10-08 14:39:42 +00002112 omsb - precision);
2113 APInt::tcExtract(dst, dstCount, src, precision, omsb - precision);
2114 } else {
2115 exponent = precision - 1;
2116 lost_fraction = lfExactlyZero;
2117 APInt::tcExtract(dst, dstCount, src, omsb, 0);
Neil Booth643ce592007-10-07 12:07:53 +00002118 }
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002119
2120 return normalize(rounding_mode, lost_fraction);
2121}
2122
Dan Gohman93c276e2008-02-29 01:26:11 +00002123APFloat::opStatus
2124APFloat::convertFromAPInt(const APInt &Val,
2125 bool isSigned,
2126 roundingMode rounding_mode)
2127{
2128 unsigned int partCount = Val.getNumWords();
2129 APInt api = Val;
2130
2131 sign = false;
2132 if (isSigned && api.isNegative()) {
2133 sign = true;
2134 api = -api;
2135 }
2136
2137 return convertFromUnsignedParts(api.getRawData(), partCount, rounding_mode);
2138}
2139
Neil Boothf16c5952007-10-07 12:15:41 +00002140/* Convert a two's complement integer SRC to a floating point number,
2141 rounding according to ROUNDING_MODE. ISSIGNED is true if the
2142 integer is signed, in which case it must be sign-extended. */
2143APFloat::opStatus
2144APFloat::convertFromSignExtendedInteger(const integerPart *src,
2145 unsigned int srcCount,
2146 bool isSigned,
2147 roundingMode rounding_mode)
2148{
2149 opStatus status;
2150
Neil Boothcaf19d72007-10-14 10:29:28 +00002151 assertArithmeticOK(*semantics);
Neil Boothf16c5952007-10-07 12:15:41 +00002152 if (isSigned
2153 && APInt::tcExtractBit(src, srcCount * integerPartWidth - 1)) {
2154 integerPart *copy;
2155
2156 /* If we're signed and negative negate a copy. */
2157 sign = true;
2158 copy = new integerPart[srcCount];
2159 APInt::tcAssign(copy, src, srcCount);
2160 APInt::tcNegate(copy, srcCount);
2161 status = convertFromUnsignedParts(copy, srcCount, rounding_mode);
2162 delete [] copy;
2163 } else {
2164 sign = false;
2165 status = convertFromUnsignedParts(src, srcCount, rounding_mode);
2166 }
2167
2168 return status;
2169}
2170
Neil Boothccf596a2007-10-07 11:45:55 +00002171/* FIXME: should this just take a const APInt reference? */
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002172APFloat::opStatus
Neil Boothccf596a2007-10-07 11:45:55 +00002173APFloat::convertFromZeroExtendedInteger(const integerPart *parts,
2174 unsigned int width, bool isSigned,
2175 roundingMode rounding_mode)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002176{
Dale Johannesen910993e2007-09-21 22:09:37 +00002177 unsigned int partCount = partCountForBits(width);
Dale Johannesen910993e2007-09-21 22:09:37 +00002178 APInt api = APInt(width, partCount, parts);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002179
2180 sign = false;
Dale Johannesencce23a42007-09-30 18:17:01 +00002181 if(isSigned && APInt::tcExtractBit(parts, width - 1)) {
2182 sign = true;
2183 api = -api;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002184 }
2185
Neil Booth7a7bc0f2007-10-07 12:10:57 +00002186 return convertFromUnsignedParts(api.getRawData(), partCount, rounding_mode);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002187}
2188
2189APFloat::opStatus
Erick Tryzelaara15d8902009-08-16 23:36:19 +00002190APFloat::convertFromHexadecimalString(const StringRef &s,
Neil Booth4f881702007-09-26 21:33:42 +00002191 roundingMode rounding_mode)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002192{
Erick Tryzelaarf8bc8012009-08-18 18:20:37 +00002193 lostFraction lost_fraction = lfExactlyZero;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002194 integerPart *significand;
2195 unsigned int bitPos, partsCount;
Erick Tryzelaara15d8902009-08-16 23:36:19 +00002196 StringRef::iterator dot, firstSignificantDigit;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002197
2198 zeroSignificand();
2199 exponent = 0;
2200 category = fcNormal;
2201
2202 significand = significandParts();
2203 partsCount = partCount();
2204 bitPos = partsCount * integerPartWidth;
2205
Neil Booth33d4c922007-10-07 08:51:21 +00002206 /* Skip leading zeroes and any (hexa)decimal point. */
Erick Tryzelaarc78b33b2009-08-20 23:30:43 +00002207 StringRef::iterator begin = s.begin();
2208 StringRef::iterator end = s.end();
2209 StringRef::iterator p = skipLeadingZeroesAndAnyDot(begin, end, &dot);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002210 firstSignificantDigit = p;
2211
Erick Tryzelaarc78b33b2009-08-20 23:30:43 +00002212 for(; p != end;) {
Dale Johannesen386f3e92008-05-14 22:53:25 +00002213 integerPart hex_value;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002214
2215 if(*p == '.') {
Erick Tryzelaarc78b33b2009-08-20 23:30:43 +00002216 assert(dot == end && "String contains multiple dots");
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002217 dot = p++;
Erick Tryzelaarc78b33b2009-08-20 23:30:43 +00002218 if (p == end) {
2219 break;
2220 }
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002221 }
2222
2223 hex_value = hexDigitValue(*p);
2224 if(hex_value == -1U) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002225 break;
2226 }
2227
2228 p++;
2229
Erick Tryzelaarc78b33b2009-08-20 23:30:43 +00002230 if (p == end) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002231 break;
Erick Tryzelaara15d8902009-08-16 23:36:19 +00002232 } else {
2233 /* Store the number whilst 4-bit nibbles remain. */
2234 if(bitPos) {
2235 bitPos -= 4;
2236 hex_value <<= bitPos % integerPartWidth;
2237 significand[bitPos / integerPartWidth] |= hex_value;
2238 } else {
Erick Tryzelaarc78b33b2009-08-20 23:30:43 +00002239 lost_fraction = trailingHexadecimalFraction(p, end, hex_value);
2240 while(p != end && hexDigitValue(*p) != -1U)
Erick Tryzelaara15d8902009-08-16 23:36:19 +00002241 p++;
2242 break;
2243 }
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002244 }
2245 }
2246
2247 /* Hex floats require an exponent but not a hexadecimal point. */
Erick Tryzelaarc78b33b2009-08-20 23:30:43 +00002248 assert(p != end && "Hex strings require an exponent");
2249 assert((*p == 'p' || *p == 'P') && "Invalid character in significand");
2250 assert(p != begin && "Significand has no digits");
2251 assert((dot == end || p - begin != 1) && "Significand has no digits");
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002252
2253 /* Ignore the exponent if we are zero. */
2254 if(p != firstSignificantDigit) {
2255 int expAdjustment;
2256
2257 /* Implicit hexadecimal point? */
Erick Tryzelaarc78b33b2009-08-20 23:30:43 +00002258 if (dot == end)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002259 dot = p;
2260
2261 /* Calculate the exponent adjustment implicit in the number of
2262 significant digits. */
Evan Cheng48e8c802008-05-02 21:15:08 +00002263 expAdjustment = static_cast<int>(dot - firstSignificantDigit);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002264 if(expAdjustment < 0)
2265 expAdjustment++;
2266 expAdjustment = expAdjustment * 4 - 1;
2267
2268 /* Adjust for writing the significand starting at the most
2269 significant nibble. */
2270 expAdjustment += semantics->precision;
2271 expAdjustment -= partsCount * integerPartWidth;
2272
2273 /* Adjust for the given exponent. */
Erick Tryzelaarc78b33b2009-08-20 23:30:43 +00002274 exponent = totalExponent(p + 1, end, expAdjustment);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002275 }
2276
2277 return normalize(rounding_mode, lost_fraction);
2278}
2279
2280APFloat::opStatus
Neil Booth96c74712007-10-12 16:02:31 +00002281APFloat::roundSignificandWithExponent(const integerPart *decSigParts,
2282 unsigned sigPartCount, int exp,
2283 roundingMode rounding_mode)
2284{
2285 unsigned int parts, pow5PartCount;
Neil Boothcaf19d72007-10-14 10:29:28 +00002286 fltSemantics calcSemantics = { 32767, -32767, 0, true };
Neil Booth96c74712007-10-12 16:02:31 +00002287 integerPart pow5Parts[maxPowerOfFiveParts];
2288 bool isNearest;
2289
2290 isNearest = (rounding_mode == rmNearestTiesToEven
2291 || rounding_mode == rmNearestTiesToAway);
2292
2293 parts = partCountForBits(semantics->precision + 11);
2294
2295 /* Calculate pow(5, abs(exp)). */
2296 pow5PartCount = powerOf5(pow5Parts, exp >= 0 ? exp: -exp);
2297
2298 for (;; parts *= 2) {
2299 opStatus sigStatus, powStatus;
2300 unsigned int excessPrecision, truncatedBits;
2301
2302 calcSemantics.precision = parts * integerPartWidth - 1;
2303 excessPrecision = calcSemantics.precision - semantics->precision;
2304 truncatedBits = excessPrecision;
2305
2306 APFloat decSig(calcSemantics, fcZero, sign);
2307 APFloat pow5(calcSemantics, fcZero, false);
2308
2309 sigStatus = decSig.convertFromUnsignedParts(decSigParts, sigPartCount,
2310 rmNearestTiesToEven);
2311 powStatus = pow5.convertFromUnsignedParts(pow5Parts, pow5PartCount,
2312 rmNearestTiesToEven);
2313 /* Add exp, as 10^n = 5^n * 2^n. */
2314 decSig.exponent += exp;
2315
2316 lostFraction calcLostFraction;
Evan Cheng48e8c802008-05-02 21:15:08 +00002317 integerPart HUerr, HUdistance;
2318 unsigned int powHUerr;
Neil Booth96c74712007-10-12 16:02:31 +00002319
2320 if (exp >= 0) {
2321 /* multiplySignificand leaves the precision-th bit set to 1. */
2322 calcLostFraction = decSig.multiplySignificand(pow5, NULL);
2323 powHUerr = powStatus != opOK;
2324 } else {
2325 calcLostFraction = decSig.divideSignificand(pow5);
2326 /* Denormal numbers have less precision. */
2327 if (decSig.exponent < semantics->minExponent) {
2328 excessPrecision += (semantics->minExponent - decSig.exponent);
2329 truncatedBits = excessPrecision;
2330 if (excessPrecision > calcSemantics.precision)
2331 excessPrecision = calcSemantics.precision;
2332 }
2333 /* Extra half-ulp lost in reciprocal of exponent. */
Evan Cheng48e8c802008-05-02 21:15:08 +00002334 powHUerr = (powStatus == opOK && calcLostFraction == lfExactlyZero) ? 0:2;
Neil Booth96c74712007-10-12 16:02:31 +00002335 }
2336
2337 /* Both multiplySignificand and divideSignificand return the
2338 result with the integer bit set. */
Evan Cheng99ebfa52009-10-27 21:35:42 +00002339 assert(APInt::tcExtractBit
2340 (decSig.significandParts(), calcSemantics.precision - 1) == 1);
Neil Booth96c74712007-10-12 16:02:31 +00002341
2342 HUerr = HUerrBound(calcLostFraction != lfExactlyZero, sigStatus != opOK,
2343 powHUerr);
2344 HUdistance = 2 * ulpsFromBoundary(decSig.significandParts(),
2345 excessPrecision, isNearest);
2346
2347 /* Are we guaranteed to round correctly if we truncate? */
2348 if (HUdistance >= HUerr) {
2349 APInt::tcExtract(significandParts(), partCount(), decSig.significandParts(),
2350 calcSemantics.precision - excessPrecision,
2351 excessPrecision);
2352 /* Take the exponent of decSig. If we tcExtract-ed less bits
2353 above we must adjust our exponent to compensate for the
2354 implicit right shift. */
2355 exponent = (decSig.exponent + semantics->precision
2356 - (calcSemantics.precision - excessPrecision));
2357 calcLostFraction = lostFractionThroughTruncation(decSig.significandParts(),
2358 decSig.partCount(),
2359 truncatedBits);
2360 return normalize(rounding_mode, calcLostFraction);
2361 }
2362 }
2363}
2364
2365APFloat::opStatus
Erick Tryzelaara15d8902009-08-16 23:36:19 +00002366APFloat::convertFromDecimalString(const StringRef &str, roundingMode rounding_mode)
Neil Booth96c74712007-10-12 16:02:31 +00002367{
Neil Booth1870f292007-10-14 10:16:12 +00002368 decimalInfo D;
Neil Booth96c74712007-10-12 16:02:31 +00002369 opStatus fs;
2370
Neil Booth1870f292007-10-14 10:16:12 +00002371 /* Scan the text. */
Erick Tryzelaara15d8902009-08-16 23:36:19 +00002372 StringRef::iterator p = str.begin();
2373 interpretDecimal(p, str.end(), &D);
Neil Booth96c74712007-10-12 16:02:31 +00002374
Neil Booth686700e2007-10-15 15:00:55 +00002375 /* Handle the quick cases. First the case of no significant digits,
2376 i.e. zero, and then exponents that are obviously too large or too
2377 small. Writing L for log 10 / log 2, a number d.ddddd*10^exp
2378 definitely overflows if
2379
2380 (exp - 1) * L >= maxExponent
2381
2382 and definitely underflows to zero where
2383
2384 (exp + 1) * L <= minExponent - precision
2385
2386 With integer arithmetic the tightest bounds for L are
2387
2388 93/28 < L < 196/59 [ numerator <= 256 ]
2389 42039/12655 < L < 28738/8651 [ numerator <= 65536 ]
2390 */
2391
Neil Boothcc233592007-12-05 13:06:04 +00002392 if (decDigitValue(*D.firstSigDigit) >= 10U) {
Neil Booth96c74712007-10-12 16:02:31 +00002393 category = fcZero;
2394 fs = opOK;
John McCall8b3f3302010-02-26 22:20:41 +00002395
2396 /* Check whether the normalized exponent is high enough to overflow
2397 max during the log-rebasing in the max-exponent check below. */
2398 } else if (D.normalizedExponent - 1 > INT_MAX / 42039) {
2399 fs = handleOverflow(rounding_mode);
2400
2401 /* If it wasn't, then it also wasn't high enough to overflow max
2402 during the log-rebasing in the min-exponent check. Check that it
2403 won't overflow min in either check, then perform the min-exponent
2404 check. */
2405 } else if (D.normalizedExponent - 1 < INT_MIN / 42039 ||
2406 (D.normalizedExponent + 1) * 28738 <=
2407 8651 * (semantics->minExponent - (int) semantics->precision)) {
Neil Booth686700e2007-10-15 15:00:55 +00002408 /* Underflow to zero and round. */
2409 zeroSignificand();
2410 fs = normalize(rounding_mode, lfLessThanHalf);
John McCall8b3f3302010-02-26 22:20:41 +00002411
2412 /* We can finally safely perform the max-exponent check. */
Neil Booth686700e2007-10-15 15:00:55 +00002413 } else if ((D.normalizedExponent - 1) * 42039
2414 >= 12655 * semantics->maxExponent) {
2415 /* Overflow and round. */
2416 fs = handleOverflow(rounding_mode);
Neil Booth96c74712007-10-12 16:02:31 +00002417 } else {
Neil Booth1870f292007-10-14 10:16:12 +00002418 integerPart *decSignificand;
2419 unsigned int partCount;
Neil Booth96c74712007-10-12 16:02:31 +00002420
Neil Booth1870f292007-10-14 10:16:12 +00002421 /* A tight upper bound on number of bits required to hold an
Neil Booth686700e2007-10-15 15:00:55 +00002422 N-digit decimal integer is N * 196 / 59. Allocate enough space
Neil Booth1870f292007-10-14 10:16:12 +00002423 to hold the full significand, and an extra part required by
2424 tcMultiplyPart. */
Evan Cheng48e8c802008-05-02 21:15:08 +00002425 partCount = static_cast<unsigned int>(D.lastSigDigit - D.firstSigDigit) + 1;
Neil Booth686700e2007-10-15 15:00:55 +00002426 partCount = partCountForBits(1 + 196 * partCount / 59);
Neil Booth1870f292007-10-14 10:16:12 +00002427 decSignificand = new integerPart[partCount + 1];
2428 partCount = 0;
Neil Booth96c74712007-10-12 16:02:31 +00002429
Neil Booth1870f292007-10-14 10:16:12 +00002430 /* Convert to binary efficiently - we do almost all multiplication
2431 in an integerPart. When this would overflow do we do a single
2432 bignum multiplication, and then revert again to multiplication
2433 in an integerPart. */
2434 do {
2435 integerPart decValue, val, multiplier;
2436
2437 val = 0;
2438 multiplier = 1;
2439
2440 do {
Erick Tryzelaara15d8902009-08-16 23:36:19 +00002441 if (*p == '.') {
Neil Booth1870f292007-10-14 10:16:12 +00002442 p++;
Erick Tryzelaara15d8902009-08-16 23:36:19 +00002443 if (p == str.end()) {
2444 break;
2445 }
2446 }
Neil Booth1870f292007-10-14 10:16:12 +00002447 decValue = decDigitValue(*p++);
Erick Tryzelaarc78b33b2009-08-20 23:30:43 +00002448 assert(decValue < 10U && "Invalid character in significand");
Neil Booth1870f292007-10-14 10:16:12 +00002449 multiplier *= 10;
2450 val = val * 10 + decValue;
2451 /* The maximum number that can be multiplied by ten with any
2452 digit added without overflowing an integerPart. */
2453 } while (p <= D.lastSigDigit && multiplier <= (~ (integerPart) 0 - 9) / 10);
2454
2455 /* Multiply out the current part. */
2456 APInt::tcMultiplyPart(decSignificand, decSignificand, multiplier, val,
2457 partCount, partCount + 1, false);
2458
2459 /* If we used another part (likely but not guaranteed), increase
2460 the count. */
2461 if (decSignificand[partCount])
2462 partCount++;
2463 } while (p <= D.lastSigDigit);
Neil Booth96c74712007-10-12 16:02:31 +00002464
Neil Booth43a4b282007-11-01 22:51:07 +00002465 category = fcNormal;
Neil Booth96c74712007-10-12 16:02:31 +00002466 fs = roundSignificandWithExponent(decSignificand, partCount,
Neil Booth1870f292007-10-14 10:16:12 +00002467 D.exponent, rounding_mode);
Neil Booth96c74712007-10-12 16:02:31 +00002468
Neil Booth1870f292007-10-14 10:16:12 +00002469 delete [] decSignificand;
2470 }
Neil Booth96c74712007-10-12 16:02:31 +00002471
2472 return fs;
2473}
2474
2475APFloat::opStatus
Erick Tryzelaara15d8902009-08-16 23:36:19 +00002476APFloat::convertFromString(const StringRef &str, roundingMode rounding_mode)
Neil Booth4f881702007-09-26 21:33:42 +00002477{
Neil Boothcaf19d72007-10-14 10:29:28 +00002478 assertArithmeticOK(*semantics);
Erick Tryzelaara15d8902009-08-16 23:36:19 +00002479 assert(!str.empty() && "Invalid string length");
Neil Boothcaf19d72007-10-14 10:29:28 +00002480
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002481 /* Handle a leading minus sign. */
Erick Tryzelaara15d8902009-08-16 23:36:19 +00002482 StringRef::iterator p = str.begin();
2483 size_t slen = str.size();
Erick Tryzelaarc78b33b2009-08-20 23:30:43 +00002484 sign = *p == '-' ? 1 : 0;
2485 if(*p == '-' || *p == '+') {
Erick Tryzelaara15d8902009-08-16 23:36:19 +00002486 p++;
2487 slen--;
Erick Tryzelaarc78b33b2009-08-20 23:30:43 +00002488 assert(slen && "String has no digits");
Erick Tryzelaara15d8902009-08-16 23:36:19 +00002489 }
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002490
Erick Tryzelaara15d8902009-08-16 23:36:19 +00002491 if(slen >= 2 && p[0] == '0' && (p[1] == 'x' || p[1] == 'X')) {
2492 assert(slen - 2 && "Invalid string");
Erick Tryzelaarc78b33b2009-08-20 23:30:43 +00002493 return convertFromHexadecimalString(StringRef(p + 2, slen - 2),
Erick Tryzelaara15d8902009-08-16 23:36:19 +00002494 rounding_mode);
2495 }
Bill Wendlingb7c0d942008-11-27 08:00:12 +00002496
Erick Tryzelaarc78b33b2009-08-20 23:30:43 +00002497 return convertFromDecimalString(StringRef(p, slen), rounding_mode);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002498}
Dale Johannesen343e7702007-08-24 00:56:33 +00002499
Neil Bootha30b0ee2007-10-03 22:26:02 +00002500/* Write out a hexadecimal representation of the floating point value
2501 to DST, which must be of sufficient size, in the C99 form
2502 [-]0xh.hhhhp[+-]d. Return the number of characters written,
2503 excluding the terminating NUL.
2504
2505 If UPPERCASE, the output is in upper case, otherwise in lower case.
2506
2507 HEXDIGITS digits appear altogether, rounding the value if
2508 necessary. If HEXDIGITS is 0, the minimal precision to display the
2509 number precisely is used instead. If nothing would appear after
2510 the decimal point it is suppressed.
2511
2512 The decimal exponent is always printed and has at least one digit.
2513 Zero values display an exponent of zero. Infinities and NaNs
2514 appear as "infinity" or "nan" respectively.
2515
2516 The above rules are as specified by C99. There is ambiguity about
2517 what the leading hexadecimal digit should be. This implementation
2518 uses whatever is necessary so that the exponent is displayed as
2519 stored. This implies the exponent will fall within the IEEE format
2520 range, and the leading hexadecimal digit will be 0 (for denormals),
2521 1 (normal numbers) or 2 (normal numbers rounded-away-from-zero with
2522 any other digits zero).
2523*/
2524unsigned int
2525APFloat::convertToHexString(char *dst, unsigned int hexDigits,
2526 bool upperCase, roundingMode rounding_mode) const
2527{
2528 char *p;
2529
Neil Boothcaf19d72007-10-14 10:29:28 +00002530 assertArithmeticOK(*semantics);
2531
Neil Bootha30b0ee2007-10-03 22:26:02 +00002532 p = dst;
2533 if (sign)
2534 *dst++ = '-';
2535
2536 switch (category) {
2537 case fcInfinity:
2538 memcpy (dst, upperCase ? infinityU: infinityL, sizeof infinityU - 1);
2539 dst += sizeof infinityL - 1;
2540 break;
2541
2542 case fcNaN:
2543 memcpy (dst, upperCase ? NaNU: NaNL, sizeof NaNU - 1);
2544 dst += sizeof NaNU - 1;
2545 break;
2546
2547 case fcZero:
2548 *dst++ = '0';
2549 *dst++ = upperCase ? 'X': 'x';
2550 *dst++ = '0';
2551 if (hexDigits > 1) {
2552 *dst++ = '.';
2553 memset (dst, '0', hexDigits - 1);
2554 dst += hexDigits - 1;
2555 }
2556 *dst++ = upperCase ? 'P': 'p';
2557 *dst++ = '0';
2558 break;
2559
2560 case fcNormal:
2561 dst = convertNormalToHexString (dst, hexDigits, upperCase, rounding_mode);
2562 break;
2563 }
2564
2565 *dst = 0;
2566
Evan Cheng48e8c802008-05-02 21:15:08 +00002567 return static_cast<unsigned int>(dst - p);
Neil Bootha30b0ee2007-10-03 22:26:02 +00002568}
2569
2570/* Does the hard work of outputting the correctly rounded hexadecimal
2571 form of a normal floating point number with the specified number of
2572 hexadecimal digits. If HEXDIGITS is zero the minimum number of
2573 digits necessary to print the value precisely is output. */
2574char *
2575APFloat::convertNormalToHexString(char *dst, unsigned int hexDigits,
2576 bool upperCase,
2577 roundingMode rounding_mode) const
2578{
2579 unsigned int count, valueBits, shift, partsCount, outputDigits;
2580 const char *hexDigitChars;
2581 const integerPart *significand;
2582 char *p;
2583 bool roundUp;
2584
2585 *dst++ = '0';
2586 *dst++ = upperCase ? 'X': 'x';
2587
2588 roundUp = false;
2589 hexDigitChars = upperCase ? hexDigitsUpper: hexDigitsLower;
2590
2591 significand = significandParts();
2592 partsCount = partCount();
2593
2594 /* +3 because the first digit only uses the single integer bit, so
2595 we have 3 virtual zero most-significant-bits. */
2596 valueBits = semantics->precision + 3;
2597 shift = integerPartWidth - valueBits % integerPartWidth;
2598
2599 /* The natural number of digits required ignoring trailing
2600 insignificant zeroes. */
2601 outputDigits = (valueBits - significandLSB () + 3) / 4;
2602
2603 /* hexDigits of zero means use the required number for the
2604 precision. Otherwise, see if we are truncating. If we are,
Neil Booth978661d2007-10-06 00:24:48 +00002605 find out if we need to round away from zero. */
Neil Bootha30b0ee2007-10-03 22:26:02 +00002606 if (hexDigits) {
2607 if (hexDigits < outputDigits) {
2608 /* We are dropping non-zero bits, so need to check how to round.
2609 "bits" is the number of dropped bits. */
2610 unsigned int bits;
2611 lostFraction fraction;
2612
2613 bits = valueBits - hexDigits * 4;
2614 fraction = lostFractionThroughTruncation (significand, partsCount, bits);
2615 roundUp = roundAwayFromZero(rounding_mode, fraction, bits);
2616 }
2617 outputDigits = hexDigits;
2618 }
2619
2620 /* Write the digits consecutively, and start writing in the location
2621 of the hexadecimal point. We move the most significant digit
2622 left and add the hexadecimal point later. */
2623 p = ++dst;
2624
2625 count = (valueBits + integerPartWidth - 1) / integerPartWidth;
2626
2627 while (outputDigits && count) {
2628 integerPart part;
2629
2630 /* Put the most significant integerPartWidth bits in "part". */
2631 if (--count == partsCount)
2632 part = 0; /* An imaginary higher zero part. */
2633 else
2634 part = significand[count] << shift;
2635
2636 if (count && shift)
2637 part |= significand[count - 1] >> (integerPartWidth - shift);
2638
2639 /* Convert as much of "part" to hexdigits as we can. */
2640 unsigned int curDigits = integerPartWidth / 4;
2641
2642 if (curDigits > outputDigits)
2643 curDigits = outputDigits;
2644 dst += partAsHex (dst, part, curDigits, hexDigitChars);
2645 outputDigits -= curDigits;
2646 }
2647
2648 if (roundUp) {
2649 char *q = dst;
2650
2651 /* Note that hexDigitChars has a trailing '0'. */
2652 do {
2653 q--;
2654 *q = hexDigitChars[hexDigitValue (*q) + 1];
Neil Booth978661d2007-10-06 00:24:48 +00002655 } while (*q == '0');
Evan Cheng99ebfa52009-10-27 21:35:42 +00002656 assert(q >= p);
Neil Bootha30b0ee2007-10-03 22:26:02 +00002657 } else {
2658 /* Add trailing zeroes. */
2659 memset (dst, '0', outputDigits);
2660 dst += outputDigits;
2661 }
2662
2663 /* Move the most significant digit to before the point, and if there
2664 is something after the decimal point add it. This must come
2665 after rounding above. */
2666 p[-1] = p[0];
2667 if (dst -1 == p)
2668 dst--;
2669 else
2670 p[0] = '.';
2671
2672 /* Finally output the exponent. */
2673 *dst++ = upperCase ? 'P': 'p';
2674
Neil Booth92f7e8d2007-10-06 07:29:25 +00002675 return writeSignedDecimal (dst, exponent);
Neil Bootha30b0ee2007-10-03 22:26:02 +00002676}
2677
Dale Johannesen343e7702007-08-24 00:56:33 +00002678// For good performance it is desirable for different APFloats
2679// to produce different integers.
2680uint32_t
Neil Booth4f881702007-09-26 21:33:42 +00002681APFloat::getHashValue() const
2682{
Dale Johannesen343e7702007-08-24 00:56:33 +00002683 if (category==fcZero) return sign<<8 | semantics->precision ;
2684 else if (category==fcInfinity) return sign<<9 | semantics->precision;
Dale Johanneseneaf08942007-08-31 04:03:46 +00002685 else if (category==fcNaN) return 1<<10 | semantics->precision;
Dale Johannesen343e7702007-08-24 00:56:33 +00002686 else {
2687 uint32_t hash = sign<<11 | semantics->precision | exponent<<12;
2688 const integerPart* p = significandParts();
2689 for (int i=partCount(); i>0; i--, p++)
Evan Cheng48e8c802008-05-02 21:15:08 +00002690 hash ^= ((uint32_t)*p) ^ (uint32_t)((*p)>>32);
Dale Johannesen343e7702007-08-24 00:56:33 +00002691 return hash;
2692 }
2693}
2694
2695// Conversion from APFloat to/from host float/double. It may eventually be
2696// possible to eliminate these and have everybody deal with APFloats, but that
2697// will take a while. This approach will not easily extend to long double.
Dale Johannesena72a5a02007-09-20 23:47:58 +00002698// Current implementation requires integerPartWidth==64, which is correct at
2699// the moment but could be made more general.
Dale Johannesen343e7702007-08-24 00:56:33 +00002700
Dale Johannesen58c2e4c2007-09-05 20:39:49 +00002701// Denormals have exponent minExponent in APFloat, but minExponent-1 in
Dale Johannesena72a5a02007-09-20 23:47:58 +00002702// the actual IEEE respresentations. We compensate for that here.
Dale Johannesen58c2e4c2007-09-05 20:39:49 +00002703
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002704APInt
Neil Booth4f881702007-09-26 21:33:42 +00002705APFloat::convertF80LongDoubleAPFloatToAPInt() const
2706{
Dan Gohmanb10abe12008-01-29 12:08:20 +00002707 assert(semantics == (const llvm::fltSemantics*)&x87DoubleExtended);
Evan Cheng99ebfa52009-10-27 21:35:42 +00002708 assert(partCount()==2);
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002709
2710 uint64_t myexponent, mysignificand;
2711
2712 if (category==fcNormal) {
2713 myexponent = exponent+16383; //bias
Dale Johannesena72a5a02007-09-20 23:47:58 +00002714 mysignificand = significandParts()[0];
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002715 if (myexponent==1 && !(mysignificand & 0x8000000000000000ULL))
2716 myexponent = 0; // denormal
2717 } else if (category==fcZero) {
2718 myexponent = 0;
2719 mysignificand = 0;
2720 } else if (category==fcInfinity) {
2721 myexponent = 0x7fff;
2722 mysignificand = 0x8000000000000000ULL;
Chris Lattnera11ef822007-10-06 06:13:42 +00002723 } else {
2724 assert(category == fcNaN && "Unknown category");
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002725 myexponent = 0x7fff;
Dale Johannesena72a5a02007-09-20 23:47:58 +00002726 mysignificand = significandParts()[0];
Chris Lattnera11ef822007-10-06 06:13:42 +00002727 }
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002728
2729 uint64_t words[2];
Dale Johannesen1b25cb22009-03-23 21:16:53 +00002730 words[0] = mysignificand;
2731 words[1] = ((uint64_t)(sign & 1) << 15) |
2732 (myexponent & 0x7fffLL);
Chris Lattnera11ef822007-10-06 06:13:42 +00002733 return APInt(80, 2, words);
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002734}
2735
2736APInt
Dale Johannesena471c2e2007-10-11 18:07:22 +00002737APFloat::convertPPCDoubleDoubleAPFloatToAPInt() const
2738{
Dan Gohmanb10abe12008-01-29 12:08:20 +00002739 assert(semantics == (const llvm::fltSemantics*)&PPCDoubleDouble);
Evan Cheng99ebfa52009-10-27 21:35:42 +00002740 assert(partCount()==2);
Dale Johannesena471c2e2007-10-11 18:07:22 +00002741
2742 uint64_t myexponent, mysignificand, myexponent2, mysignificand2;
2743
2744 if (category==fcNormal) {
2745 myexponent = exponent + 1023; //bias
2746 myexponent2 = exponent2 + 1023;
2747 mysignificand = significandParts()[0];
2748 mysignificand2 = significandParts()[1];
2749 if (myexponent==1 && !(mysignificand & 0x10000000000000LL))
2750 myexponent = 0; // denormal
2751 if (myexponent2==1 && !(mysignificand2 & 0x10000000000000LL))
2752 myexponent2 = 0; // denormal
2753 } else if (category==fcZero) {
2754 myexponent = 0;
2755 mysignificand = 0;
2756 myexponent2 = 0;
2757 mysignificand2 = 0;
2758 } else if (category==fcInfinity) {
2759 myexponent = 0x7ff;
2760 myexponent2 = 0;
2761 mysignificand = 0;
2762 mysignificand2 = 0;
2763 } else {
2764 assert(category == fcNaN && "Unknown category");
2765 myexponent = 0x7ff;
2766 mysignificand = significandParts()[0];
2767 myexponent2 = exponent2;
2768 mysignificand2 = significandParts()[1];
2769 }
2770
2771 uint64_t words[2];
Evan Cheng48e8c802008-05-02 21:15:08 +00002772 words[0] = ((uint64_t)(sign & 1) << 63) |
Dale Johannesena471c2e2007-10-11 18:07:22 +00002773 ((myexponent & 0x7ff) << 52) |
2774 (mysignificand & 0xfffffffffffffLL);
Evan Cheng48e8c802008-05-02 21:15:08 +00002775 words[1] = ((uint64_t)(sign2 & 1) << 63) |
Dale Johannesena471c2e2007-10-11 18:07:22 +00002776 ((myexponent2 & 0x7ff) << 52) |
2777 (mysignificand2 & 0xfffffffffffffLL);
2778 return APInt(128, 2, words);
2779}
2780
2781APInt
Anton Korobeynikov7e844f12009-08-21 22:10:30 +00002782APFloat::convertQuadrupleAPFloatToAPInt() const
2783{
2784 assert(semantics == (const llvm::fltSemantics*)&IEEEquad);
Evan Cheng99ebfa52009-10-27 21:35:42 +00002785 assert(partCount()==2);
Anton Korobeynikov7e844f12009-08-21 22:10:30 +00002786
2787 uint64_t myexponent, mysignificand, mysignificand2;
2788
2789 if (category==fcNormal) {
2790 myexponent = exponent+16383; //bias
2791 mysignificand = significandParts()[0];
2792 mysignificand2 = significandParts()[1];
2793 if (myexponent==1 && !(mysignificand2 & 0x1000000000000LL))
2794 myexponent = 0; // denormal
2795 } else if (category==fcZero) {
2796 myexponent = 0;
2797 mysignificand = mysignificand2 = 0;
2798 } else if (category==fcInfinity) {
2799 myexponent = 0x7fff;
2800 mysignificand = mysignificand2 = 0;
2801 } else {
2802 assert(category == fcNaN && "Unknown category!");
2803 myexponent = 0x7fff;
2804 mysignificand = significandParts()[0];
2805 mysignificand2 = significandParts()[1];
2806 }
2807
2808 uint64_t words[2];
2809 words[0] = mysignificand;
2810 words[1] = ((uint64_t)(sign & 1) << 63) |
2811 ((myexponent & 0x7fff) << 48) |
Anton Korobeynikov4755e992009-08-21 23:09:47 +00002812 (mysignificand2 & 0xffffffffffffLL);
Anton Korobeynikov7e844f12009-08-21 22:10:30 +00002813
2814 return APInt(128, 2, words);
2815}
2816
2817APInt
Neil Booth4f881702007-09-26 21:33:42 +00002818APFloat::convertDoubleAPFloatToAPInt() const
2819{
Dan Gohmancb648f92007-09-14 20:08:19 +00002820 assert(semantics == (const llvm::fltSemantics*)&IEEEdouble);
Evan Cheng99ebfa52009-10-27 21:35:42 +00002821 assert(partCount()==1);
Dale Johannesen343e7702007-08-24 00:56:33 +00002822
Dale Johanneseneaf08942007-08-31 04:03:46 +00002823 uint64_t myexponent, mysignificand;
Dale Johannesen343e7702007-08-24 00:56:33 +00002824
2825 if (category==fcNormal) {
Dale Johannesen343e7702007-08-24 00:56:33 +00002826 myexponent = exponent+1023; //bias
Dale Johannesen58c2e4c2007-09-05 20:39:49 +00002827 mysignificand = *significandParts();
2828 if (myexponent==1 && !(mysignificand & 0x10000000000000LL))
2829 myexponent = 0; // denormal
Dale Johannesen343e7702007-08-24 00:56:33 +00002830 } else if (category==fcZero) {
Dale Johannesen343e7702007-08-24 00:56:33 +00002831 myexponent = 0;
2832 mysignificand = 0;
2833 } else if (category==fcInfinity) {
Dale Johannesen343e7702007-08-24 00:56:33 +00002834 myexponent = 0x7ff;
2835 mysignificand = 0;
Chris Lattnera11ef822007-10-06 06:13:42 +00002836 } else {
2837 assert(category == fcNaN && "Unknown category!");
Dale Johannesen343e7702007-08-24 00:56:33 +00002838 myexponent = 0x7ff;
Dale Johanneseneaf08942007-08-31 04:03:46 +00002839 mysignificand = *significandParts();
Chris Lattnera11ef822007-10-06 06:13:42 +00002840 }
Dale Johannesen343e7702007-08-24 00:56:33 +00002841
Evan Cheng48e8c802008-05-02 21:15:08 +00002842 return APInt(64, ((((uint64_t)(sign & 1) << 63) |
Chris Lattnera11ef822007-10-06 06:13:42 +00002843 ((myexponent & 0x7ff) << 52) |
2844 (mysignificand & 0xfffffffffffffLL))));
Dale Johannesen343e7702007-08-24 00:56:33 +00002845}
2846
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002847APInt
Neil Booth4f881702007-09-26 21:33:42 +00002848APFloat::convertFloatAPFloatToAPInt() const
2849{
Dan Gohmancb648f92007-09-14 20:08:19 +00002850 assert(semantics == (const llvm::fltSemantics*)&IEEEsingle);
Evan Cheng99ebfa52009-10-27 21:35:42 +00002851 assert(partCount()==1);
Neil Booth4f881702007-09-26 21:33:42 +00002852
Dale Johanneseneaf08942007-08-31 04:03:46 +00002853 uint32_t myexponent, mysignificand;
Dale Johannesen343e7702007-08-24 00:56:33 +00002854
2855 if (category==fcNormal) {
Dale Johannesen343e7702007-08-24 00:56:33 +00002856 myexponent = exponent+127; //bias
Evan Cheng48e8c802008-05-02 21:15:08 +00002857 mysignificand = (uint32_t)*significandParts();
Dale Johannesend0763b92007-11-17 01:02:27 +00002858 if (myexponent == 1 && !(mysignificand & 0x800000))
Dale Johannesen58c2e4c2007-09-05 20:39:49 +00002859 myexponent = 0; // denormal
Dale Johannesen343e7702007-08-24 00:56:33 +00002860 } else if (category==fcZero) {
Dale Johannesen343e7702007-08-24 00:56:33 +00002861 myexponent = 0;
2862 mysignificand = 0;
2863 } else if (category==fcInfinity) {
Dale Johannesen343e7702007-08-24 00:56:33 +00002864 myexponent = 0xff;
2865 mysignificand = 0;
Chris Lattnera11ef822007-10-06 06:13:42 +00002866 } else {
2867 assert(category == fcNaN && "Unknown category!");
Dale Johannesen58c2e4c2007-09-05 20:39:49 +00002868 myexponent = 0xff;
Evan Cheng48e8c802008-05-02 21:15:08 +00002869 mysignificand = (uint32_t)*significandParts();
Chris Lattnera11ef822007-10-06 06:13:42 +00002870 }
Dale Johannesen343e7702007-08-24 00:56:33 +00002871
Chris Lattnera11ef822007-10-06 06:13:42 +00002872 return APInt(32, (((sign&1) << 31) | ((myexponent&0xff) << 23) |
2873 (mysignificand & 0x7fffff)));
Dale Johannesen343e7702007-08-24 00:56:33 +00002874}
2875
Chris Lattnercc4287a2009-10-16 02:13:51 +00002876APInt
2877APFloat::convertHalfAPFloatToAPInt() const
2878{
2879 assert(semantics == (const llvm::fltSemantics*)&IEEEhalf);
Evan Cheng99ebfa52009-10-27 21:35:42 +00002880 assert(partCount()==1);
Chris Lattnercc4287a2009-10-16 02:13:51 +00002881
2882 uint32_t myexponent, mysignificand;
2883
2884 if (category==fcNormal) {
2885 myexponent = exponent+15; //bias
2886 mysignificand = (uint32_t)*significandParts();
2887 if (myexponent == 1 && !(mysignificand & 0x400))
2888 myexponent = 0; // denormal
2889 } else if (category==fcZero) {
2890 myexponent = 0;
2891 mysignificand = 0;
2892 } else if (category==fcInfinity) {
Dale Johannesena223aed2009-10-23 04:02:51 +00002893 myexponent = 0x1f;
Chris Lattnercc4287a2009-10-16 02:13:51 +00002894 mysignificand = 0;
2895 } else {
2896 assert(category == fcNaN && "Unknown category!");
Dale Johannesena223aed2009-10-23 04:02:51 +00002897 myexponent = 0x1f;
Chris Lattnercc4287a2009-10-16 02:13:51 +00002898 mysignificand = (uint32_t)*significandParts();
2899 }
2900
2901 return APInt(16, (((sign&1) << 15) | ((myexponent&0x1f) << 10) |
2902 (mysignificand & 0x3ff)));
2903}
2904
Dale Johannesena471c2e2007-10-11 18:07:22 +00002905// This function creates an APInt that is just a bit map of the floating
2906// point constant as it would appear in memory. It is not a conversion,
2907// and treating the result as a normal integer is unlikely to be useful.
2908
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002909APInt
Dale Johannesen7111b022008-10-09 18:53:47 +00002910APFloat::bitcastToAPInt() const
Neil Booth4f881702007-09-26 21:33:42 +00002911{
Chris Lattnercc4287a2009-10-16 02:13:51 +00002912 if (semantics == (const llvm::fltSemantics*)&IEEEhalf)
2913 return convertHalfAPFloatToAPInt();
2914
Dan Gohmanb10abe12008-01-29 12:08:20 +00002915 if (semantics == (const llvm::fltSemantics*)&IEEEsingle)
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002916 return convertFloatAPFloatToAPInt();
Anton Korobeynikov7e844f12009-08-21 22:10:30 +00002917
Dan Gohmanb10abe12008-01-29 12:08:20 +00002918 if (semantics == (const llvm::fltSemantics*)&IEEEdouble)
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002919 return convertDoubleAPFloatToAPInt();
Neil Booth4f881702007-09-26 21:33:42 +00002920
Anton Korobeynikov7e844f12009-08-21 22:10:30 +00002921 if (semantics == (const llvm::fltSemantics*)&IEEEquad)
2922 return convertQuadrupleAPFloatToAPInt();
2923
Dan Gohmanb10abe12008-01-29 12:08:20 +00002924 if (semantics == (const llvm::fltSemantics*)&PPCDoubleDouble)
Dale Johannesena471c2e2007-10-11 18:07:22 +00002925 return convertPPCDoubleDoubleAPFloatToAPInt();
2926
Dan Gohmanb10abe12008-01-29 12:08:20 +00002927 assert(semantics == (const llvm::fltSemantics*)&x87DoubleExtended &&
Chris Lattnera11ef822007-10-06 06:13:42 +00002928 "unknown format!");
2929 return convertF80LongDoubleAPFloatToAPInt();
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002930}
2931
Neil Booth4f881702007-09-26 21:33:42 +00002932float
2933APFloat::convertToFloat() const
2934{
Chris Lattnerad785002009-09-24 21:44:20 +00002935 assert(semantics == (const llvm::fltSemantics*)&IEEEsingle &&
2936 "Float semantics are not IEEEsingle");
Dale Johannesen7111b022008-10-09 18:53:47 +00002937 APInt api = bitcastToAPInt();
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002938 return api.bitsToFloat();
2939}
2940
Neil Booth4f881702007-09-26 21:33:42 +00002941double
2942APFloat::convertToDouble() const
2943{
Chris Lattnerad785002009-09-24 21:44:20 +00002944 assert(semantics == (const llvm::fltSemantics*)&IEEEdouble &&
2945 "Float semantics are not IEEEdouble");
Dale Johannesen7111b022008-10-09 18:53:47 +00002946 APInt api = bitcastToAPInt();
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002947 return api.bitsToDouble();
2948}
2949
Dale Johannesend3d8ce32008-10-06 18:22:29 +00002950/// Integer bit is explicit in this format. Intel hardware (387 and later)
2951/// does not support these bit patterns:
2952/// exponent = all 1's, integer bit 0, significand 0 ("pseudoinfinity")
2953/// exponent = all 1's, integer bit 0, significand nonzero ("pseudoNaN")
2954/// exponent = 0, integer bit 1 ("pseudodenormal")
2955/// exponent!=0 nor all 1's, integer bit 0 ("unnormal")
2956/// At the moment, the first two are treated as NaNs, the second two as Normal.
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002957void
Neil Booth4f881702007-09-26 21:33:42 +00002958APFloat::initFromF80LongDoubleAPInt(const APInt &api)
2959{
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002960 assert(api.getBitWidth()==80);
2961 uint64_t i1 = api.getRawData()[0];
2962 uint64_t i2 = api.getRawData()[1];
Dale Johannesen1b25cb22009-03-23 21:16:53 +00002963 uint64_t myexponent = (i2 & 0x7fff);
2964 uint64_t mysignificand = i1;
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002965
2966 initialize(&APFloat::x87DoubleExtended);
Dale Johannesena72a5a02007-09-20 23:47:58 +00002967 assert(partCount()==2);
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002968
Dale Johannesen1b25cb22009-03-23 21:16:53 +00002969 sign = static_cast<unsigned int>(i2>>15);
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002970 if (myexponent==0 && mysignificand==0) {
2971 // exponent, significand meaningless
2972 category = fcZero;
2973 } else if (myexponent==0x7fff && mysignificand==0x8000000000000000ULL) {
2974 // exponent, significand meaningless
2975 category = fcInfinity;
2976 } else if (myexponent==0x7fff && mysignificand!=0x8000000000000000ULL) {
2977 // exponent meaningless
2978 category = fcNaN;
Dale Johannesena72a5a02007-09-20 23:47:58 +00002979 significandParts()[0] = mysignificand;
2980 significandParts()[1] = 0;
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002981 } else {
2982 category = fcNormal;
2983 exponent = myexponent - 16383;
Dale Johannesena72a5a02007-09-20 23:47:58 +00002984 significandParts()[0] = mysignificand;
2985 significandParts()[1] = 0;
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002986 if (myexponent==0) // denormal
2987 exponent = -16382;
Neil Booth4f881702007-09-26 21:33:42 +00002988 }
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002989}
2990
2991void
Dale Johannesena471c2e2007-10-11 18:07:22 +00002992APFloat::initFromPPCDoubleDoubleAPInt(const APInt &api)
2993{
2994 assert(api.getBitWidth()==128);
2995 uint64_t i1 = api.getRawData()[0];
2996 uint64_t i2 = api.getRawData()[1];
2997 uint64_t myexponent = (i1 >> 52) & 0x7ff;
2998 uint64_t mysignificand = i1 & 0xfffffffffffffLL;
2999 uint64_t myexponent2 = (i2 >> 52) & 0x7ff;
3000 uint64_t mysignificand2 = i2 & 0xfffffffffffffLL;
3001
3002 initialize(&APFloat::PPCDoubleDouble);
3003 assert(partCount()==2);
3004
Evan Cheng48e8c802008-05-02 21:15:08 +00003005 sign = static_cast<unsigned int>(i1>>63);
3006 sign2 = static_cast<unsigned int>(i2>>63);
Dale Johannesena471c2e2007-10-11 18:07:22 +00003007 if (myexponent==0 && mysignificand==0) {
3008 // exponent, significand meaningless
3009 // exponent2 and significand2 are required to be 0; we don't check
3010 category = fcZero;
3011 } else if (myexponent==0x7ff && mysignificand==0) {
3012 // exponent, significand meaningless
3013 // exponent2 and significand2 are required to be 0; we don't check
3014 category = fcInfinity;
3015 } else if (myexponent==0x7ff && mysignificand!=0) {
3016 // exponent meaningless. So is the whole second word, but keep it
3017 // for determinism.
3018 category = fcNaN;
3019 exponent2 = myexponent2;
3020 significandParts()[0] = mysignificand;
3021 significandParts()[1] = mysignificand2;
3022 } else {
3023 category = fcNormal;
3024 // Note there is no category2; the second word is treated as if it is
3025 // fcNormal, although it might be something else considered by itself.
3026 exponent = myexponent - 1023;
3027 exponent2 = myexponent2 - 1023;
3028 significandParts()[0] = mysignificand;
3029 significandParts()[1] = mysignificand2;
3030 if (myexponent==0) // denormal
3031 exponent = -1022;
3032 else
3033 significandParts()[0] |= 0x10000000000000LL; // integer bit
3034 if (myexponent2==0)
3035 exponent2 = -1022;
3036 else
3037 significandParts()[1] |= 0x10000000000000LL; // integer bit
3038 }
3039}
3040
3041void
Anton Korobeynikov7e844f12009-08-21 22:10:30 +00003042APFloat::initFromQuadrupleAPInt(const APInt &api)
3043{
3044 assert(api.getBitWidth()==128);
3045 uint64_t i1 = api.getRawData()[0];
3046 uint64_t i2 = api.getRawData()[1];
3047 uint64_t myexponent = (i2 >> 48) & 0x7fff;
3048 uint64_t mysignificand = i1;
3049 uint64_t mysignificand2 = i2 & 0xffffffffffffLL;
3050
3051 initialize(&APFloat::IEEEquad);
3052 assert(partCount()==2);
3053
3054 sign = static_cast<unsigned int>(i2>>63);
3055 if (myexponent==0 &&
3056 (mysignificand==0 && mysignificand2==0)) {
3057 // exponent, significand meaningless
3058 category = fcZero;
3059 } else if (myexponent==0x7fff &&
3060 (mysignificand==0 && mysignificand2==0)) {
3061 // exponent, significand meaningless
3062 category = fcInfinity;
3063 } else if (myexponent==0x7fff &&
3064 (mysignificand!=0 || mysignificand2 !=0)) {
3065 // exponent meaningless
3066 category = fcNaN;
3067 significandParts()[0] = mysignificand;
3068 significandParts()[1] = mysignificand2;
3069 } else {
3070 category = fcNormal;
3071 exponent = myexponent - 16383;
3072 significandParts()[0] = mysignificand;
3073 significandParts()[1] = mysignificand2;
3074 if (myexponent==0) // denormal
3075 exponent = -16382;
3076 else
3077 significandParts()[1] |= 0x1000000000000LL; // integer bit
3078 }
3079}
3080
3081void
Neil Booth4f881702007-09-26 21:33:42 +00003082APFloat::initFromDoubleAPInt(const APInt &api)
3083{
Dale Johannesen3f6eb742007-09-11 18:32:33 +00003084 assert(api.getBitWidth()==64);
3085 uint64_t i = *api.getRawData();
Dale Johannesend3b51fd2007-08-24 05:08:11 +00003086 uint64_t myexponent = (i >> 52) & 0x7ff;
3087 uint64_t mysignificand = i & 0xfffffffffffffLL;
3088
Dale Johannesen343e7702007-08-24 00:56:33 +00003089 initialize(&APFloat::IEEEdouble);
Dale Johannesen343e7702007-08-24 00:56:33 +00003090 assert(partCount()==1);
3091
Evan Cheng48e8c802008-05-02 21:15:08 +00003092 sign = static_cast<unsigned int>(i>>63);
Dale Johannesen343e7702007-08-24 00:56:33 +00003093 if (myexponent==0 && mysignificand==0) {
3094 // exponent, significand meaningless
3095 category = fcZero;
Dale Johannesen343e7702007-08-24 00:56:33 +00003096 } else if (myexponent==0x7ff && mysignificand==0) {
3097 // exponent, significand meaningless
3098 category = fcInfinity;
Dale Johanneseneaf08942007-08-31 04:03:46 +00003099 } else if (myexponent==0x7ff && mysignificand!=0) {
3100 // exponent meaningless
3101 category = fcNaN;
3102 *significandParts() = mysignificand;
Dale Johannesen343e7702007-08-24 00:56:33 +00003103 } else {
Dale Johannesen343e7702007-08-24 00:56:33 +00003104 category = fcNormal;
3105 exponent = myexponent - 1023;
Dale Johannesen58c2e4c2007-09-05 20:39:49 +00003106 *significandParts() = mysignificand;
3107 if (myexponent==0) // denormal
3108 exponent = -1022;
3109 else
3110 *significandParts() |= 0x10000000000000LL; // integer bit
Neil Booth4f881702007-09-26 21:33:42 +00003111 }
Dale Johannesen343e7702007-08-24 00:56:33 +00003112}
3113
Dale Johannesen3f6eb742007-09-11 18:32:33 +00003114void
Neil Booth4f881702007-09-26 21:33:42 +00003115APFloat::initFromFloatAPInt(const APInt & api)
3116{
Dale Johannesen3f6eb742007-09-11 18:32:33 +00003117 assert(api.getBitWidth()==32);
3118 uint32_t i = (uint32_t)*api.getRawData();
Dale Johannesend3b51fd2007-08-24 05:08:11 +00003119 uint32_t myexponent = (i >> 23) & 0xff;
3120 uint32_t mysignificand = i & 0x7fffff;
3121
Dale Johannesen343e7702007-08-24 00:56:33 +00003122 initialize(&APFloat::IEEEsingle);
Dale Johannesen343e7702007-08-24 00:56:33 +00003123 assert(partCount()==1);
3124
Dale Johanneseneaf08942007-08-31 04:03:46 +00003125 sign = i >> 31;
Dale Johannesen343e7702007-08-24 00:56:33 +00003126 if (myexponent==0 && mysignificand==0) {
3127 // exponent, significand meaningless
3128 category = fcZero;
Dale Johannesen343e7702007-08-24 00:56:33 +00003129 } else if (myexponent==0xff && mysignificand==0) {
3130 // exponent, significand meaningless
3131 category = fcInfinity;
Dale Johannesen902ff942007-09-25 17:25:00 +00003132 } else if (myexponent==0xff && mysignificand!=0) {
Dale Johannesen343e7702007-08-24 00:56:33 +00003133 // sign, exponent, significand meaningless
Dale Johanneseneaf08942007-08-31 04:03:46 +00003134 category = fcNaN;
3135 *significandParts() = mysignificand;
Dale Johannesen343e7702007-08-24 00:56:33 +00003136 } else {
3137 category = fcNormal;
Dale Johannesen343e7702007-08-24 00:56:33 +00003138 exponent = myexponent - 127; //bias
Dale Johannesen58c2e4c2007-09-05 20:39:49 +00003139 *significandParts() = mysignificand;
3140 if (myexponent==0) // denormal
3141 exponent = -126;
3142 else
3143 *significandParts() |= 0x800000; // integer bit
Dale Johannesen343e7702007-08-24 00:56:33 +00003144 }
3145}
Dale Johannesen3f6eb742007-09-11 18:32:33 +00003146
Chris Lattnercc4287a2009-10-16 02:13:51 +00003147void
3148APFloat::initFromHalfAPInt(const APInt & api)
3149{
3150 assert(api.getBitWidth()==16);
3151 uint32_t i = (uint32_t)*api.getRawData();
Dale Johannesena223aed2009-10-23 04:02:51 +00003152 uint32_t myexponent = (i >> 10) & 0x1f;
Chris Lattnercc4287a2009-10-16 02:13:51 +00003153 uint32_t mysignificand = i & 0x3ff;
3154
3155 initialize(&APFloat::IEEEhalf);
3156 assert(partCount()==1);
3157
3158 sign = i >> 15;
3159 if (myexponent==0 && mysignificand==0) {
3160 // exponent, significand meaningless
3161 category = fcZero;
3162 } else if (myexponent==0x1f && mysignificand==0) {
3163 // exponent, significand meaningless
3164 category = fcInfinity;
3165 } else if (myexponent==0x1f && mysignificand!=0) {
3166 // sign, exponent, significand meaningless
3167 category = fcNaN;
3168 *significandParts() = mysignificand;
3169 } else {
3170 category = fcNormal;
3171 exponent = myexponent - 15; //bias
3172 *significandParts() = mysignificand;
3173 if (myexponent==0) // denormal
3174 exponent = -14;
3175 else
3176 *significandParts() |= 0x400; // integer bit
3177 }
3178}
3179
Dale Johannesen3f6eb742007-09-11 18:32:33 +00003180/// Treat api as containing the bits of a floating point number. Currently
Dale Johannesena471c2e2007-10-11 18:07:22 +00003181/// we infer the floating point type from the size of the APInt. The
3182/// isIEEE argument distinguishes between PPC128 and IEEE128 (not meaningful
3183/// when the size is anything else).
Dale Johannesen3f6eb742007-09-11 18:32:33 +00003184void
Dale Johannesena471c2e2007-10-11 18:07:22 +00003185APFloat::initFromAPInt(const APInt& api, bool isIEEE)
Neil Booth4f881702007-09-26 21:33:42 +00003186{
Chris Lattnercc4287a2009-10-16 02:13:51 +00003187 if (api.getBitWidth() == 16)
3188 return initFromHalfAPInt(api);
3189 else if (api.getBitWidth() == 32)
Dale Johannesen3f6eb742007-09-11 18:32:33 +00003190 return initFromFloatAPInt(api);
3191 else if (api.getBitWidth()==64)
3192 return initFromDoubleAPInt(api);
3193 else if (api.getBitWidth()==80)
3194 return initFromF80LongDoubleAPInt(api);
Anton Korobeynikov7e844f12009-08-21 22:10:30 +00003195 else if (api.getBitWidth()==128)
3196 return (isIEEE ?
3197 initFromQuadrupleAPInt(api) : initFromPPCDoubleDoubleAPInt(api));
Dale Johannesen3f6eb742007-09-11 18:32:33 +00003198 else
Torok Edwinc23197a2009-07-14 16:55:14 +00003199 llvm_unreachable(0);
Dale Johannesen3f6eb742007-09-11 18:32:33 +00003200}
3201
John McCall00e65de2009-12-24 08:56:26 +00003202APFloat APFloat::getLargest(const fltSemantics &Sem, bool Negative) {
3203 APFloat Val(Sem, fcNormal, Negative);
3204
3205 // We want (in interchange format):
3206 // sign = {Negative}
3207 // exponent = 1..10
3208 // significand = 1..1
3209
3210 Val.exponent = Sem.maxExponent; // unbiased
3211
3212 // 1-initialize all bits....
3213 Val.zeroSignificand();
3214 integerPart *significand = Val.significandParts();
3215 unsigned N = partCountForBits(Sem.precision);
3216 for (unsigned i = 0; i != N; ++i)
3217 significand[i] = ~((integerPart) 0);
3218
3219 // ...and then clear the top bits for internal consistency.
3220 significand[N-1]
3221 &= (((integerPart) 1) << ((Sem.precision % integerPartWidth) - 1)) - 1;
3222
3223 return Val;
3224}
3225
3226APFloat APFloat::getSmallest(const fltSemantics &Sem, bool Negative) {
3227 APFloat Val(Sem, fcNormal, Negative);
3228
3229 // We want (in interchange format):
3230 // sign = {Negative}
3231 // exponent = 0..0
3232 // significand = 0..01
3233
3234 Val.exponent = Sem.minExponent; // unbiased
3235 Val.zeroSignificand();
3236 Val.significandParts()[0] = 1;
3237 return Val;
3238}
3239
3240APFloat APFloat::getSmallestNormalized(const fltSemantics &Sem, bool Negative) {
3241 APFloat Val(Sem, fcNormal, Negative);
3242
3243 // We want (in interchange format):
3244 // sign = {Negative}
3245 // exponent = 0..0
3246 // significand = 10..0
3247
3248 Val.exponent = Sem.minExponent;
3249 Val.zeroSignificand();
3250 Val.significandParts()[partCountForBits(Sem.precision)-1]
3251 |= (((integerPart) 1) << ((Sem.precision % integerPartWidth) - 1));
3252
3253 return Val;
3254}
3255
Dale Johannesena471c2e2007-10-11 18:07:22 +00003256APFloat::APFloat(const APInt& api, bool isIEEE)
Neil Booth4f881702007-09-26 21:33:42 +00003257{
Dale Johannesena471c2e2007-10-11 18:07:22 +00003258 initFromAPInt(api, isIEEE);
Dale Johannesen3f6eb742007-09-11 18:32:33 +00003259}
3260
Neil Booth4f881702007-09-26 21:33:42 +00003261APFloat::APFloat(float f)
3262{
Dale Johannesen3f6eb742007-09-11 18:32:33 +00003263 APInt api = APInt(32, 0);
3264 initFromAPInt(api.floatToBits(f));
3265}
3266
Neil Booth4f881702007-09-26 21:33:42 +00003267APFloat::APFloat(double d)
3268{
Dale Johannesen3f6eb742007-09-11 18:32:33 +00003269 APInt api = APInt(64, 0);
3270 initFromAPInt(api.doubleToBits(d));
3271}
John McCall00e65de2009-12-24 08:56:26 +00003272
3273namespace {
3274 static void append(SmallVectorImpl<char> &Buffer,
3275 unsigned N, const char *Str) {
3276 unsigned Start = Buffer.size();
3277 Buffer.set_size(Start + N);
3278 memcpy(&Buffer[Start], Str, N);
3279 }
3280
3281 template <unsigned N>
3282 void append(SmallVectorImpl<char> &Buffer, const char (&Str)[N]) {
3283 append(Buffer, N, Str);
3284 }
3285
John McCall003a09c2009-12-24 12:16:56 +00003286 /// Removes data from the given significand until it is no more
3287 /// precise than is required for the desired precision.
3288 void AdjustToPrecision(APInt &significand,
3289 int &exp, unsigned FormatPrecision) {
3290 unsigned bits = significand.getActiveBits();
3291
3292 // 196/59 is a very slight overestimate of lg_2(10).
3293 unsigned bitsRequired = (FormatPrecision * 196 + 58) / 59;
3294
3295 if (bits <= bitsRequired) return;
3296
3297 unsigned tensRemovable = (bits - bitsRequired) * 59 / 196;
3298 if (!tensRemovable) return;
3299
3300 exp += tensRemovable;
3301
3302 APInt divisor(significand.getBitWidth(), 1);
3303 APInt powten(significand.getBitWidth(), 10);
3304 while (true) {
3305 if (tensRemovable & 1)
3306 divisor *= powten;
3307 tensRemovable >>= 1;
3308 if (!tensRemovable) break;
3309 powten *= powten;
3310 }
3311
3312 significand = significand.udiv(divisor);
3313
3314 // Truncate the significand down to its active bit count, but
3315 // don't try to drop below 32.
John McCall6a09aff2009-12-24 23:18:09 +00003316 unsigned newPrecision = std::max(32U, significand.getActiveBits());
John McCall003a09c2009-12-24 12:16:56 +00003317 significand.trunc(newPrecision);
3318 }
3319
3320
John McCall00e65de2009-12-24 08:56:26 +00003321 void AdjustToPrecision(SmallVectorImpl<char> &buffer,
3322 int &exp, unsigned FormatPrecision) {
3323 unsigned N = buffer.size();
3324 if (N <= FormatPrecision) return;
3325
3326 // The most significant figures are the last ones in the buffer.
3327 unsigned FirstSignificant = N - FormatPrecision;
3328
3329 // Round.
3330 // FIXME: this probably shouldn't use 'round half up'.
3331
3332 // Rounding down is just a truncation, except we also want to drop
3333 // trailing zeros from the new result.
3334 if (buffer[FirstSignificant - 1] < '5') {
3335 while (buffer[FirstSignificant] == '0')
3336 FirstSignificant++;
3337
3338 exp += FirstSignificant;
3339 buffer.erase(&buffer[0], &buffer[FirstSignificant]);
3340 return;
3341 }
3342
3343 // Rounding up requires a decimal add-with-carry. If we continue
3344 // the carry, the newly-introduced zeros will just be truncated.
3345 for (unsigned I = FirstSignificant; I != N; ++I) {
3346 if (buffer[I] == '9') {
3347 FirstSignificant++;
3348 } else {
3349 buffer[I]++;
3350 break;
3351 }
3352 }
3353
3354 // If we carried through, we have exactly one digit of precision.
3355 if (FirstSignificant == N) {
3356 exp += FirstSignificant;
3357 buffer.clear();
3358 buffer.push_back('1');
3359 return;
3360 }
3361
3362 exp += FirstSignificant;
3363 buffer.erase(&buffer[0], &buffer[FirstSignificant]);
3364 }
3365}
3366
3367void APFloat::toString(SmallVectorImpl<char> &Str,
3368 unsigned FormatPrecision,
3369 unsigned FormatMaxPadding) {
3370 switch (category) {
3371 case fcInfinity:
3372 if (isNegative())
3373 return append(Str, "-Inf");
3374 else
3375 return append(Str, "+Inf");
3376
3377 case fcNaN: return append(Str, "NaN");
3378
3379 case fcZero:
3380 if (isNegative())
3381 Str.push_back('-');
3382
3383 if (!FormatMaxPadding)
3384 append(Str, "0.0E+0");
3385 else
3386 Str.push_back('0');
3387 return;
3388
3389 case fcNormal:
3390 break;
3391 }
3392
3393 if (isNegative())
3394 Str.push_back('-');
3395
3396 // Decompose the number into an APInt and an exponent.
3397 int exp = exponent - ((int) semantics->precision - 1);
3398 APInt significand(semantics->precision,
3399 partCountForBits(semantics->precision),
3400 significandParts());
3401
John McCall6a09aff2009-12-24 23:18:09 +00003402 // Set FormatPrecision if zero. We want to do this before we
3403 // truncate trailing zeros, as those are part of the precision.
3404 if (!FormatPrecision) {
3405 // It's an interesting question whether to use the nominal
3406 // precision or the active precision here for denormals.
3407
3408 // FormatPrecision = ceil(significandBits / lg_2(10))
3409 FormatPrecision = (semantics->precision * 59 + 195) / 196;
3410 }
3411
John McCall00e65de2009-12-24 08:56:26 +00003412 // Ignore trailing binary zeros.
3413 int trailingZeros = significand.countTrailingZeros();
3414 exp += trailingZeros;
3415 significand = significand.lshr(trailingZeros);
3416
3417 // Change the exponent from 2^e to 10^e.
3418 if (exp == 0) {
3419 // Nothing to do.
3420 } else if (exp > 0) {
3421 // Just shift left.
3422 significand.zext(semantics->precision + exp);
3423 significand <<= exp;
3424 exp = 0;
3425 } else { /* exp < 0 */
3426 int texp = -exp;
3427
3428 // We transform this using the identity:
3429 // (N)(2^-e) == (N)(5^e)(10^-e)
3430 // This means we have to multiply N (the significand) by 5^e.
3431 // To avoid overflow, we have to operate on numbers large
3432 // enough to store N * 5^e:
3433 // log2(N * 5^e) == log2(N) + e * log2(5)
John McCall6a09aff2009-12-24 23:18:09 +00003434 // <= semantics->precision + e * 137 / 59
3435 // (log_2(5) ~ 2.321928 < 2.322034 ~ 137/59)
3436
3437 unsigned precision = semantics->precision + 137 * texp / 59;
John McCall00e65de2009-12-24 08:56:26 +00003438
3439 // Multiply significand by 5^e.
3440 // N * 5^0101 == N * 5^(1*1) * 5^(0*2) * 5^(1*4) * 5^(0*8)
3441 significand.zext(precision);
3442 APInt five_to_the_i(precision, 5);
3443 while (true) {
3444 if (texp & 1) significand *= five_to_the_i;
3445
3446 texp >>= 1;
3447 if (!texp) break;
3448 five_to_the_i *= five_to_the_i;
3449 }
3450 }
3451
John McCall003a09c2009-12-24 12:16:56 +00003452 AdjustToPrecision(significand, exp, FormatPrecision);
3453
John McCall00e65de2009-12-24 08:56:26 +00003454 llvm::SmallVector<char, 256> buffer;
3455
3456 // Fill the buffer.
3457 unsigned precision = significand.getBitWidth();
3458 APInt ten(precision, 10);
3459 APInt digit(precision, 0);
3460
3461 bool inTrail = true;
3462 while (significand != 0) {
3463 // digit <- significand % 10
3464 // significand <- significand / 10
3465 APInt::udivrem(significand, ten, significand, digit);
3466
3467 unsigned d = digit.getZExtValue();
3468
3469 // Drop trailing zeros.
3470 if (inTrail && !d) exp++;
3471 else {
3472 buffer.push_back((char) ('0' + d));
3473 inTrail = false;
3474 }
3475 }
3476
3477 assert(!buffer.empty() && "no characters in buffer!");
3478
3479 // Drop down to FormatPrecision.
3480 // TODO: don't do more precise calculations above than are required.
3481 AdjustToPrecision(buffer, exp, FormatPrecision);
3482
3483 unsigned NDigits = buffer.size();
3484
John McCall6a09aff2009-12-24 23:18:09 +00003485 // Check whether we should use scientific notation.
John McCall00e65de2009-12-24 08:56:26 +00003486 bool FormatScientific;
3487 if (!FormatMaxPadding)
3488 FormatScientific = true;
3489 else {
John McCall00e65de2009-12-24 08:56:26 +00003490 if (exp >= 0) {
John McCall6a09aff2009-12-24 23:18:09 +00003491 // 765e3 --> 765000
3492 // ^^^
3493 // But we shouldn't make the number look more precise than it is.
3494 FormatScientific = ((unsigned) exp > FormatMaxPadding ||
3495 NDigits + (unsigned) exp > FormatPrecision);
John McCall00e65de2009-12-24 08:56:26 +00003496 } else {
John McCall6a09aff2009-12-24 23:18:09 +00003497 // Power of the most significant digit.
3498 int MSD = exp + (int) (NDigits - 1);
3499 if (MSD >= 0) {
John McCall00e65de2009-12-24 08:56:26 +00003500 // 765e-2 == 7.65
John McCall6a09aff2009-12-24 23:18:09 +00003501 FormatScientific = false;
John McCall00e65de2009-12-24 08:56:26 +00003502 } else {
3503 // 765e-5 == 0.00765
3504 // ^ ^^
John McCall6a09aff2009-12-24 23:18:09 +00003505 FormatScientific = ((unsigned) -MSD) > FormatMaxPadding;
John McCall00e65de2009-12-24 08:56:26 +00003506 }
3507 }
John McCall00e65de2009-12-24 08:56:26 +00003508 }
3509
3510 // Scientific formatting is pretty straightforward.
3511 if (FormatScientific) {
3512 exp += (NDigits - 1);
3513
3514 Str.push_back(buffer[NDigits-1]);
3515 Str.push_back('.');
3516 if (NDigits == 1)
3517 Str.push_back('0');
3518 else
3519 for (unsigned I = 1; I != NDigits; ++I)
3520 Str.push_back(buffer[NDigits-1-I]);
3521 Str.push_back('E');
3522
3523 Str.push_back(exp >= 0 ? '+' : '-');
3524 if (exp < 0) exp = -exp;
3525 SmallVector<char, 6> expbuf;
3526 do {
3527 expbuf.push_back((char) ('0' + (exp % 10)));
3528 exp /= 10;
3529 } while (exp);
3530 for (unsigned I = 0, E = expbuf.size(); I != E; ++I)
3531 Str.push_back(expbuf[E-1-I]);
3532 return;
3533 }
3534
3535 // Non-scientific, positive exponents.
3536 if (exp >= 0) {
3537 for (unsigned I = 0; I != NDigits; ++I)
3538 Str.push_back(buffer[NDigits-1-I]);
3539 for (unsigned I = 0; I != (unsigned) exp; ++I)
3540 Str.push_back('0');
3541 return;
3542 }
3543
3544 // Non-scientific, negative exponents.
3545
3546 // The number of digits to the left of the decimal point.
3547 int NWholeDigits = exp + (int) NDigits;
3548
3549 unsigned I = 0;
3550 if (NWholeDigits > 0) {
3551 for (; I != (unsigned) NWholeDigits; ++I)
3552 Str.push_back(buffer[NDigits-I-1]);
3553 Str.push_back('.');
3554 } else {
3555 unsigned NZeros = 1 + (unsigned) -NWholeDigits;
3556
3557 Str.push_back('0');
3558 Str.push_back('.');
3559 for (unsigned Z = 1; Z != NZeros; ++Z)
3560 Str.push_back('0');
3561 }
3562
3563 for (; I != NDigits; ++I)
3564 Str.push_back(buffer[NDigits-I-1]);
3565}