blob: 43d009976bd7924763d607a31f3071aeb564eb7f [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. */
Benjamin Kramer7000ca32014-10-12 17:56:40 +000038static_assert(integerPartWidth % 4 == 0, "Part width must be divisible by 4!");
Chris Lattnerfe02c1f2007-08-20 22:49:32 +000039
40namespace llvm {
41
42 /* Represents floating point arithmetic semantics. */
43 struct fltSemantics {
44 /* The largest E such that 2^E is representable; this matches the
45 definition of IEEE 754. */
Michael Gottesman9dc98332013-06-24 04:06:23 +000046 APFloat::ExponentType maxExponent;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +000047
48 /* The smallest E such that 2^E is a normalized number; this
49 matches the definition of IEEE 754. */
Michael Gottesman9dc98332013-06-24 04:06:23 +000050 APFloat::ExponentType minExponent;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +000051
52 /* Number of bits in the significand. This includes the integer
53 bit. */
Neil Booth146fdb32007-10-12 15:33:27 +000054 unsigned int precision;
Tamas Berghammerb6b0ddf2015-07-09 10:13:39 +000055
56 /* Number of bits actually used in the semantics. */
57 unsigned int sizeInBits;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +000058 };
59
Tamas Berghammerb6b0ddf2015-07-09 10:13:39 +000060 const fltSemantics APFloat::IEEEhalf = { 15, -14, 11, 16 };
61 const fltSemantics APFloat::IEEEsingle = { 127, -126, 24, 32 };
62 const fltSemantics APFloat::IEEEdouble = { 1023, -1022, 53, 64 };
63 const fltSemantics APFloat::IEEEquad = { 16383, -16382, 113, 128 };
64 const fltSemantics APFloat::x87DoubleExtended = { 16383, -16382, 64, 80 };
65 const fltSemantics APFloat::Bogus = { 0, 0, 0, 0 };
Dale Johannesen007aa372007-10-11 18:07:22 +000066
Ulrich Weigandd9f7e252012-10-29 18:09:01 +000067 /* The PowerPC format consists of two doubles. It does not map cleanly
68 onto the usual format above. It is approximated using twice the
69 mantissa bits. Note that for exponents near the double minimum,
70 we no longer can represent the full 106 mantissa bits, so those
71 will be treated as denormal numbers.
72
73 FIXME: While this approximation is equivalent to what GCC uses for
74 compile-time arithmetic on PPC double-double numbers, it is not able
75 to represent all possible values held by a PPC double-double number,
76 for example: (long double) 1.0 + (long double) 0x1p-106
77 Should this be replaced by a full emulation of PPC double-double? */
Tamas Berghammerb6b0ddf2015-07-09 10:13:39 +000078 const fltSemantics APFloat::PPCDoubleDouble = { 1023, -1022 + 53, 53 + 53, 128 };
Neil Boothb93d90e2007-10-12 16:02:31 +000079
80 /* A tight upper bound on number of parts required to hold the value
81 pow(5, power) is
82
Neil Booth91305512007-10-15 15:00:55 +000083 power * 815 / (351 * integerPartWidth) + 1
Dan Gohmanb452d4e2010-03-24 19:38:02 +000084
Neil Boothb93d90e2007-10-12 16:02:31 +000085 However, whilst the result may require only this many parts,
86 because we are multiplying two values to get it, the
87 multiplication may require an extra part with the excess part
88 being zero (consider the trivial case of 1 * 1, tcFullMultiply
89 requires two parts to hold the single-part result). So we add an
90 extra one to guarantee enough space whilst multiplying. */
91 const unsigned int maxExponent = 16383;
92 const unsigned int maxPrecision = 113;
93 const unsigned int maxPowerOfFiveExponent = maxExponent + maxPrecision - 1;
Neil Booth91305512007-10-15 15:00:55 +000094 const unsigned int maxPowerOfFiveParts = 2 + ((maxPowerOfFiveExponent * 815)
95 / (351 * integerPartWidth));
Alexander Kornienkof00654e2015-06-23 09:49:53 +000096}
Chris Lattnerfe02c1f2007-08-20 22:49:32 +000097
Chris Lattner91702092009-03-12 23:59:55 +000098/* A bunch of private, handy routines. */
Chris Lattnerfe02c1f2007-08-20 22:49:32 +000099
Chris Lattner91702092009-03-12 23:59:55 +0000100static inline unsigned int
101partCountForBits(unsigned int bits)
102{
103 return ((bits) + integerPartWidth - 1) / integerPartWidth;
104}
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000105
Chris Lattner91702092009-03-12 23:59:55 +0000106/* Returns 0U-9U. Return values >= 10U are not digits. */
107static inline unsigned int
108decDigitValue(unsigned int c)
109{
110 return c - '0';
111}
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000112
Chris Lattner91702092009-03-12 23:59:55 +0000113/* Return the value of a decimal exponent of the form
114 [+-]ddddddd.
Neil Booth4ed401b2007-10-14 10:16:12 +0000115
Chris Lattner91702092009-03-12 23:59:55 +0000116 If the exponent overflows, returns a large exponent with the
117 appropriate sign. */
118static int
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000119readExponent(StringRef::iterator begin, StringRef::iterator end)
Chris Lattner91702092009-03-12 23:59:55 +0000120{
121 bool isNegative;
122 unsigned int absExponent;
123 const unsigned int overlargeExponent = 24000; /* FIXME. */
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000124 StringRef::iterator p = begin;
125
126 assert(p != end && "Exponent has no digits");
Neil Booth4ed401b2007-10-14 10:16:12 +0000127
Chris Lattner91702092009-03-12 23:59:55 +0000128 isNegative = (*p == '-');
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000129 if (*p == '-' || *p == '+') {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000130 p++;
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000131 assert(p != end && "Exponent has no digits");
132 }
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000133
Chris Lattner91702092009-03-12 23:59:55 +0000134 absExponent = decDigitValue(*p++);
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000135 assert(absExponent < 10U && "Invalid character in exponent");
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000136
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000137 for (; p != end; ++p) {
Chris Lattner91702092009-03-12 23:59:55 +0000138 unsigned int value;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000139
Chris Lattner91702092009-03-12 23:59:55 +0000140 value = decDigitValue(*p);
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000141 assert(value < 10U && "Invalid character in exponent");
Chris Lattner91702092009-03-12 23:59:55 +0000142
Chris Lattner91702092009-03-12 23:59:55 +0000143 value += absExponent * 10;
144 if (absExponent >= overlargeExponent) {
145 absExponent = overlargeExponent;
Dale Johannesen370c77c2010-08-19 17:58:35 +0000146 p = end; /* outwit assert below */
Chris Lattner91702092009-03-12 23:59:55 +0000147 break;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000148 }
Chris Lattner91702092009-03-12 23:59:55 +0000149 absExponent = value;
150 }
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000151
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000152 assert(p == end && "Invalid exponent in exponent");
153
Chris Lattner91702092009-03-12 23:59:55 +0000154 if (isNegative)
155 return -(int) absExponent;
156 else
157 return (int) absExponent;
158}
159
160/* This is ugly and needs cleaning up, but I don't immediately see
161 how whilst remaining safe. */
162static int
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000163totalExponent(StringRef::iterator p, StringRef::iterator end,
164 int exponentAdjustment)
Chris Lattner91702092009-03-12 23:59:55 +0000165{
166 int unsignedExponent;
167 bool negative, overflow;
Ted Kremenek3c4408c2011-01-23 17:05:06 +0000168 int exponent = 0;
Chris Lattner91702092009-03-12 23:59:55 +0000169
Erick Tryzelaarda666c82009-08-20 23:30:43 +0000170 assert(p != end && "Exponent has no digits");
171
Chris Lattner91702092009-03-12 23:59:55 +0000172 negative = *p == '-';
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000173 if (*p == '-' || *p == '+') {
Chris Lattner91702092009-03-12 23:59:55 +0000174 p++;
Erick Tryzelaarda666c82009-08-20 23:30:43 +0000175 assert(p != end && "Exponent has no digits");
176 }
Chris Lattner91702092009-03-12 23:59:55 +0000177
178 unsignedExponent = 0;
179 overflow = false;
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000180 for (; p != end; ++p) {
Chris Lattner91702092009-03-12 23:59:55 +0000181 unsigned int value;
182
183 value = decDigitValue(*p);
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000184 assert(value < 10U && "Invalid character in exponent");
Chris Lattner91702092009-03-12 23:59:55 +0000185
Chris Lattner91702092009-03-12 23:59:55 +0000186 unsignedExponent = unsignedExponent * 10 + value;
Richard Smith156d9202012-08-24 00:01:19 +0000187 if (unsignedExponent > 32767) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000188 overflow = true;
Richard Smith156d9202012-08-24 00:01:19 +0000189 break;
190 }
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000191 }
192
Abramo Bagnaraa41d7ae2011-01-06 16:55:14 +0000193 if (exponentAdjustment > 32767 || exponentAdjustment < -32768)
Chris Lattner91702092009-03-12 23:59:55 +0000194 overflow = true;
195
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000196 if (!overflow) {
Chris Lattner91702092009-03-12 23:59:55 +0000197 exponent = unsignedExponent;
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000198 if (negative)
Chris Lattner91702092009-03-12 23:59:55 +0000199 exponent = -exponent;
200 exponent += exponentAdjustment;
Abramo Bagnaraa41d7ae2011-01-06 16:55:14 +0000201 if (exponent > 32767 || exponent < -32768)
Chris Lattner91702092009-03-12 23:59:55 +0000202 overflow = true;
203 }
204
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000205 if (overflow)
Abramo Bagnaraa41d7ae2011-01-06 16:55:14 +0000206 exponent = negative ? -32768: 32767;
Chris Lattner91702092009-03-12 23:59:55 +0000207
208 return exponent;
209}
210
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000211static StringRef::iterator
212skipLeadingZeroesAndAnyDot(StringRef::iterator begin, StringRef::iterator end,
213 StringRef::iterator *dot)
Chris Lattner91702092009-03-12 23:59:55 +0000214{
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000215 StringRef::iterator p = begin;
216 *dot = end;
Nick Lewycky095b92e2014-09-06 01:16:42 +0000217 while (p != end && *p == '0')
Chris Lattner91702092009-03-12 23:59:55 +0000218 p++;
219
Nick Lewycky095b92e2014-09-06 01:16:42 +0000220 if (p != end && *p == '.') {
Chris Lattner91702092009-03-12 23:59:55 +0000221 *dot = p++;
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000222
Erick Tryzelaarda666c82009-08-20 23:30:43 +0000223 assert(end - begin != 1 && "Significand has no digits");
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000224
Nick Lewycky095b92e2014-09-06 01:16:42 +0000225 while (p != end && *p == '0')
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000226 p++;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000227 }
228
Chris Lattner91702092009-03-12 23:59:55 +0000229 return p;
230}
Neil Booth4ed401b2007-10-14 10:16:12 +0000231
Chris Lattner91702092009-03-12 23:59:55 +0000232/* Given a normal decimal floating point number of the form
Neil Booth4ed401b2007-10-14 10:16:12 +0000233
Chris Lattner91702092009-03-12 23:59:55 +0000234 dddd.dddd[eE][+-]ddd
Neil Booth91305512007-10-15 15:00:55 +0000235
Chris Lattner91702092009-03-12 23:59:55 +0000236 where the decimal point and exponent are optional, fill out the
237 structure D. Exponent is appropriate if the significand is
238 treated as an integer, and normalizedExponent if the significand
239 is taken to have the decimal point after a single leading
240 non-zero digit.
Neil Booth4ed401b2007-10-14 10:16:12 +0000241
Chris Lattner91702092009-03-12 23:59:55 +0000242 If the value is zero, V->firstSigDigit points to a non-digit, and
243 the return exponent is zero.
244*/
245struct decimalInfo {
246 const char *firstSigDigit;
247 const char *lastSigDigit;
248 int exponent;
249 int normalizedExponent;
250};
Neil Booth4ed401b2007-10-14 10:16:12 +0000251
Chris Lattner91702092009-03-12 23:59:55 +0000252static void
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000253interpretDecimal(StringRef::iterator begin, StringRef::iterator end,
254 decimalInfo *D)
Chris Lattner91702092009-03-12 23:59:55 +0000255{
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000256 StringRef::iterator dot = end;
257 StringRef::iterator p = skipLeadingZeroesAndAnyDot (begin, end, &dot);
Neil Booth4ed401b2007-10-14 10:16:12 +0000258
Chris Lattner91702092009-03-12 23:59:55 +0000259 D->firstSigDigit = p;
260 D->exponent = 0;
261 D->normalizedExponent = 0;
262
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000263 for (; p != end; ++p) {
Chris Lattner91702092009-03-12 23:59:55 +0000264 if (*p == '.') {
Erick Tryzelaarda666c82009-08-20 23:30:43 +0000265 assert(dot == end && "String contains multiple dots");
Chris Lattner91702092009-03-12 23:59:55 +0000266 dot = p++;
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000267 if (p == end)
268 break;
Neil Booth4ed401b2007-10-14 10:16:12 +0000269 }
Chris Lattner91702092009-03-12 23:59:55 +0000270 if (decDigitValue(*p) >= 10U)
271 break;
Chris Lattner91702092009-03-12 23:59:55 +0000272 }
Neil Booth4ed401b2007-10-14 10:16:12 +0000273
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000274 if (p != end) {
Erick Tryzelaarda666c82009-08-20 23:30:43 +0000275 assert((*p == 'e' || *p == 'E') && "Invalid character in significand");
276 assert(p != begin && "Significand has no digits");
277 assert((dot == end || p - begin != 1) && "Significand has no digits");
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000278
279 /* p points to the first non-digit in the string */
Erick Tryzelaarda666c82009-08-20 23:30:43 +0000280 D->exponent = readExponent(p + 1, end);
Neil Booth4ed401b2007-10-14 10:16:12 +0000281
Chris Lattner91702092009-03-12 23:59:55 +0000282 /* Implied decimal point? */
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000283 if (dot == end)
Chris Lattner91702092009-03-12 23:59:55 +0000284 dot = p;
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000285 }
Neil Booth4ed401b2007-10-14 10:16:12 +0000286
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000287 /* If number is all zeroes accept any exponent. */
288 if (p != D->firstSigDigit) {
Chris Lattner91702092009-03-12 23:59:55 +0000289 /* Drop insignificant trailing zeroes. */
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000290 if (p != begin) {
Neil Booth4ed401b2007-10-14 10:16:12 +0000291 do
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000292 do
293 p--;
294 while (p != begin && *p == '0');
295 while (p != begin && *p == '.');
296 }
Neil Booth4ed401b2007-10-14 10:16:12 +0000297
Chris Lattner91702092009-03-12 23:59:55 +0000298 /* Adjust the exponents for any decimal point. */
Michael Gottesman9dc98332013-06-24 04:06:23 +0000299 D->exponent += static_cast<APFloat::ExponentType>((dot - p) - (dot > p));
Chris Lattner91702092009-03-12 23:59:55 +0000300 D->normalizedExponent = (D->exponent +
Michael Gottesman9dc98332013-06-24 04:06:23 +0000301 static_cast<APFloat::ExponentType>((p - D->firstSigDigit)
Chris Lattner91702092009-03-12 23:59:55 +0000302 - (dot > D->firstSigDigit && dot < p)));
Neil Booth4ed401b2007-10-14 10:16:12 +0000303 }
304
Chris Lattner91702092009-03-12 23:59:55 +0000305 D->lastSigDigit = p;
306}
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000307
Chris Lattner91702092009-03-12 23:59:55 +0000308/* Return the trailing fraction of a hexadecimal number.
309 DIGITVALUE is the first hex digit of the fraction, P points to
310 the next digit. */
311static lostFraction
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000312trailingHexadecimalFraction(StringRef::iterator p, StringRef::iterator end,
313 unsigned int digitValue)
Chris Lattner91702092009-03-12 23:59:55 +0000314{
315 unsigned int hexDigit;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000316
Chris Lattner91702092009-03-12 23:59:55 +0000317 /* If the first trailing digit isn't 0 or 8 we can work out the
318 fraction immediately. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000319 if (digitValue > 8)
Chris Lattner91702092009-03-12 23:59:55 +0000320 return lfMoreThanHalf;
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000321 else if (digitValue < 8 && digitValue > 0)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000322 return lfLessThanHalf;
Chris Lattner91702092009-03-12 23:59:55 +0000323
Eli Friedmand2eb07a2013-07-17 22:17:29 +0000324 // Otherwise we need to find the first non-zero digit.
325 while (p != end && (*p == '0' || *p == '.'))
Chris Lattner91702092009-03-12 23:59:55 +0000326 p++;
327
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000328 assert(p != end && "Invalid trailing hexadecimal fraction!");
329
Chris Lattner91702092009-03-12 23:59:55 +0000330 hexDigit = hexDigitValue(*p);
331
332 /* If we ran off the end it is exactly zero or one-half, otherwise
333 a little more. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000334 if (hexDigit == -1U)
Chris Lattner91702092009-03-12 23:59:55 +0000335 return digitValue == 0 ? lfExactlyZero: lfExactlyHalf;
336 else
337 return digitValue == 0 ? lfLessThanHalf: lfMoreThanHalf;
338}
339
340/* Return the fraction lost were a bignum truncated losing the least
341 significant BITS bits. */
342static lostFraction
343lostFractionThroughTruncation(const integerPart *parts,
344 unsigned int partCount,
345 unsigned int bits)
346{
347 unsigned int lsb;
348
349 lsb = APInt::tcLSB(parts, partCount);
350
351 /* Note this is guaranteed true if bits == 0, or LSB == -1U. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000352 if (bits <= lsb)
Chris Lattner91702092009-03-12 23:59:55 +0000353 return lfExactlyZero;
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000354 if (bits == lsb + 1)
Chris Lattner91702092009-03-12 23:59:55 +0000355 return lfExactlyHalf;
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000356 if (bits <= partCount * integerPartWidth &&
357 APInt::tcExtractBit(parts, bits - 1))
Chris Lattner91702092009-03-12 23:59:55 +0000358 return lfMoreThanHalf;
359
360 return lfLessThanHalf;
361}
362
363/* Shift DST right BITS bits noting lost fraction. */
364static lostFraction
365shiftRight(integerPart *dst, unsigned int parts, unsigned int bits)
366{
367 lostFraction lost_fraction;
368
369 lost_fraction = lostFractionThroughTruncation(dst, parts, bits);
370
371 APInt::tcShiftRight(dst, parts, bits);
372
373 return lost_fraction;
374}
375
376/* Combine the effect of two lost fractions. */
377static lostFraction
378combineLostFractions(lostFraction moreSignificant,
379 lostFraction lessSignificant)
380{
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000381 if (lessSignificant != lfExactlyZero) {
382 if (moreSignificant == lfExactlyZero)
Chris Lattner91702092009-03-12 23:59:55 +0000383 moreSignificant = lfLessThanHalf;
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000384 else if (moreSignificant == lfExactlyHalf)
Chris Lattner91702092009-03-12 23:59:55 +0000385 moreSignificant = lfMoreThanHalf;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000386 }
387
Chris Lattner91702092009-03-12 23:59:55 +0000388 return moreSignificant;
389}
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000390
Chris Lattner91702092009-03-12 23:59:55 +0000391/* The error from the true value, in half-ulps, on multiplying two
392 floating point numbers, which differ from the value they
393 approximate by at most HUE1 and HUE2 half-ulps, is strictly less
394 than the returned value.
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000395
Chris Lattner91702092009-03-12 23:59:55 +0000396 See "How to Read Floating Point Numbers Accurately" by William D
397 Clinger. */
398static unsigned int
399HUerrBound(bool inexactMultiply, unsigned int HUerr1, unsigned int HUerr2)
400{
401 assert(HUerr1 < 2 || HUerr2 < 2 || (HUerr1 + HUerr2 < 8));
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000402
Chris Lattner91702092009-03-12 23:59:55 +0000403 if (HUerr1 + HUerr2 == 0)
404 return inexactMultiply * 2; /* <= inexactMultiply half-ulps. */
405 else
406 return inexactMultiply + 2 * (HUerr1 + HUerr2);
407}
Neil Booth8f1946f2007-10-03 22:26:02 +0000408
Chris Lattner91702092009-03-12 23:59:55 +0000409/* The number of ulps from the boundary (zero, or half if ISNEAREST)
410 when the least significant BITS are truncated. BITS cannot be
411 zero. */
412static integerPart
413ulpsFromBoundary(const integerPart *parts, unsigned int bits, bool isNearest)
414{
415 unsigned int count, partBits;
416 integerPart part, boundary;
Neil Boothd3985922007-10-07 08:51:21 +0000417
Evan Cheng67c90212009-10-27 21:35:42 +0000418 assert(bits != 0);
Neil Booth8f1946f2007-10-03 22:26:02 +0000419
Chris Lattner91702092009-03-12 23:59:55 +0000420 bits--;
421 count = bits / integerPartWidth;
422 partBits = bits % integerPartWidth + 1;
Neil Boothb93d90e2007-10-12 16:02:31 +0000423
Chris Lattner91702092009-03-12 23:59:55 +0000424 part = parts[count] & (~(integerPart) 0 >> (integerPartWidth - partBits));
Neil Boothb93d90e2007-10-12 16:02:31 +0000425
Chris Lattner91702092009-03-12 23:59:55 +0000426 if (isNearest)
427 boundary = (integerPart) 1 << (partBits - 1);
428 else
429 boundary = 0;
430
431 if (count == 0) {
432 if (part - boundary <= boundary - part)
433 return part - boundary;
Neil Boothb93d90e2007-10-12 16:02:31 +0000434 else
Chris Lattner91702092009-03-12 23:59:55 +0000435 return boundary - part;
Neil Boothb93d90e2007-10-12 16:02:31 +0000436 }
437
Chris Lattner91702092009-03-12 23:59:55 +0000438 if (part == boundary) {
439 while (--count)
440 if (parts[count])
441 return ~(integerPart) 0; /* A lot. */
Neil Boothb93d90e2007-10-12 16:02:31 +0000442
Chris Lattner91702092009-03-12 23:59:55 +0000443 return parts[0];
444 } else if (part == boundary - 1) {
445 while (--count)
446 if (~parts[count])
447 return ~(integerPart) 0; /* A lot. */
Neil Boothb93d90e2007-10-12 16:02:31 +0000448
Chris Lattner91702092009-03-12 23:59:55 +0000449 return -parts[0];
450 }
Neil Boothb93d90e2007-10-12 16:02:31 +0000451
Chris Lattner91702092009-03-12 23:59:55 +0000452 return ~(integerPart) 0; /* A lot. */
453}
Neil Boothb93d90e2007-10-12 16:02:31 +0000454
Chris Lattner91702092009-03-12 23:59:55 +0000455/* Place pow(5, power) in DST, and return the number of parts used.
456 DST must be at least one part larger than size of the answer. */
457static unsigned int
458powerOf5(integerPart *dst, unsigned int power)
459{
460 static const integerPart firstEightPowers[] = { 1, 5, 25, 125, 625, 3125,
461 15625, 78125 };
Chris Lattnerb858c0e2009-03-13 00:24:01 +0000462 integerPart pow5s[maxPowerOfFiveParts * 2 + 5];
463 pow5s[0] = 78125 * 5;
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000464
Chris Lattner0bf18692009-03-13 00:03:51 +0000465 unsigned int partsCount[16] = { 1 };
Chris Lattner91702092009-03-12 23:59:55 +0000466 integerPart scratch[maxPowerOfFiveParts], *p1, *p2, *pow5;
467 unsigned int result;
Chris Lattner91702092009-03-12 23:59:55 +0000468 assert(power <= maxExponent);
469
470 p1 = dst;
471 p2 = scratch;
472
473 *p1 = firstEightPowers[power & 7];
474 power >>= 3;
475
476 result = 1;
477 pow5 = pow5s;
478
479 for (unsigned int n = 0; power; power >>= 1, n++) {
480 unsigned int pc;
481
482 pc = partsCount[n];
483
484 /* Calculate pow(5,pow(2,n+3)) if we haven't yet. */
485 if (pc == 0) {
486 pc = partsCount[n - 1];
487 APInt::tcFullMultiply(pow5, pow5 - pc, pow5 - pc, pc, pc);
488 pc *= 2;
489 if (pow5[pc - 1] == 0)
490 pc--;
491 partsCount[n] = pc;
Neil Boothb93d90e2007-10-12 16:02:31 +0000492 }
493
Chris Lattner91702092009-03-12 23:59:55 +0000494 if (power & 1) {
495 integerPart *tmp;
Neil Boothb93d90e2007-10-12 16:02:31 +0000496
Chris Lattner91702092009-03-12 23:59:55 +0000497 APInt::tcFullMultiply(p2, p1, pow5, result, pc);
498 result += pc;
499 if (p2[result - 1] == 0)
500 result--;
Neil Boothb93d90e2007-10-12 16:02:31 +0000501
Chris Lattner91702092009-03-12 23:59:55 +0000502 /* Now result is in p1 with partsCount parts and p2 is scratch
503 space. */
504 tmp = p1, p1 = p2, p2 = tmp;
Neil Boothb93d90e2007-10-12 16:02:31 +0000505 }
506
Chris Lattner91702092009-03-12 23:59:55 +0000507 pow5 += pc;
Neil Boothb93d90e2007-10-12 16:02:31 +0000508 }
509
Chris Lattner91702092009-03-12 23:59:55 +0000510 if (p1 != dst)
511 APInt::tcAssign(dst, p1, result);
Neil Boothb93d90e2007-10-12 16:02:31 +0000512
Chris Lattner91702092009-03-12 23:59:55 +0000513 return result;
514}
Neil Boothb93d90e2007-10-12 16:02:31 +0000515
Chris Lattner91702092009-03-12 23:59:55 +0000516/* Zero at the end to avoid modular arithmetic when adding one; used
517 when rounding up during hexadecimal output. */
518static const char hexDigitsLower[] = "0123456789abcdef0";
519static const char hexDigitsUpper[] = "0123456789ABCDEF0";
520static const char infinityL[] = "infinity";
521static const char infinityU[] = "INFINITY";
522static const char NaNL[] = "nan";
523static const char NaNU[] = "NAN";
Neil Boothb93d90e2007-10-12 16:02:31 +0000524
Chris Lattner91702092009-03-12 23:59:55 +0000525/* Write out an integerPart in hexadecimal, starting with the most
526 significant nibble. Write out exactly COUNT hexdigits, return
527 COUNT. */
528static unsigned int
529partAsHex (char *dst, integerPart part, unsigned int count,
530 const char *hexDigitChars)
531{
532 unsigned int result = count;
Neil Boothb93d90e2007-10-12 16:02:31 +0000533
Evan Cheng67c90212009-10-27 21:35:42 +0000534 assert(count != 0 && count <= integerPartWidth / 4);
Neil Boothb93d90e2007-10-12 16:02:31 +0000535
Chris Lattner91702092009-03-12 23:59:55 +0000536 part >>= (integerPartWidth - 4 * count);
537 while (count--) {
538 dst[count] = hexDigitChars[part & 0xf];
539 part >>= 4;
Neil Boothb93d90e2007-10-12 16:02:31 +0000540 }
541
Chris Lattner91702092009-03-12 23:59:55 +0000542 return result;
543}
Neil Booth8f1946f2007-10-03 22:26:02 +0000544
Chris Lattner91702092009-03-12 23:59:55 +0000545/* Write out an unsigned decimal integer. */
546static char *
547writeUnsignedDecimal (char *dst, unsigned int n)
548{
549 char buff[40], *p;
Neil Booth8f1946f2007-10-03 22:26:02 +0000550
Chris Lattner91702092009-03-12 23:59:55 +0000551 p = buff;
552 do
553 *p++ = '0' + n % 10;
554 while (n /= 10);
Neil Booth8f1946f2007-10-03 22:26:02 +0000555
Chris Lattner91702092009-03-12 23:59:55 +0000556 do
557 *dst++ = *--p;
558 while (p != buff);
Neil Booth8f1946f2007-10-03 22:26:02 +0000559
Chris Lattner91702092009-03-12 23:59:55 +0000560 return dst;
561}
Neil Booth8f1946f2007-10-03 22:26:02 +0000562
Chris Lattner91702092009-03-12 23:59:55 +0000563/* Write out a signed decimal integer. */
564static char *
565writeSignedDecimal (char *dst, int value)
566{
567 if (value < 0) {
568 *dst++ = '-';
569 dst = writeUnsignedDecimal(dst, -(unsigned) value);
570 } else
571 dst = writeUnsignedDecimal(dst, value);
Neil Booth8f1946f2007-10-03 22:26:02 +0000572
Chris Lattner91702092009-03-12 23:59:55 +0000573 return dst;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000574}
575
576/* Constructors. */
577void
578APFloat::initialize(const fltSemantics *ourSemantics)
579{
580 unsigned int count;
581
582 semantics = ourSemantics;
583 count = partCount();
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000584 if (count > 1)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000585 significand.parts = new integerPart[count];
586}
587
588void
589APFloat::freeSignificand()
590{
Manuel Klimekd0cf5b22013-06-03 13:03:05 +0000591 if (needsCleanup())
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000592 delete [] significand.parts;
593}
594
595void
596APFloat::assign(const APFloat &rhs)
597{
598 assert(semantics == rhs.semantics);
599
600 sign = rhs.sign;
601 category = rhs.category;
602 exponent = rhs.exponent;
Michael Gottesman8136c382013-06-26 23:17:28 +0000603 if (isFiniteNonZero() || category == fcNaN)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000604 copySignificand(rhs);
605}
606
607void
608APFloat::copySignificand(const APFloat &rhs)
609{
Michael Gottesman8136c382013-06-26 23:17:28 +0000610 assert(isFiniteNonZero() || category == fcNaN);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000611 assert(rhs.partCount() >= partCount());
612
613 APInt::tcAssign(significandParts(), rhs.significandParts(),
Neil Booth9acbf5a2007-09-26 21:33:42 +0000614 partCount());
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000615}
616
Neil Booth5fe658b2007-10-14 10:39:51 +0000617/* Make this number a NaN, with an arbitrary but deterministic value
Dale Johannesen1f864982009-01-21 20:32:55 +0000618 for the significand. If double or longer, this is a signalling NaN,
Mike Stump799bf582009-05-30 03:49:43 +0000619 which may not be ideal. If float, this is QNaN(0). */
John McCalldcb9a7a2010-02-28 02:51:25 +0000620void APFloat::makeNaN(bool SNaN, bool Negative, const APInt *fill)
Neil Booth5fe658b2007-10-14 10:39:51 +0000621{
622 category = fcNaN;
John McCalldcb9a7a2010-02-28 02:51:25 +0000623 sign = Negative;
624
John McCallc12b1332010-02-28 12:49:50 +0000625 integerPart *significand = significandParts();
626 unsigned numParts = partCount();
627
John McCalldcb9a7a2010-02-28 02:51:25 +0000628 // Set the significand bits to the fill.
John McCallc12b1332010-02-28 12:49:50 +0000629 if (!fill || fill->getNumWords() < numParts)
630 APInt::tcSet(significand, 0, numParts);
631 if (fill) {
John McCallc6dbe302010-03-01 18:38:45 +0000632 APInt::tcAssign(significand, fill->getRawData(),
633 std::min(fill->getNumWords(), numParts));
John McCallc12b1332010-02-28 12:49:50 +0000634
635 // Zero out the excess bits of the significand.
636 unsigned bitsToPreserve = semantics->precision - 1;
637 unsigned part = bitsToPreserve / 64;
638 bitsToPreserve %= 64;
639 significand[part] &= ((1ULL << bitsToPreserve) - 1);
640 for (part++; part != numParts; ++part)
641 significand[part] = 0;
642 }
643
644 unsigned QNaNBit = semantics->precision - 2;
John McCalldcb9a7a2010-02-28 02:51:25 +0000645
646 if (SNaN) {
647 // We always have to clear the QNaN bit to make it an SNaN.
John McCallc12b1332010-02-28 12:49:50 +0000648 APInt::tcClearBit(significand, QNaNBit);
John McCalldcb9a7a2010-02-28 02:51:25 +0000649
650 // If there are no bits set in the payload, we have to set
651 // *something* to make it a NaN instead of an infinity;
652 // conventionally, this is the next bit down from the QNaN bit.
John McCallc12b1332010-02-28 12:49:50 +0000653 if (APInt::tcIsZero(significand, numParts))
654 APInt::tcSetBit(significand, QNaNBit - 1);
John McCalldcb9a7a2010-02-28 02:51:25 +0000655 } else {
656 // We always have to set the QNaN bit to make it a QNaN.
John McCallc12b1332010-02-28 12:49:50 +0000657 APInt::tcSetBit(significand, QNaNBit);
John McCalldcb9a7a2010-02-28 02:51:25 +0000658 }
John McCallc12b1332010-02-28 12:49:50 +0000659
660 // For x87 extended precision, we want to make a NaN, not a
661 // pseudo-NaN. Maybe we should expose the ability to make
662 // pseudo-NaNs?
663 if (semantics == &APFloat::x87DoubleExtended)
664 APInt::tcSetBit(significand, QNaNBit + 1);
John McCalldcb9a7a2010-02-28 02:51:25 +0000665}
666
667APFloat APFloat::makeNaN(const fltSemantics &Sem, bool SNaN, bool Negative,
668 const APInt *fill) {
669 APFloat value(Sem, uninitialized);
670 value.makeNaN(SNaN, Negative, fill);
671 return value;
Neil Booth5fe658b2007-10-14 10:39:51 +0000672}
673
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000674APFloat &
675APFloat::operator=(const APFloat &rhs)
676{
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000677 if (this != &rhs) {
678 if (semantics != rhs.semantics) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000679 freeSignificand();
680 initialize(rhs.semantics);
681 }
682 assign(rhs);
683 }
684
685 return *this;
686}
687
Benjamin Kramer06f47782014-03-04 20:26:51 +0000688APFloat &
689APFloat::operator=(APFloat &&rhs) {
690 freeSignificand();
691
692 semantics = rhs.semantics;
693 significand = rhs.significand;
694 exponent = rhs.exponent;
695 category = rhs.category;
696 sign = rhs.sign;
697
698 rhs.semantics = &Bogus;
699 return *this;
700}
701
Dale Johannesena719a602007-08-24 00:56:33 +0000702bool
Shuxin Yang4fb504f2013-01-07 18:59:35 +0000703APFloat::isDenormal() const {
Michael Gottesman3cb77ab2013-06-19 21:23:18 +0000704 return isFiniteNonZero() && (exponent == semantics->minExponent) &&
Shuxin Yang4fb504f2013-01-07 18:59:35 +0000705 (APInt::tcExtractBit(significandParts(),
706 semantics->precision - 1) == 0);
707}
708
709bool
Michael Gottesman0c622ea2013-05-30 18:07:13 +0000710APFloat::isSmallest() const {
711 // The smallest number by magnitude in our format will be the smallest
Michael Gottesmana7cc1242013-06-19 07:34:21 +0000712 // denormal, i.e. the floating point number with exponent being minimum
Michael Gottesman0c622ea2013-05-30 18:07:13 +0000713 // exponent and significand bitwise equal to 1 (i.e. with MSB equal to 0).
Michael Gottesman3cb77ab2013-06-19 21:23:18 +0000714 return isFiniteNonZero() && exponent == semantics->minExponent &&
Michael Gottesman0c622ea2013-05-30 18:07:13 +0000715 significandMSB() == 0;
716}
717
718bool APFloat::isSignificandAllOnes() const {
719 // Test if the significand excluding the integral bit is all ones. This allows
720 // us to test for binade boundaries.
721 const integerPart *Parts = significandParts();
722 const unsigned PartCount = partCount();
723 for (unsigned i = 0; i < PartCount - 1; i++)
724 if (~Parts[i])
725 return false;
726
727 // Set the unused high bits to all ones when we compare.
728 const unsigned NumHighBits =
729 PartCount*integerPartWidth - semantics->precision + 1;
730 assert(NumHighBits <= integerPartWidth && "Can not have more high bits to "
731 "fill than integerPartWidth");
732 const integerPart HighBitFill =
733 ~integerPart(0) << (integerPartWidth - NumHighBits);
734 if (~(Parts[PartCount - 1] | HighBitFill))
735 return false;
736
737 return true;
738}
739
740bool APFloat::isSignificandAllZeros() const {
741 // Test if the significand excluding the integral bit is all zeros. This
742 // allows us to test for binade boundaries.
743 const integerPart *Parts = significandParts();
744 const unsigned PartCount = partCount();
745
746 for (unsigned i = 0; i < PartCount - 1; i++)
747 if (Parts[i])
748 return false;
749
750 const unsigned NumHighBits =
751 PartCount*integerPartWidth - semantics->precision + 1;
752 assert(NumHighBits <= integerPartWidth && "Can not have more high bits to "
753 "clear than integerPartWidth");
754 const integerPart HighBitMask = ~integerPart(0) >> NumHighBits;
755
756 if (Parts[PartCount - 1] & HighBitMask)
757 return false;
758
759 return true;
760}
761
762bool
763APFloat::isLargest() const {
764 // The largest number by magnitude in our format will be the floating point
765 // number with maximum exponent and with significand that is all ones.
Michael Gottesman3cb77ab2013-06-19 21:23:18 +0000766 return isFiniteNonZero() && exponent == semantics->maxExponent
Michael Gottesman0c622ea2013-05-30 18:07:13 +0000767 && isSignificandAllOnes();
768}
769
770bool
Dale Johannesenbdea32d2007-08-24 22:09:56 +0000771APFloat::bitwiseIsEqual(const APFloat &rhs) const {
Dale Johannesena719a602007-08-24 00:56:33 +0000772 if (this == &rhs)
773 return true;
774 if (semantics != rhs.semantics ||
Dale Johannesen3cf889f2007-08-31 04:03:46 +0000775 category != rhs.category ||
776 sign != rhs.sign)
Dale Johannesena719a602007-08-24 00:56:33 +0000777 return false;
Dale Johannesen3cf889f2007-08-31 04:03:46 +0000778 if (category==fcZero || category==fcInfinity)
Dale Johannesena719a602007-08-24 00:56:33 +0000779 return true;
Benjamin Kramer103fc942015-08-21 16:44:52 +0000780
781 if (isFiniteNonZero() && exponent != rhs.exponent)
Dale Johannesen3cf889f2007-08-31 04:03:46 +0000782 return false;
Benjamin Kramer103fc942015-08-21 16:44:52 +0000783
784 return std::equal(significandParts(), significandParts() + partCount(),
785 rhs.significandParts());
Dale Johannesena719a602007-08-24 00:56:33 +0000786}
787
Ulrich Weigande1d62f92012-10-29 18:17:42 +0000788APFloat::APFloat(const fltSemantics &ourSemantics, integerPart value) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000789 initialize(&ourSemantics);
790 sign = 0;
Michael Gottesman30a90eb2013-07-27 21:49:21 +0000791 category = fcNormal;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000792 zeroSignificand();
793 exponent = ourSemantics.precision - 1;
794 significandParts()[0] = value;
795 normalize(rmNearestTiesToEven, lfExactlyZero);
796}
797
Ulrich Weigande1d62f92012-10-29 18:17:42 +0000798APFloat::APFloat(const fltSemantics &ourSemantics) {
Chris Lattnerac6271e2009-09-17 01:08:43 +0000799 initialize(&ourSemantics);
800 category = fcZero;
801 sign = false;
802}
803
Ulrich Weigande1d62f92012-10-29 18:17:42 +0000804APFloat::APFloat(const fltSemantics &ourSemantics, uninitializedTag tag) {
John McCalldcb9a7a2010-02-28 02:51:25 +0000805 // Allocates storage if necessary but does not initialize it.
806 initialize(&ourSemantics);
807}
Chris Lattnerac6271e2009-09-17 01:08:43 +0000808
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
Benjamin Kramer06f47782014-03-04 20:26:51 +0000819APFloat::APFloat(APFloat &&rhs) : semantics(&Bogus) {
820 *this = std::move(rhs);
821}
822
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000823APFloat::~APFloat()
824{
825 freeSignificand();
826}
827
Ted Kremenek6f30a072008-02-11 17:24:50 +0000828// Profile - This method 'profiles' an APFloat for use with FoldingSet.
829void APFloat::Profile(FoldingSetNodeID& ID) const {
Dale Johannesen54306fe2008-10-09 18:53:47 +0000830 ID.Add(bitcastToAPInt());
Ted Kremenek6f30a072008-02-11 17:24:50 +0000831}
832
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000833unsigned int
834APFloat::partCount() const
835{
Dale Johannesen146a0ea2007-09-20 23:47:58 +0000836 return partCountForBits(semantics->precision + 1);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000837}
838
839unsigned int
840APFloat::semanticsPrecision(const fltSemantics &semantics)
841{
842 return semantics.precision;
843}
844
845const integerPart *
846APFloat::significandParts() const
847{
848 return const_cast<APFloat *>(this)->significandParts();
849}
850
851integerPart *
852APFloat::significandParts()
853{
Evan Cheng67c90212009-10-27 21:35:42 +0000854 if (partCount() > 1)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000855 return significand.parts;
856 else
857 return &significand.part;
858}
859
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000860void
861APFloat::zeroSignificand()
862{
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000863 APInt::tcSet(significandParts(), 0, partCount());
864}
865
866/* Increment an fcNormal floating point number's significand. */
867void
868APFloat::incrementSignificand()
869{
870 integerPart carry;
871
872 carry = APInt::tcIncrement(significandParts(), partCount());
873
874 /* Our callers should never cause us to overflow. */
875 assert(carry == 0);
Duncan Sandsa41634e2011-08-12 14:54:45 +0000876 (void)carry;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000877}
878
879/* Add the significand of the RHS. Returns the carry flag. */
880integerPart
881APFloat::addSignificand(const APFloat &rhs)
882{
883 integerPart *parts;
884
885 parts = significandParts();
886
887 assert(semantics == rhs.semantics);
888 assert(exponent == rhs.exponent);
889
890 return APInt::tcAdd(parts, rhs.significandParts(), 0, partCount());
891}
892
893/* Subtract the significand of the RHS with a borrow flag. Returns
894 the borrow flag. */
895integerPart
896APFloat::subtractSignificand(const APFloat &rhs, integerPart borrow)
897{
898 integerPart *parts;
899
900 parts = significandParts();
901
902 assert(semantics == rhs.semantics);
903 assert(exponent == rhs.exponent);
904
905 return APInt::tcSubtract(parts, rhs.significandParts(), borrow,
Neil Booth9acbf5a2007-09-26 21:33:42 +0000906 partCount());
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000907}
908
909/* Multiply the significand of the RHS. If ADDEND is non-NULL, add it
910 on to the full-precision result of the multiplication. Returns the
911 lost fraction. */
912lostFraction
913APFloat::multiplySignificand(const APFloat &rhs, const APFloat *addend)
914{
Neil Booth9acbf5a2007-09-26 21:33:42 +0000915 unsigned int omsb; // One, not zero, based MSB.
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000916 unsigned int partsCount, newPartsCount, precision;
917 integerPart *lhsSignificand;
918 integerPart scratch[4];
919 integerPart *fullSignificand;
920 lostFraction lost_fraction;
Dale Johannesen4f0bd682008-10-09 23:00:39 +0000921 bool ignored;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000922
923 assert(semantics == rhs.semantics);
924
925 precision = semantics->precision;
Lang Hames56c0eb22014-11-19 19:15:41 +0000926
927 // Allocate space for twice as many bits as the original significand, plus one
928 // extra bit for the addition to overflow into.
929 newPartsCount = partCountForBits(precision * 2 + 1);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000930
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000931 if (newPartsCount > 4)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000932 fullSignificand = new integerPart[newPartsCount];
933 else
934 fullSignificand = scratch;
935
936 lhsSignificand = significandParts();
937 partsCount = partCount();
938
939 APInt::tcFullMultiply(fullSignificand, lhsSignificand,
Neil Booth0ea72a92007-10-06 00:24:48 +0000940 rhs.significandParts(), partsCount, partsCount);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000941
942 lost_fraction = lfExactlyZero;
943 omsb = APInt::tcMSB(fullSignificand, newPartsCount) + 1;
944 exponent += rhs.exponent;
945
Shuxin Yangbbddbac2013-05-13 18:03:12 +0000946 // Assume the operands involved in the multiplication are single-precision
947 // FP, and the two multiplicants are:
948 // *this = a23 . a22 ... a0 * 2^e1
949 // rhs = b23 . b22 ... b0 * 2^e2
950 // the result of multiplication is:
Lang Hames56c0eb22014-11-19 19:15:41 +0000951 // *this = c48 c47 c46 . c45 ... c0 * 2^(e1+e2)
952 // Note that there are three significant bits at the left-hand side of the
953 // radix point: two for the multiplication, and an overflow bit for the
954 // addition (that will always be zero at this point). Move the radix point
955 // toward left by two bits, and adjust exponent accordingly.
956 exponent += 2;
Shuxin Yangbbddbac2013-05-13 18:03:12 +0000957
Hal Finkel171c2ec2014-10-14 19:23:07 +0000958 if (addend && addend->isNonZero()) {
Shuxin Yangbbddbac2013-05-13 18:03:12 +0000959 // The intermediate result of the multiplication has "2 * precision"
960 // signicant bit; adjust the addend to be consistent with mul result.
961 //
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000962 Significand savedSignificand = significand;
963 const fltSemantics *savedSemantics = semantics;
964 fltSemantics extendedSemantics;
965 opStatus status;
966 unsigned int extendedPrecision;
967
Lang Hames56c0eb22014-11-19 19:15:41 +0000968 // Normalize our MSB to one below the top bit to allow for overflow.
969 extendedPrecision = 2 * precision + 1;
970 if (omsb != extendedPrecision - 1) {
Shuxin Yangbbddbac2013-05-13 18:03:12 +0000971 assert(extendedPrecision > omsb);
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000972 APInt::tcShiftLeft(fullSignificand, newPartsCount,
Lang Hames56c0eb22014-11-19 19:15:41 +0000973 (extendedPrecision - 1) - omsb);
974 exponent -= (extendedPrecision - 1) - omsb;
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000975 }
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000976
977 /* Create new semantics. */
978 extendedSemantics = *semantics;
979 extendedSemantics.precision = extendedPrecision;
980
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000981 if (newPartsCount == 1)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000982 significand.part = fullSignificand[0];
983 else
984 significand.parts = fullSignificand;
985 semantics = &extendedSemantics;
986
987 APFloat extendedAddend(*addend);
Dale Johannesen4f0bd682008-10-09 23:00:39 +0000988 status = extendedAddend.convert(extendedSemantics, rmTowardZero, &ignored);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000989 assert(status == opOK);
Duncan Sandsa41634e2011-08-12 14:54:45 +0000990 (void)status;
Lang Hames56c0eb22014-11-19 19:15:41 +0000991
992 // Shift the significand of the addend right by one bit. This guarantees
993 // that the high bit of the significand is zero (same as fullSignificand),
994 // so the addition will overflow (if it does overflow at all) into the top bit.
995 lost_fraction = extendedAddend.shiftSignificandRight(1);
996 assert(lost_fraction == lfExactlyZero &&
997 "Lost precision while shifting addend for fused-multiply-add.");
998
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000999 lost_fraction = addOrSubtractSignificand(extendedAddend, false);
1000
1001 /* Restore our state. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001002 if (newPartsCount == 1)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001003 fullSignificand[0] = significand.part;
1004 significand = savedSignificand;
1005 semantics = savedSemantics;
1006
1007 omsb = APInt::tcMSB(fullSignificand, newPartsCount) + 1;
1008 }
1009
Shuxin Yangbbddbac2013-05-13 18:03:12 +00001010 // Convert the result having "2 * precision" significant-bits back to the one
1011 // having "precision" significant-bits. First, move the radix point from
1012 // poision "2*precision - 1" to "precision - 1". The exponent need to be
1013 // adjusted by "2*precision - 1" - "precision - 1" = "precision".
Lang Hames56c0eb22014-11-19 19:15:41 +00001014 exponent -= precision + 1;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001015
Shuxin Yangbbddbac2013-05-13 18:03:12 +00001016 // In case MSB resides at the left-hand side of radix point, shift the
1017 // mantissa right by some amount to make sure the MSB reside right before
1018 // the radix point (i.e. "MSB . rest-significant-bits").
1019 //
1020 // Note that the result is not normalized when "omsb < precision". So, the
1021 // caller needs to call APFloat::normalize() if normalized value is expected.
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001022 if (omsb > precision) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001023 unsigned int bits, significantParts;
1024 lostFraction lf;
1025
1026 bits = omsb - precision;
1027 significantParts = partCountForBits(omsb);
1028 lf = shiftRight(fullSignificand, significantParts, bits);
1029 lost_fraction = combineLostFractions(lf, lost_fraction);
1030 exponent += bits;
1031 }
1032
1033 APInt::tcAssign(lhsSignificand, fullSignificand, partsCount);
1034
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001035 if (newPartsCount > 4)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001036 delete [] fullSignificand;
1037
1038 return lost_fraction;
1039}
1040
1041/* Multiply the significands of LHS and RHS to DST. */
1042lostFraction
1043APFloat::divideSignificand(const APFloat &rhs)
1044{
1045 unsigned int bit, i, partsCount;
1046 const integerPart *rhsSignificand;
1047 integerPart *lhsSignificand, *dividend, *divisor;
1048 integerPart scratch[4];
1049 lostFraction lost_fraction;
1050
1051 assert(semantics == rhs.semantics);
1052
1053 lhsSignificand = significandParts();
1054 rhsSignificand = rhs.significandParts();
1055 partsCount = partCount();
1056
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001057 if (partsCount > 2)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001058 dividend = new integerPart[partsCount * 2];
1059 else
1060 dividend = scratch;
1061
1062 divisor = dividend + partsCount;
1063
1064 /* Copy the dividend and divisor as they will be modified in-place. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001065 for (i = 0; i < partsCount; i++) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001066 dividend[i] = lhsSignificand[i];
1067 divisor[i] = rhsSignificand[i];
1068 lhsSignificand[i] = 0;
1069 }
1070
1071 exponent -= rhs.exponent;
1072
1073 unsigned int precision = semantics->precision;
1074
1075 /* Normalize the divisor. */
1076 bit = precision - APInt::tcMSB(divisor, partsCount) - 1;
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001077 if (bit) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001078 exponent += bit;
1079 APInt::tcShiftLeft(divisor, partsCount, bit);
1080 }
1081
1082 /* Normalize the dividend. */
1083 bit = precision - APInt::tcMSB(dividend, partsCount) - 1;
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001084 if (bit) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001085 exponent -= bit;
1086 APInt::tcShiftLeft(dividend, partsCount, bit);
1087 }
1088
Neil Boothb93d90e2007-10-12 16:02:31 +00001089 /* Ensure the dividend >= divisor initially for the loop below.
1090 Incidentally, this means that the division loop below is
1091 guaranteed to set the integer bit to one. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001092 if (APInt::tcCompare(dividend, divisor, partsCount) < 0) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001093 exponent--;
1094 APInt::tcShiftLeft(dividend, partsCount, 1);
1095 assert(APInt::tcCompare(dividend, divisor, partsCount) >= 0);
1096 }
1097
1098 /* Long division. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001099 for (bit = precision; bit; bit -= 1) {
1100 if (APInt::tcCompare(dividend, divisor, partsCount) >= 0) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001101 APInt::tcSubtract(dividend, divisor, 0, partsCount);
1102 APInt::tcSetBit(lhsSignificand, bit - 1);
1103 }
1104
1105 APInt::tcShiftLeft(dividend, partsCount, 1);
1106 }
1107
1108 /* Figure out the lost fraction. */
1109 int cmp = APInt::tcCompare(dividend, divisor, partsCount);
1110
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001111 if (cmp > 0)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001112 lost_fraction = lfMoreThanHalf;
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001113 else if (cmp == 0)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001114 lost_fraction = lfExactlyHalf;
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001115 else if (APInt::tcIsZero(dividend, partsCount))
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001116 lost_fraction = lfExactlyZero;
1117 else
1118 lost_fraction = lfLessThanHalf;
1119
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001120 if (partsCount > 2)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001121 delete [] dividend;
1122
1123 return lost_fraction;
1124}
1125
1126unsigned int
1127APFloat::significandMSB() const
1128{
1129 return APInt::tcMSB(significandParts(), partCount());
1130}
1131
1132unsigned int
1133APFloat::significandLSB() const
1134{
1135 return APInt::tcLSB(significandParts(), partCount());
1136}
1137
1138/* Note that a zero result is NOT normalized to fcZero. */
1139lostFraction
1140APFloat::shiftSignificandRight(unsigned int bits)
1141{
1142 /* Our exponent should not overflow. */
Michael Gottesman9dc98332013-06-24 04:06:23 +00001143 assert((ExponentType) (exponent + bits) >= exponent);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001144
1145 exponent += bits;
1146
1147 return shiftRight(significandParts(), partCount(), bits);
1148}
1149
1150/* Shift the significand left BITS bits, subtract BITS from its exponent. */
1151void
1152APFloat::shiftSignificandLeft(unsigned int bits)
1153{
1154 assert(bits < semantics->precision);
1155
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001156 if (bits) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001157 unsigned int partsCount = partCount();
1158
1159 APInt::tcShiftLeft(significandParts(), partsCount, bits);
1160 exponent -= bits;
1161
1162 assert(!APInt::tcIsZero(significandParts(), partsCount));
1163 }
1164}
1165
1166APFloat::cmpResult
1167APFloat::compareAbsoluteValue(const APFloat &rhs) const
1168{
1169 int compare;
1170
1171 assert(semantics == rhs.semantics);
Michael Gottesman8136c382013-06-26 23:17:28 +00001172 assert(isFiniteNonZero());
1173 assert(rhs.isFiniteNonZero());
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001174
1175 compare = exponent - rhs.exponent;
1176
1177 /* If exponents are equal, do an unsigned bignum comparison of the
1178 significands. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001179 if (compare == 0)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001180 compare = APInt::tcCompare(significandParts(), rhs.significandParts(),
Neil Booth9acbf5a2007-09-26 21:33:42 +00001181 partCount());
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001182
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001183 if (compare > 0)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001184 return cmpGreaterThan;
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001185 else if (compare < 0)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001186 return cmpLessThan;
1187 else
1188 return cmpEqual;
1189}
1190
1191/* Handle overflow. Sign is preserved. We either become infinity or
1192 the largest finite number. */
1193APFloat::opStatus
1194APFloat::handleOverflow(roundingMode rounding_mode)
1195{
1196 /* Infinity? */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001197 if (rounding_mode == rmNearestTiesToEven ||
1198 rounding_mode == rmNearestTiesToAway ||
1199 (rounding_mode == rmTowardPositive && !sign) ||
1200 (rounding_mode == rmTowardNegative && sign)) {
1201 category = fcInfinity;
1202 return (opStatus) (opOverflow | opInexact);
1203 }
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001204
1205 /* Otherwise we become the largest finite number. */
1206 category = fcNormal;
1207 exponent = semantics->maxExponent;
1208 APInt::tcSetLeastSignificantBits(significandParts(), partCount(),
Neil Booth9acbf5a2007-09-26 21:33:42 +00001209 semantics->precision);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001210
1211 return opInexact;
1212}
1213
Neil Booth1ca1f802007-10-03 15:16:41 +00001214/* Returns TRUE if, when truncating the current number, with BIT the
1215 new LSB, with the given lost fraction and rounding mode, the result
1216 would need to be rounded away from zero (i.e., by increasing the
1217 signficand). This routine must work for fcZero of both signs, and
1218 fcNormal numbers. */
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001219bool
1220APFloat::roundAwayFromZero(roundingMode rounding_mode,
Neil Booth1ca1f802007-10-03 15:16:41 +00001221 lostFraction lost_fraction,
1222 unsigned int bit) const
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001223{
Dale Johannesen3cf889f2007-08-31 04:03:46 +00001224 /* NaNs and infinities should not have lost fractions. */
Michael Gottesman8136c382013-06-26 23:17:28 +00001225 assert(isFiniteNonZero() || category == fcZero);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001226
Neil Booth1ca1f802007-10-03 15:16:41 +00001227 /* Current callers never pass this so we don't handle it. */
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001228 assert(lost_fraction != lfExactlyZero);
1229
Mike Stump889285d2009-05-13 23:23:20 +00001230 switch (rounding_mode) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001231 case rmNearestTiesToAway:
1232 return lost_fraction == lfExactlyHalf || lost_fraction == lfMoreThanHalf;
1233
1234 case rmNearestTiesToEven:
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001235 if (lost_fraction == lfMoreThanHalf)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001236 return true;
1237
1238 /* Our zeroes don't have a significand to test. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001239 if (lost_fraction == lfExactlyHalf && category != fcZero)
Neil Booth1ca1f802007-10-03 15:16:41 +00001240 return APInt::tcExtractBit(significandParts(), bit);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001241
1242 return false;
1243
1244 case rmTowardZero:
1245 return false;
1246
1247 case rmTowardPositive:
David Blaikiedc3f01e2015-03-09 01:57:13 +00001248 return !sign;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001249
1250 case rmTowardNegative:
David Blaikiedc3f01e2015-03-09 01:57:13 +00001251 return sign;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001252 }
Chandler Carruthf3e85022012-01-10 18:08:01 +00001253 llvm_unreachable("Invalid rounding mode found");
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001254}
1255
1256APFloat::opStatus
1257APFloat::normalize(roundingMode rounding_mode,
Neil Booth9acbf5a2007-09-26 21:33:42 +00001258 lostFraction lost_fraction)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001259{
Neil Booth9acbf5a2007-09-26 21:33:42 +00001260 unsigned int omsb; /* One, not zero, based MSB. */
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001261 int exponentChange;
1262
Michael Gottesman8136c382013-06-26 23:17:28 +00001263 if (!isFiniteNonZero())
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001264 return opOK;
1265
1266 /* Before rounding normalize the exponent of fcNormal numbers. */
1267 omsb = significandMSB() + 1;
1268
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001269 if (omsb) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001270 /* OMSB is numbered from 1. We want to place it in the integer
Nick Lewyckyf66daac2011-10-03 21:30:08 +00001271 bit numbered PRECISION if possible, with a compensating change in
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001272 the exponent. */
1273 exponentChange = omsb - semantics->precision;
1274
1275 /* If the resulting exponent is too high, overflow according to
1276 the rounding mode. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001277 if (exponent + exponentChange > semantics->maxExponent)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001278 return handleOverflow(rounding_mode);
1279
1280 /* Subnormal numbers have exponent minExponent, and their MSB
1281 is forced based on that. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001282 if (exponent + exponentChange < semantics->minExponent)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001283 exponentChange = semantics->minExponent - exponent;
1284
1285 /* Shifting left is easy as we don't lose precision. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001286 if (exponentChange < 0) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001287 assert(lost_fraction == lfExactlyZero);
1288
1289 shiftSignificandLeft(-exponentChange);
1290
1291 return opOK;
1292 }
1293
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001294 if (exponentChange > 0) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001295 lostFraction lf;
1296
1297 /* Shift right and capture any new lost fraction. */
1298 lf = shiftSignificandRight(exponentChange);
1299
1300 lost_fraction = combineLostFractions(lf, lost_fraction);
1301
1302 /* Keep OMSB up-to-date. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001303 if (omsb > (unsigned) exponentChange)
Neil Boothb93d90e2007-10-12 16:02:31 +00001304 omsb -= exponentChange;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001305 else
Neil Booth9acbf5a2007-09-26 21:33:42 +00001306 omsb = 0;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001307 }
1308 }
1309
1310 /* Now round the number according to rounding_mode given the lost
1311 fraction. */
1312
1313 /* As specified in IEEE 754, since we do not trap we do not report
1314 underflow for exact results. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001315 if (lost_fraction == lfExactlyZero) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001316 /* Canonicalize zeroes. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001317 if (omsb == 0)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001318 category = fcZero;
1319
1320 return opOK;
1321 }
1322
1323 /* Increment the significand if we're rounding away from zero. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001324 if (roundAwayFromZero(rounding_mode, lost_fraction, 0)) {
1325 if (omsb == 0)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001326 exponent = semantics->minExponent;
1327
1328 incrementSignificand();
1329 omsb = significandMSB() + 1;
1330
1331 /* Did the significand increment overflow? */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001332 if (omsb == (unsigned) semantics->precision + 1) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001333 /* Renormalize by incrementing the exponent and shifting our
Neil Booth9acbf5a2007-09-26 21:33:42 +00001334 significand right one. However if we already have the
1335 maximum exponent we overflow to infinity. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001336 if (exponent == semantics->maxExponent) {
Neil Booth9acbf5a2007-09-26 21:33:42 +00001337 category = fcInfinity;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001338
Neil Booth9acbf5a2007-09-26 21:33:42 +00001339 return (opStatus) (opOverflow | opInexact);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001340 }
1341
1342 shiftSignificandRight(1);
1343
1344 return opInexact;
1345 }
1346 }
1347
1348 /* The normal case - we were and are not denormal, and any
1349 significand increment above didn't overflow. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001350 if (omsb == semantics->precision)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001351 return opInexact;
1352
1353 /* We have a non-zero denormal. */
1354 assert(omsb < semantics->precision);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001355
1356 /* Canonicalize zeroes. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001357 if (omsb == 0)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001358 category = fcZero;
1359
1360 /* The fcZero case is a denormal that underflowed to zero. */
1361 return (opStatus) (opUnderflow | opInexact);
1362}
1363
1364APFloat::opStatus
1365APFloat::addOrSubtractSpecials(const APFloat &rhs, bool subtract)
1366{
Michael Gottesman9b877e12013-06-24 09:57:57 +00001367 switch (PackCategoriesIntoKey(category, rhs.category)) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001368 default:
Craig Topper2617dcc2014-04-15 06:32:26 +00001369 llvm_unreachable(nullptr);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001370
Michael Gottesman9b877e12013-06-24 09:57:57 +00001371 case PackCategoriesIntoKey(fcNaN, fcZero):
1372 case PackCategoriesIntoKey(fcNaN, fcNormal):
1373 case PackCategoriesIntoKey(fcNaN, fcInfinity):
1374 case PackCategoriesIntoKey(fcNaN, fcNaN):
1375 case PackCategoriesIntoKey(fcNormal, fcZero):
1376 case PackCategoriesIntoKey(fcInfinity, fcNormal):
1377 case PackCategoriesIntoKey(fcInfinity, fcZero):
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001378 return opOK;
1379
Michael Gottesman9b877e12013-06-24 09:57:57 +00001380 case PackCategoriesIntoKey(fcZero, fcNaN):
1381 case PackCategoriesIntoKey(fcNormal, fcNaN):
1382 case PackCategoriesIntoKey(fcInfinity, fcNaN):
Stephen Canond3278282014-06-08 16:53:31 +00001383 // We need to be sure to flip the sign here for subtraction because we
1384 // don't have a separate negate operation so -NaN becomes 0 - NaN here.
1385 sign = rhs.sign ^ subtract;
Dale Johannesen3cf889f2007-08-31 04:03:46 +00001386 category = fcNaN;
1387 copySignificand(rhs);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001388 return opOK;
1389
Michael Gottesman9b877e12013-06-24 09:57:57 +00001390 case PackCategoriesIntoKey(fcNormal, fcInfinity):
1391 case PackCategoriesIntoKey(fcZero, fcInfinity):
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001392 category = fcInfinity;
1393 sign = rhs.sign ^ subtract;
1394 return opOK;
1395
Michael Gottesman9b877e12013-06-24 09:57:57 +00001396 case PackCategoriesIntoKey(fcZero, fcNormal):
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001397 assign(rhs);
1398 sign = rhs.sign ^ subtract;
1399 return opOK;
1400
Michael Gottesman9b877e12013-06-24 09:57:57 +00001401 case PackCategoriesIntoKey(fcZero, fcZero):
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001402 /* Sign depends on rounding mode; handled by caller. */
1403 return opOK;
1404
Michael Gottesman9b877e12013-06-24 09:57:57 +00001405 case PackCategoriesIntoKey(fcInfinity, fcInfinity):
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001406 /* Differently signed infinities can only be validly
1407 subtracted. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001408 if (((sign ^ rhs.sign)!=0) != subtract) {
Neil Booth5fe658b2007-10-14 10:39:51 +00001409 makeNaN();
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001410 return opInvalidOp;
1411 }
1412
1413 return opOK;
1414
Michael Gottesman9b877e12013-06-24 09:57:57 +00001415 case PackCategoriesIntoKey(fcNormal, fcNormal):
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001416 return opDivByZero;
1417 }
1418}
1419
1420/* Add or subtract two normal numbers. */
1421lostFraction
1422APFloat::addOrSubtractSignificand(const APFloat &rhs, bool subtract)
1423{
1424 integerPart carry;
1425 lostFraction lost_fraction;
1426 int bits;
1427
1428 /* Determine if the operation on the absolute values is effectively
1429 an addition or subtraction. */
Aaron Ballmand5cc45f2015-03-24 12:47:51 +00001430 subtract ^= static_cast<bool>(sign ^ rhs.sign);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001431
1432 /* Are we bigger exponent-wise than the RHS? */
1433 bits = exponent - rhs.exponent;
1434
1435 /* Subtraction is more subtle than one might naively expect. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001436 if (subtract) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001437 APFloat temp_rhs(rhs);
1438 bool reverse;
1439
Chris Lattner3da18eb2007-08-24 03:02:34 +00001440 if (bits == 0) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001441 reverse = compareAbsoluteValue(temp_rhs) == cmpLessThan;
1442 lost_fraction = lfExactlyZero;
Chris Lattner3da18eb2007-08-24 03:02:34 +00001443 } else if (bits > 0) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001444 lost_fraction = temp_rhs.shiftSignificandRight(bits - 1);
1445 shiftSignificandLeft(1);
1446 reverse = false;
Chris Lattner3da18eb2007-08-24 03:02:34 +00001447 } else {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001448 lost_fraction = shiftSignificandRight(-bits - 1);
1449 temp_rhs.shiftSignificandLeft(1);
1450 reverse = true;
1451 }
1452
Chris Lattner3da18eb2007-08-24 03:02:34 +00001453 if (reverse) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001454 carry = temp_rhs.subtractSignificand
Neil Booth9acbf5a2007-09-26 21:33:42 +00001455 (*this, lost_fraction != lfExactlyZero);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001456 copySignificand(temp_rhs);
1457 sign = !sign;
1458 } else {
1459 carry = subtractSignificand
Neil Booth9acbf5a2007-09-26 21:33:42 +00001460 (temp_rhs, lost_fraction != lfExactlyZero);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001461 }
1462
1463 /* Invert the lost fraction - it was on the RHS and
1464 subtracted. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001465 if (lost_fraction == lfLessThanHalf)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001466 lost_fraction = lfMoreThanHalf;
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001467 else if (lost_fraction == lfMoreThanHalf)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001468 lost_fraction = lfLessThanHalf;
1469
1470 /* The code above is intended to ensure that no borrow is
1471 necessary. */
1472 assert(!carry);
Duncan Sandsa41634e2011-08-12 14:54:45 +00001473 (void)carry;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001474 } else {
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001475 if (bits > 0) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001476 APFloat temp_rhs(rhs);
1477
1478 lost_fraction = temp_rhs.shiftSignificandRight(bits);
1479 carry = addSignificand(temp_rhs);
1480 } else {
1481 lost_fraction = shiftSignificandRight(-bits);
1482 carry = addSignificand(rhs);
1483 }
1484
1485 /* We have a guard bit; generating a carry cannot happen. */
1486 assert(!carry);
Duncan Sandsa41634e2011-08-12 14:54:45 +00001487 (void)carry;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001488 }
1489
1490 return lost_fraction;
1491}
1492
1493APFloat::opStatus
1494APFloat::multiplySpecials(const APFloat &rhs)
1495{
Michael Gottesman9b877e12013-06-24 09:57:57 +00001496 switch (PackCategoriesIntoKey(category, rhs.category)) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001497 default:
Craig Topper2617dcc2014-04-15 06:32:26 +00001498 llvm_unreachable(nullptr);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001499
Michael Gottesman9b877e12013-06-24 09:57:57 +00001500 case PackCategoriesIntoKey(fcNaN, fcZero):
1501 case PackCategoriesIntoKey(fcNaN, fcNormal):
1502 case PackCategoriesIntoKey(fcNaN, fcInfinity):
1503 case PackCategoriesIntoKey(fcNaN, fcNaN):
Michael Gottesmanb0e688e2013-07-27 21:49:25 +00001504 sign = false;
Dale Johannesen3cf889f2007-08-31 04:03:46 +00001505 return opOK;
1506
Michael Gottesman9b877e12013-06-24 09:57:57 +00001507 case PackCategoriesIntoKey(fcZero, fcNaN):
1508 case PackCategoriesIntoKey(fcNormal, fcNaN):
1509 case PackCategoriesIntoKey(fcInfinity, fcNaN):
Michael Gottesmanb0e688e2013-07-27 21:49:25 +00001510 sign = false;
Dale Johannesen3cf889f2007-08-31 04:03:46 +00001511 category = fcNaN;
1512 copySignificand(rhs);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001513 return opOK;
1514
Michael Gottesman9b877e12013-06-24 09:57:57 +00001515 case PackCategoriesIntoKey(fcNormal, fcInfinity):
1516 case PackCategoriesIntoKey(fcInfinity, fcNormal):
1517 case PackCategoriesIntoKey(fcInfinity, fcInfinity):
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001518 category = fcInfinity;
1519 return opOK;
1520
Michael Gottesman9b877e12013-06-24 09:57:57 +00001521 case PackCategoriesIntoKey(fcZero, fcNormal):
1522 case PackCategoriesIntoKey(fcNormal, fcZero):
1523 case PackCategoriesIntoKey(fcZero, fcZero):
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001524 category = fcZero;
1525 return opOK;
1526
Michael Gottesman9b877e12013-06-24 09:57:57 +00001527 case PackCategoriesIntoKey(fcZero, fcInfinity):
1528 case PackCategoriesIntoKey(fcInfinity, fcZero):
Neil Booth5fe658b2007-10-14 10:39:51 +00001529 makeNaN();
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001530 return opInvalidOp;
1531
Michael Gottesman9b877e12013-06-24 09:57:57 +00001532 case PackCategoriesIntoKey(fcNormal, fcNormal):
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001533 return opOK;
1534 }
1535}
1536
1537APFloat::opStatus
1538APFloat::divideSpecials(const APFloat &rhs)
1539{
Michael Gottesman9b877e12013-06-24 09:57:57 +00001540 switch (PackCategoriesIntoKey(category, rhs.category)) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001541 default:
Craig Topper2617dcc2014-04-15 06:32:26 +00001542 llvm_unreachable(nullptr);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001543
Michael Gottesman9b877e12013-06-24 09:57:57 +00001544 case PackCategoriesIntoKey(fcZero, fcNaN):
1545 case PackCategoriesIntoKey(fcNormal, fcNaN):
1546 case PackCategoriesIntoKey(fcInfinity, fcNaN):
Dale Johannesen3cf889f2007-08-31 04:03:46 +00001547 category = fcNaN;
1548 copySignificand(rhs);
Michael Gottesmanb0e688e2013-07-27 21:49:25 +00001549 case PackCategoriesIntoKey(fcNaN, fcZero):
1550 case PackCategoriesIntoKey(fcNaN, fcNormal):
1551 case PackCategoriesIntoKey(fcNaN, fcInfinity):
1552 case PackCategoriesIntoKey(fcNaN, fcNaN):
1553 sign = false;
1554 case PackCategoriesIntoKey(fcInfinity, fcZero):
1555 case PackCategoriesIntoKey(fcInfinity, fcNormal):
1556 case PackCategoriesIntoKey(fcZero, fcInfinity):
1557 case PackCategoriesIntoKey(fcZero, fcNormal):
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001558 return opOK;
1559
Michael Gottesman9b877e12013-06-24 09:57:57 +00001560 case PackCategoriesIntoKey(fcNormal, fcInfinity):
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001561 category = fcZero;
1562 return opOK;
1563
Michael Gottesman9b877e12013-06-24 09:57:57 +00001564 case PackCategoriesIntoKey(fcNormal, fcZero):
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001565 category = fcInfinity;
1566 return opDivByZero;
1567
Michael Gottesman9b877e12013-06-24 09:57:57 +00001568 case PackCategoriesIntoKey(fcInfinity, fcInfinity):
1569 case PackCategoriesIntoKey(fcZero, fcZero):
Neil Booth5fe658b2007-10-14 10:39:51 +00001570 makeNaN();
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001571 return opInvalidOp;
1572
Michael Gottesman9b877e12013-06-24 09:57:57 +00001573 case PackCategoriesIntoKey(fcNormal, fcNormal):
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001574 return opOK;
1575 }
1576}
1577
Dale Johannesenb5721632009-01-21 00:35:19 +00001578APFloat::opStatus
1579APFloat::modSpecials(const APFloat &rhs)
1580{
Michael Gottesman9b877e12013-06-24 09:57:57 +00001581 switch (PackCategoriesIntoKey(category, rhs.category)) {
Dale Johannesenb5721632009-01-21 00:35:19 +00001582 default:
Craig Topper2617dcc2014-04-15 06:32:26 +00001583 llvm_unreachable(nullptr);
Dale Johannesenb5721632009-01-21 00:35:19 +00001584
Michael Gottesman9b877e12013-06-24 09:57:57 +00001585 case PackCategoriesIntoKey(fcNaN, fcZero):
1586 case PackCategoriesIntoKey(fcNaN, fcNormal):
1587 case PackCategoriesIntoKey(fcNaN, fcInfinity):
1588 case PackCategoriesIntoKey(fcNaN, fcNaN):
1589 case PackCategoriesIntoKey(fcZero, fcInfinity):
1590 case PackCategoriesIntoKey(fcZero, fcNormal):
1591 case PackCategoriesIntoKey(fcNormal, fcInfinity):
Dale Johannesenb5721632009-01-21 00:35:19 +00001592 return opOK;
1593
Michael Gottesman9b877e12013-06-24 09:57:57 +00001594 case PackCategoriesIntoKey(fcZero, fcNaN):
1595 case PackCategoriesIntoKey(fcNormal, fcNaN):
1596 case PackCategoriesIntoKey(fcInfinity, fcNaN):
Michael Gottesmanb0e688e2013-07-27 21:49:25 +00001597 sign = false;
Dale Johannesenb5721632009-01-21 00:35:19 +00001598 category = fcNaN;
1599 copySignificand(rhs);
1600 return opOK;
1601
Michael Gottesman9b877e12013-06-24 09:57:57 +00001602 case PackCategoriesIntoKey(fcNormal, fcZero):
1603 case PackCategoriesIntoKey(fcInfinity, fcZero):
1604 case PackCategoriesIntoKey(fcInfinity, fcNormal):
1605 case PackCategoriesIntoKey(fcInfinity, fcInfinity):
1606 case PackCategoriesIntoKey(fcZero, fcZero):
Dale Johannesenb5721632009-01-21 00:35:19 +00001607 makeNaN();
1608 return opInvalidOp;
1609
Michael Gottesman9b877e12013-06-24 09:57:57 +00001610 case PackCategoriesIntoKey(fcNormal, fcNormal):
Dale Johannesenb5721632009-01-21 00:35:19 +00001611 return opOK;
1612 }
1613}
1614
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001615/* Change sign. */
1616void
1617APFloat::changeSign()
1618{
1619 /* Look mummy, this one's easy. */
1620 sign = !sign;
1621}
1622
Dale Johannesen689d17d2007-08-31 23:35:31 +00001623void
1624APFloat::clearSign()
1625{
1626 /* So is this one. */
1627 sign = 0;
1628}
1629
1630void
1631APFloat::copySign(const APFloat &rhs)
1632{
1633 /* And this one. */
1634 sign = rhs.sign;
1635}
1636
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001637/* Normalized addition or subtraction. */
1638APFloat::opStatus
1639APFloat::addOrSubtract(const APFloat &rhs, roundingMode rounding_mode,
Neil Booth9acbf5a2007-09-26 21:33:42 +00001640 bool subtract)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001641{
1642 opStatus fs;
1643
1644 fs = addOrSubtractSpecials(rhs, subtract);
1645
1646 /* This return code means it was not a simple case. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001647 if (fs == opDivByZero) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001648 lostFraction lost_fraction;
1649
1650 lost_fraction = addOrSubtractSignificand(rhs, subtract);
1651 fs = normalize(rounding_mode, lost_fraction);
1652
1653 /* Can only be zero if we lost no fraction. */
1654 assert(category != fcZero || lost_fraction == lfExactlyZero);
1655 }
1656
1657 /* If two numbers add (exactly) to zero, IEEE 754 decrees it is a
1658 positive zero unless rounding to minus infinity, except that
1659 adding two like-signed zeroes gives that zero. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001660 if (category == fcZero) {
1661 if (rhs.category != fcZero || (sign == rhs.sign) == subtract)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001662 sign = (rounding_mode == rmTowardNegative);
1663 }
1664
1665 return fs;
1666}
1667
1668/* Normalized addition. */
1669APFloat::opStatus
1670APFloat::add(const APFloat &rhs, roundingMode rounding_mode)
1671{
1672 return addOrSubtract(rhs, rounding_mode, false);
1673}
1674
1675/* Normalized subtraction. */
1676APFloat::opStatus
1677APFloat::subtract(const APFloat &rhs, roundingMode rounding_mode)
1678{
1679 return addOrSubtract(rhs, rounding_mode, true);
1680}
1681
1682/* Normalized multiply. */
1683APFloat::opStatus
1684APFloat::multiply(const APFloat &rhs, roundingMode rounding_mode)
1685{
1686 opStatus fs;
1687
1688 sign ^= rhs.sign;
1689 fs = multiplySpecials(rhs);
1690
Michael Gottesman8136c382013-06-26 23:17:28 +00001691 if (isFiniteNonZero()) {
Craig Topperc10719f2014-04-07 04:17:22 +00001692 lostFraction lost_fraction = multiplySignificand(rhs, nullptr);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001693 fs = normalize(rounding_mode, lost_fraction);
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001694 if (lost_fraction != lfExactlyZero)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001695 fs = (opStatus) (fs | opInexact);
1696 }
1697
1698 return fs;
1699}
1700
1701/* Normalized divide. */
1702APFloat::opStatus
1703APFloat::divide(const APFloat &rhs, roundingMode rounding_mode)
1704{
1705 opStatus fs;
1706
1707 sign ^= rhs.sign;
1708 fs = divideSpecials(rhs);
1709
Michael Gottesman8136c382013-06-26 23:17:28 +00001710 if (isFiniteNonZero()) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001711 lostFraction lost_fraction = divideSignificand(rhs);
1712 fs = normalize(rounding_mode, lost_fraction);
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001713 if (lost_fraction != lfExactlyZero)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001714 fs = (opStatus) (fs | opInexact);
1715 }
1716
1717 return fs;
1718}
1719
Dale Johannesenfe750172009-01-20 18:35:05 +00001720/* Normalized remainder. This is not currently correct in all cases. */
1721APFloat::opStatus
1722APFloat::remainder(const APFloat &rhs)
1723{
1724 opStatus fs;
1725 APFloat V = *this;
1726 unsigned int origSign = sign;
1727
Dale Johannesenfe750172009-01-20 18:35:05 +00001728 fs = V.divide(rhs, rmNearestTiesToEven);
1729 if (fs == opDivByZero)
1730 return fs;
1731
1732 int parts = partCount();
Dylan Noblesmith4e69e292014-08-26 02:03:33 +00001733 integerPart *x = new integerPart[parts];
Dale Johannesenfe750172009-01-20 18:35:05 +00001734 bool ignored;
1735 fs = V.convertToInteger(x, parts * integerPartWidth, true,
1736 rmNearestTiesToEven, &ignored);
1737 if (fs==opInvalidOp)
1738 return fs;
1739
1740 fs = V.convertFromZeroExtendedInteger(x, parts * integerPartWidth, true,
1741 rmNearestTiesToEven);
1742 assert(fs==opOK); // should always work
1743
1744 fs = V.multiply(rhs, rmNearestTiesToEven);
1745 assert(fs==opOK || fs==opInexact); // should not overflow or underflow
1746
1747 fs = subtract(V, rmNearestTiesToEven);
1748 assert(fs==opOK || fs==opInexact); // likewise
1749
1750 if (isZero())
1751 sign = origSign; // IEEE754 requires this
Dylan Noblesmith4e69e292014-08-26 02:03:33 +00001752 delete[] x;
Dale Johannesenfe750172009-01-20 18:35:05 +00001753 return fs;
1754}
1755
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001756/* Normalized llvm frem (C fmod).
Dale Johannesenfe750172009-01-20 18:35:05 +00001757 This is not currently correct in all cases. */
Dale Johannesen689d17d2007-08-31 23:35:31 +00001758APFloat::opStatus
1759APFloat::mod(const APFloat &rhs, roundingMode rounding_mode)
1760{
1761 opStatus fs;
Dale Johannesenb5721632009-01-21 00:35:19 +00001762 fs = modSpecials(rhs);
Dale Johannesen689d17d2007-08-31 23:35:31 +00001763
Michael Gottesman8136c382013-06-26 23:17:28 +00001764 if (isFiniteNonZero() && rhs.isFiniteNonZero()) {
Dale Johannesenb5721632009-01-21 00:35:19 +00001765 APFloat V = *this;
1766 unsigned int origSign = sign;
Dale Johannesen689d17d2007-08-31 23:35:31 +00001767
Dale Johannesenb5721632009-01-21 00:35:19 +00001768 fs = V.divide(rhs, rmNearestTiesToEven);
1769 if (fs == opDivByZero)
1770 return fs;
Dale Johannesen728687c2007-09-05 20:39:49 +00001771
Dale Johannesenb5721632009-01-21 00:35:19 +00001772 int parts = partCount();
Dylan Noblesmith4e69e292014-08-26 02:03:33 +00001773 integerPart *x = new integerPart[parts];
Dale Johannesenb5721632009-01-21 00:35:19 +00001774 bool ignored;
1775 fs = V.convertToInteger(x, parts * integerPartWidth, true,
1776 rmTowardZero, &ignored);
1777 if (fs==opInvalidOp)
1778 return fs;
Dale Johannesen728687c2007-09-05 20:39:49 +00001779
Dale Johannesenb5721632009-01-21 00:35:19 +00001780 fs = V.convertFromZeroExtendedInteger(x, parts * integerPartWidth, true,
1781 rmNearestTiesToEven);
1782 assert(fs==opOK); // should always work
Dale Johannesen728687c2007-09-05 20:39:49 +00001783
Dale Johannesenb5721632009-01-21 00:35:19 +00001784 fs = V.multiply(rhs, rounding_mode);
1785 assert(fs==opOK || fs==opInexact); // should not overflow or underflow
1786
1787 fs = subtract(V, rounding_mode);
1788 assert(fs==opOK || fs==opInexact); // likewise
1789
1790 if (isZero())
1791 sign = origSign; // IEEE754 requires this
Dylan Noblesmith4e69e292014-08-26 02:03:33 +00001792 delete[] x;
Dale Johannesenb5721632009-01-21 00:35:19 +00001793 }
Dale Johannesen689d17d2007-08-31 23:35:31 +00001794 return fs;
1795}
1796
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001797/* Normalized fused-multiply-add. */
1798APFloat::opStatus
1799APFloat::fusedMultiplyAdd(const APFloat &multiplicand,
Neil Booth9acbf5a2007-09-26 21:33:42 +00001800 const APFloat &addend,
1801 roundingMode rounding_mode)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001802{
1803 opStatus fs;
1804
1805 /* Post-multiplication sign, before addition. */
1806 sign ^= multiplicand.sign;
1807
1808 /* If and only if all arguments are normal do we need to do an
1809 extended-precision calculation. */
Michael Gottesman8136c382013-06-26 23:17:28 +00001810 if (isFiniteNonZero() &&
1811 multiplicand.isFiniteNonZero() &&
Hal Finkel171c2ec2014-10-14 19:23:07 +00001812 addend.isFinite()) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001813 lostFraction lost_fraction;
1814
1815 lost_fraction = multiplySignificand(multiplicand, &addend);
1816 fs = normalize(rounding_mode, lost_fraction);
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001817 if (lost_fraction != lfExactlyZero)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001818 fs = (opStatus) (fs | opInexact);
1819
1820 /* If two numbers add (exactly) to zero, IEEE 754 decrees it is a
1821 positive zero unless rounding to minus infinity, except that
1822 adding two like-signed zeroes gives that zero. */
Lang Hames12b12e82015-01-04 01:20:55 +00001823 if (category == fcZero && !(fs & opUnderflow) && sign != addend.sign)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001824 sign = (rounding_mode == rmTowardNegative);
1825 } else {
1826 fs = multiplySpecials(multiplicand);
1827
1828 /* FS can only be opOK or opInvalidOp. There is no more work
1829 to do in the latter case. The IEEE-754R standard says it is
1830 implementation-defined in this case whether, if ADDEND is a
Dale Johannesen3cf889f2007-08-31 04:03:46 +00001831 quiet NaN, we raise invalid op; this implementation does so.
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001832
1833 If we need to do the addition we can do so with normal
1834 precision. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001835 if (fs == opOK)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001836 fs = addOrSubtract(addend, rounding_mode, false);
1837 }
1838
1839 return fs;
1840}
1841
Owen Andersona40319b2012-08-13 23:32:49 +00001842/* Rounding-mode corrrect round to integral value. */
1843APFloat::opStatus APFloat::roundToIntegral(roundingMode rounding_mode) {
1844 opStatus fs;
Owen Andersona40319b2012-08-13 23:32:49 +00001845
Owen Anderson352dfff2012-08-15 18:28:45 +00001846 // If the exponent is large enough, we know that this value is already
1847 // integral, and the arithmetic below would potentially cause it to saturate
1848 // to +/-Inf. Bail out early instead.
Michael Gottesman8136c382013-06-26 23:17:28 +00001849 if (isFiniteNonZero() && exponent+1 >= (int)semanticsPrecision(*semantics))
Owen Anderson352dfff2012-08-15 18:28:45 +00001850 return opOK;
1851
Owen Andersona40319b2012-08-13 23:32:49 +00001852 // The algorithm here is quite simple: we add 2^(p-1), where p is the
1853 // precision of our format, and then subtract it back off again. The choice
1854 // of rounding modes for the addition/subtraction determines the rounding mode
1855 // for our integral rounding as well.
Owen Andersonbe7e2972012-08-15 16:42:53 +00001856 // NOTE: When the input value is negative, we do subtraction followed by
Owen Anderson1ff74b02012-08-15 05:39:46 +00001857 // addition instead.
Owen Anderson0b357222012-08-14 18:51:15 +00001858 APInt IntegerConstant(NextPowerOf2(semanticsPrecision(*semantics)), 1);
1859 IntegerConstant <<= semanticsPrecision(*semantics)-1;
Owen Andersona40319b2012-08-13 23:32:49 +00001860 APFloat MagicConstant(*semantics);
1861 fs = MagicConstant.convertFromAPInt(IntegerConstant, false,
1862 rmNearestTiesToEven);
Owen Anderson1ff74b02012-08-15 05:39:46 +00001863 MagicConstant.copySign(*this);
1864
Owen Andersona40319b2012-08-13 23:32:49 +00001865 if (fs != opOK)
1866 return fs;
1867
Owen Anderson1ff74b02012-08-15 05:39:46 +00001868 // Preserve the input sign so that we can handle 0.0/-0.0 cases correctly.
1869 bool inputSign = isNegative();
1870
Owen Andersona40319b2012-08-13 23:32:49 +00001871 fs = add(MagicConstant, rounding_mode);
1872 if (fs != opOK && fs != opInexact)
1873 return fs;
1874
1875 fs = subtract(MagicConstant, rounding_mode);
Owen Anderson1ff74b02012-08-15 05:39:46 +00001876
1877 // Restore the input sign.
1878 if (inputSign != isNegative())
1879 changeSign();
1880
Owen Andersona40319b2012-08-13 23:32:49 +00001881 return fs;
1882}
1883
1884
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001885/* Comparison requires normalized numbers. */
1886APFloat::cmpResult
1887APFloat::compare(const APFloat &rhs) const
1888{
1889 cmpResult result;
1890
1891 assert(semantics == rhs.semantics);
1892
Michael Gottesman9b877e12013-06-24 09:57:57 +00001893 switch (PackCategoriesIntoKey(category, rhs.category)) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001894 default:
Craig Topper2617dcc2014-04-15 06:32:26 +00001895 llvm_unreachable(nullptr);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001896
Michael Gottesman9b877e12013-06-24 09:57:57 +00001897 case PackCategoriesIntoKey(fcNaN, fcZero):
1898 case PackCategoriesIntoKey(fcNaN, fcNormal):
1899 case PackCategoriesIntoKey(fcNaN, fcInfinity):
1900 case PackCategoriesIntoKey(fcNaN, fcNaN):
1901 case PackCategoriesIntoKey(fcZero, fcNaN):
1902 case PackCategoriesIntoKey(fcNormal, fcNaN):
1903 case PackCategoriesIntoKey(fcInfinity, fcNaN):
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001904 return cmpUnordered;
1905
Michael Gottesman9b877e12013-06-24 09:57:57 +00001906 case PackCategoriesIntoKey(fcInfinity, fcNormal):
1907 case PackCategoriesIntoKey(fcInfinity, fcZero):
1908 case PackCategoriesIntoKey(fcNormal, fcZero):
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001909 if (sign)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001910 return cmpLessThan;
1911 else
1912 return cmpGreaterThan;
1913
Michael Gottesman9b877e12013-06-24 09:57:57 +00001914 case PackCategoriesIntoKey(fcNormal, fcInfinity):
1915 case PackCategoriesIntoKey(fcZero, fcInfinity):
1916 case PackCategoriesIntoKey(fcZero, fcNormal):
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001917 if (rhs.sign)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001918 return cmpGreaterThan;
1919 else
1920 return cmpLessThan;
1921
Michael Gottesman9b877e12013-06-24 09:57:57 +00001922 case PackCategoriesIntoKey(fcInfinity, fcInfinity):
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001923 if (sign == rhs.sign)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001924 return cmpEqual;
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001925 else if (sign)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001926 return cmpLessThan;
1927 else
1928 return cmpGreaterThan;
1929
Michael Gottesman9b877e12013-06-24 09:57:57 +00001930 case PackCategoriesIntoKey(fcZero, fcZero):
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001931 return cmpEqual;
1932
Michael Gottesman9b877e12013-06-24 09:57:57 +00001933 case PackCategoriesIntoKey(fcNormal, fcNormal):
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001934 break;
1935 }
1936
1937 /* Two normal numbers. Do they have the same sign? */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001938 if (sign != rhs.sign) {
1939 if (sign)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001940 result = cmpLessThan;
1941 else
1942 result = cmpGreaterThan;
1943 } else {
1944 /* Compare absolute values; invert result if negative. */
1945 result = compareAbsoluteValue(rhs);
1946
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001947 if (sign) {
1948 if (result == cmpLessThan)
Neil Booth9acbf5a2007-09-26 21:33:42 +00001949 result = cmpGreaterThan;
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001950 else if (result == cmpGreaterThan)
Neil Booth9acbf5a2007-09-26 21:33:42 +00001951 result = cmpLessThan;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001952 }
1953 }
1954
1955 return result;
1956}
1957
Dale Johannesen4f0bd682008-10-09 23:00:39 +00001958/// APFloat::convert - convert a value of one floating point type to another.
1959/// The return value corresponds to the IEEE754 exceptions. *losesInfo
1960/// records whether the transformation lost information, i.e. whether
1961/// converting the result back to the original type will produce the
1962/// original value (this is almost the same as return value==fsOK, but there
1963/// are edge cases where this is not so).
1964
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001965APFloat::opStatus
1966APFloat::convert(const fltSemantics &toSemantics,
Dale Johannesen4f0bd682008-10-09 23:00:39 +00001967 roundingMode rounding_mode, bool *losesInfo)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001968{
Neil Bootha8d72692007-09-22 02:56:19 +00001969 lostFraction lostFraction;
1970 unsigned int newPartCount, oldPartCount;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001971 opStatus fs;
Eli Friedmana84ad7d2011-11-26 03:38:02 +00001972 int shift;
1973 const fltSemantics &fromSemantics = *semantics;
Neil Booth9acbf5a2007-09-26 21:33:42 +00001974
Neil Bootha8d72692007-09-22 02:56:19 +00001975 lostFraction = lfExactlyZero;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001976 newPartCount = partCountForBits(toSemantics.precision + 1);
Neil Bootha8d72692007-09-22 02:56:19 +00001977 oldPartCount = partCount();
Eli Friedmana84ad7d2011-11-26 03:38:02 +00001978 shift = toSemantics.precision - fromSemantics.precision;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001979
Eli Friedmana84ad7d2011-11-26 03:38:02 +00001980 bool X86SpecialNan = false;
1981 if (&fromSemantics == &APFloat::x87DoubleExtended &&
1982 &toSemantics != &APFloat::x87DoubleExtended && category == fcNaN &&
1983 (!(*significandParts() & 0x8000000000000000ULL) ||
1984 !(*significandParts() & 0x4000000000000000ULL))) {
1985 // x86 has some unusual NaNs which cannot be represented in any other
1986 // format; note them here.
1987 X86SpecialNan = true;
1988 }
1989
Ulrich Weigand1d4dbda2013-07-16 13:03:25 +00001990 // If this is a truncation of a denormal number, and the target semantics
1991 // has larger exponent range than the source semantics (this can happen
1992 // when truncating from PowerPC double-double to double format), the
1993 // right shift could lose result mantissa bits. Adjust exponent instead
1994 // of performing excessive shift.
1995 if (shift < 0 && isFiniteNonZero()) {
1996 int exponentChange = significandMSB() + 1 - fromSemantics.precision;
1997 if (exponent + exponentChange < toSemantics.minExponent)
1998 exponentChange = toSemantics.minExponent - exponent;
1999 if (exponentChange < shift)
2000 exponentChange = shift;
2001 if (exponentChange < 0) {
2002 shift -= exponentChange;
2003 exponent += exponentChange;
2004 }
2005 }
2006
Eli Friedmana84ad7d2011-11-26 03:38:02 +00002007 // If this is a truncation, perform the shift before we narrow the storage.
Michael Gottesman8136c382013-06-26 23:17:28 +00002008 if (shift < 0 && (isFiniteNonZero() || category==fcNaN))
Eli Friedmana84ad7d2011-11-26 03:38:02 +00002009 lostFraction = shiftRight(significandParts(), oldPartCount, -shift);
2010
2011 // Fix the storage so it can hold to new value.
Neil Bootha8d72692007-09-22 02:56:19 +00002012 if (newPartCount > oldPartCount) {
Eli Friedmana84ad7d2011-11-26 03:38:02 +00002013 // The new type requires more storage; make it available.
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002014 integerPart *newParts;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002015 newParts = new integerPart[newPartCount];
2016 APInt::tcSet(newParts, 0, newPartCount);
Michael Gottesman8136c382013-06-26 23:17:28 +00002017 if (isFiniteNonZero() || category==fcNaN)
Dale Johannesen4f55d9f2007-09-25 17:25:00 +00002018 APInt::tcAssign(newParts, significandParts(), oldPartCount);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002019 freeSignificand();
2020 significand.parts = newParts;
Eli Friedmana84ad7d2011-11-26 03:38:02 +00002021 } else if (newPartCount == 1 && oldPartCount != 1) {
2022 // Switch to built-in storage for a single part.
2023 integerPart newPart = 0;
Michael Gottesman8136c382013-06-26 23:17:28 +00002024 if (isFiniteNonZero() || category==fcNaN)
Eli Friedmana84ad7d2011-11-26 03:38:02 +00002025 newPart = significandParts()[0];
2026 freeSignificand();
2027 significand.part = newPart;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002028 }
2029
Eli Friedmana84ad7d2011-11-26 03:38:02 +00002030 // Now that we have the right storage, switch the semantics.
2031 semantics = &toSemantics;
2032
2033 // If this is an extension, perform the shift now that the storage is
2034 // available.
Michael Gottesman8136c382013-06-26 23:17:28 +00002035 if (shift > 0 && (isFiniteNonZero() || category==fcNaN))
Eli Friedmana84ad7d2011-11-26 03:38:02 +00002036 APInt::tcShiftLeft(significandParts(), newPartCount, shift);
2037
Michael Gottesman8136c382013-06-26 23:17:28 +00002038 if (isFiniteNonZero()) {
Neil Bootha8d72692007-09-22 02:56:19 +00002039 fs = normalize(rounding_mode, lostFraction);
Dale Johannesen4f0bd682008-10-09 23:00:39 +00002040 *losesInfo = (fs != opOK);
Dale Johannesen4f55d9f2007-09-25 17:25:00 +00002041 } else if (category == fcNaN) {
Eli Friedmana84ad7d2011-11-26 03:38:02 +00002042 *losesInfo = lostFraction != lfExactlyZero || X86SpecialNan;
Benjamin Kramerb361adb2013-01-25 17:01:00 +00002043
2044 // For x87 extended precision, we want to make a NaN, not a special NaN if
2045 // the input wasn't special either.
2046 if (!X86SpecialNan && semantics == &APFloat::x87DoubleExtended)
2047 APInt::tcSetBit(significandParts(), semantics->precision - 1);
2048
Dale Johannesen4f55d9f2007-09-25 17:25:00 +00002049 // gcc forces the Quiet bit on, which means (float)(double)(float_sNan)
2050 // does not give you back the same bits. This is dubious, and we
2051 // don't currently do it. You're really supposed to get
2052 // an invalid operation signal at runtime, but nobody does that.
Dale Johannesen4f0bd682008-10-09 23:00:39 +00002053 fs = opOK;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002054 } else {
Dale Johannesen4f0bd682008-10-09 23:00:39 +00002055 *losesInfo = false;
Eli Friedman31f01162011-11-28 18:50:37 +00002056 fs = opOK;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002057 }
2058
2059 return fs;
2060}
2061
2062/* Convert a floating point number to an integer according to the
2063 rounding mode. If the rounded integer value is out of range this
Neil Booth618d0fc2007-11-01 22:43:37 +00002064 returns an invalid operation exception and the contents of the
2065 destination parts are unspecified. If the rounded value is in
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002066 range but the floating point number is not the exact integer, the C
2067 standard doesn't require an inexact exception to be raised. IEEE
2068 854 does require it so we do that.
2069
2070 Note that for conversions to integer type the C standard requires
2071 round-to-zero to always be used. */
2072APFloat::opStatus
Neil Booth618d0fc2007-11-01 22:43:37 +00002073APFloat::convertToSignExtendedInteger(integerPart *parts, unsigned int width,
2074 bool isSigned,
Dale Johannesen4f0bd682008-10-09 23:00:39 +00002075 roundingMode rounding_mode,
2076 bool *isExact) const
Neil Booth618d0fc2007-11-01 22:43:37 +00002077{
2078 lostFraction lost_fraction;
2079 const integerPart *src;
2080 unsigned int dstPartsCount, truncatedBits;
2081
Dale Johannesen4f0bd682008-10-09 23:00:39 +00002082 *isExact = false;
2083
Neil Booth618d0fc2007-11-01 22:43:37 +00002084 /* Handle the three special cases first. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002085 if (category == fcInfinity || category == fcNaN)
Neil Booth618d0fc2007-11-01 22:43:37 +00002086 return opInvalidOp;
2087
2088 dstPartsCount = partCountForBits(width);
2089
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002090 if (category == fcZero) {
Neil Booth618d0fc2007-11-01 22:43:37 +00002091 APInt::tcSet(parts, 0, dstPartsCount);
Dale Johannesen7221af32008-10-07 00:40:01 +00002092 // Negative zero can't be represented as an int.
Dale Johannesen4f0bd682008-10-09 23:00:39 +00002093 *isExact = !sign;
2094 return opOK;
Neil Booth618d0fc2007-11-01 22:43:37 +00002095 }
2096
2097 src = significandParts();
2098
2099 /* Step 1: place our absolute value, with any fraction truncated, in
2100 the destination. */
2101 if (exponent < 0) {
2102 /* Our absolute value is less than one; truncate everything. */
2103 APInt::tcSet(parts, 0, dstPartsCount);
Dale Johannesen740e9872009-01-19 21:17:05 +00002104 /* For exponent -1 the integer bit represents .5, look at that.
2105 For smaller exponents leftmost truncated bit is 0. */
2106 truncatedBits = semantics->precision -1U - exponent;
Neil Booth618d0fc2007-11-01 22:43:37 +00002107 } else {
2108 /* We want the most significant (exponent + 1) bits; the rest are
2109 truncated. */
2110 unsigned int bits = exponent + 1U;
2111
2112 /* Hopelessly large in magnitude? */
2113 if (bits > width)
2114 return opInvalidOp;
2115
2116 if (bits < semantics->precision) {
2117 /* We truncate (semantics->precision - bits) bits. */
2118 truncatedBits = semantics->precision - bits;
2119 APInt::tcExtract(parts, dstPartsCount, src, bits, truncatedBits);
2120 } else {
2121 /* We want at least as many bits as are available. */
2122 APInt::tcExtract(parts, dstPartsCount, src, semantics->precision, 0);
2123 APInt::tcShiftLeft(parts, dstPartsCount, bits - semantics->precision);
2124 truncatedBits = 0;
2125 }
2126 }
2127
2128 /* Step 2: work out any lost fraction, and increment the absolute
2129 value if we would round away from zero. */
2130 if (truncatedBits) {
2131 lost_fraction = lostFractionThroughTruncation(src, partCount(),
2132 truncatedBits);
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002133 if (lost_fraction != lfExactlyZero &&
2134 roundAwayFromZero(rounding_mode, lost_fraction, truncatedBits)) {
Neil Booth618d0fc2007-11-01 22:43:37 +00002135 if (APInt::tcIncrement(parts, dstPartsCount))
2136 return opInvalidOp; /* Overflow. */
2137 }
2138 } else {
2139 lost_fraction = lfExactlyZero;
2140 }
2141
2142 /* Step 3: check if we fit in the destination. */
2143 unsigned int omsb = APInt::tcMSB(parts, dstPartsCount) + 1;
2144
2145 if (sign) {
2146 if (!isSigned) {
2147 /* Negative numbers cannot be represented as unsigned. */
2148 if (omsb != 0)
2149 return opInvalidOp;
2150 } else {
2151 /* It takes omsb bits to represent the unsigned integer value.
2152 We lose a bit for the sign, but care is needed as the
2153 maximally negative integer is a special case. */
2154 if (omsb == width && APInt::tcLSB(parts, dstPartsCount) + 1 != omsb)
2155 return opInvalidOp;
2156
2157 /* This case can happen because of rounding. */
2158 if (omsb > width)
2159 return opInvalidOp;
2160 }
2161
2162 APInt::tcNegate (parts, dstPartsCount);
2163 } else {
2164 if (omsb >= width + !isSigned)
2165 return opInvalidOp;
2166 }
2167
Dale Johannesen4f0bd682008-10-09 23:00:39 +00002168 if (lost_fraction == lfExactlyZero) {
2169 *isExact = true;
Neil Booth618d0fc2007-11-01 22:43:37 +00002170 return opOK;
Dale Johannesen4f0bd682008-10-09 23:00:39 +00002171 } else
Neil Booth618d0fc2007-11-01 22:43:37 +00002172 return opInexact;
2173}
2174
2175/* Same as convertToSignExtendedInteger, except we provide
2176 deterministic values in case of an invalid operation exception,
2177 namely zero for NaNs and the minimal or maximal value respectively
Dale Johannesen4f0bd682008-10-09 23:00:39 +00002178 for underflow or overflow.
2179 The *isExact output tells whether the result is exact, in the sense
2180 that converting it back to the original floating point type produces
2181 the original value. This is almost equivalent to result==opOK,
2182 except for negative zeroes.
2183*/
Neil Booth618d0fc2007-11-01 22:43:37 +00002184APFloat::opStatus
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002185APFloat::convertToInteger(integerPart *parts, unsigned int width,
Neil Booth9acbf5a2007-09-26 21:33:42 +00002186 bool isSigned,
Dale Johannesen4f0bd682008-10-09 23:00:39 +00002187 roundingMode rounding_mode, bool *isExact) const
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002188{
Neil Booth618d0fc2007-11-01 22:43:37 +00002189 opStatus fs;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002190
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002191 fs = convertToSignExtendedInteger(parts, width, isSigned, rounding_mode,
Dale Johannesen4f0bd682008-10-09 23:00:39 +00002192 isExact);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002193
Neil Booth618d0fc2007-11-01 22:43:37 +00002194 if (fs == opInvalidOp) {
2195 unsigned int bits, dstPartsCount;
2196
2197 dstPartsCount = partCountForBits(width);
2198
2199 if (category == fcNaN)
2200 bits = 0;
2201 else if (sign)
2202 bits = isSigned;
2203 else
2204 bits = width - isSigned;
2205
2206 APInt::tcSetLeastSignificantBits(parts, dstPartsCount, bits);
2207 if (sign && isSigned)
2208 APInt::tcShiftLeft(parts, dstPartsCount, width - 1);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002209 }
2210
Neil Booth618d0fc2007-11-01 22:43:37 +00002211 return fs;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002212}
2213
Jeffrey Yasskin03b81a22011-07-15 07:04:56 +00002214/* Same as convertToInteger(integerPart*, ...), except the result is returned in
2215 an APSInt, whose initial bit-width and signed-ness are used to determine the
2216 precision of the conversion.
2217 */
2218APFloat::opStatus
2219APFloat::convertToInteger(APSInt &result,
2220 roundingMode rounding_mode, bool *isExact) const
2221{
2222 unsigned bitWidth = result.getBitWidth();
2223 SmallVector<uint64_t, 4> parts(result.getNumWords());
2224 opStatus status = convertToInteger(
2225 parts.data(), bitWidth, result.isSigned(), rounding_mode, isExact);
2226 // Keeps the original signed-ness.
Jeffrey Yasskin7a162882011-07-18 21:45:40 +00002227 result = APInt(bitWidth, parts);
Jeffrey Yasskin03b81a22011-07-15 07:04:56 +00002228 return status;
2229}
2230
Neil Booth6c1c8582007-10-07 12:07:53 +00002231/* Convert an unsigned integer SRC to a floating point number,
2232 rounding according to ROUNDING_MODE. The sign of the floating
2233 point number is not modified. */
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002234APFloat::opStatus
Neil Booth6c1c8582007-10-07 12:07:53 +00002235APFloat::convertFromUnsignedParts(const integerPart *src,
2236 unsigned int srcCount,
2237 roundingMode rounding_mode)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002238{
Neil Booth49c6aab2007-10-08 14:39:42 +00002239 unsigned int omsb, precision, dstCount;
Neil Booth6c1c8582007-10-07 12:07:53 +00002240 integerPart *dst;
Neil Booth49c6aab2007-10-08 14:39:42 +00002241 lostFraction lost_fraction;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002242
2243 category = fcNormal;
Neil Booth49c6aab2007-10-08 14:39:42 +00002244 omsb = APInt::tcMSB(src, srcCount) + 1;
Neil Booth6c1c8582007-10-07 12:07:53 +00002245 dst = significandParts();
2246 dstCount = partCount();
Neil Booth49c6aab2007-10-08 14:39:42 +00002247 precision = semantics->precision;
Neil Booth6c1c8582007-10-07 12:07:53 +00002248
Nick Lewyckyf66daac2011-10-03 21:30:08 +00002249 /* We want the most significant PRECISION bits of SRC. There may not
Neil Booth49c6aab2007-10-08 14:39:42 +00002250 be that many; extract what we can. */
2251 if (precision <= omsb) {
2252 exponent = omsb - 1;
Neil Booth6c1c8582007-10-07 12:07:53 +00002253 lost_fraction = lostFractionThroughTruncation(src, srcCount,
Neil Booth49c6aab2007-10-08 14:39:42 +00002254 omsb - precision);
2255 APInt::tcExtract(dst, dstCount, src, precision, omsb - precision);
2256 } else {
2257 exponent = precision - 1;
2258 lost_fraction = lfExactlyZero;
2259 APInt::tcExtract(dst, dstCount, src, omsb, 0);
Neil Booth6c1c8582007-10-07 12:07:53 +00002260 }
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002261
2262 return normalize(rounding_mode, lost_fraction);
2263}
2264
Dan Gohman35723eb2008-02-29 01:26:11 +00002265APFloat::opStatus
2266APFloat::convertFromAPInt(const APInt &Val,
2267 bool isSigned,
2268 roundingMode rounding_mode)
2269{
2270 unsigned int partCount = Val.getNumWords();
2271 APInt api = Val;
2272
2273 sign = false;
2274 if (isSigned && api.isNegative()) {
2275 sign = true;
2276 api = -api;
2277 }
2278
2279 return convertFromUnsignedParts(api.getRawData(), partCount, rounding_mode);
2280}
2281
Neil Booth03f58ab2007-10-07 12:15:41 +00002282/* Convert a two's complement integer SRC to a floating point number,
2283 rounding according to ROUNDING_MODE. ISSIGNED is true if the
2284 integer is signed, in which case it must be sign-extended. */
2285APFloat::opStatus
2286APFloat::convertFromSignExtendedInteger(const integerPart *src,
2287 unsigned int srcCount,
2288 bool isSigned,
2289 roundingMode rounding_mode)
2290{
2291 opStatus status;
2292
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002293 if (isSigned &&
2294 APInt::tcExtractBit(src, srcCount * integerPartWidth - 1)) {
Dylan Noblesmith4e69e292014-08-26 02:03:33 +00002295 integerPart *copy;
Neil Booth03f58ab2007-10-07 12:15:41 +00002296
2297 /* If we're signed and negative negate a copy. */
2298 sign = true;
Dylan Noblesmith4e69e292014-08-26 02:03:33 +00002299 copy = new integerPart[srcCount];
Neil Booth03f58ab2007-10-07 12:15:41 +00002300 APInt::tcAssign(copy, src, srcCount);
2301 APInt::tcNegate(copy, srcCount);
2302 status = convertFromUnsignedParts(copy, srcCount, rounding_mode);
Dylan Noblesmith4e69e292014-08-26 02:03:33 +00002303 delete [] copy;
Neil Booth03f58ab2007-10-07 12:15:41 +00002304 } else {
2305 sign = false;
2306 status = convertFromUnsignedParts(src, srcCount, rounding_mode);
2307 }
2308
2309 return status;
2310}
2311
Neil Booth5f009732007-10-07 11:45:55 +00002312/* FIXME: should this just take a const APInt reference? */
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002313APFloat::opStatus
Neil Booth5f009732007-10-07 11:45:55 +00002314APFloat::convertFromZeroExtendedInteger(const integerPart *parts,
2315 unsigned int width, bool isSigned,
2316 roundingMode rounding_mode)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002317{
Dale Johannesen42305122007-09-21 22:09:37 +00002318 unsigned int partCount = partCountForBits(width);
Jeffrey Yasskin7a162882011-07-18 21:45:40 +00002319 APInt api = APInt(width, makeArrayRef(parts, partCount));
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002320
2321 sign = false;
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002322 if (isSigned && APInt::tcExtractBit(parts, width - 1)) {
Dale Johannesen28a2c4a2007-09-30 18:17:01 +00002323 sign = true;
2324 api = -api;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002325 }
2326
Neil Boothba205222007-10-07 12:10:57 +00002327 return convertFromUnsignedParts(api.getRawData(), partCount, rounding_mode);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002328}
2329
2330APFloat::opStatus
Benjamin Kramer92d89982010-07-14 22:38:02 +00002331APFloat::convertFromHexadecimalString(StringRef s, roundingMode rounding_mode)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002332{
Erick Tryzelaara9680df2009-08-18 18:20:37 +00002333 lostFraction lost_fraction = lfExactlyZero;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002334
Michael Gottesman30a90eb2013-07-27 21:49:21 +00002335 category = fcNormal;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002336 zeroSignificand();
2337 exponent = 0;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002338
Eli Friedmand2eb07a2013-07-17 22:17:29 +00002339 integerPart *significand = significandParts();
2340 unsigned partsCount = partCount();
2341 unsigned bitPos = partsCount * integerPartWidth;
2342 bool computedTrailingFraction = false;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002343
Eli Friedmand2eb07a2013-07-17 22:17:29 +00002344 // Skip leading zeroes and any (hexa)decimal point.
Erick Tryzelaarda666c82009-08-20 23:30:43 +00002345 StringRef::iterator begin = s.begin();
2346 StringRef::iterator end = s.end();
Eli Friedmand2eb07a2013-07-17 22:17:29 +00002347 StringRef::iterator dot;
Erick Tryzelaarda666c82009-08-20 23:30:43 +00002348 StringRef::iterator p = skipLeadingZeroesAndAnyDot(begin, end, &dot);
Eli Friedmand2eb07a2013-07-17 22:17:29 +00002349 StringRef::iterator firstSignificantDigit = p;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002350
Eli Friedmand2eb07a2013-07-17 22:17:29 +00002351 while (p != end) {
Dale Johannesenfa483722008-05-14 22:53:25 +00002352 integerPart hex_value;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002353
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002354 if (*p == '.') {
Erick Tryzelaarda666c82009-08-20 23:30:43 +00002355 assert(dot == end && "String contains multiple dots");
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002356 dot = p++;
Eli Friedmand2eb07a2013-07-17 22:17:29 +00002357 continue;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002358 }
2359
2360 hex_value = hexDigitValue(*p);
Eli Friedmand2eb07a2013-07-17 22:17:29 +00002361 if (hex_value == -1U)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002362 break;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002363
2364 p++;
2365
Eli Friedmand2eb07a2013-07-17 22:17:29 +00002366 // Store the number while we have space.
2367 if (bitPos) {
2368 bitPos -= 4;
2369 hex_value <<= bitPos % integerPartWidth;
2370 significand[bitPos / integerPartWidth] |= hex_value;
2371 } else if (!computedTrailingFraction) {
2372 lost_fraction = trailingHexadecimalFraction(p, end, hex_value);
2373 computedTrailingFraction = true;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002374 }
2375 }
2376
2377 /* Hex floats require an exponent but not a hexadecimal point. */
Erick Tryzelaarda666c82009-08-20 23:30:43 +00002378 assert(p != end && "Hex strings require an exponent");
2379 assert((*p == 'p' || *p == 'P') && "Invalid character in significand");
2380 assert(p != begin && "Significand has no digits");
2381 assert((dot == end || p - begin != 1) && "Significand has no digits");
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002382
2383 /* Ignore the exponent if we are zero. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002384 if (p != firstSignificantDigit) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002385 int expAdjustment;
2386
2387 /* Implicit hexadecimal point? */
Erick Tryzelaarda666c82009-08-20 23:30:43 +00002388 if (dot == end)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002389 dot = p;
2390
2391 /* Calculate the exponent adjustment implicit in the number of
2392 significant digits. */
Evan Cheng82b9e962008-05-02 21:15:08 +00002393 expAdjustment = static_cast<int>(dot - firstSignificantDigit);
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002394 if (expAdjustment < 0)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002395 expAdjustment++;
2396 expAdjustment = expAdjustment * 4 - 1;
2397
2398 /* Adjust for writing the significand starting at the most
2399 significant nibble. */
2400 expAdjustment += semantics->precision;
2401 expAdjustment -= partsCount * integerPartWidth;
2402
2403 /* Adjust for the given exponent. */
Erick Tryzelaarda666c82009-08-20 23:30:43 +00002404 exponent = totalExponent(p + 1, end, expAdjustment);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002405 }
2406
2407 return normalize(rounding_mode, lost_fraction);
2408}
2409
2410APFloat::opStatus
Neil Boothb93d90e2007-10-12 16:02:31 +00002411APFloat::roundSignificandWithExponent(const integerPart *decSigParts,
2412 unsigned sigPartCount, int exp,
2413 roundingMode rounding_mode)
2414{
2415 unsigned int parts, pow5PartCount;
Tamas Berghammerb6b0ddf2015-07-09 10:13:39 +00002416 fltSemantics calcSemantics = { 32767, -32767, 0, 0 };
Neil Boothb93d90e2007-10-12 16:02:31 +00002417 integerPart pow5Parts[maxPowerOfFiveParts];
2418 bool isNearest;
2419
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002420 isNearest = (rounding_mode == rmNearestTiesToEven ||
2421 rounding_mode == rmNearestTiesToAway);
Neil Boothb93d90e2007-10-12 16:02:31 +00002422
2423 parts = partCountForBits(semantics->precision + 11);
2424
2425 /* Calculate pow(5, abs(exp)). */
2426 pow5PartCount = powerOf5(pow5Parts, exp >= 0 ? exp: -exp);
2427
2428 for (;; parts *= 2) {
2429 opStatus sigStatus, powStatus;
2430 unsigned int excessPrecision, truncatedBits;
2431
2432 calcSemantics.precision = parts * integerPartWidth - 1;
2433 excessPrecision = calcSemantics.precision - semantics->precision;
2434 truncatedBits = excessPrecision;
2435
Michael Gottesman79b09672013-06-27 21:58:19 +00002436 APFloat decSig = APFloat::getZero(calcSemantics, sign);
2437 APFloat pow5(calcSemantics);
Neil Boothb93d90e2007-10-12 16:02:31 +00002438
2439 sigStatus = decSig.convertFromUnsignedParts(decSigParts, sigPartCount,
2440 rmNearestTiesToEven);
2441 powStatus = pow5.convertFromUnsignedParts(pow5Parts, pow5PartCount,
2442 rmNearestTiesToEven);
2443 /* Add exp, as 10^n = 5^n * 2^n. */
2444 decSig.exponent += exp;
2445
2446 lostFraction calcLostFraction;
Evan Cheng82b9e962008-05-02 21:15:08 +00002447 integerPart HUerr, HUdistance;
2448 unsigned int powHUerr;
Neil Boothb93d90e2007-10-12 16:02:31 +00002449
2450 if (exp >= 0) {
2451 /* multiplySignificand leaves the precision-th bit set to 1. */
Craig Topperc10719f2014-04-07 04:17:22 +00002452 calcLostFraction = decSig.multiplySignificand(pow5, nullptr);
Neil Boothb93d90e2007-10-12 16:02:31 +00002453 powHUerr = powStatus != opOK;
2454 } else {
2455 calcLostFraction = decSig.divideSignificand(pow5);
2456 /* Denormal numbers have less precision. */
2457 if (decSig.exponent < semantics->minExponent) {
2458 excessPrecision += (semantics->minExponent - decSig.exponent);
2459 truncatedBits = excessPrecision;
2460 if (excessPrecision > calcSemantics.precision)
2461 excessPrecision = calcSemantics.precision;
2462 }
2463 /* Extra half-ulp lost in reciprocal of exponent. */
Evan Cheng82b9e962008-05-02 21:15:08 +00002464 powHUerr = (powStatus == opOK && calcLostFraction == lfExactlyZero) ? 0:2;
Neil Boothb93d90e2007-10-12 16:02:31 +00002465 }
2466
2467 /* Both multiplySignificand and divideSignificand return the
2468 result with the integer bit set. */
Evan Cheng67c90212009-10-27 21:35:42 +00002469 assert(APInt::tcExtractBit
2470 (decSig.significandParts(), calcSemantics.precision - 1) == 1);
Neil Boothb93d90e2007-10-12 16:02:31 +00002471
2472 HUerr = HUerrBound(calcLostFraction != lfExactlyZero, sigStatus != opOK,
2473 powHUerr);
2474 HUdistance = 2 * ulpsFromBoundary(decSig.significandParts(),
2475 excessPrecision, isNearest);
2476
2477 /* Are we guaranteed to round correctly if we truncate? */
2478 if (HUdistance >= HUerr) {
2479 APInt::tcExtract(significandParts(), partCount(), decSig.significandParts(),
2480 calcSemantics.precision - excessPrecision,
2481 excessPrecision);
2482 /* Take the exponent of decSig. If we tcExtract-ed less bits
2483 above we must adjust our exponent to compensate for the
2484 implicit right shift. */
2485 exponent = (decSig.exponent + semantics->precision
2486 - (calcSemantics.precision - excessPrecision));
2487 calcLostFraction = lostFractionThroughTruncation(decSig.significandParts(),
2488 decSig.partCount(),
2489 truncatedBits);
2490 return normalize(rounding_mode, calcLostFraction);
2491 }
2492 }
2493}
2494
2495APFloat::opStatus
Benjamin Kramer92d89982010-07-14 22:38:02 +00002496APFloat::convertFromDecimalString(StringRef str, roundingMode rounding_mode)
Neil Boothb93d90e2007-10-12 16:02:31 +00002497{
Neil Booth4ed401b2007-10-14 10:16:12 +00002498 decimalInfo D;
Neil Boothb93d90e2007-10-12 16:02:31 +00002499 opStatus fs;
2500
Neil Booth4ed401b2007-10-14 10:16:12 +00002501 /* Scan the text. */
Erick Tryzelaar19f63b22009-08-16 23:36:19 +00002502 StringRef::iterator p = str.begin();
2503 interpretDecimal(p, str.end(), &D);
Neil Boothb93d90e2007-10-12 16:02:31 +00002504
Neil Booth91305512007-10-15 15:00:55 +00002505 /* Handle the quick cases. First the case of no significant digits,
2506 i.e. zero, and then exponents that are obviously too large or too
2507 small. Writing L for log 10 / log 2, a number d.ddddd*10^exp
2508 definitely overflows if
2509
2510 (exp - 1) * L >= maxExponent
2511
2512 and definitely underflows to zero where
2513
2514 (exp + 1) * L <= minExponent - precision
2515
2516 With integer arithmetic the tightest bounds for L are
2517
2518 93/28 < L < 196/59 [ numerator <= 256 ]
2519 42039/12655 < L < 28738/8651 [ numerator <= 65536 ]
2520 */
2521
Michael Gottesman228156c2013-07-01 23:54:08 +00002522 // Test if we have a zero number allowing for strings with no null terminators
2523 // and zero decimals with non-zero exponents.
2524 //
2525 // We computed firstSigDigit by ignoring all zeros and dots. Thus if
2526 // D->firstSigDigit equals str.end(), every digit must be a zero and there can
2527 // be at most one dot. On the other hand, if we have a zero with a non-zero
2528 // exponent, then we know that D.firstSigDigit will be non-numeric.
Michael Gottesman94d61952013-07-02 15:50:05 +00002529 if (D.firstSigDigit == str.end() || decDigitValue(*D.firstSigDigit) >= 10U) {
Neil Boothb93d90e2007-10-12 16:02:31 +00002530 category = fcZero;
2531 fs = opOK;
John McCallb42cc682010-02-26 22:20:41 +00002532
2533 /* Check whether the normalized exponent is high enough to overflow
2534 max during the log-rebasing in the max-exponent check below. */
2535 } else if (D.normalizedExponent - 1 > INT_MAX / 42039) {
2536 fs = handleOverflow(rounding_mode);
2537
2538 /* If it wasn't, then it also wasn't high enough to overflow max
2539 during the log-rebasing in the min-exponent check. Check that it
2540 won't overflow min in either check, then perform the min-exponent
2541 check. */
2542 } else if (D.normalizedExponent - 1 < INT_MIN / 42039 ||
2543 (D.normalizedExponent + 1) * 28738 <=
2544 8651 * (semantics->minExponent - (int) semantics->precision)) {
Neil Booth91305512007-10-15 15:00:55 +00002545 /* Underflow to zero and round. */
Michael Gottesman30a90eb2013-07-27 21:49:21 +00002546 category = fcNormal;
Neil Booth91305512007-10-15 15:00:55 +00002547 zeroSignificand();
2548 fs = normalize(rounding_mode, lfLessThanHalf);
John McCallb42cc682010-02-26 22:20:41 +00002549
2550 /* We can finally safely perform the max-exponent check. */
Neil Booth91305512007-10-15 15:00:55 +00002551 } else if ((D.normalizedExponent - 1) * 42039
2552 >= 12655 * semantics->maxExponent) {
2553 /* Overflow and round. */
2554 fs = handleOverflow(rounding_mode);
Neil Boothb93d90e2007-10-12 16:02:31 +00002555 } else {
Dylan Noblesmith4e69e292014-08-26 02:03:33 +00002556 integerPart *decSignificand;
Neil Booth4ed401b2007-10-14 10:16:12 +00002557 unsigned int partCount;
Neil Boothb93d90e2007-10-12 16:02:31 +00002558
Neil Booth4ed401b2007-10-14 10:16:12 +00002559 /* A tight upper bound on number of bits required to hold an
Neil Booth91305512007-10-15 15:00:55 +00002560 N-digit decimal integer is N * 196 / 59. Allocate enough space
Neil Booth4ed401b2007-10-14 10:16:12 +00002561 to hold the full significand, and an extra part required by
2562 tcMultiplyPart. */
Evan Cheng82b9e962008-05-02 21:15:08 +00002563 partCount = static_cast<unsigned int>(D.lastSigDigit - D.firstSigDigit) + 1;
Neil Booth91305512007-10-15 15:00:55 +00002564 partCount = partCountForBits(1 + 196 * partCount / 59);
Dylan Noblesmith4e69e292014-08-26 02:03:33 +00002565 decSignificand = new integerPart[partCount + 1];
Neil Booth4ed401b2007-10-14 10:16:12 +00002566 partCount = 0;
Neil Boothb93d90e2007-10-12 16:02:31 +00002567
Neil Booth4ed401b2007-10-14 10:16:12 +00002568 /* Convert to binary efficiently - we do almost all multiplication
2569 in an integerPart. When this would overflow do we do a single
2570 bignum multiplication, and then revert again to multiplication
2571 in an integerPart. */
2572 do {
2573 integerPart decValue, val, multiplier;
2574
2575 val = 0;
2576 multiplier = 1;
2577
2578 do {
Erick Tryzelaar19f63b22009-08-16 23:36:19 +00002579 if (*p == '.') {
Neil Booth4ed401b2007-10-14 10:16:12 +00002580 p++;
Erick Tryzelaar19f63b22009-08-16 23:36:19 +00002581 if (p == str.end()) {
2582 break;
2583 }
2584 }
Neil Booth4ed401b2007-10-14 10:16:12 +00002585 decValue = decDigitValue(*p++);
Erick Tryzelaarda666c82009-08-20 23:30:43 +00002586 assert(decValue < 10U && "Invalid character in significand");
Neil Booth4ed401b2007-10-14 10:16:12 +00002587 multiplier *= 10;
2588 val = val * 10 + decValue;
2589 /* The maximum number that can be multiplied by ten with any
2590 digit added without overflowing an integerPart. */
2591 } while (p <= D.lastSigDigit && multiplier <= (~ (integerPart) 0 - 9) / 10);
2592
2593 /* Multiply out the current part. */
2594 APInt::tcMultiplyPart(decSignificand, decSignificand, multiplier, val,
2595 partCount, partCount + 1, false);
2596
2597 /* If we used another part (likely but not guaranteed), increase
2598 the count. */
2599 if (decSignificand[partCount])
2600 partCount++;
2601 } while (p <= D.lastSigDigit);
Neil Boothb93d90e2007-10-12 16:02:31 +00002602
Neil Boothae077d22007-11-01 22:51:07 +00002603 category = fcNormal;
Neil Boothb93d90e2007-10-12 16:02:31 +00002604 fs = roundSignificandWithExponent(decSignificand, partCount,
Neil Booth4ed401b2007-10-14 10:16:12 +00002605 D.exponent, rounding_mode);
Dylan Noblesmith4e69e292014-08-26 02:03:33 +00002606
2607 delete [] decSignificand;
Neil Booth4ed401b2007-10-14 10:16:12 +00002608 }
Neil Boothb93d90e2007-10-12 16:02:31 +00002609
2610 return fs;
2611}
2612
Michael Gottesman40e8a182013-06-24 09:58:05 +00002613bool
2614APFloat::convertFromStringSpecials(StringRef str) {
2615 if (str.equals("inf") || str.equals("INFINITY")) {
2616 makeInf(false);
2617 return true;
2618 }
2619
2620 if (str.equals("-inf") || str.equals("-INFINITY")) {
2621 makeInf(true);
2622 return true;
2623 }
2624
2625 if (str.equals("nan") || str.equals("NaN")) {
2626 makeNaN(false, false);
2627 return true;
2628 }
2629
2630 if (str.equals("-nan") || str.equals("-NaN")) {
2631 makeNaN(false, true);
2632 return true;
2633 }
2634
2635 return false;
2636}
2637
Neil Boothb93d90e2007-10-12 16:02:31 +00002638APFloat::opStatus
Benjamin Kramer92d89982010-07-14 22:38:02 +00002639APFloat::convertFromString(StringRef str, roundingMode rounding_mode)
Neil Booth9acbf5a2007-09-26 21:33:42 +00002640{
Erick Tryzelaar19f63b22009-08-16 23:36:19 +00002641 assert(!str.empty() && "Invalid string length");
Neil Booth06077e72007-10-14 10:29:28 +00002642
Michael Gottesman40e8a182013-06-24 09:58:05 +00002643 // Handle special cases.
2644 if (convertFromStringSpecials(str))
2645 return opOK;
2646
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002647 /* Handle a leading minus sign. */
Erick Tryzelaar19f63b22009-08-16 23:36:19 +00002648 StringRef::iterator p = str.begin();
2649 size_t slen = str.size();
Erick Tryzelaarda666c82009-08-20 23:30:43 +00002650 sign = *p == '-' ? 1 : 0;
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002651 if (*p == '-' || *p == '+') {
Erick Tryzelaar19f63b22009-08-16 23:36:19 +00002652 p++;
2653 slen--;
Erick Tryzelaarda666c82009-08-20 23:30:43 +00002654 assert(slen && "String has no digits");
Erick Tryzelaar19f63b22009-08-16 23:36:19 +00002655 }
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002656
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002657 if (slen >= 2 && p[0] == '0' && (p[1] == 'x' || p[1] == 'X')) {
Erick Tryzelaar19f63b22009-08-16 23:36:19 +00002658 assert(slen - 2 && "Invalid string");
Erick Tryzelaarda666c82009-08-20 23:30:43 +00002659 return convertFromHexadecimalString(StringRef(p + 2, slen - 2),
Erick Tryzelaar19f63b22009-08-16 23:36:19 +00002660 rounding_mode);
2661 }
Bill Wendlingc6075402008-11-27 08:00:12 +00002662
Erick Tryzelaarda666c82009-08-20 23:30:43 +00002663 return convertFromDecimalString(StringRef(p, slen), rounding_mode);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002664}
Dale Johannesena719a602007-08-24 00:56:33 +00002665
Neil Booth8f1946f2007-10-03 22:26:02 +00002666/* Write out a hexadecimal representation of the floating point value
2667 to DST, which must be of sufficient size, in the C99 form
2668 [-]0xh.hhhhp[+-]d. Return the number of characters written,
2669 excluding the terminating NUL.
2670
2671 If UPPERCASE, the output is in upper case, otherwise in lower case.
2672
2673 HEXDIGITS digits appear altogether, rounding the value if
2674 necessary. If HEXDIGITS is 0, the minimal precision to display the
2675 number precisely is used instead. If nothing would appear after
2676 the decimal point it is suppressed.
2677
2678 The decimal exponent is always printed and has at least one digit.
2679 Zero values display an exponent of zero. Infinities and NaNs
2680 appear as "infinity" or "nan" respectively.
2681
2682 The above rules are as specified by C99. There is ambiguity about
2683 what the leading hexadecimal digit should be. This implementation
2684 uses whatever is necessary so that the exponent is displayed as
2685 stored. This implies the exponent will fall within the IEEE format
2686 range, and the leading hexadecimal digit will be 0 (for denormals),
2687 1 (normal numbers) or 2 (normal numbers rounded-away-from-zero with
2688 any other digits zero).
2689*/
2690unsigned int
2691APFloat::convertToHexString(char *dst, unsigned int hexDigits,
2692 bool upperCase, roundingMode rounding_mode) const
2693{
2694 char *p;
2695
2696 p = dst;
2697 if (sign)
2698 *dst++ = '-';
2699
2700 switch (category) {
2701 case fcInfinity:
2702 memcpy (dst, upperCase ? infinityU: infinityL, sizeof infinityU - 1);
2703 dst += sizeof infinityL - 1;
2704 break;
2705
2706 case fcNaN:
2707 memcpy (dst, upperCase ? NaNU: NaNL, sizeof NaNU - 1);
2708 dst += sizeof NaNU - 1;
2709 break;
2710
2711 case fcZero:
2712 *dst++ = '0';
2713 *dst++ = upperCase ? 'X': 'x';
2714 *dst++ = '0';
2715 if (hexDigits > 1) {
2716 *dst++ = '.';
2717 memset (dst, '0', hexDigits - 1);
2718 dst += hexDigits - 1;
2719 }
2720 *dst++ = upperCase ? 'P': 'p';
2721 *dst++ = '0';
2722 break;
2723
2724 case fcNormal:
2725 dst = convertNormalToHexString (dst, hexDigits, upperCase, rounding_mode);
2726 break;
2727 }
2728
2729 *dst = 0;
2730
Evan Cheng82b9e962008-05-02 21:15:08 +00002731 return static_cast<unsigned int>(dst - p);
Neil Booth8f1946f2007-10-03 22:26:02 +00002732}
2733
2734/* Does the hard work of outputting the correctly rounded hexadecimal
2735 form of a normal floating point number with the specified number of
2736 hexadecimal digits. If HEXDIGITS is zero the minimum number of
2737 digits necessary to print the value precisely is output. */
2738char *
2739APFloat::convertNormalToHexString(char *dst, unsigned int hexDigits,
2740 bool upperCase,
2741 roundingMode rounding_mode) const
2742{
2743 unsigned int count, valueBits, shift, partsCount, outputDigits;
2744 const char *hexDigitChars;
2745 const integerPart *significand;
2746 char *p;
2747 bool roundUp;
2748
2749 *dst++ = '0';
2750 *dst++ = upperCase ? 'X': 'x';
2751
2752 roundUp = false;
2753 hexDigitChars = upperCase ? hexDigitsUpper: hexDigitsLower;
2754
2755 significand = significandParts();
2756 partsCount = partCount();
2757
2758 /* +3 because the first digit only uses the single integer bit, so
2759 we have 3 virtual zero most-significant-bits. */
2760 valueBits = semantics->precision + 3;
2761 shift = integerPartWidth - valueBits % integerPartWidth;
2762
2763 /* The natural number of digits required ignoring trailing
2764 insignificant zeroes. */
2765 outputDigits = (valueBits - significandLSB () + 3) / 4;
2766
2767 /* hexDigits of zero means use the required number for the
2768 precision. Otherwise, see if we are truncating. If we are,
Neil Booth0ea72a92007-10-06 00:24:48 +00002769 find out if we need to round away from zero. */
Neil Booth8f1946f2007-10-03 22:26:02 +00002770 if (hexDigits) {
2771 if (hexDigits < outputDigits) {
2772 /* We are dropping non-zero bits, so need to check how to round.
2773 "bits" is the number of dropped bits. */
2774 unsigned int bits;
2775 lostFraction fraction;
2776
2777 bits = valueBits - hexDigits * 4;
2778 fraction = lostFractionThroughTruncation (significand, partsCount, bits);
2779 roundUp = roundAwayFromZero(rounding_mode, fraction, bits);
2780 }
2781 outputDigits = hexDigits;
2782 }
2783
2784 /* Write the digits consecutively, and start writing in the location
2785 of the hexadecimal point. We move the most significant digit
2786 left and add the hexadecimal point later. */
2787 p = ++dst;
2788
2789 count = (valueBits + integerPartWidth - 1) / integerPartWidth;
2790
2791 while (outputDigits && count) {
2792 integerPart part;
2793
2794 /* Put the most significant integerPartWidth bits in "part". */
2795 if (--count == partsCount)
2796 part = 0; /* An imaginary higher zero part. */
2797 else
2798 part = significand[count] << shift;
2799
2800 if (count && shift)
2801 part |= significand[count - 1] >> (integerPartWidth - shift);
2802
2803 /* Convert as much of "part" to hexdigits as we can. */
2804 unsigned int curDigits = integerPartWidth / 4;
2805
2806 if (curDigits > outputDigits)
2807 curDigits = outputDigits;
2808 dst += partAsHex (dst, part, curDigits, hexDigitChars);
2809 outputDigits -= curDigits;
2810 }
2811
2812 if (roundUp) {
2813 char *q = dst;
2814
2815 /* Note that hexDigitChars has a trailing '0'. */
2816 do {
2817 q--;
2818 *q = hexDigitChars[hexDigitValue (*q) + 1];
Neil Booth0ea72a92007-10-06 00:24:48 +00002819 } while (*q == '0');
Evan Cheng67c90212009-10-27 21:35:42 +00002820 assert(q >= p);
Neil Booth8f1946f2007-10-03 22:26:02 +00002821 } else {
2822 /* Add trailing zeroes. */
2823 memset (dst, '0', outputDigits);
2824 dst += outputDigits;
2825 }
2826
2827 /* Move the most significant digit to before the point, and if there
2828 is something after the decimal point add it. This must come
2829 after rounding above. */
2830 p[-1] = p[0];
2831 if (dst -1 == p)
2832 dst--;
2833 else
2834 p[0] = '.';
2835
2836 /* Finally output the exponent. */
2837 *dst++ = upperCase ? 'P': 'p';
2838
Neil Booth32897f52007-10-06 07:29:25 +00002839 return writeSignedDecimal (dst, exponent);
Neil Booth8f1946f2007-10-03 22:26:02 +00002840}
2841
Chandler Carruth71bd7d12012-03-04 12:02:57 +00002842hash_code llvm::hash_value(const APFloat &Arg) {
Michael Gottesman8136c382013-06-26 23:17:28 +00002843 if (!Arg.isFiniteNonZero())
Chandler Carruth71bd7d12012-03-04 12:02:57 +00002844 return hash_combine((uint8_t)Arg.category,
2845 // NaN has no sign, fix it at zero.
2846 Arg.isNaN() ? (uint8_t)0 : (uint8_t)Arg.sign,
2847 Arg.semantics->precision);
2848
2849 // Normal floats need their exponent and significand hashed.
2850 return hash_combine((uint8_t)Arg.category, (uint8_t)Arg.sign,
2851 Arg.semantics->precision, Arg.exponent,
2852 hash_combine_range(
2853 Arg.significandParts(),
2854 Arg.significandParts() + Arg.partCount()));
Dale Johannesena719a602007-08-24 00:56:33 +00002855}
2856
2857// Conversion from APFloat to/from host float/double. It may eventually be
2858// possible to eliminate these and have everybody deal with APFloats, but that
2859// will take a while. This approach will not easily extend to long double.
Dale Johannesen146a0ea2007-09-20 23:47:58 +00002860// Current implementation requires integerPartWidth==64, which is correct at
2861// the moment but could be made more general.
Dale Johannesena719a602007-08-24 00:56:33 +00002862
Dale Johannesen728687c2007-09-05 20:39:49 +00002863// Denormals have exponent minExponent in APFloat, but minExponent-1 in
Dale Johannesen146a0ea2007-09-20 23:47:58 +00002864// the actual IEEE respresentations. We compensate for that here.
Dale Johannesen728687c2007-09-05 20:39:49 +00002865
Dale Johannesen245dceb2007-09-11 18:32:33 +00002866APInt
Neil Booth9acbf5a2007-09-26 21:33:42 +00002867APFloat::convertF80LongDoubleAPFloatToAPInt() const
2868{
Dan Gohmanb456a152008-01-29 12:08:20 +00002869 assert(semantics == (const llvm::fltSemantics*)&x87DoubleExtended);
Evan Cheng67c90212009-10-27 21:35:42 +00002870 assert(partCount()==2);
Dale Johannesen245dceb2007-09-11 18:32:33 +00002871
2872 uint64_t myexponent, mysignificand;
2873
Michael Gottesman8136c382013-06-26 23:17:28 +00002874 if (isFiniteNonZero()) {
Dale Johannesen245dceb2007-09-11 18:32:33 +00002875 myexponent = exponent+16383; //bias
Dale Johannesen146a0ea2007-09-20 23:47:58 +00002876 mysignificand = significandParts()[0];
Dale Johannesen245dceb2007-09-11 18:32:33 +00002877 if (myexponent==1 && !(mysignificand & 0x8000000000000000ULL))
2878 myexponent = 0; // denormal
2879 } else if (category==fcZero) {
2880 myexponent = 0;
2881 mysignificand = 0;
2882 } else if (category==fcInfinity) {
2883 myexponent = 0x7fff;
2884 mysignificand = 0x8000000000000000ULL;
Chris Lattner2a9bcb92007-10-06 06:13:42 +00002885 } else {
2886 assert(category == fcNaN && "Unknown category");
Dale Johannesen245dceb2007-09-11 18:32:33 +00002887 myexponent = 0x7fff;
Dale Johannesen146a0ea2007-09-20 23:47:58 +00002888 mysignificand = significandParts()[0];
Chris Lattner2a9bcb92007-10-06 06:13:42 +00002889 }
Dale Johannesen245dceb2007-09-11 18:32:33 +00002890
2891 uint64_t words[2];
Dale Johannesen93eefa02009-03-23 21:16:53 +00002892 words[0] = mysignificand;
2893 words[1] = ((uint64_t)(sign & 1) << 15) |
2894 (myexponent & 0x7fffLL);
Jeffrey Yasskin7a162882011-07-18 21:45:40 +00002895 return APInt(80, words);
Dale Johannesen245dceb2007-09-11 18:32:33 +00002896}
2897
2898APInt
Dale Johannesen007aa372007-10-11 18:07:22 +00002899APFloat::convertPPCDoubleDoubleAPFloatToAPInt() const
2900{
Dan Gohmanb456a152008-01-29 12:08:20 +00002901 assert(semantics == (const llvm::fltSemantics*)&PPCDoubleDouble);
Evan Cheng67c90212009-10-27 21:35:42 +00002902 assert(partCount()==2);
Dale Johannesen007aa372007-10-11 18:07:22 +00002903
Ulrich Weigandd9f7e252012-10-29 18:09:01 +00002904 uint64_t words[2];
2905 opStatus fs;
2906 bool losesInfo;
Dale Johannesen007aa372007-10-11 18:07:22 +00002907
Ulrich Weigandd9f7e252012-10-29 18:09:01 +00002908 // Convert number to double. To avoid spurious underflows, we re-
2909 // normalize against the "double" minExponent first, and only *then*
2910 // truncate the mantissa. The result of that second conversion
2911 // may be inexact, but should never underflow.
Alexey Samsonov2b431d92012-11-30 22:27:54 +00002912 // Declare fltSemantics before APFloat that uses it (and
2913 // saves pointer to it) to ensure correct destruction order.
Ulrich Weigandd9f7e252012-10-29 18:09:01 +00002914 fltSemantics extendedSemantics = *semantics;
2915 extendedSemantics.minExponent = IEEEdouble.minExponent;
Alexey Samsonov2b431d92012-11-30 22:27:54 +00002916 APFloat extended(*this);
Ulrich Weigandd9f7e252012-10-29 18:09:01 +00002917 fs = extended.convert(extendedSemantics, rmNearestTiesToEven, &losesInfo);
2918 assert(fs == opOK && !losesInfo);
2919 (void)fs;
2920
2921 APFloat u(extended);
2922 fs = u.convert(IEEEdouble, rmNearestTiesToEven, &losesInfo);
2923 assert(fs == opOK || fs == opInexact);
2924 (void)fs;
2925 words[0] = *u.convertDoubleAPFloatToAPInt().getRawData();
2926
2927 // If conversion was exact or resulted in a special case, we're done;
2928 // just set the second double to zero. Otherwise, re-convert back to
2929 // the extended format and compute the difference. This now should
2930 // convert exactly to double.
Michael Gottesman8136c382013-06-26 23:17:28 +00002931 if (u.isFiniteNonZero() && losesInfo) {
Ulrich Weigandd9f7e252012-10-29 18:09:01 +00002932 fs = u.convert(extendedSemantics, rmNearestTiesToEven, &losesInfo);
2933 assert(fs == opOK && !losesInfo);
2934 (void)fs;
2935
2936 APFloat v(extended);
2937 v.subtract(u, rmNearestTiesToEven);
2938 fs = v.convert(IEEEdouble, rmNearestTiesToEven, &losesInfo);
2939 assert(fs == opOK && !losesInfo);
2940 (void)fs;
2941 words[1] = *v.convertDoubleAPFloatToAPInt().getRawData();
Dale Johannesen007aa372007-10-11 18:07:22 +00002942 } else {
Ulrich Weigandd9f7e252012-10-29 18:09:01 +00002943 words[1] = 0;
Dale Johannesen007aa372007-10-11 18:07:22 +00002944 }
2945
Jeffrey Yasskin7a162882011-07-18 21:45:40 +00002946 return APInt(128, words);
Dale Johannesen007aa372007-10-11 18:07:22 +00002947}
2948
2949APInt
Anton Korobeynikov13e8c7e2009-08-21 22:10:30 +00002950APFloat::convertQuadrupleAPFloatToAPInt() const
2951{
2952 assert(semantics == (const llvm::fltSemantics*)&IEEEquad);
Evan Cheng67c90212009-10-27 21:35:42 +00002953 assert(partCount()==2);
Anton Korobeynikov13e8c7e2009-08-21 22:10:30 +00002954
2955 uint64_t myexponent, mysignificand, mysignificand2;
2956
Michael Gottesman8136c382013-06-26 23:17:28 +00002957 if (isFiniteNonZero()) {
Anton Korobeynikov13e8c7e2009-08-21 22:10:30 +00002958 myexponent = exponent+16383; //bias
2959 mysignificand = significandParts()[0];
2960 mysignificand2 = significandParts()[1];
2961 if (myexponent==1 && !(mysignificand2 & 0x1000000000000LL))
2962 myexponent = 0; // denormal
2963 } else if (category==fcZero) {
2964 myexponent = 0;
2965 mysignificand = mysignificand2 = 0;
2966 } else if (category==fcInfinity) {
2967 myexponent = 0x7fff;
2968 mysignificand = mysignificand2 = 0;
2969 } else {
2970 assert(category == fcNaN && "Unknown category!");
2971 myexponent = 0x7fff;
2972 mysignificand = significandParts()[0];
2973 mysignificand2 = significandParts()[1];
2974 }
2975
2976 uint64_t words[2];
2977 words[0] = mysignificand;
2978 words[1] = ((uint64_t)(sign & 1) << 63) |
2979 ((myexponent & 0x7fff) << 48) |
Anton Korobeynikov876955c2009-08-21 23:09:47 +00002980 (mysignificand2 & 0xffffffffffffLL);
Anton Korobeynikov13e8c7e2009-08-21 22:10:30 +00002981
Jeffrey Yasskin7a162882011-07-18 21:45:40 +00002982 return APInt(128, words);
Anton Korobeynikov13e8c7e2009-08-21 22:10:30 +00002983}
2984
2985APInt
Neil Booth9acbf5a2007-09-26 21:33:42 +00002986APFloat::convertDoubleAPFloatToAPInt() const
2987{
Dan Gohman58c468f2007-09-14 20:08:19 +00002988 assert(semantics == (const llvm::fltSemantics*)&IEEEdouble);
Evan Cheng67c90212009-10-27 21:35:42 +00002989 assert(partCount()==1);
Dale Johannesena719a602007-08-24 00:56:33 +00002990
Dale Johannesen3cf889f2007-08-31 04:03:46 +00002991 uint64_t myexponent, mysignificand;
Dale Johannesena719a602007-08-24 00:56:33 +00002992
Michael Gottesman8136c382013-06-26 23:17:28 +00002993 if (isFiniteNonZero()) {
Dale Johannesena719a602007-08-24 00:56:33 +00002994 myexponent = exponent+1023; //bias
Dale Johannesen728687c2007-09-05 20:39:49 +00002995 mysignificand = *significandParts();
2996 if (myexponent==1 && !(mysignificand & 0x10000000000000LL))
2997 myexponent = 0; // denormal
Dale Johannesena719a602007-08-24 00:56:33 +00002998 } else if (category==fcZero) {
Dale Johannesena719a602007-08-24 00:56:33 +00002999 myexponent = 0;
3000 mysignificand = 0;
3001 } else if (category==fcInfinity) {
Dale Johannesena719a602007-08-24 00:56:33 +00003002 myexponent = 0x7ff;
3003 mysignificand = 0;
Chris Lattner2a9bcb92007-10-06 06:13:42 +00003004 } else {
3005 assert(category == fcNaN && "Unknown category!");
Dale Johannesena719a602007-08-24 00:56:33 +00003006 myexponent = 0x7ff;
Dale Johannesen3cf889f2007-08-31 04:03:46 +00003007 mysignificand = *significandParts();
Chris Lattner2a9bcb92007-10-06 06:13:42 +00003008 }
Dale Johannesena719a602007-08-24 00:56:33 +00003009
Evan Cheng82b9e962008-05-02 21:15:08 +00003010 return APInt(64, ((((uint64_t)(sign & 1) << 63) |
Chris Lattner2a9bcb92007-10-06 06:13:42 +00003011 ((myexponent & 0x7ff) << 52) |
3012 (mysignificand & 0xfffffffffffffLL))));
Dale Johannesena719a602007-08-24 00:56:33 +00003013}
3014
Dale Johannesen245dceb2007-09-11 18:32:33 +00003015APInt
Neil Booth9acbf5a2007-09-26 21:33:42 +00003016APFloat::convertFloatAPFloatToAPInt() const
3017{
Dan Gohman58c468f2007-09-14 20:08:19 +00003018 assert(semantics == (const llvm::fltSemantics*)&IEEEsingle);
Evan Cheng67c90212009-10-27 21:35:42 +00003019 assert(partCount()==1);
Neil Booth9acbf5a2007-09-26 21:33:42 +00003020
Dale Johannesen3cf889f2007-08-31 04:03:46 +00003021 uint32_t myexponent, mysignificand;
Dale Johannesena719a602007-08-24 00:56:33 +00003022
Michael Gottesman8136c382013-06-26 23:17:28 +00003023 if (isFiniteNonZero()) {
Dale Johannesena719a602007-08-24 00:56:33 +00003024 myexponent = exponent+127; //bias
Evan Cheng82b9e962008-05-02 21:15:08 +00003025 mysignificand = (uint32_t)*significandParts();
Dale Johannesen06a10df2007-11-17 01:02:27 +00003026 if (myexponent == 1 && !(mysignificand & 0x800000))
Dale Johannesen728687c2007-09-05 20:39:49 +00003027 myexponent = 0; // denormal
Dale Johannesena719a602007-08-24 00:56:33 +00003028 } else if (category==fcZero) {
Dale Johannesena719a602007-08-24 00:56:33 +00003029 myexponent = 0;
3030 mysignificand = 0;
3031 } else if (category==fcInfinity) {
Dale Johannesena719a602007-08-24 00:56:33 +00003032 myexponent = 0xff;
3033 mysignificand = 0;
Chris Lattner2a9bcb92007-10-06 06:13:42 +00003034 } else {
3035 assert(category == fcNaN && "Unknown category!");
Dale Johannesen728687c2007-09-05 20:39:49 +00003036 myexponent = 0xff;
Evan Cheng82b9e962008-05-02 21:15:08 +00003037 mysignificand = (uint32_t)*significandParts();
Chris Lattner2a9bcb92007-10-06 06:13:42 +00003038 }
Dale Johannesena719a602007-08-24 00:56:33 +00003039
Chris Lattner2a9bcb92007-10-06 06:13:42 +00003040 return APInt(32, (((sign&1) << 31) | ((myexponent&0xff) << 23) |
3041 (mysignificand & 0x7fffff)));
Dale Johannesena719a602007-08-24 00:56:33 +00003042}
3043
Chris Lattner4794b2b2009-10-16 02:13:51 +00003044APInt
3045APFloat::convertHalfAPFloatToAPInt() const
3046{
3047 assert(semantics == (const llvm::fltSemantics*)&IEEEhalf);
Evan Cheng67c90212009-10-27 21:35:42 +00003048 assert(partCount()==1);
Chris Lattner4794b2b2009-10-16 02:13:51 +00003049
3050 uint32_t myexponent, mysignificand;
3051
Michael Gottesman8136c382013-06-26 23:17:28 +00003052 if (isFiniteNonZero()) {
Chris Lattner4794b2b2009-10-16 02:13:51 +00003053 myexponent = exponent+15; //bias
3054 mysignificand = (uint32_t)*significandParts();
3055 if (myexponent == 1 && !(mysignificand & 0x400))
3056 myexponent = 0; // denormal
3057 } else if (category==fcZero) {
3058 myexponent = 0;
3059 mysignificand = 0;
3060 } else if (category==fcInfinity) {
Dale Johannesen0d670b52009-10-23 04:02:51 +00003061 myexponent = 0x1f;
Chris Lattner4794b2b2009-10-16 02:13:51 +00003062 mysignificand = 0;
3063 } else {
3064 assert(category == fcNaN && "Unknown category!");
Dale Johannesen0d670b52009-10-23 04:02:51 +00003065 myexponent = 0x1f;
Chris Lattner4794b2b2009-10-16 02:13:51 +00003066 mysignificand = (uint32_t)*significandParts();
3067 }
3068
3069 return APInt(16, (((sign&1) << 15) | ((myexponent&0x1f) << 10) |
3070 (mysignificand & 0x3ff)));
3071}
3072
Dale Johannesen007aa372007-10-11 18:07:22 +00003073// This function creates an APInt that is just a bit map of the floating
3074// point constant as it would appear in memory. It is not a conversion,
3075// and treating the result as a normal integer is unlikely to be useful.
3076
Dale Johannesen245dceb2007-09-11 18:32:33 +00003077APInt
Dale Johannesen54306fe2008-10-09 18:53:47 +00003078APFloat::bitcastToAPInt() const
Neil Booth9acbf5a2007-09-26 21:33:42 +00003079{
Chris Lattner4794b2b2009-10-16 02:13:51 +00003080 if (semantics == (const llvm::fltSemantics*)&IEEEhalf)
3081 return convertHalfAPFloatToAPInt();
3082
Dan Gohmanb456a152008-01-29 12:08:20 +00003083 if (semantics == (const llvm::fltSemantics*)&IEEEsingle)
Dale Johannesen245dceb2007-09-11 18:32:33 +00003084 return convertFloatAPFloatToAPInt();
Anton Korobeynikov13e8c7e2009-08-21 22:10:30 +00003085
Dan Gohmanb456a152008-01-29 12:08:20 +00003086 if (semantics == (const llvm::fltSemantics*)&IEEEdouble)
Dale Johannesen245dceb2007-09-11 18:32:33 +00003087 return convertDoubleAPFloatToAPInt();
Neil Booth9acbf5a2007-09-26 21:33:42 +00003088
Anton Korobeynikov13e8c7e2009-08-21 22:10:30 +00003089 if (semantics == (const llvm::fltSemantics*)&IEEEquad)
3090 return convertQuadrupleAPFloatToAPInt();
3091
Dan Gohmanb456a152008-01-29 12:08:20 +00003092 if (semantics == (const llvm::fltSemantics*)&PPCDoubleDouble)
Dale Johannesen007aa372007-10-11 18:07:22 +00003093 return convertPPCDoubleDoubleAPFloatToAPInt();
3094
Dan Gohmanb456a152008-01-29 12:08:20 +00003095 assert(semantics == (const llvm::fltSemantics*)&x87DoubleExtended &&
Chris Lattner2a9bcb92007-10-06 06:13:42 +00003096 "unknown format!");
3097 return convertF80LongDoubleAPFloatToAPInt();
Dale Johannesen245dceb2007-09-11 18:32:33 +00003098}
3099
Neil Booth9acbf5a2007-09-26 21:33:42 +00003100float
3101APFloat::convertToFloat() const
3102{
Chris Lattner688f9912009-09-24 21:44:20 +00003103 assert(semantics == (const llvm::fltSemantics*)&IEEEsingle &&
3104 "Float semantics are not IEEEsingle");
Dale Johannesen54306fe2008-10-09 18:53:47 +00003105 APInt api = bitcastToAPInt();
Dale Johannesen245dceb2007-09-11 18:32:33 +00003106 return api.bitsToFloat();
3107}
3108
Neil Booth9acbf5a2007-09-26 21:33:42 +00003109double
3110APFloat::convertToDouble() const
3111{
Chris Lattner688f9912009-09-24 21:44:20 +00003112 assert(semantics == (const llvm::fltSemantics*)&IEEEdouble &&
3113 "Float semantics are not IEEEdouble");
Dale Johannesen54306fe2008-10-09 18:53:47 +00003114 APInt api = bitcastToAPInt();
Dale Johannesen245dceb2007-09-11 18:32:33 +00003115 return api.bitsToDouble();
3116}
3117
Dale Johannesenfff29952008-10-06 18:22:29 +00003118/// Integer bit is explicit in this format. Intel hardware (387 and later)
3119/// does not support these bit patterns:
3120/// exponent = all 1's, integer bit 0, significand 0 ("pseudoinfinity")
3121/// exponent = all 1's, integer bit 0, significand nonzero ("pseudoNaN")
3122/// exponent = 0, integer bit 1 ("pseudodenormal")
3123/// exponent!=0 nor all 1's, integer bit 0 ("unnormal")
3124/// At the moment, the first two are treated as NaNs, the second two as Normal.
Dale Johannesen245dceb2007-09-11 18:32:33 +00003125void
Neil Booth9acbf5a2007-09-26 21:33:42 +00003126APFloat::initFromF80LongDoubleAPInt(const APInt &api)
3127{
Dale Johannesen245dceb2007-09-11 18:32:33 +00003128 assert(api.getBitWidth()==80);
3129 uint64_t i1 = api.getRawData()[0];
3130 uint64_t i2 = api.getRawData()[1];
Dale Johannesen93eefa02009-03-23 21:16:53 +00003131 uint64_t myexponent = (i2 & 0x7fff);
3132 uint64_t mysignificand = i1;
Dale Johannesen245dceb2007-09-11 18:32:33 +00003133
3134 initialize(&APFloat::x87DoubleExtended);
Dale Johannesen146a0ea2007-09-20 23:47:58 +00003135 assert(partCount()==2);
Dale Johannesen245dceb2007-09-11 18:32:33 +00003136
Dale Johannesen93eefa02009-03-23 21:16:53 +00003137 sign = static_cast<unsigned int>(i2>>15);
Dale Johannesen245dceb2007-09-11 18:32:33 +00003138 if (myexponent==0 && mysignificand==0) {
3139 // exponent, significand meaningless
3140 category = fcZero;
3141 } else if (myexponent==0x7fff && mysignificand==0x8000000000000000ULL) {
3142 // exponent, significand meaningless
3143 category = fcInfinity;
3144 } else if (myexponent==0x7fff && mysignificand!=0x8000000000000000ULL) {
3145 // exponent meaningless
3146 category = fcNaN;
Dale Johannesen146a0ea2007-09-20 23:47:58 +00003147 significandParts()[0] = mysignificand;
3148 significandParts()[1] = 0;
Dale Johannesen245dceb2007-09-11 18:32:33 +00003149 } else {
3150 category = fcNormal;
3151 exponent = myexponent - 16383;
Dale Johannesen146a0ea2007-09-20 23:47:58 +00003152 significandParts()[0] = mysignificand;
3153 significandParts()[1] = 0;
Dale Johannesen245dceb2007-09-11 18:32:33 +00003154 if (myexponent==0) // denormal
3155 exponent = -16382;
Neil Booth9acbf5a2007-09-26 21:33:42 +00003156 }
Dale Johannesen245dceb2007-09-11 18:32:33 +00003157}
3158
3159void
Dale Johannesen007aa372007-10-11 18:07:22 +00003160APFloat::initFromPPCDoubleDoubleAPInt(const APInt &api)
3161{
3162 assert(api.getBitWidth()==128);
3163 uint64_t i1 = api.getRawData()[0];
3164 uint64_t i2 = api.getRawData()[1];
Ulrich Weigandd9f7e252012-10-29 18:09:01 +00003165 opStatus fs;
3166 bool losesInfo;
Dale Johannesen007aa372007-10-11 18:07:22 +00003167
Ulrich Weigandd9f7e252012-10-29 18:09:01 +00003168 // Get the first double and convert to our format.
3169 initFromDoubleAPInt(APInt(64, i1));
3170 fs = convert(PPCDoubleDouble, rmNearestTiesToEven, &losesInfo);
3171 assert(fs == opOK && !losesInfo);
3172 (void)fs;
Dale Johannesen007aa372007-10-11 18:07:22 +00003173
Ulrich Weigandd9f7e252012-10-29 18:09:01 +00003174 // Unless we have a special case, add in second double.
Michael Gottesman8136c382013-06-26 23:17:28 +00003175 if (isFiniteNonZero()) {
Tim Northover29178a32013-01-22 09:46:31 +00003176 APFloat v(IEEEdouble, APInt(64, i2));
Ulrich Weigandd9f7e252012-10-29 18:09:01 +00003177 fs = v.convert(PPCDoubleDouble, rmNearestTiesToEven, &losesInfo);
3178 assert(fs == opOK && !losesInfo);
3179 (void)fs;
3180
3181 add(v, rmNearestTiesToEven);
Dale Johannesen007aa372007-10-11 18:07:22 +00003182 }
3183}
3184
3185void
Anton Korobeynikov13e8c7e2009-08-21 22:10:30 +00003186APFloat::initFromQuadrupleAPInt(const APInt &api)
3187{
3188 assert(api.getBitWidth()==128);
3189 uint64_t i1 = api.getRawData()[0];
3190 uint64_t i2 = api.getRawData()[1];
3191 uint64_t myexponent = (i2 >> 48) & 0x7fff;
3192 uint64_t mysignificand = i1;
3193 uint64_t mysignificand2 = i2 & 0xffffffffffffLL;
3194
3195 initialize(&APFloat::IEEEquad);
3196 assert(partCount()==2);
3197
3198 sign = static_cast<unsigned int>(i2>>63);
3199 if (myexponent==0 &&
3200 (mysignificand==0 && mysignificand2==0)) {
3201 // exponent, significand meaningless
3202 category = fcZero;
3203 } else if (myexponent==0x7fff &&
3204 (mysignificand==0 && mysignificand2==0)) {
3205 // exponent, significand meaningless
3206 category = fcInfinity;
3207 } else if (myexponent==0x7fff &&
3208 (mysignificand!=0 || mysignificand2 !=0)) {
3209 // exponent meaningless
3210 category = fcNaN;
3211 significandParts()[0] = mysignificand;
3212 significandParts()[1] = mysignificand2;
3213 } else {
3214 category = fcNormal;
3215 exponent = myexponent - 16383;
3216 significandParts()[0] = mysignificand;
3217 significandParts()[1] = mysignificand2;
3218 if (myexponent==0) // denormal
3219 exponent = -16382;
3220 else
3221 significandParts()[1] |= 0x1000000000000LL; // integer bit
3222 }
3223}
3224
3225void
Neil Booth9acbf5a2007-09-26 21:33:42 +00003226APFloat::initFromDoubleAPInt(const APInt &api)
3227{
Dale Johannesen245dceb2007-09-11 18:32:33 +00003228 assert(api.getBitWidth()==64);
3229 uint64_t i = *api.getRawData();
Dale Johannesen918c33c2007-08-24 05:08:11 +00003230 uint64_t myexponent = (i >> 52) & 0x7ff;
3231 uint64_t mysignificand = i & 0xfffffffffffffLL;
3232
Dale Johannesena719a602007-08-24 00:56:33 +00003233 initialize(&APFloat::IEEEdouble);
Dale Johannesena719a602007-08-24 00:56:33 +00003234 assert(partCount()==1);
3235
Evan Cheng82b9e962008-05-02 21:15:08 +00003236 sign = static_cast<unsigned int>(i>>63);
Dale Johannesena719a602007-08-24 00:56:33 +00003237 if (myexponent==0 && mysignificand==0) {
3238 // exponent, significand meaningless
3239 category = fcZero;
Dale Johannesena719a602007-08-24 00:56:33 +00003240 } else if (myexponent==0x7ff && mysignificand==0) {
3241 // exponent, significand meaningless
3242 category = fcInfinity;
Dale Johannesen3cf889f2007-08-31 04:03:46 +00003243 } else if (myexponent==0x7ff && mysignificand!=0) {
3244 // exponent meaningless
3245 category = fcNaN;
3246 *significandParts() = mysignificand;
Dale Johannesena719a602007-08-24 00:56:33 +00003247 } else {
Dale Johannesena719a602007-08-24 00:56:33 +00003248 category = fcNormal;
3249 exponent = myexponent - 1023;
Dale Johannesen728687c2007-09-05 20:39:49 +00003250 *significandParts() = mysignificand;
3251 if (myexponent==0) // denormal
3252 exponent = -1022;
3253 else
3254 *significandParts() |= 0x10000000000000LL; // integer bit
Neil Booth9acbf5a2007-09-26 21:33:42 +00003255 }
Dale Johannesena719a602007-08-24 00:56:33 +00003256}
3257
Dale Johannesen245dceb2007-09-11 18:32:33 +00003258void
Neil Booth9acbf5a2007-09-26 21:33:42 +00003259APFloat::initFromFloatAPInt(const APInt & api)
3260{
Dale Johannesen245dceb2007-09-11 18:32:33 +00003261 assert(api.getBitWidth()==32);
3262 uint32_t i = (uint32_t)*api.getRawData();
Dale Johannesen918c33c2007-08-24 05:08:11 +00003263 uint32_t myexponent = (i >> 23) & 0xff;
3264 uint32_t mysignificand = i & 0x7fffff;
3265
Dale Johannesena719a602007-08-24 00:56:33 +00003266 initialize(&APFloat::IEEEsingle);
Dale Johannesena719a602007-08-24 00:56:33 +00003267 assert(partCount()==1);
3268
Dale Johannesen3cf889f2007-08-31 04:03:46 +00003269 sign = i >> 31;
Dale Johannesena719a602007-08-24 00:56:33 +00003270 if (myexponent==0 && mysignificand==0) {
3271 // exponent, significand meaningless
3272 category = fcZero;
Dale Johannesena719a602007-08-24 00:56:33 +00003273 } else if (myexponent==0xff && mysignificand==0) {
3274 // exponent, significand meaningless
3275 category = fcInfinity;
Dale Johannesen4f55d9f2007-09-25 17:25:00 +00003276 } else if (myexponent==0xff && mysignificand!=0) {
Dale Johannesena719a602007-08-24 00:56:33 +00003277 // sign, exponent, significand meaningless
Dale Johannesen3cf889f2007-08-31 04:03:46 +00003278 category = fcNaN;
3279 *significandParts() = mysignificand;
Dale Johannesena719a602007-08-24 00:56:33 +00003280 } else {
3281 category = fcNormal;
Dale Johannesena719a602007-08-24 00:56:33 +00003282 exponent = myexponent - 127; //bias
Dale Johannesen728687c2007-09-05 20:39:49 +00003283 *significandParts() = mysignificand;
3284 if (myexponent==0) // denormal
3285 exponent = -126;
3286 else
3287 *significandParts() |= 0x800000; // integer bit
Dale Johannesena719a602007-08-24 00:56:33 +00003288 }
3289}
Dale Johannesen245dceb2007-09-11 18:32:33 +00003290
Chris Lattner4794b2b2009-10-16 02:13:51 +00003291void
3292APFloat::initFromHalfAPInt(const APInt & api)
3293{
3294 assert(api.getBitWidth()==16);
3295 uint32_t i = (uint32_t)*api.getRawData();
Dale Johannesen0d670b52009-10-23 04:02:51 +00003296 uint32_t myexponent = (i >> 10) & 0x1f;
Chris Lattner4794b2b2009-10-16 02:13:51 +00003297 uint32_t mysignificand = i & 0x3ff;
3298
3299 initialize(&APFloat::IEEEhalf);
3300 assert(partCount()==1);
3301
3302 sign = i >> 15;
3303 if (myexponent==0 && mysignificand==0) {
3304 // exponent, significand meaningless
3305 category = fcZero;
3306 } else if (myexponent==0x1f && mysignificand==0) {
3307 // exponent, significand meaningless
3308 category = fcInfinity;
3309 } else if (myexponent==0x1f && mysignificand!=0) {
3310 // sign, exponent, significand meaningless
3311 category = fcNaN;
3312 *significandParts() = mysignificand;
3313 } else {
3314 category = fcNormal;
3315 exponent = myexponent - 15; //bias
3316 *significandParts() = mysignificand;
3317 if (myexponent==0) // denormal
3318 exponent = -14;
3319 else
3320 *significandParts() |= 0x400; // integer bit
3321 }
3322}
3323
Dale Johannesen245dceb2007-09-11 18:32:33 +00003324/// Treat api as containing the bits of a floating point number. Currently
Dale Johannesen007aa372007-10-11 18:07:22 +00003325/// we infer the floating point type from the size of the APInt. The
3326/// isIEEE argument distinguishes between PPC128 and IEEE128 (not meaningful
3327/// when the size is anything else).
Dale Johannesen245dceb2007-09-11 18:32:33 +00003328void
Tim Northover29178a32013-01-22 09:46:31 +00003329APFloat::initFromAPInt(const fltSemantics* Sem, const APInt& api)
Neil Booth9acbf5a2007-09-26 21:33:42 +00003330{
Tim Northover29178a32013-01-22 09:46:31 +00003331 if (Sem == &IEEEhalf)
Chris Lattner4794b2b2009-10-16 02:13:51 +00003332 return initFromHalfAPInt(api);
Tim Northover29178a32013-01-22 09:46:31 +00003333 if (Sem == &IEEEsingle)
Dale Johannesen245dceb2007-09-11 18:32:33 +00003334 return initFromFloatAPInt(api);
Tim Northover29178a32013-01-22 09:46:31 +00003335 if (Sem == &IEEEdouble)
Dale Johannesen245dceb2007-09-11 18:32:33 +00003336 return initFromDoubleAPInt(api);
Tim Northover29178a32013-01-22 09:46:31 +00003337 if (Sem == &x87DoubleExtended)
Dale Johannesen245dceb2007-09-11 18:32:33 +00003338 return initFromF80LongDoubleAPInt(api);
Tim Northover29178a32013-01-22 09:46:31 +00003339 if (Sem == &IEEEquad)
3340 return initFromQuadrupleAPInt(api);
3341 if (Sem == &PPCDoubleDouble)
3342 return initFromPPCDoubleDoubleAPInt(api);
3343
Craig Topper2617dcc2014-04-15 06:32:26 +00003344 llvm_unreachable(nullptr);
Dale Johannesen245dceb2007-09-11 18:32:33 +00003345}
3346
Nadav Rotem7cc6d122011-02-17 21:22:27 +00003347APFloat
3348APFloat::getAllOnesValue(unsigned BitWidth, bool isIEEE)
3349{
Tim Northover29178a32013-01-22 09:46:31 +00003350 switch (BitWidth) {
3351 case 16:
3352 return APFloat(IEEEhalf, APInt::getAllOnesValue(BitWidth));
3353 case 32:
3354 return APFloat(IEEEsingle, APInt::getAllOnesValue(BitWidth));
3355 case 64:
3356 return APFloat(IEEEdouble, APInt::getAllOnesValue(BitWidth));
3357 case 80:
3358 return APFloat(x87DoubleExtended, APInt::getAllOnesValue(BitWidth));
3359 case 128:
3360 if (isIEEE)
3361 return APFloat(IEEEquad, APInt::getAllOnesValue(BitWidth));
3362 return APFloat(PPCDoubleDouble, APInt::getAllOnesValue(BitWidth));
3363 default:
3364 llvm_unreachable("Unknown floating bit width");
3365 }
Nadav Rotem7cc6d122011-02-17 21:22:27 +00003366}
3367
Tamas Berghammerb6b0ddf2015-07-09 10:13:39 +00003368unsigned APFloat::getSizeInBits(const fltSemantics &Sem) {
3369 return Sem.sizeInBits;
3370}
3371
Michael Gottesman0c622ea2013-05-30 18:07:13 +00003372/// Make this number the largest magnitude normal number in the given
3373/// semantics.
3374void APFloat::makeLargest(bool Negative) {
John McCall29b5c282009-12-24 08:56:26 +00003375 // We want (in interchange format):
3376 // sign = {Negative}
3377 // exponent = 1..10
3378 // significand = 1..1
Michael Gottesman0c622ea2013-05-30 18:07:13 +00003379 category = fcNormal;
3380 sign = Negative;
3381 exponent = semantics->maxExponent;
John McCall29b5c282009-12-24 08:56:26 +00003382
Michael Gottesman0c622ea2013-05-30 18:07:13 +00003383 // Use memset to set all but the highest integerPart to all ones.
3384 integerPart *significand = significandParts();
3385 unsigned PartCount = partCount();
3386 memset(significand, 0xFF, sizeof(integerPart)*(PartCount - 1));
John McCall29b5c282009-12-24 08:56:26 +00003387
Michael Gottesman0c622ea2013-05-30 18:07:13 +00003388 // Set the high integerPart especially setting all unused top bits for
3389 // internal consistency.
3390 const unsigned NumUnusedHighBits =
3391 PartCount*integerPartWidth - semantics->precision;
Alexey Samsonovba1ecbc2014-09-06 00:41:19 +00003392 significand[PartCount - 1] = (NumUnusedHighBits < integerPartWidth)
3393 ? (~integerPart(0) >> NumUnusedHighBits)
3394 : 0;
John McCall29b5c282009-12-24 08:56:26 +00003395}
3396
Michael Gottesman0c622ea2013-05-30 18:07:13 +00003397/// Make this number the smallest magnitude denormal number in the given
3398/// semantics.
3399void APFloat::makeSmallest(bool Negative) {
John McCall29b5c282009-12-24 08:56:26 +00003400 // We want (in interchange format):
3401 // sign = {Negative}
3402 // exponent = 0..0
3403 // significand = 0..01
Michael Gottesman0c622ea2013-05-30 18:07:13 +00003404 category = fcNormal;
3405 sign = Negative;
3406 exponent = semantics->minExponent;
3407 APInt::tcSet(significandParts(), 1, partCount());
3408}
John McCall29b5c282009-12-24 08:56:26 +00003409
Michael Gottesman0c622ea2013-05-30 18:07:13 +00003410
3411APFloat APFloat::getLargest(const fltSemantics &Sem, bool Negative) {
3412 // We want (in interchange format):
3413 // sign = {Negative}
3414 // exponent = 1..10
3415 // significand = 1..1
3416 APFloat Val(Sem, uninitialized);
3417 Val.makeLargest(Negative);
3418 return Val;
3419}
3420
3421APFloat APFloat::getSmallest(const fltSemantics &Sem, bool Negative) {
3422 // We want (in interchange format):
3423 // sign = {Negative}
3424 // exponent = 0..0
3425 // significand = 0..01
3426 APFloat Val(Sem, uninitialized);
3427 Val.makeSmallest(Negative);
John McCall29b5c282009-12-24 08:56:26 +00003428 return Val;
3429}
3430
3431APFloat APFloat::getSmallestNormalized(const fltSemantics &Sem, bool Negative) {
Michael Gottesman79b09672013-06-27 21:58:19 +00003432 APFloat Val(Sem, uninitialized);
John McCall29b5c282009-12-24 08:56:26 +00003433
3434 // We want (in interchange format):
3435 // sign = {Negative}
3436 // exponent = 0..0
3437 // significand = 10..0
3438
Michael Gottesman30a90eb2013-07-27 21:49:21 +00003439 Val.category = fcNormal;
Michael Gottesmanccaf3322013-06-27 20:40:11 +00003440 Val.zeroSignificand();
Michael Gottesman79b09672013-06-27 21:58:19 +00003441 Val.sign = Negative;
3442 Val.exponent = Sem.minExponent;
Dan Gohmanb452d4e2010-03-24 19:38:02 +00003443 Val.significandParts()[partCountForBits(Sem.precision)-1] |=
Eli Friedmand4330422011-10-12 21:56:19 +00003444 (((integerPart) 1) << ((Sem.precision - 1) % integerPartWidth));
John McCall29b5c282009-12-24 08:56:26 +00003445
3446 return Val;
3447}
3448
Tim Northover29178a32013-01-22 09:46:31 +00003449APFloat::APFloat(const fltSemantics &Sem, const APInt &API) {
3450 initFromAPInt(&Sem, API);
Dale Johannesen245dceb2007-09-11 18:32:33 +00003451}
3452
Ulrich Weigande1d62f92012-10-29 18:17:42 +00003453APFloat::APFloat(float f) {
Tim Northover29178a32013-01-22 09:46:31 +00003454 initFromAPInt(&IEEEsingle, APInt::floatToBits(f));
Dale Johannesen245dceb2007-09-11 18:32:33 +00003455}
3456
Ulrich Weigande1d62f92012-10-29 18:17:42 +00003457APFloat::APFloat(double d) {
Tim Northover29178a32013-01-22 09:46:31 +00003458 initFromAPInt(&IEEEdouble, APInt::doubleToBits(d));
Dale Johannesen245dceb2007-09-11 18:32:33 +00003459}
John McCall29b5c282009-12-24 08:56:26 +00003460
3461namespace {
David Blaikie70fdf722012-07-25 18:04:24 +00003462 void append(SmallVectorImpl<char> &Buffer, StringRef Str) {
3463 Buffer.append(Str.begin(), Str.end());
John McCall29b5c282009-12-24 08:56:26 +00003464 }
3465
John McCalle6212ace2009-12-24 12:16:56 +00003466 /// Removes data from the given significand until it is no more
3467 /// precise than is required for the desired precision.
3468 void AdjustToPrecision(APInt &significand,
3469 int &exp, unsigned FormatPrecision) {
3470 unsigned bits = significand.getActiveBits();
3471
3472 // 196/59 is a very slight overestimate of lg_2(10).
3473 unsigned bitsRequired = (FormatPrecision * 196 + 58) / 59;
3474
3475 if (bits <= bitsRequired) return;
3476
3477 unsigned tensRemovable = (bits - bitsRequired) * 59 / 196;
3478 if (!tensRemovable) return;
3479
3480 exp += tensRemovable;
3481
3482 APInt divisor(significand.getBitWidth(), 1);
3483 APInt powten(significand.getBitWidth(), 10);
3484 while (true) {
3485 if (tensRemovable & 1)
3486 divisor *= powten;
3487 tensRemovable >>= 1;
3488 if (!tensRemovable) break;
3489 powten *= powten;
3490 }
3491
3492 significand = significand.udiv(divisor);
3493
Hao Liube99cc32013-03-20 01:46:36 +00003494 // Truncate the significand down to its active bit count.
3495 significand = significand.trunc(significand.getActiveBits());
John McCalle6212ace2009-12-24 12:16:56 +00003496 }
3497
3498
John McCall29b5c282009-12-24 08:56:26 +00003499 void AdjustToPrecision(SmallVectorImpl<char> &buffer,
3500 int &exp, unsigned FormatPrecision) {
3501 unsigned N = buffer.size();
3502 if (N <= FormatPrecision) return;
3503
3504 // The most significant figures are the last ones in the buffer.
3505 unsigned FirstSignificant = N - FormatPrecision;
3506
3507 // Round.
3508 // FIXME: this probably shouldn't use 'round half up'.
3509
3510 // Rounding down is just a truncation, except we also want to drop
3511 // trailing zeros from the new result.
3512 if (buffer[FirstSignificant - 1] < '5') {
NAKAMURA Takumi5adeb932012-02-19 03:18:29 +00003513 while (FirstSignificant < N && buffer[FirstSignificant] == '0')
John McCall29b5c282009-12-24 08:56:26 +00003514 FirstSignificant++;
3515
3516 exp += FirstSignificant;
3517 buffer.erase(&buffer[0], &buffer[FirstSignificant]);
3518 return;
3519 }
3520
3521 // Rounding up requires a decimal add-with-carry. If we continue
3522 // the carry, the newly-introduced zeros will just be truncated.
3523 for (unsigned I = FirstSignificant; I != N; ++I) {
3524 if (buffer[I] == '9') {
3525 FirstSignificant++;
3526 } else {
3527 buffer[I]++;
3528 break;
3529 }
3530 }
3531
3532 // If we carried through, we have exactly one digit of precision.
3533 if (FirstSignificant == N) {
3534 exp += FirstSignificant;
3535 buffer.clear();
3536 buffer.push_back('1');
3537 return;
3538 }
3539
3540 exp += FirstSignificant;
3541 buffer.erase(&buffer[0], &buffer[FirstSignificant]);
3542 }
Alexander Kornienkof00654e2015-06-23 09:49:53 +00003543}
John McCall29b5c282009-12-24 08:56:26 +00003544
3545void APFloat::toString(SmallVectorImpl<char> &Str,
3546 unsigned FormatPrecision,
Chris Lattner4c1e4db2010-03-06 19:20:13 +00003547 unsigned FormatMaxPadding) const {
John McCall29b5c282009-12-24 08:56:26 +00003548 switch (category) {
3549 case fcInfinity:
3550 if (isNegative())
3551 return append(Str, "-Inf");
3552 else
3553 return append(Str, "+Inf");
3554
3555 case fcNaN: return append(Str, "NaN");
3556
3557 case fcZero:
3558 if (isNegative())
3559 Str.push_back('-');
3560
3561 if (!FormatMaxPadding)
3562 append(Str, "0.0E+0");
3563 else
3564 Str.push_back('0');
3565 return;
3566
3567 case fcNormal:
3568 break;
3569 }
3570
3571 if (isNegative())
3572 Str.push_back('-');
3573
3574 // Decompose the number into an APInt and an exponent.
3575 int exp = exponent - ((int) semantics->precision - 1);
3576 APInt significand(semantics->precision,
Jeffrey Yasskin7a162882011-07-18 21:45:40 +00003577 makeArrayRef(significandParts(),
3578 partCountForBits(semantics->precision)));
John McCall29b5c282009-12-24 08:56:26 +00003579
John McCalldd5044a2009-12-24 23:18:09 +00003580 // Set FormatPrecision if zero. We want to do this before we
3581 // truncate trailing zeros, as those are part of the precision.
3582 if (!FormatPrecision) {
Eli Friedmane72f1322013-08-29 23:44:34 +00003583 // We use enough digits so the number can be round-tripped back to an
3584 // APFloat. The formula comes from "How to Print Floating-Point Numbers
3585 // Accurately" by Steele and White.
3586 // FIXME: Using a formula based purely on the precision is conservative;
3587 // we can print fewer digits depending on the actual value being printed.
John McCalldd5044a2009-12-24 23:18:09 +00003588
Eli Friedmane72f1322013-08-29 23:44:34 +00003589 // FormatPrecision = 2 + floor(significandBits / lg_2(10))
3590 FormatPrecision = 2 + semantics->precision * 59 / 196;
John McCalldd5044a2009-12-24 23:18:09 +00003591 }
3592
John McCall29b5c282009-12-24 08:56:26 +00003593 // Ignore trailing binary zeros.
3594 int trailingZeros = significand.countTrailingZeros();
3595 exp += trailingZeros;
3596 significand = significand.lshr(trailingZeros);
3597
3598 // Change the exponent from 2^e to 10^e.
3599 if (exp == 0) {
3600 // Nothing to do.
3601 } else if (exp > 0) {
3602 // Just shift left.
Jay Foad583abbc2010-12-07 08:25:19 +00003603 significand = significand.zext(semantics->precision + exp);
John McCall29b5c282009-12-24 08:56:26 +00003604 significand <<= exp;
3605 exp = 0;
3606 } else { /* exp < 0 */
3607 int texp = -exp;
3608
3609 // We transform this using the identity:
3610 // (N)(2^-e) == (N)(5^e)(10^-e)
3611 // This means we have to multiply N (the significand) by 5^e.
3612 // To avoid overflow, we have to operate on numbers large
3613 // enough to store N * 5^e:
3614 // log2(N * 5^e) == log2(N) + e * log2(5)
John McCalldd5044a2009-12-24 23:18:09 +00003615 // <= semantics->precision + e * 137 / 59
3616 // (log_2(5) ~ 2.321928 < 2.322034 ~ 137/59)
Dan Gohmanb452d4e2010-03-24 19:38:02 +00003617
Eli Friedman19546412011-10-07 23:40:49 +00003618 unsigned precision = semantics->precision + (137 * texp + 136) / 59;
John McCall29b5c282009-12-24 08:56:26 +00003619
3620 // Multiply significand by 5^e.
3621 // N * 5^0101 == N * 5^(1*1) * 5^(0*2) * 5^(1*4) * 5^(0*8)
Jay Foad583abbc2010-12-07 08:25:19 +00003622 significand = significand.zext(precision);
John McCall29b5c282009-12-24 08:56:26 +00003623 APInt five_to_the_i(precision, 5);
3624 while (true) {
3625 if (texp & 1) significand *= five_to_the_i;
Dan Gohmanb452d4e2010-03-24 19:38:02 +00003626
John McCall29b5c282009-12-24 08:56:26 +00003627 texp >>= 1;
3628 if (!texp) break;
3629 five_to_the_i *= five_to_the_i;
3630 }
3631 }
3632
John McCalle6212ace2009-12-24 12:16:56 +00003633 AdjustToPrecision(significand, exp, FormatPrecision);
3634
Dmitri Gribenko226fea52013-01-13 16:01:15 +00003635 SmallVector<char, 256> buffer;
John McCall29b5c282009-12-24 08:56:26 +00003636
3637 // Fill the buffer.
3638 unsigned precision = significand.getBitWidth();
3639 APInt ten(precision, 10);
3640 APInt digit(precision, 0);
3641
3642 bool inTrail = true;
3643 while (significand != 0) {
3644 // digit <- significand % 10
3645 // significand <- significand / 10
3646 APInt::udivrem(significand, ten, significand, digit);
3647
3648 unsigned d = digit.getZExtValue();
3649
3650 // Drop trailing zeros.
3651 if (inTrail && !d) exp++;
3652 else {
3653 buffer.push_back((char) ('0' + d));
3654 inTrail = false;
3655 }
3656 }
3657
3658 assert(!buffer.empty() && "no characters in buffer!");
3659
3660 // Drop down to FormatPrecision.
3661 // TODO: don't do more precise calculations above than are required.
3662 AdjustToPrecision(buffer, exp, FormatPrecision);
3663
3664 unsigned NDigits = buffer.size();
3665
John McCalldd5044a2009-12-24 23:18:09 +00003666 // Check whether we should use scientific notation.
John McCall29b5c282009-12-24 08:56:26 +00003667 bool FormatScientific;
3668 if (!FormatMaxPadding)
3669 FormatScientific = true;
3670 else {
John McCall29b5c282009-12-24 08:56:26 +00003671 if (exp >= 0) {
John McCalldd5044a2009-12-24 23:18:09 +00003672 // 765e3 --> 765000
3673 // ^^^
3674 // But we shouldn't make the number look more precise than it is.
3675 FormatScientific = ((unsigned) exp > FormatMaxPadding ||
3676 NDigits + (unsigned) exp > FormatPrecision);
John McCall29b5c282009-12-24 08:56:26 +00003677 } else {
John McCalldd5044a2009-12-24 23:18:09 +00003678 // Power of the most significant digit.
3679 int MSD = exp + (int) (NDigits - 1);
3680 if (MSD >= 0) {
John McCall29b5c282009-12-24 08:56:26 +00003681 // 765e-2 == 7.65
John McCalldd5044a2009-12-24 23:18:09 +00003682 FormatScientific = false;
John McCall29b5c282009-12-24 08:56:26 +00003683 } else {
3684 // 765e-5 == 0.00765
3685 // ^ ^^
John McCalldd5044a2009-12-24 23:18:09 +00003686 FormatScientific = ((unsigned) -MSD) > FormatMaxPadding;
John McCall29b5c282009-12-24 08:56:26 +00003687 }
3688 }
John McCall29b5c282009-12-24 08:56:26 +00003689 }
3690
3691 // Scientific formatting is pretty straightforward.
3692 if (FormatScientific) {
3693 exp += (NDigits - 1);
3694
3695 Str.push_back(buffer[NDigits-1]);
3696 Str.push_back('.');
3697 if (NDigits == 1)
3698 Str.push_back('0');
3699 else
3700 for (unsigned I = 1; I != NDigits; ++I)
3701 Str.push_back(buffer[NDigits-1-I]);
3702 Str.push_back('E');
3703
3704 Str.push_back(exp >= 0 ? '+' : '-');
3705 if (exp < 0) exp = -exp;
3706 SmallVector<char, 6> expbuf;
3707 do {
3708 expbuf.push_back((char) ('0' + (exp % 10)));
3709 exp /= 10;
3710 } while (exp);
3711 for (unsigned I = 0, E = expbuf.size(); I != E; ++I)
3712 Str.push_back(expbuf[E-1-I]);
3713 return;
3714 }
3715
3716 // Non-scientific, positive exponents.
3717 if (exp >= 0) {
3718 for (unsigned I = 0; I != NDigits; ++I)
3719 Str.push_back(buffer[NDigits-1-I]);
3720 for (unsigned I = 0; I != (unsigned) exp; ++I)
3721 Str.push_back('0');
3722 return;
3723 }
3724
3725 // Non-scientific, negative exponents.
3726
3727 // The number of digits to the left of the decimal point.
3728 int NWholeDigits = exp + (int) NDigits;
3729
3730 unsigned I = 0;
3731 if (NWholeDigits > 0) {
3732 for (; I != (unsigned) NWholeDigits; ++I)
3733 Str.push_back(buffer[NDigits-I-1]);
3734 Str.push_back('.');
3735 } else {
3736 unsigned NZeros = 1 + (unsigned) -NWholeDigits;
3737
3738 Str.push_back('0');
3739 Str.push_back('.');
3740 for (unsigned Z = 1; Z != NZeros; ++Z)
3741 Str.push_back('0');
3742 }
3743
3744 for (; I != NDigits; ++I)
3745 Str.push_back(buffer[NDigits-I-1]);
3746}
Benjamin Kramer03fd6722011-03-30 15:42:27 +00003747
3748bool APFloat::getExactInverse(APFloat *inv) const {
Benjamin Kramer03fd6722011-03-30 15:42:27 +00003749 // Special floats and denormals have no exact inverse.
Michael Gottesman8136c382013-06-26 23:17:28 +00003750 if (!isFiniteNonZero())
Benjamin Kramer03fd6722011-03-30 15:42:27 +00003751 return false;
3752
3753 // Check that the number is a power of two by making sure that only the
3754 // integer bit is set in the significand.
3755 if (significandLSB() != semantics->precision - 1)
3756 return false;
3757
3758 // Get the inverse.
3759 APFloat reciprocal(*semantics, 1ULL);
3760 if (reciprocal.divide(*this, rmNearestTiesToEven) != opOK)
3761 return false;
3762
Benjamin Krameraf0ed952011-03-30 17:02:54 +00003763 // Avoid multiplication with a denormal, it is not safe on all platforms and
3764 // may be slower than a normal division.
Benjamin Kramer6bef24f2013-06-01 11:26:33 +00003765 if (reciprocal.isDenormal())
Benjamin Krameraf0ed952011-03-30 17:02:54 +00003766 return false;
3767
Michael Gottesman8136c382013-06-26 23:17:28 +00003768 assert(reciprocal.isFiniteNonZero() &&
Benjamin Krameraf0ed952011-03-30 17:02:54 +00003769 reciprocal.significandLSB() == reciprocal.semantics->precision - 1);
3770
Benjamin Kramer03fd6722011-03-30 15:42:27 +00003771 if (inv)
3772 *inv = reciprocal;
3773
3774 return true;
3775}
Michael Gottesman0c622ea2013-05-30 18:07:13 +00003776
3777bool APFloat::isSignaling() const {
3778 if (!isNaN())
3779 return false;
3780
3781 // IEEE-754R 2008 6.2.1: A signaling NaN bit string should be encoded with the
3782 // first bit of the trailing significand being 0.
3783 return !APInt::tcExtractBit(significandParts(), semantics->precision - 2);
3784}
3785
3786/// IEEE-754R 2008 5.3.1: nextUp/nextDown.
3787///
3788/// *NOTE* since nextDown(x) = -nextUp(-x), we only implement nextUp with
3789/// appropriate sign switching before/after the computation.
3790APFloat::opStatus APFloat::next(bool nextDown) {
3791 // If we are performing nextDown, swap sign so we have -x.
3792 if (nextDown)
3793 changeSign();
3794
3795 // Compute nextUp(x)
3796 opStatus result = opOK;
3797
3798 // Handle each float category separately.
3799 switch (category) {
3800 case fcInfinity:
3801 // nextUp(+inf) = +inf
3802 if (!isNegative())
3803 break;
3804 // nextUp(-inf) = -getLargest()
3805 makeLargest(true);
3806 break;
3807 case fcNaN:
3808 // IEEE-754R 2008 6.2 Par 2: nextUp(sNaN) = qNaN. Set Invalid flag.
3809 // IEEE-754R 2008 6.2: nextUp(qNaN) = qNaN. Must be identity so we do not
3810 // change the payload.
3811 if (isSignaling()) {
3812 result = opInvalidOp;
Alp Tokercb402912014-01-24 17:20:08 +00003813 // For consistency, propagate the sign of the sNaN to the qNaN.
Craig Topperc10719f2014-04-07 04:17:22 +00003814 makeNaN(false, isNegative(), nullptr);
Michael Gottesman0c622ea2013-05-30 18:07:13 +00003815 }
3816 break;
3817 case fcZero:
3818 // nextUp(pm 0) = +getSmallest()
3819 makeSmallest(false);
3820 break;
3821 case fcNormal:
3822 // nextUp(-getSmallest()) = -0
3823 if (isSmallest() && isNegative()) {
3824 APInt::tcSet(significandParts(), 0, partCount());
3825 category = fcZero;
3826 exponent = 0;
3827 break;
3828 }
3829
3830 // nextUp(getLargest()) == INFINITY
3831 if (isLargest() && !isNegative()) {
3832 APInt::tcSet(significandParts(), 0, partCount());
3833 category = fcInfinity;
3834 exponent = semantics->maxExponent + 1;
3835 break;
3836 }
3837
3838 // nextUp(normal) == normal + inc.
3839 if (isNegative()) {
3840 // If we are negative, we need to decrement the significand.
3841
3842 // We only cross a binade boundary that requires adjusting the exponent
3843 // if:
3844 // 1. exponent != semantics->minExponent. This implies we are not in the
3845 // smallest binade or are dealing with denormals.
3846 // 2. Our significand excluding the integral bit is all zeros.
3847 bool WillCrossBinadeBoundary =
3848 exponent != semantics->minExponent && isSignificandAllZeros();
3849
3850 // Decrement the significand.
3851 //
3852 // We always do this since:
Alp Tokerf907b892013-12-05 05:44:44 +00003853 // 1. If we are dealing with a non-binade decrement, by definition we
Michael Gottesman0c622ea2013-05-30 18:07:13 +00003854 // just decrement the significand.
3855 // 2. If we are dealing with a normal -> normal binade decrement, since
3856 // we have an explicit integral bit the fact that all bits but the
3857 // integral bit are zero implies that subtracting one will yield a
3858 // significand with 0 integral bit and 1 in all other spots. Thus we
3859 // must just adjust the exponent and set the integral bit to 1.
3860 // 3. If we are dealing with a normal -> denormal binade decrement,
3861 // since we set the integral bit to 0 when we represent denormals, we
3862 // just decrement the significand.
3863 integerPart *Parts = significandParts();
3864 APInt::tcDecrement(Parts, partCount());
3865
3866 if (WillCrossBinadeBoundary) {
3867 // Our result is a normal number. Do the following:
3868 // 1. Set the integral bit to 1.
3869 // 2. Decrement the exponent.
3870 APInt::tcSetBit(Parts, semantics->precision - 1);
3871 exponent--;
3872 }
3873 } else {
3874 // If we are positive, we need to increment the significand.
3875
3876 // We only cross a binade boundary that requires adjusting the exponent if
3877 // the input is not a denormal and all of said input's significand bits
3878 // are set. If all of said conditions are true: clear the significand, set
3879 // the integral bit to 1, and increment the exponent. If we have a
3880 // denormal always increment since moving denormals and the numbers in the
3881 // smallest normal binade have the same exponent in our representation.
3882 bool WillCrossBinadeBoundary = !isDenormal() && isSignificandAllOnes();
3883
3884 if (WillCrossBinadeBoundary) {
3885 integerPart *Parts = significandParts();
3886 APInt::tcSet(Parts, 0, partCount());
3887 APInt::tcSetBit(Parts, semantics->precision - 1);
3888 assert(exponent != semantics->maxExponent &&
3889 "We can not increment an exponent beyond the maxExponent allowed"
3890 " by the given floating point semantics.");
3891 exponent++;
3892 } else {
3893 incrementSignificand();
3894 }
3895 }
3896 break;
3897 }
3898
3899 // If we are performing nextDown, swap sign so we have -nextUp(-x)
3900 if (nextDown)
3901 changeSign();
3902
3903 return result;
3904}
Michael Gottesmanc4facdf2013-06-24 09:58:02 +00003905
3906void
3907APFloat::makeInf(bool Negative) {
3908 category = fcInfinity;
3909 sign = Negative;
3910 exponent = semantics->maxExponent + 1;
3911 APInt::tcSet(significandParts(), 0, partCount());
3912}
3913
3914void
3915APFloat::makeZero(bool Negative) {
3916 category = fcZero;
3917 sign = Negative;
3918 exponent = semantics->minExponent-1;
3919 APInt::tcSet(significandParts(), 0, partCount());
3920}
Chandler Carruthd9edd1e2014-10-10 04:54:30 +00003921
3922APFloat llvm::scalbn(APFloat X, int Exp) {
3923 if (X.isInfinity() || X.isZero() || X.isNaN())
Richard Trieu6ae37962015-04-30 23:07:00 +00003924 return X;
Chandler Carruthd9edd1e2014-10-10 04:54:30 +00003925
3926 auto MaxExp = X.getSemantics().maxExponent;
3927 auto MinExp = X.getSemantics().minExponent;
3928 if (Exp > (MaxExp - X.exponent))
3929 // Overflow saturates to infinity.
3930 return APFloat::getInf(X.getSemantics(), X.isNegative());
3931 if (Exp < (MinExp - X.exponent))
3932 // Underflow saturates to zero.
3933 return APFloat::getZero(X.getSemantics(), X.isNegative());
3934
3935 X.exponent += Exp;
Richard Trieu6ae37962015-04-30 23:07:00 +00003936 return X;
Chandler Carruthd9edd1e2014-10-10 04:54:30 +00003937}