blob: ff8b7f157ee0eda6f19c8ff6f36a6d9cbc70ac44 [file] [log] [blame]
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001//===-- APFloat.cpp - Implement APFloat class -----------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattnerf3ebc3f2007-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 Lattnerfe02c1f2007-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 Lattnere5256752007-12-08 19:00:03 +000015#include "llvm/ADT/APFloat.h"
Jeffrey Yasskin03b81a22011-07-15 07:04:56 +000016#include "llvm/ADT/APSInt.h"
Ted Kremenek6f30a072008-02-11 17:24:50 +000017#include "llvm/ADT/FoldingSet.h"
Chandler Carruth71bd7d12012-03-04 12:02:57 +000018#include "llvm/ADT/Hashing.h"
Jordan Rosee1f76582013-01-18 21:45:30 +000019#include "llvm/ADT/StringExtras.h"
Chandler Carruth71bd7d12012-03-04 12:02:57 +000020#include "llvm/ADT/StringRef.h"
Torok Edwin56d06592009-07-11 20:10:48 +000021#include "llvm/Support/ErrorHandling.h"
Dale Johannesen918c33c2007-08-24 05:08:11 +000022#include "llvm/Support/MathExtras.h"
Chris Lattner17f71652008-08-17 07:19:36 +000023#include <cstring>
Chandler Carruthed0881b2012-12-03 16:50:05 +000024#include <limits.h>
Chris Lattnerfe02c1f2007-08-20 22:49:32 +000025
26using namespace llvm;
27
Michael Gottesman9b877e12013-06-24 09:57:57 +000028/// A macro used to combine two fcCategory enums into one key which can be used
29/// in a switch statement to classify how the interaction of two APFloat's
30/// categories affects an operation.
31///
32/// TODO: If clang source code is ever allowed to use constexpr in its own
33/// codebase, change this into a static inline function.
34#define PackCategoriesIntoKey(_lhs, _rhs) ((_lhs) * 4 + (_rhs))
Chris Lattnerfe02c1f2007-08-20 22:49:32 +000035
Neil Booth8f1946f2007-10-03 22:26:02 +000036/* Assumed in hexadecimal significand parsing, and conversion to
37 hexadecimal strings. */
Chris Lattner8fcea672008-08-17 04:58:58 +000038#define COMPILE_TIME_ASSERT(cond) extern int CTAssert[(cond) ? 1 : -1]
Chris Lattnerfe02c1f2007-08-20 22:49:32 +000039COMPILE_TIME_ASSERT(integerPartWidth % 4 == 0);
40
41namespace llvm {
42
43 /* Represents floating point arithmetic semantics. */
44 struct fltSemantics {
45 /* The largest E such that 2^E is representable; this matches the
46 definition of IEEE 754. */
Michael Gottesman9dc98332013-06-24 04:06:23 +000047 APFloat::ExponentType maxExponent;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +000048
49 /* The smallest E such that 2^E is a normalized number; this
50 matches the definition of IEEE 754. */
Michael Gottesman9dc98332013-06-24 04:06:23 +000051 APFloat::ExponentType minExponent;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +000052
53 /* Number of bits in the significand. This includes the integer
54 bit. */
Neil Booth146fdb32007-10-12 15:33:27 +000055 unsigned int precision;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +000056 };
57
Ulrich Weigand908c9362012-10-29 18:18:44 +000058 const fltSemantics APFloat::IEEEhalf = { 15, -14, 11 };
59 const fltSemantics APFloat::IEEEsingle = { 127, -126, 24 };
60 const fltSemantics APFloat::IEEEdouble = { 1023, -1022, 53 };
61 const fltSemantics APFloat::IEEEquad = { 16383, -16382, 113 };
62 const fltSemantics APFloat::x87DoubleExtended = { 16383, -16382, 64 };
63 const fltSemantics APFloat::Bogus = { 0, 0, 0 };
Dale Johannesen007aa372007-10-11 18:07:22 +000064
Ulrich Weigandd9f7e252012-10-29 18:09:01 +000065 /* The PowerPC format consists of two doubles. It does not map cleanly
66 onto the usual format above. It is approximated using twice the
67 mantissa bits. Note that for exponents near the double minimum,
68 we no longer can represent the full 106 mantissa bits, so those
69 will be treated as denormal numbers.
70
71 FIXME: While this approximation is equivalent to what GCC uses for
72 compile-time arithmetic on PPC double-double numbers, it is not able
73 to represent all possible values held by a PPC double-double number,
74 for example: (long double) 1.0 + (long double) 0x1p-106
75 Should this be replaced by a full emulation of PPC double-double? */
Ulrich Weigand908c9362012-10-29 18:18:44 +000076 const fltSemantics APFloat::PPCDoubleDouble = { 1023, -1022 + 53, 53 + 53 };
Neil Boothb93d90e2007-10-12 16:02:31 +000077
78 /* A tight upper bound on number of parts required to hold the value
79 pow(5, power) is
80
Neil Booth91305512007-10-15 15:00:55 +000081 power * 815 / (351 * integerPartWidth) + 1
Dan Gohmanb452d4e2010-03-24 19:38:02 +000082
Neil Boothb93d90e2007-10-12 16:02:31 +000083 However, whilst the result may require only this many parts,
84 because we are multiplying two values to get it, the
85 multiplication may require an extra part with the excess part
86 being zero (consider the trivial case of 1 * 1, tcFullMultiply
87 requires two parts to hold the single-part result). So we add an
88 extra one to guarantee enough space whilst multiplying. */
89 const unsigned int maxExponent = 16383;
90 const unsigned int maxPrecision = 113;
91 const unsigned int maxPowerOfFiveExponent = maxExponent + maxPrecision - 1;
Neil Booth91305512007-10-15 15:00:55 +000092 const unsigned int maxPowerOfFiveParts = 2 + ((maxPowerOfFiveExponent * 815)
93 / (351 * integerPartWidth));
Chris Lattnerfe02c1f2007-08-20 22:49:32 +000094}
95
Chris Lattner91702092009-03-12 23:59:55 +000096/* A bunch of private, handy routines. */
Chris Lattnerfe02c1f2007-08-20 22:49:32 +000097
Chris Lattner91702092009-03-12 23:59:55 +000098static inline unsigned int
99partCountForBits(unsigned int bits)
100{
101 return ((bits) + integerPartWidth - 1) / integerPartWidth;
102}
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000103
Chris Lattner91702092009-03-12 23:59:55 +0000104/* Returns 0U-9U. Return values >= 10U are not digits. */
105static inline unsigned int
106decDigitValue(unsigned int c)
107{
108 return c - '0';
109}
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000110
Chris Lattner91702092009-03-12 23:59:55 +0000111/* Return the value of a decimal exponent of the form
112 [+-]ddddddd.
Neil Booth4ed401b2007-10-14 10:16:12 +0000113
Chris Lattner91702092009-03-12 23:59:55 +0000114 If the exponent overflows, returns a large exponent with the
115 appropriate sign. */
116static int
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000117readExponent(StringRef::iterator begin, StringRef::iterator end)
Chris Lattner91702092009-03-12 23:59:55 +0000118{
119 bool isNegative;
120 unsigned int absExponent;
121 const unsigned int overlargeExponent = 24000; /* FIXME. */
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000122 StringRef::iterator p = begin;
123
124 assert(p != end && "Exponent has no digits");
Neil Booth4ed401b2007-10-14 10:16:12 +0000125
Chris Lattner91702092009-03-12 23:59:55 +0000126 isNegative = (*p == '-');
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000127 if (*p == '-' || *p == '+') {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000128 p++;
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000129 assert(p != end && "Exponent has no digits");
130 }
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000131
Chris Lattner91702092009-03-12 23:59:55 +0000132 absExponent = decDigitValue(*p++);
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000133 assert(absExponent < 10U && "Invalid character in exponent");
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000134
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000135 for (; p != end; ++p) {
Chris Lattner91702092009-03-12 23:59:55 +0000136 unsigned int value;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000137
Chris Lattner91702092009-03-12 23:59:55 +0000138 value = decDigitValue(*p);
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000139 assert(value < 10U && "Invalid character in exponent");
Chris Lattner91702092009-03-12 23:59:55 +0000140
Chris Lattner91702092009-03-12 23:59:55 +0000141 value += absExponent * 10;
142 if (absExponent >= overlargeExponent) {
143 absExponent = overlargeExponent;
Dale Johannesen370c77c2010-08-19 17:58:35 +0000144 p = end; /* outwit assert below */
Chris Lattner91702092009-03-12 23:59:55 +0000145 break;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000146 }
Chris Lattner91702092009-03-12 23:59:55 +0000147 absExponent = value;
148 }
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000149
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000150 assert(p == end && "Invalid exponent in exponent");
151
Chris Lattner91702092009-03-12 23:59:55 +0000152 if (isNegative)
153 return -(int) absExponent;
154 else
155 return (int) absExponent;
156}
157
158/* This is ugly and needs cleaning up, but I don't immediately see
159 how whilst remaining safe. */
160static int
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000161totalExponent(StringRef::iterator p, StringRef::iterator end,
162 int exponentAdjustment)
Chris Lattner91702092009-03-12 23:59:55 +0000163{
164 int unsignedExponent;
165 bool negative, overflow;
Ted Kremenek3c4408c2011-01-23 17:05:06 +0000166 int exponent = 0;
Chris Lattner91702092009-03-12 23:59:55 +0000167
Erick Tryzelaarda666c82009-08-20 23:30:43 +0000168 assert(p != end && "Exponent has no digits");
169
Chris Lattner91702092009-03-12 23:59:55 +0000170 negative = *p == '-';
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000171 if (*p == '-' || *p == '+') {
Chris Lattner91702092009-03-12 23:59:55 +0000172 p++;
Erick Tryzelaarda666c82009-08-20 23:30:43 +0000173 assert(p != end && "Exponent has no digits");
174 }
Chris Lattner91702092009-03-12 23:59:55 +0000175
176 unsignedExponent = 0;
177 overflow = false;
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000178 for (; p != end; ++p) {
Chris Lattner91702092009-03-12 23:59:55 +0000179 unsigned int value;
180
181 value = decDigitValue(*p);
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000182 assert(value < 10U && "Invalid character in exponent");
Chris Lattner91702092009-03-12 23:59:55 +0000183
Chris Lattner91702092009-03-12 23:59:55 +0000184 unsignedExponent = unsignedExponent * 10 + value;
Richard Smith156d9202012-08-24 00:01:19 +0000185 if (unsignedExponent > 32767) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000186 overflow = true;
Richard Smith156d9202012-08-24 00:01:19 +0000187 break;
188 }
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000189 }
190
Abramo Bagnaraa41d7ae2011-01-06 16:55:14 +0000191 if (exponentAdjustment > 32767 || exponentAdjustment < -32768)
Chris Lattner91702092009-03-12 23:59:55 +0000192 overflow = true;
193
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000194 if (!overflow) {
Chris Lattner91702092009-03-12 23:59:55 +0000195 exponent = unsignedExponent;
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000196 if (negative)
Chris Lattner91702092009-03-12 23:59:55 +0000197 exponent = -exponent;
198 exponent += exponentAdjustment;
Abramo Bagnaraa41d7ae2011-01-06 16:55:14 +0000199 if (exponent > 32767 || exponent < -32768)
Chris Lattner91702092009-03-12 23:59:55 +0000200 overflow = true;
201 }
202
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000203 if (overflow)
Abramo Bagnaraa41d7ae2011-01-06 16:55:14 +0000204 exponent = negative ? -32768: 32767;
Chris Lattner91702092009-03-12 23:59:55 +0000205
206 return exponent;
207}
208
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000209static StringRef::iterator
210skipLeadingZeroesAndAnyDot(StringRef::iterator begin, StringRef::iterator end,
211 StringRef::iterator *dot)
Chris Lattner91702092009-03-12 23:59:55 +0000212{
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000213 StringRef::iterator p = begin;
214 *dot = end;
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000215 while (*p == '0' && p != end)
Chris Lattner91702092009-03-12 23:59:55 +0000216 p++;
217
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000218 if (*p == '.') {
Chris Lattner91702092009-03-12 23:59:55 +0000219 *dot = p++;
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000220
Erick Tryzelaarda666c82009-08-20 23:30:43 +0000221 assert(end - begin != 1 && "Significand has no digits");
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000222
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000223 while (*p == '0' && p != end)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000224 p++;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000225 }
226
Chris Lattner91702092009-03-12 23:59:55 +0000227 return p;
228}
Neil Booth4ed401b2007-10-14 10:16:12 +0000229
Chris Lattner91702092009-03-12 23:59:55 +0000230/* Given a normal decimal floating point number of the form
Neil Booth4ed401b2007-10-14 10:16:12 +0000231
Chris Lattner91702092009-03-12 23:59:55 +0000232 dddd.dddd[eE][+-]ddd
Neil Booth91305512007-10-15 15:00:55 +0000233
Chris Lattner91702092009-03-12 23:59:55 +0000234 where the decimal point and exponent are optional, fill out the
235 structure D. Exponent is appropriate if the significand is
236 treated as an integer, and normalizedExponent if the significand
237 is taken to have the decimal point after a single leading
238 non-zero digit.
Neil Booth4ed401b2007-10-14 10:16:12 +0000239
Chris Lattner91702092009-03-12 23:59:55 +0000240 If the value is zero, V->firstSigDigit points to a non-digit, and
241 the return exponent is zero.
242*/
243struct decimalInfo {
244 const char *firstSigDigit;
245 const char *lastSigDigit;
246 int exponent;
247 int normalizedExponent;
248};
Neil Booth4ed401b2007-10-14 10:16:12 +0000249
Chris Lattner91702092009-03-12 23:59:55 +0000250static void
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000251interpretDecimal(StringRef::iterator begin, StringRef::iterator end,
252 decimalInfo *D)
Chris Lattner91702092009-03-12 23:59:55 +0000253{
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000254 StringRef::iterator dot = end;
255 StringRef::iterator p = skipLeadingZeroesAndAnyDot (begin, end, &dot);
Neil Booth4ed401b2007-10-14 10:16:12 +0000256
Chris Lattner91702092009-03-12 23:59:55 +0000257 D->firstSigDigit = p;
258 D->exponent = 0;
259 D->normalizedExponent = 0;
260
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000261 for (; p != end; ++p) {
Chris Lattner91702092009-03-12 23:59:55 +0000262 if (*p == '.') {
Erick Tryzelaarda666c82009-08-20 23:30:43 +0000263 assert(dot == end && "String contains multiple dots");
Chris Lattner91702092009-03-12 23:59:55 +0000264 dot = p++;
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000265 if (p == end)
266 break;
Neil Booth4ed401b2007-10-14 10:16:12 +0000267 }
Chris Lattner91702092009-03-12 23:59:55 +0000268 if (decDigitValue(*p) >= 10U)
269 break;
Chris Lattner91702092009-03-12 23:59:55 +0000270 }
Neil Booth4ed401b2007-10-14 10:16:12 +0000271
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000272 if (p != end) {
Erick Tryzelaarda666c82009-08-20 23:30:43 +0000273 assert((*p == 'e' || *p == 'E') && "Invalid character in significand");
274 assert(p != begin && "Significand has no digits");
275 assert((dot == end || p - begin != 1) && "Significand has no digits");
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000276
277 /* p points to the first non-digit in the string */
Erick Tryzelaarda666c82009-08-20 23:30:43 +0000278 D->exponent = readExponent(p + 1, end);
Neil Booth4ed401b2007-10-14 10:16:12 +0000279
Chris Lattner91702092009-03-12 23:59:55 +0000280 /* Implied decimal point? */
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000281 if (dot == end)
Chris Lattner91702092009-03-12 23:59:55 +0000282 dot = p;
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000283 }
Neil Booth4ed401b2007-10-14 10:16:12 +0000284
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000285 /* If number is all zeroes accept any exponent. */
286 if (p != D->firstSigDigit) {
Chris Lattner91702092009-03-12 23:59:55 +0000287 /* Drop insignificant trailing zeroes. */
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000288 if (p != begin) {
Neil Booth4ed401b2007-10-14 10:16:12 +0000289 do
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000290 do
291 p--;
292 while (p != begin && *p == '0');
293 while (p != begin && *p == '.');
294 }
Neil Booth4ed401b2007-10-14 10:16:12 +0000295
Chris Lattner91702092009-03-12 23:59:55 +0000296 /* Adjust the exponents for any decimal point. */
Michael Gottesman9dc98332013-06-24 04:06:23 +0000297 D->exponent += static_cast<APFloat::ExponentType>((dot - p) - (dot > p));
Chris Lattner91702092009-03-12 23:59:55 +0000298 D->normalizedExponent = (D->exponent +
Michael Gottesman9dc98332013-06-24 04:06:23 +0000299 static_cast<APFloat::ExponentType>((p - D->firstSigDigit)
Chris Lattner91702092009-03-12 23:59:55 +0000300 - (dot > D->firstSigDigit && dot < p)));
Neil Booth4ed401b2007-10-14 10:16:12 +0000301 }
302
Chris Lattner91702092009-03-12 23:59:55 +0000303 D->lastSigDigit = p;
304}
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000305
Chris Lattner91702092009-03-12 23:59:55 +0000306/* Return the trailing fraction of a hexadecimal number.
307 DIGITVALUE is the first hex digit of the fraction, P points to
308 the next digit. */
309static lostFraction
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000310trailingHexadecimalFraction(StringRef::iterator p, StringRef::iterator end,
311 unsigned int digitValue)
Chris Lattner91702092009-03-12 23:59:55 +0000312{
313 unsigned int hexDigit;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000314
Chris Lattner91702092009-03-12 23:59:55 +0000315 /* If the first trailing digit isn't 0 or 8 we can work out the
316 fraction immediately. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000317 if (digitValue > 8)
Chris Lattner91702092009-03-12 23:59:55 +0000318 return lfMoreThanHalf;
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000319 else if (digitValue < 8 && digitValue > 0)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000320 return lfLessThanHalf;
Chris Lattner91702092009-03-12 23:59:55 +0000321
322 /* Otherwise we need to find the first non-zero digit. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000323 while (*p == '0')
Chris Lattner91702092009-03-12 23:59:55 +0000324 p++;
325
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000326 assert(p != end && "Invalid trailing hexadecimal fraction!");
327
Chris Lattner91702092009-03-12 23:59:55 +0000328 hexDigit = hexDigitValue(*p);
329
330 /* If we ran off the end it is exactly zero or one-half, otherwise
331 a little more. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000332 if (hexDigit == -1U)
Chris Lattner91702092009-03-12 23:59:55 +0000333 return digitValue == 0 ? lfExactlyZero: lfExactlyHalf;
334 else
335 return digitValue == 0 ? lfLessThanHalf: lfMoreThanHalf;
336}
337
338/* Return the fraction lost were a bignum truncated losing the least
339 significant BITS bits. */
340static lostFraction
341lostFractionThroughTruncation(const integerPart *parts,
342 unsigned int partCount,
343 unsigned int bits)
344{
345 unsigned int lsb;
346
347 lsb = APInt::tcLSB(parts, partCount);
348
349 /* Note this is guaranteed true if bits == 0, or LSB == -1U. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000350 if (bits <= lsb)
Chris Lattner91702092009-03-12 23:59:55 +0000351 return lfExactlyZero;
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000352 if (bits == lsb + 1)
Chris Lattner91702092009-03-12 23:59:55 +0000353 return lfExactlyHalf;
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000354 if (bits <= partCount * integerPartWidth &&
355 APInt::tcExtractBit(parts, bits - 1))
Chris Lattner91702092009-03-12 23:59:55 +0000356 return lfMoreThanHalf;
357
358 return lfLessThanHalf;
359}
360
361/* Shift DST right BITS bits noting lost fraction. */
362static lostFraction
363shiftRight(integerPart *dst, unsigned int parts, unsigned int bits)
364{
365 lostFraction lost_fraction;
366
367 lost_fraction = lostFractionThroughTruncation(dst, parts, bits);
368
369 APInt::tcShiftRight(dst, parts, bits);
370
371 return lost_fraction;
372}
373
374/* Combine the effect of two lost fractions. */
375static lostFraction
376combineLostFractions(lostFraction moreSignificant,
377 lostFraction lessSignificant)
378{
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000379 if (lessSignificant != lfExactlyZero) {
380 if (moreSignificant == lfExactlyZero)
Chris Lattner91702092009-03-12 23:59:55 +0000381 moreSignificant = lfLessThanHalf;
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000382 else if (moreSignificant == lfExactlyHalf)
Chris Lattner91702092009-03-12 23:59:55 +0000383 moreSignificant = lfMoreThanHalf;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000384 }
385
Chris Lattner91702092009-03-12 23:59:55 +0000386 return moreSignificant;
387}
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000388
Chris Lattner91702092009-03-12 23:59:55 +0000389/* The error from the true value, in half-ulps, on multiplying two
390 floating point numbers, which differ from the value they
391 approximate by at most HUE1 and HUE2 half-ulps, is strictly less
392 than the returned value.
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000393
Chris Lattner91702092009-03-12 23:59:55 +0000394 See "How to Read Floating Point Numbers Accurately" by William D
395 Clinger. */
396static unsigned int
397HUerrBound(bool inexactMultiply, unsigned int HUerr1, unsigned int HUerr2)
398{
399 assert(HUerr1 < 2 || HUerr2 < 2 || (HUerr1 + HUerr2 < 8));
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000400
Chris Lattner91702092009-03-12 23:59:55 +0000401 if (HUerr1 + HUerr2 == 0)
402 return inexactMultiply * 2; /* <= inexactMultiply half-ulps. */
403 else
404 return inexactMultiply + 2 * (HUerr1 + HUerr2);
405}
Neil Booth8f1946f2007-10-03 22:26:02 +0000406
Chris Lattner91702092009-03-12 23:59:55 +0000407/* The number of ulps from the boundary (zero, or half if ISNEAREST)
408 when the least significant BITS are truncated. BITS cannot be
409 zero. */
410static integerPart
411ulpsFromBoundary(const integerPart *parts, unsigned int bits, bool isNearest)
412{
413 unsigned int count, partBits;
414 integerPart part, boundary;
Neil Boothd3985922007-10-07 08:51:21 +0000415
Evan Cheng67c90212009-10-27 21:35:42 +0000416 assert(bits != 0);
Neil Booth8f1946f2007-10-03 22:26:02 +0000417
Chris Lattner91702092009-03-12 23:59:55 +0000418 bits--;
419 count = bits / integerPartWidth;
420 partBits = bits % integerPartWidth + 1;
Neil Boothb93d90e2007-10-12 16:02:31 +0000421
Chris Lattner91702092009-03-12 23:59:55 +0000422 part = parts[count] & (~(integerPart) 0 >> (integerPartWidth - partBits));
Neil Boothb93d90e2007-10-12 16:02:31 +0000423
Chris Lattner91702092009-03-12 23:59:55 +0000424 if (isNearest)
425 boundary = (integerPart) 1 << (partBits - 1);
426 else
427 boundary = 0;
428
429 if (count == 0) {
430 if (part - boundary <= boundary - part)
431 return part - boundary;
Neil Boothb93d90e2007-10-12 16:02:31 +0000432 else
Chris Lattner91702092009-03-12 23:59:55 +0000433 return boundary - part;
Neil Boothb93d90e2007-10-12 16:02:31 +0000434 }
435
Chris Lattner91702092009-03-12 23:59:55 +0000436 if (part == boundary) {
437 while (--count)
438 if (parts[count])
439 return ~(integerPart) 0; /* A lot. */
Neil Boothb93d90e2007-10-12 16:02:31 +0000440
Chris Lattner91702092009-03-12 23:59:55 +0000441 return parts[0];
442 } else if (part == boundary - 1) {
443 while (--count)
444 if (~parts[count])
445 return ~(integerPart) 0; /* A lot. */
Neil Boothb93d90e2007-10-12 16:02:31 +0000446
Chris Lattner91702092009-03-12 23:59:55 +0000447 return -parts[0];
448 }
Neil Boothb93d90e2007-10-12 16:02:31 +0000449
Chris Lattner91702092009-03-12 23:59:55 +0000450 return ~(integerPart) 0; /* A lot. */
451}
Neil Boothb93d90e2007-10-12 16:02:31 +0000452
Chris Lattner91702092009-03-12 23:59:55 +0000453/* Place pow(5, power) in DST, and return the number of parts used.
454 DST must be at least one part larger than size of the answer. */
455static unsigned int
456powerOf5(integerPart *dst, unsigned int power)
457{
458 static const integerPart firstEightPowers[] = { 1, 5, 25, 125, 625, 3125,
459 15625, 78125 };
Chris Lattnerb858c0e2009-03-13 00:24:01 +0000460 integerPart pow5s[maxPowerOfFiveParts * 2 + 5];
461 pow5s[0] = 78125 * 5;
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000462
Chris Lattner0bf18692009-03-13 00:03:51 +0000463 unsigned int partsCount[16] = { 1 };
Chris Lattner91702092009-03-12 23:59:55 +0000464 integerPart scratch[maxPowerOfFiveParts], *p1, *p2, *pow5;
465 unsigned int result;
Chris Lattner91702092009-03-12 23:59:55 +0000466 assert(power <= maxExponent);
467
468 p1 = dst;
469 p2 = scratch;
470
471 *p1 = firstEightPowers[power & 7];
472 power >>= 3;
473
474 result = 1;
475 pow5 = pow5s;
476
477 for (unsigned int n = 0; power; power >>= 1, n++) {
478 unsigned int pc;
479
480 pc = partsCount[n];
481
482 /* Calculate pow(5,pow(2,n+3)) if we haven't yet. */
483 if (pc == 0) {
484 pc = partsCount[n - 1];
485 APInt::tcFullMultiply(pow5, pow5 - pc, pow5 - pc, pc, pc);
486 pc *= 2;
487 if (pow5[pc - 1] == 0)
488 pc--;
489 partsCount[n] = pc;
Neil Boothb93d90e2007-10-12 16:02:31 +0000490 }
491
Chris Lattner91702092009-03-12 23:59:55 +0000492 if (power & 1) {
493 integerPart *tmp;
Neil Boothb93d90e2007-10-12 16:02:31 +0000494
Chris Lattner91702092009-03-12 23:59:55 +0000495 APInt::tcFullMultiply(p2, p1, pow5, result, pc);
496 result += pc;
497 if (p2[result - 1] == 0)
498 result--;
Neil Boothb93d90e2007-10-12 16:02:31 +0000499
Chris Lattner91702092009-03-12 23:59:55 +0000500 /* Now result is in p1 with partsCount parts and p2 is scratch
501 space. */
502 tmp = p1, p1 = p2, p2 = tmp;
Neil Boothb93d90e2007-10-12 16:02:31 +0000503 }
504
Chris Lattner91702092009-03-12 23:59:55 +0000505 pow5 += pc;
Neil Boothb93d90e2007-10-12 16:02:31 +0000506 }
507
Chris Lattner91702092009-03-12 23:59:55 +0000508 if (p1 != dst)
509 APInt::tcAssign(dst, p1, result);
Neil Boothb93d90e2007-10-12 16:02:31 +0000510
Chris Lattner91702092009-03-12 23:59:55 +0000511 return result;
512}
Neil Boothb93d90e2007-10-12 16:02:31 +0000513
Chris Lattner91702092009-03-12 23:59:55 +0000514/* Zero at the end to avoid modular arithmetic when adding one; used
515 when rounding up during hexadecimal output. */
516static const char hexDigitsLower[] = "0123456789abcdef0";
517static const char hexDigitsUpper[] = "0123456789ABCDEF0";
518static const char infinityL[] = "infinity";
519static const char infinityU[] = "INFINITY";
520static const char NaNL[] = "nan";
521static const char NaNU[] = "NAN";
Neil Boothb93d90e2007-10-12 16:02:31 +0000522
Chris Lattner91702092009-03-12 23:59:55 +0000523/* Write out an integerPart in hexadecimal, starting with the most
524 significant nibble. Write out exactly COUNT hexdigits, return
525 COUNT. */
526static unsigned int
527partAsHex (char *dst, integerPart part, unsigned int count,
528 const char *hexDigitChars)
529{
530 unsigned int result = count;
Neil Boothb93d90e2007-10-12 16:02:31 +0000531
Evan Cheng67c90212009-10-27 21:35:42 +0000532 assert(count != 0 && count <= integerPartWidth / 4);
Neil Boothb93d90e2007-10-12 16:02:31 +0000533
Chris Lattner91702092009-03-12 23:59:55 +0000534 part >>= (integerPartWidth - 4 * count);
535 while (count--) {
536 dst[count] = hexDigitChars[part & 0xf];
537 part >>= 4;
Neil Boothb93d90e2007-10-12 16:02:31 +0000538 }
539
Chris Lattner91702092009-03-12 23:59:55 +0000540 return result;
541}
Neil Booth8f1946f2007-10-03 22:26:02 +0000542
Chris Lattner91702092009-03-12 23:59:55 +0000543/* Write out an unsigned decimal integer. */
544static char *
545writeUnsignedDecimal (char *dst, unsigned int n)
546{
547 char buff[40], *p;
Neil Booth8f1946f2007-10-03 22:26:02 +0000548
Chris Lattner91702092009-03-12 23:59:55 +0000549 p = buff;
550 do
551 *p++ = '0' + n % 10;
552 while (n /= 10);
Neil Booth8f1946f2007-10-03 22:26:02 +0000553
Chris Lattner91702092009-03-12 23:59:55 +0000554 do
555 *dst++ = *--p;
556 while (p != buff);
Neil Booth8f1946f2007-10-03 22:26:02 +0000557
Chris Lattner91702092009-03-12 23:59:55 +0000558 return dst;
559}
Neil Booth8f1946f2007-10-03 22:26:02 +0000560
Chris Lattner91702092009-03-12 23:59:55 +0000561/* Write out a signed decimal integer. */
562static char *
563writeSignedDecimal (char *dst, int value)
564{
565 if (value < 0) {
566 *dst++ = '-';
567 dst = writeUnsignedDecimal(dst, -(unsigned) value);
568 } else
569 dst = writeUnsignedDecimal(dst, value);
Neil Booth8f1946f2007-10-03 22:26:02 +0000570
Chris Lattner91702092009-03-12 23:59:55 +0000571 return dst;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000572}
573
574/* Constructors. */
575void
576APFloat::initialize(const fltSemantics *ourSemantics)
577{
578 unsigned int count;
579
580 semantics = ourSemantics;
581 count = partCount();
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000582 if (count > 1)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000583 significand.parts = new integerPart[count];
584}
585
586void
587APFloat::freeSignificand()
588{
Manuel Klimekd0cf5b22013-06-03 13:03:05 +0000589 if (needsCleanup())
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000590 delete [] significand.parts;
591}
592
593void
594APFloat::assign(const APFloat &rhs)
595{
596 assert(semantics == rhs.semantics);
597
598 sign = rhs.sign;
599 category = rhs.category;
600 exponent = rhs.exponent;
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000601 if (category == fcNormal || category == fcNaN)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000602 copySignificand(rhs);
603}
604
605void
606APFloat::copySignificand(const APFloat &rhs)
607{
Dale Johannesen3cf889f2007-08-31 04:03:46 +0000608 assert(category == fcNormal || category == fcNaN);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000609 assert(rhs.partCount() >= partCount());
610
611 APInt::tcAssign(significandParts(), rhs.significandParts(),
Neil Booth9acbf5a2007-09-26 21:33:42 +0000612 partCount());
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000613}
614
Neil Booth5fe658b2007-10-14 10:39:51 +0000615/* Make this number a NaN, with an arbitrary but deterministic value
Dale Johannesen1f864982009-01-21 20:32:55 +0000616 for the significand. If double or longer, this is a signalling NaN,
Mike Stump799bf582009-05-30 03:49:43 +0000617 which may not be ideal. If float, this is QNaN(0). */
John McCalldcb9a7a2010-02-28 02:51:25 +0000618void APFloat::makeNaN(bool SNaN, bool Negative, const APInt *fill)
Neil Booth5fe658b2007-10-14 10:39:51 +0000619{
620 category = fcNaN;
John McCalldcb9a7a2010-02-28 02:51:25 +0000621 sign = Negative;
622
John McCallc12b1332010-02-28 12:49:50 +0000623 integerPart *significand = significandParts();
624 unsigned numParts = partCount();
625
John McCalldcb9a7a2010-02-28 02:51:25 +0000626 // Set the significand bits to the fill.
John McCallc12b1332010-02-28 12:49:50 +0000627 if (!fill || fill->getNumWords() < numParts)
628 APInt::tcSet(significand, 0, numParts);
629 if (fill) {
John McCallc6dbe302010-03-01 18:38:45 +0000630 APInt::tcAssign(significand, fill->getRawData(),
631 std::min(fill->getNumWords(), numParts));
John McCallc12b1332010-02-28 12:49:50 +0000632
633 // Zero out the excess bits of the significand.
634 unsigned bitsToPreserve = semantics->precision - 1;
635 unsigned part = bitsToPreserve / 64;
636 bitsToPreserve %= 64;
637 significand[part] &= ((1ULL << bitsToPreserve) - 1);
638 for (part++; part != numParts; ++part)
639 significand[part] = 0;
640 }
641
642 unsigned QNaNBit = semantics->precision - 2;
John McCalldcb9a7a2010-02-28 02:51:25 +0000643
644 if (SNaN) {
645 // We always have to clear the QNaN bit to make it an SNaN.
John McCallc12b1332010-02-28 12:49:50 +0000646 APInt::tcClearBit(significand, QNaNBit);
John McCalldcb9a7a2010-02-28 02:51:25 +0000647
648 // If there are no bits set in the payload, we have to set
649 // *something* to make it a NaN instead of an infinity;
650 // conventionally, this is the next bit down from the QNaN bit.
John McCallc12b1332010-02-28 12:49:50 +0000651 if (APInt::tcIsZero(significand, numParts))
652 APInt::tcSetBit(significand, QNaNBit - 1);
John McCalldcb9a7a2010-02-28 02:51:25 +0000653 } else {
654 // We always have to set the QNaN bit to make it a QNaN.
John McCallc12b1332010-02-28 12:49:50 +0000655 APInt::tcSetBit(significand, QNaNBit);
John McCalldcb9a7a2010-02-28 02:51:25 +0000656 }
John McCallc12b1332010-02-28 12:49:50 +0000657
658 // For x87 extended precision, we want to make a NaN, not a
659 // pseudo-NaN. Maybe we should expose the ability to make
660 // pseudo-NaNs?
661 if (semantics == &APFloat::x87DoubleExtended)
662 APInt::tcSetBit(significand, QNaNBit + 1);
John McCalldcb9a7a2010-02-28 02:51:25 +0000663}
664
665APFloat APFloat::makeNaN(const fltSemantics &Sem, bool SNaN, bool Negative,
666 const APInt *fill) {
667 APFloat value(Sem, uninitialized);
668 value.makeNaN(SNaN, Negative, fill);
669 return value;
Neil Booth5fe658b2007-10-14 10:39:51 +0000670}
671
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000672APFloat &
673APFloat::operator=(const APFloat &rhs)
674{
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000675 if (this != &rhs) {
676 if (semantics != rhs.semantics) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000677 freeSignificand();
678 initialize(rhs.semantics);
679 }
680 assign(rhs);
681 }
682
683 return *this;
684}
685
Dale Johannesena719a602007-08-24 00:56:33 +0000686bool
Shuxin Yang4fb504f2013-01-07 18:59:35 +0000687APFloat::isDenormal() const {
Michael Gottesman3cb77ab2013-06-19 21:23:18 +0000688 return isFiniteNonZero() && (exponent == semantics->minExponent) &&
Shuxin Yang4fb504f2013-01-07 18:59:35 +0000689 (APInt::tcExtractBit(significandParts(),
690 semantics->precision - 1) == 0);
691}
692
693bool
Michael Gottesman0c622ea2013-05-30 18:07:13 +0000694APFloat::isSmallest() const {
695 // The smallest number by magnitude in our format will be the smallest
Michael Gottesmana7cc1242013-06-19 07:34:21 +0000696 // denormal, i.e. the floating point number with exponent being minimum
Michael Gottesman0c622ea2013-05-30 18:07:13 +0000697 // exponent and significand bitwise equal to 1 (i.e. with MSB equal to 0).
Michael Gottesman3cb77ab2013-06-19 21:23:18 +0000698 return isFiniteNonZero() && exponent == semantics->minExponent &&
Michael Gottesman0c622ea2013-05-30 18:07:13 +0000699 significandMSB() == 0;
700}
701
702bool APFloat::isSignificandAllOnes() const {
703 // Test if the significand excluding the integral bit is all ones. This allows
704 // us to test for binade boundaries.
705 const integerPart *Parts = significandParts();
706 const unsigned PartCount = partCount();
707 for (unsigned i = 0; i < PartCount - 1; i++)
708 if (~Parts[i])
709 return false;
710
711 // Set the unused high bits to all ones when we compare.
712 const unsigned NumHighBits =
713 PartCount*integerPartWidth - semantics->precision + 1;
714 assert(NumHighBits <= integerPartWidth && "Can not have more high bits to "
715 "fill than integerPartWidth");
716 const integerPart HighBitFill =
717 ~integerPart(0) << (integerPartWidth - NumHighBits);
718 if (~(Parts[PartCount - 1] | HighBitFill))
719 return false;
720
721 return true;
722}
723
724bool APFloat::isSignificandAllZeros() const {
725 // Test if the significand excluding the integral bit is all zeros. This
726 // allows us to test for binade boundaries.
727 const integerPart *Parts = significandParts();
728 const unsigned PartCount = partCount();
729
730 for (unsigned i = 0; i < PartCount - 1; i++)
731 if (Parts[i])
732 return false;
733
734 const unsigned NumHighBits =
735 PartCount*integerPartWidth - semantics->precision + 1;
736 assert(NumHighBits <= integerPartWidth && "Can not have more high bits to "
737 "clear than integerPartWidth");
738 const integerPart HighBitMask = ~integerPart(0) >> NumHighBits;
739
740 if (Parts[PartCount - 1] & HighBitMask)
741 return false;
742
743 return true;
744}
745
746bool
747APFloat::isLargest() const {
748 // The largest number by magnitude in our format will be the floating point
749 // number with maximum exponent and with significand that is all ones.
Michael Gottesman3cb77ab2013-06-19 21:23:18 +0000750 return isFiniteNonZero() && exponent == semantics->maxExponent
Michael Gottesman0c622ea2013-05-30 18:07:13 +0000751 && isSignificandAllOnes();
752}
753
754bool
Dale Johannesenbdea32d2007-08-24 22:09:56 +0000755APFloat::bitwiseIsEqual(const APFloat &rhs) const {
Dale Johannesena719a602007-08-24 00:56:33 +0000756 if (this == &rhs)
757 return true;
758 if (semantics != rhs.semantics ||
Dale Johannesen3cf889f2007-08-31 04:03:46 +0000759 category != rhs.category ||
760 sign != rhs.sign)
Dale Johannesena719a602007-08-24 00:56:33 +0000761 return false;
Dale Johannesen3cf889f2007-08-31 04:03:46 +0000762 if (category==fcZero || category==fcInfinity)
Dale Johannesena719a602007-08-24 00:56:33 +0000763 return true;
Dale Johannesen3cf889f2007-08-31 04:03:46 +0000764 else if (category==fcNormal && exponent!=rhs.exponent)
765 return false;
Dale Johannesena719a602007-08-24 00:56:33 +0000766 else {
Dale Johannesena719a602007-08-24 00:56:33 +0000767 int i= partCount();
768 const integerPart* p=significandParts();
769 const integerPart* q=rhs.significandParts();
770 for (; i>0; i--, p++, q++) {
771 if (*p != *q)
772 return false;
773 }
774 return true;
775 }
776}
777
Ulrich Weigande1d62f92012-10-29 18:17:42 +0000778APFloat::APFloat(const fltSemantics &ourSemantics, integerPart value) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000779 initialize(&ourSemantics);
780 sign = 0;
781 zeroSignificand();
782 exponent = ourSemantics.precision - 1;
783 significandParts()[0] = value;
784 normalize(rmNearestTiesToEven, lfExactlyZero);
785}
786
Ulrich Weigande1d62f92012-10-29 18:17:42 +0000787APFloat::APFloat(const fltSemantics &ourSemantics) {
Chris Lattnerac6271e2009-09-17 01:08:43 +0000788 initialize(&ourSemantics);
789 category = fcZero;
790 sign = false;
791}
792
Ulrich Weigande1d62f92012-10-29 18:17:42 +0000793APFloat::APFloat(const fltSemantics &ourSemantics, uninitializedTag tag) {
John McCalldcb9a7a2010-02-28 02:51:25 +0000794 // Allocates storage if necessary but does not initialize it.
795 initialize(&ourSemantics);
796}
Chris Lattnerac6271e2009-09-17 01:08:43 +0000797
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000798APFloat::APFloat(const fltSemantics &ourSemantics,
Ulrich Weigande1d62f92012-10-29 18:17:42 +0000799 fltCategory ourCategory, bool negative) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000800 initialize(&ourSemantics);
801 category = ourCategory;
802 sign = negative;
Mike Stump799bf582009-05-30 03:49:43 +0000803 if (category == fcNormal)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000804 category = fcZero;
Neil Booth5fe658b2007-10-14 10:39:51 +0000805 else if (ourCategory == fcNaN)
John McCalldcb9a7a2010-02-28 02:51:25 +0000806 makeNaN();
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000807}
808
Ulrich Weigande1d62f92012-10-29 18:17:42 +0000809APFloat::APFloat(const fltSemantics &ourSemantics, StringRef text) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000810 initialize(&ourSemantics);
811 convertFromString(text, rmNearestTiesToEven);
812}
813
Ulrich Weigande1d62f92012-10-29 18:17:42 +0000814APFloat::APFloat(const APFloat &rhs) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000815 initialize(rhs.semantics);
816 assign(rhs);
817}
818
819APFloat::~APFloat()
820{
821 freeSignificand();
822}
823
Ted Kremenek6f30a072008-02-11 17:24:50 +0000824// Profile - This method 'profiles' an APFloat for use with FoldingSet.
825void APFloat::Profile(FoldingSetNodeID& ID) const {
Dale Johannesen54306fe2008-10-09 18:53:47 +0000826 ID.Add(bitcastToAPInt());
Ted Kremenek6f30a072008-02-11 17:24:50 +0000827}
828
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000829unsigned int
830APFloat::partCount() const
831{
Dale Johannesen146a0ea2007-09-20 23:47:58 +0000832 return partCountForBits(semantics->precision + 1);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000833}
834
835unsigned int
836APFloat::semanticsPrecision(const fltSemantics &semantics)
837{
838 return semantics.precision;
839}
840
841const integerPart *
842APFloat::significandParts() const
843{
844 return const_cast<APFloat *>(this)->significandParts();
845}
846
847integerPart *
848APFloat::significandParts()
849{
Dale Johannesen3cf889f2007-08-31 04:03:46 +0000850 assert(category == fcNormal || category == fcNaN);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000851
Evan Cheng67c90212009-10-27 21:35:42 +0000852 if (partCount() > 1)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000853 return significand.parts;
854 else
855 return &significand.part;
856}
857
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000858void
859APFloat::zeroSignificand()
860{
861 category = fcNormal;
862 APInt::tcSet(significandParts(), 0, partCount());
863}
864
865/* Increment an fcNormal floating point number's significand. */
866void
867APFloat::incrementSignificand()
868{
869 integerPart carry;
870
871 carry = APInt::tcIncrement(significandParts(), partCount());
872
873 /* Our callers should never cause us to overflow. */
874 assert(carry == 0);
Duncan Sandsa41634e2011-08-12 14:54:45 +0000875 (void)carry;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000876}
877
878/* Add the significand of the RHS. Returns the carry flag. */
879integerPart
880APFloat::addSignificand(const APFloat &rhs)
881{
882 integerPart *parts;
883
884 parts = significandParts();
885
886 assert(semantics == rhs.semantics);
887 assert(exponent == rhs.exponent);
888
889 return APInt::tcAdd(parts, rhs.significandParts(), 0, partCount());
890}
891
892/* Subtract the significand of the RHS with a borrow flag. Returns
893 the borrow flag. */
894integerPart
895APFloat::subtractSignificand(const APFloat &rhs, integerPart borrow)
896{
897 integerPart *parts;
898
899 parts = significandParts();
900
901 assert(semantics == rhs.semantics);
902 assert(exponent == rhs.exponent);
903
904 return APInt::tcSubtract(parts, rhs.significandParts(), borrow,
Neil Booth9acbf5a2007-09-26 21:33:42 +0000905 partCount());
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000906}
907
908/* Multiply the significand of the RHS. If ADDEND is non-NULL, add it
909 on to the full-precision result of the multiplication. Returns the
910 lost fraction. */
911lostFraction
912APFloat::multiplySignificand(const APFloat &rhs, const APFloat *addend)
913{
Neil Booth9acbf5a2007-09-26 21:33:42 +0000914 unsigned int omsb; // One, not zero, based MSB.
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000915 unsigned int partsCount, newPartsCount, precision;
916 integerPart *lhsSignificand;
917 integerPart scratch[4];
918 integerPart *fullSignificand;
919 lostFraction lost_fraction;
Dale Johannesen4f0bd682008-10-09 23:00:39 +0000920 bool ignored;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000921
922 assert(semantics == rhs.semantics);
923
924 precision = semantics->precision;
925 newPartsCount = partCountForBits(precision * 2);
926
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000927 if (newPartsCount > 4)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000928 fullSignificand = new integerPart[newPartsCount];
929 else
930 fullSignificand = scratch;
931
932 lhsSignificand = significandParts();
933 partsCount = partCount();
934
935 APInt::tcFullMultiply(fullSignificand, lhsSignificand,
Neil Booth0ea72a92007-10-06 00:24:48 +0000936 rhs.significandParts(), partsCount, partsCount);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000937
938 lost_fraction = lfExactlyZero;
939 omsb = APInt::tcMSB(fullSignificand, newPartsCount) + 1;
940 exponent += rhs.exponent;
941
Shuxin Yangbbddbac2013-05-13 18:03:12 +0000942 // Assume the operands involved in the multiplication are single-precision
943 // FP, and the two multiplicants are:
944 // *this = a23 . a22 ... a0 * 2^e1
945 // rhs = b23 . b22 ... b0 * 2^e2
946 // the result of multiplication is:
947 // *this = c47 c46 . c45 ... c0 * 2^(e1+e2)
948 // Note that there are two significant bits at the left-hand side of the
949 // radix point. Move the radix point toward left by one bit, and adjust
950 // exponent accordingly.
951 exponent += 1;
952
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000953 if (addend) {
Shuxin Yangbbddbac2013-05-13 18:03:12 +0000954 // The intermediate result of the multiplication has "2 * precision"
955 // signicant bit; adjust the addend to be consistent with mul result.
956 //
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000957 Significand savedSignificand = significand;
958 const fltSemantics *savedSemantics = semantics;
959 fltSemantics extendedSemantics;
960 opStatus status;
961 unsigned int extendedPrecision;
962
963 /* Normalize our MSB. */
Shuxin Yangbbddbac2013-05-13 18:03:12 +0000964 extendedPrecision = 2 * precision;
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000965 if (omsb != extendedPrecision) {
Shuxin Yangbbddbac2013-05-13 18:03:12 +0000966 assert(extendedPrecision > omsb);
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000967 APInt::tcShiftLeft(fullSignificand, newPartsCount,
968 extendedPrecision - omsb);
969 exponent -= extendedPrecision - omsb;
970 }
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000971
972 /* Create new semantics. */
973 extendedSemantics = *semantics;
974 extendedSemantics.precision = extendedPrecision;
975
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000976 if (newPartsCount == 1)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000977 significand.part = fullSignificand[0];
978 else
979 significand.parts = fullSignificand;
980 semantics = &extendedSemantics;
981
982 APFloat extendedAddend(*addend);
Dale Johannesen4f0bd682008-10-09 23:00:39 +0000983 status = extendedAddend.convert(extendedSemantics, rmTowardZero, &ignored);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000984 assert(status == opOK);
Duncan Sandsa41634e2011-08-12 14:54:45 +0000985 (void)status;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000986 lost_fraction = addOrSubtractSignificand(extendedAddend, false);
987
988 /* Restore our state. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000989 if (newPartsCount == 1)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000990 fullSignificand[0] = significand.part;
991 significand = savedSignificand;
992 semantics = savedSemantics;
993
994 omsb = APInt::tcMSB(fullSignificand, newPartsCount) + 1;
995 }
996
Shuxin Yangbbddbac2013-05-13 18:03:12 +0000997 // Convert the result having "2 * precision" significant-bits back to the one
998 // having "precision" significant-bits. First, move the radix point from
999 // poision "2*precision - 1" to "precision - 1". The exponent need to be
1000 // adjusted by "2*precision - 1" - "precision - 1" = "precision".
1001 exponent -= precision;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001002
Shuxin Yangbbddbac2013-05-13 18:03:12 +00001003 // In case MSB resides at the left-hand side of radix point, shift the
1004 // mantissa right by some amount to make sure the MSB reside right before
1005 // the radix point (i.e. "MSB . rest-significant-bits").
1006 //
1007 // Note that the result is not normalized when "omsb < precision". So, the
1008 // caller needs to call APFloat::normalize() if normalized value is expected.
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001009 if (omsb > precision) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001010 unsigned int bits, significantParts;
1011 lostFraction lf;
1012
1013 bits = omsb - precision;
1014 significantParts = partCountForBits(omsb);
1015 lf = shiftRight(fullSignificand, significantParts, bits);
1016 lost_fraction = combineLostFractions(lf, lost_fraction);
1017 exponent += bits;
1018 }
1019
1020 APInt::tcAssign(lhsSignificand, fullSignificand, partsCount);
1021
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001022 if (newPartsCount > 4)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001023 delete [] fullSignificand;
1024
1025 return lost_fraction;
1026}
1027
1028/* Multiply the significands of LHS and RHS to DST. */
1029lostFraction
1030APFloat::divideSignificand(const APFloat &rhs)
1031{
1032 unsigned int bit, i, partsCount;
1033 const integerPart *rhsSignificand;
1034 integerPart *lhsSignificand, *dividend, *divisor;
1035 integerPart scratch[4];
1036 lostFraction lost_fraction;
1037
1038 assert(semantics == rhs.semantics);
1039
1040 lhsSignificand = significandParts();
1041 rhsSignificand = rhs.significandParts();
1042 partsCount = partCount();
1043
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001044 if (partsCount > 2)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001045 dividend = new integerPart[partsCount * 2];
1046 else
1047 dividend = scratch;
1048
1049 divisor = dividend + partsCount;
1050
1051 /* Copy the dividend and divisor as they will be modified in-place. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001052 for (i = 0; i < partsCount; i++) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001053 dividend[i] = lhsSignificand[i];
1054 divisor[i] = rhsSignificand[i];
1055 lhsSignificand[i] = 0;
1056 }
1057
1058 exponent -= rhs.exponent;
1059
1060 unsigned int precision = semantics->precision;
1061
1062 /* Normalize the divisor. */
1063 bit = precision - APInt::tcMSB(divisor, partsCount) - 1;
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001064 if (bit) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001065 exponent += bit;
1066 APInt::tcShiftLeft(divisor, partsCount, bit);
1067 }
1068
1069 /* Normalize the dividend. */
1070 bit = precision - APInt::tcMSB(dividend, partsCount) - 1;
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001071 if (bit) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001072 exponent -= bit;
1073 APInt::tcShiftLeft(dividend, partsCount, bit);
1074 }
1075
Neil Boothb93d90e2007-10-12 16:02:31 +00001076 /* Ensure the dividend >= divisor initially for the loop below.
1077 Incidentally, this means that the division loop below is
1078 guaranteed to set the integer bit to one. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001079 if (APInt::tcCompare(dividend, divisor, partsCount) < 0) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001080 exponent--;
1081 APInt::tcShiftLeft(dividend, partsCount, 1);
1082 assert(APInt::tcCompare(dividend, divisor, partsCount) >= 0);
1083 }
1084
1085 /* Long division. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001086 for (bit = precision; bit; bit -= 1) {
1087 if (APInt::tcCompare(dividend, divisor, partsCount) >= 0) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001088 APInt::tcSubtract(dividend, divisor, 0, partsCount);
1089 APInt::tcSetBit(lhsSignificand, bit - 1);
1090 }
1091
1092 APInt::tcShiftLeft(dividend, partsCount, 1);
1093 }
1094
1095 /* Figure out the lost fraction. */
1096 int cmp = APInt::tcCompare(dividend, divisor, partsCount);
1097
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001098 if (cmp > 0)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001099 lost_fraction = lfMoreThanHalf;
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001100 else if (cmp == 0)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001101 lost_fraction = lfExactlyHalf;
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001102 else if (APInt::tcIsZero(dividend, partsCount))
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001103 lost_fraction = lfExactlyZero;
1104 else
1105 lost_fraction = lfLessThanHalf;
1106
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001107 if (partsCount > 2)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001108 delete [] dividend;
1109
1110 return lost_fraction;
1111}
1112
1113unsigned int
1114APFloat::significandMSB() const
1115{
1116 return APInt::tcMSB(significandParts(), partCount());
1117}
1118
1119unsigned int
1120APFloat::significandLSB() const
1121{
1122 return APInt::tcLSB(significandParts(), partCount());
1123}
1124
1125/* Note that a zero result is NOT normalized to fcZero. */
1126lostFraction
1127APFloat::shiftSignificandRight(unsigned int bits)
1128{
1129 /* Our exponent should not overflow. */
Michael Gottesman9dc98332013-06-24 04:06:23 +00001130 assert((ExponentType) (exponent + bits) >= exponent);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001131
1132 exponent += bits;
1133
1134 return shiftRight(significandParts(), partCount(), bits);
1135}
1136
1137/* Shift the significand left BITS bits, subtract BITS from its exponent. */
1138void
1139APFloat::shiftSignificandLeft(unsigned int bits)
1140{
1141 assert(bits < semantics->precision);
1142
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001143 if (bits) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001144 unsigned int partsCount = partCount();
1145
1146 APInt::tcShiftLeft(significandParts(), partsCount, bits);
1147 exponent -= bits;
1148
1149 assert(!APInt::tcIsZero(significandParts(), partsCount));
1150 }
1151}
1152
1153APFloat::cmpResult
1154APFloat::compareAbsoluteValue(const APFloat &rhs) const
1155{
1156 int compare;
1157
1158 assert(semantics == rhs.semantics);
1159 assert(category == fcNormal);
1160 assert(rhs.category == fcNormal);
1161
1162 compare = exponent - rhs.exponent;
1163
1164 /* If exponents are equal, do an unsigned bignum comparison of the
1165 significands. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001166 if (compare == 0)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001167 compare = APInt::tcCompare(significandParts(), rhs.significandParts(),
Neil Booth9acbf5a2007-09-26 21:33:42 +00001168 partCount());
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001169
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001170 if (compare > 0)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001171 return cmpGreaterThan;
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001172 else if (compare < 0)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001173 return cmpLessThan;
1174 else
1175 return cmpEqual;
1176}
1177
1178/* Handle overflow. Sign is preserved. We either become infinity or
1179 the largest finite number. */
1180APFloat::opStatus
1181APFloat::handleOverflow(roundingMode rounding_mode)
1182{
1183 /* Infinity? */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001184 if (rounding_mode == rmNearestTiesToEven ||
1185 rounding_mode == rmNearestTiesToAway ||
1186 (rounding_mode == rmTowardPositive && !sign) ||
1187 (rounding_mode == rmTowardNegative && sign)) {
1188 category = fcInfinity;
1189 return (opStatus) (opOverflow | opInexact);
1190 }
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001191
1192 /* Otherwise we become the largest finite number. */
1193 category = fcNormal;
1194 exponent = semantics->maxExponent;
1195 APInt::tcSetLeastSignificantBits(significandParts(), partCount(),
Neil Booth9acbf5a2007-09-26 21:33:42 +00001196 semantics->precision);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001197
1198 return opInexact;
1199}
1200
Neil Booth1ca1f802007-10-03 15:16:41 +00001201/* Returns TRUE if, when truncating the current number, with BIT the
1202 new LSB, with the given lost fraction and rounding mode, the result
1203 would need to be rounded away from zero (i.e., by increasing the
1204 signficand). This routine must work for fcZero of both signs, and
1205 fcNormal numbers. */
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001206bool
1207APFloat::roundAwayFromZero(roundingMode rounding_mode,
Neil Booth1ca1f802007-10-03 15:16:41 +00001208 lostFraction lost_fraction,
1209 unsigned int bit) const
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001210{
Dale Johannesen3cf889f2007-08-31 04:03:46 +00001211 /* NaNs and infinities should not have lost fractions. */
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001212 assert(category == fcNormal || category == fcZero);
1213
Neil Booth1ca1f802007-10-03 15:16:41 +00001214 /* Current callers never pass this so we don't handle it. */
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001215 assert(lost_fraction != lfExactlyZero);
1216
Mike Stump889285d2009-05-13 23:23:20 +00001217 switch (rounding_mode) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001218 case rmNearestTiesToAway:
1219 return lost_fraction == lfExactlyHalf || lost_fraction == lfMoreThanHalf;
1220
1221 case rmNearestTiesToEven:
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001222 if (lost_fraction == lfMoreThanHalf)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001223 return true;
1224
1225 /* Our zeroes don't have a significand to test. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001226 if (lost_fraction == lfExactlyHalf && category != fcZero)
Neil Booth1ca1f802007-10-03 15:16:41 +00001227 return APInt::tcExtractBit(significandParts(), bit);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001228
1229 return false;
1230
1231 case rmTowardZero:
1232 return false;
1233
1234 case rmTowardPositive:
1235 return sign == false;
1236
1237 case rmTowardNegative:
1238 return sign == true;
1239 }
Chandler Carruthf3e85022012-01-10 18:08:01 +00001240 llvm_unreachable("Invalid rounding mode found");
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001241}
1242
1243APFloat::opStatus
1244APFloat::normalize(roundingMode rounding_mode,
Neil Booth9acbf5a2007-09-26 21:33:42 +00001245 lostFraction lost_fraction)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001246{
Neil Booth9acbf5a2007-09-26 21:33:42 +00001247 unsigned int omsb; /* One, not zero, based MSB. */
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001248 int exponentChange;
1249
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001250 if (category != fcNormal)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001251 return opOK;
1252
1253 /* Before rounding normalize the exponent of fcNormal numbers. */
1254 omsb = significandMSB() + 1;
1255
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001256 if (omsb) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001257 /* OMSB is numbered from 1. We want to place it in the integer
Nick Lewyckyf66daac2011-10-03 21:30:08 +00001258 bit numbered PRECISION if possible, with a compensating change in
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001259 the exponent. */
1260 exponentChange = omsb - semantics->precision;
1261
1262 /* If the resulting exponent is too high, overflow according to
1263 the rounding mode. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001264 if (exponent + exponentChange > semantics->maxExponent)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001265 return handleOverflow(rounding_mode);
1266
1267 /* Subnormal numbers have exponent minExponent, and their MSB
1268 is forced based on that. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001269 if (exponent + exponentChange < semantics->minExponent)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001270 exponentChange = semantics->minExponent - exponent;
1271
1272 /* Shifting left is easy as we don't lose precision. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001273 if (exponentChange < 0) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001274 assert(lost_fraction == lfExactlyZero);
1275
1276 shiftSignificandLeft(-exponentChange);
1277
1278 return opOK;
1279 }
1280
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001281 if (exponentChange > 0) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001282 lostFraction lf;
1283
1284 /* Shift right and capture any new lost fraction. */
1285 lf = shiftSignificandRight(exponentChange);
1286
1287 lost_fraction = combineLostFractions(lf, lost_fraction);
1288
1289 /* Keep OMSB up-to-date. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001290 if (omsb > (unsigned) exponentChange)
Neil Boothb93d90e2007-10-12 16:02:31 +00001291 omsb -= exponentChange;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001292 else
Neil Booth9acbf5a2007-09-26 21:33:42 +00001293 omsb = 0;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001294 }
1295 }
1296
1297 /* Now round the number according to rounding_mode given the lost
1298 fraction. */
1299
1300 /* As specified in IEEE 754, since we do not trap we do not report
1301 underflow for exact results. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001302 if (lost_fraction == lfExactlyZero) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001303 /* Canonicalize zeroes. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001304 if (omsb == 0)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001305 category = fcZero;
1306
1307 return opOK;
1308 }
1309
1310 /* Increment the significand if we're rounding away from zero. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001311 if (roundAwayFromZero(rounding_mode, lost_fraction, 0)) {
1312 if (omsb == 0)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001313 exponent = semantics->minExponent;
1314
1315 incrementSignificand();
1316 omsb = significandMSB() + 1;
1317
1318 /* Did the significand increment overflow? */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001319 if (omsb == (unsigned) semantics->precision + 1) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001320 /* Renormalize by incrementing the exponent and shifting our
Neil Booth9acbf5a2007-09-26 21:33:42 +00001321 significand right one. However if we already have the
1322 maximum exponent we overflow to infinity. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001323 if (exponent == semantics->maxExponent) {
Neil Booth9acbf5a2007-09-26 21:33:42 +00001324 category = fcInfinity;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001325
Neil Booth9acbf5a2007-09-26 21:33:42 +00001326 return (opStatus) (opOverflow | opInexact);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001327 }
1328
1329 shiftSignificandRight(1);
1330
1331 return opInexact;
1332 }
1333 }
1334
1335 /* The normal case - we were and are not denormal, and any
1336 significand increment above didn't overflow. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001337 if (omsb == semantics->precision)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001338 return opInexact;
1339
1340 /* We have a non-zero denormal. */
1341 assert(omsb < semantics->precision);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001342
1343 /* Canonicalize zeroes. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001344 if (omsb == 0)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001345 category = fcZero;
1346
1347 /* The fcZero case is a denormal that underflowed to zero. */
1348 return (opStatus) (opUnderflow | opInexact);
1349}
1350
1351APFloat::opStatus
1352APFloat::addOrSubtractSpecials(const APFloat &rhs, bool subtract)
1353{
Michael Gottesman9b877e12013-06-24 09:57:57 +00001354 switch (PackCategoriesIntoKey(category, rhs.category)) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001355 default:
Torok Edwinfbcc6632009-07-14 16:55:14 +00001356 llvm_unreachable(0);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001357
Michael Gottesman9b877e12013-06-24 09:57:57 +00001358 case PackCategoriesIntoKey(fcNaN, fcZero):
1359 case PackCategoriesIntoKey(fcNaN, fcNormal):
1360 case PackCategoriesIntoKey(fcNaN, fcInfinity):
1361 case PackCategoriesIntoKey(fcNaN, fcNaN):
1362 case PackCategoriesIntoKey(fcNormal, fcZero):
1363 case PackCategoriesIntoKey(fcInfinity, fcNormal):
1364 case PackCategoriesIntoKey(fcInfinity, fcZero):
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001365 return opOK;
1366
Michael Gottesman9b877e12013-06-24 09:57:57 +00001367 case PackCategoriesIntoKey(fcZero, fcNaN):
1368 case PackCategoriesIntoKey(fcNormal, fcNaN):
1369 case PackCategoriesIntoKey(fcInfinity, fcNaN):
Dale Johannesen3cf889f2007-08-31 04:03:46 +00001370 category = fcNaN;
1371 copySignificand(rhs);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001372 return opOK;
1373
Michael Gottesman9b877e12013-06-24 09:57:57 +00001374 case PackCategoriesIntoKey(fcNormal, fcInfinity):
1375 case PackCategoriesIntoKey(fcZero, fcInfinity):
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001376 category = fcInfinity;
1377 sign = rhs.sign ^ subtract;
1378 return opOK;
1379
Michael Gottesman9b877e12013-06-24 09:57:57 +00001380 case PackCategoriesIntoKey(fcZero, fcNormal):
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001381 assign(rhs);
1382 sign = rhs.sign ^ subtract;
1383 return opOK;
1384
Michael Gottesman9b877e12013-06-24 09:57:57 +00001385 case PackCategoriesIntoKey(fcZero, fcZero):
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001386 /* Sign depends on rounding mode; handled by caller. */
1387 return opOK;
1388
Michael Gottesman9b877e12013-06-24 09:57:57 +00001389 case PackCategoriesIntoKey(fcInfinity, fcInfinity):
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001390 /* Differently signed infinities can only be validly
1391 subtracted. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001392 if (((sign ^ rhs.sign)!=0) != subtract) {
Neil Booth5fe658b2007-10-14 10:39:51 +00001393 makeNaN();
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001394 return opInvalidOp;
1395 }
1396
1397 return opOK;
1398
Michael Gottesman9b877e12013-06-24 09:57:57 +00001399 case PackCategoriesIntoKey(fcNormal, fcNormal):
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001400 return opDivByZero;
1401 }
1402}
1403
1404/* Add or subtract two normal numbers. */
1405lostFraction
1406APFloat::addOrSubtractSignificand(const APFloat &rhs, bool subtract)
1407{
1408 integerPart carry;
1409 lostFraction lost_fraction;
1410 int bits;
1411
1412 /* Determine if the operation on the absolute values is effectively
1413 an addition or subtraction. */
Hartmut Kaiserfc69d322007-10-25 23:15:31 +00001414 subtract ^= (sign ^ rhs.sign) ? true : false;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001415
1416 /* Are we bigger exponent-wise than the RHS? */
1417 bits = exponent - rhs.exponent;
1418
1419 /* Subtraction is more subtle than one might naively expect. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001420 if (subtract) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001421 APFloat temp_rhs(rhs);
1422 bool reverse;
1423
Chris Lattner3da18eb2007-08-24 03:02:34 +00001424 if (bits == 0) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001425 reverse = compareAbsoluteValue(temp_rhs) == cmpLessThan;
1426 lost_fraction = lfExactlyZero;
Chris Lattner3da18eb2007-08-24 03:02:34 +00001427 } else if (bits > 0) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001428 lost_fraction = temp_rhs.shiftSignificandRight(bits - 1);
1429 shiftSignificandLeft(1);
1430 reverse = false;
Chris Lattner3da18eb2007-08-24 03:02:34 +00001431 } else {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001432 lost_fraction = shiftSignificandRight(-bits - 1);
1433 temp_rhs.shiftSignificandLeft(1);
1434 reverse = true;
1435 }
1436
Chris Lattner3da18eb2007-08-24 03:02:34 +00001437 if (reverse) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001438 carry = temp_rhs.subtractSignificand
Neil Booth9acbf5a2007-09-26 21:33:42 +00001439 (*this, lost_fraction != lfExactlyZero);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001440 copySignificand(temp_rhs);
1441 sign = !sign;
1442 } else {
1443 carry = subtractSignificand
Neil Booth9acbf5a2007-09-26 21:33:42 +00001444 (temp_rhs, lost_fraction != lfExactlyZero);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001445 }
1446
1447 /* Invert the lost fraction - it was on the RHS and
1448 subtracted. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001449 if (lost_fraction == lfLessThanHalf)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001450 lost_fraction = lfMoreThanHalf;
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001451 else if (lost_fraction == lfMoreThanHalf)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001452 lost_fraction = lfLessThanHalf;
1453
1454 /* The code above is intended to ensure that no borrow is
1455 necessary. */
1456 assert(!carry);
Duncan Sandsa41634e2011-08-12 14:54:45 +00001457 (void)carry;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001458 } else {
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001459 if (bits > 0) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001460 APFloat temp_rhs(rhs);
1461
1462 lost_fraction = temp_rhs.shiftSignificandRight(bits);
1463 carry = addSignificand(temp_rhs);
1464 } else {
1465 lost_fraction = shiftSignificandRight(-bits);
1466 carry = addSignificand(rhs);
1467 }
1468
1469 /* We have a guard bit; generating a carry cannot happen. */
1470 assert(!carry);
Duncan Sandsa41634e2011-08-12 14:54:45 +00001471 (void)carry;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001472 }
1473
1474 return lost_fraction;
1475}
1476
1477APFloat::opStatus
1478APFloat::multiplySpecials(const APFloat &rhs)
1479{
Michael Gottesman9b877e12013-06-24 09:57:57 +00001480 switch (PackCategoriesIntoKey(category, rhs.category)) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001481 default:
Torok Edwinfbcc6632009-07-14 16:55:14 +00001482 llvm_unreachable(0);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001483
Michael Gottesman9b877e12013-06-24 09:57:57 +00001484 case PackCategoriesIntoKey(fcNaN, fcZero):
1485 case PackCategoriesIntoKey(fcNaN, fcNormal):
1486 case PackCategoriesIntoKey(fcNaN, fcInfinity):
1487 case PackCategoriesIntoKey(fcNaN, fcNaN):
Dale Johannesen3cf889f2007-08-31 04:03:46 +00001488 return opOK;
1489
Michael Gottesman9b877e12013-06-24 09:57:57 +00001490 case PackCategoriesIntoKey(fcZero, fcNaN):
1491 case PackCategoriesIntoKey(fcNormal, fcNaN):
1492 case PackCategoriesIntoKey(fcInfinity, fcNaN):
Dale Johannesen3cf889f2007-08-31 04:03:46 +00001493 category = fcNaN;
1494 copySignificand(rhs);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001495 return opOK;
1496
Michael Gottesman9b877e12013-06-24 09:57:57 +00001497 case PackCategoriesIntoKey(fcNormal, fcInfinity):
1498 case PackCategoriesIntoKey(fcInfinity, fcNormal):
1499 case PackCategoriesIntoKey(fcInfinity, fcInfinity):
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001500 category = fcInfinity;
1501 return opOK;
1502
Michael Gottesman9b877e12013-06-24 09:57:57 +00001503 case PackCategoriesIntoKey(fcZero, fcNormal):
1504 case PackCategoriesIntoKey(fcNormal, fcZero):
1505 case PackCategoriesIntoKey(fcZero, fcZero):
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001506 category = fcZero;
1507 return opOK;
1508
Michael Gottesman9b877e12013-06-24 09:57:57 +00001509 case PackCategoriesIntoKey(fcZero, fcInfinity):
1510 case PackCategoriesIntoKey(fcInfinity, fcZero):
Neil Booth5fe658b2007-10-14 10:39:51 +00001511 makeNaN();
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001512 return opInvalidOp;
1513
Michael Gottesman9b877e12013-06-24 09:57:57 +00001514 case PackCategoriesIntoKey(fcNormal, fcNormal):
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001515 return opOK;
1516 }
1517}
1518
1519APFloat::opStatus
1520APFloat::divideSpecials(const APFloat &rhs)
1521{
Michael Gottesman9b877e12013-06-24 09:57:57 +00001522 switch (PackCategoriesIntoKey(category, rhs.category)) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001523 default:
Torok Edwinfbcc6632009-07-14 16:55:14 +00001524 llvm_unreachable(0);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001525
Michael Gottesman9b877e12013-06-24 09:57:57 +00001526 case PackCategoriesIntoKey(fcNaN, fcZero):
1527 case PackCategoriesIntoKey(fcNaN, fcNormal):
1528 case PackCategoriesIntoKey(fcNaN, fcInfinity):
1529 case PackCategoriesIntoKey(fcNaN, fcNaN):
1530 case PackCategoriesIntoKey(fcInfinity, fcZero):
1531 case PackCategoriesIntoKey(fcInfinity, fcNormal):
1532 case PackCategoriesIntoKey(fcZero, fcInfinity):
1533 case PackCategoriesIntoKey(fcZero, fcNormal):
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001534 return opOK;
1535
Michael Gottesman9b877e12013-06-24 09:57:57 +00001536 case PackCategoriesIntoKey(fcZero, fcNaN):
1537 case PackCategoriesIntoKey(fcNormal, fcNaN):
1538 case PackCategoriesIntoKey(fcInfinity, fcNaN):
Dale Johannesen3cf889f2007-08-31 04:03:46 +00001539 category = fcNaN;
1540 copySignificand(rhs);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001541 return opOK;
1542
Michael Gottesman9b877e12013-06-24 09:57:57 +00001543 case PackCategoriesIntoKey(fcNormal, fcInfinity):
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001544 category = fcZero;
1545 return opOK;
1546
Michael Gottesman9b877e12013-06-24 09:57:57 +00001547 case PackCategoriesIntoKey(fcNormal, fcZero):
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001548 category = fcInfinity;
1549 return opDivByZero;
1550
Michael Gottesman9b877e12013-06-24 09:57:57 +00001551 case PackCategoriesIntoKey(fcInfinity, fcInfinity):
1552 case PackCategoriesIntoKey(fcZero, fcZero):
Neil Booth5fe658b2007-10-14 10:39:51 +00001553 makeNaN();
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001554 return opInvalidOp;
1555
Michael Gottesman9b877e12013-06-24 09:57:57 +00001556 case PackCategoriesIntoKey(fcNormal, fcNormal):
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001557 return opOK;
1558 }
1559}
1560
Dale Johannesenb5721632009-01-21 00:35:19 +00001561APFloat::opStatus
1562APFloat::modSpecials(const APFloat &rhs)
1563{
Michael Gottesman9b877e12013-06-24 09:57:57 +00001564 switch (PackCategoriesIntoKey(category, rhs.category)) {
Dale Johannesenb5721632009-01-21 00:35:19 +00001565 default:
Torok Edwinfbcc6632009-07-14 16:55:14 +00001566 llvm_unreachable(0);
Dale Johannesenb5721632009-01-21 00:35:19 +00001567
Michael Gottesman9b877e12013-06-24 09:57:57 +00001568 case PackCategoriesIntoKey(fcNaN, fcZero):
1569 case PackCategoriesIntoKey(fcNaN, fcNormal):
1570 case PackCategoriesIntoKey(fcNaN, fcInfinity):
1571 case PackCategoriesIntoKey(fcNaN, fcNaN):
1572 case PackCategoriesIntoKey(fcZero, fcInfinity):
1573 case PackCategoriesIntoKey(fcZero, fcNormal):
1574 case PackCategoriesIntoKey(fcNormal, fcInfinity):
Dale Johannesenb5721632009-01-21 00:35:19 +00001575 return opOK;
1576
Michael Gottesman9b877e12013-06-24 09:57:57 +00001577 case PackCategoriesIntoKey(fcZero, fcNaN):
1578 case PackCategoriesIntoKey(fcNormal, fcNaN):
1579 case PackCategoriesIntoKey(fcInfinity, fcNaN):
Dale Johannesenb5721632009-01-21 00:35:19 +00001580 category = fcNaN;
1581 copySignificand(rhs);
1582 return opOK;
1583
Michael Gottesman9b877e12013-06-24 09:57:57 +00001584 case PackCategoriesIntoKey(fcNormal, fcZero):
1585 case PackCategoriesIntoKey(fcInfinity, fcZero):
1586 case PackCategoriesIntoKey(fcInfinity, fcNormal):
1587 case PackCategoriesIntoKey(fcInfinity, fcInfinity):
1588 case PackCategoriesIntoKey(fcZero, fcZero):
Dale Johannesenb5721632009-01-21 00:35:19 +00001589 makeNaN();
1590 return opInvalidOp;
1591
Michael Gottesman9b877e12013-06-24 09:57:57 +00001592 case PackCategoriesIntoKey(fcNormal, fcNormal):
Dale Johannesenb5721632009-01-21 00:35:19 +00001593 return opOK;
1594 }
1595}
1596
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001597/* Change sign. */
1598void
1599APFloat::changeSign()
1600{
1601 /* Look mummy, this one's easy. */
1602 sign = !sign;
1603}
1604
Dale Johannesen689d17d2007-08-31 23:35:31 +00001605void
1606APFloat::clearSign()
1607{
1608 /* So is this one. */
1609 sign = 0;
1610}
1611
1612void
1613APFloat::copySign(const APFloat &rhs)
1614{
1615 /* And this one. */
1616 sign = rhs.sign;
1617}
1618
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001619/* Normalized addition or subtraction. */
1620APFloat::opStatus
1621APFloat::addOrSubtract(const APFloat &rhs, roundingMode rounding_mode,
Neil Booth9acbf5a2007-09-26 21:33:42 +00001622 bool subtract)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001623{
1624 opStatus fs;
1625
1626 fs = addOrSubtractSpecials(rhs, subtract);
1627
1628 /* This return code means it was not a simple case. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001629 if (fs == opDivByZero) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001630 lostFraction lost_fraction;
1631
1632 lost_fraction = addOrSubtractSignificand(rhs, subtract);
1633 fs = normalize(rounding_mode, lost_fraction);
1634
1635 /* Can only be zero if we lost no fraction. */
1636 assert(category != fcZero || lost_fraction == lfExactlyZero);
1637 }
1638
1639 /* If two numbers add (exactly) to zero, IEEE 754 decrees it is a
1640 positive zero unless rounding to minus infinity, except that
1641 adding two like-signed zeroes gives that zero. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001642 if (category == fcZero) {
1643 if (rhs.category != fcZero || (sign == rhs.sign) == subtract)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001644 sign = (rounding_mode == rmTowardNegative);
1645 }
1646
1647 return fs;
1648}
1649
1650/* Normalized addition. */
1651APFloat::opStatus
1652APFloat::add(const APFloat &rhs, roundingMode rounding_mode)
1653{
1654 return addOrSubtract(rhs, rounding_mode, false);
1655}
1656
1657/* Normalized subtraction. */
1658APFloat::opStatus
1659APFloat::subtract(const APFloat &rhs, roundingMode rounding_mode)
1660{
1661 return addOrSubtract(rhs, rounding_mode, true);
1662}
1663
1664/* Normalized multiply. */
1665APFloat::opStatus
1666APFloat::multiply(const APFloat &rhs, roundingMode rounding_mode)
1667{
1668 opStatus fs;
1669
1670 sign ^= rhs.sign;
1671 fs = multiplySpecials(rhs);
1672
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001673 if (category == fcNormal) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001674 lostFraction lost_fraction = multiplySignificand(rhs, 0);
1675 fs = normalize(rounding_mode, lost_fraction);
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001676 if (lost_fraction != lfExactlyZero)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001677 fs = (opStatus) (fs | opInexact);
1678 }
1679
1680 return fs;
1681}
1682
1683/* Normalized divide. */
1684APFloat::opStatus
1685APFloat::divide(const APFloat &rhs, roundingMode rounding_mode)
1686{
1687 opStatus fs;
1688
1689 sign ^= rhs.sign;
1690 fs = divideSpecials(rhs);
1691
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001692 if (category == fcNormal) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001693 lostFraction lost_fraction = divideSignificand(rhs);
1694 fs = normalize(rounding_mode, lost_fraction);
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001695 if (lost_fraction != lfExactlyZero)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001696 fs = (opStatus) (fs | opInexact);
1697 }
1698
1699 return fs;
1700}
1701
Dale Johannesenfe750172009-01-20 18:35:05 +00001702/* Normalized remainder. This is not currently correct in all cases. */
1703APFloat::opStatus
1704APFloat::remainder(const APFloat &rhs)
1705{
1706 opStatus fs;
1707 APFloat V = *this;
1708 unsigned int origSign = sign;
1709
Dale Johannesenfe750172009-01-20 18:35:05 +00001710 fs = V.divide(rhs, rmNearestTiesToEven);
1711 if (fs == opDivByZero)
1712 return fs;
1713
1714 int parts = partCount();
1715 integerPart *x = new integerPart[parts];
1716 bool ignored;
1717 fs = V.convertToInteger(x, parts * integerPartWidth, true,
1718 rmNearestTiesToEven, &ignored);
1719 if (fs==opInvalidOp)
1720 return fs;
1721
1722 fs = V.convertFromZeroExtendedInteger(x, parts * integerPartWidth, true,
1723 rmNearestTiesToEven);
1724 assert(fs==opOK); // should always work
1725
1726 fs = V.multiply(rhs, rmNearestTiesToEven);
1727 assert(fs==opOK || fs==opInexact); // should not overflow or underflow
1728
1729 fs = subtract(V, rmNearestTiesToEven);
1730 assert(fs==opOK || fs==opInexact); // likewise
1731
1732 if (isZero())
1733 sign = origSign; // IEEE754 requires this
1734 delete[] x;
1735 return fs;
1736}
1737
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001738/* Normalized llvm frem (C fmod).
Dale Johannesenfe750172009-01-20 18:35:05 +00001739 This is not currently correct in all cases. */
Dale Johannesen689d17d2007-08-31 23:35:31 +00001740APFloat::opStatus
1741APFloat::mod(const APFloat &rhs, roundingMode rounding_mode)
1742{
1743 opStatus fs;
Dale Johannesenb5721632009-01-21 00:35:19 +00001744 fs = modSpecials(rhs);
Dale Johannesen689d17d2007-08-31 23:35:31 +00001745
Dale Johannesenb5721632009-01-21 00:35:19 +00001746 if (category == fcNormal && rhs.category == fcNormal) {
1747 APFloat V = *this;
1748 unsigned int origSign = sign;
Dale Johannesen689d17d2007-08-31 23:35:31 +00001749
Dale Johannesenb5721632009-01-21 00:35:19 +00001750 fs = V.divide(rhs, rmNearestTiesToEven);
1751 if (fs == opDivByZero)
1752 return fs;
Dale Johannesen728687c2007-09-05 20:39:49 +00001753
Dale Johannesenb5721632009-01-21 00:35:19 +00001754 int parts = partCount();
1755 integerPart *x = new integerPart[parts];
1756 bool ignored;
1757 fs = V.convertToInteger(x, parts * integerPartWidth, true,
1758 rmTowardZero, &ignored);
1759 if (fs==opInvalidOp)
1760 return fs;
Dale Johannesen728687c2007-09-05 20:39:49 +00001761
Dale Johannesenb5721632009-01-21 00:35:19 +00001762 fs = V.convertFromZeroExtendedInteger(x, parts * integerPartWidth, true,
1763 rmNearestTiesToEven);
1764 assert(fs==opOK); // should always work
Dale Johannesen728687c2007-09-05 20:39:49 +00001765
Dale Johannesenb5721632009-01-21 00:35:19 +00001766 fs = V.multiply(rhs, rounding_mode);
1767 assert(fs==opOK || fs==opInexact); // should not overflow or underflow
1768
1769 fs = subtract(V, rounding_mode);
1770 assert(fs==opOK || fs==opInexact); // likewise
1771
1772 if (isZero())
1773 sign = origSign; // IEEE754 requires this
1774 delete[] x;
1775 }
Dale Johannesen689d17d2007-08-31 23:35:31 +00001776 return fs;
1777}
1778
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001779/* Normalized fused-multiply-add. */
1780APFloat::opStatus
1781APFloat::fusedMultiplyAdd(const APFloat &multiplicand,
Neil Booth9acbf5a2007-09-26 21:33:42 +00001782 const APFloat &addend,
1783 roundingMode rounding_mode)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001784{
1785 opStatus fs;
1786
1787 /* Post-multiplication sign, before addition. */
1788 sign ^= multiplicand.sign;
1789
1790 /* If and only if all arguments are normal do we need to do an
1791 extended-precision calculation. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001792 if (category == fcNormal &&
1793 multiplicand.category == fcNormal &&
1794 addend.category == fcNormal) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001795 lostFraction lost_fraction;
1796
1797 lost_fraction = multiplySignificand(multiplicand, &addend);
1798 fs = normalize(rounding_mode, lost_fraction);
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001799 if (lost_fraction != lfExactlyZero)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001800 fs = (opStatus) (fs | opInexact);
1801
1802 /* If two numbers add (exactly) to zero, IEEE 754 decrees it is a
1803 positive zero unless rounding to minus infinity, except that
1804 adding two like-signed zeroes gives that zero. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001805 if (category == fcZero && sign != addend.sign)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001806 sign = (rounding_mode == rmTowardNegative);
1807 } else {
1808 fs = multiplySpecials(multiplicand);
1809
1810 /* FS can only be opOK or opInvalidOp. There is no more work
1811 to do in the latter case. The IEEE-754R standard says it is
1812 implementation-defined in this case whether, if ADDEND is a
Dale Johannesen3cf889f2007-08-31 04:03:46 +00001813 quiet NaN, we raise invalid op; this implementation does so.
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001814
1815 If we need to do the addition we can do so with normal
1816 precision. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001817 if (fs == opOK)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001818 fs = addOrSubtract(addend, rounding_mode, false);
1819 }
1820
1821 return fs;
1822}
1823
Owen Andersona40319b2012-08-13 23:32:49 +00001824/* Rounding-mode corrrect round to integral value. */
1825APFloat::opStatus APFloat::roundToIntegral(roundingMode rounding_mode) {
1826 opStatus fs;
Owen Andersona40319b2012-08-13 23:32:49 +00001827
Owen Anderson352dfff2012-08-15 18:28:45 +00001828 // If the exponent is large enough, we know that this value is already
1829 // integral, and the arithmetic below would potentially cause it to saturate
1830 // to +/-Inf. Bail out early instead.
Benjamin Kramerc38fab22012-09-26 14:06:58 +00001831 if (category == fcNormal && exponent+1 >= (int)semanticsPrecision(*semantics))
Owen Anderson352dfff2012-08-15 18:28:45 +00001832 return opOK;
1833
Owen Andersona40319b2012-08-13 23:32:49 +00001834 // The algorithm here is quite simple: we add 2^(p-1), where p is the
1835 // precision of our format, and then subtract it back off again. The choice
1836 // of rounding modes for the addition/subtraction determines the rounding mode
1837 // for our integral rounding as well.
Owen Andersonbe7e2972012-08-15 16:42:53 +00001838 // NOTE: When the input value is negative, we do subtraction followed by
Owen Anderson1ff74b02012-08-15 05:39:46 +00001839 // addition instead.
Owen Anderson0b357222012-08-14 18:51:15 +00001840 APInt IntegerConstant(NextPowerOf2(semanticsPrecision(*semantics)), 1);
1841 IntegerConstant <<= semanticsPrecision(*semantics)-1;
Owen Andersona40319b2012-08-13 23:32:49 +00001842 APFloat MagicConstant(*semantics);
1843 fs = MagicConstant.convertFromAPInt(IntegerConstant, false,
1844 rmNearestTiesToEven);
Owen Anderson1ff74b02012-08-15 05:39:46 +00001845 MagicConstant.copySign(*this);
1846
Owen Andersona40319b2012-08-13 23:32:49 +00001847 if (fs != opOK)
1848 return fs;
1849
Owen Anderson1ff74b02012-08-15 05:39:46 +00001850 // Preserve the input sign so that we can handle 0.0/-0.0 cases correctly.
1851 bool inputSign = isNegative();
1852
Owen Andersona40319b2012-08-13 23:32:49 +00001853 fs = add(MagicConstant, rounding_mode);
1854 if (fs != opOK && fs != opInexact)
1855 return fs;
1856
1857 fs = subtract(MagicConstant, rounding_mode);
Owen Anderson1ff74b02012-08-15 05:39:46 +00001858
1859 // Restore the input sign.
1860 if (inputSign != isNegative())
1861 changeSign();
1862
Owen Andersona40319b2012-08-13 23:32:49 +00001863 return fs;
1864}
1865
1866
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001867/* Comparison requires normalized numbers. */
1868APFloat::cmpResult
1869APFloat::compare(const APFloat &rhs) const
1870{
1871 cmpResult result;
1872
1873 assert(semantics == rhs.semantics);
1874
Michael Gottesman9b877e12013-06-24 09:57:57 +00001875 switch (PackCategoriesIntoKey(category, rhs.category)) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001876 default:
Torok Edwinfbcc6632009-07-14 16:55:14 +00001877 llvm_unreachable(0);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001878
Michael Gottesman9b877e12013-06-24 09:57:57 +00001879 case PackCategoriesIntoKey(fcNaN, fcZero):
1880 case PackCategoriesIntoKey(fcNaN, fcNormal):
1881 case PackCategoriesIntoKey(fcNaN, fcInfinity):
1882 case PackCategoriesIntoKey(fcNaN, fcNaN):
1883 case PackCategoriesIntoKey(fcZero, fcNaN):
1884 case PackCategoriesIntoKey(fcNormal, fcNaN):
1885 case PackCategoriesIntoKey(fcInfinity, fcNaN):
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001886 return cmpUnordered;
1887
Michael Gottesman9b877e12013-06-24 09:57:57 +00001888 case PackCategoriesIntoKey(fcInfinity, fcNormal):
1889 case PackCategoriesIntoKey(fcInfinity, fcZero):
1890 case PackCategoriesIntoKey(fcNormal, fcZero):
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001891 if (sign)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001892 return cmpLessThan;
1893 else
1894 return cmpGreaterThan;
1895
Michael Gottesman9b877e12013-06-24 09:57:57 +00001896 case PackCategoriesIntoKey(fcNormal, fcInfinity):
1897 case PackCategoriesIntoKey(fcZero, fcInfinity):
1898 case PackCategoriesIntoKey(fcZero, fcNormal):
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001899 if (rhs.sign)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001900 return cmpGreaterThan;
1901 else
1902 return cmpLessThan;
1903
Michael Gottesman9b877e12013-06-24 09:57:57 +00001904 case PackCategoriesIntoKey(fcInfinity, fcInfinity):
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001905 if (sign == rhs.sign)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001906 return cmpEqual;
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001907 else if (sign)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001908 return cmpLessThan;
1909 else
1910 return cmpGreaterThan;
1911
Michael Gottesman9b877e12013-06-24 09:57:57 +00001912 case PackCategoriesIntoKey(fcZero, fcZero):
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001913 return cmpEqual;
1914
Michael Gottesman9b877e12013-06-24 09:57:57 +00001915 case PackCategoriesIntoKey(fcNormal, fcNormal):
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001916 break;
1917 }
1918
1919 /* Two normal numbers. Do they have the same sign? */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001920 if (sign != rhs.sign) {
1921 if (sign)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001922 result = cmpLessThan;
1923 else
1924 result = cmpGreaterThan;
1925 } else {
1926 /* Compare absolute values; invert result if negative. */
1927 result = compareAbsoluteValue(rhs);
1928
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001929 if (sign) {
1930 if (result == cmpLessThan)
Neil Booth9acbf5a2007-09-26 21:33:42 +00001931 result = cmpGreaterThan;
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001932 else if (result == cmpGreaterThan)
Neil Booth9acbf5a2007-09-26 21:33:42 +00001933 result = cmpLessThan;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001934 }
1935 }
1936
1937 return result;
1938}
1939
Dale Johannesen4f0bd682008-10-09 23:00:39 +00001940/// APFloat::convert - convert a value of one floating point type to another.
1941/// The return value corresponds to the IEEE754 exceptions. *losesInfo
1942/// records whether the transformation lost information, i.e. whether
1943/// converting the result back to the original type will produce the
1944/// original value (this is almost the same as return value==fsOK, but there
1945/// are edge cases where this is not so).
1946
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001947APFloat::opStatus
1948APFloat::convert(const fltSemantics &toSemantics,
Dale Johannesen4f0bd682008-10-09 23:00:39 +00001949 roundingMode rounding_mode, bool *losesInfo)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001950{
Neil Bootha8d72692007-09-22 02:56:19 +00001951 lostFraction lostFraction;
1952 unsigned int newPartCount, oldPartCount;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001953 opStatus fs;
Eli Friedmana84ad7d2011-11-26 03:38:02 +00001954 int shift;
1955 const fltSemantics &fromSemantics = *semantics;
Neil Booth9acbf5a2007-09-26 21:33:42 +00001956
Neil Bootha8d72692007-09-22 02:56:19 +00001957 lostFraction = lfExactlyZero;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001958 newPartCount = partCountForBits(toSemantics.precision + 1);
Neil Bootha8d72692007-09-22 02:56:19 +00001959 oldPartCount = partCount();
Eli Friedmana84ad7d2011-11-26 03:38:02 +00001960 shift = toSemantics.precision - fromSemantics.precision;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001961
Eli Friedmana84ad7d2011-11-26 03:38:02 +00001962 bool X86SpecialNan = false;
1963 if (&fromSemantics == &APFloat::x87DoubleExtended &&
1964 &toSemantics != &APFloat::x87DoubleExtended && category == fcNaN &&
1965 (!(*significandParts() & 0x8000000000000000ULL) ||
1966 !(*significandParts() & 0x4000000000000000ULL))) {
1967 // x86 has some unusual NaNs which cannot be represented in any other
1968 // format; note them here.
1969 X86SpecialNan = true;
1970 }
1971
1972 // If this is a truncation, perform the shift before we narrow the storage.
1973 if (shift < 0 && (category==fcNormal || category==fcNaN))
1974 lostFraction = shiftRight(significandParts(), oldPartCount, -shift);
1975
1976 // Fix the storage so it can hold to new value.
Neil Bootha8d72692007-09-22 02:56:19 +00001977 if (newPartCount > oldPartCount) {
Eli Friedmana84ad7d2011-11-26 03:38:02 +00001978 // The new type requires more storage; make it available.
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001979 integerPart *newParts;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001980 newParts = new integerPart[newPartCount];
1981 APInt::tcSet(newParts, 0, newPartCount);
Dale Johannesen4f55d9f2007-09-25 17:25:00 +00001982 if (category==fcNormal || category==fcNaN)
1983 APInt::tcAssign(newParts, significandParts(), oldPartCount);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001984 freeSignificand();
1985 significand.parts = newParts;
Eli Friedmana84ad7d2011-11-26 03:38:02 +00001986 } else if (newPartCount == 1 && oldPartCount != 1) {
1987 // Switch to built-in storage for a single part.
1988 integerPart newPart = 0;
1989 if (category==fcNormal || category==fcNaN)
1990 newPart = significandParts()[0];
1991 freeSignificand();
1992 significand.part = newPart;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001993 }
1994
Eli Friedmana84ad7d2011-11-26 03:38:02 +00001995 // Now that we have the right storage, switch the semantics.
1996 semantics = &toSemantics;
1997
1998 // If this is an extension, perform the shift now that the storage is
1999 // available.
2000 if (shift > 0 && (category==fcNormal || category==fcNaN))
2001 APInt::tcShiftLeft(significandParts(), newPartCount, shift);
2002
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002003 if (category == fcNormal) {
Neil Bootha8d72692007-09-22 02:56:19 +00002004 fs = normalize(rounding_mode, lostFraction);
Dale Johannesen4f0bd682008-10-09 23:00:39 +00002005 *losesInfo = (fs != opOK);
Dale Johannesen4f55d9f2007-09-25 17:25:00 +00002006 } else if (category == fcNaN) {
Eli Friedmana84ad7d2011-11-26 03:38:02 +00002007 *losesInfo = lostFraction != lfExactlyZero || X86SpecialNan;
Benjamin Kramerb361adb2013-01-25 17:01:00 +00002008
2009 // For x87 extended precision, we want to make a NaN, not a special NaN if
2010 // the input wasn't special either.
2011 if (!X86SpecialNan && semantics == &APFloat::x87DoubleExtended)
2012 APInt::tcSetBit(significandParts(), semantics->precision - 1);
2013
Dale Johannesen4f55d9f2007-09-25 17:25:00 +00002014 // gcc forces the Quiet bit on, which means (float)(double)(float_sNan)
2015 // does not give you back the same bits. This is dubious, and we
2016 // don't currently do it. You're really supposed to get
2017 // an invalid operation signal at runtime, but nobody does that.
Dale Johannesen4f0bd682008-10-09 23:00:39 +00002018 fs = opOK;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002019 } else {
Dale Johannesen4f0bd682008-10-09 23:00:39 +00002020 *losesInfo = false;
Eli Friedman31f01162011-11-28 18:50:37 +00002021 fs = opOK;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002022 }
2023
2024 return fs;
2025}
2026
2027/* Convert a floating point number to an integer according to the
2028 rounding mode. If the rounded integer value is out of range this
Neil Booth618d0fc2007-11-01 22:43:37 +00002029 returns an invalid operation exception and the contents of the
2030 destination parts are unspecified. If the rounded value is in
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002031 range but the floating point number is not the exact integer, the C
2032 standard doesn't require an inexact exception to be raised. IEEE
2033 854 does require it so we do that.
2034
2035 Note that for conversions to integer type the C standard requires
2036 round-to-zero to always be used. */
2037APFloat::opStatus
Neil Booth618d0fc2007-11-01 22:43:37 +00002038APFloat::convertToSignExtendedInteger(integerPart *parts, unsigned int width,
2039 bool isSigned,
Dale Johannesen4f0bd682008-10-09 23:00:39 +00002040 roundingMode rounding_mode,
2041 bool *isExact) const
Neil Booth618d0fc2007-11-01 22:43:37 +00002042{
2043 lostFraction lost_fraction;
2044 const integerPart *src;
2045 unsigned int dstPartsCount, truncatedBits;
2046
Dale Johannesen4f0bd682008-10-09 23:00:39 +00002047 *isExact = false;
2048
Neil Booth618d0fc2007-11-01 22:43:37 +00002049 /* Handle the three special cases first. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002050 if (category == fcInfinity || category == fcNaN)
Neil Booth618d0fc2007-11-01 22:43:37 +00002051 return opInvalidOp;
2052
2053 dstPartsCount = partCountForBits(width);
2054
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002055 if (category == fcZero) {
Neil Booth618d0fc2007-11-01 22:43:37 +00002056 APInt::tcSet(parts, 0, dstPartsCount);
Dale Johannesen7221af32008-10-07 00:40:01 +00002057 // Negative zero can't be represented as an int.
Dale Johannesen4f0bd682008-10-09 23:00:39 +00002058 *isExact = !sign;
2059 return opOK;
Neil Booth618d0fc2007-11-01 22:43:37 +00002060 }
2061
2062 src = significandParts();
2063
2064 /* Step 1: place our absolute value, with any fraction truncated, in
2065 the destination. */
2066 if (exponent < 0) {
2067 /* Our absolute value is less than one; truncate everything. */
2068 APInt::tcSet(parts, 0, dstPartsCount);
Dale Johannesen740e9872009-01-19 21:17:05 +00002069 /* For exponent -1 the integer bit represents .5, look at that.
2070 For smaller exponents leftmost truncated bit is 0. */
2071 truncatedBits = semantics->precision -1U - exponent;
Neil Booth618d0fc2007-11-01 22:43:37 +00002072 } else {
2073 /* We want the most significant (exponent + 1) bits; the rest are
2074 truncated. */
2075 unsigned int bits = exponent + 1U;
2076
2077 /* Hopelessly large in magnitude? */
2078 if (bits > width)
2079 return opInvalidOp;
2080
2081 if (bits < semantics->precision) {
2082 /* We truncate (semantics->precision - bits) bits. */
2083 truncatedBits = semantics->precision - bits;
2084 APInt::tcExtract(parts, dstPartsCount, src, bits, truncatedBits);
2085 } else {
2086 /* We want at least as many bits as are available. */
2087 APInt::tcExtract(parts, dstPartsCount, src, semantics->precision, 0);
2088 APInt::tcShiftLeft(parts, dstPartsCount, bits - semantics->precision);
2089 truncatedBits = 0;
2090 }
2091 }
2092
2093 /* Step 2: work out any lost fraction, and increment the absolute
2094 value if we would round away from zero. */
2095 if (truncatedBits) {
2096 lost_fraction = lostFractionThroughTruncation(src, partCount(),
2097 truncatedBits);
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002098 if (lost_fraction != lfExactlyZero &&
2099 roundAwayFromZero(rounding_mode, lost_fraction, truncatedBits)) {
Neil Booth618d0fc2007-11-01 22:43:37 +00002100 if (APInt::tcIncrement(parts, dstPartsCount))
2101 return opInvalidOp; /* Overflow. */
2102 }
2103 } else {
2104 lost_fraction = lfExactlyZero;
2105 }
2106
2107 /* Step 3: check if we fit in the destination. */
2108 unsigned int omsb = APInt::tcMSB(parts, dstPartsCount) + 1;
2109
2110 if (sign) {
2111 if (!isSigned) {
2112 /* Negative numbers cannot be represented as unsigned. */
2113 if (omsb != 0)
2114 return opInvalidOp;
2115 } else {
2116 /* It takes omsb bits to represent the unsigned integer value.
2117 We lose a bit for the sign, but care is needed as the
2118 maximally negative integer is a special case. */
2119 if (omsb == width && APInt::tcLSB(parts, dstPartsCount) + 1 != omsb)
2120 return opInvalidOp;
2121
2122 /* This case can happen because of rounding. */
2123 if (omsb > width)
2124 return opInvalidOp;
2125 }
2126
2127 APInt::tcNegate (parts, dstPartsCount);
2128 } else {
2129 if (omsb >= width + !isSigned)
2130 return opInvalidOp;
2131 }
2132
Dale Johannesen4f0bd682008-10-09 23:00:39 +00002133 if (lost_fraction == lfExactlyZero) {
2134 *isExact = true;
Neil Booth618d0fc2007-11-01 22:43:37 +00002135 return opOK;
Dale Johannesen4f0bd682008-10-09 23:00:39 +00002136 } else
Neil Booth618d0fc2007-11-01 22:43:37 +00002137 return opInexact;
2138}
2139
2140/* Same as convertToSignExtendedInteger, except we provide
2141 deterministic values in case of an invalid operation exception,
2142 namely zero for NaNs and the minimal or maximal value respectively
Dale Johannesen4f0bd682008-10-09 23:00:39 +00002143 for underflow or overflow.
2144 The *isExact output tells whether the result is exact, in the sense
2145 that converting it back to the original floating point type produces
2146 the original value. This is almost equivalent to result==opOK,
2147 except for negative zeroes.
2148*/
Neil Booth618d0fc2007-11-01 22:43:37 +00002149APFloat::opStatus
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002150APFloat::convertToInteger(integerPart *parts, unsigned int width,
Neil Booth9acbf5a2007-09-26 21:33:42 +00002151 bool isSigned,
Dale Johannesen4f0bd682008-10-09 23:00:39 +00002152 roundingMode rounding_mode, bool *isExact) const
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002153{
Neil Booth618d0fc2007-11-01 22:43:37 +00002154 opStatus fs;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002155
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002156 fs = convertToSignExtendedInteger(parts, width, isSigned, rounding_mode,
Dale Johannesen4f0bd682008-10-09 23:00:39 +00002157 isExact);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002158
Neil Booth618d0fc2007-11-01 22:43:37 +00002159 if (fs == opInvalidOp) {
2160 unsigned int bits, dstPartsCount;
2161
2162 dstPartsCount = partCountForBits(width);
2163
2164 if (category == fcNaN)
2165 bits = 0;
2166 else if (sign)
2167 bits = isSigned;
2168 else
2169 bits = width - isSigned;
2170
2171 APInt::tcSetLeastSignificantBits(parts, dstPartsCount, bits);
2172 if (sign && isSigned)
2173 APInt::tcShiftLeft(parts, dstPartsCount, width - 1);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002174 }
2175
Neil Booth618d0fc2007-11-01 22:43:37 +00002176 return fs;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002177}
2178
Jeffrey Yasskin03b81a22011-07-15 07:04:56 +00002179/* Same as convertToInteger(integerPart*, ...), except the result is returned in
2180 an APSInt, whose initial bit-width and signed-ness are used to determine the
2181 precision of the conversion.
2182 */
2183APFloat::opStatus
2184APFloat::convertToInteger(APSInt &result,
2185 roundingMode rounding_mode, bool *isExact) const
2186{
2187 unsigned bitWidth = result.getBitWidth();
2188 SmallVector<uint64_t, 4> parts(result.getNumWords());
2189 opStatus status = convertToInteger(
2190 parts.data(), bitWidth, result.isSigned(), rounding_mode, isExact);
2191 // Keeps the original signed-ness.
Jeffrey Yasskin7a162882011-07-18 21:45:40 +00002192 result = APInt(bitWidth, parts);
Jeffrey Yasskin03b81a22011-07-15 07:04:56 +00002193 return status;
2194}
2195
Neil Booth6c1c8582007-10-07 12:07:53 +00002196/* Convert an unsigned integer SRC to a floating point number,
2197 rounding according to ROUNDING_MODE. The sign of the floating
2198 point number is not modified. */
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002199APFloat::opStatus
Neil Booth6c1c8582007-10-07 12:07:53 +00002200APFloat::convertFromUnsignedParts(const integerPart *src,
2201 unsigned int srcCount,
2202 roundingMode rounding_mode)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002203{
Neil Booth49c6aab2007-10-08 14:39:42 +00002204 unsigned int omsb, precision, dstCount;
Neil Booth6c1c8582007-10-07 12:07:53 +00002205 integerPart *dst;
Neil Booth49c6aab2007-10-08 14:39:42 +00002206 lostFraction lost_fraction;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002207
2208 category = fcNormal;
Neil Booth49c6aab2007-10-08 14:39:42 +00002209 omsb = APInt::tcMSB(src, srcCount) + 1;
Neil Booth6c1c8582007-10-07 12:07:53 +00002210 dst = significandParts();
2211 dstCount = partCount();
Neil Booth49c6aab2007-10-08 14:39:42 +00002212 precision = semantics->precision;
Neil Booth6c1c8582007-10-07 12:07:53 +00002213
Nick Lewyckyf66daac2011-10-03 21:30:08 +00002214 /* We want the most significant PRECISION bits of SRC. There may not
Neil Booth49c6aab2007-10-08 14:39:42 +00002215 be that many; extract what we can. */
2216 if (precision <= omsb) {
2217 exponent = omsb - 1;
Neil Booth6c1c8582007-10-07 12:07:53 +00002218 lost_fraction = lostFractionThroughTruncation(src, srcCount,
Neil Booth49c6aab2007-10-08 14:39:42 +00002219 omsb - precision);
2220 APInt::tcExtract(dst, dstCount, src, precision, omsb - precision);
2221 } else {
2222 exponent = precision - 1;
2223 lost_fraction = lfExactlyZero;
2224 APInt::tcExtract(dst, dstCount, src, omsb, 0);
Neil Booth6c1c8582007-10-07 12:07:53 +00002225 }
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002226
2227 return normalize(rounding_mode, lost_fraction);
2228}
2229
Dan Gohman35723eb2008-02-29 01:26:11 +00002230APFloat::opStatus
2231APFloat::convertFromAPInt(const APInt &Val,
2232 bool isSigned,
2233 roundingMode rounding_mode)
2234{
2235 unsigned int partCount = Val.getNumWords();
2236 APInt api = Val;
2237
2238 sign = false;
2239 if (isSigned && api.isNegative()) {
2240 sign = true;
2241 api = -api;
2242 }
2243
2244 return convertFromUnsignedParts(api.getRawData(), partCount, rounding_mode);
2245}
2246
Neil Booth03f58ab2007-10-07 12:15:41 +00002247/* Convert a two's complement integer SRC to a floating point number,
2248 rounding according to ROUNDING_MODE. ISSIGNED is true if the
2249 integer is signed, in which case it must be sign-extended. */
2250APFloat::opStatus
2251APFloat::convertFromSignExtendedInteger(const integerPart *src,
2252 unsigned int srcCount,
2253 bool isSigned,
2254 roundingMode rounding_mode)
2255{
2256 opStatus status;
2257
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002258 if (isSigned &&
2259 APInt::tcExtractBit(src, srcCount * integerPartWidth - 1)) {
Neil Booth03f58ab2007-10-07 12:15:41 +00002260 integerPart *copy;
2261
2262 /* If we're signed and negative negate a copy. */
2263 sign = true;
2264 copy = new integerPart[srcCount];
2265 APInt::tcAssign(copy, src, srcCount);
2266 APInt::tcNegate(copy, srcCount);
2267 status = convertFromUnsignedParts(copy, srcCount, rounding_mode);
2268 delete [] copy;
2269 } else {
2270 sign = false;
2271 status = convertFromUnsignedParts(src, srcCount, rounding_mode);
2272 }
2273
2274 return status;
2275}
2276
Neil Booth5f009732007-10-07 11:45:55 +00002277/* FIXME: should this just take a const APInt reference? */
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002278APFloat::opStatus
Neil Booth5f009732007-10-07 11:45:55 +00002279APFloat::convertFromZeroExtendedInteger(const integerPart *parts,
2280 unsigned int width, bool isSigned,
2281 roundingMode rounding_mode)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002282{
Dale Johannesen42305122007-09-21 22:09:37 +00002283 unsigned int partCount = partCountForBits(width);
Jeffrey Yasskin7a162882011-07-18 21:45:40 +00002284 APInt api = APInt(width, makeArrayRef(parts, partCount));
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002285
2286 sign = false;
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002287 if (isSigned && APInt::tcExtractBit(parts, width - 1)) {
Dale Johannesen28a2c4a2007-09-30 18:17:01 +00002288 sign = true;
2289 api = -api;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002290 }
2291
Neil Boothba205222007-10-07 12:10:57 +00002292 return convertFromUnsignedParts(api.getRawData(), partCount, rounding_mode);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002293}
2294
2295APFloat::opStatus
Benjamin Kramer92d89982010-07-14 22:38:02 +00002296APFloat::convertFromHexadecimalString(StringRef s, roundingMode rounding_mode)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002297{
Erick Tryzelaara9680df2009-08-18 18:20:37 +00002298 lostFraction lost_fraction = lfExactlyZero;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002299 integerPart *significand;
2300 unsigned int bitPos, partsCount;
Erick Tryzelaar19f63b22009-08-16 23:36:19 +00002301 StringRef::iterator dot, firstSignificantDigit;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002302
2303 zeroSignificand();
2304 exponent = 0;
2305 category = fcNormal;
2306
2307 significand = significandParts();
2308 partsCount = partCount();
2309 bitPos = partsCount * integerPartWidth;
2310
Neil Boothd3985922007-10-07 08:51:21 +00002311 /* Skip leading zeroes and any (hexa)decimal point. */
Erick Tryzelaarda666c82009-08-20 23:30:43 +00002312 StringRef::iterator begin = s.begin();
2313 StringRef::iterator end = s.end();
2314 StringRef::iterator p = skipLeadingZeroesAndAnyDot(begin, end, &dot);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002315 firstSignificantDigit = p;
2316
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002317 for (; p != end;) {
Dale Johannesenfa483722008-05-14 22:53:25 +00002318 integerPart hex_value;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002319
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002320 if (*p == '.') {
Erick Tryzelaarda666c82009-08-20 23:30:43 +00002321 assert(dot == end && "String contains multiple dots");
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002322 dot = p++;
Erick Tryzelaarda666c82009-08-20 23:30:43 +00002323 if (p == end) {
2324 break;
2325 }
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002326 }
2327
2328 hex_value = hexDigitValue(*p);
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002329 if (hex_value == -1U) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002330 break;
2331 }
2332
2333 p++;
2334
Erick Tryzelaarda666c82009-08-20 23:30:43 +00002335 if (p == end) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002336 break;
Erick Tryzelaar19f63b22009-08-16 23:36:19 +00002337 } else {
2338 /* Store the number whilst 4-bit nibbles remain. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002339 if (bitPos) {
Erick Tryzelaar19f63b22009-08-16 23:36:19 +00002340 bitPos -= 4;
2341 hex_value <<= bitPos % integerPartWidth;
2342 significand[bitPos / integerPartWidth] |= hex_value;
2343 } else {
Erick Tryzelaarda666c82009-08-20 23:30:43 +00002344 lost_fraction = trailingHexadecimalFraction(p, end, hex_value);
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002345 while (p != end && hexDigitValue(*p) != -1U)
Erick Tryzelaar19f63b22009-08-16 23:36:19 +00002346 p++;
2347 break;
2348 }
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002349 }
2350 }
2351
2352 /* Hex floats require an exponent but not a hexadecimal point. */
Erick Tryzelaarda666c82009-08-20 23:30:43 +00002353 assert(p != end && "Hex strings require an exponent");
2354 assert((*p == 'p' || *p == 'P') && "Invalid character in significand");
2355 assert(p != begin && "Significand has no digits");
2356 assert((dot == end || p - begin != 1) && "Significand has no digits");
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002357
2358 /* Ignore the exponent if we are zero. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002359 if (p != firstSignificantDigit) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002360 int expAdjustment;
2361
2362 /* Implicit hexadecimal point? */
Erick Tryzelaarda666c82009-08-20 23:30:43 +00002363 if (dot == end)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002364 dot = p;
2365
2366 /* Calculate the exponent adjustment implicit in the number of
2367 significant digits. */
Evan Cheng82b9e962008-05-02 21:15:08 +00002368 expAdjustment = static_cast<int>(dot - firstSignificantDigit);
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002369 if (expAdjustment < 0)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002370 expAdjustment++;
2371 expAdjustment = expAdjustment * 4 - 1;
2372
2373 /* Adjust for writing the significand starting at the most
2374 significant nibble. */
2375 expAdjustment += semantics->precision;
2376 expAdjustment -= partsCount * integerPartWidth;
2377
2378 /* Adjust for the given exponent. */
Erick Tryzelaarda666c82009-08-20 23:30:43 +00002379 exponent = totalExponent(p + 1, end, expAdjustment);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002380 }
2381
2382 return normalize(rounding_mode, lost_fraction);
2383}
2384
2385APFloat::opStatus
Neil Boothb93d90e2007-10-12 16:02:31 +00002386APFloat::roundSignificandWithExponent(const integerPart *decSigParts,
2387 unsigned sigPartCount, int exp,
2388 roundingMode rounding_mode)
2389{
2390 unsigned int parts, pow5PartCount;
Ulrich Weigand908c9362012-10-29 18:18:44 +00002391 fltSemantics calcSemantics = { 32767, -32767, 0 };
Neil Boothb93d90e2007-10-12 16:02:31 +00002392 integerPart pow5Parts[maxPowerOfFiveParts];
2393 bool isNearest;
2394
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002395 isNearest = (rounding_mode == rmNearestTiesToEven ||
2396 rounding_mode == rmNearestTiesToAway);
Neil Boothb93d90e2007-10-12 16:02:31 +00002397
2398 parts = partCountForBits(semantics->precision + 11);
2399
2400 /* Calculate pow(5, abs(exp)). */
2401 pow5PartCount = powerOf5(pow5Parts, exp >= 0 ? exp: -exp);
2402
2403 for (;; parts *= 2) {
2404 opStatus sigStatus, powStatus;
2405 unsigned int excessPrecision, truncatedBits;
2406
2407 calcSemantics.precision = parts * integerPartWidth - 1;
2408 excessPrecision = calcSemantics.precision - semantics->precision;
2409 truncatedBits = excessPrecision;
2410
2411 APFloat decSig(calcSemantics, fcZero, sign);
2412 APFloat pow5(calcSemantics, fcZero, false);
2413
2414 sigStatus = decSig.convertFromUnsignedParts(decSigParts, sigPartCount,
2415 rmNearestTiesToEven);
2416 powStatus = pow5.convertFromUnsignedParts(pow5Parts, pow5PartCount,
2417 rmNearestTiesToEven);
2418 /* Add exp, as 10^n = 5^n * 2^n. */
2419 decSig.exponent += exp;
2420
2421 lostFraction calcLostFraction;
Evan Cheng82b9e962008-05-02 21:15:08 +00002422 integerPart HUerr, HUdistance;
2423 unsigned int powHUerr;
Neil Boothb93d90e2007-10-12 16:02:31 +00002424
2425 if (exp >= 0) {
2426 /* multiplySignificand leaves the precision-th bit set to 1. */
2427 calcLostFraction = decSig.multiplySignificand(pow5, NULL);
2428 powHUerr = powStatus != opOK;
2429 } else {
2430 calcLostFraction = decSig.divideSignificand(pow5);
2431 /* Denormal numbers have less precision. */
2432 if (decSig.exponent < semantics->minExponent) {
2433 excessPrecision += (semantics->minExponent - decSig.exponent);
2434 truncatedBits = excessPrecision;
2435 if (excessPrecision > calcSemantics.precision)
2436 excessPrecision = calcSemantics.precision;
2437 }
2438 /* Extra half-ulp lost in reciprocal of exponent. */
Evan Cheng82b9e962008-05-02 21:15:08 +00002439 powHUerr = (powStatus == opOK && calcLostFraction == lfExactlyZero) ? 0:2;
Neil Boothb93d90e2007-10-12 16:02:31 +00002440 }
2441
2442 /* Both multiplySignificand and divideSignificand return the
2443 result with the integer bit set. */
Evan Cheng67c90212009-10-27 21:35:42 +00002444 assert(APInt::tcExtractBit
2445 (decSig.significandParts(), calcSemantics.precision - 1) == 1);
Neil Boothb93d90e2007-10-12 16:02:31 +00002446
2447 HUerr = HUerrBound(calcLostFraction != lfExactlyZero, sigStatus != opOK,
2448 powHUerr);
2449 HUdistance = 2 * ulpsFromBoundary(decSig.significandParts(),
2450 excessPrecision, isNearest);
2451
2452 /* Are we guaranteed to round correctly if we truncate? */
2453 if (HUdistance >= HUerr) {
2454 APInt::tcExtract(significandParts(), partCount(), decSig.significandParts(),
2455 calcSemantics.precision - excessPrecision,
2456 excessPrecision);
2457 /* Take the exponent of decSig. If we tcExtract-ed less bits
2458 above we must adjust our exponent to compensate for the
2459 implicit right shift. */
2460 exponent = (decSig.exponent + semantics->precision
2461 - (calcSemantics.precision - excessPrecision));
2462 calcLostFraction = lostFractionThroughTruncation(decSig.significandParts(),
2463 decSig.partCount(),
2464 truncatedBits);
2465 return normalize(rounding_mode, calcLostFraction);
2466 }
2467 }
2468}
2469
2470APFloat::opStatus
Benjamin Kramer92d89982010-07-14 22:38:02 +00002471APFloat::convertFromDecimalString(StringRef str, roundingMode rounding_mode)
Neil Boothb93d90e2007-10-12 16:02:31 +00002472{
Neil Booth4ed401b2007-10-14 10:16:12 +00002473 decimalInfo D;
Neil Boothb93d90e2007-10-12 16:02:31 +00002474 opStatus fs;
2475
Neil Booth4ed401b2007-10-14 10:16:12 +00002476 /* Scan the text. */
Erick Tryzelaar19f63b22009-08-16 23:36:19 +00002477 StringRef::iterator p = str.begin();
2478 interpretDecimal(p, str.end(), &D);
Neil Boothb93d90e2007-10-12 16:02:31 +00002479
Neil Booth91305512007-10-15 15:00:55 +00002480 /* Handle the quick cases. First the case of no significant digits,
2481 i.e. zero, and then exponents that are obviously too large or too
2482 small. Writing L for log 10 / log 2, a number d.ddddd*10^exp
2483 definitely overflows if
2484
2485 (exp - 1) * L >= maxExponent
2486
2487 and definitely underflows to zero where
2488
2489 (exp + 1) * L <= minExponent - precision
2490
2491 With integer arithmetic the tightest bounds for L are
2492
2493 93/28 < L < 196/59 [ numerator <= 256 ]
2494 42039/12655 < L < 28738/8651 [ numerator <= 65536 ]
2495 */
2496
Neil Booth06f20ea2007-12-05 13:06:04 +00002497 if (decDigitValue(*D.firstSigDigit) >= 10U) {
Neil Boothb93d90e2007-10-12 16:02:31 +00002498 category = fcZero;
2499 fs = opOK;
John McCallb42cc682010-02-26 22:20:41 +00002500
2501 /* Check whether the normalized exponent is high enough to overflow
2502 max during the log-rebasing in the max-exponent check below. */
2503 } else if (D.normalizedExponent - 1 > INT_MAX / 42039) {
2504 fs = handleOverflow(rounding_mode);
2505
2506 /* If it wasn't, then it also wasn't high enough to overflow max
2507 during the log-rebasing in the min-exponent check. Check that it
2508 won't overflow min in either check, then perform the min-exponent
2509 check. */
2510 } else if (D.normalizedExponent - 1 < INT_MIN / 42039 ||
2511 (D.normalizedExponent + 1) * 28738 <=
2512 8651 * (semantics->minExponent - (int) semantics->precision)) {
Neil Booth91305512007-10-15 15:00:55 +00002513 /* Underflow to zero and round. */
2514 zeroSignificand();
2515 fs = normalize(rounding_mode, lfLessThanHalf);
John McCallb42cc682010-02-26 22:20:41 +00002516
2517 /* We can finally safely perform the max-exponent check. */
Neil Booth91305512007-10-15 15:00:55 +00002518 } else if ((D.normalizedExponent - 1) * 42039
2519 >= 12655 * semantics->maxExponent) {
2520 /* Overflow and round. */
2521 fs = handleOverflow(rounding_mode);
Neil Boothb93d90e2007-10-12 16:02:31 +00002522 } else {
Neil Booth4ed401b2007-10-14 10:16:12 +00002523 integerPart *decSignificand;
2524 unsigned int partCount;
Neil Boothb93d90e2007-10-12 16:02:31 +00002525
Neil Booth4ed401b2007-10-14 10:16:12 +00002526 /* A tight upper bound on number of bits required to hold an
Neil Booth91305512007-10-15 15:00:55 +00002527 N-digit decimal integer is N * 196 / 59. Allocate enough space
Neil Booth4ed401b2007-10-14 10:16:12 +00002528 to hold the full significand, and an extra part required by
2529 tcMultiplyPart. */
Evan Cheng82b9e962008-05-02 21:15:08 +00002530 partCount = static_cast<unsigned int>(D.lastSigDigit - D.firstSigDigit) + 1;
Neil Booth91305512007-10-15 15:00:55 +00002531 partCount = partCountForBits(1 + 196 * partCount / 59);
Neil Booth4ed401b2007-10-14 10:16:12 +00002532 decSignificand = new integerPart[partCount + 1];
2533 partCount = 0;
Neil Boothb93d90e2007-10-12 16:02:31 +00002534
Neil Booth4ed401b2007-10-14 10:16:12 +00002535 /* Convert to binary efficiently - we do almost all multiplication
2536 in an integerPart. When this would overflow do we do a single
2537 bignum multiplication, and then revert again to multiplication
2538 in an integerPart. */
2539 do {
2540 integerPart decValue, val, multiplier;
2541
2542 val = 0;
2543 multiplier = 1;
2544
2545 do {
Erick Tryzelaar19f63b22009-08-16 23:36:19 +00002546 if (*p == '.') {
Neil Booth4ed401b2007-10-14 10:16:12 +00002547 p++;
Erick Tryzelaar19f63b22009-08-16 23:36:19 +00002548 if (p == str.end()) {
2549 break;
2550 }
2551 }
Neil Booth4ed401b2007-10-14 10:16:12 +00002552 decValue = decDigitValue(*p++);
Erick Tryzelaarda666c82009-08-20 23:30:43 +00002553 assert(decValue < 10U && "Invalid character in significand");
Neil Booth4ed401b2007-10-14 10:16:12 +00002554 multiplier *= 10;
2555 val = val * 10 + decValue;
2556 /* The maximum number that can be multiplied by ten with any
2557 digit added without overflowing an integerPart. */
2558 } while (p <= D.lastSigDigit && multiplier <= (~ (integerPart) 0 - 9) / 10);
2559
2560 /* Multiply out the current part. */
2561 APInt::tcMultiplyPart(decSignificand, decSignificand, multiplier, val,
2562 partCount, partCount + 1, false);
2563
2564 /* If we used another part (likely but not guaranteed), increase
2565 the count. */
2566 if (decSignificand[partCount])
2567 partCount++;
2568 } while (p <= D.lastSigDigit);
Neil Boothb93d90e2007-10-12 16:02:31 +00002569
Neil Boothae077d22007-11-01 22:51:07 +00002570 category = fcNormal;
Neil Boothb93d90e2007-10-12 16:02:31 +00002571 fs = roundSignificandWithExponent(decSignificand, partCount,
Neil Booth4ed401b2007-10-14 10:16:12 +00002572 D.exponent, rounding_mode);
Neil Boothb93d90e2007-10-12 16:02:31 +00002573
Neil Booth4ed401b2007-10-14 10:16:12 +00002574 delete [] decSignificand;
2575 }
Neil Boothb93d90e2007-10-12 16:02:31 +00002576
2577 return fs;
2578}
2579
2580APFloat::opStatus
Benjamin Kramer92d89982010-07-14 22:38:02 +00002581APFloat::convertFromString(StringRef str, roundingMode rounding_mode)
Neil Booth9acbf5a2007-09-26 21:33:42 +00002582{
Erick Tryzelaar19f63b22009-08-16 23:36:19 +00002583 assert(!str.empty() && "Invalid string length");
Neil Booth06077e72007-10-14 10:29:28 +00002584
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002585 /* Handle a leading minus sign. */
Erick Tryzelaar19f63b22009-08-16 23:36:19 +00002586 StringRef::iterator p = str.begin();
2587 size_t slen = str.size();
Erick Tryzelaarda666c82009-08-20 23:30:43 +00002588 sign = *p == '-' ? 1 : 0;
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002589 if (*p == '-' || *p == '+') {
Erick Tryzelaar19f63b22009-08-16 23:36:19 +00002590 p++;
2591 slen--;
Erick Tryzelaarda666c82009-08-20 23:30:43 +00002592 assert(slen && "String has no digits");
Erick Tryzelaar19f63b22009-08-16 23:36:19 +00002593 }
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002594
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002595 if (slen >= 2 && p[0] == '0' && (p[1] == 'x' || p[1] == 'X')) {
Erick Tryzelaar19f63b22009-08-16 23:36:19 +00002596 assert(slen - 2 && "Invalid string");
Erick Tryzelaarda666c82009-08-20 23:30:43 +00002597 return convertFromHexadecimalString(StringRef(p + 2, slen - 2),
Erick Tryzelaar19f63b22009-08-16 23:36:19 +00002598 rounding_mode);
2599 }
Bill Wendlingc6075402008-11-27 08:00:12 +00002600
Erick Tryzelaarda666c82009-08-20 23:30:43 +00002601 return convertFromDecimalString(StringRef(p, slen), rounding_mode);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002602}
Dale Johannesena719a602007-08-24 00:56:33 +00002603
Neil Booth8f1946f2007-10-03 22:26:02 +00002604/* Write out a hexadecimal representation of the floating point value
2605 to DST, which must be of sufficient size, in the C99 form
2606 [-]0xh.hhhhp[+-]d. Return the number of characters written,
2607 excluding the terminating NUL.
2608
2609 If UPPERCASE, the output is in upper case, otherwise in lower case.
2610
2611 HEXDIGITS digits appear altogether, rounding the value if
2612 necessary. If HEXDIGITS is 0, the minimal precision to display the
2613 number precisely is used instead. If nothing would appear after
2614 the decimal point it is suppressed.
2615
2616 The decimal exponent is always printed and has at least one digit.
2617 Zero values display an exponent of zero. Infinities and NaNs
2618 appear as "infinity" or "nan" respectively.
2619
2620 The above rules are as specified by C99. There is ambiguity about
2621 what the leading hexadecimal digit should be. This implementation
2622 uses whatever is necessary so that the exponent is displayed as
2623 stored. This implies the exponent will fall within the IEEE format
2624 range, and the leading hexadecimal digit will be 0 (for denormals),
2625 1 (normal numbers) or 2 (normal numbers rounded-away-from-zero with
2626 any other digits zero).
2627*/
2628unsigned int
2629APFloat::convertToHexString(char *dst, unsigned int hexDigits,
2630 bool upperCase, roundingMode rounding_mode) const
2631{
2632 char *p;
2633
2634 p = dst;
2635 if (sign)
2636 *dst++ = '-';
2637
2638 switch (category) {
2639 case fcInfinity:
2640 memcpy (dst, upperCase ? infinityU: infinityL, sizeof infinityU - 1);
2641 dst += sizeof infinityL - 1;
2642 break;
2643
2644 case fcNaN:
2645 memcpy (dst, upperCase ? NaNU: NaNL, sizeof NaNU - 1);
2646 dst += sizeof NaNU - 1;
2647 break;
2648
2649 case fcZero:
2650 *dst++ = '0';
2651 *dst++ = upperCase ? 'X': 'x';
2652 *dst++ = '0';
2653 if (hexDigits > 1) {
2654 *dst++ = '.';
2655 memset (dst, '0', hexDigits - 1);
2656 dst += hexDigits - 1;
2657 }
2658 *dst++ = upperCase ? 'P': 'p';
2659 *dst++ = '0';
2660 break;
2661
2662 case fcNormal:
2663 dst = convertNormalToHexString (dst, hexDigits, upperCase, rounding_mode);
2664 break;
2665 }
2666
2667 *dst = 0;
2668
Evan Cheng82b9e962008-05-02 21:15:08 +00002669 return static_cast<unsigned int>(dst - p);
Neil Booth8f1946f2007-10-03 22:26:02 +00002670}
2671
2672/* Does the hard work of outputting the correctly rounded hexadecimal
2673 form of a normal floating point number with the specified number of
2674 hexadecimal digits. If HEXDIGITS is zero the minimum number of
2675 digits necessary to print the value precisely is output. */
2676char *
2677APFloat::convertNormalToHexString(char *dst, unsigned int hexDigits,
2678 bool upperCase,
2679 roundingMode rounding_mode) const
2680{
2681 unsigned int count, valueBits, shift, partsCount, outputDigits;
2682 const char *hexDigitChars;
2683 const integerPart *significand;
2684 char *p;
2685 bool roundUp;
2686
2687 *dst++ = '0';
2688 *dst++ = upperCase ? 'X': 'x';
2689
2690 roundUp = false;
2691 hexDigitChars = upperCase ? hexDigitsUpper: hexDigitsLower;
2692
2693 significand = significandParts();
2694 partsCount = partCount();
2695
2696 /* +3 because the first digit only uses the single integer bit, so
2697 we have 3 virtual zero most-significant-bits. */
2698 valueBits = semantics->precision + 3;
2699 shift = integerPartWidth - valueBits % integerPartWidth;
2700
2701 /* The natural number of digits required ignoring trailing
2702 insignificant zeroes. */
2703 outputDigits = (valueBits - significandLSB () + 3) / 4;
2704
2705 /* hexDigits of zero means use the required number for the
2706 precision. Otherwise, see if we are truncating. If we are,
Neil Booth0ea72a92007-10-06 00:24:48 +00002707 find out if we need to round away from zero. */
Neil Booth8f1946f2007-10-03 22:26:02 +00002708 if (hexDigits) {
2709 if (hexDigits < outputDigits) {
2710 /* We are dropping non-zero bits, so need to check how to round.
2711 "bits" is the number of dropped bits. */
2712 unsigned int bits;
2713 lostFraction fraction;
2714
2715 bits = valueBits - hexDigits * 4;
2716 fraction = lostFractionThroughTruncation (significand, partsCount, bits);
2717 roundUp = roundAwayFromZero(rounding_mode, fraction, bits);
2718 }
2719 outputDigits = hexDigits;
2720 }
2721
2722 /* Write the digits consecutively, and start writing in the location
2723 of the hexadecimal point. We move the most significant digit
2724 left and add the hexadecimal point later. */
2725 p = ++dst;
2726
2727 count = (valueBits + integerPartWidth - 1) / integerPartWidth;
2728
2729 while (outputDigits && count) {
2730 integerPart part;
2731
2732 /* Put the most significant integerPartWidth bits in "part". */
2733 if (--count == partsCount)
2734 part = 0; /* An imaginary higher zero part. */
2735 else
2736 part = significand[count] << shift;
2737
2738 if (count && shift)
2739 part |= significand[count - 1] >> (integerPartWidth - shift);
2740
2741 /* Convert as much of "part" to hexdigits as we can. */
2742 unsigned int curDigits = integerPartWidth / 4;
2743
2744 if (curDigits > outputDigits)
2745 curDigits = outputDigits;
2746 dst += partAsHex (dst, part, curDigits, hexDigitChars);
2747 outputDigits -= curDigits;
2748 }
2749
2750 if (roundUp) {
2751 char *q = dst;
2752
2753 /* Note that hexDigitChars has a trailing '0'. */
2754 do {
2755 q--;
2756 *q = hexDigitChars[hexDigitValue (*q) + 1];
Neil Booth0ea72a92007-10-06 00:24:48 +00002757 } while (*q == '0');
Evan Cheng67c90212009-10-27 21:35:42 +00002758 assert(q >= p);
Neil Booth8f1946f2007-10-03 22:26:02 +00002759 } else {
2760 /* Add trailing zeroes. */
2761 memset (dst, '0', outputDigits);
2762 dst += outputDigits;
2763 }
2764
2765 /* Move the most significant digit to before the point, and if there
2766 is something after the decimal point add it. This must come
2767 after rounding above. */
2768 p[-1] = p[0];
2769 if (dst -1 == p)
2770 dst--;
2771 else
2772 p[0] = '.';
2773
2774 /* Finally output the exponent. */
2775 *dst++ = upperCase ? 'P': 'p';
2776
Neil Booth32897f52007-10-06 07:29:25 +00002777 return writeSignedDecimal (dst, exponent);
Neil Booth8f1946f2007-10-03 22:26:02 +00002778}
2779
Chandler Carruth71bd7d12012-03-04 12:02:57 +00002780hash_code llvm::hash_value(const APFloat &Arg) {
2781 if (Arg.category != APFloat::fcNormal)
2782 return hash_combine((uint8_t)Arg.category,
2783 // NaN has no sign, fix it at zero.
2784 Arg.isNaN() ? (uint8_t)0 : (uint8_t)Arg.sign,
2785 Arg.semantics->precision);
2786
2787 // Normal floats need their exponent and significand hashed.
2788 return hash_combine((uint8_t)Arg.category, (uint8_t)Arg.sign,
2789 Arg.semantics->precision, Arg.exponent,
2790 hash_combine_range(
2791 Arg.significandParts(),
2792 Arg.significandParts() + Arg.partCount()));
Dale Johannesena719a602007-08-24 00:56:33 +00002793}
2794
2795// Conversion from APFloat to/from host float/double. It may eventually be
2796// possible to eliminate these and have everybody deal with APFloats, but that
2797// will take a while. This approach will not easily extend to long double.
Dale Johannesen146a0ea2007-09-20 23:47:58 +00002798// Current implementation requires integerPartWidth==64, which is correct at
2799// the moment but could be made more general.
Dale Johannesena719a602007-08-24 00:56:33 +00002800
Dale Johannesen728687c2007-09-05 20:39:49 +00002801// Denormals have exponent minExponent in APFloat, but minExponent-1 in
Dale Johannesen146a0ea2007-09-20 23:47:58 +00002802// the actual IEEE respresentations. We compensate for that here.
Dale Johannesen728687c2007-09-05 20:39:49 +00002803
Dale Johannesen245dceb2007-09-11 18:32:33 +00002804APInt
Neil Booth9acbf5a2007-09-26 21:33:42 +00002805APFloat::convertF80LongDoubleAPFloatToAPInt() const
2806{
Dan Gohmanb456a152008-01-29 12:08:20 +00002807 assert(semantics == (const llvm::fltSemantics*)&x87DoubleExtended);
Evan Cheng67c90212009-10-27 21:35:42 +00002808 assert(partCount()==2);
Dale Johannesen245dceb2007-09-11 18:32:33 +00002809
2810 uint64_t myexponent, mysignificand;
2811
2812 if (category==fcNormal) {
2813 myexponent = exponent+16383; //bias
Dale Johannesen146a0ea2007-09-20 23:47:58 +00002814 mysignificand = significandParts()[0];
Dale Johannesen245dceb2007-09-11 18:32:33 +00002815 if (myexponent==1 && !(mysignificand & 0x8000000000000000ULL))
2816 myexponent = 0; // denormal
2817 } else if (category==fcZero) {
2818 myexponent = 0;
2819 mysignificand = 0;
2820 } else if (category==fcInfinity) {
2821 myexponent = 0x7fff;
2822 mysignificand = 0x8000000000000000ULL;
Chris Lattner2a9bcb92007-10-06 06:13:42 +00002823 } else {
2824 assert(category == fcNaN && "Unknown category");
Dale Johannesen245dceb2007-09-11 18:32:33 +00002825 myexponent = 0x7fff;
Dale Johannesen146a0ea2007-09-20 23:47:58 +00002826 mysignificand = significandParts()[0];
Chris Lattner2a9bcb92007-10-06 06:13:42 +00002827 }
Dale Johannesen245dceb2007-09-11 18:32:33 +00002828
2829 uint64_t words[2];
Dale Johannesen93eefa02009-03-23 21:16:53 +00002830 words[0] = mysignificand;
2831 words[1] = ((uint64_t)(sign & 1) << 15) |
2832 (myexponent & 0x7fffLL);
Jeffrey Yasskin7a162882011-07-18 21:45:40 +00002833 return APInt(80, words);
Dale Johannesen245dceb2007-09-11 18:32:33 +00002834}
2835
2836APInt
Dale Johannesen007aa372007-10-11 18:07:22 +00002837APFloat::convertPPCDoubleDoubleAPFloatToAPInt() const
2838{
Dan Gohmanb456a152008-01-29 12:08:20 +00002839 assert(semantics == (const llvm::fltSemantics*)&PPCDoubleDouble);
Evan Cheng67c90212009-10-27 21:35:42 +00002840 assert(partCount()==2);
Dale Johannesen007aa372007-10-11 18:07:22 +00002841
Ulrich Weigandd9f7e252012-10-29 18:09:01 +00002842 uint64_t words[2];
2843 opStatus fs;
2844 bool losesInfo;
Dale Johannesen007aa372007-10-11 18:07:22 +00002845
Ulrich Weigandd9f7e252012-10-29 18:09:01 +00002846 // Convert number to double. To avoid spurious underflows, we re-
2847 // normalize against the "double" minExponent first, and only *then*
2848 // truncate the mantissa. The result of that second conversion
2849 // may be inexact, but should never underflow.
Alexey Samsonov2b431d92012-11-30 22:27:54 +00002850 // Declare fltSemantics before APFloat that uses it (and
2851 // saves pointer to it) to ensure correct destruction order.
Ulrich Weigandd9f7e252012-10-29 18:09:01 +00002852 fltSemantics extendedSemantics = *semantics;
2853 extendedSemantics.minExponent = IEEEdouble.minExponent;
Alexey Samsonov2b431d92012-11-30 22:27:54 +00002854 APFloat extended(*this);
Ulrich Weigandd9f7e252012-10-29 18:09:01 +00002855 fs = extended.convert(extendedSemantics, rmNearestTiesToEven, &losesInfo);
2856 assert(fs == opOK && !losesInfo);
2857 (void)fs;
2858
2859 APFloat u(extended);
2860 fs = u.convert(IEEEdouble, rmNearestTiesToEven, &losesInfo);
2861 assert(fs == opOK || fs == opInexact);
2862 (void)fs;
2863 words[0] = *u.convertDoubleAPFloatToAPInt().getRawData();
2864
2865 // If conversion was exact or resulted in a special case, we're done;
2866 // just set the second double to zero. Otherwise, re-convert back to
2867 // the extended format and compute the difference. This now should
2868 // convert exactly to double.
2869 if (u.category == fcNormal && losesInfo) {
2870 fs = u.convert(extendedSemantics, rmNearestTiesToEven, &losesInfo);
2871 assert(fs == opOK && !losesInfo);
2872 (void)fs;
2873
2874 APFloat v(extended);
2875 v.subtract(u, rmNearestTiesToEven);
2876 fs = v.convert(IEEEdouble, rmNearestTiesToEven, &losesInfo);
2877 assert(fs == opOK && !losesInfo);
2878 (void)fs;
2879 words[1] = *v.convertDoubleAPFloatToAPInt().getRawData();
Dale Johannesen007aa372007-10-11 18:07:22 +00002880 } else {
Ulrich Weigandd9f7e252012-10-29 18:09:01 +00002881 words[1] = 0;
Dale Johannesen007aa372007-10-11 18:07:22 +00002882 }
2883
Jeffrey Yasskin7a162882011-07-18 21:45:40 +00002884 return APInt(128, words);
Dale Johannesen007aa372007-10-11 18:07:22 +00002885}
2886
2887APInt
Anton Korobeynikov13e8c7e2009-08-21 22:10:30 +00002888APFloat::convertQuadrupleAPFloatToAPInt() const
2889{
2890 assert(semantics == (const llvm::fltSemantics*)&IEEEquad);
Evan Cheng67c90212009-10-27 21:35:42 +00002891 assert(partCount()==2);
Anton Korobeynikov13e8c7e2009-08-21 22:10:30 +00002892
2893 uint64_t myexponent, mysignificand, mysignificand2;
2894
2895 if (category==fcNormal) {
2896 myexponent = exponent+16383; //bias
2897 mysignificand = significandParts()[0];
2898 mysignificand2 = significandParts()[1];
2899 if (myexponent==1 && !(mysignificand2 & 0x1000000000000LL))
2900 myexponent = 0; // denormal
2901 } else if (category==fcZero) {
2902 myexponent = 0;
2903 mysignificand = mysignificand2 = 0;
2904 } else if (category==fcInfinity) {
2905 myexponent = 0x7fff;
2906 mysignificand = mysignificand2 = 0;
2907 } else {
2908 assert(category == fcNaN && "Unknown category!");
2909 myexponent = 0x7fff;
2910 mysignificand = significandParts()[0];
2911 mysignificand2 = significandParts()[1];
2912 }
2913
2914 uint64_t words[2];
2915 words[0] = mysignificand;
2916 words[1] = ((uint64_t)(sign & 1) << 63) |
2917 ((myexponent & 0x7fff) << 48) |
Anton Korobeynikov876955c2009-08-21 23:09:47 +00002918 (mysignificand2 & 0xffffffffffffLL);
Anton Korobeynikov13e8c7e2009-08-21 22:10:30 +00002919
Jeffrey Yasskin7a162882011-07-18 21:45:40 +00002920 return APInt(128, words);
Anton Korobeynikov13e8c7e2009-08-21 22:10:30 +00002921}
2922
2923APInt
Neil Booth9acbf5a2007-09-26 21:33:42 +00002924APFloat::convertDoubleAPFloatToAPInt() const
2925{
Dan Gohman58c468f2007-09-14 20:08:19 +00002926 assert(semantics == (const llvm::fltSemantics*)&IEEEdouble);
Evan Cheng67c90212009-10-27 21:35:42 +00002927 assert(partCount()==1);
Dale Johannesena719a602007-08-24 00:56:33 +00002928
Dale Johannesen3cf889f2007-08-31 04:03:46 +00002929 uint64_t myexponent, mysignificand;
Dale Johannesena719a602007-08-24 00:56:33 +00002930
2931 if (category==fcNormal) {
Dale Johannesena719a602007-08-24 00:56:33 +00002932 myexponent = exponent+1023; //bias
Dale Johannesen728687c2007-09-05 20:39:49 +00002933 mysignificand = *significandParts();
2934 if (myexponent==1 && !(mysignificand & 0x10000000000000LL))
2935 myexponent = 0; // denormal
Dale Johannesena719a602007-08-24 00:56:33 +00002936 } else if (category==fcZero) {
Dale Johannesena719a602007-08-24 00:56:33 +00002937 myexponent = 0;
2938 mysignificand = 0;
2939 } else if (category==fcInfinity) {
Dale Johannesena719a602007-08-24 00:56:33 +00002940 myexponent = 0x7ff;
2941 mysignificand = 0;
Chris Lattner2a9bcb92007-10-06 06:13:42 +00002942 } else {
2943 assert(category == fcNaN && "Unknown category!");
Dale Johannesena719a602007-08-24 00:56:33 +00002944 myexponent = 0x7ff;
Dale Johannesen3cf889f2007-08-31 04:03:46 +00002945 mysignificand = *significandParts();
Chris Lattner2a9bcb92007-10-06 06:13:42 +00002946 }
Dale Johannesena719a602007-08-24 00:56:33 +00002947
Evan Cheng82b9e962008-05-02 21:15:08 +00002948 return APInt(64, ((((uint64_t)(sign & 1) << 63) |
Chris Lattner2a9bcb92007-10-06 06:13:42 +00002949 ((myexponent & 0x7ff) << 52) |
2950 (mysignificand & 0xfffffffffffffLL))));
Dale Johannesena719a602007-08-24 00:56:33 +00002951}
2952
Dale Johannesen245dceb2007-09-11 18:32:33 +00002953APInt
Neil Booth9acbf5a2007-09-26 21:33:42 +00002954APFloat::convertFloatAPFloatToAPInt() const
2955{
Dan Gohman58c468f2007-09-14 20:08:19 +00002956 assert(semantics == (const llvm::fltSemantics*)&IEEEsingle);
Evan Cheng67c90212009-10-27 21:35:42 +00002957 assert(partCount()==1);
Neil Booth9acbf5a2007-09-26 21:33:42 +00002958
Dale Johannesen3cf889f2007-08-31 04:03:46 +00002959 uint32_t myexponent, mysignificand;
Dale Johannesena719a602007-08-24 00:56:33 +00002960
2961 if (category==fcNormal) {
Dale Johannesena719a602007-08-24 00:56:33 +00002962 myexponent = exponent+127; //bias
Evan Cheng82b9e962008-05-02 21:15:08 +00002963 mysignificand = (uint32_t)*significandParts();
Dale Johannesen06a10df2007-11-17 01:02:27 +00002964 if (myexponent == 1 && !(mysignificand & 0x800000))
Dale Johannesen728687c2007-09-05 20:39:49 +00002965 myexponent = 0; // denormal
Dale Johannesena719a602007-08-24 00:56:33 +00002966 } else if (category==fcZero) {
Dale Johannesena719a602007-08-24 00:56:33 +00002967 myexponent = 0;
2968 mysignificand = 0;
2969 } else if (category==fcInfinity) {
Dale Johannesena719a602007-08-24 00:56:33 +00002970 myexponent = 0xff;
2971 mysignificand = 0;
Chris Lattner2a9bcb92007-10-06 06:13:42 +00002972 } else {
2973 assert(category == fcNaN && "Unknown category!");
Dale Johannesen728687c2007-09-05 20:39:49 +00002974 myexponent = 0xff;
Evan Cheng82b9e962008-05-02 21:15:08 +00002975 mysignificand = (uint32_t)*significandParts();
Chris Lattner2a9bcb92007-10-06 06:13:42 +00002976 }
Dale Johannesena719a602007-08-24 00:56:33 +00002977
Chris Lattner2a9bcb92007-10-06 06:13:42 +00002978 return APInt(32, (((sign&1) << 31) | ((myexponent&0xff) << 23) |
2979 (mysignificand & 0x7fffff)));
Dale Johannesena719a602007-08-24 00:56:33 +00002980}
2981
Chris Lattner4794b2b2009-10-16 02:13:51 +00002982APInt
2983APFloat::convertHalfAPFloatToAPInt() const
2984{
2985 assert(semantics == (const llvm::fltSemantics*)&IEEEhalf);
Evan Cheng67c90212009-10-27 21:35:42 +00002986 assert(partCount()==1);
Chris Lattner4794b2b2009-10-16 02:13:51 +00002987
2988 uint32_t myexponent, mysignificand;
2989
2990 if (category==fcNormal) {
2991 myexponent = exponent+15; //bias
2992 mysignificand = (uint32_t)*significandParts();
2993 if (myexponent == 1 && !(mysignificand & 0x400))
2994 myexponent = 0; // denormal
2995 } else if (category==fcZero) {
2996 myexponent = 0;
2997 mysignificand = 0;
2998 } else if (category==fcInfinity) {
Dale Johannesen0d670b52009-10-23 04:02:51 +00002999 myexponent = 0x1f;
Chris Lattner4794b2b2009-10-16 02:13:51 +00003000 mysignificand = 0;
3001 } else {
3002 assert(category == fcNaN && "Unknown category!");
Dale Johannesen0d670b52009-10-23 04:02:51 +00003003 myexponent = 0x1f;
Chris Lattner4794b2b2009-10-16 02:13:51 +00003004 mysignificand = (uint32_t)*significandParts();
3005 }
3006
3007 return APInt(16, (((sign&1) << 15) | ((myexponent&0x1f) << 10) |
3008 (mysignificand & 0x3ff)));
3009}
3010
Dale Johannesen007aa372007-10-11 18:07:22 +00003011// This function creates an APInt that is just a bit map of the floating
3012// point constant as it would appear in memory. It is not a conversion,
3013// and treating the result as a normal integer is unlikely to be useful.
3014
Dale Johannesen245dceb2007-09-11 18:32:33 +00003015APInt
Dale Johannesen54306fe2008-10-09 18:53:47 +00003016APFloat::bitcastToAPInt() const
Neil Booth9acbf5a2007-09-26 21:33:42 +00003017{
Chris Lattner4794b2b2009-10-16 02:13:51 +00003018 if (semantics == (const llvm::fltSemantics*)&IEEEhalf)
3019 return convertHalfAPFloatToAPInt();
3020
Dan Gohmanb456a152008-01-29 12:08:20 +00003021 if (semantics == (const llvm::fltSemantics*)&IEEEsingle)
Dale Johannesen245dceb2007-09-11 18:32:33 +00003022 return convertFloatAPFloatToAPInt();
Anton Korobeynikov13e8c7e2009-08-21 22:10:30 +00003023
Dan Gohmanb456a152008-01-29 12:08:20 +00003024 if (semantics == (const llvm::fltSemantics*)&IEEEdouble)
Dale Johannesen245dceb2007-09-11 18:32:33 +00003025 return convertDoubleAPFloatToAPInt();
Neil Booth9acbf5a2007-09-26 21:33:42 +00003026
Anton Korobeynikov13e8c7e2009-08-21 22:10:30 +00003027 if (semantics == (const llvm::fltSemantics*)&IEEEquad)
3028 return convertQuadrupleAPFloatToAPInt();
3029
Dan Gohmanb456a152008-01-29 12:08:20 +00003030 if (semantics == (const llvm::fltSemantics*)&PPCDoubleDouble)
Dale Johannesen007aa372007-10-11 18:07:22 +00003031 return convertPPCDoubleDoubleAPFloatToAPInt();
3032
Dan Gohmanb456a152008-01-29 12:08:20 +00003033 assert(semantics == (const llvm::fltSemantics*)&x87DoubleExtended &&
Chris Lattner2a9bcb92007-10-06 06:13:42 +00003034 "unknown format!");
3035 return convertF80LongDoubleAPFloatToAPInt();
Dale Johannesen245dceb2007-09-11 18:32:33 +00003036}
3037
Neil Booth9acbf5a2007-09-26 21:33:42 +00003038float
3039APFloat::convertToFloat() const
3040{
Chris Lattner688f9912009-09-24 21:44:20 +00003041 assert(semantics == (const llvm::fltSemantics*)&IEEEsingle &&
3042 "Float semantics are not IEEEsingle");
Dale Johannesen54306fe2008-10-09 18:53:47 +00003043 APInt api = bitcastToAPInt();
Dale Johannesen245dceb2007-09-11 18:32:33 +00003044 return api.bitsToFloat();
3045}
3046
Neil Booth9acbf5a2007-09-26 21:33:42 +00003047double
3048APFloat::convertToDouble() const
3049{
Chris Lattner688f9912009-09-24 21:44:20 +00003050 assert(semantics == (const llvm::fltSemantics*)&IEEEdouble &&
3051 "Float semantics are not IEEEdouble");
Dale Johannesen54306fe2008-10-09 18:53:47 +00003052 APInt api = bitcastToAPInt();
Dale Johannesen245dceb2007-09-11 18:32:33 +00003053 return api.bitsToDouble();
3054}
3055
Dale Johannesenfff29952008-10-06 18:22:29 +00003056/// Integer bit is explicit in this format. Intel hardware (387 and later)
3057/// does not support these bit patterns:
3058/// exponent = all 1's, integer bit 0, significand 0 ("pseudoinfinity")
3059/// exponent = all 1's, integer bit 0, significand nonzero ("pseudoNaN")
3060/// exponent = 0, integer bit 1 ("pseudodenormal")
3061/// exponent!=0 nor all 1's, integer bit 0 ("unnormal")
3062/// At the moment, the first two are treated as NaNs, the second two as Normal.
Dale Johannesen245dceb2007-09-11 18:32:33 +00003063void
Neil Booth9acbf5a2007-09-26 21:33:42 +00003064APFloat::initFromF80LongDoubleAPInt(const APInt &api)
3065{
Dale Johannesen245dceb2007-09-11 18:32:33 +00003066 assert(api.getBitWidth()==80);
3067 uint64_t i1 = api.getRawData()[0];
3068 uint64_t i2 = api.getRawData()[1];
Dale Johannesen93eefa02009-03-23 21:16:53 +00003069 uint64_t myexponent = (i2 & 0x7fff);
3070 uint64_t mysignificand = i1;
Dale Johannesen245dceb2007-09-11 18:32:33 +00003071
3072 initialize(&APFloat::x87DoubleExtended);
Dale Johannesen146a0ea2007-09-20 23:47:58 +00003073 assert(partCount()==2);
Dale Johannesen245dceb2007-09-11 18:32:33 +00003074
Dale Johannesen93eefa02009-03-23 21:16:53 +00003075 sign = static_cast<unsigned int>(i2>>15);
Dale Johannesen245dceb2007-09-11 18:32:33 +00003076 if (myexponent==0 && mysignificand==0) {
3077 // exponent, significand meaningless
3078 category = fcZero;
3079 } else if (myexponent==0x7fff && mysignificand==0x8000000000000000ULL) {
3080 // exponent, significand meaningless
3081 category = fcInfinity;
3082 } else if (myexponent==0x7fff && mysignificand!=0x8000000000000000ULL) {
3083 // exponent meaningless
3084 category = fcNaN;
Dale Johannesen146a0ea2007-09-20 23:47:58 +00003085 significandParts()[0] = mysignificand;
3086 significandParts()[1] = 0;
Dale Johannesen245dceb2007-09-11 18:32:33 +00003087 } else {
3088 category = fcNormal;
3089 exponent = myexponent - 16383;
Dale Johannesen146a0ea2007-09-20 23:47:58 +00003090 significandParts()[0] = mysignificand;
3091 significandParts()[1] = 0;
Dale Johannesen245dceb2007-09-11 18:32:33 +00003092 if (myexponent==0) // denormal
3093 exponent = -16382;
Neil Booth9acbf5a2007-09-26 21:33:42 +00003094 }
Dale Johannesen245dceb2007-09-11 18:32:33 +00003095}
3096
3097void
Dale Johannesen007aa372007-10-11 18:07:22 +00003098APFloat::initFromPPCDoubleDoubleAPInt(const APInt &api)
3099{
3100 assert(api.getBitWidth()==128);
3101 uint64_t i1 = api.getRawData()[0];
3102 uint64_t i2 = api.getRawData()[1];
Ulrich Weigandd9f7e252012-10-29 18:09:01 +00003103 opStatus fs;
3104 bool losesInfo;
Dale Johannesen007aa372007-10-11 18:07:22 +00003105
Ulrich Weigandd9f7e252012-10-29 18:09:01 +00003106 // Get the first double and convert to our format.
3107 initFromDoubleAPInt(APInt(64, i1));
3108 fs = convert(PPCDoubleDouble, rmNearestTiesToEven, &losesInfo);
3109 assert(fs == opOK && !losesInfo);
3110 (void)fs;
Dale Johannesen007aa372007-10-11 18:07:22 +00003111
Ulrich Weigandd9f7e252012-10-29 18:09:01 +00003112 // Unless we have a special case, add in second double.
3113 if (category == fcNormal) {
Tim Northover29178a32013-01-22 09:46:31 +00003114 APFloat v(IEEEdouble, APInt(64, i2));
Ulrich Weigandd9f7e252012-10-29 18:09:01 +00003115 fs = v.convert(PPCDoubleDouble, rmNearestTiesToEven, &losesInfo);
3116 assert(fs == opOK && !losesInfo);
3117 (void)fs;
3118
3119 add(v, rmNearestTiesToEven);
Dale Johannesen007aa372007-10-11 18:07:22 +00003120 }
3121}
3122
3123void
Anton Korobeynikov13e8c7e2009-08-21 22:10:30 +00003124APFloat::initFromQuadrupleAPInt(const APInt &api)
3125{
3126 assert(api.getBitWidth()==128);
3127 uint64_t i1 = api.getRawData()[0];
3128 uint64_t i2 = api.getRawData()[1];
3129 uint64_t myexponent = (i2 >> 48) & 0x7fff;
3130 uint64_t mysignificand = i1;
3131 uint64_t mysignificand2 = i2 & 0xffffffffffffLL;
3132
3133 initialize(&APFloat::IEEEquad);
3134 assert(partCount()==2);
3135
3136 sign = static_cast<unsigned int>(i2>>63);
3137 if (myexponent==0 &&
3138 (mysignificand==0 && mysignificand2==0)) {
3139 // exponent, significand meaningless
3140 category = fcZero;
3141 } else if (myexponent==0x7fff &&
3142 (mysignificand==0 && mysignificand2==0)) {
3143 // exponent, significand meaningless
3144 category = fcInfinity;
3145 } else if (myexponent==0x7fff &&
3146 (mysignificand!=0 || mysignificand2 !=0)) {
3147 // exponent meaningless
3148 category = fcNaN;
3149 significandParts()[0] = mysignificand;
3150 significandParts()[1] = mysignificand2;
3151 } else {
3152 category = fcNormal;
3153 exponent = myexponent - 16383;
3154 significandParts()[0] = mysignificand;
3155 significandParts()[1] = mysignificand2;
3156 if (myexponent==0) // denormal
3157 exponent = -16382;
3158 else
3159 significandParts()[1] |= 0x1000000000000LL; // integer bit
3160 }
3161}
3162
3163void
Neil Booth9acbf5a2007-09-26 21:33:42 +00003164APFloat::initFromDoubleAPInt(const APInt &api)
3165{
Dale Johannesen245dceb2007-09-11 18:32:33 +00003166 assert(api.getBitWidth()==64);
3167 uint64_t i = *api.getRawData();
Dale Johannesen918c33c2007-08-24 05:08:11 +00003168 uint64_t myexponent = (i >> 52) & 0x7ff;
3169 uint64_t mysignificand = i & 0xfffffffffffffLL;
3170
Dale Johannesena719a602007-08-24 00:56:33 +00003171 initialize(&APFloat::IEEEdouble);
Dale Johannesena719a602007-08-24 00:56:33 +00003172 assert(partCount()==1);
3173
Evan Cheng82b9e962008-05-02 21:15:08 +00003174 sign = static_cast<unsigned int>(i>>63);
Dale Johannesena719a602007-08-24 00:56:33 +00003175 if (myexponent==0 && mysignificand==0) {
3176 // exponent, significand meaningless
3177 category = fcZero;
Dale Johannesena719a602007-08-24 00:56:33 +00003178 } else if (myexponent==0x7ff && mysignificand==0) {
3179 // exponent, significand meaningless
3180 category = fcInfinity;
Dale Johannesen3cf889f2007-08-31 04:03:46 +00003181 } else if (myexponent==0x7ff && mysignificand!=0) {
3182 // exponent meaningless
3183 category = fcNaN;
3184 *significandParts() = mysignificand;
Dale Johannesena719a602007-08-24 00:56:33 +00003185 } else {
Dale Johannesena719a602007-08-24 00:56:33 +00003186 category = fcNormal;
3187 exponent = myexponent - 1023;
Dale Johannesen728687c2007-09-05 20:39:49 +00003188 *significandParts() = mysignificand;
3189 if (myexponent==0) // denormal
3190 exponent = -1022;
3191 else
3192 *significandParts() |= 0x10000000000000LL; // integer bit
Neil Booth9acbf5a2007-09-26 21:33:42 +00003193 }
Dale Johannesena719a602007-08-24 00:56:33 +00003194}
3195
Dale Johannesen245dceb2007-09-11 18:32:33 +00003196void
Neil Booth9acbf5a2007-09-26 21:33:42 +00003197APFloat::initFromFloatAPInt(const APInt & api)
3198{
Dale Johannesen245dceb2007-09-11 18:32:33 +00003199 assert(api.getBitWidth()==32);
3200 uint32_t i = (uint32_t)*api.getRawData();
Dale Johannesen918c33c2007-08-24 05:08:11 +00003201 uint32_t myexponent = (i >> 23) & 0xff;
3202 uint32_t mysignificand = i & 0x7fffff;
3203
Dale Johannesena719a602007-08-24 00:56:33 +00003204 initialize(&APFloat::IEEEsingle);
Dale Johannesena719a602007-08-24 00:56:33 +00003205 assert(partCount()==1);
3206
Dale Johannesen3cf889f2007-08-31 04:03:46 +00003207 sign = i >> 31;
Dale Johannesena719a602007-08-24 00:56:33 +00003208 if (myexponent==0 && mysignificand==0) {
3209 // exponent, significand meaningless
3210 category = fcZero;
Dale Johannesena719a602007-08-24 00:56:33 +00003211 } else if (myexponent==0xff && mysignificand==0) {
3212 // exponent, significand meaningless
3213 category = fcInfinity;
Dale Johannesen4f55d9f2007-09-25 17:25:00 +00003214 } else if (myexponent==0xff && mysignificand!=0) {
Dale Johannesena719a602007-08-24 00:56:33 +00003215 // sign, exponent, significand meaningless
Dale Johannesen3cf889f2007-08-31 04:03:46 +00003216 category = fcNaN;
3217 *significandParts() = mysignificand;
Dale Johannesena719a602007-08-24 00:56:33 +00003218 } else {
3219 category = fcNormal;
Dale Johannesena719a602007-08-24 00:56:33 +00003220 exponent = myexponent - 127; //bias
Dale Johannesen728687c2007-09-05 20:39:49 +00003221 *significandParts() = mysignificand;
3222 if (myexponent==0) // denormal
3223 exponent = -126;
3224 else
3225 *significandParts() |= 0x800000; // integer bit
Dale Johannesena719a602007-08-24 00:56:33 +00003226 }
3227}
Dale Johannesen245dceb2007-09-11 18:32:33 +00003228
Chris Lattner4794b2b2009-10-16 02:13:51 +00003229void
3230APFloat::initFromHalfAPInt(const APInt & api)
3231{
3232 assert(api.getBitWidth()==16);
3233 uint32_t i = (uint32_t)*api.getRawData();
Dale Johannesen0d670b52009-10-23 04:02:51 +00003234 uint32_t myexponent = (i >> 10) & 0x1f;
Chris Lattner4794b2b2009-10-16 02:13:51 +00003235 uint32_t mysignificand = i & 0x3ff;
3236
3237 initialize(&APFloat::IEEEhalf);
3238 assert(partCount()==1);
3239
3240 sign = i >> 15;
3241 if (myexponent==0 && mysignificand==0) {
3242 // exponent, significand meaningless
3243 category = fcZero;
3244 } else if (myexponent==0x1f && mysignificand==0) {
3245 // exponent, significand meaningless
3246 category = fcInfinity;
3247 } else if (myexponent==0x1f && mysignificand!=0) {
3248 // sign, exponent, significand meaningless
3249 category = fcNaN;
3250 *significandParts() = mysignificand;
3251 } else {
3252 category = fcNormal;
3253 exponent = myexponent - 15; //bias
3254 *significandParts() = mysignificand;
3255 if (myexponent==0) // denormal
3256 exponent = -14;
3257 else
3258 *significandParts() |= 0x400; // integer bit
3259 }
3260}
3261
Dale Johannesen245dceb2007-09-11 18:32:33 +00003262/// Treat api as containing the bits of a floating point number. Currently
Dale Johannesen007aa372007-10-11 18:07:22 +00003263/// we infer the floating point type from the size of the APInt. The
3264/// isIEEE argument distinguishes between PPC128 and IEEE128 (not meaningful
3265/// when the size is anything else).
Dale Johannesen245dceb2007-09-11 18:32:33 +00003266void
Tim Northover29178a32013-01-22 09:46:31 +00003267APFloat::initFromAPInt(const fltSemantics* Sem, const APInt& api)
Neil Booth9acbf5a2007-09-26 21:33:42 +00003268{
Tim Northover29178a32013-01-22 09:46:31 +00003269 if (Sem == &IEEEhalf)
Chris Lattner4794b2b2009-10-16 02:13:51 +00003270 return initFromHalfAPInt(api);
Tim Northover29178a32013-01-22 09:46:31 +00003271 if (Sem == &IEEEsingle)
Dale Johannesen245dceb2007-09-11 18:32:33 +00003272 return initFromFloatAPInt(api);
Tim Northover29178a32013-01-22 09:46:31 +00003273 if (Sem == &IEEEdouble)
Dale Johannesen245dceb2007-09-11 18:32:33 +00003274 return initFromDoubleAPInt(api);
Tim Northover29178a32013-01-22 09:46:31 +00003275 if (Sem == &x87DoubleExtended)
Dale Johannesen245dceb2007-09-11 18:32:33 +00003276 return initFromF80LongDoubleAPInt(api);
Tim Northover29178a32013-01-22 09:46:31 +00003277 if (Sem == &IEEEquad)
3278 return initFromQuadrupleAPInt(api);
3279 if (Sem == &PPCDoubleDouble)
3280 return initFromPPCDoubleDoubleAPInt(api);
3281
3282 llvm_unreachable(0);
Dale Johannesen245dceb2007-09-11 18:32:33 +00003283}
3284
Nadav Rotem7cc6d122011-02-17 21:22:27 +00003285APFloat
3286APFloat::getAllOnesValue(unsigned BitWidth, bool isIEEE)
3287{
Tim Northover29178a32013-01-22 09:46:31 +00003288 switch (BitWidth) {
3289 case 16:
3290 return APFloat(IEEEhalf, APInt::getAllOnesValue(BitWidth));
3291 case 32:
3292 return APFloat(IEEEsingle, APInt::getAllOnesValue(BitWidth));
3293 case 64:
3294 return APFloat(IEEEdouble, APInt::getAllOnesValue(BitWidth));
3295 case 80:
3296 return APFloat(x87DoubleExtended, APInt::getAllOnesValue(BitWidth));
3297 case 128:
3298 if (isIEEE)
3299 return APFloat(IEEEquad, APInt::getAllOnesValue(BitWidth));
3300 return APFloat(PPCDoubleDouble, APInt::getAllOnesValue(BitWidth));
3301 default:
3302 llvm_unreachable("Unknown floating bit width");
3303 }
Nadav Rotem7cc6d122011-02-17 21:22:27 +00003304}
3305
Michael Gottesman0c622ea2013-05-30 18:07:13 +00003306/// Make this number the largest magnitude normal number in the given
3307/// semantics.
3308void APFloat::makeLargest(bool Negative) {
John McCall29b5c282009-12-24 08:56:26 +00003309 // We want (in interchange format):
3310 // sign = {Negative}
3311 // exponent = 1..10
3312 // significand = 1..1
Michael Gottesman0c622ea2013-05-30 18:07:13 +00003313 category = fcNormal;
3314 sign = Negative;
3315 exponent = semantics->maxExponent;
John McCall29b5c282009-12-24 08:56:26 +00003316
Michael Gottesman0c622ea2013-05-30 18:07:13 +00003317 // Use memset to set all but the highest integerPart to all ones.
3318 integerPart *significand = significandParts();
3319 unsigned PartCount = partCount();
3320 memset(significand, 0xFF, sizeof(integerPart)*(PartCount - 1));
John McCall29b5c282009-12-24 08:56:26 +00003321
Michael Gottesman0c622ea2013-05-30 18:07:13 +00003322 // Set the high integerPart especially setting all unused top bits for
3323 // internal consistency.
3324 const unsigned NumUnusedHighBits =
3325 PartCount*integerPartWidth - semantics->precision;
3326 significand[PartCount - 1] = ~integerPart(0) >> NumUnusedHighBits;
John McCall29b5c282009-12-24 08:56:26 +00003327}
3328
Michael Gottesman0c622ea2013-05-30 18:07:13 +00003329/// Make this number the smallest magnitude denormal number in the given
3330/// semantics.
3331void APFloat::makeSmallest(bool Negative) {
John McCall29b5c282009-12-24 08:56:26 +00003332 // We want (in interchange format):
3333 // sign = {Negative}
3334 // exponent = 0..0
3335 // significand = 0..01
Michael Gottesman0c622ea2013-05-30 18:07:13 +00003336 category = fcNormal;
3337 sign = Negative;
3338 exponent = semantics->minExponent;
3339 APInt::tcSet(significandParts(), 1, partCount());
3340}
John McCall29b5c282009-12-24 08:56:26 +00003341
Michael Gottesman0c622ea2013-05-30 18:07:13 +00003342
3343APFloat APFloat::getLargest(const fltSemantics &Sem, bool Negative) {
3344 // We want (in interchange format):
3345 // sign = {Negative}
3346 // exponent = 1..10
3347 // significand = 1..1
3348 APFloat Val(Sem, uninitialized);
3349 Val.makeLargest(Negative);
3350 return Val;
3351}
3352
3353APFloat APFloat::getSmallest(const fltSemantics &Sem, bool Negative) {
3354 // We want (in interchange format):
3355 // sign = {Negative}
3356 // exponent = 0..0
3357 // significand = 0..01
3358 APFloat Val(Sem, uninitialized);
3359 Val.makeSmallest(Negative);
John McCall29b5c282009-12-24 08:56:26 +00003360 return Val;
3361}
3362
3363APFloat APFloat::getSmallestNormalized(const fltSemantics &Sem, bool Negative) {
3364 APFloat Val(Sem, fcNormal, Negative);
3365
3366 // We want (in interchange format):
3367 // sign = {Negative}
3368 // exponent = 0..0
3369 // significand = 10..0
3370
3371 Val.exponent = Sem.minExponent;
3372 Val.zeroSignificand();
Dan Gohmanb452d4e2010-03-24 19:38:02 +00003373 Val.significandParts()[partCountForBits(Sem.precision)-1] |=
Eli Friedmand4330422011-10-12 21:56:19 +00003374 (((integerPart) 1) << ((Sem.precision - 1) % integerPartWidth));
John McCall29b5c282009-12-24 08:56:26 +00003375
3376 return Val;
3377}
3378
Tim Northover29178a32013-01-22 09:46:31 +00003379APFloat::APFloat(const fltSemantics &Sem, const APInt &API) {
3380 initFromAPInt(&Sem, API);
Dale Johannesen245dceb2007-09-11 18:32:33 +00003381}
3382
Ulrich Weigande1d62f92012-10-29 18:17:42 +00003383APFloat::APFloat(float f) {
Tim Northover29178a32013-01-22 09:46:31 +00003384 initFromAPInt(&IEEEsingle, APInt::floatToBits(f));
Dale Johannesen245dceb2007-09-11 18:32:33 +00003385}
3386
Ulrich Weigande1d62f92012-10-29 18:17:42 +00003387APFloat::APFloat(double d) {
Tim Northover29178a32013-01-22 09:46:31 +00003388 initFromAPInt(&IEEEdouble, APInt::doubleToBits(d));
Dale Johannesen245dceb2007-09-11 18:32:33 +00003389}
John McCall29b5c282009-12-24 08:56:26 +00003390
3391namespace {
David Blaikie70fdf722012-07-25 18:04:24 +00003392 void append(SmallVectorImpl<char> &Buffer, StringRef Str) {
3393 Buffer.append(Str.begin(), Str.end());
John McCall29b5c282009-12-24 08:56:26 +00003394 }
3395
John McCalle6212ace2009-12-24 12:16:56 +00003396 /// Removes data from the given significand until it is no more
3397 /// precise than is required for the desired precision.
3398 void AdjustToPrecision(APInt &significand,
3399 int &exp, unsigned FormatPrecision) {
3400 unsigned bits = significand.getActiveBits();
3401
3402 // 196/59 is a very slight overestimate of lg_2(10).
3403 unsigned bitsRequired = (FormatPrecision * 196 + 58) / 59;
3404
3405 if (bits <= bitsRequired) return;
3406
3407 unsigned tensRemovable = (bits - bitsRequired) * 59 / 196;
3408 if (!tensRemovable) return;
3409
3410 exp += tensRemovable;
3411
3412 APInt divisor(significand.getBitWidth(), 1);
3413 APInt powten(significand.getBitWidth(), 10);
3414 while (true) {
3415 if (tensRemovable & 1)
3416 divisor *= powten;
3417 tensRemovable >>= 1;
3418 if (!tensRemovable) break;
3419 powten *= powten;
3420 }
3421
3422 significand = significand.udiv(divisor);
3423
Hao Liube99cc32013-03-20 01:46:36 +00003424 // Truncate the significand down to its active bit count.
3425 significand = significand.trunc(significand.getActiveBits());
John McCalle6212ace2009-12-24 12:16:56 +00003426 }
3427
3428
John McCall29b5c282009-12-24 08:56:26 +00003429 void AdjustToPrecision(SmallVectorImpl<char> &buffer,
3430 int &exp, unsigned FormatPrecision) {
3431 unsigned N = buffer.size();
3432 if (N <= FormatPrecision) return;
3433
3434 // The most significant figures are the last ones in the buffer.
3435 unsigned FirstSignificant = N - FormatPrecision;
3436
3437 // Round.
3438 // FIXME: this probably shouldn't use 'round half up'.
3439
3440 // Rounding down is just a truncation, except we also want to drop
3441 // trailing zeros from the new result.
3442 if (buffer[FirstSignificant - 1] < '5') {
NAKAMURA Takumi5adeb932012-02-19 03:18:29 +00003443 while (FirstSignificant < N && buffer[FirstSignificant] == '0')
John McCall29b5c282009-12-24 08:56:26 +00003444 FirstSignificant++;
3445
3446 exp += FirstSignificant;
3447 buffer.erase(&buffer[0], &buffer[FirstSignificant]);
3448 return;
3449 }
3450
3451 // Rounding up requires a decimal add-with-carry. If we continue
3452 // the carry, the newly-introduced zeros will just be truncated.
3453 for (unsigned I = FirstSignificant; I != N; ++I) {
3454 if (buffer[I] == '9') {
3455 FirstSignificant++;
3456 } else {
3457 buffer[I]++;
3458 break;
3459 }
3460 }
3461
3462 // If we carried through, we have exactly one digit of precision.
3463 if (FirstSignificant == N) {
3464 exp += FirstSignificant;
3465 buffer.clear();
3466 buffer.push_back('1');
3467 return;
3468 }
3469
3470 exp += FirstSignificant;
3471 buffer.erase(&buffer[0], &buffer[FirstSignificant]);
3472 }
3473}
3474
3475void APFloat::toString(SmallVectorImpl<char> &Str,
3476 unsigned FormatPrecision,
Chris Lattner4c1e4db2010-03-06 19:20:13 +00003477 unsigned FormatMaxPadding) const {
John McCall29b5c282009-12-24 08:56:26 +00003478 switch (category) {
3479 case fcInfinity:
3480 if (isNegative())
3481 return append(Str, "-Inf");
3482 else
3483 return append(Str, "+Inf");
3484
3485 case fcNaN: return append(Str, "NaN");
3486
3487 case fcZero:
3488 if (isNegative())
3489 Str.push_back('-');
3490
3491 if (!FormatMaxPadding)
3492 append(Str, "0.0E+0");
3493 else
3494 Str.push_back('0');
3495 return;
3496
3497 case fcNormal:
3498 break;
3499 }
3500
3501 if (isNegative())
3502 Str.push_back('-');
3503
3504 // Decompose the number into an APInt and an exponent.
3505 int exp = exponent - ((int) semantics->precision - 1);
3506 APInt significand(semantics->precision,
Jeffrey Yasskin7a162882011-07-18 21:45:40 +00003507 makeArrayRef(significandParts(),
3508 partCountForBits(semantics->precision)));
John McCall29b5c282009-12-24 08:56:26 +00003509
John McCalldd5044a2009-12-24 23:18:09 +00003510 // Set FormatPrecision if zero. We want to do this before we
3511 // truncate trailing zeros, as those are part of the precision.
3512 if (!FormatPrecision) {
3513 // It's an interesting question whether to use the nominal
3514 // precision or the active precision here for denormals.
3515
3516 // FormatPrecision = ceil(significandBits / lg_2(10))
3517 FormatPrecision = (semantics->precision * 59 + 195) / 196;
3518 }
3519
John McCall29b5c282009-12-24 08:56:26 +00003520 // Ignore trailing binary zeros.
3521 int trailingZeros = significand.countTrailingZeros();
3522 exp += trailingZeros;
3523 significand = significand.lshr(trailingZeros);
3524
3525 // Change the exponent from 2^e to 10^e.
3526 if (exp == 0) {
3527 // Nothing to do.
3528 } else if (exp > 0) {
3529 // Just shift left.
Jay Foad583abbc2010-12-07 08:25:19 +00003530 significand = significand.zext(semantics->precision + exp);
John McCall29b5c282009-12-24 08:56:26 +00003531 significand <<= exp;
3532 exp = 0;
3533 } else { /* exp < 0 */
3534 int texp = -exp;
3535
3536 // We transform this using the identity:
3537 // (N)(2^-e) == (N)(5^e)(10^-e)
3538 // This means we have to multiply N (the significand) by 5^e.
3539 // To avoid overflow, we have to operate on numbers large
3540 // enough to store N * 5^e:
3541 // log2(N * 5^e) == log2(N) + e * log2(5)
John McCalldd5044a2009-12-24 23:18:09 +00003542 // <= semantics->precision + e * 137 / 59
3543 // (log_2(5) ~ 2.321928 < 2.322034 ~ 137/59)
Dan Gohmanb452d4e2010-03-24 19:38:02 +00003544
Eli Friedman19546412011-10-07 23:40:49 +00003545 unsigned precision = semantics->precision + (137 * texp + 136) / 59;
John McCall29b5c282009-12-24 08:56:26 +00003546
3547 // Multiply significand by 5^e.
3548 // N * 5^0101 == N * 5^(1*1) * 5^(0*2) * 5^(1*4) * 5^(0*8)
Jay Foad583abbc2010-12-07 08:25:19 +00003549 significand = significand.zext(precision);
John McCall29b5c282009-12-24 08:56:26 +00003550 APInt five_to_the_i(precision, 5);
3551 while (true) {
3552 if (texp & 1) significand *= five_to_the_i;
Dan Gohmanb452d4e2010-03-24 19:38:02 +00003553
John McCall29b5c282009-12-24 08:56:26 +00003554 texp >>= 1;
3555 if (!texp) break;
3556 five_to_the_i *= five_to_the_i;
3557 }
3558 }
3559
John McCalle6212ace2009-12-24 12:16:56 +00003560 AdjustToPrecision(significand, exp, FormatPrecision);
3561
Dmitri Gribenko226fea52013-01-13 16:01:15 +00003562 SmallVector<char, 256> buffer;
John McCall29b5c282009-12-24 08:56:26 +00003563
3564 // Fill the buffer.
3565 unsigned precision = significand.getBitWidth();
3566 APInt ten(precision, 10);
3567 APInt digit(precision, 0);
3568
3569 bool inTrail = true;
3570 while (significand != 0) {
3571 // digit <- significand % 10
3572 // significand <- significand / 10
3573 APInt::udivrem(significand, ten, significand, digit);
3574
3575 unsigned d = digit.getZExtValue();
3576
3577 // Drop trailing zeros.
3578 if (inTrail && !d) exp++;
3579 else {
3580 buffer.push_back((char) ('0' + d));
3581 inTrail = false;
3582 }
3583 }
3584
3585 assert(!buffer.empty() && "no characters in buffer!");
3586
3587 // Drop down to FormatPrecision.
3588 // TODO: don't do more precise calculations above than are required.
3589 AdjustToPrecision(buffer, exp, FormatPrecision);
3590
3591 unsigned NDigits = buffer.size();
3592
John McCalldd5044a2009-12-24 23:18:09 +00003593 // Check whether we should use scientific notation.
John McCall29b5c282009-12-24 08:56:26 +00003594 bool FormatScientific;
3595 if (!FormatMaxPadding)
3596 FormatScientific = true;
3597 else {
John McCall29b5c282009-12-24 08:56:26 +00003598 if (exp >= 0) {
John McCalldd5044a2009-12-24 23:18:09 +00003599 // 765e3 --> 765000
3600 // ^^^
3601 // But we shouldn't make the number look more precise than it is.
3602 FormatScientific = ((unsigned) exp > FormatMaxPadding ||
3603 NDigits + (unsigned) exp > FormatPrecision);
John McCall29b5c282009-12-24 08:56:26 +00003604 } else {
John McCalldd5044a2009-12-24 23:18:09 +00003605 // Power of the most significant digit.
3606 int MSD = exp + (int) (NDigits - 1);
3607 if (MSD >= 0) {
John McCall29b5c282009-12-24 08:56:26 +00003608 // 765e-2 == 7.65
John McCalldd5044a2009-12-24 23:18:09 +00003609 FormatScientific = false;
John McCall29b5c282009-12-24 08:56:26 +00003610 } else {
3611 // 765e-5 == 0.00765
3612 // ^ ^^
John McCalldd5044a2009-12-24 23:18:09 +00003613 FormatScientific = ((unsigned) -MSD) > FormatMaxPadding;
John McCall29b5c282009-12-24 08:56:26 +00003614 }
3615 }
John McCall29b5c282009-12-24 08:56:26 +00003616 }
3617
3618 // Scientific formatting is pretty straightforward.
3619 if (FormatScientific) {
3620 exp += (NDigits - 1);
3621
3622 Str.push_back(buffer[NDigits-1]);
3623 Str.push_back('.');
3624 if (NDigits == 1)
3625 Str.push_back('0');
3626 else
3627 for (unsigned I = 1; I != NDigits; ++I)
3628 Str.push_back(buffer[NDigits-1-I]);
3629 Str.push_back('E');
3630
3631 Str.push_back(exp >= 0 ? '+' : '-');
3632 if (exp < 0) exp = -exp;
3633 SmallVector<char, 6> expbuf;
3634 do {
3635 expbuf.push_back((char) ('0' + (exp % 10)));
3636 exp /= 10;
3637 } while (exp);
3638 for (unsigned I = 0, E = expbuf.size(); I != E; ++I)
3639 Str.push_back(expbuf[E-1-I]);
3640 return;
3641 }
3642
3643 // Non-scientific, positive exponents.
3644 if (exp >= 0) {
3645 for (unsigned I = 0; I != NDigits; ++I)
3646 Str.push_back(buffer[NDigits-1-I]);
3647 for (unsigned I = 0; I != (unsigned) exp; ++I)
3648 Str.push_back('0');
3649 return;
3650 }
3651
3652 // Non-scientific, negative exponents.
3653
3654 // The number of digits to the left of the decimal point.
3655 int NWholeDigits = exp + (int) NDigits;
3656
3657 unsigned I = 0;
3658 if (NWholeDigits > 0) {
3659 for (; I != (unsigned) NWholeDigits; ++I)
3660 Str.push_back(buffer[NDigits-I-1]);
3661 Str.push_back('.');
3662 } else {
3663 unsigned NZeros = 1 + (unsigned) -NWholeDigits;
3664
3665 Str.push_back('0');
3666 Str.push_back('.');
3667 for (unsigned Z = 1; Z != NZeros; ++Z)
3668 Str.push_back('0');
3669 }
3670
3671 for (; I != NDigits; ++I)
3672 Str.push_back(buffer[NDigits-I-1]);
3673}
Benjamin Kramer03fd6722011-03-30 15:42:27 +00003674
3675bool APFloat::getExactInverse(APFloat *inv) const {
Benjamin Kramer03fd6722011-03-30 15:42:27 +00003676 // Special floats and denormals have no exact inverse.
3677 if (category != fcNormal)
3678 return false;
3679
3680 // Check that the number is a power of two by making sure that only the
3681 // integer bit is set in the significand.
3682 if (significandLSB() != semantics->precision - 1)
3683 return false;
3684
3685 // Get the inverse.
3686 APFloat reciprocal(*semantics, 1ULL);
3687 if (reciprocal.divide(*this, rmNearestTiesToEven) != opOK)
3688 return false;
3689
Benjamin Krameraf0ed952011-03-30 17:02:54 +00003690 // Avoid multiplication with a denormal, it is not safe on all platforms and
3691 // may be slower than a normal division.
Benjamin Kramer6bef24f2013-06-01 11:26:33 +00003692 if (reciprocal.isDenormal())
Benjamin Krameraf0ed952011-03-30 17:02:54 +00003693 return false;
3694
3695 assert(reciprocal.category == fcNormal &&
3696 reciprocal.significandLSB() == reciprocal.semantics->precision - 1);
3697
Benjamin Kramer03fd6722011-03-30 15:42:27 +00003698 if (inv)
3699 *inv = reciprocal;
3700
3701 return true;
3702}
Michael Gottesman0c622ea2013-05-30 18:07:13 +00003703
3704bool APFloat::isSignaling() const {
3705 if (!isNaN())
3706 return false;
3707
3708 // IEEE-754R 2008 6.2.1: A signaling NaN bit string should be encoded with the
3709 // first bit of the trailing significand being 0.
3710 return !APInt::tcExtractBit(significandParts(), semantics->precision - 2);
3711}
3712
3713/// IEEE-754R 2008 5.3.1: nextUp/nextDown.
3714///
3715/// *NOTE* since nextDown(x) = -nextUp(-x), we only implement nextUp with
3716/// appropriate sign switching before/after the computation.
3717APFloat::opStatus APFloat::next(bool nextDown) {
3718 // If we are performing nextDown, swap sign so we have -x.
3719 if (nextDown)
3720 changeSign();
3721
3722 // Compute nextUp(x)
3723 opStatus result = opOK;
3724
3725 // Handle each float category separately.
3726 switch (category) {
3727 case fcInfinity:
3728 // nextUp(+inf) = +inf
3729 if (!isNegative())
3730 break;
3731 // nextUp(-inf) = -getLargest()
3732 makeLargest(true);
3733 break;
3734 case fcNaN:
3735 // IEEE-754R 2008 6.2 Par 2: nextUp(sNaN) = qNaN. Set Invalid flag.
3736 // IEEE-754R 2008 6.2: nextUp(qNaN) = qNaN. Must be identity so we do not
3737 // change the payload.
3738 if (isSignaling()) {
3739 result = opInvalidOp;
3740 // For consistency, propogate the sign of the sNaN to the qNaN.
3741 makeNaN(false, isNegative(), 0);
3742 }
3743 break;
3744 case fcZero:
3745 // nextUp(pm 0) = +getSmallest()
3746 makeSmallest(false);
3747 break;
3748 case fcNormal:
3749 // nextUp(-getSmallest()) = -0
3750 if (isSmallest() && isNegative()) {
3751 APInt::tcSet(significandParts(), 0, partCount());
3752 category = fcZero;
3753 exponent = 0;
3754 break;
3755 }
3756
3757 // nextUp(getLargest()) == INFINITY
3758 if (isLargest() && !isNegative()) {
3759 APInt::tcSet(significandParts(), 0, partCount());
3760 category = fcInfinity;
3761 exponent = semantics->maxExponent + 1;
3762 break;
3763 }
3764
3765 // nextUp(normal) == normal + inc.
3766 if (isNegative()) {
3767 // If we are negative, we need to decrement the significand.
3768
3769 // We only cross a binade boundary that requires adjusting the exponent
3770 // if:
3771 // 1. exponent != semantics->minExponent. This implies we are not in the
3772 // smallest binade or are dealing with denormals.
3773 // 2. Our significand excluding the integral bit is all zeros.
3774 bool WillCrossBinadeBoundary =
3775 exponent != semantics->minExponent && isSignificandAllZeros();
3776
3777 // Decrement the significand.
3778 //
3779 // We always do this since:
3780 // 1. If we are dealing with a non binade decrement, by definition we
3781 // just decrement the significand.
3782 // 2. If we are dealing with a normal -> normal binade decrement, since
3783 // we have an explicit integral bit the fact that all bits but the
3784 // integral bit are zero implies that subtracting one will yield a
3785 // significand with 0 integral bit and 1 in all other spots. Thus we
3786 // must just adjust the exponent and set the integral bit to 1.
3787 // 3. If we are dealing with a normal -> denormal binade decrement,
3788 // since we set the integral bit to 0 when we represent denormals, we
3789 // just decrement the significand.
3790 integerPart *Parts = significandParts();
3791 APInt::tcDecrement(Parts, partCount());
3792
3793 if (WillCrossBinadeBoundary) {
3794 // Our result is a normal number. Do the following:
3795 // 1. Set the integral bit to 1.
3796 // 2. Decrement the exponent.
3797 APInt::tcSetBit(Parts, semantics->precision - 1);
3798 exponent--;
3799 }
3800 } else {
3801 // If we are positive, we need to increment the significand.
3802
3803 // We only cross a binade boundary that requires adjusting the exponent if
3804 // the input is not a denormal and all of said input's significand bits
3805 // are set. If all of said conditions are true: clear the significand, set
3806 // the integral bit to 1, and increment the exponent. If we have a
3807 // denormal always increment since moving denormals and the numbers in the
3808 // smallest normal binade have the same exponent in our representation.
3809 bool WillCrossBinadeBoundary = !isDenormal() && isSignificandAllOnes();
3810
3811 if (WillCrossBinadeBoundary) {
3812 integerPart *Parts = significandParts();
3813 APInt::tcSet(Parts, 0, partCount());
3814 APInt::tcSetBit(Parts, semantics->precision - 1);
3815 assert(exponent != semantics->maxExponent &&
3816 "We can not increment an exponent beyond the maxExponent allowed"
3817 " by the given floating point semantics.");
3818 exponent++;
3819 } else {
3820 incrementSignificand();
3821 }
3822 }
3823 break;
3824 }
3825
3826 // If we are performing nextDown, swap sign so we have -nextUp(-x)
3827 if (nextDown)
3828 changeSign();
3829
3830 return result;
3831}