blob: 6182e3415005253a5dcd426cd179a508454c98c2 [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"
Jeffrey Yasskin3d42bfb2011-07-15 07:04:56 +000016#include "llvm/ADT/APSInt.h"
Ted Kremenek1f801fa2008-02-11 17:24:50 +000017#include "llvm/ADT/FoldingSet.h"
Chandler Carruthed7692a2012-03-04 12:02:57 +000018#include "llvm/ADT/Hashing.h"
Jordan Rose8a53a832013-01-18 21:45:30 +000019#include "llvm/ADT/StringExtras.h"
Chandler Carruthed7692a2012-03-04 12:02:57 +000020#include "llvm/ADT/StringRef.h"
Torok Edwinc25e7582009-07-11 20:10:48 +000021#include "llvm/Support/ErrorHandling.h"
Dale Johannesend3b51fd2007-08-24 05:08:11 +000022#include "llvm/Support/MathExtras.h"
Chris Lattnerfad86b02008-08-17 07:19:36 +000023#include <cstring>
Chandler Carruthd04a8d42012-12-03 16:50:05 +000024#include <limits.h>
Chris Lattnerb39cdde2007-08-20 22:49:32 +000025
26using namespace llvm;
27
28#define convolve(lhs, rhs) ((lhs) * 4 + (rhs))
29
Neil Bootha30b0ee2007-10-03 22:26:02 +000030/* Assumed in hexadecimal significand parsing, and conversion to
31 hexadecimal strings. */
Chris Lattner9f17eb02008-08-17 04:58:58 +000032#define COMPILE_TIME_ASSERT(cond) extern int CTAssert[(cond) ? 1 : -1]
Chris Lattnerb39cdde2007-08-20 22:49:32 +000033COMPILE_TIME_ASSERT(integerPartWidth % 4 == 0);
34
35namespace llvm {
36
37 /* Represents floating point arithmetic semantics. */
38 struct fltSemantics {
39 /* The largest E such that 2^E is representable; this matches the
40 definition of IEEE 754. */
41 exponent_t maxExponent;
42
43 /* The smallest E such that 2^E is a normalized number; this
44 matches the definition of IEEE 754. */
45 exponent_t minExponent;
46
47 /* Number of bits in the significand. This includes the integer
48 bit. */
Neil Booth7a951ca2007-10-12 15:33:27 +000049 unsigned int precision;
Chris Lattnerb39cdde2007-08-20 22:49:32 +000050 };
51
Ulrich Weigand159c7352012-10-29 18:18:44 +000052 const fltSemantics APFloat::IEEEhalf = { 15, -14, 11 };
53 const fltSemantics APFloat::IEEEsingle = { 127, -126, 24 };
54 const fltSemantics APFloat::IEEEdouble = { 1023, -1022, 53 };
55 const fltSemantics APFloat::IEEEquad = { 16383, -16382, 113 };
56 const fltSemantics APFloat::x87DoubleExtended = { 16383, -16382, 64 };
57 const fltSemantics APFloat::Bogus = { 0, 0, 0 };
Dale Johannesena471c2e2007-10-11 18:07:22 +000058
Ulrich Weigand69c9c8c2012-10-29 18:09:01 +000059 /* The PowerPC format consists of two doubles. It does not map cleanly
60 onto the usual format above. It is approximated using twice the
61 mantissa bits. Note that for exponents near the double minimum,
62 we no longer can represent the full 106 mantissa bits, so those
63 will be treated as denormal numbers.
64
65 FIXME: While this approximation is equivalent to what GCC uses for
66 compile-time arithmetic on PPC double-double numbers, it is not able
67 to represent all possible values held by a PPC double-double number,
68 for example: (long double) 1.0 + (long double) 0x1p-106
69 Should this be replaced by a full emulation of PPC double-double? */
Ulrich Weigand159c7352012-10-29 18:18:44 +000070 const fltSemantics APFloat::PPCDoubleDouble = { 1023, -1022 + 53, 53 + 53 };
Neil Booth96c74712007-10-12 16:02:31 +000071
72 /* A tight upper bound on number of parts required to hold the value
73 pow(5, power) is
74
Neil Booth686700e2007-10-15 15:00:55 +000075 power * 815 / (351 * integerPartWidth) + 1
Dan Gohman16e02092010-03-24 19:38:02 +000076
Neil Booth96c74712007-10-12 16:02:31 +000077 However, whilst the result may require only this many parts,
78 because we are multiplying two values to get it, the
79 multiplication may require an extra part with the excess part
80 being zero (consider the trivial case of 1 * 1, tcFullMultiply
81 requires two parts to hold the single-part result). So we add an
82 extra one to guarantee enough space whilst multiplying. */
83 const unsigned int maxExponent = 16383;
84 const unsigned int maxPrecision = 113;
85 const unsigned int maxPowerOfFiveExponent = maxExponent + maxPrecision - 1;
Neil Booth686700e2007-10-15 15:00:55 +000086 const unsigned int maxPowerOfFiveParts = 2 + ((maxPowerOfFiveExponent * 815)
87 / (351 * integerPartWidth));
Chris Lattnerb39cdde2007-08-20 22:49:32 +000088}
89
Chris Lattnere213f3f2009-03-12 23:59:55 +000090/* A bunch of private, handy routines. */
Chris Lattnerb39cdde2007-08-20 22:49:32 +000091
Chris Lattnere213f3f2009-03-12 23:59:55 +000092static inline unsigned int
93partCountForBits(unsigned int bits)
94{
95 return ((bits) + integerPartWidth - 1) / integerPartWidth;
96}
Chris Lattnerb39cdde2007-08-20 22:49:32 +000097
Chris Lattnere213f3f2009-03-12 23:59:55 +000098/* Returns 0U-9U. Return values >= 10U are not digits. */
99static inline unsigned int
100decDigitValue(unsigned int c)
101{
102 return c - '0';
103}
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000104
Chris Lattnere213f3f2009-03-12 23:59:55 +0000105/* Return the value of a decimal exponent of the form
106 [+-]ddddddd.
Neil Booth1870f292007-10-14 10:16:12 +0000107
Chris Lattnere213f3f2009-03-12 23:59:55 +0000108 If the exponent overflows, returns a large exponent with the
109 appropriate sign. */
110static int
Erick Tryzelaara15d8902009-08-16 23:36:19 +0000111readExponent(StringRef::iterator begin, StringRef::iterator end)
Chris Lattnere213f3f2009-03-12 23:59:55 +0000112{
113 bool isNegative;
114 unsigned int absExponent;
115 const unsigned int overlargeExponent = 24000; /* FIXME. */
Erick Tryzelaara15d8902009-08-16 23:36:19 +0000116 StringRef::iterator p = begin;
117
118 assert(p != end && "Exponent has no digits");
Neil Booth1870f292007-10-14 10:16:12 +0000119
Chris Lattnere213f3f2009-03-12 23:59:55 +0000120 isNegative = (*p == '-');
Erick Tryzelaara15d8902009-08-16 23:36:19 +0000121 if (*p == '-' || *p == '+') {
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000122 p++;
Erick Tryzelaara15d8902009-08-16 23:36:19 +0000123 assert(p != end && "Exponent has no digits");
124 }
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000125
Chris Lattnere213f3f2009-03-12 23:59:55 +0000126 absExponent = decDigitValue(*p++);
Erick Tryzelaara15d8902009-08-16 23:36:19 +0000127 assert(absExponent < 10U && "Invalid character in exponent");
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000128
Erick Tryzelaara15d8902009-08-16 23:36:19 +0000129 for (; p != end; ++p) {
Chris Lattnere213f3f2009-03-12 23:59:55 +0000130 unsigned int value;
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000131
Chris Lattnere213f3f2009-03-12 23:59:55 +0000132 value = decDigitValue(*p);
Erick Tryzelaara15d8902009-08-16 23:36:19 +0000133 assert(value < 10U && "Invalid character in exponent");
Chris Lattnere213f3f2009-03-12 23:59:55 +0000134
Chris Lattnere213f3f2009-03-12 23:59:55 +0000135 value += absExponent * 10;
136 if (absExponent >= overlargeExponent) {
137 absExponent = overlargeExponent;
Dale Johannesenb1508d12010-08-19 17:58:35 +0000138 p = end; /* outwit assert below */
Chris Lattnere213f3f2009-03-12 23:59:55 +0000139 break;
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000140 }
Chris Lattnere213f3f2009-03-12 23:59:55 +0000141 absExponent = value;
142 }
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000143
Erick Tryzelaara15d8902009-08-16 23:36:19 +0000144 assert(p == end && "Invalid exponent in exponent");
145
Chris Lattnere213f3f2009-03-12 23:59:55 +0000146 if (isNegative)
147 return -(int) absExponent;
148 else
149 return (int) absExponent;
150}
151
152/* This is ugly and needs cleaning up, but I don't immediately see
153 how whilst remaining safe. */
154static int
Erick Tryzelaara15d8902009-08-16 23:36:19 +0000155totalExponent(StringRef::iterator p, StringRef::iterator end,
156 int exponentAdjustment)
Chris Lattnere213f3f2009-03-12 23:59:55 +0000157{
158 int unsignedExponent;
159 bool negative, overflow;
Ted Kremenek584520e2011-01-23 17:05:06 +0000160 int exponent = 0;
Chris Lattnere213f3f2009-03-12 23:59:55 +0000161
Erick Tryzelaarc78b33b2009-08-20 23:30:43 +0000162 assert(p != end && "Exponent has no digits");
163
Chris Lattnere213f3f2009-03-12 23:59:55 +0000164 negative = *p == '-';
Dan Gohman16e02092010-03-24 19:38:02 +0000165 if (*p == '-' || *p == '+') {
Chris Lattnere213f3f2009-03-12 23:59:55 +0000166 p++;
Erick Tryzelaarc78b33b2009-08-20 23:30:43 +0000167 assert(p != end && "Exponent has no digits");
168 }
Chris Lattnere213f3f2009-03-12 23:59:55 +0000169
170 unsignedExponent = 0;
171 overflow = false;
Dan Gohman16e02092010-03-24 19:38:02 +0000172 for (; p != end; ++p) {
Chris Lattnere213f3f2009-03-12 23:59:55 +0000173 unsigned int value;
174
175 value = decDigitValue(*p);
Erick Tryzelaara15d8902009-08-16 23:36:19 +0000176 assert(value < 10U && "Invalid character in exponent");
Chris Lattnere213f3f2009-03-12 23:59:55 +0000177
Chris Lattnere213f3f2009-03-12 23:59:55 +0000178 unsignedExponent = unsignedExponent * 10 + value;
Richard Smithb080e2f2012-08-24 00:01:19 +0000179 if (unsignedExponent > 32767) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000180 overflow = true;
Richard Smithb080e2f2012-08-24 00:01:19 +0000181 break;
182 }
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000183 }
184
Abramo Bagnara4bb46f42011-01-06 16:55:14 +0000185 if (exponentAdjustment > 32767 || exponentAdjustment < -32768)
Chris Lattnere213f3f2009-03-12 23:59:55 +0000186 overflow = true;
187
Dan Gohman16e02092010-03-24 19:38:02 +0000188 if (!overflow) {
Chris Lattnere213f3f2009-03-12 23:59:55 +0000189 exponent = unsignedExponent;
Dan Gohman16e02092010-03-24 19:38:02 +0000190 if (negative)
Chris Lattnere213f3f2009-03-12 23:59:55 +0000191 exponent = -exponent;
192 exponent += exponentAdjustment;
Abramo Bagnara4bb46f42011-01-06 16:55:14 +0000193 if (exponent > 32767 || exponent < -32768)
Chris Lattnere213f3f2009-03-12 23:59:55 +0000194 overflow = true;
195 }
196
Dan Gohman16e02092010-03-24 19:38:02 +0000197 if (overflow)
Abramo Bagnara4bb46f42011-01-06 16:55:14 +0000198 exponent = negative ? -32768: 32767;
Chris Lattnere213f3f2009-03-12 23:59:55 +0000199
200 return exponent;
201}
202
Erick Tryzelaara15d8902009-08-16 23:36:19 +0000203static StringRef::iterator
204skipLeadingZeroesAndAnyDot(StringRef::iterator begin, StringRef::iterator end,
205 StringRef::iterator *dot)
Chris Lattnere213f3f2009-03-12 23:59:55 +0000206{
Erick Tryzelaara15d8902009-08-16 23:36:19 +0000207 StringRef::iterator p = begin;
208 *dot = end;
Dan Gohman16e02092010-03-24 19:38:02 +0000209 while (*p == '0' && p != end)
Chris Lattnere213f3f2009-03-12 23:59:55 +0000210 p++;
211
Dan Gohman16e02092010-03-24 19:38:02 +0000212 if (*p == '.') {
Chris Lattnere213f3f2009-03-12 23:59:55 +0000213 *dot = p++;
Erick Tryzelaara15d8902009-08-16 23:36:19 +0000214
Erick Tryzelaarc78b33b2009-08-20 23:30:43 +0000215 assert(end - begin != 1 && "Significand has no digits");
Erick Tryzelaara15d8902009-08-16 23:36:19 +0000216
Dan Gohman16e02092010-03-24 19:38:02 +0000217 while (*p == '0' && p != end)
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000218 p++;
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000219 }
220
Chris Lattnere213f3f2009-03-12 23:59:55 +0000221 return p;
222}
Neil Booth1870f292007-10-14 10:16:12 +0000223
Chris Lattnere213f3f2009-03-12 23:59:55 +0000224/* Given a normal decimal floating point number of the form
Neil Booth1870f292007-10-14 10:16:12 +0000225
Chris Lattnere213f3f2009-03-12 23:59:55 +0000226 dddd.dddd[eE][+-]ddd
Neil Booth686700e2007-10-15 15:00:55 +0000227
Chris Lattnere213f3f2009-03-12 23:59:55 +0000228 where the decimal point and exponent are optional, fill out the
229 structure D. Exponent is appropriate if the significand is
230 treated as an integer, and normalizedExponent if the significand
231 is taken to have the decimal point after a single leading
232 non-zero digit.
Neil Booth1870f292007-10-14 10:16:12 +0000233
Chris Lattnere213f3f2009-03-12 23:59:55 +0000234 If the value is zero, V->firstSigDigit points to a non-digit, and
235 the return exponent is zero.
236*/
237struct decimalInfo {
238 const char *firstSigDigit;
239 const char *lastSigDigit;
240 int exponent;
241 int normalizedExponent;
242};
Neil Booth1870f292007-10-14 10:16:12 +0000243
Chris Lattnere213f3f2009-03-12 23:59:55 +0000244static void
Erick Tryzelaara15d8902009-08-16 23:36:19 +0000245interpretDecimal(StringRef::iterator begin, StringRef::iterator end,
246 decimalInfo *D)
Chris Lattnere213f3f2009-03-12 23:59:55 +0000247{
Erick Tryzelaara15d8902009-08-16 23:36:19 +0000248 StringRef::iterator dot = end;
249 StringRef::iterator p = skipLeadingZeroesAndAnyDot (begin, end, &dot);
Neil Booth1870f292007-10-14 10:16:12 +0000250
Chris Lattnere213f3f2009-03-12 23:59:55 +0000251 D->firstSigDigit = p;
252 D->exponent = 0;
253 D->normalizedExponent = 0;
254
Erick Tryzelaara15d8902009-08-16 23:36:19 +0000255 for (; p != end; ++p) {
Chris Lattnere213f3f2009-03-12 23:59:55 +0000256 if (*p == '.') {
Erick Tryzelaarc78b33b2009-08-20 23:30:43 +0000257 assert(dot == end && "String contains multiple dots");
Chris Lattnere213f3f2009-03-12 23:59:55 +0000258 dot = p++;
Erick Tryzelaara15d8902009-08-16 23:36:19 +0000259 if (p == end)
260 break;
Neil Booth1870f292007-10-14 10:16:12 +0000261 }
Chris Lattnere213f3f2009-03-12 23:59:55 +0000262 if (decDigitValue(*p) >= 10U)
263 break;
Chris Lattnere213f3f2009-03-12 23:59:55 +0000264 }
Neil Booth1870f292007-10-14 10:16:12 +0000265
Erick Tryzelaara15d8902009-08-16 23:36:19 +0000266 if (p != end) {
Erick Tryzelaarc78b33b2009-08-20 23:30:43 +0000267 assert((*p == 'e' || *p == 'E') && "Invalid character in significand");
268 assert(p != begin && "Significand has no digits");
269 assert((dot == end || p - begin != 1) && "Significand has no digits");
Erick Tryzelaara15d8902009-08-16 23:36:19 +0000270
271 /* p points to the first non-digit in the string */
Erick Tryzelaarc78b33b2009-08-20 23:30:43 +0000272 D->exponent = readExponent(p + 1, end);
Neil Booth1870f292007-10-14 10:16:12 +0000273
Chris Lattnere213f3f2009-03-12 23:59:55 +0000274 /* Implied decimal point? */
Erick Tryzelaara15d8902009-08-16 23:36:19 +0000275 if (dot == end)
Chris Lattnere213f3f2009-03-12 23:59:55 +0000276 dot = p;
Erick Tryzelaara15d8902009-08-16 23:36:19 +0000277 }
Neil Booth1870f292007-10-14 10:16:12 +0000278
Erick Tryzelaara15d8902009-08-16 23:36:19 +0000279 /* If number is all zeroes accept any exponent. */
280 if (p != D->firstSigDigit) {
Chris Lattnere213f3f2009-03-12 23:59:55 +0000281 /* Drop insignificant trailing zeroes. */
Erick Tryzelaara15d8902009-08-16 23:36:19 +0000282 if (p != begin) {
Neil Booth1870f292007-10-14 10:16:12 +0000283 do
Erick Tryzelaara15d8902009-08-16 23:36:19 +0000284 do
285 p--;
286 while (p != begin && *p == '0');
287 while (p != begin && *p == '.');
288 }
Neil Booth1870f292007-10-14 10:16:12 +0000289
Chris Lattnere213f3f2009-03-12 23:59:55 +0000290 /* Adjust the exponents for any decimal point. */
291 D->exponent += static_cast<exponent_t>((dot - p) - (dot > p));
292 D->normalizedExponent = (D->exponent +
293 static_cast<exponent_t>((p - D->firstSigDigit)
294 - (dot > D->firstSigDigit && dot < p)));
Neil Booth1870f292007-10-14 10:16:12 +0000295 }
296
Chris Lattnere213f3f2009-03-12 23:59:55 +0000297 D->lastSigDigit = p;
298}
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000299
Chris Lattnere213f3f2009-03-12 23:59:55 +0000300/* Return the trailing fraction of a hexadecimal number.
301 DIGITVALUE is the first hex digit of the fraction, P points to
302 the next digit. */
303static lostFraction
Erick Tryzelaara15d8902009-08-16 23:36:19 +0000304trailingHexadecimalFraction(StringRef::iterator p, StringRef::iterator end,
305 unsigned int digitValue)
Chris Lattnere213f3f2009-03-12 23:59:55 +0000306{
307 unsigned int hexDigit;
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000308
Chris Lattnere213f3f2009-03-12 23:59:55 +0000309 /* If the first trailing digit isn't 0 or 8 we can work out the
310 fraction immediately. */
Dan Gohman16e02092010-03-24 19:38:02 +0000311 if (digitValue > 8)
Chris Lattnere213f3f2009-03-12 23:59:55 +0000312 return lfMoreThanHalf;
Dan Gohman16e02092010-03-24 19:38:02 +0000313 else if (digitValue < 8 && digitValue > 0)
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000314 return lfLessThanHalf;
Chris Lattnere213f3f2009-03-12 23:59:55 +0000315
316 /* Otherwise we need to find the first non-zero digit. */
Dan Gohman16e02092010-03-24 19:38:02 +0000317 while (*p == '0')
Chris Lattnere213f3f2009-03-12 23:59:55 +0000318 p++;
319
Erick Tryzelaara15d8902009-08-16 23:36:19 +0000320 assert(p != end && "Invalid trailing hexadecimal fraction!");
321
Chris Lattnere213f3f2009-03-12 23:59:55 +0000322 hexDigit = hexDigitValue(*p);
323
324 /* If we ran off the end it is exactly zero or one-half, otherwise
325 a little more. */
Dan Gohman16e02092010-03-24 19:38:02 +0000326 if (hexDigit == -1U)
Chris Lattnere213f3f2009-03-12 23:59:55 +0000327 return digitValue == 0 ? lfExactlyZero: lfExactlyHalf;
328 else
329 return digitValue == 0 ? lfLessThanHalf: lfMoreThanHalf;
330}
331
332/* Return the fraction lost were a bignum truncated losing the least
333 significant BITS bits. */
334static lostFraction
335lostFractionThroughTruncation(const integerPart *parts,
336 unsigned int partCount,
337 unsigned int bits)
338{
339 unsigned int lsb;
340
341 lsb = APInt::tcLSB(parts, partCount);
342
343 /* Note this is guaranteed true if bits == 0, or LSB == -1U. */
Dan Gohman16e02092010-03-24 19:38:02 +0000344 if (bits <= lsb)
Chris Lattnere213f3f2009-03-12 23:59:55 +0000345 return lfExactlyZero;
Dan Gohman16e02092010-03-24 19:38:02 +0000346 if (bits == lsb + 1)
Chris Lattnere213f3f2009-03-12 23:59:55 +0000347 return lfExactlyHalf;
Dan Gohman16e02092010-03-24 19:38:02 +0000348 if (bits <= partCount * integerPartWidth &&
349 APInt::tcExtractBit(parts, bits - 1))
Chris Lattnere213f3f2009-03-12 23:59:55 +0000350 return lfMoreThanHalf;
351
352 return lfLessThanHalf;
353}
354
355/* Shift DST right BITS bits noting lost fraction. */
356static lostFraction
357shiftRight(integerPart *dst, unsigned int parts, unsigned int bits)
358{
359 lostFraction lost_fraction;
360
361 lost_fraction = lostFractionThroughTruncation(dst, parts, bits);
362
363 APInt::tcShiftRight(dst, parts, bits);
364
365 return lost_fraction;
366}
367
368/* Combine the effect of two lost fractions. */
369static lostFraction
370combineLostFractions(lostFraction moreSignificant,
371 lostFraction lessSignificant)
372{
Dan Gohman16e02092010-03-24 19:38:02 +0000373 if (lessSignificant != lfExactlyZero) {
374 if (moreSignificant == lfExactlyZero)
Chris Lattnere213f3f2009-03-12 23:59:55 +0000375 moreSignificant = lfLessThanHalf;
Dan Gohman16e02092010-03-24 19:38:02 +0000376 else if (moreSignificant == lfExactlyHalf)
Chris Lattnere213f3f2009-03-12 23:59:55 +0000377 moreSignificant = lfMoreThanHalf;
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000378 }
379
Chris Lattnere213f3f2009-03-12 23:59:55 +0000380 return moreSignificant;
381}
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000382
Chris Lattnere213f3f2009-03-12 23:59:55 +0000383/* The error from the true value, in half-ulps, on multiplying two
384 floating point numbers, which differ from the value they
385 approximate by at most HUE1 and HUE2 half-ulps, is strictly less
386 than the returned value.
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000387
Chris Lattnere213f3f2009-03-12 23:59:55 +0000388 See "How to Read Floating Point Numbers Accurately" by William D
389 Clinger. */
390static unsigned int
391HUerrBound(bool inexactMultiply, unsigned int HUerr1, unsigned int HUerr2)
392{
393 assert(HUerr1 < 2 || HUerr2 < 2 || (HUerr1 + HUerr2 < 8));
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000394
Chris Lattnere213f3f2009-03-12 23:59:55 +0000395 if (HUerr1 + HUerr2 == 0)
396 return inexactMultiply * 2; /* <= inexactMultiply half-ulps. */
397 else
398 return inexactMultiply + 2 * (HUerr1 + HUerr2);
399}
Neil Bootha30b0ee2007-10-03 22:26:02 +0000400
Chris Lattnere213f3f2009-03-12 23:59:55 +0000401/* The number of ulps from the boundary (zero, or half if ISNEAREST)
402 when the least significant BITS are truncated. BITS cannot be
403 zero. */
404static integerPart
405ulpsFromBoundary(const integerPart *parts, unsigned int bits, bool isNearest)
406{
407 unsigned int count, partBits;
408 integerPart part, boundary;
Neil Booth33d4c922007-10-07 08:51:21 +0000409
Evan Cheng99ebfa52009-10-27 21:35:42 +0000410 assert(bits != 0);
Neil Bootha30b0ee2007-10-03 22:26:02 +0000411
Chris Lattnere213f3f2009-03-12 23:59:55 +0000412 bits--;
413 count = bits / integerPartWidth;
414 partBits = bits % integerPartWidth + 1;
Neil Booth96c74712007-10-12 16:02:31 +0000415
Chris Lattnere213f3f2009-03-12 23:59:55 +0000416 part = parts[count] & (~(integerPart) 0 >> (integerPartWidth - partBits));
Neil Booth96c74712007-10-12 16:02:31 +0000417
Chris Lattnere213f3f2009-03-12 23:59:55 +0000418 if (isNearest)
419 boundary = (integerPart) 1 << (partBits - 1);
420 else
421 boundary = 0;
422
423 if (count == 0) {
424 if (part - boundary <= boundary - part)
425 return part - boundary;
Neil Booth96c74712007-10-12 16:02:31 +0000426 else
Chris Lattnere213f3f2009-03-12 23:59:55 +0000427 return boundary - part;
Neil Booth96c74712007-10-12 16:02:31 +0000428 }
429
Chris Lattnere213f3f2009-03-12 23:59:55 +0000430 if (part == boundary) {
431 while (--count)
432 if (parts[count])
433 return ~(integerPart) 0; /* A lot. */
Neil Booth96c74712007-10-12 16:02:31 +0000434
Chris Lattnere213f3f2009-03-12 23:59:55 +0000435 return parts[0];
436 } else if (part == boundary - 1) {
437 while (--count)
438 if (~parts[count])
439 return ~(integerPart) 0; /* A lot. */
Neil Booth96c74712007-10-12 16:02:31 +0000440
Chris Lattnere213f3f2009-03-12 23:59:55 +0000441 return -parts[0];
442 }
Neil Booth96c74712007-10-12 16:02:31 +0000443
Chris Lattnere213f3f2009-03-12 23:59:55 +0000444 return ~(integerPart) 0; /* A lot. */
445}
Neil Booth96c74712007-10-12 16:02:31 +0000446
Chris Lattnere213f3f2009-03-12 23:59:55 +0000447/* Place pow(5, power) in DST, and return the number of parts used.
448 DST must be at least one part larger than size of the answer. */
449static unsigned int
450powerOf5(integerPart *dst, unsigned int power)
451{
452 static const integerPart firstEightPowers[] = { 1, 5, 25, 125, 625, 3125,
453 15625, 78125 };
Chris Lattneree167a72009-03-13 00:24:01 +0000454 integerPart pow5s[maxPowerOfFiveParts * 2 + 5];
455 pow5s[0] = 78125 * 5;
Dan Gohman16e02092010-03-24 19:38:02 +0000456
Chris Lattner807926a2009-03-13 00:03:51 +0000457 unsigned int partsCount[16] = { 1 };
Chris Lattnere213f3f2009-03-12 23:59:55 +0000458 integerPart scratch[maxPowerOfFiveParts], *p1, *p2, *pow5;
459 unsigned int result;
Chris Lattnere213f3f2009-03-12 23:59:55 +0000460 assert(power <= maxExponent);
461
462 p1 = dst;
463 p2 = scratch;
464
465 *p1 = firstEightPowers[power & 7];
466 power >>= 3;
467
468 result = 1;
469 pow5 = pow5s;
470
471 for (unsigned int n = 0; power; power >>= 1, n++) {
472 unsigned int pc;
473
474 pc = partsCount[n];
475
476 /* Calculate pow(5,pow(2,n+3)) if we haven't yet. */
477 if (pc == 0) {
478 pc = partsCount[n - 1];
479 APInt::tcFullMultiply(pow5, pow5 - pc, pow5 - pc, pc, pc);
480 pc *= 2;
481 if (pow5[pc - 1] == 0)
482 pc--;
483 partsCount[n] = pc;
Neil Booth96c74712007-10-12 16:02:31 +0000484 }
485
Chris Lattnere213f3f2009-03-12 23:59:55 +0000486 if (power & 1) {
487 integerPart *tmp;
Neil Booth96c74712007-10-12 16:02:31 +0000488
Chris Lattnere213f3f2009-03-12 23:59:55 +0000489 APInt::tcFullMultiply(p2, p1, pow5, result, pc);
490 result += pc;
491 if (p2[result - 1] == 0)
492 result--;
Neil Booth96c74712007-10-12 16:02:31 +0000493
Chris Lattnere213f3f2009-03-12 23:59:55 +0000494 /* Now result is in p1 with partsCount parts and p2 is scratch
495 space. */
496 tmp = p1, p1 = p2, p2 = tmp;
Neil Booth96c74712007-10-12 16:02:31 +0000497 }
498
Chris Lattnere213f3f2009-03-12 23:59:55 +0000499 pow5 += pc;
Neil Booth96c74712007-10-12 16:02:31 +0000500 }
501
Chris Lattnere213f3f2009-03-12 23:59:55 +0000502 if (p1 != dst)
503 APInt::tcAssign(dst, p1, result);
Neil Booth96c74712007-10-12 16:02:31 +0000504
Chris Lattnere213f3f2009-03-12 23:59:55 +0000505 return result;
506}
Neil Booth96c74712007-10-12 16:02:31 +0000507
Chris Lattnere213f3f2009-03-12 23:59:55 +0000508/* Zero at the end to avoid modular arithmetic when adding one; used
509 when rounding up during hexadecimal output. */
510static const char hexDigitsLower[] = "0123456789abcdef0";
511static const char hexDigitsUpper[] = "0123456789ABCDEF0";
512static const char infinityL[] = "infinity";
513static const char infinityU[] = "INFINITY";
514static const char NaNL[] = "nan";
515static const char NaNU[] = "NAN";
Neil Booth96c74712007-10-12 16:02:31 +0000516
Chris Lattnere213f3f2009-03-12 23:59:55 +0000517/* Write out an integerPart in hexadecimal, starting with the most
518 significant nibble. Write out exactly COUNT hexdigits, return
519 COUNT. */
520static unsigned int
521partAsHex (char *dst, integerPart part, unsigned int count,
522 const char *hexDigitChars)
523{
524 unsigned int result = count;
Neil Booth96c74712007-10-12 16:02:31 +0000525
Evan Cheng99ebfa52009-10-27 21:35:42 +0000526 assert(count != 0 && count <= integerPartWidth / 4);
Neil Booth96c74712007-10-12 16:02:31 +0000527
Chris Lattnere213f3f2009-03-12 23:59:55 +0000528 part >>= (integerPartWidth - 4 * count);
529 while (count--) {
530 dst[count] = hexDigitChars[part & 0xf];
531 part >>= 4;
Neil Booth96c74712007-10-12 16:02:31 +0000532 }
533
Chris Lattnere213f3f2009-03-12 23:59:55 +0000534 return result;
535}
Neil Bootha30b0ee2007-10-03 22:26:02 +0000536
Chris Lattnere213f3f2009-03-12 23:59:55 +0000537/* Write out an unsigned decimal integer. */
538static char *
539writeUnsignedDecimal (char *dst, unsigned int n)
540{
541 char buff[40], *p;
Neil Bootha30b0ee2007-10-03 22:26:02 +0000542
Chris Lattnere213f3f2009-03-12 23:59:55 +0000543 p = buff;
544 do
545 *p++ = '0' + n % 10;
546 while (n /= 10);
Neil Bootha30b0ee2007-10-03 22:26:02 +0000547
Chris Lattnere213f3f2009-03-12 23:59:55 +0000548 do
549 *dst++ = *--p;
550 while (p != buff);
Neil Bootha30b0ee2007-10-03 22:26:02 +0000551
Chris Lattnere213f3f2009-03-12 23:59:55 +0000552 return dst;
553}
Neil Bootha30b0ee2007-10-03 22:26:02 +0000554
Chris Lattnere213f3f2009-03-12 23:59:55 +0000555/* Write out a signed decimal integer. */
556static char *
557writeSignedDecimal (char *dst, int value)
558{
559 if (value < 0) {
560 *dst++ = '-';
561 dst = writeUnsignedDecimal(dst, -(unsigned) value);
562 } else
563 dst = writeUnsignedDecimal(dst, value);
Neil Bootha30b0ee2007-10-03 22:26:02 +0000564
Chris Lattnere213f3f2009-03-12 23:59:55 +0000565 return dst;
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000566}
567
568/* Constructors. */
569void
570APFloat::initialize(const fltSemantics *ourSemantics)
571{
572 unsigned int count;
573
574 semantics = ourSemantics;
575 count = partCount();
Dan Gohman16e02092010-03-24 19:38:02 +0000576 if (count > 1)
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000577 significand.parts = new integerPart[count];
578}
579
580void
581APFloat::freeSignificand()
582{
Dan Gohman16e02092010-03-24 19:38:02 +0000583 if (partCount() > 1)
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000584 delete [] significand.parts;
585}
586
587void
588APFloat::assign(const APFloat &rhs)
589{
590 assert(semantics == rhs.semantics);
591
592 sign = rhs.sign;
593 category = rhs.category;
594 exponent = rhs.exponent;
Dan Gohman16e02092010-03-24 19:38:02 +0000595 if (category == fcNormal || category == fcNaN)
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000596 copySignificand(rhs);
597}
598
599void
600APFloat::copySignificand(const APFloat &rhs)
601{
Dale Johanneseneaf08942007-08-31 04:03:46 +0000602 assert(category == fcNormal || category == fcNaN);
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000603 assert(rhs.partCount() >= partCount());
604
605 APInt::tcAssign(significandParts(), rhs.significandParts(),
Neil Booth4f881702007-09-26 21:33:42 +0000606 partCount());
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000607}
608
Neil Boothe5e01942007-10-14 10:39:51 +0000609/* Make this number a NaN, with an arbitrary but deterministic value
Dale Johannesen541ed9f2009-01-21 20:32:55 +0000610 for the significand. If double or longer, this is a signalling NaN,
Mike Stumpc5ca7132009-05-30 03:49:43 +0000611 which may not be ideal. If float, this is QNaN(0). */
John McCalle12b7382010-02-28 02:51:25 +0000612void APFloat::makeNaN(bool SNaN, bool Negative, const APInt *fill)
Neil Boothe5e01942007-10-14 10:39:51 +0000613{
614 category = fcNaN;
John McCalle12b7382010-02-28 02:51:25 +0000615 sign = Negative;
616
John McCall165e96b2010-02-28 12:49:50 +0000617 integerPart *significand = significandParts();
618 unsigned numParts = partCount();
619
John McCalle12b7382010-02-28 02:51:25 +0000620 // Set the significand bits to the fill.
John McCall165e96b2010-02-28 12:49:50 +0000621 if (!fill || fill->getNumWords() < numParts)
622 APInt::tcSet(significand, 0, numParts);
623 if (fill) {
John McCalld44c6cc2010-03-01 18:38:45 +0000624 APInt::tcAssign(significand, fill->getRawData(),
625 std::min(fill->getNumWords(), numParts));
John McCall165e96b2010-02-28 12:49:50 +0000626
627 // Zero out the excess bits of the significand.
628 unsigned bitsToPreserve = semantics->precision - 1;
629 unsigned part = bitsToPreserve / 64;
630 bitsToPreserve %= 64;
631 significand[part] &= ((1ULL << bitsToPreserve) - 1);
632 for (part++; part != numParts; ++part)
633 significand[part] = 0;
634 }
635
636 unsigned QNaNBit = semantics->precision - 2;
John McCalle12b7382010-02-28 02:51:25 +0000637
638 if (SNaN) {
639 // We always have to clear the QNaN bit to make it an SNaN.
John McCall165e96b2010-02-28 12:49:50 +0000640 APInt::tcClearBit(significand, QNaNBit);
John McCalle12b7382010-02-28 02:51:25 +0000641
642 // If there are no bits set in the payload, we have to set
643 // *something* to make it a NaN instead of an infinity;
644 // conventionally, this is the next bit down from the QNaN bit.
John McCall165e96b2010-02-28 12:49:50 +0000645 if (APInt::tcIsZero(significand, numParts))
646 APInt::tcSetBit(significand, QNaNBit - 1);
John McCalle12b7382010-02-28 02:51:25 +0000647 } else {
648 // We always have to set the QNaN bit to make it a QNaN.
John McCall165e96b2010-02-28 12:49:50 +0000649 APInt::tcSetBit(significand, QNaNBit);
John McCalle12b7382010-02-28 02:51:25 +0000650 }
John McCall165e96b2010-02-28 12:49:50 +0000651
652 // For x87 extended precision, we want to make a NaN, not a
653 // pseudo-NaN. Maybe we should expose the ability to make
654 // pseudo-NaNs?
655 if (semantics == &APFloat::x87DoubleExtended)
656 APInt::tcSetBit(significand, QNaNBit + 1);
John McCalle12b7382010-02-28 02:51:25 +0000657}
658
659APFloat APFloat::makeNaN(const fltSemantics &Sem, bool SNaN, bool Negative,
660 const APInt *fill) {
661 APFloat value(Sem, uninitialized);
662 value.makeNaN(SNaN, Negative, fill);
663 return value;
Neil Boothe5e01942007-10-14 10:39:51 +0000664}
665
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000666APFloat &
667APFloat::operator=(const APFloat &rhs)
668{
Dan Gohman16e02092010-03-24 19:38:02 +0000669 if (this != &rhs) {
670 if (semantics != rhs.semantics) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000671 freeSignificand();
672 initialize(rhs.semantics);
673 }
674 assign(rhs);
675 }
676
677 return *this;
678}
679
Dale Johannesen343e7702007-08-24 00:56:33 +0000680bool
Shuxin Yang7aa1c322013-01-07 18:59:35 +0000681APFloat::isDenormal() const {
682 return isNormal() && (exponent == semantics->minExponent) &&
683 (APInt::tcExtractBit(significandParts(),
684 semantics->precision - 1) == 0);
685}
686
687bool
Dale Johannesen12595d72007-08-24 22:09:56 +0000688APFloat::bitwiseIsEqual(const APFloat &rhs) const {
Dale Johannesen343e7702007-08-24 00:56:33 +0000689 if (this == &rhs)
690 return true;
691 if (semantics != rhs.semantics ||
Dale Johanneseneaf08942007-08-31 04:03:46 +0000692 category != rhs.category ||
693 sign != rhs.sign)
Dale Johannesen343e7702007-08-24 00:56:33 +0000694 return false;
Dale Johanneseneaf08942007-08-31 04:03:46 +0000695 if (category==fcZero || category==fcInfinity)
Dale Johannesen343e7702007-08-24 00:56:33 +0000696 return true;
Dale Johanneseneaf08942007-08-31 04:03:46 +0000697 else if (category==fcNormal && exponent!=rhs.exponent)
698 return false;
Dale Johannesen343e7702007-08-24 00:56:33 +0000699 else {
Dale Johannesen343e7702007-08-24 00:56:33 +0000700 int i= partCount();
701 const integerPart* p=significandParts();
702 const integerPart* q=rhs.significandParts();
703 for (; i>0; i--, p++, q++) {
704 if (*p != *q)
705 return false;
706 }
707 return true;
708 }
709}
710
Ulrich Weigandfce241d2012-10-29 18:17:42 +0000711APFloat::APFloat(const fltSemantics &ourSemantics, integerPart value) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000712 initialize(&ourSemantics);
713 sign = 0;
714 zeroSignificand();
715 exponent = ourSemantics.precision - 1;
716 significandParts()[0] = value;
717 normalize(rmNearestTiesToEven, lfExactlyZero);
718}
719
Ulrich Weigandfce241d2012-10-29 18:17:42 +0000720APFloat::APFloat(const fltSemantics &ourSemantics) {
Chris Lattnerd7bd78e2009-09-17 01:08:43 +0000721 initialize(&ourSemantics);
722 category = fcZero;
723 sign = false;
724}
725
Ulrich Weigandfce241d2012-10-29 18:17:42 +0000726APFloat::APFloat(const fltSemantics &ourSemantics, uninitializedTag tag) {
John McCalle12b7382010-02-28 02:51:25 +0000727 // Allocates storage if necessary but does not initialize it.
728 initialize(&ourSemantics);
729}
Chris Lattnerd7bd78e2009-09-17 01:08:43 +0000730
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000731APFloat::APFloat(const fltSemantics &ourSemantics,
Ulrich Weigandfce241d2012-10-29 18:17:42 +0000732 fltCategory ourCategory, bool negative) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000733 initialize(&ourSemantics);
734 category = ourCategory;
735 sign = negative;
Mike Stumpc5ca7132009-05-30 03:49:43 +0000736 if (category == fcNormal)
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000737 category = fcZero;
Neil Boothe5e01942007-10-14 10:39:51 +0000738 else if (ourCategory == fcNaN)
John McCalle12b7382010-02-28 02:51:25 +0000739 makeNaN();
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000740}
741
Ulrich Weigandfce241d2012-10-29 18:17:42 +0000742APFloat::APFloat(const fltSemantics &ourSemantics, StringRef text) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000743 initialize(&ourSemantics);
744 convertFromString(text, rmNearestTiesToEven);
745}
746
Ulrich Weigandfce241d2012-10-29 18:17:42 +0000747APFloat::APFloat(const APFloat &rhs) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000748 initialize(rhs.semantics);
749 assign(rhs);
750}
751
752APFloat::~APFloat()
753{
754 freeSignificand();
755}
756
Ted Kremenek1f801fa2008-02-11 17:24:50 +0000757// Profile - This method 'profiles' an APFloat for use with FoldingSet.
758void APFloat::Profile(FoldingSetNodeID& ID) const {
Dale Johannesen7111b022008-10-09 18:53:47 +0000759 ID.Add(bitcastToAPInt());
Ted Kremenek1f801fa2008-02-11 17:24:50 +0000760}
761
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000762unsigned int
763APFloat::partCount() const
764{
Dale Johannesena72a5a02007-09-20 23:47:58 +0000765 return partCountForBits(semantics->precision + 1);
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000766}
767
768unsigned int
769APFloat::semanticsPrecision(const fltSemantics &semantics)
770{
771 return semantics.precision;
772}
773
774const integerPart *
775APFloat::significandParts() const
776{
777 return const_cast<APFloat *>(this)->significandParts();
778}
779
780integerPart *
781APFloat::significandParts()
782{
Dale Johanneseneaf08942007-08-31 04:03:46 +0000783 assert(category == fcNormal || category == fcNaN);
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000784
Evan Cheng99ebfa52009-10-27 21:35:42 +0000785 if (partCount() > 1)
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000786 return significand.parts;
787 else
788 return &significand.part;
789}
790
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000791void
792APFloat::zeroSignificand()
793{
794 category = fcNormal;
795 APInt::tcSet(significandParts(), 0, partCount());
796}
797
798/* Increment an fcNormal floating point number's significand. */
799void
800APFloat::incrementSignificand()
801{
802 integerPart carry;
803
804 carry = APInt::tcIncrement(significandParts(), partCount());
805
806 /* Our callers should never cause us to overflow. */
807 assert(carry == 0);
Duncan Sands1f6a3292011-08-12 14:54:45 +0000808 (void)carry;
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000809}
810
811/* Add the significand of the RHS. Returns the carry flag. */
812integerPart
813APFloat::addSignificand(const APFloat &rhs)
814{
815 integerPart *parts;
816
817 parts = significandParts();
818
819 assert(semantics == rhs.semantics);
820 assert(exponent == rhs.exponent);
821
822 return APInt::tcAdd(parts, rhs.significandParts(), 0, partCount());
823}
824
825/* Subtract the significand of the RHS with a borrow flag. Returns
826 the borrow flag. */
827integerPart
828APFloat::subtractSignificand(const APFloat &rhs, integerPart borrow)
829{
830 integerPart *parts;
831
832 parts = significandParts();
833
834 assert(semantics == rhs.semantics);
835 assert(exponent == rhs.exponent);
836
837 return APInt::tcSubtract(parts, rhs.significandParts(), borrow,
Neil Booth4f881702007-09-26 21:33:42 +0000838 partCount());
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000839}
840
841/* Multiply the significand of the RHS. If ADDEND is non-NULL, add it
842 on to the full-precision result of the multiplication. Returns the
843 lost fraction. */
844lostFraction
845APFloat::multiplySignificand(const APFloat &rhs, const APFloat *addend)
846{
Neil Booth4f881702007-09-26 21:33:42 +0000847 unsigned int omsb; // One, not zero, based MSB.
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000848 unsigned int partsCount, newPartsCount, precision;
849 integerPart *lhsSignificand;
850 integerPart scratch[4];
851 integerPart *fullSignificand;
852 lostFraction lost_fraction;
Dale Johannesen23a98552008-10-09 23:00:39 +0000853 bool ignored;
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000854
855 assert(semantics == rhs.semantics);
856
857 precision = semantics->precision;
858 newPartsCount = partCountForBits(precision * 2);
859
Dan Gohman16e02092010-03-24 19:38:02 +0000860 if (newPartsCount > 4)
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000861 fullSignificand = new integerPart[newPartsCount];
862 else
863 fullSignificand = scratch;
864
865 lhsSignificand = significandParts();
866 partsCount = partCount();
867
868 APInt::tcFullMultiply(fullSignificand, lhsSignificand,
Neil Booth978661d2007-10-06 00:24:48 +0000869 rhs.significandParts(), partsCount, partsCount);
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000870
871 lost_fraction = lfExactlyZero;
872 omsb = APInt::tcMSB(fullSignificand, newPartsCount) + 1;
873 exponent += rhs.exponent;
874
Dan Gohman16e02092010-03-24 19:38:02 +0000875 if (addend) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000876 Significand savedSignificand = significand;
877 const fltSemantics *savedSemantics = semantics;
878 fltSemantics extendedSemantics;
879 opStatus status;
880 unsigned int extendedPrecision;
881
882 /* Normalize our MSB. */
883 extendedPrecision = precision + precision - 1;
Dan Gohman16e02092010-03-24 19:38:02 +0000884 if (omsb != extendedPrecision) {
885 APInt::tcShiftLeft(fullSignificand, newPartsCount,
886 extendedPrecision - omsb);
887 exponent -= extendedPrecision - omsb;
888 }
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000889
890 /* Create new semantics. */
891 extendedSemantics = *semantics;
892 extendedSemantics.precision = extendedPrecision;
893
Dan Gohman16e02092010-03-24 19:38:02 +0000894 if (newPartsCount == 1)
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000895 significand.part = fullSignificand[0];
896 else
897 significand.parts = fullSignificand;
898 semantics = &extendedSemantics;
899
900 APFloat extendedAddend(*addend);
Dale Johannesen23a98552008-10-09 23:00:39 +0000901 status = extendedAddend.convert(extendedSemantics, rmTowardZero, &ignored);
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000902 assert(status == opOK);
Duncan Sands1f6a3292011-08-12 14:54:45 +0000903 (void)status;
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000904 lost_fraction = addOrSubtractSignificand(extendedAddend, false);
905
906 /* Restore our state. */
Dan Gohman16e02092010-03-24 19:38:02 +0000907 if (newPartsCount == 1)
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000908 fullSignificand[0] = significand.part;
909 significand = savedSignificand;
910 semantics = savedSemantics;
911
912 omsb = APInt::tcMSB(fullSignificand, newPartsCount) + 1;
913 }
914
915 exponent -= (precision - 1);
916
Dan Gohman16e02092010-03-24 19:38:02 +0000917 if (omsb > precision) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000918 unsigned int bits, significantParts;
919 lostFraction lf;
920
921 bits = omsb - precision;
922 significantParts = partCountForBits(omsb);
923 lf = shiftRight(fullSignificand, significantParts, bits);
924 lost_fraction = combineLostFractions(lf, lost_fraction);
925 exponent += bits;
926 }
927
928 APInt::tcAssign(lhsSignificand, fullSignificand, partsCount);
929
Dan Gohman16e02092010-03-24 19:38:02 +0000930 if (newPartsCount > 4)
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000931 delete [] fullSignificand;
932
933 return lost_fraction;
934}
935
936/* Multiply the significands of LHS and RHS to DST. */
937lostFraction
938APFloat::divideSignificand(const APFloat &rhs)
939{
940 unsigned int bit, i, partsCount;
941 const integerPart *rhsSignificand;
942 integerPart *lhsSignificand, *dividend, *divisor;
943 integerPart scratch[4];
944 lostFraction lost_fraction;
945
946 assert(semantics == rhs.semantics);
947
948 lhsSignificand = significandParts();
949 rhsSignificand = rhs.significandParts();
950 partsCount = partCount();
951
Dan Gohman16e02092010-03-24 19:38:02 +0000952 if (partsCount > 2)
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000953 dividend = new integerPart[partsCount * 2];
954 else
955 dividend = scratch;
956
957 divisor = dividend + partsCount;
958
959 /* Copy the dividend and divisor as they will be modified in-place. */
Dan Gohman16e02092010-03-24 19:38:02 +0000960 for (i = 0; i < partsCount; i++) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000961 dividend[i] = lhsSignificand[i];
962 divisor[i] = rhsSignificand[i];
963 lhsSignificand[i] = 0;
964 }
965
966 exponent -= rhs.exponent;
967
968 unsigned int precision = semantics->precision;
969
970 /* Normalize the divisor. */
971 bit = precision - APInt::tcMSB(divisor, partsCount) - 1;
Dan Gohman16e02092010-03-24 19:38:02 +0000972 if (bit) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000973 exponent += bit;
974 APInt::tcShiftLeft(divisor, partsCount, bit);
975 }
976
977 /* Normalize the dividend. */
978 bit = precision - APInt::tcMSB(dividend, partsCount) - 1;
Dan Gohman16e02092010-03-24 19:38:02 +0000979 if (bit) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000980 exponent -= bit;
981 APInt::tcShiftLeft(dividend, partsCount, bit);
982 }
983
Neil Booth96c74712007-10-12 16:02:31 +0000984 /* Ensure the dividend >= divisor initially for the loop below.
985 Incidentally, this means that the division loop below is
986 guaranteed to set the integer bit to one. */
Dan Gohman16e02092010-03-24 19:38:02 +0000987 if (APInt::tcCompare(dividend, divisor, partsCount) < 0) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000988 exponent--;
989 APInt::tcShiftLeft(dividend, partsCount, 1);
990 assert(APInt::tcCompare(dividend, divisor, partsCount) >= 0);
991 }
992
993 /* Long division. */
Dan Gohman16e02092010-03-24 19:38:02 +0000994 for (bit = precision; bit; bit -= 1) {
995 if (APInt::tcCompare(dividend, divisor, partsCount) >= 0) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000996 APInt::tcSubtract(dividend, divisor, 0, partsCount);
997 APInt::tcSetBit(lhsSignificand, bit - 1);
998 }
999
1000 APInt::tcShiftLeft(dividend, partsCount, 1);
1001 }
1002
1003 /* Figure out the lost fraction. */
1004 int cmp = APInt::tcCompare(dividend, divisor, partsCount);
1005
Dan Gohman16e02092010-03-24 19:38:02 +00001006 if (cmp > 0)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001007 lost_fraction = lfMoreThanHalf;
Dan Gohman16e02092010-03-24 19:38:02 +00001008 else if (cmp == 0)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001009 lost_fraction = lfExactlyHalf;
Dan Gohman16e02092010-03-24 19:38:02 +00001010 else if (APInt::tcIsZero(dividend, partsCount))
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001011 lost_fraction = lfExactlyZero;
1012 else
1013 lost_fraction = lfLessThanHalf;
1014
Dan Gohman16e02092010-03-24 19:38:02 +00001015 if (partsCount > 2)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001016 delete [] dividend;
1017
1018 return lost_fraction;
1019}
1020
1021unsigned int
1022APFloat::significandMSB() const
1023{
1024 return APInt::tcMSB(significandParts(), partCount());
1025}
1026
1027unsigned int
1028APFloat::significandLSB() const
1029{
1030 return APInt::tcLSB(significandParts(), partCount());
1031}
1032
1033/* Note that a zero result is NOT normalized to fcZero. */
1034lostFraction
1035APFloat::shiftSignificandRight(unsigned int bits)
1036{
1037 /* Our exponent should not overflow. */
1038 assert((exponent_t) (exponent + bits) >= exponent);
1039
1040 exponent += bits;
1041
1042 return shiftRight(significandParts(), partCount(), bits);
1043}
1044
1045/* Shift the significand left BITS bits, subtract BITS from its exponent. */
1046void
1047APFloat::shiftSignificandLeft(unsigned int bits)
1048{
1049 assert(bits < semantics->precision);
1050
Dan Gohman16e02092010-03-24 19:38:02 +00001051 if (bits) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001052 unsigned int partsCount = partCount();
1053
1054 APInt::tcShiftLeft(significandParts(), partsCount, bits);
1055 exponent -= bits;
1056
1057 assert(!APInt::tcIsZero(significandParts(), partsCount));
1058 }
1059}
1060
1061APFloat::cmpResult
1062APFloat::compareAbsoluteValue(const APFloat &rhs) const
1063{
1064 int compare;
1065
1066 assert(semantics == rhs.semantics);
1067 assert(category == fcNormal);
1068 assert(rhs.category == fcNormal);
1069
1070 compare = exponent - rhs.exponent;
1071
1072 /* If exponents are equal, do an unsigned bignum comparison of the
1073 significands. */
Dan Gohman16e02092010-03-24 19:38:02 +00001074 if (compare == 0)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001075 compare = APInt::tcCompare(significandParts(), rhs.significandParts(),
Neil Booth4f881702007-09-26 21:33:42 +00001076 partCount());
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001077
Dan Gohman16e02092010-03-24 19:38:02 +00001078 if (compare > 0)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001079 return cmpGreaterThan;
Dan Gohman16e02092010-03-24 19:38:02 +00001080 else if (compare < 0)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001081 return cmpLessThan;
1082 else
1083 return cmpEqual;
1084}
1085
1086/* Handle overflow. Sign is preserved. We either become infinity or
1087 the largest finite number. */
1088APFloat::opStatus
1089APFloat::handleOverflow(roundingMode rounding_mode)
1090{
1091 /* Infinity? */
Dan Gohman16e02092010-03-24 19:38:02 +00001092 if (rounding_mode == rmNearestTiesToEven ||
1093 rounding_mode == rmNearestTiesToAway ||
1094 (rounding_mode == rmTowardPositive && !sign) ||
1095 (rounding_mode == rmTowardNegative && sign)) {
1096 category = fcInfinity;
1097 return (opStatus) (opOverflow | opInexact);
1098 }
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001099
1100 /* Otherwise we become the largest finite number. */
1101 category = fcNormal;
1102 exponent = semantics->maxExponent;
1103 APInt::tcSetLeastSignificantBits(significandParts(), partCount(),
Neil Booth4f881702007-09-26 21:33:42 +00001104 semantics->precision);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001105
1106 return opInexact;
1107}
1108
Neil Boothb7dea4c2007-10-03 15:16:41 +00001109/* Returns TRUE if, when truncating the current number, with BIT the
1110 new LSB, with the given lost fraction and rounding mode, the result
1111 would need to be rounded away from zero (i.e., by increasing the
1112 signficand). This routine must work for fcZero of both signs, and
1113 fcNormal numbers. */
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001114bool
1115APFloat::roundAwayFromZero(roundingMode rounding_mode,
Neil Boothb7dea4c2007-10-03 15:16:41 +00001116 lostFraction lost_fraction,
1117 unsigned int bit) const
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001118{
Dale Johanneseneaf08942007-08-31 04:03:46 +00001119 /* NaNs and infinities should not have lost fractions. */
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001120 assert(category == fcNormal || category == fcZero);
1121
Neil Boothb7dea4c2007-10-03 15:16:41 +00001122 /* Current callers never pass this so we don't handle it. */
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001123 assert(lost_fraction != lfExactlyZero);
1124
Mike Stumpf3dc0c02009-05-13 23:23:20 +00001125 switch (rounding_mode) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001126 case rmNearestTiesToAway:
1127 return lost_fraction == lfExactlyHalf || lost_fraction == lfMoreThanHalf;
1128
1129 case rmNearestTiesToEven:
Dan Gohman16e02092010-03-24 19:38:02 +00001130 if (lost_fraction == lfMoreThanHalf)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001131 return true;
1132
1133 /* Our zeroes don't have a significand to test. */
Dan Gohman16e02092010-03-24 19:38:02 +00001134 if (lost_fraction == lfExactlyHalf && category != fcZero)
Neil Boothb7dea4c2007-10-03 15:16:41 +00001135 return APInt::tcExtractBit(significandParts(), bit);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001136
1137 return false;
1138
1139 case rmTowardZero:
1140 return false;
1141
1142 case rmTowardPositive:
1143 return sign == false;
1144
1145 case rmTowardNegative:
1146 return sign == true;
1147 }
Chandler Carruth732f05c2012-01-10 18:08:01 +00001148 llvm_unreachable("Invalid rounding mode found");
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001149}
1150
1151APFloat::opStatus
1152APFloat::normalize(roundingMode rounding_mode,
Neil Booth4f881702007-09-26 21:33:42 +00001153 lostFraction lost_fraction)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001154{
Neil Booth4f881702007-09-26 21:33:42 +00001155 unsigned int omsb; /* One, not zero, based MSB. */
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001156 int exponentChange;
1157
Dan Gohman16e02092010-03-24 19:38:02 +00001158 if (category != fcNormal)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001159 return opOK;
1160
1161 /* Before rounding normalize the exponent of fcNormal numbers. */
1162 omsb = significandMSB() + 1;
1163
Dan Gohman16e02092010-03-24 19:38:02 +00001164 if (omsb) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001165 /* OMSB is numbered from 1. We want to place it in the integer
Nick Lewycky03dd4e82011-10-03 21:30:08 +00001166 bit numbered PRECISION if possible, with a compensating change in
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001167 the exponent. */
1168 exponentChange = omsb - semantics->precision;
1169
1170 /* If the resulting exponent is too high, overflow according to
1171 the rounding mode. */
Dan Gohman16e02092010-03-24 19:38:02 +00001172 if (exponent + exponentChange > semantics->maxExponent)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001173 return handleOverflow(rounding_mode);
1174
1175 /* Subnormal numbers have exponent minExponent, and their MSB
1176 is forced based on that. */
Dan Gohman16e02092010-03-24 19:38:02 +00001177 if (exponent + exponentChange < semantics->minExponent)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001178 exponentChange = semantics->minExponent - exponent;
1179
1180 /* Shifting left is easy as we don't lose precision. */
Dan Gohman16e02092010-03-24 19:38:02 +00001181 if (exponentChange < 0) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001182 assert(lost_fraction == lfExactlyZero);
1183
1184 shiftSignificandLeft(-exponentChange);
1185
1186 return opOK;
1187 }
1188
Dan Gohman16e02092010-03-24 19:38:02 +00001189 if (exponentChange > 0) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001190 lostFraction lf;
1191
1192 /* Shift right and capture any new lost fraction. */
1193 lf = shiftSignificandRight(exponentChange);
1194
1195 lost_fraction = combineLostFractions(lf, lost_fraction);
1196
1197 /* Keep OMSB up-to-date. */
Dan Gohman16e02092010-03-24 19:38:02 +00001198 if (omsb > (unsigned) exponentChange)
Neil Booth96c74712007-10-12 16:02:31 +00001199 omsb -= exponentChange;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001200 else
Neil Booth4f881702007-09-26 21:33:42 +00001201 omsb = 0;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001202 }
1203 }
1204
1205 /* Now round the number according to rounding_mode given the lost
1206 fraction. */
1207
1208 /* As specified in IEEE 754, since we do not trap we do not report
1209 underflow for exact results. */
Dan Gohman16e02092010-03-24 19:38:02 +00001210 if (lost_fraction == lfExactlyZero) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001211 /* Canonicalize zeroes. */
Dan Gohman16e02092010-03-24 19:38:02 +00001212 if (omsb == 0)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001213 category = fcZero;
1214
1215 return opOK;
1216 }
1217
1218 /* Increment the significand if we're rounding away from zero. */
Dan Gohman16e02092010-03-24 19:38:02 +00001219 if (roundAwayFromZero(rounding_mode, lost_fraction, 0)) {
1220 if (omsb == 0)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001221 exponent = semantics->minExponent;
1222
1223 incrementSignificand();
1224 omsb = significandMSB() + 1;
1225
1226 /* Did the significand increment overflow? */
Dan Gohman16e02092010-03-24 19:38:02 +00001227 if (omsb == (unsigned) semantics->precision + 1) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001228 /* Renormalize by incrementing the exponent and shifting our
Neil Booth4f881702007-09-26 21:33:42 +00001229 significand right one. However if we already have the
1230 maximum exponent we overflow to infinity. */
Dan Gohman16e02092010-03-24 19:38:02 +00001231 if (exponent == semantics->maxExponent) {
Neil Booth4f881702007-09-26 21:33:42 +00001232 category = fcInfinity;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001233
Neil Booth4f881702007-09-26 21:33:42 +00001234 return (opStatus) (opOverflow | opInexact);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001235 }
1236
1237 shiftSignificandRight(1);
1238
1239 return opInexact;
1240 }
1241 }
1242
1243 /* The normal case - we were and are not denormal, and any
1244 significand increment above didn't overflow. */
Dan Gohman16e02092010-03-24 19:38:02 +00001245 if (omsb == semantics->precision)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001246 return opInexact;
1247
1248 /* We have a non-zero denormal. */
1249 assert(omsb < semantics->precision);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001250
1251 /* Canonicalize zeroes. */
Dan Gohman16e02092010-03-24 19:38:02 +00001252 if (omsb == 0)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001253 category = fcZero;
1254
1255 /* The fcZero case is a denormal that underflowed to zero. */
1256 return (opStatus) (opUnderflow | opInexact);
1257}
1258
1259APFloat::opStatus
1260APFloat::addOrSubtractSpecials(const APFloat &rhs, bool subtract)
1261{
Mike Stumpf3dc0c02009-05-13 23:23:20 +00001262 switch (convolve(category, rhs.category)) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001263 default:
Torok Edwinc23197a2009-07-14 16:55:14 +00001264 llvm_unreachable(0);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001265
Dale Johanneseneaf08942007-08-31 04:03:46 +00001266 case convolve(fcNaN, fcZero):
1267 case convolve(fcNaN, fcNormal):
1268 case convolve(fcNaN, fcInfinity):
1269 case convolve(fcNaN, fcNaN):
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001270 case convolve(fcNormal, fcZero):
1271 case convolve(fcInfinity, fcNormal):
1272 case convolve(fcInfinity, fcZero):
1273 return opOK;
1274
Dale Johanneseneaf08942007-08-31 04:03:46 +00001275 case convolve(fcZero, fcNaN):
1276 case convolve(fcNormal, fcNaN):
1277 case convolve(fcInfinity, fcNaN):
1278 category = fcNaN;
1279 copySignificand(rhs);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001280 return opOK;
1281
1282 case convolve(fcNormal, fcInfinity):
1283 case convolve(fcZero, fcInfinity):
1284 category = fcInfinity;
1285 sign = rhs.sign ^ subtract;
1286 return opOK;
1287
1288 case convolve(fcZero, fcNormal):
1289 assign(rhs);
1290 sign = rhs.sign ^ subtract;
1291 return opOK;
1292
1293 case convolve(fcZero, fcZero):
1294 /* Sign depends on rounding mode; handled by caller. */
1295 return opOK;
1296
1297 case convolve(fcInfinity, fcInfinity):
1298 /* Differently signed infinities can only be validly
1299 subtracted. */
Dan Gohman16e02092010-03-24 19:38:02 +00001300 if (((sign ^ rhs.sign)!=0) != subtract) {
Neil Boothe5e01942007-10-14 10:39:51 +00001301 makeNaN();
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001302 return opInvalidOp;
1303 }
1304
1305 return opOK;
1306
1307 case convolve(fcNormal, fcNormal):
1308 return opDivByZero;
1309 }
1310}
1311
1312/* Add or subtract two normal numbers. */
1313lostFraction
1314APFloat::addOrSubtractSignificand(const APFloat &rhs, bool subtract)
1315{
1316 integerPart carry;
1317 lostFraction lost_fraction;
1318 int bits;
1319
1320 /* Determine if the operation on the absolute values is effectively
1321 an addition or subtraction. */
Hartmut Kaiser8df77a92007-10-25 23:15:31 +00001322 subtract ^= (sign ^ rhs.sign) ? true : false;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001323
1324 /* Are we bigger exponent-wise than the RHS? */
1325 bits = exponent - rhs.exponent;
1326
1327 /* Subtraction is more subtle than one might naively expect. */
Dan Gohman16e02092010-03-24 19:38:02 +00001328 if (subtract) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001329 APFloat temp_rhs(rhs);
1330 bool reverse;
1331
Chris Lattnerada530b2007-08-24 03:02:34 +00001332 if (bits == 0) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001333 reverse = compareAbsoluteValue(temp_rhs) == cmpLessThan;
1334 lost_fraction = lfExactlyZero;
Chris Lattnerada530b2007-08-24 03:02:34 +00001335 } else if (bits > 0) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001336 lost_fraction = temp_rhs.shiftSignificandRight(bits - 1);
1337 shiftSignificandLeft(1);
1338 reverse = false;
Chris Lattnerada530b2007-08-24 03:02:34 +00001339 } else {
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001340 lost_fraction = shiftSignificandRight(-bits - 1);
1341 temp_rhs.shiftSignificandLeft(1);
1342 reverse = true;
1343 }
1344
Chris Lattnerada530b2007-08-24 03:02:34 +00001345 if (reverse) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001346 carry = temp_rhs.subtractSignificand
Neil Booth4f881702007-09-26 21:33:42 +00001347 (*this, lost_fraction != lfExactlyZero);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001348 copySignificand(temp_rhs);
1349 sign = !sign;
1350 } else {
1351 carry = subtractSignificand
Neil Booth4f881702007-09-26 21:33:42 +00001352 (temp_rhs, lost_fraction != lfExactlyZero);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001353 }
1354
1355 /* Invert the lost fraction - it was on the RHS and
1356 subtracted. */
Dan Gohman16e02092010-03-24 19:38:02 +00001357 if (lost_fraction == lfLessThanHalf)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001358 lost_fraction = lfMoreThanHalf;
Dan Gohman16e02092010-03-24 19:38:02 +00001359 else if (lost_fraction == lfMoreThanHalf)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001360 lost_fraction = lfLessThanHalf;
1361
1362 /* The code above is intended to ensure that no borrow is
1363 necessary. */
1364 assert(!carry);
Duncan Sands1f6a3292011-08-12 14:54:45 +00001365 (void)carry;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001366 } else {
Dan Gohman16e02092010-03-24 19:38:02 +00001367 if (bits > 0) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001368 APFloat temp_rhs(rhs);
1369
1370 lost_fraction = temp_rhs.shiftSignificandRight(bits);
1371 carry = addSignificand(temp_rhs);
1372 } else {
1373 lost_fraction = shiftSignificandRight(-bits);
1374 carry = addSignificand(rhs);
1375 }
1376
1377 /* We have a guard bit; generating a carry cannot happen. */
1378 assert(!carry);
Duncan Sands1f6a3292011-08-12 14:54:45 +00001379 (void)carry;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001380 }
1381
1382 return lost_fraction;
1383}
1384
1385APFloat::opStatus
1386APFloat::multiplySpecials(const APFloat &rhs)
1387{
Mike Stumpf3dc0c02009-05-13 23:23:20 +00001388 switch (convolve(category, rhs.category)) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001389 default:
Torok Edwinc23197a2009-07-14 16:55:14 +00001390 llvm_unreachable(0);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001391
Dale Johanneseneaf08942007-08-31 04:03:46 +00001392 case convolve(fcNaN, fcZero):
1393 case convolve(fcNaN, fcNormal):
1394 case convolve(fcNaN, fcInfinity):
1395 case convolve(fcNaN, fcNaN):
1396 return opOK;
1397
1398 case convolve(fcZero, fcNaN):
1399 case convolve(fcNormal, fcNaN):
1400 case convolve(fcInfinity, fcNaN):
1401 category = fcNaN;
1402 copySignificand(rhs);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001403 return opOK;
1404
1405 case convolve(fcNormal, fcInfinity):
1406 case convolve(fcInfinity, fcNormal):
1407 case convolve(fcInfinity, fcInfinity):
1408 category = fcInfinity;
1409 return opOK;
1410
1411 case convolve(fcZero, fcNormal):
1412 case convolve(fcNormal, fcZero):
1413 case convolve(fcZero, fcZero):
1414 category = fcZero;
1415 return opOK;
1416
1417 case convolve(fcZero, fcInfinity):
1418 case convolve(fcInfinity, fcZero):
Neil Boothe5e01942007-10-14 10:39:51 +00001419 makeNaN();
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001420 return opInvalidOp;
1421
1422 case convolve(fcNormal, fcNormal):
1423 return opOK;
1424 }
1425}
1426
1427APFloat::opStatus
1428APFloat::divideSpecials(const APFloat &rhs)
1429{
Mike Stumpf3dc0c02009-05-13 23:23:20 +00001430 switch (convolve(category, rhs.category)) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001431 default:
Torok Edwinc23197a2009-07-14 16:55:14 +00001432 llvm_unreachable(0);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001433
Dale Johanneseneaf08942007-08-31 04:03:46 +00001434 case convolve(fcNaN, fcZero):
1435 case convolve(fcNaN, fcNormal):
1436 case convolve(fcNaN, fcInfinity):
1437 case convolve(fcNaN, fcNaN):
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001438 case convolve(fcInfinity, fcZero):
1439 case convolve(fcInfinity, fcNormal):
1440 case convolve(fcZero, fcInfinity):
1441 case convolve(fcZero, fcNormal):
1442 return opOK;
1443
Dale Johanneseneaf08942007-08-31 04:03:46 +00001444 case convolve(fcZero, fcNaN):
1445 case convolve(fcNormal, fcNaN):
1446 case convolve(fcInfinity, fcNaN):
1447 category = fcNaN;
1448 copySignificand(rhs);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001449 return opOK;
1450
1451 case convolve(fcNormal, fcInfinity):
1452 category = fcZero;
1453 return opOK;
1454
1455 case convolve(fcNormal, fcZero):
1456 category = fcInfinity;
1457 return opDivByZero;
1458
1459 case convolve(fcInfinity, fcInfinity):
1460 case convolve(fcZero, fcZero):
Neil Boothe5e01942007-10-14 10:39:51 +00001461 makeNaN();
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001462 return opInvalidOp;
1463
1464 case convolve(fcNormal, fcNormal):
1465 return opOK;
1466 }
1467}
1468
Dale Johannesened6af242009-01-21 00:35:19 +00001469APFloat::opStatus
1470APFloat::modSpecials(const APFloat &rhs)
1471{
Mike Stumpf3dc0c02009-05-13 23:23:20 +00001472 switch (convolve(category, rhs.category)) {
Dale Johannesened6af242009-01-21 00:35:19 +00001473 default:
Torok Edwinc23197a2009-07-14 16:55:14 +00001474 llvm_unreachable(0);
Dale Johannesened6af242009-01-21 00:35:19 +00001475
1476 case convolve(fcNaN, fcZero):
1477 case convolve(fcNaN, fcNormal):
1478 case convolve(fcNaN, fcInfinity):
1479 case convolve(fcNaN, fcNaN):
1480 case convolve(fcZero, fcInfinity):
1481 case convolve(fcZero, fcNormal):
1482 case convolve(fcNormal, fcInfinity):
1483 return opOK;
1484
1485 case convolve(fcZero, fcNaN):
1486 case convolve(fcNormal, fcNaN):
1487 case convolve(fcInfinity, fcNaN):
1488 category = fcNaN;
1489 copySignificand(rhs);
1490 return opOK;
1491
1492 case convolve(fcNormal, fcZero):
1493 case convolve(fcInfinity, fcZero):
1494 case convolve(fcInfinity, fcNormal):
1495 case convolve(fcInfinity, fcInfinity):
1496 case convolve(fcZero, fcZero):
1497 makeNaN();
1498 return opInvalidOp;
1499
1500 case convolve(fcNormal, fcNormal):
1501 return opOK;
1502 }
1503}
1504
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001505/* Change sign. */
1506void
1507APFloat::changeSign()
1508{
1509 /* Look mummy, this one's easy. */
1510 sign = !sign;
1511}
1512
Dale Johannesene15c2db2007-08-31 23:35:31 +00001513void
1514APFloat::clearSign()
1515{
1516 /* So is this one. */
1517 sign = 0;
1518}
1519
1520void
1521APFloat::copySign(const APFloat &rhs)
1522{
1523 /* And this one. */
1524 sign = rhs.sign;
1525}
1526
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001527/* Normalized addition or subtraction. */
1528APFloat::opStatus
1529APFloat::addOrSubtract(const APFloat &rhs, roundingMode rounding_mode,
Neil Booth4f881702007-09-26 21:33:42 +00001530 bool subtract)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001531{
1532 opStatus fs;
1533
1534 fs = addOrSubtractSpecials(rhs, subtract);
1535
1536 /* This return code means it was not a simple case. */
Dan Gohman16e02092010-03-24 19:38:02 +00001537 if (fs == opDivByZero) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001538 lostFraction lost_fraction;
1539
1540 lost_fraction = addOrSubtractSignificand(rhs, subtract);
1541 fs = normalize(rounding_mode, lost_fraction);
1542
1543 /* Can only be zero if we lost no fraction. */
1544 assert(category != fcZero || lost_fraction == lfExactlyZero);
1545 }
1546
1547 /* If two numbers add (exactly) to zero, IEEE 754 decrees it is a
1548 positive zero unless rounding to minus infinity, except that
1549 adding two like-signed zeroes gives that zero. */
Dan Gohman16e02092010-03-24 19:38:02 +00001550 if (category == fcZero) {
1551 if (rhs.category != fcZero || (sign == rhs.sign) == subtract)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001552 sign = (rounding_mode == rmTowardNegative);
1553 }
1554
1555 return fs;
1556}
1557
1558/* Normalized addition. */
1559APFloat::opStatus
1560APFloat::add(const APFloat &rhs, roundingMode rounding_mode)
1561{
1562 return addOrSubtract(rhs, rounding_mode, false);
1563}
1564
1565/* Normalized subtraction. */
1566APFloat::opStatus
1567APFloat::subtract(const APFloat &rhs, roundingMode rounding_mode)
1568{
1569 return addOrSubtract(rhs, rounding_mode, true);
1570}
1571
1572/* Normalized multiply. */
1573APFloat::opStatus
1574APFloat::multiply(const APFloat &rhs, roundingMode rounding_mode)
1575{
1576 opStatus fs;
1577
1578 sign ^= rhs.sign;
1579 fs = multiplySpecials(rhs);
1580
Dan Gohman16e02092010-03-24 19:38:02 +00001581 if (category == fcNormal) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001582 lostFraction lost_fraction = multiplySignificand(rhs, 0);
1583 fs = normalize(rounding_mode, lost_fraction);
Dan Gohman16e02092010-03-24 19:38:02 +00001584 if (lost_fraction != lfExactlyZero)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001585 fs = (opStatus) (fs | opInexact);
1586 }
1587
1588 return fs;
1589}
1590
1591/* Normalized divide. */
1592APFloat::opStatus
1593APFloat::divide(const APFloat &rhs, roundingMode rounding_mode)
1594{
1595 opStatus fs;
1596
1597 sign ^= rhs.sign;
1598 fs = divideSpecials(rhs);
1599
Dan Gohman16e02092010-03-24 19:38:02 +00001600 if (category == fcNormal) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001601 lostFraction lost_fraction = divideSignificand(rhs);
1602 fs = normalize(rounding_mode, lost_fraction);
Dan Gohman16e02092010-03-24 19:38:02 +00001603 if (lost_fraction != lfExactlyZero)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001604 fs = (opStatus) (fs | opInexact);
1605 }
1606
1607 return fs;
1608}
1609
Dale Johannesen24b66a82009-01-20 18:35:05 +00001610/* Normalized remainder. This is not currently correct in all cases. */
1611APFloat::opStatus
1612APFloat::remainder(const APFloat &rhs)
1613{
1614 opStatus fs;
1615 APFloat V = *this;
1616 unsigned int origSign = sign;
1617
Dale Johannesen24b66a82009-01-20 18:35:05 +00001618 fs = V.divide(rhs, rmNearestTiesToEven);
1619 if (fs == opDivByZero)
1620 return fs;
1621
1622 int parts = partCount();
1623 integerPart *x = new integerPart[parts];
1624 bool ignored;
1625 fs = V.convertToInteger(x, parts * integerPartWidth, true,
1626 rmNearestTiesToEven, &ignored);
1627 if (fs==opInvalidOp)
1628 return fs;
1629
1630 fs = V.convertFromZeroExtendedInteger(x, parts * integerPartWidth, true,
1631 rmNearestTiesToEven);
1632 assert(fs==opOK); // should always work
1633
1634 fs = V.multiply(rhs, rmNearestTiesToEven);
1635 assert(fs==opOK || fs==opInexact); // should not overflow or underflow
1636
1637 fs = subtract(V, rmNearestTiesToEven);
1638 assert(fs==opOK || fs==opInexact); // likewise
1639
1640 if (isZero())
1641 sign = origSign; // IEEE754 requires this
1642 delete[] x;
1643 return fs;
1644}
1645
Dan Gohman16e02092010-03-24 19:38:02 +00001646/* Normalized llvm frem (C fmod).
Dale Johannesen24b66a82009-01-20 18:35:05 +00001647 This is not currently correct in all cases. */
Dale Johannesene15c2db2007-08-31 23:35:31 +00001648APFloat::opStatus
1649APFloat::mod(const APFloat &rhs, roundingMode rounding_mode)
1650{
1651 opStatus fs;
Dale Johannesened6af242009-01-21 00:35:19 +00001652 fs = modSpecials(rhs);
Dale Johannesene15c2db2007-08-31 23:35:31 +00001653
Dale Johannesened6af242009-01-21 00:35:19 +00001654 if (category == fcNormal && rhs.category == fcNormal) {
1655 APFloat V = *this;
1656 unsigned int origSign = sign;
Dale Johannesene15c2db2007-08-31 23:35:31 +00001657
Dale Johannesened6af242009-01-21 00:35:19 +00001658 fs = V.divide(rhs, rmNearestTiesToEven);
1659 if (fs == opDivByZero)
1660 return fs;
Dale Johannesen58c2e4c2007-09-05 20:39:49 +00001661
Dale Johannesened6af242009-01-21 00:35:19 +00001662 int parts = partCount();
1663 integerPart *x = new integerPart[parts];
1664 bool ignored;
1665 fs = V.convertToInteger(x, parts * integerPartWidth, true,
1666 rmTowardZero, &ignored);
1667 if (fs==opInvalidOp)
1668 return fs;
Dale Johannesen58c2e4c2007-09-05 20:39:49 +00001669
Dale Johannesened6af242009-01-21 00:35:19 +00001670 fs = V.convertFromZeroExtendedInteger(x, parts * integerPartWidth, true,
1671 rmNearestTiesToEven);
1672 assert(fs==opOK); // should always work
Dale Johannesen58c2e4c2007-09-05 20:39:49 +00001673
Dale Johannesened6af242009-01-21 00:35:19 +00001674 fs = V.multiply(rhs, rounding_mode);
1675 assert(fs==opOK || fs==opInexact); // should not overflow or underflow
1676
1677 fs = subtract(V, rounding_mode);
1678 assert(fs==opOK || fs==opInexact); // likewise
1679
1680 if (isZero())
1681 sign = origSign; // IEEE754 requires this
1682 delete[] x;
1683 }
Dale Johannesene15c2db2007-08-31 23:35:31 +00001684 return fs;
1685}
1686
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001687/* Normalized fused-multiply-add. */
1688APFloat::opStatus
1689APFloat::fusedMultiplyAdd(const APFloat &multiplicand,
Neil Booth4f881702007-09-26 21:33:42 +00001690 const APFloat &addend,
1691 roundingMode rounding_mode)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001692{
1693 opStatus fs;
1694
1695 /* Post-multiplication sign, before addition. */
1696 sign ^= multiplicand.sign;
1697
1698 /* If and only if all arguments are normal do we need to do an
1699 extended-precision calculation. */
Dan Gohman16e02092010-03-24 19:38:02 +00001700 if (category == fcNormal &&
1701 multiplicand.category == fcNormal &&
1702 addend.category == fcNormal) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001703 lostFraction lost_fraction;
1704
1705 lost_fraction = multiplySignificand(multiplicand, &addend);
1706 fs = normalize(rounding_mode, lost_fraction);
Dan Gohman16e02092010-03-24 19:38:02 +00001707 if (lost_fraction != lfExactlyZero)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001708 fs = (opStatus) (fs | opInexact);
1709
1710 /* If two numbers add (exactly) to zero, IEEE 754 decrees it is a
1711 positive zero unless rounding to minus infinity, except that
1712 adding two like-signed zeroes gives that zero. */
Dan Gohman16e02092010-03-24 19:38:02 +00001713 if (category == fcZero && sign != addend.sign)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001714 sign = (rounding_mode == rmTowardNegative);
1715 } else {
1716 fs = multiplySpecials(multiplicand);
1717
1718 /* FS can only be opOK or opInvalidOp. There is no more work
1719 to do in the latter case. The IEEE-754R standard says it is
1720 implementation-defined in this case whether, if ADDEND is a
Dale Johanneseneaf08942007-08-31 04:03:46 +00001721 quiet NaN, we raise invalid op; this implementation does so.
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001722
1723 If we need to do the addition we can do so with normal
1724 precision. */
Dan Gohman16e02092010-03-24 19:38:02 +00001725 if (fs == opOK)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001726 fs = addOrSubtract(addend, rounding_mode, false);
1727 }
1728
1729 return fs;
1730}
1731
Owen Anderson7c626d32012-08-13 23:32:49 +00001732/* Rounding-mode corrrect round to integral value. */
1733APFloat::opStatus APFloat::roundToIntegral(roundingMode rounding_mode) {
1734 opStatus fs;
Owen Anderson7c626d32012-08-13 23:32:49 +00001735
Owen Andersonc82cc582012-08-15 18:28:45 +00001736 // If the exponent is large enough, we know that this value is already
1737 // integral, and the arithmetic below would potentially cause it to saturate
1738 // to +/-Inf. Bail out early instead.
Benjamin Kramer3e7735f2012-09-26 14:06:58 +00001739 if (category == fcNormal && exponent+1 >= (int)semanticsPrecision(*semantics))
Owen Andersonc82cc582012-08-15 18:28:45 +00001740 return opOK;
1741
Owen Anderson7c626d32012-08-13 23:32:49 +00001742 // The algorithm here is quite simple: we add 2^(p-1), where p is the
1743 // precision of our format, and then subtract it back off again. The choice
1744 // of rounding modes for the addition/subtraction determines the rounding mode
1745 // for our integral rounding as well.
Owen Anderson7c289782012-08-15 16:42:53 +00001746 // NOTE: When the input value is negative, we do subtraction followed by
Owen Andersonf7a5dfc2012-08-15 05:39:46 +00001747 // addition instead.
Owen Andersond7a85b12012-08-14 18:51:15 +00001748 APInt IntegerConstant(NextPowerOf2(semanticsPrecision(*semantics)), 1);
1749 IntegerConstant <<= semanticsPrecision(*semantics)-1;
Owen Anderson7c626d32012-08-13 23:32:49 +00001750 APFloat MagicConstant(*semantics);
1751 fs = MagicConstant.convertFromAPInt(IntegerConstant, false,
1752 rmNearestTiesToEven);
Owen Andersonf7a5dfc2012-08-15 05:39:46 +00001753 MagicConstant.copySign(*this);
1754
Owen Anderson7c626d32012-08-13 23:32:49 +00001755 if (fs != opOK)
1756 return fs;
1757
Owen Andersonf7a5dfc2012-08-15 05:39:46 +00001758 // Preserve the input sign so that we can handle 0.0/-0.0 cases correctly.
1759 bool inputSign = isNegative();
1760
Owen Anderson7c626d32012-08-13 23:32:49 +00001761 fs = add(MagicConstant, rounding_mode);
1762 if (fs != opOK && fs != opInexact)
1763 return fs;
1764
1765 fs = subtract(MagicConstant, rounding_mode);
Owen Andersonf7a5dfc2012-08-15 05:39:46 +00001766
1767 // Restore the input sign.
1768 if (inputSign != isNegative())
1769 changeSign();
1770
Owen Anderson7c626d32012-08-13 23:32:49 +00001771 return fs;
1772}
1773
1774
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001775/* Comparison requires normalized numbers. */
1776APFloat::cmpResult
1777APFloat::compare(const APFloat &rhs) const
1778{
1779 cmpResult result;
1780
1781 assert(semantics == rhs.semantics);
1782
Mike Stumpf3dc0c02009-05-13 23:23:20 +00001783 switch (convolve(category, rhs.category)) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001784 default:
Torok Edwinc23197a2009-07-14 16:55:14 +00001785 llvm_unreachable(0);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001786
Dale Johanneseneaf08942007-08-31 04:03:46 +00001787 case convolve(fcNaN, fcZero):
1788 case convolve(fcNaN, fcNormal):
1789 case convolve(fcNaN, fcInfinity):
1790 case convolve(fcNaN, fcNaN):
1791 case convolve(fcZero, fcNaN):
1792 case convolve(fcNormal, fcNaN):
1793 case convolve(fcInfinity, fcNaN):
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001794 return cmpUnordered;
1795
1796 case convolve(fcInfinity, fcNormal):
1797 case convolve(fcInfinity, fcZero):
1798 case convolve(fcNormal, fcZero):
Dan Gohman16e02092010-03-24 19:38:02 +00001799 if (sign)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001800 return cmpLessThan;
1801 else
1802 return cmpGreaterThan;
1803
1804 case convolve(fcNormal, fcInfinity):
1805 case convolve(fcZero, fcInfinity):
1806 case convolve(fcZero, fcNormal):
Dan Gohman16e02092010-03-24 19:38:02 +00001807 if (rhs.sign)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001808 return cmpGreaterThan;
1809 else
1810 return cmpLessThan;
1811
1812 case convolve(fcInfinity, fcInfinity):
Dan Gohman16e02092010-03-24 19:38:02 +00001813 if (sign == rhs.sign)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001814 return cmpEqual;
Dan Gohman16e02092010-03-24 19:38:02 +00001815 else if (sign)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001816 return cmpLessThan;
1817 else
1818 return cmpGreaterThan;
1819
1820 case convolve(fcZero, fcZero):
1821 return cmpEqual;
1822
1823 case convolve(fcNormal, fcNormal):
1824 break;
1825 }
1826
1827 /* Two normal numbers. Do they have the same sign? */
Dan Gohman16e02092010-03-24 19:38:02 +00001828 if (sign != rhs.sign) {
1829 if (sign)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001830 result = cmpLessThan;
1831 else
1832 result = cmpGreaterThan;
1833 } else {
1834 /* Compare absolute values; invert result if negative. */
1835 result = compareAbsoluteValue(rhs);
1836
Dan Gohman16e02092010-03-24 19:38:02 +00001837 if (sign) {
1838 if (result == cmpLessThan)
Neil Booth4f881702007-09-26 21:33:42 +00001839 result = cmpGreaterThan;
Dan Gohman16e02092010-03-24 19:38:02 +00001840 else if (result == cmpGreaterThan)
Neil Booth4f881702007-09-26 21:33:42 +00001841 result = cmpLessThan;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001842 }
1843 }
1844
1845 return result;
1846}
1847
Dale Johannesen23a98552008-10-09 23:00:39 +00001848/// APFloat::convert - convert a value of one floating point type to another.
1849/// The return value corresponds to the IEEE754 exceptions. *losesInfo
1850/// records whether the transformation lost information, i.e. whether
1851/// converting the result back to the original type will produce the
1852/// original value (this is almost the same as return value==fsOK, but there
1853/// are edge cases where this is not so).
1854
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001855APFloat::opStatus
1856APFloat::convert(const fltSemantics &toSemantics,
Dale Johannesen23a98552008-10-09 23:00:39 +00001857 roundingMode rounding_mode, bool *losesInfo)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001858{
Neil Boothc8db43d2007-09-22 02:56:19 +00001859 lostFraction lostFraction;
1860 unsigned int newPartCount, oldPartCount;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001861 opStatus fs;
Eli Friedman44551422011-11-26 03:38:02 +00001862 int shift;
1863 const fltSemantics &fromSemantics = *semantics;
Neil Booth4f881702007-09-26 21:33:42 +00001864
Neil Boothc8db43d2007-09-22 02:56:19 +00001865 lostFraction = lfExactlyZero;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001866 newPartCount = partCountForBits(toSemantics.precision + 1);
Neil Boothc8db43d2007-09-22 02:56:19 +00001867 oldPartCount = partCount();
Eli Friedman44551422011-11-26 03:38:02 +00001868 shift = toSemantics.precision - fromSemantics.precision;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001869
Eli Friedman44551422011-11-26 03:38:02 +00001870 bool X86SpecialNan = false;
1871 if (&fromSemantics == &APFloat::x87DoubleExtended &&
1872 &toSemantics != &APFloat::x87DoubleExtended && category == fcNaN &&
1873 (!(*significandParts() & 0x8000000000000000ULL) ||
1874 !(*significandParts() & 0x4000000000000000ULL))) {
1875 // x86 has some unusual NaNs which cannot be represented in any other
1876 // format; note them here.
1877 X86SpecialNan = true;
1878 }
1879
1880 // If this is a truncation, perform the shift before we narrow the storage.
1881 if (shift < 0 && (category==fcNormal || category==fcNaN))
1882 lostFraction = shiftRight(significandParts(), oldPartCount, -shift);
1883
1884 // Fix the storage so it can hold to new value.
Neil Boothc8db43d2007-09-22 02:56:19 +00001885 if (newPartCount > oldPartCount) {
Eli Friedman44551422011-11-26 03:38:02 +00001886 // The new type requires more storage; make it available.
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001887 integerPart *newParts;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001888 newParts = new integerPart[newPartCount];
1889 APInt::tcSet(newParts, 0, newPartCount);
Dale Johannesen902ff942007-09-25 17:25:00 +00001890 if (category==fcNormal || category==fcNaN)
1891 APInt::tcAssign(newParts, significandParts(), oldPartCount);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001892 freeSignificand();
1893 significand.parts = newParts;
Eli Friedman44551422011-11-26 03:38:02 +00001894 } else if (newPartCount == 1 && oldPartCount != 1) {
1895 // Switch to built-in storage for a single part.
1896 integerPart newPart = 0;
1897 if (category==fcNormal || category==fcNaN)
1898 newPart = significandParts()[0];
1899 freeSignificand();
1900 significand.part = newPart;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001901 }
1902
Eli Friedman44551422011-11-26 03:38:02 +00001903 // Now that we have the right storage, switch the semantics.
1904 semantics = &toSemantics;
1905
1906 // If this is an extension, perform the shift now that the storage is
1907 // available.
1908 if (shift > 0 && (category==fcNormal || category==fcNaN))
1909 APInt::tcShiftLeft(significandParts(), newPartCount, shift);
1910
Dan Gohman16e02092010-03-24 19:38:02 +00001911 if (category == fcNormal) {
Neil Boothc8db43d2007-09-22 02:56:19 +00001912 fs = normalize(rounding_mode, lostFraction);
Dale Johannesen23a98552008-10-09 23:00:39 +00001913 *losesInfo = (fs != opOK);
Dale Johannesen902ff942007-09-25 17:25:00 +00001914 } else if (category == fcNaN) {
Eli Friedman44551422011-11-26 03:38:02 +00001915 *losesInfo = lostFraction != lfExactlyZero || X86SpecialNan;
Benjamin Kramerbd7561e2013-01-25 17:01:00 +00001916
1917 // For x87 extended precision, we want to make a NaN, not a special NaN if
1918 // the input wasn't special either.
1919 if (!X86SpecialNan && semantics == &APFloat::x87DoubleExtended)
1920 APInt::tcSetBit(significandParts(), semantics->precision - 1);
1921
Dale Johannesen902ff942007-09-25 17:25:00 +00001922 // gcc forces the Quiet bit on, which means (float)(double)(float_sNan)
1923 // does not give you back the same bits. This is dubious, and we
1924 // don't currently do it. You're really supposed to get
1925 // an invalid operation signal at runtime, but nobody does that.
Dale Johannesen23a98552008-10-09 23:00:39 +00001926 fs = opOK;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001927 } else {
Dale Johannesen23a98552008-10-09 23:00:39 +00001928 *losesInfo = false;
Eli Friedmanf9b1cd02011-11-28 18:50:37 +00001929 fs = opOK;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001930 }
1931
1932 return fs;
1933}
1934
1935/* Convert a floating point number to an integer according to the
1936 rounding mode. If the rounded integer value is out of range this
Neil Boothee7ae382007-11-01 22:43:37 +00001937 returns an invalid operation exception and the contents of the
1938 destination parts are unspecified. If the rounded value is in
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001939 range but the floating point number is not the exact integer, the C
1940 standard doesn't require an inexact exception to be raised. IEEE
1941 854 does require it so we do that.
1942
1943 Note that for conversions to integer type the C standard requires
1944 round-to-zero to always be used. */
1945APFloat::opStatus
Neil Boothee7ae382007-11-01 22:43:37 +00001946APFloat::convertToSignExtendedInteger(integerPart *parts, unsigned int width,
1947 bool isSigned,
Dale Johannesen23a98552008-10-09 23:00:39 +00001948 roundingMode rounding_mode,
1949 bool *isExact) const
Neil Boothee7ae382007-11-01 22:43:37 +00001950{
1951 lostFraction lost_fraction;
1952 const integerPart *src;
1953 unsigned int dstPartsCount, truncatedBits;
1954
Dale Johannesen23a98552008-10-09 23:00:39 +00001955 *isExact = false;
1956
Neil Boothee7ae382007-11-01 22:43:37 +00001957 /* Handle the three special cases first. */
Dan Gohman16e02092010-03-24 19:38:02 +00001958 if (category == fcInfinity || category == fcNaN)
Neil Boothee7ae382007-11-01 22:43:37 +00001959 return opInvalidOp;
1960
1961 dstPartsCount = partCountForBits(width);
1962
Dan Gohman16e02092010-03-24 19:38:02 +00001963 if (category == fcZero) {
Neil Boothee7ae382007-11-01 22:43:37 +00001964 APInt::tcSet(parts, 0, dstPartsCount);
Dale Johannesene4a42452008-10-07 00:40:01 +00001965 // Negative zero can't be represented as an int.
Dale Johannesen23a98552008-10-09 23:00:39 +00001966 *isExact = !sign;
1967 return opOK;
Neil Boothee7ae382007-11-01 22:43:37 +00001968 }
1969
1970 src = significandParts();
1971
1972 /* Step 1: place our absolute value, with any fraction truncated, in
1973 the destination. */
1974 if (exponent < 0) {
1975 /* Our absolute value is less than one; truncate everything. */
1976 APInt::tcSet(parts, 0, dstPartsCount);
Dale Johannesen1f54f582009-01-19 21:17:05 +00001977 /* For exponent -1 the integer bit represents .5, look at that.
1978 For smaller exponents leftmost truncated bit is 0. */
1979 truncatedBits = semantics->precision -1U - exponent;
Neil Boothee7ae382007-11-01 22:43:37 +00001980 } else {
1981 /* We want the most significant (exponent + 1) bits; the rest are
1982 truncated. */
1983 unsigned int bits = exponent + 1U;
1984
1985 /* Hopelessly large in magnitude? */
1986 if (bits > width)
1987 return opInvalidOp;
1988
1989 if (bits < semantics->precision) {
1990 /* We truncate (semantics->precision - bits) bits. */
1991 truncatedBits = semantics->precision - bits;
1992 APInt::tcExtract(parts, dstPartsCount, src, bits, truncatedBits);
1993 } else {
1994 /* We want at least as many bits as are available. */
1995 APInt::tcExtract(parts, dstPartsCount, src, semantics->precision, 0);
1996 APInt::tcShiftLeft(parts, dstPartsCount, bits - semantics->precision);
1997 truncatedBits = 0;
1998 }
1999 }
2000
2001 /* Step 2: work out any lost fraction, and increment the absolute
2002 value if we would round away from zero. */
2003 if (truncatedBits) {
2004 lost_fraction = lostFractionThroughTruncation(src, partCount(),
2005 truncatedBits);
Dan Gohman16e02092010-03-24 19:38:02 +00002006 if (lost_fraction != lfExactlyZero &&
2007 roundAwayFromZero(rounding_mode, lost_fraction, truncatedBits)) {
Neil Boothee7ae382007-11-01 22:43:37 +00002008 if (APInt::tcIncrement(parts, dstPartsCount))
2009 return opInvalidOp; /* Overflow. */
2010 }
2011 } else {
2012 lost_fraction = lfExactlyZero;
2013 }
2014
2015 /* Step 3: check if we fit in the destination. */
2016 unsigned int omsb = APInt::tcMSB(parts, dstPartsCount) + 1;
2017
2018 if (sign) {
2019 if (!isSigned) {
2020 /* Negative numbers cannot be represented as unsigned. */
2021 if (omsb != 0)
2022 return opInvalidOp;
2023 } else {
2024 /* It takes omsb bits to represent the unsigned integer value.
2025 We lose a bit for the sign, but care is needed as the
2026 maximally negative integer is a special case. */
2027 if (omsb == width && APInt::tcLSB(parts, dstPartsCount) + 1 != omsb)
2028 return opInvalidOp;
2029
2030 /* This case can happen because of rounding. */
2031 if (omsb > width)
2032 return opInvalidOp;
2033 }
2034
2035 APInt::tcNegate (parts, dstPartsCount);
2036 } else {
2037 if (omsb >= width + !isSigned)
2038 return opInvalidOp;
2039 }
2040
Dale Johannesen23a98552008-10-09 23:00:39 +00002041 if (lost_fraction == lfExactlyZero) {
2042 *isExact = true;
Neil Boothee7ae382007-11-01 22:43:37 +00002043 return opOK;
Dale Johannesen23a98552008-10-09 23:00:39 +00002044 } else
Neil Boothee7ae382007-11-01 22:43:37 +00002045 return opInexact;
2046}
2047
2048/* Same as convertToSignExtendedInteger, except we provide
2049 deterministic values in case of an invalid operation exception,
2050 namely zero for NaNs and the minimal or maximal value respectively
Dale Johannesen23a98552008-10-09 23:00:39 +00002051 for underflow or overflow.
2052 The *isExact output tells whether the result is exact, in the sense
2053 that converting it back to the original floating point type produces
2054 the original value. This is almost equivalent to result==opOK,
2055 except for negative zeroes.
2056*/
Neil Boothee7ae382007-11-01 22:43:37 +00002057APFloat::opStatus
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002058APFloat::convertToInteger(integerPart *parts, unsigned int width,
Neil Booth4f881702007-09-26 21:33:42 +00002059 bool isSigned,
Dale Johannesen23a98552008-10-09 23:00:39 +00002060 roundingMode rounding_mode, bool *isExact) const
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002061{
Neil Boothee7ae382007-11-01 22:43:37 +00002062 opStatus fs;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002063
Dan Gohman16e02092010-03-24 19:38:02 +00002064 fs = convertToSignExtendedInteger(parts, width, isSigned, rounding_mode,
Dale Johannesen23a98552008-10-09 23:00:39 +00002065 isExact);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002066
Neil Boothee7ae382007-11-01 22:43:37 +00002067 if (fs == opInvalidOp) {
2068 unsigned int bits, dstPartsCount;
2069
2070 dstPartsCount = partCountForBits(width);
2071
2072 if (category == fcNaN)
2073 bits = 0;
2074 else if (sign)
2075 bits = isSigned;
2076 else
2077 bits = width - isSigned;
2078
2079 APInt::tcSetLeastSignificantBits(parts, dstPartsCount, bits);
2080 if (sign && isSigned)
2081 APInt::tcShiftLeft(parts, dstPartsCount, width - 1);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002082 }
2083
Neil Boothee7ae382007-11-01 22:43:37 +00002084 return fs;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002085}
2086
Jeffrey Yasskin3d42bfb2011-07-15 07:04:56 +00002087/* Same as convertToInteger(integerPart*, ...), except the result is returned in
2088 an APSInt, whose initial bit-width and signed-ness are used to determine the
2089 precision of the conversion.
2090 */
2091APFloat::opStatus
2092APFloat::convertToInteger(APSInt &result,
2093 roundingMode rounding_mode, bool *isExact) const
2094{
2095 unsigned bitWidth = result.getBitWidth();
2096 SmallVector<uint64_t, 4> parts(result.getNumWords());
2097 opStatus status = convertToInteger(
2098 parts.data(), bitWidth, result.isSigned(), rounding_mode, isExact);
2099 // Keeps the original signed-ness.
Jeffrey Yasskin3ba292d2011-07-18 21:45:40 +00002100 result = APInt(bitWidth, parts);
Jeffrey Yasskin3d42bfb2011-07-15 07:04:56 +00002101 return status;
2102}
2103
Neil Booth643ce592007-10-07 12:07:53 +00002104/* Convert an unsigned integer SRC to a floating point number,
2105 rounding according to ROUNDING_MODE. The sign of the floating
2106 point number is not modified. */
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002107APFloat::opStatus
Neil Booth643ce592007-10-07 12:07:53 +00002108APFloat::convertFromUnsignedParts(const integerPart *src,
2109 unsigned int srcCount,
2110 roundingMode rounding_mode)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002111{
Neil Booth5477f852007-10-08 14:39:42 +00002112 unsigned int omsb, precision, dstCount;
Neil Booth643ce592007-10-07 12:07:53 +00002113 integerPart *dst;
Neil Booth5477f852007-10-08 14:39:42 +00002114 lostFraction lost_fraction;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002115
2116 category = fcNormal;
Neil Booth5477f852007-10-08 14:39:42 +00002117 omsb = APInt::tcMSB(src, srcCount) + 1;
Neil Booth643ce592007-10-07 12:07:53 +00002118 dst = significandParts();
2119 dstCount = partCount();
Neil Booth5477f852007-10-08 14:39:42 +00002120 precision = semantics->precision;
Neil Booth643ce592007-10-07 12:07:53 +00002121
Nick Lewycky03dd4e82011-10-03 21:30:08 +00002122 /* We want the most significant PRECISION bits of SRC. There may not
Neil Booth5477f852007-10-08 14:39:42 +00002123 be that many; extract what we can. */
2124 if (precision <= omsb) {
2125 exponent = omsb - 1;
Neil Booth643ce592007-10-07 12:07:53 +00002126 lost_fraction = lostFractionThroughTruncation(src, srcCount,
Neil Booth5477f852007-10-08 14:39:42 +00002127 omsb - precision);
2128 APInt::tcExtract(dst, dstCount, src, precision, omsb - precision);
2129 } else {
2130 exponent = precision - 1;
2131 lost_fraction = lfExactlyZero;
2132 APInt::tcExtract(dst, dstCount, src, omsb, 0);
Neil Booth643ce592007-10-07 12:07:53 +00002133 }
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002134
2135 return normalize(rounding_mode, lost_fraction);
2136}
2137
Dan Gohman93c276e2008-02-29 01:26:11 +00002138APFloat::opStatus
2139APFloat::convertFromAPInt(const APInt &Val,
2140 bool isSigned,
2141 roundingMode rounding_mode)
2142{
2143 unsigned int partCount = Val.getNumWords();
2144 APInt api = Val;
2145
2146 sign = false;
2147 if (isSigned && api.isNegative()) {
2148 sign = true;
2149 api = -api;
2150 }
2151
2152 return convertFromUnsignedParts(api.getRawData(), partCount, rounding_mode);
2153}
2154
Neil Boothf16c5952007-10-07 12:15:41 +00002155/* Convert a two's complement integer SRC to a floating point number,
2156 rounding according to ROUNDING_MODE. ISSIGNED is true if the
2157 integer is signed, in which case it must be sign-extended. */
2158APFloat::opStatus
2159APFloat::convertFromSignExtendedInteger(const integerPart *src,
2160 unsigned int srcCount,
2161 bool isSigned,
2162 roundingMode rounding_mode)
2163{
2164 opStatus status;
2165
Dan Gohman16e02092010-03-24 19:38:02 +00002166 if (isSigned &&
2167 APInt::tcExtractBit(src, srcCount * integerPartWidth - 1)) {
Neil Boothf16c5952007-10-07 12:15:41 +00002168 integerPart *copy;
2169
2170 /* If we're signed and negative negate a copy. */
2171 sign = true;
2172 copy = new integerPart[srcCount];
2173 APInt::tcAssign(copy, src, srcCount);
2174 APInt::tcNegate(copy, srcCount);
2175 status = convertFromUnsignedParts(copy, srcCount, rounding_mode);
2176 delete [] copy;
2177 } else {
2178 sign = false;
2179 status = convertFromUnsignedParts(src, srcCount, rounding_mode);
2180 }
2181
2182 return status;
2183}
2184
Neil Boothccf596a2007-10-07 11:45:55 +00002185/* FIXME: should this just take a const APInt reference? */
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002186APFloat::opStatus
Neil Boothccf596a2007-10-07 11:45:55 +00002187APFloat::convertFromZeroExtendedInteger(const integerPart *parts,
2188 unsigned int width, bool isSigned,
2189 roundingMode rounding_mode)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002190{
Dale Johannesen910993e2007-09-21 22:09:37 +00002191 unsigned int partCount = partCountForBits(width);
Jeffrey Yasskin3ba292d2011-07-18 21:45:40 +00002192 APInt api = APInt(width, makeArrayRef(parts, partCount));
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002193
2194 sign = false;
Dan Gohman16e02092010-03-24 19:38:02 +00002195 if (isSigned && APInt::tcExtractBit(parts, width - 1)) {
Dale Johannesencce23a42007-09-30 18:17:01 +00002196 sign = true;
2197 api = -api;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002198 }
2199
Neil Booth7a7bc0f2007-10-07 12:10:57 +00002200 return convertFromUnsignedParts(api.getRawData(), partCount, rounding_mode);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002201}
2202
2203APFloat::opStatus
Benjamin Kramer38e59892010-07-14 22:38:02 +00002204APFloat::convertFromHexadecimalString(StringRef s, roundingMode rounding_mode)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002205{
Erick Tryzelaarf8bc8012009-08-18 18:20:37 +00002206 lostFraction lost_fraction = lfExactlyZero;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002207 integerPart *significand;
2208 unsigned int bitPos, partsCount;
Erick Tryzelaara15d8902009-08-16 23:36:19 +00002209 StringRef::iterator dot, firstSignificantDigit;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002210
2211 zeroSignificand();
2212 exponent = 0;
2213 category = fcNormal;
2214
2215 significand = significandParts();
2216 partsCount = partCount();
2217 bitPos = partsCount * integerPartWidth;
2218
Neil Booth33d4c922007-10-07 08:51:21 +00002219 /* Skip leading zeroes and any (hexa)decimal point. */
Erick Tryzelaarc78b33b2009-08-20 23:30:43 +00002220 StringRef::iterator begin = s.begin();
2221 StringRef::iterator end = s.end();
2222 StringRef::iterator p = skipLeadingZeroesAndAnyDot(begin, end, &dot);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002223 firstSignificantDigit = p;
2224
Dan Gohman16e02092010-03-24 19:38:02 +00002225 for (; p != end;) {
Dale Johannesen386f3e92008-05-14 22:53:25 +00002226 integerPart hex_value;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002227
Dan Gohman16e02092010-03-24 19:38:02 +00002228 if (*p == '.') {
Erick Tryzelaarc78b33b2009-08-20 23:30:43 +00002229 assert(dot == end && "String contains multiple dots");
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002230 dot = p++;
Erick Tryzelaarc78b33b2009-08-20 23:30:43 +00002231 if (p == end) {
2232 break;
2233 }
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002234 }
2235
2236 hex_value = hexDigitValue(*p);
Dan Gohman16e02092010-03-24 19:38:02 +00002237 if (hex_value == -1U) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002238 break;
2239 }
2240
2241 p++;
2242
Erick Tryzelaarc78b33b2009-08-20 23:30:43 +00002243 if (p == end) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002244 break;
Erick Tryzelaara15d8902009-08-16 23:36:19 +00002245 } else {
2246 /* Store the number whilst 4-bit nibbles remain. */
Dan Gohman16e02092010-03-24 19:38:02 +00002247 if (bitPos) {
Erick Tryzelaara15d8902009-08-16 23:36:19 +00002248 bitPos -= 4;
2249 hex_value <<= bitPos % integerPartWidth;
2250 significand[bitPos / integerPartWidth] |= hex_value;
2251 } else {
Erick Tryzelaarc78b33b2009-08-20 23:30:43 +00002252 lost_fraction = trailingHexadecimalFraction(p, end, hex_value);
Dan Gohman16e02092010-03-24 19:38:02 +00002253 while (p != end && hexDigitValue(*p) != -1U)
Erick Tryzelaara15d8902009-08-16 23:36:19 +00002254 p++;
2255 break;
2256 }
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002257 }
2258 }
2259
2260 /* Hex floats require an exponent but not a hexadecimal point. */
Erick Tryzelaarc78b33b2009-08-20 23:30:43 +00002261 assert(p != end && "Hex strings require an exponent");
2262 assert((*p == 'p' || *p == 'P') && "Invalid character in significand");
2263 assert(p != begin && "Significand has no digits");
2264 assert((dot == end || p - begin != 1) && "Significand has no digits");
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002265
2266 /* Ignore the exponent if we are zero. */
Dan Gohman16e02092010-03-24 19:38:02 +00002267 if (p != firstSignificantDigit) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002268 int expAdjustment;
2269
2270 /* Implicit hexadecimal point? */
Erick Tryzelaarc78b33b2009-08-20 23:30:43 +00002271 if (dot == end)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002272 dot = p;
2273
2274 /* Calculate the exponent adjustment implicit in the number of
2275 significant digits. */
Evan Cheng48e8c802008-05-02 21:15:08 +00002276 expAdjustment = static_cast<int>(dot - firstSignificantDigit);
Dan Gohman16e02092010-03-24 19:38:02 +00002277 if (expAdjustment < 0)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002278 expAdjustment++;
2279 expAdjustment = expAdjustment * 4 - 1;
2280
2281 /* Adjust for writing the significand starting at the most
2282 significant nibble. */
2283 expAdjustment += semantics->precision;
2284 expAdjustment -= partsCount * integerPartWidth;
2285
2286 /* Adjust for the given exponent. */
Erick Tryzelaarc78b33b2009-08-20 23:30:43 +00002287 exponent = totalExponent(p + 1, end, expAdjustment);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002288 }
2289
2290 return normalize(rounding_mode, lost_fraction);
2291}
2292
2293APFloat::opStatus
Neil Booth96c74712007-10-12 16:02:31 +00002294APFloat::roundSignificandWithExponent(const integerPart *decSigParts,
2295 unsigned sigPartCount, int exp,
2296 roundingMode rounding_mode)
2297{
2298 unsigned int parts, pow5PartCount;
Ulrich Weigand159c7352012-10-29 18:18:44 +00002299 fltSemantics calcSemantics = { 32767, -32767, 0 };
Neil Booth96c74712007-10-12 16:02:31 +00002300 integerPart pow5Parts[maxPowerOfFiveParts];
2301 bool isNearest;
2302
Dan Gohman16e02092010-03-24 19:38:02 +00002303 isNearest = (rounding_mode == rmNearestTiesToEven ||
2304 rounding_mode == rmNearestTiesToAway);
Neil Booth96c74712007-10-12 16:02:31 +00002305
2306 parts = partCountForBits(semantics->precision + 11);
2307
2308 /* Calculate pow(5, abs(exp)). */
2309 pow5PartCount = powerOf5(pow5Parts, exp >= 0 ? exp: -exp);
2310
2311 for (;; parts *= 2) {
2312 opStatus sigStatus, powStatus;
2313 unsigned int excessPrecision, truncatedBits;
2314
2315 calcSemantics.precision = parts * integerPartWidth - 1;
2316 excessPrecision = calcSemantics.precision - semantics->precision;
2317 truncatedBits = excessPrecision;
2318
2319 APFloat decSig(calcSemantics, fcZero, sign);
2320 APFloat pow5(calcSemantics, fcZero, false);
2321
2322 sigStatus = decSig.convertFromUnsignedParts(decSigParts, sigPartCount,
2323 rmNearestTiesToEven);
2324 powStatus = pow5.convertFromUnsignedParts(pow5Parts, pow5PartCount,
2325 rmNearestTiesToEven);
2326 /* Add exp, as 10^n = 5^n * 2^n. */
2327 decSig.exponent += exp;
2328
2329 lostFraction calcLostFraction;
Evan Cheng48e8c802008-05-02 21:15:08 +00002330 integerPart HUerr, HUdistance;
2331 unsigned int powHUerr;
Neil Booth96c74712007-10-12 16:02:31 +00002332
2333 if (exp >= 0) {
2334 /* multiplySignificand leaves the precision-th bit set to 1. */
2335 calcLostFraction = decSig.multiplySignificand(pow5, NULL);
2336 powHUerr = powStatus != opOK;
2337 } else {
2338 calcLostFraction = decSig.divideSignificand(pow5);
2339 /* Denormal numbers have less precision. */
2340 if (decSig.exponent < semantics->minExponent) {
2341 excessPrecision += (semantics->minExponent - decSig.exponent);
2342 truncatedBits = excessPrecision;
2343 if (excessPrecision > calcSemantics.precision)
2344 excessPrecision = calcSemantics.precision;
2345 }
2346 /* Extra half-ulp lost in reciprocal of exponent. */
Evan Cheng48e8c802008-05-02 21:15:08 +00002347 powHUerr = (powStatus == opOK && calcLostFraction == lfExactlyZero) ? 0:2;
Neil Booth96c74712007-10-12 16:02:31 +00002348 }
2349
2350 /* Both multiplySignificand and divideSignificand return the
2351 result with the integer bit set. */
Evan Cheng99ebfa52009-10-27 21:35:42 +00002352 assert(APInt::tcExtractBit
2353 (decSig.significandParts(), calcSemantics.precision - 1) == 1);
Neil Booth96c74712007-10-12 16:02:31 +00002354
2355 HUerr = HUerrBound(calcLostFraction != lfExactlyZero, sigStatus != opOK,
2356 powHUerr);
2357 HUdistance = 2 * ulpsFromBoundary(decSig.significandParts(),
2358 excessPrecision, isNearest);
2359
2360 /* Are we guaranteed to round correctly if we truncate? */
2361 if (HUdistance >= HUerr) {
2362 APInt::tcExtract(significandParts(), partCount(), decSig.significandParts(),
2363 calcSemantics.precision - excessPrecision,
2364 excessPrecision);
2365 /* Take the exponent of decSig. If we tcExtract-ed less bits
2366 above we must adjust our exponent to compensate for the
2367 implicit right shift. */
2368 exponent = (decSig.exponent + semantics->precision
2369 - (calcSemantics.precision - excessPrecision));
2370 calcLostFraction = lostFractionThroughTruncation(decSig.significandParts(),
2371 decSig.partCount(),
2372 truncatedBits);
2373 return normalize(rounding_mode, calcLostFraction);
2374 }
2375 }
2376}
2377
2378APFloat::opStatus
Benjamin Kramer38e59892010-07-14 22:38:02 +00002379APFloat::convertFromDecimalString(StringRef str, roundingMode rounding_mode)
Neil Booth96c74712007-10-12 16:02:31 +00002380{
Neil Booth1870f292007-10-14 10:16:12 +00002381 decimalInfo D;
Neil Booth96c74712007-10-12 16:02:31 +00002382 opStatus fs;
2383
Neil Booth1870f292007-10-14 10:16:12 +00002384 /* Scan the text. */
Erick Tryzelaara15d8902009-08-16 23:36:19 +00002385 StringRef::iterator p = str.begin();
2386 interpretDecimal(p, str.end(), &D);
Neil Booth96c74712007-10-12 16:02:31 +00002387
Neil Booth686700e2007-10-15 15:00:55 +00002388 /* Handle the quick cases. First the case of no significant digits,
2389 i.e. zero, and then exponents that are obviously too large or too
2390 small. Writing L for log 10 / log 2, a number d.ddddd*10^exp
2391 definitely overflows if
2392
2393 (exp - 1) * L >= maxExponent
2394
2395 and definitely underflows to zero where
2396
2397 (exp + 1) * L <= minExponent - precision
2398
2399 With integer arithmetic the tightest bounds for L are
2400
2401 93/28 < L < 196/59 [ numerator <= 256 ]
2402 42039/12655 < L < 28738/8651 [ numerator <= 65536 ]
2403 */
2404
Neil Boothcc233592007-12-05 13:06:04 +00002405 if (decDigitValue(*D.firstSigDigit) >= 10U) {
Neil Booth96c74712007-10-12 16:02:31 +00002406 category = fcZero;
2407 fs = opOK;
John McCall8b3f3302010-02-26 22:20:41 +00002408
2409 /* Check whether the normalized exponent is high enough to overflow
2410 max during the log-rebasing in the max-exponent check below. */
2411 } else if (D.normalizedExponent - 1 > INT_MAX / 42039) {
2412 fs = handleOverflow(rounding_mode);
2413
2414 /* If it wasn't, then it also wasn't high enough to overflow max
2415 during the log-rebasing in the min-exponent check. Check that it
2416 won't overflow min in either check, then perform the min-exponent
2417 check. */
2418 } else if (D.normalizedExponent - 1 < INT_MIN / 42039 ||
2419 (D.normalizedExponent + 1) * 28738 <=
2420 8651 * (semantics->minExponent - (int) semantics->precision)) {
Neil Booth686700e2007-10-15 15:00:55 +00002421 /* Underflow to zero and round. */
2422 zeroSignificand();
2423 fs = normalize(rounding_mode, lfLessThanHalf);
John McCall8b3f3302010-02-26 22:20:41 +00002424
2425 /* We can finally safely perform the max-exponent check. */
Neil Booth686700e2007-10-15 15:00:55 +00002426 } else if ((D.normalizedExponent - 1) * 42039
2427 >= 12655 * semantics->maxExponent) {
2428 /* Overflow and round. */
2429 fs = handleOverflow(rounding_mode);
Neil Booth96c74712007-10-12 16:02:31 +00002430 } else {
Neil Booth1870f292007-10-14 10:16:12 +00002431 integerPart *decSignificand;
2432 unsigned int partCount;
Neil Booth96c74712007-10-12 16:02:31 +00002433
Neil Booth1870f292007-10-14 10:16:12 +00002434 /* A tight upper bound on number of bits required to hold an
Neil Booth686700e2007-10-15 15:00:55 +00002435 N-digit decimal integer is N * 196 / 59. Allocate enough space
Neil Booth1870f292007-10-14 10:16:12 +00002436 to hold the full significand, and an extra part required by
2437 tcMultiplyPart. */
Evan Cheng48e8c802008-05-02 21:15:08 +00002438 partCount = static_cast<unsigned int>(D.lastSigDigit - D.firstSigDigit) + 1;
Neil Booth686700e2007-10-15 15:00:55 +00002439 partCount = partCountForBits(1 + 196 * partCount / 59);
Neil Booth1870f292007-10-14 10:16:12 +00002440 decSignificand = new integerPart[partCount + 1];
2441 partCount = 0;
Neil Booth96c74712007-10-12 16:02:31 +00002442
Neil Booth1870f292007-10-14 10:16:12 +00002443 /* Convert to binary efficiently - we do almost all multiplication
2444 in an integerPart. When this would overflow do we do a single
2445 bignum multiplication, and then revert again to multiplication
2446 in an integerPart. */
2447 do {
2448 integerPart decValue, val, multiplier;
2449
2450 val = 0;
2451 multiplier = 1;
2452
2453 do {
Erick Tryzelaara15d8902009-08-16 23:36:19 +00002454 if (*p == '.') {
Neil Booth1870f292007-10-14 10:16:12 +00002455 p++;
Erick Tryzelaara15d8902009-08-16 23:36:19 +00002456 if (p == str.end()) {
2457 break;
2458 }
2459 }
Neil Booth1870f292007-10-14 10:16:12 +00002460 decValue = decDigitValue(*p++);
Erick Tryzelaarc78b33b2009-08-20 23:30:43 +00002461 assert(decValue < 10U && "Invalid character in significand");
Neil Booth1870f292007-10-14 10:16:12 +00002462 multiplier *= 10;
2463 val = val * 10 + decValue;
2464 /* The maximum number that can be multiplied by ten with any
2465 digit added without overflowing an integerPart. */
2466 } while (p <= D.lastSigDigit && multiplier <= (~ (integerPart) 0 - 9) / 10);
2467
2468 /* Multiply out the current part. */
2469 APInt::tcMultiplyPart(decSignificand, decSignificand, multiplier, val,
2470 partCount, partCount + 1, false);
2471
2472 /* If we used another part (likely but not guaranteed), increase
2473 the count. */
2474 if (decSignificand[partCount])
2475 partCount++;
2476 } while (p <= D.lastSigDigit);
Neil Booth96c74712007-10-12 16:02:31 +00002477
Neil Booth43a4b282007-11-01 22:51:07 +00002478 category = fcNormal;
Neil Booth96c74712007-10-12 16:02:31 +00002479 fs = roundSignificandWithExponent(decSignificand, partCount,
Neil Booth1870f292007-10-14 10:16:12 +00002480 D.exponent, rounding_mode);
Neil Booth96c74712007-10-12 16:02:31 +00002481
Neil Booth1870f292007-10-14 10:16:12 +00002482 delete [] decSignificand;
2483 }
Neil Booth96c74712007-10-12 16:02:31 +00002484
2485 return fs;
2486}
2487
2488APFloat::opStatus
Benjamin Kramer38e59892010-07-14 22:38:02 +00002489APFloat::convertFromString(StringRef str, roundingMode rounding_mode)
Neil Booth4f881702007-09-26 21:33:42 +00002490{
Erick Tryzelaara15d8902009-08-16 23:36:19 +00002491 assert(!str.empty() && "Invalid string length");
Neil Boothcaf19d72007-10-14 10:29:28 +00002492
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002493 /* Handle a leading minus sign. */
Erick Tryzelaara15d8902009-08-16 23:36:19 +00002494 StringRef::iterator p = str.begin();
2495 size_t slen = str.size();
Erick Tryzelaarc78b33b2009-08-20 23:30:43 +00002496 sign = *p == '-' ? 1 : 0;
Dan Gohman16e02092010-03-24 19:38:02 +00002497 if (*p == '-' || *p == '+') {
Erick Tryzelaara15d8902009-08-16 23:36:19 +00002498 p++;
2499 slen--;
Erick Tryzelaarc78b33b2009-08-20 23:30:43 +00002500 assert(slen && "String has no digits");
Erick Tryzelaara15d8902009-08-16 23:36:19 +00002501 }
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002502
Dan Gohman16e02092010-03-24 19:38:02 +00002503 if (slen >= 2 && p[0] == '0' && (p[1] == 'x' || p[1] == 'X')) {
Erick Tryzelaara15d8902009-08-16 23:36:19 +00002504 assert(slen - 2 && "Invalid string");
Erick Tryzelaarc78b33b2009-08-20 23:30:43 +00002505 return convertFromHexadecimalString(StringRef(p + 2, slen - 2),
Erick Tryzelaara15d8902009-08-16 23:36:19 +00002506 rounding_mode);
2507 }
Bill Wendlingb7c0d942008-11-27 08:00:12 +00002508
Erick Tryzelaarc78b33b2009-08-20 23:30:43 +00002509 return convertFromDecimalString(StringRef(p, slen), rounding_mode);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002510}
Dale Johannesen343e7702007-08-24 00:56:33 +00002511
Neil Bootha30b0ee2007-10-03 22:26:02 +00002512/* Write out a hexadecimal representation of the floating point value
2513 to DST, which must be of sufficient size, in the C99 form
2514 [-]0xh.hhhhp[+-]d. Return the number of characters written,
2515 excluding the terminating NUL.
2516
2517 If UPPERCASE, the output is in upper case, otherwise in lower case.
2518
2519 HEXDIGITS digits appear altogether, rounding the value if
2520 necessary. If HEXDIGITS is 0, the minimal precision to display the
2521 number precisely is used instead. If nothing would appear after
2522 the decimal point it is suppressed.
2523
2524 The decimal exponent is always printed and has at least one digit.
2525 Zero values display an exponent of zero. Infinities and NaNs
2526 appear as "infinity" or "nan" respectively.
2527
2528 The above rules are as specified by C99. There is ambiguity about
2529 what the leading hexadecimal digit should be. This implementation
2530 uses whatever is necessary so that the exponent is displayed as
2531 stored. This implies the exponent will fall within the IEEE format
2532 range, and the leading hexadecimal digit will be 0 (for denormals),
2533 1 (normal numbers) or 2 (normal numbers rounded-away-from-zero with
2534 any other digits zero).
2535*/
2536unsigned int
2537APFloat::convertToHexString(char *dst, unsigned int hexDigits,
2538 bool upperCase, roundingMode rounding_mode) const
2539{
2540 char *p;
2541
2542 p = dst;
2543 if (sign)
2544 *dst++ = '-';
2545
2546 switch (category) {
2547 case fcInfinity:
2548 memcpy (dst, upperCase ? infinityU: infinityL, sizeof infinityU - 1);
2549 dst += sizeof infinityL - 1;
2550 break;
2551
2552 case fcNaN:
2553 memcpy (dst, upperCase ? NaNU: NaNL, sizeof NaNU - 1);
2554 dst += sizeof NaNU - 1;
2555 break;
2556
2557 case fcZero:
2558 *dst++ = '0';
2559 *dst++ = upperCase ? 'X': 'x';
2560 *dst++ = '0';
2561 if (hexDigits > 1) {
2562 *dst++ = '.';
2563 memset (dst, '0', hexDigits - 1);
2564 dst += hexDigits - 1;
2565 }
2566 *dst++ = upperCase ? 'P': 'p';
2567 *dst++ = '0';
2568 break;
2569
2570 case fcNormal:
2571 dst = convertNormalToHexString (dst, hexDigits, upperCase, rounding_mode);
2572 break;
2573 }
2574
2575 *dst = 0;
2576
Evan Cheng48e8c802008-05-02 21:15:08 +00002577 return static_cast<unsigned int>(dst - p);
Neil Bootha30b0ee2007-10-03 22:26:02 +00002578}
2579
2580/* Does the hard work of outputting the correctly rounded hexadecimal
2581 form of a normal floating point number with the specified number of
2582 hexadecimal digits. If HEXDIGITS is zero the minimum number of
2583 digits necessary to print the value precisely is output. */
2584char *
2585APFloat::convertNormalToHexString(char *dst, unsigned int hexDigits,
2586 bool upperCase,
2587 roundingMode rounding_mode) const
2588{
2589 unsigned int count, valueBits, shift, partsCount, outputDigits;
2590 const char *hexDigitChars;
2591 const integerPart *significand;
2592 char *p;
2593 bool roundUp;
2594
2595 *dst++ = '0';
2596 *dst++ = upperCase ? 'X': 'x';
2597
2598 roundUp = false;
2599 hexDigitChars = upperCase ? hexDigitsUpper: hexDigitsLower;
2600
2601 significand = significandParts();
2602 partsCount = partCount();
2603
2604 /* +3 because the first digit only uses the single integer bit, so
2605 we have 3 virtual zero most-significant-bits. */
2606 valueBits = semantics->precision + 3;
2607 shift = integerPartWidth - valueBits % integerPartWidth;
2608
2609 /* The natural number of digits required ignoring trailing
2610 insignificant zeroes. */
2611 outputDigits = (valueBits - significandLSB () + 3) / 4;
2612
2613 /* hexDigits of zero means use the required number for the
2614 precision. Otherwise, see if we are truncating. If we are,
Neil Booth978661d2007-10-06 00:24:48 +00002615 find out if we need to round away from zero. */
Neil Bootha30b0ee2007-10-03 22:26:02 +00002616 if (hexDigits) {
2617 if (hexDigits < outputDigits) {
2618 /* We are dropping non-zero bits, so need to check how to round.
2619 "bits" is the number of dropped bits. */
2620 unsigned int bits;
2621 lostFraction fraction;
2622
2623 bits = valueBits - hexDigits * 4;
2624 fraction = lostFractionThroughTruncation (significand, partsCount, bits);
2625 roundUp = roundAwayFromZero(rounding_mode, fraction, bits);
2626 }
2627 outputDigits = hexDigits;
2628 }
2629
2630 /* Write the digits consecutively, and start writing in the location
2631 of the hexadecimal point. We move the most significant digit
2632 left and add the hexadecimal point later. */
2633 p = ++dst;
2634
2635 count = (valueBits + integerPartWidth - 1) / integerPartWidth;
2636
2637 while (outputDigits && count) {
2638 integerPart part;
2639
2640 /* Put the most significant integerPartWidth bits in "part". */
2641 if (--count == partsCount)
2642 part = 0; /* An imaginary higher zero part. */
2643 else
2644 part = significand[count] << shift;
2645
2646 if (count && shift)
2647 part |= significand[count - 1] >> (integerPartWidth - shift);
2648
2649 /* Convert as much of "part" to hexdigits as we can. */
2650 unsigned int curDigits = integerPartWidth / 4;
2651
2652 if (curDigits > outputDigits)
2653 curDigits = outputDigits;
2654 dst += partAsHex (dst, part, curDigits, hexDigitChars);
2655 outputDigits -= curDigits;
2656 }
2657
2658 if (roundUp) {
2659 char *q = dst;
2660
2661 /* Note that hexDigitChars has a trailing '0'. */
2662 do {
2663 q--;
2664 *q = hexDigitChars[hexDigitValue (*q) + 1];
Neil Booth978661d2007-10-06 00:24:48 +00002665 } while (*q == '0');
Evan Cheng99ebfa52009-10-27 21:35:42 +00002666 assert(q >= p);
Neil Bootha30b0ee2007-10-03 22:26:02 +00002667 } else {
2668 /* Add trailing zeroes. */
2669 memset (dst, '0', outputDigits);
2670 dst += outputDigits;
2671 }
2672
2673 /* Move the most significant digit to before the point, and if there
2674 is something after the decimal point add it. This must come
2675 after rounding above. */
2676 p[-1] = p[0];
2677 if (dst -1 == p)
2678 dst--;
2679 else
2680 p[0] = '.';
2681
2682 /* Finally output the exponent. */
2683 *dst++ = upperCase ? 'P': 'p';
2684
Neil Booth92f7e8d2007-10-06 07:29:25 +00002685 return writeSignedDecimal (dst, exponent);
Neil Bootha30b0ee2007-10-03 22:26:02 +00002686}
2687
Chandler Carruthed7692a2012-03-04 12:02:57 +00002688hash_code llvm::hash_value(const APFloat &Arg) {
2689 if (Arg.category != APFloat::fcNormal)
2690 return hash_combine((uint8_t)Arg.category,
2691 // NaN has no sign, fix it at zero.
2692 Arg.isNaN() ? (uint8_t)0 : (uint8_t)Arg.sign,
2693 Arg.semantics->precision);
2694
2695 // Normal floats need their exponent and significand hashed.
2696 return hash_combine((uint8_t)Arg.category, (uint8_t)Arg.sign,
2697 Arg.semantics->precision, Arg.exponent,
2698 hash_combine_range(
2699 Arg.significandParts(),
2700 Arg.significandParts() + Arg.partCount()));
Dale Johannesen343e7702007-08-24 00:56:33 +00002701}
2702
2703// Conversion from APFloat to/from host float/double. It may eventually be
2704// possible to eliminate these and have everybody deal with APFloats, but that
2705// will take a while. This approach will not easily extend to long double.
Dale Johannesena72a5a02007-09-20 23:47:58 +00002706// Current implementation requires integerPartWidth==64, which is correct at
2707// the moment but could be made more general.
Dale Johannesen343e7702007-08-24 00:56:33 +00002708
Dale Johannesen58c2e4c2007-09-05 20:39:49 +00002709// Denormals have exponent minExponent in APFloat, but minExponent-1 in
Dale Johannesena72a5a02007-09-20 23:47:58 +00002710// the actual IEEE respresentations. We compensate for that here.
Dale Johannesen58c2e4c2007-09-05 20:39:49 +00002711
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002712APInt
Neil Booth4f881702007-09-26 21:33:42 +00002713APFloat::convertF80LongDoubleAPFloatToAPInt() const
2714{
Dan Gohmanb10abe12008-01-29 12:08:20 +00002715 assert(semantics == (const llvm::fltSemantics*)&x87DoubleExtended);
Evan Cheng99ebfa52009-10-27 21:35:42 +00002716 assert(partCount()==2);
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002717
2718 uint64_t myexponent, mysignificand;
2719
2720 if (category==fcNormal) {
2721 myexponent = exponent+16383; //bias
Dale Johannesena72a5a02007-09-20 23:47:58 +00002722 mysignificand = significandParts()[0];
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002723 if (myexponent==1 && !(mysignificand & 0x8000000000000000ULL))
2724 myexponent = 0; // denormal
2725 } else if (category==fcZero) {
2726 myexponent = 0;
2727 mysignificand = 0;
2728 } else if (category==fcInfinity) {
2729 myexponent = 0x7fff;
2730 mysignificand = 0x8000000000000000ULL;
Chris Lattnera11ef822007-10-06 06:13:42 +00002731 } else {
2732 assert(category == fcNaN && "Unknown category");
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002733 myexponent = 0x7fff;
Dale Johannesena72a5a02007-09-20 23:47:58 +00002734 mysignificand = significandParts()[0];
Chris Lattnera11ef822007-10-06 06:13:42 +00002735 }
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002736
2737 uint64_t words[2];
Dale Johannesen1b25cb22009-03-23 21:16:53 +00002738 words[0] = mysignificand;
2739 words[1] = ((uint64_t)(sign & 1) << 15) |
2740 (myexponent & 0x7fffLL);
Jeffrey Yasskin3ba292d2011-07-18 21:45:40 +00002741 return APInt(80, words);
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002742}
2743
2744APInt
Dale Johannesena471c2e2007-10-11 18:07:22 +00002745APFloat::convertPPCDoubleDoubleAPFloatToAPInt() const
2746{
Dan Gohmanb10abe12008-01-29 12:08:20 +00002747 assert(semantics == (const llvm::fltSemantics*)&PPCDoubleDouble);
Evan Cheng99ebfa52009-10-27 21:35:42 +00002748 assert(partCount()==2);
Dale Johannesena471c2e2007-10-11 18:07:22 +00002749
Ulrich Weigand69c9c8c2012-10-29 18:09:01 +00002750 uint64_t words[2];
2751 opStatus fs;
2752 bool losesInfo;
Dale Johannesena471c2e2007-10-11 18:07:22 +00002753
Ulrich Weigand69c9c8c2012-10-29 18:09:01 +00002754 // Convert number to double. To avoid spurious underflows, we re-
2755 // normalize against the "double" minExponent first, and only *then*
2756 // truncate the mantissa. The result of that second conversion
2757 // may be inexact, but should never underflow.
Alexey Samsonov999d8bc2012-11-30 22:27:54 +00002758 // Declare fltSemantics before APFloat that uses it (and
2759 // saves pointer to it) to ensure correct destruction order.
Ulrich Weigand69c9c8c2012-10-29 18:09:01 +00002760 fltSemantics extendedSemantics = *semantics;
2761 extendedSemantics.minExponent = IEEEdouble.minExponent;
Alexey Samsonov999d8bc2012-11-30 22:27:54 +00002762 APFloat extended(*this);
Ulrich Weigand69c9c8c2012-10-29 18:09:01 +00002763 fs = extended.convert(extendedSemantics, rmNearestTiesToEven, &losesInfo);
2764 assert(fs == opOK && !losesInfo);
2765 (void)fs;
2766
2767 APFloat u(extended);
2768 fs = u.convert(IEEEdouble, rmNearestTiesToEven, &losesInfo);
2769 assert(fs == opOK || fs == opInexact);
2770 (void)fs;
2771 words[0] = *u.convertDoubleAPFloatToAPInt().getRawData();
2772
2773 // If conversion was exact or resulted in a special case, we're done;
2774 // just set the second double to zero. Otherwise, re-convert back to
2775 // the extended format and compute the difference. This now should
2776 // convert exactly to double.
2777 if (u.category == fcNormal && losesInfo) {
2778 fs = u.convert(extendedSemantics, rmNearestTiesToEven, &losesInfo);
2779 assert(fs == opOK && !losesInfo);
2780 (void)fs;
2781
2782 APFloat v(extended);
2783 v.subtract(u, rmNearestTiesToEven);
2784 fs = v.convert(IEEEdouble, rmNearestTiesToEven, &losesInfo);
2785 assert(fs == opOK && !losesInfo);
2786 (void)fs;
2787 words[1] = *v.convertDoubleAPFloatToAPInt().getRawData();
Dale Johannesena471c2e2007-10-11 18:07:22 +00002788 } else {
Ulrich Weigand69c9c8c2012-10-29 18:09:01 +00002789 words[1] = 0;
Dale Johannesena471c2e2007-10-11 18:07:22 +00002790 }
2791
Jeffrey Yasskin3ba292d2011-07-18 21:45:40 +00002792 return APInt(128, words);
Dale Johannesena471c2e2007-10-11 18:07:22 +00002793}
2794
2795APInt
Anton Korobeynikov7e844f12009-08-21 22:10:30 +00002796APFloat::convertQuadrupleAPFloatToAPInt() const
2797{
2798 assert(semantics == (const llvm::fltSemantics*)&IEEEquad);
Evan Cheng99ebfa52009-10-27 21:35:42 +00002799 assert(partCount()==2);
Anton Korobeynikov7e844f12009-08-21 22:10:30 +00002800
2801 uint64_t myexponent, mysignificand, mysignificand2;
2802
2803 if (category==fcNormal) {
2804 myexponent = exponent+16383; //bias
2805 mysignificand = significandParts()[0];
2806 mysignificand2 = significandParts()[1];
2807 if (myexponent==1 && !(mysignificand2 & 0x1000000000000LL))
2808 myexponent = 0; // denormal
2809 } else if (category==fcZero) {
2810 myexponent = 0;
2811 mysignificand = mysignificand2 = 0;
2812 } else if (category==fcInfinity) {
2813 myexponent = 0x7fff;
2814 mysignificand = mysignificand2 = 0;
2815 } else {
2816 assert(category == fcNaN && "Unknown category!");
2817 myexponent = 0x7fff;
2818 mysignificand = significandParts()[0];
2819 mysignificand2 = significandParts()[1];
2820 }
2821
2822 uint64_t words[2];
2823 words[0] = mysignificand;
2824 words[1] = ((uint64_t)(sign & 1) << 63) |
2825 ((myexponent & 0x7fff) << 48) |
Anton Korobeynikov4755e992009-08-21 23:09:47 +00002826 (mysignificand2 & 0xffffffffffffLL);
Anton Korobeynikov7e844f12009-08-21 22:10:30 +00002827
Jeffrey Yasskin3ba292d2011-07-18 21:45:40 +00002828 return APInt(128, words);
Anton Korobeynikov7e844f12009-08-21 22:10:30 +00002829}
2830
2831APInt
Neil Booth4f881702007-09-26 21:33:42 +00002832APFloat::convertDoubleAPFloatToAPInt() const
2833{
Dan Gohmancb648f92007-09-14 20:08:19 +00002834 assert(semantics == (const llvm::fltSemantics*)&IEEEdouble);
Evan Cheng99ebfa52009-10-27 21:35:42 +00002835 assert(partCount()==1);
Dale Johannesen343e7702007-08-24 00:56:33 +00002836
Dale Johanneseneaf08942007-08-31 04:03:46 +00002837 uint64_t myexponent, mysignificand;
Dale Johannesen343e7702007-08-24 00:56:33 +00002838
2839 if (category==fcNormal) {
Dale Johannesen343e7702007-08-24 00:56:33 +00002840 myexponent = exponent+1023; //bias
Dale Johannesen58c2e4c2007-09-05 20:39:49 +00002841 mysignificand = *significandParts();
2842 if (myexponent==1 && !(mysignificand & 0x10000000000000LL))
2843 myexponent = 0; // denormal
Dale Johannesen343e7702007-08-24 00:56:33 +00002844 } else if (category==fcZero) {
Dale Johannesen343e7702007-08-24 00:56:33 +00002845 myexponent = 0;
2846 mysignificand = 0;
2847 } else if (category==fcInfinity) {
Dale Johannesen343e7702007-08-24 00:56:33 +00002848 myexponent = 0x7ff;
2849 mysignificand = 0;
Chris Lattnera11ef822007-10-06 06:13:42 +00002850 } else {
2851 assert(category == fcNaN && "Unknown category!");
Dale Johannesen343e7702007-08-24 00:56:33 +00002852 myexponent = 0x7ff;
Dale Johanneseneaf08942007-08-31 04:03:46 +00002853 mysignificand = *significandParts();
Chris Lattnera11ef822007-10-06 06:13:42 +00002854 }
Dale Johannesen343e7702007-08-24 00:56:33 +00002855
Evan Cheng48e8c802008-05-02 21:15:08 +00002856 return APInt(64, ((((uint64_t)(sign & 1) << 63) |
Chris Lattnera11ef822007-10-06 06:13:42 +00002857 ((myexponent & 0x7ff) << 52) |
2858 (mysignificand & 0xfffffffffffffLL))));
Dale Johannesen343e7702007-08-24 00:56:33 +00002859}
2860
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002861APInt
Neil Booth4f881702007-09-26 21:33:42 +00002862APFloat::convertFloatAPFloatToAPInt() const
2863{
Dan Gohmancb648f92007-09-14 20:08:19 +00002864 assert(semantics == (const llvm::fltSemantics*)&IEEEsingle);
Evan Cheng99ebfa52009-10-27 21:35:42 +00002865 assert(partCount()==1);
Neil Booth4f881702007-09-26 21:33:42 +00002866
Dale Johanneseneaf08942007-08-31 04:03:46 +00002867 uint32_t myexponent, mysignificand;
Dale Johannesen343e7702007-08-24 00:56:33 +00002868
2869 if (category==fcNormal) {
Dale Johannesen343e7702007-08-24 00:56:33 +00002870 myexponent = exponent+127; //bias
Evan Cheng48e8c802008-05-02 21:15:08 +00002871 mysignificand = (uint32_t)*significandParts();
Dale Johannesend0763b92007-11-17 01:02:27 +00002872 if (myexponent == 1 && !(mysignificand & 0x800000))
Dale Johannesen58c2e4c2007-09-05 20:39:49 +00002873 myexponent = 0; // denormal
Dale Johannesen343e7702007-08-24 00:56:33 +00002874 } else if (category==fcZero) {
Dale Johannesen343e7702007-08-24 00:56:33 +00002875 myexponent = 0;
2876 mysignificand = 0;
2877 } else if (category==fcInfinity) {
Dale Johannesen343e7702007-08-24 00:56:33 +00002878 myexponent = 0xff;
2879 mysignificand = 0;
Chris Lattnera11ef822007-10-06 06:13:42 +00002880 } else {
2881 assert(category == fcNaN && "Unknown category!");
Dale Johannesen58c2e4c2007-09-05 20:39:49 +00002882 myexponent = 0xff;
Evan Cheng48e8c802008-05-02 21:15:08 +00002883 mysignificand = (uint32_t)*significandParts();
Chris Lattnera11ef822007-10-06 06:13:42 +00002884 }
Dale Johannesen343e7702007-08-24 00:56:33 +00002885
Chris Lattnera11ef822007-10-06 06:13:42 +00002886 return APInt(32, (((sign&1) << 31) | ((myexponent&0xff) << 23) |
2887 (mysignificand & 0x7fffff)));
Dale Johannesen343e7702007-08-24 00:56:33 +00002888}
2889
Chris Lattnercc4287a2009-10-16 02:13:51 +00002890APInt
2891APFloat::convertHalfAPFloatToAPInt() const
2892{
2893 assert(semantics == (const llvm::fltSemantics*)&IEEEhalf);
Evan Cheng99ebfa52009-10-27 21:35:42 +00002894 assert(partCount()==1);
Chris Lattnercc4287a2009-10-16 02:13:51 +00002895
2896 uint32_t myexponent, mysignificand;
2897
2898 if (category==fcNormal) {
2899 myexponent = exponent+15; //bias
2900 mysignificand = (uint32_t)*significandParts();
2901 if (myexponent == 1 && !(mysignificand & 0x400))
2902 myexponent = 0; // denormal
2903 } else if (category==fcZero) {
2904 myexponent = 0;
2905 mysignificand = 0;
2906 } else if (category==fcInfinity) {
Dale Johannesena223aed2009-10-23 04:02:51 +00002907 myexponent = 0x1f;
Chris Lattnercc4287a2009-10-16 02:13:51 +00002908 mysignificand = 0;
2909 } else {
2910 assert(category == fcNaN && "Unknown category!");
Dale Johannesena223aed2009-10-23 04:02:51 +00002911 myexponent = 0x1f;
Chris Lattnercc4287a2009-10-16 02:13:51 +00002912 mysignificand = (uint32_t)*significandParts();
2913 }
2914
2915 return APInt(16, (((sign&1) << 15) | ((myexponent&0x1f) << 10) |
2916 (mysignificand & 0x3ff)));
2917}
2918
Dale Johannesena471c2e2007-10-11 18:07:22 +00002919// This function creates an APInt that is just a bit map of the floating
2920// point constant as it would appear in memory. It is not a conversion,
2921// and treating the result as a normal integer is unlikely to be useful.
2922
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002923APInt
Dale Johannesen7111b022008-10-09 18:53:47 +00002924APFloat::bitcastToAPInt() const
Neil Booth4f881702007-09-26 21:33:42 +00002925{
Chris Lattnercc4287a2009-10-16 02:13:51 +00002926 if (semantics == (const llvm::fltSemantics*)&IEEEhalf)
2927 return convertHalfAPFloatToAPInt();
2928
Dan Gohmanb10abe12008-01-29 12:08:20 +00002929 if (semantics == (const llvm::fltSemantics*)&IEEEsingle)
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002930 return convertFloatAPFloatToAPInt();
Anton Korobeynikov7e844f12009-08-21 22:10:30 +00002931
Dan Gohmanb10abe12008-01-29 12:08:20 +00002932 if (semantics == (const llvm::fltSemantics*)&IEEEdouble)
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002933 return convertDoubleAPFloatToAPInt();
Neil Booth4f881702007-09-26 21:33:42 +00002934
Anton Korobeynikov7e844f12009-08-21 22:10:30 +00002935 if (semantics == (const llvm::fltSemantics*)&IEEEquad)
2936 return convertQuadrupleAPFloatToAPInt();
2937
Dan Gohmanb10abe12008-01-29 12:08:20 +00002938 if (semantics == (const llvm::fltSemantics*)&PPCDoubleDouble)
Dale Johannesena471c2e2007-10-11 18:07:22 +00002939 return convertPPCDoubleDoubleAPFloatToAPInt();
2940
Dan Gohmanb10abe12008-01-29 12:08:20 +00002941 assert(semantics == (const llvm::fltSemantics*)&x87DoubleExtended &&
Chris Lattnera11ef822007-10-06 06:13:42 +00002942 "unknown format!");
2943 return convertF80LongDoubleAPFloatToAPInt();
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002944}
2945
Neil Booth4f881702007-09-26 21:33:42 +00002946float
2947APFloat::convertToFloat() const
2948{
Chris Lattnerad785002009-09-24 21:44:20 +00002949 assert(semantics == (const llvm::fltSemantics*)&IEEEsingle &&
2950 "Float semantics are not IEEEsingle");
Dale Johannesen7111b022008-10-09 18:53:47 +00002951 APInt api = bitcastToAPInt();
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002952 return api.bitsToFloat();
2953}
2954
Neil Booth4f881702007-09-26 21:33:42 +00002955double
2956APFloat::convertToDouble() const
2957{
Chris Lattnerad785002009-09-24 21:44:20 +00002958 assert(semantics == (const llvm::fltSemantics*)&IEEEdouble &&
2959 "Float semantics are not IEEEdouble");
Dale Johannesen7111b022008-10-09 18:53:47 +00002960 APInt api = bitcastToAPInt();
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002961 return api.bitsToDouble();
2962}
2963
Dale Johannesend3d8ce32008-10-06 18:22:29 +00002964/// Integer bit is explicit in this format. Intel hardware (387 and later)
2965/// does not support these bit patterns:
2966/// exponent = all 1's, integer bit 0, significand 0 ("pseudoinfinity")
2967/// exponent = all 1's, integer bit 0, significand nonzero ("pseudoNaN")
2968/// exponent = 0, integer bit 1 ("pseudodenormal")
2969/// exponent!=0 nor all 1's, integer bit 0 ("unnormal")
2970/// At the moment, the first two are treated as NaNs, the second two as Normal.
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002971void
Neil Booth4f881702007-09-26 21:33:42 +00002972APFloat::initFromF80LongDoubleAPInt(const APInt &api)
2973{
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002974 assert(api.getBitWidth()==80);
2975 uint64_t i1 = api.getRawData()[0];
2976 uint64_t i2 = api.getRawData()[1];
Dale Johannesen1b25cb22009-03-23 21:16:53 +00002977 uint64_t myexponent = (i2 & 0x7fff);
2978 uint64_t mysignificand = i1;
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002979
2980 initialize(&APFloat::x87DoubleExtended);
Dale Johannesena72a5a02007-09-20 23:47:58 +00002981 assert(partCount()==2);
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002982
Dale Johannesen1b25cb22009-03-23 21:16:53 +00002983 sign = static_cast<unsigned int>(i2>>15);
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002984 if (myexponent==0 && mysignificand==0) {
2985 // exponent, significand meaningless
2986 category = fcZero;
2987 } else if (myexponent==0x7fff && mysignificand==0x8000000000000000ULL) {
2988 // exponent, significand meaningless
2989 category = fcInfinity;
2990 } else if (myexponent==0x7fff && mysignificand!=0x8000000000000000ULL) {
2991 // exponent meaningless
2992 category = fcNaN;
Dale Johannesena72a5a02007-09-20 23:47:58 +00002993 significandParts()[0] = mysignificand;
2994 significandParts()[1] = 0;
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002995 } else {
2996 category = fcNormal;
2997 exponent = myexponent - 16383;
Dale Johannesena72a5a02007-09-20 23:47:58 +00002998 significandParts()[0] = mysignificand;
2999 significandParts()[1] = 0;
Dale Johannesen3f6eb742007-09-11 18:32:33 +00003000 if (myexponent==0) // denormal
3001 exponent = -16382;
Neil Booth4f881702007-09-26 21:33:42 +00003002 }
Dale Johannesen3f6eb742007-09-11 18:32:33 +00003003}
3004
3005void
Dale Johannesena471c2e2007-10-11 18:07:22 +00003006APFloat::initFromPPCDoubleDoubleAPInt(const APInt &api)
3007{
3008 assert(api.getBitWidth()==128);
3009 uint64_t i1 = api.getRawData()[0];
3010 uint64_t i2 = api.getRawData()[1];
Ulrich Weigand69c9c8c2012-10-29 18:09:01 +00003011 opStatus fs;
3012 bool losesInfo;
Dale Johannesena471c2e2007-10-11 18:07:22 +00003013
Ulrich Weigand69c9c8c2012-10-29 18:09:01 +00003014 // Get the first double and convert to our format.
3015 initFromDoubleAPInt(APInt(64, i1));
3016 fs = convert(PPCDoubleDouble, rmNearestTiesToEven, &losesInfo);
3017 assert(fs == opOK && !losesInfo);
3018 (void)fs;
Dale Johannesena471c2e2007-10-11 18:07:22 +00003019
Ulrich Weigand69c9c8c2012-10-29 18:09:01 +00003020 // Unless we have a special case, add in second double.
3021 if (category == fcNormal) {
Tim Northover0a29cb02013-01-22 09:46:31 +00003022 APFloat v(IEEEdouble, APInt(64, i2));
Ulrich Weigand69c9c8c2012-10-29 18:09:01 +00003023 fs = v.convert(PPCDoubleDouble, rmNearestTiesToEven, &losesInfo);
3024 assert(fs == opOK && !losesInfo);
3025 (void)fs;
3026
3027 add(v, rmNearestTiesToEven);
Dale Johannesena471c2e2007-10-11 18:07:22 +00003028 }
3029}
3030
3031void
Anton Korobeynikov7e844f12009-08-21 22:10:30 +00003032APFloat::initFromQuadrupleAPInt(const APInt &api)
3033{
3034 assert(api.getBitWidth()==128);
3035 uint64_t i1 = api.getRawData()[0];
3036 uint64_t i2 = api.getRawData()[1];
3037 uint64_t myexponent = (i2 >> 48) & 0x7fff;
3038 uint64_t mysignificand = i1;
3039 uint64_t mysignificand2 = i2 & 0xffffffffffffLL;
3040
3041 initialize(&APFloat::IEEEquad);
3042 assert(partCount()==2);
3043
3044 sign = static_cast<unsigned int>(i2>>63);
3045 if (myexponent==0 &&
3046 (mysignificand==0 && mysignificand2==0)) {
3047 // exponent, significand meaningless
3048 category = fcZero;
3049 } else if (myexponent==0x7fff &&
3050 (mysignificand==0 && mysignificand2==0)) {
3051 // exponent, significand meaningless
3052 category = fcInfinity;
3053 } else if (myexponent==0x7fff &&
3054 (mysignificand!=0 || mysignificand2 !=0)) {
3055 // exponent meaningless
3056 category = fcNaN;
3057 significandParts()[0] = mysignificand;
3058 significandParts()[1] = mysignificand2;
3059 } else {
3060 category = fcNormal;
3061 exponent = myexponent - 16383;
3062 significandParts()[0] = mysignificand;
3063 significandParts()[1] = mysignificand2;
3064 if (myexponent==0) // denormal
3065 exponent = -16382;
3066 else
3067 significandParts()[1] |= 0x1000000000000LL; // integer bit
3068 }
3069}
3070
3071void
Neil Booth4f881702007-09-26 21:33:42 +00003072APFloat::initFromDoubleAPInt(const APInt &api)
3073{
Dale Johannesen3f6eb742007-09-11 18:32:33 +00003074 assert(api.getBitWidth()==64);
3075 uint64_t i = *api.getRawData();
Dale Johannesend3b51fd2007-08-24 05:08:11 +00003076 uint64_t myexponent = (i >> 52) & 0x7ff;
3077 uint64_t mysignificand = i & 0xfffffffffffffLL;
3078
Dale Johannesen343e7702007-08-24 00:56:33 +00003079 initialize(&APFloat::IEEEdouble);
Dale Johannesen343e7702007-08-24 00:56:33 +00003080 assert(partCount()==1);
3081
Evan Cheng48e8c802008-05-02 21:15:08 +00003082 sign = static_cast<unsigned int>(i>>63);
Dale Johannesen343e7702007-08-24 00:56:33 +00003083 if (myexponent==0 && mysignificand==0) {
3084 // exponent, significand meaningless
3085 category = fcZero;
Dale Johannesen343e7702007-08-24 00:56:33 +00003086 } else if (myexponent==0x7ff && mysignificand==0) {
3087 // exponent, significand meaningless
3088 category = fcInfinity;
Dale Johanneseneaf08942007-08-31 04:03:46 +00003089 } else if (myexponent==0x7ff && mysignificand!=0) {
3090 // exponent meaningless
3091 category = fcNaN;
3092 *significandParts() = mysignificand;
Dale Johannesen343e7702007-08-24 00:56:33 +00003093 } else {
Dale Johannesen343e7702007-08-24 00:56:33 +00003094 category = fcNormal;
3095 exponent = myexponent - 1023;
Dale Johannesen58c2e4c2007-09-05 20:39:49 +00003096 *significandParts() = mysignificand;
3097 if (myexponent==0) // denormal
3098 exponent = -1022;
3099 else
3100 *significandParts() |= 0x10000000000000LL; // integer bit
Neil Booth4f881702007-09-26 21:33:42 +00003101 }
Dale Johannesen343e7702007-08-24 00:56:33 +00003102}
3103
Dale Johannesen3f6eb742007-09-11 18:32:33 +00003104void
Neil Booth4f881702007-09-26 21:33:42 +00003105APFloat::initFromFloatAPInt(const APInt & api)
3106{
Dale Johannesen3f6eb742007-09-11 18:32:33 +00003107 assert(api.getBitWidth()==32);
3108 uint32_t i = (uint32_t)*api.getRawData();
Dale Johannesend3b51fd2007-08-24 05:08:11 +00003109 uint32_t myexponent = (i >> 23) & 0xff;
3110 uint32_t mysignificand = i & 0x7fffff;
3111
Dale Johannesen343e7702007-08-24 00:56:33 +00003112 initialize(&APFloat::IEEEsingle);
Dale Johannesen343e7702007-08-24 00:56:33 +00003113 assert(partCount()==1);
3114
Dale Johanneseneaf08942007-08-31 04:03:46 +00003115 sign = i >> 31;
Dale Johannesen343e7702007-08-24 00:56:33 +00003116 if (myexponent==0 && mysignificand==0) {
3117 // exponent, significand meaningless
3118 category = fcZero;
Dale Johannesen343e7702007-08-24 00:56:33 +00003119 } else if (myexponent==0xff && mysignificand==0) {
3120 // exponent, significand meaningless
3121 category = fcInfinity;
Dale Johannesen902ff942007-09-25 17:25:00 +00003122 } else if (myexponent==0xff && mysignificand!=0) {
Dale Johannesen343e7702007-08-24 00:56:33 +00003123 // sign, exponent, significand meaningless
Dale Johanneseneaf08942007-08-31 04:03:46 +00003124 category = fcNaN;
3125 *significandParts() = mysignificand;
Dale Johannesen343e7702007-08-24 00:56:33 +00003126 } else {
3127 category = fcNormal;
Dale Johannesen343e7702007-08-24 00:56:33 +00003128 exponent = myexponent - 127; //bias
Dale Johannesen58c2e4c2007-09-05 20:39:49 +00003129 *significandParts() = mysignificand;
3130 if (myexponent==0) // denormal
3131 exponent = -126;
3132 else
3133 *significandParts() |= 0x800000; // integer bit
Dale Johannesen343e7702007-08-24 00:56:33 +00003134 }
3135}
Dale Johannesen3f6eb742007-09-11 18:32:33 +00003136
Chris Lattnercc4287a2009-10-16 02:13:51 +00003137void
3138APFloat::initFromHalfAPInt(const APInt & api)
3139{
3140 assert(api.getBitWidth()==16);
3141 uint32_t i = (uint32_t)*api.getRawData();
Dale Johannesena223aed2009-10-23 04:02:51 +00003142 uint32_t myexponent = (i >> 10) & 0x1f;
Chris Lattnercc4287a2009-10-16 02:13:51 +00003143 uint32_t mysignificand = i & 0x3ff;
3144
3145 initialize(&APFloat::IEEEhalf);
3146 assert(partCount()==1);
3147
3148 sign = i >> 15;
3149 if (myexponent==0 && mysignificand==0) {
3150 // exponent, significand meaningless
3151 category = fcZero;
3152 } else if (myexponent==0x1f && mysignificand==0) {
3153 // exponent, significand meaningless
3154 category = fcInfinity;
3155 } else if (myexponent==0x1f && mysignificand!=0) {
3156 // sign, exponent, significand meaningless
3157 category = fcNaN;
3158 *significandParts() = mysignificand;
3159 } else {
3160 category = fcNormal;
3161 exponent = myexponent - 15; //bias
3162 *significandParts() = mysignificand;
3163 if (myexponent==0) // denormal
3164 exponent = -14;
3165 else
3166 *significandParts() |= 0x400; // integer bit
3167 }
3168}
3169
Dale Johannesen3f6eb742007-09-11 18:32:33 +00003170/// Treat api as containing the bits of a floating point number. Currently
Dale Johannesena471c2e2007-10-11 18:07:22 +00003171/// we infer the floating point type from the size of the APInt. The
3172/// isIEEE argument distinguishes between PPC128 and IEEE128 (not meaningful
3173/// when the size is anything else).
Dale Johannesen3f6eb742007-09-11 18:32:33 +00003174void
Tim Northover0a29cb02013-01-22 09:46:31 +00003175APFloat::initFromAPInt(const fltSemantics* Sem, const APInt& api)
Neil Booth4f881702007-09-26 21:33:42 +00003176{
Tim Northover0a29cb02013-01-22 09:46:31 +00003177 if (Sem == &IEEEhalf)
Chris Lattnercc4287a2009-10-16 02:13:51 +00003178 return initFromHalfAPInt(api);
Tim Northover0a29cb02013-01-22 09:46:31 +00003179 if (Sem == &IEEEsingle)
Dale Johannesen3f6eb742007-09-11 18:32:33 +00003180 return initFromFloatAPInt(api);
Tim Northover0a29cb02013-01-22 09:46:31 +00003181 if (Sem == &IEEEdouble)
Dale Johannesen3f6eb742007-09-11 18:32:33 +00003182 return initFromDoubleAPInt(api);
Tim Northover0a29cb02013-01-22 09:46:31 +00003183 if (Sem == &x87DoubleExtended)
Dale Johannesen3f6eb742007-09-11 18:32:33 +00003184 return initFromF80LongDoubleAPInt(api);
Tim Northover0a29cb02013-01-22 09:46:31 +00003185 if (Sem == &IEEEquad)
3186 return initFromQuadrupleAPInt(api);
3187 if (Sem == &PPCDoubleDouble)
3188 return initFromPPCDoubleDoubleAPInt(api);
3189
3190 llvm_unreachable(0);
Dale Johannesen3f6eb742007-09-11 18:32:33 +00003191}
3192
Nadav Rotem093399c2011-02-17 21:22:27 +00003193APFloat
3194APFloat::getAllOnesValue(unsigned BitWidth, bool isIEEE)
3195{
Tim Northover0a29cb02013-01-22 09:46:31 +00003196 switch (BitWidth) {
3197 case 16:
3198 return APFloat(IEEEhalf, APInt::getAllOnesValue(BitWidth));
3199 case 32:
3200 return APFloat(IEEEsingle, APInt::getAllOnesValue(BitWidth));
3201 case 64:
3202 return APFloat(IEEEdouble, APInt::getAllOnesValue(BitWidth));
3203 case 80:
3204 return APFloat(x87DoubleExtended, APInt::getAllOnesValue(BitWidth));
3205 case 128:
3206 if (isIEEE)
3207 return APFloat(IEEEquad, APInt::getAllOnesValue(BitWidth));
3208 return APFloat(PPCDoubleDouble, APInt::getAllOnesValue(BitWidth));
3209 default:
3210 llvm_unreachable("Unknown floating bit width");
3211 }
Nadav Rotem093399c2011-02-17 21:22:27 +00003212}
3213
John McCall00e65de2009-12-24 08:56:26 +00003214APFloat APFloat::getLargest(const fltSemantics &Sem, bool Negative) {
3215 APFloat Val(Sem, fcNormal, Negative);
3216
3217 // We want (in interchange format):
3218 // sign = {Negative}
3219 // exponent = 1..10
3220 // significand = 1..1
3221
3222 Val.exponent = Sem.maxExponent; // unbiased
3223
3224 // 1-initialize all bits....
3225 Val.zeroSignificand();
3226 integerPart *significand = Val.significandParts();
3227 unsigned N = partCountForBits(Sem.precision);
3228 for (unsigned i = 0; i != N; ++i)
3229 significand[i] = ~((integerPart) 0);
3230
3231 // ...and then clear the top bits for internal consistency.
Eli Friedman7247a5f2011-10-12 21:51:36 +00003232 if (Sem.precision % integerPartWidth != 0)
3233 significand[N-1] &=
3234 (((integerPart) 1) << (Sem.precision % integerPartWidth)) - 1;
John McCall00e65de2009-12-24 08:56:26 +00003235
3236 return Val;
3237}
3238
3239APFloat APFloat::getSmallest(const fltSemantics &Sem, bool Negative) {
3240 APFloat Val(Sem, fcNormal, Negative);
3241
3242 // We want (in interchange format):
3243 // sign = {Negative}
3244 // exponent = 0..0
3245 // significand = 0..01
3246
3247 Val.exponent = Sem.minExponent; // unbiased
3248 Val.zeroSignificand();
3249 Val.significandParts()[0] = 1;
3250 return Val;
3251}
3252
3253APFloat APFloat::getSmallestNormalized(const fltSemantics &Sem, bool Negative) {
3254 APFloat Val(Sem, fcNormal, Negative);
3255
3256 // We want (in interchange format):
3257 // sign = {Negative}
3258 // exponent = 0..0
3259 // significand = 10..0
3260
3261 Val.exponent = Sem.minExponent;
3262 Val.zeroSignificand();
Dan Gohman16e02092010-03-24 19:38:02 +00003263 Val.significandParts()[partCountForBits(Sem.precision)-1] |=
Eli Friedman90196fc2011-10-12 21:56:19 +00003264 (((integerPart) 1) << ((Sem.precision - 1) % integerPartWidth));
John McCall00e65de2009-12-24 08:56:26 +00003265
3266 return Val;
3267}
3268
Tim Northover0a29cb02013-01-22 09:46:31 +00003269APFloat::APFloat(const fltSemantics &Sem, const APInt &API) {
3270 initFromAPInt(&Sem, API);
Dale Johannesen3f6eb742007-09-11 18:32:33 +00003271}
3272
Ulrich Weigandfce241d2012-10-29 18:17:42 +00003273APFloat::APFloat(float f) {
Tim Northover0a29cb02013-01-22 09:46:31 +00003274 initFromAPInt(&IEEEsingle, APInt::floatToBits(f));
Dale Johannesen3f6eb742007-09-11 18:32:33 +00003275}
3276
Ulrich Weigandfce241d2012-10-29 18:17:42 +00003277APFloat::APFloat(double d) {
Tim Northover0a29cb02013-01-22 09:46:31 +00003278 initFromAPInt(&IEEEdouble, APInt::doubleToBits(d));
Dale Johannesen3f6eb742007-09-11 18:32:33 +00003279}
John McCall00e65de2009-12-24 08:56:26 +00003280
3281namespace {
David Blaikie9f14ed12012-07-25 18:04:24 +00003282 void append(SmallVectorImpl<char> &Buffer, StringRef Str) {
3283 Buffer.append(Str.begin(), Str.end());
John McCall00e65de2009-12-24 08:56:26 +00003284 }
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
Hao Liub631a412013-03-20 01:46:36 +00003314 // Truncate the significand down to its active bit count.
3315 significand = significand.trunc(significand.getActiveBits());
John McCall003a09c2009-12-24 12:16:56 +00003316 }
3317
3318
John McCall00e65de2009-12-24 08:56:26 +00003319 void AdjustToPrecision(SmallVectorImpl<char> &buffer,
3320 int &exp, unsigned FormatPrecision) {
3321 unsigned N = buffer.size();
3322 if (N <= FormatPrecision) return;
3323
3324 // The most significant figures are the last ones in the buffer.
3325 unsigned FirstSignificant = N - FormatPrecision;
3326
3327 // Round.
3328 // FIXME: this probably shouldn't use 'round half up'.
3329
3330 // Rounding down is just a truncation, except we also want to drop
3331 // trailing zeros from the new result.
3332 if (buffer[FirstSignificant - 1] < '5') {
NAKAMURA Takumi752b2f02012-02-19 03:18:29 +00003333 while (FirstSignificant < N && buffer[FirstSignificant] == '0')
John McCall00e65de2009-12-24 08:56:26 +00003334 FirstSignificant++;
3335
3336 exp += FirstSignificant;
3337 buffer.erase(&buffer[0], &buffer[FirstSignificant]);
3338 return;
3339 }
3340
3341 // Rounding up requires a decimal add-with-carry. If we continue
3342 // the carry, the newly-introduced zeros will just be truncated.
3343 for (unsigned I = FirstSignificant; I != N; ++I) {
3344 if (buffer[I] == '9') {
3345 FirstSignificant++;
3346 } else {
3347 buffer[I]++;
3348 break;
3349 }
3350 }
3351
3352 // If we carried through, we have exactly one digit of precision.
3353 if (FirstSignificant == N) {
3354 exp += FirstSignificant;
3355 buffer.clear();
3356 buffer.push_back('1');
3357 return;
3358 }
3359
3360 exp += FirstSignificant;
3361 buffer.erase(&buffer[0], &buffer[FirstSignificant]);
3362 }
3363}
3364
3365void APFloat::toString(SmallVectorImpl<char> &Str,
3366 unsigned FormatPrecision,
Chris Lattner0ddda3b2010-03-06 19:20:13 +00003367 unsigned FormatMaxPadding) const {
John McCall00e65de2009-12-24 08:56:26 +00003368 switch (category) {
3369 case fcInfinity:
3370 if (isNegative())
3371 return append(Str, "-Inf");
3372 else
3373 return append(Str, "+Inf");
3374
3375 case fcNaN: return append(Str, "NaN");
3376
3377 case fcZero:
3378 if (isNegative())
3379 Str.push_back('-');
3380
3381 if (!FormatMaxPadding)
3382 append(Str, "0.0E+0");
3383 else
3384 Str.push_back('0');
3385 return;
3386
3387 case fcNormal:
3388 break;
3389 }
3390
3391 if (isNegative())
3392 Str.push_back('-');
3393
3394 // Decompose the number into an APInt and an exponent.
3395 int exp = exponent - ((int) semantics->precision - 1);
3396 APInt significand(semantics->precision,
Jeffrey Yasskin3ba292d2011-07-18 21:45:40 +00003397 makeArrayRef(significandParts(),
3398 partCountForBits(semantics->precision)));
John McCall00e65de2009-12-24 08:56:26 +00003399
John McCall6a09aff2009-12-24 23:18:09 +00003400 // Set FormatPrecision if zero. We want to do this before we
3401 // truncate trailing zeros, as those are part of the precision.
3402 if (!FormatPrecision) {
3403 // It's an interesting question whether to use the nominal
3404 // precision or the active precision here for denormals.
3405
3406 // FormatPrecision = ceil(significandBits / lg_2(10))
3407 FormatPrecision = (semantics->precision * 59 + 195) / 196;
3408 }
3409
John McCall00e65de2009-12-24 08:56:26 +00003410 // Ignore trailing binary zeros.
3411 int trailingZeros = significand.countTrailingZeros();
3412 exp += trailingZeros;
3413 significand = significand.lshr(trailingZeros);
3414
3415 // Change the exponent from 2^e to 10^e.
3416 if (exp == 0) {
3417 // Nothing to do.
3418 } else if (exp > 0) {
3419 // Just shift left.
Jay Foad40f8f622010-12-07 08:25:19 +00003420 significand = significand.zext(semantics->precision + exp);
John McCall00e65de2009-12-24 08:56:26 +00003421 significand <<= exp;
3422 exp = 0;
3423 } else { /* exp < 0 */
3424 int texp = -exp;
3425
3426 // We transform this using the identity:
3427 // (N)(2^-e) == (N)(5^e)(10^-e)
3428 // This means we have to multiply N (the significand) by 5^e.
3429 // To avoid overflow, we have to operate on numbers large
3430 // enough to store N * 5^e:
3431 // log2(N * 5^e) == log2(N) + e * log2(5)
John McCall6a09aff2009-12-24 23:18:09 +00003432 // <= semantics->precision + e * 137 / 59
3433 // (log_2(5) ~ 2.321928 < 2.322034 ~ 137/59)
Dan Gohman16e02092010-03-24 19:38:02 +00003434
Eli Friedman9eb6b4d2011-10-07 23:40:49 +00003435 unsigned precision = semantics->precision + (137 * texp + 136) / 59;
John McCall00e65de2009-12-24 08:56:26 +00003436
3437 // Multiply significand by 5^e.
3438 // N * 5^0101 == N * 5^(1*1) * 5^(0*2) * 5^(1*4) * 5^(0*8)
Jay Foad40f8f622010-12-07 08:25:19 +00003439 significand = significand.zext(precision);
John McCall00e65de2009-12-24 08:56:26 +00003440 APInt five_to_the_i(precision, 5);
3441 while (true) {
3442 if (texp & 1) significand *= five_to_the_i;
Dan Gohman16e02092010-03-24 19:38:02 +00003443
John McCall00e65de2009-12-24 08:56:26 +00003444 texp >>= 1;
3445 if (!texp) break;
3446 five_to_the_i *= five_to_the_i;
3447 }
3448 }
3449
John McCall003a09c2009-12-24 12:16:56 +00003450 AdjustToPrecision(significand, exp, FormatPrecision);
3451
Dmitri Gribenko96f498b2013-01-13 16:01:15 +00003452 SmallVector<char, 256> buffer;
John McCall00e65de2009-12-24 08:56:26 +00003453
3454 // Fill the buffer.
3455 unsigned precision = significand.getBitWidth();
3456 APInt ten(precision, 10);
3457 APInt digit(precision, 0);
3458
3459 bool inTrail = true;
3460 while (significand != 0) {
3461 // digit <- significand % 10
3462 // significand <- significand / 10
3463 APInt::udivrem(significand, ten, significand, digit);
3464
3465 unsigned d = digit.getZExtValue();
3466
3467 // Drop trailing zeros.
3468 if (inTrail && !d) exp++;
3469 else {
3470 buffer.push_back((char) ('0' + d));
3471 inTrail = false;
3472 }
3473 }
3474
3475 assert(!buffer.empty() && "no characters in buffer!");
3476
3477 // Drop down to FormatPrecision.
3478 // TODO: don't do more precise calculations above than are required.
3479 AdjustToPrecision(buffer, exp, FormatPrecision);
3480
3481 unsigned NDigits = buffer.size();
3482
John McCall6a09aff2009-12-24 23:18:09 +00003483 // Check whether we should use scientific notation.
John McCall00e65de2009-12-24 08:56:26 +00003484 bool FormatScientific;
3485 if (!FormatMaxPadding)
3486 FormatScientific = true;
3487 else {
John McCall00e65de2009-12-24 08:56:26 +00003488 if (exp >= 0) {
John McCall6a09aff2009-12-24 23:18:09 +00003489 // 765e3 --> 765000
3490 // ^^^
3491 // But we shouldn't make the number look more precise than it is.
3492 FormatScientific = ((unsigned) exp > FormatMaxPadding ||
3493 NDigits + (unsigned) exp > FormatPrecision);
John McCall00e65de2009-12-24 08:56:26 +00003494 } else {
John McCall6a09aff2009-12-24 23:18:09 +00003495 // Power of the most significant digit.
3496 int MSD = exp + (int) (NDigits - 1);
3497 if (MSD >= 0) {
John McCall00e65de2009-12-24 08:56:26 +00003498 // 765e-2 == 7.65
John McCall6a09aff2009-12-24 23:18:09 +00003499 FormatScientific = false;
John McCall00e65de2009-12-24 08:56:26 +00003500 } else {
3501 // 765e-5 == 0.00765
3502 // ^ ^^
John McCall6a09aff2009-12-24 23:18:09 +00003503 FormatScientific = ((unsigned) -MSD) > FormatMaxPadding;
John McCall00e65de2009-12-24 08:56:26 +00003504 }
3505 }
John McCall00e65de2009-12-24 08:56:26 +00003506 }
3507
3508 // Scientific formatting is pretty straightforward.
3509 if (FormatScientific) {
3510 exp += (NDigits - 1);
3511
3512 Str.push_back(buffer[NDigits-1]);
3513 Str.push_back('.');
3514 if (NDigits == 1)
3515 Str.push_back('0');
3516 else
3517 for (unsigned I = 1; I != NDigits; ++I)
3518 Str.push_back(buffer[NDigits-1-I]);
3519 Str.push_back('E');
3520
3521 Str.push_back(exp >= 0 ? '+' : '-');
3522 if (exp < 0) exp = -exp;
3523 SmallVector<char, 6> expbuf;
3524 do {
3525 expbuf.push_back((char) ('0' + (exp % 10)));
3526 exp /= 10;
3527 } while (exp);
3528 for (unsigned I = 0, E = expbuf.size(); I != E; ++I)
3529 Str.push_back(expbuf[E-1-I]);
3530 return;
3531 }
3532
3533 // Non-scientific, positive exponents.
3534 if (exp >= 0) {
3535 for (unsigned I = 0; I != NDigits; ++I)
3536 Str.push_back(buffer[NDigits-1-I]);
3537 for (unsigned I = 0; I != (unsigned) exp; ++I)
3538 Str.push_back('0');
3539 return;
3540 }
3541
3542 // Non-scientific, negative exponents.
3543
3544 // The number of digits to the left of the decimal point.
3545 int NWholeDigits = exp + (int) NDigits;
3546
3547 unsigned I = 0;
3548 if (NWholeDigits > 0) {
3549 for (; I != (unsigned) NWholeDigits; ++I)
3550 Str.push_back(buffer[NDigits-I-1]);
3551 Str.push_back('.');
3552 } else {
3553 unsigned NZeros = 1 + (unsigned) -NWholeDigits;
3554
3555 Str.push_back('0');
3556 Str.push_back('.');
3557 for (unsigned Z = 1; Z != NZeros; ++Z)
3558 Str.push_back('0');
3559 }
3560
3561 for (; I != NDigits; ++I)
3562 Str.push_back(buffer[NDigits-I-1]);
3563}
Benjamin Kramer27460002011-03-30 15:42:27 +00003564
3565bool APFloat::getExactInverse(APFloat *inv) const {
Benjamin Kramer27460002011-03-30 15:42:27 +00003566 // Special floats and denormals have no exact inverse.
3567 if (category != fcNormal)
3568 return false;
3569
3570 // Check that the number is a power of two by making sure that only the
3571 // integer bit is set in the significand.
3572 if (significandLSB() != semantics->precision - 1)
3573 return false;
3574
3575 // Get the inverse.
3576 APFloat reciprocal(*semantics, 1ULL);
3577 if (reciprocal.divide(*this, rmNearestTiesToEven) != opOK)
3578 return false;
3579
Benjamin Kramer83985122011-03-30 17:02:54 +00003580 // Avoid multiplication with a denormal, it is not safe on all platforms and
3581 // may be slower than a normal division.
3582 if (reciprocal.significandMSB() + 1 < reciprocal.semantics->precision)
3583 return false;
3584
3585 assert(reciprocal.category == fcNormal &&
3586 reciprocal.significandLSB() == reciprocal.semantics->precision - 1);
3587
Benjamin Kramer27460002011-03-30 15:42:27 +00003588 if (inv)
3589 *inv = reciprocal;
3590
3591 return true;
3592}