blob: 2fe3b070023a377df74e91e7be1dab2440d08e60 [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"
Mehdi Amini47b292d2016-04-16 07:51:28 +000017#include "llvm/ADT/ArrayRef.h"
Ted Kremenek6f30a072008-02-11 17:24:50 +000018#include "llvm/ADT/FoldingSet.h"
Chandler Carruth71bd7d12012-03-04 12:02:57 +000019#include "llvm/ADT/Hashing.h"
Jordan Rosee1f76582013-01-18 21:45:30 +000020#include "llvm/ADT/StringExtras.h"
Chandler Carruth71bd7d12012-03-04 12:02:57 +000021#include "llvm/ADT/StringRef.h"
Tim Shen44bde892016-12-12 21:59:30 +000022#include "llvm/Support/Debug.h"
Torok Edwin56d06592009-07-11 20:10:48 +000023#include "llvm/Support/ErrorHandling.h"
Dale Johannesen918c33c2007-08-24 05:08:11 +000024#include "llvm/Support/MathExtras.h"
Tim Shen44bde892016-12-12 21:59:30 +000025#include "llvm/Support/raw_ostream.h"
Chris Lattner17f71652008-08-17 07:19:36 +000026#include <cstring>
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +000027#include <limits.h>
Chris Lattnerfe02c1f2007-08-20 22:49:32 +000028
Tim Shen601ba8c2017-01-27 02:11:07 +000029#define APFLOAT_DISPATCH_ON_SEMANTICS(METHOD_CALL) \
30 do { \
31 if (usesLayout<IEEEFloat>(getSemantics())) \
32 return U.IEEE.METHOD_CALL; \
33 if (usesLayout<DoubleAPFloat>(getSemantics())) \
34 return U.Double.METHOD_CALL; \
35 llvm_unreachable("Unexpected semantics"); \
36 } while (false)
37
Chris Lattnerfe02c1f2007-08-20 22:49:32 +000038using namespace llvm;
39
Michael Gottesman9b877e12013-06-24 09:57:57 +000040/// A macro used to combine two fcCategory enums into one key which can be used
41/// in a switch statement to classify how the interaction of two APFloat's
42/// categories affects an operation.
43///
44/// TODO: If clang source code is ever allowed to use constexpr in its own
45/// codebase, change this into a static inline function.
46#define PackCategoriesIntoKey(_lhs, _rhs) ((_lhs) * 4 + (_rhs))
Chris Lattnerfe02c1f2007-08-20 22:49:32 +000047
Neil Booth8f1946f2007-10-03 22:26:02 +000048/* Assumed in hexadecimal significand parsing, and conversion to
49 hexadecimal strings. */
Benjamin Kramer7000ca32014-10-12 17:56:40 +000050static_assert(integerPartWidth % 4 == 0, "Part width must be divisible by 4!");
Chris Lattnerfe02c1f2007-08-20 22:49:32 +000051
52namespace llvm {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +000053 /* Represents floating point arithmetic semantics. */
54 struct fltSemantics {
55 /* The largest E such that 2^E is representable; this matches the
56 definition of IEEE 754. */
Tim Shen85de51d2016-10-25 19:55:59 +000057 APFloatBase::ExponentType maxExponent;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +000058
59 /* The smallest E such that 2^E is a normalized number; this
60 matches the definition of IEEE 754. */
Tim Shen85de51d2016-10-25 19:55:59 +000061 APFloatBase::ExponentType minExponent;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +000062
63 /* Number of bits in the significand. This includes the integer
64 bit. */
Neil Booth146fdb32007-10-12 15:33:27 +000065 unsigned int precision;
Tamas Berghammerb6b0ddf2015-07-09 10:13:39 +000066
67 /* Number of bits actually used in the semantics. */
68 unsigned int sizeInBits;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +000069 };
70
Stephan Bergmann17c7f702016-12-14 11:57:17 +000071 static const fltSemantics semIEEEhalf = {15, -14, 11, 16};
72 static const fltSemantics semIEEEsingle = {127, -126, 24, 32};
73 static const fltSemantics semIEEEdouble = {1023, -1022, 53, 64};
74 static const fltSemantics semIEEEquad = {16383, -16382, 113, 128};
75 static const fltSemantics semX87DoubleExtended = {16383, -16382, 64, 80};
76 static const fltSemantics semBogus = {0, 0, 0, 0};
Dale Johannesen007aa372007-10-11 18:07:22 +000077
Tim Shen7117e692017-01-26 00:11:07 +000078 /* The IBM double-double semantics. Such a number consists of a pair of IEEE
79 64-bit doubles (Hi, Lo), where |Hi| > |Lo|, and if normal,
80 (double)(Hi + Lo) == Hi. The numeric value it's modeling is Hi + Lo.
81 Therefore it has two 53-bit mantissa parts that aren't necessarily adjacent
82 to each other, and two 11-bit exponents.
Michal Gorny21c12042017-01-03 16:33:50 +000083
84 Note: we need to make the value different from semBogus as otherwise
85 an unsafe optimization may collapse both values to a single address,
86 and we heavily rely on them having distinct addresses. */
87 static const fltSemantics semPPCDoubleDouble = {-1, 0, 0, 0};
Tim Shen139a58f2016-10-27 22:52:40 +000088
Tim Shenfd1e5aa2017-01-23 22:39:35 +000089 /* These are legacy semantics for the fallback, inaccrurate implementation of
90 IBM double-double, if the accurate semPPCDoubleDouble doesn't handle the
Tim Shen7117e692017-01-26 00:11:07 +000091 operation. It's equivalent to having an IEEE number with consecutive 106
92 bits of mantissa and 11 bits of exponent.
93
94 It's not equivalent to IBM double-double. For example, a legit IBM
95 double-double, 1 + epsilon:
96
97 1 + epsilon = 1 + (1 >> 1076)
98
99 is not representable by a consecutive 106 bits of mantissa.
Tim Shen139a58f2016-10-27 22:52:40 +0000100
Tim Shenfd1e5aa2017-01-23 22:39:35 +0000101 Currently, these semantics are used in the following way:
102
Tim Shen7117e692017-01-26 00:11:07 +0000103 semPPCDoubleDouble -> (IEEEdouble, IEEEdouble) ->
104 (64-bit APInt, 64-bit APInt) -> (128-bit APInt) ->
105 semPPCDoubleDoubleLegacy -> IEEE operations
Tim Shenfd1e5aa2017-01-23 22:39:35 +0000106
107 We use bitcastToAPInt() to get the bit representation (in APInt) of the
108 underlying IEEEdouble, then use the APInt constructor to construct the
109 legacy IEEE float.
110
111 TODO: Implement all operations in semPPCDoubleDouble, and delete these
112 semantics. */
113 static const fltSemantics semPPCDoubleDoubleLegacy = {1023, -1022 + 53,
114 53 + 53, 128};
Stephan Bergmann17c7f702016-12-14 11:57:17 +0000115
116 const fltSemantics &APFloatBase::IEEEhalf() {
117 return semIEEEhalf;
118 }
119 const fltSemantics &APFloatBase::IEEEsingle() {
120 return semIEEEsingle;
121 }
122 const fltSemantics &APFloatBase::IEEEdouble() {
123 return semIEEEdouble;
124 }
125 const fltSemantics &APFloatBase::IEEEquad() {
126 return semIEEEquad;
127 }
128 const fltSemantics &APFloatBase::x87DoubleExtended() {
129 return semX87DoubleExtended;
130 }
131 const fltSemantics &APFloatBase::Bogus() {
132 return semBogus;
133 }
134 const fltSemantics &APFloatBase::PPCDoubleDouble() {
135 return semPPCDoubleDouble;
136 }
Neil Boothb93d90e2007-10-12 16:02:31 +0000137
138 /* A tight upper bound on number of parts required to hold the value
139 pow(5, power) is
140
Neil Booth91305512007-10-15 15:00:55 +0000141 power * 815 / (351 * integerPartWidth) + 1
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000142
Neil Boothb93d90e2007-10-12 16:02:31 +0000143 However, whilst the result may require only this many parts,
144 because we are multiplying two values to get it, the
145 multiplication may require an extra part with the excess part
146 being zero (consider the trivial case of 1 * 1, tcFullMultiply
147 requires two parts to hold the single-part result). So we add an
148 extra one to guarantee enough space whilst multiplying. */
149 const unsigned int maxExponent = 16383;
150 const unsigned int maxPrecision = 113;
151 const unsigned int maxPowerOfFiveExponent = maxExponent + maxPrecision - 1;
Neil Booth91305512007-10-15 15:00:55 +0000152 const unsigned int maxPowerOfFiveParts = 2 + ((maxPowerOfFiveExponent * 815)
153 / (351 * integerPartWidth));
Tim Shen85de51d2016-10-25 19:55:59 +0000154
155 unsigned int APFloatBase::semanticsPrecision(const fltSemantics &semantics) {
156 return semantics.precision;
157 }
158 APFloatBase::ExponentType
159 APFloatBase::semanticsMaxExponent(const fltSemantics &semantics) {
160 return semantics.maxExponent;
161 }
162 APFloatBase::ExponentType
163 APFloatBase::semanticsMinExponent(const fltSemantics &semantics) {
164 return semantics.minExponent;
165 }
166 unsigned int APFloatBase::semanticsSizeInBits(const fltSemantics &semantics) {
167 return semantics.sizeInBits;
168 }
169
170 unsigned APFloatBase::getSizeInBits(const fltSemantics &Sem) {
171 return Sem.sizeInBits;
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000172}
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000173
Chris Lattner91702092009-03-12 23:59:55 +0000174/* A bunch of private, handy routines. */
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000175
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000176static inline unsigned int
Chris Lattner91702092009-03-12 23:59:55 +0000177partCountForBits(unsigned int bits)
178{
179 return ((bits) + integerPartWidth - 1) / integerPartWidth;
180}
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000181
Chris Lattner91702092009-03-12 23:59:55 +0000182/* Returns 0U-9U. Return values >= 10U are not digits. */
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000183static inline unsigned int
Chris Lattner91702092009-03-12 23:59:55 +0000184decDigitValue(unsigned int c)
185{
186 return c - '0';
187}
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000188
Chris Lattner91702092009-03-12 23:59:55 +0000189/* Return the value of a decimal exponent of the form
190 [+-]ddddddd.
Neil Booth4ed401b2007-10-14 10:16:12 +0000191
Chris Lattner91702092009-03-12 23:59:55 +0000192 If the exponent overflows, returns a large exponent with the
193 appropriate sign. */
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000194static int
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000195readExponent(StringRef::iterator begin, StringRef::iterator end)
Chris Lattner91702092009-03-12 23:59:55 +0000196{
197 bool isNegative;
198 unsigned int absExponent;
199 const unsigned int overlargeExponent = 24000; /* FIXME. */
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000200 StringRef::iterator p = begin;
201
202 assert(p != end && "Exponent has no digits");
Neil Booth4ed401b2007-10-14 10:16:12 +0000203
Chris Lattner91702092009-03-12 23:59:55 +0000204 isNegative = (*p == '-');
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000205 if (*p == '-' || *p == '+') {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000206 p++;
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000207 assert(p != end && "Exponent has no digits");
208 }
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000209
Chris Lattner91702092009-03-12 23:59:55 +0000210 absExponent = decDigitValue(*p++);
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000211 assert(absExponent < 10U && "Invalid character in exponent");
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000212
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000213 for (; p != end; ++p) {
Chris Lattner91702092009-03-12 23:59:55 +0000214 unsigned int value;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000215
Chris Lattner91702092009-03-12 23:59:55 +0000216 value = decDigitValue(*p);
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000217 assert(value < 10U && "Invalid character in exponent");
Chris Lattner91702092009-03-12 23:59:55 +0000218
Chris Lattner91702092009-03-12 23:59:55 +0000219 value += absExponent * 10;
220 if (absExponent >= overlargeExponent) {
221 absExponent = overlargeExponent;
Dale Johannesen370c77c2010-08-19 17:58:35 +0000222 p = end; /* outwit assert below */
Chris Lattner91702092009-03-12 23:59:55 +0000223 break;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000224 }
Chris Lattner91702092009-03-12 23:59:55 +0000225 absExponent = value;
226 }
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000227
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000228 assert(p == end && "Invalid exponent in exponent");
229
Chris Lattner91702092009-03-12 23:59:55 +0000230 if (isNegative)
231 return -(int) absExponent;
232 else
233 return (int) absExponent;
234}
235
236/* This is ugly and needs cleaning up, but I don't immediately see
237 how whilst remaining safe. */
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000238static int
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000239totalExponent(StringRef::iterator p, StringRef::iterator end,
240 int exponentAdjustment)
Chris Lattner91702092009-03-12 23:59:55 +0000241{
242 int unsignedExponent;
243 bool negative, overflow;
Ted Kremenek3c4408c2011-01-23 17:05:06 +0000244 int exponent = 0;
Chris Lattner91702092009-03-12 23:59:55 +0000245
Erick Tryzelaarda666c82009-08-20 23:30:43 +0000246 assert(p != end && "Exponent has no digits");
247
Chris Lattner91702092009-03-12 23:59:55 +0000248 negative = *p == '-';
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000249 if (*p == '-' || *p == '+') {
Chris Lattner91702092009-03-12 23:59:55 +0000250 p++;
Erick Tryzelaarda666c82009-08-20 23:30:43 +0000251 assert(p != end && "Exponent has no digits");
252 }
Chris Lattner91702092009-03-12 23:59:55 +0000253
254 unsignedExponent = 0;
255 overflow = false;
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000256 for (; p != end; ++p) {
Chris Lattner91702092009-03-12 23:59:55 +0000257 unsigned int value;
258
259 value = decDigitValue(*p);
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000260 assert(value < 10U && "Invalid character in exponent");
Chris Lattner91702092009-03-12 23:59:55 +0000261
Chris Lattner91702092009-03-12 23:59:55 +0000262 unsignedExponent = unsignedExponent * 10 + value;
Richard Smith156d9202012-08-24 00:01:19 +0000263 if (unsignedExponent > 32767) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000264 overflow = true;
Richard Smith156d9202012-08-24 00:01:19 +0000265 break;
266 }
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000267 }
268
Abramo Bagnaraa41d7ae2011-01-06 16:55:14 +0000269 if (exponentAdjustment > 32767 || exponentAdjustment < -32768)
Chris Lattner91702092009-03-12 23:59:55 +0000270 overflow = true;
271
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000272 if (!overflow) {
Chris Lattner91702092009-03-12 23:59:55 +0000273 exponent = unsignedExponent;
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000274 if (negative)
Chris Lattner91702092009-03-12 23:59:55 +0000275 exponent = -exponent;
276 exponent += exponentAdjustment;
Abramo Bagnaraa41d7ae2011-01-06 16:55:14 +0000277 if (exponent > 32767 || exponent < -32768)
Chris Lattner91702092009-03-12 23:59:55 +0000278 overflow = true;
279 }
280
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000281 if (overflow)
Abramo Bagnaraa41d7ae2011-01-06 16:55:14 +0000282 exponent = negative ? -32768: 32767;
Chris Lattner91702092009-03-12 23:59:55 +0000283
284 return exponent;
285}
286
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000287static StringRef::iterator
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000288skipLeadingZeroesAndAnyDot(StringRef::iterator begin, StringRef::iterator end,
289 StringRef::iterator *dot)
Chris Lattner91702092009-03-12 23:59:55 +0000290{
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000291 StringRef::iterator p = begin;
292 *dot = end;
Nick Lewycky095b92e2014-09-06 01:16:42 +0000293 while (p != end && *p == '0')
Chris Lattner91702092009-03-12 23:59:55 +0000294 p++;
295
Nick Lewycky095b92e2014-09-06 01:16:42 +0000296 if (p != end && *p == '.') {
Chris Lattner91702092009-03-12 23:59:55 +0000297 *dot = p++;
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000298
Erick Tryzelaarda666c82009-08-20 23:30:43 +0000299 assert(end - begin != 1 && "Significand has no digits");
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000300
Nick Lewycky095b92e2014-09-06 01:16:42 +0000301 while (p != end && *p == '0')
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000302 p++;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000303 }
304
Chris Lattner91702092009-03-12 23:59:55 +0000305 return p;
306}
Neil Booth4ed401b2007-10-14 10:16:12 +0000307
Chris Lattner91702092009-03-12 23:59:55 +0000308/* Given a normal decimal floating point number of the form
Neil Booth4ed401b2007-10-14 10:16:12 +0000309
Chris Lattner91702092009-03-12 23:59:55 +0000310 dddd.dddd[eE][+-]ddd
Neil Booth91305512007-10-15 15:00:55 +0000311
Chris Lattner91702092009-03-12 23:59:55 +0000312 where the decimal point and exponent are optional, fill out the
313 structure D. Exponent is appropriate if the significand is
314 treated as an integer, and normalizedExponent if the significand
315 is taken to have the decimal point after a single leading
316 non-zero digit.
Neil Booth4ed401b2007-10-14 10:16:12 +0000317
Chris Lattner91702092009-03-12 23:59:55 +0000318 If the value is zero, V->firstSigDigit points to a non-digit, and
319 the return exponent is zero.
320*/
321struct decimalInfo {
322 const char *firstSigDigit;
323 const char *lastSigDigit;
324 int exponent;
325 int normalizedExponent;
326};
Neil Booth4ed401b2007-10-14 10:16:12 +0000327
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000328static void
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000329interpretDecimal(StringRef::iterator begin, StringRef::iterator end,
330 decimalInfo *D)
Chris Lattner91702092009-03-12 23:59:55 +0000331{
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000332 StringRef::iterator dot = end;
333 StringRef::iterator p = skipLeadingZeroesAndAnyDot (begin, end, &dot);
Neil Booth4ed401b2007-10-14 10:16:12 +0000334
Chris Lattner91702092009-03-12 23:59:55 +0000335 D->firstSigDigit = p;
336 D->exponent = 0;
337 D->normalizedExponent = 0;
338
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000339 for (; p != end; ++p) {
Chris Lattner91702092009-03-12 23:59:55 +0000340 if (*p == '.') {
Erick Tryzelaarda666c82009-08-20 23:30:43 +0000341 assert(dot == end && "String contains multiple dots");
Chris Lattner91702092009-03-12 23:59:55 +0000342 dot = p++;
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000343 if (p == end)
344 break;
Neil Booth4ed401b2007-10-14 10:16:12 +0000345 }
Chris Lattner91702092009-03-12 23:59:55 +0000346 if (decDigitValue(*p) >= 10U)
347 break;
Chris Lattner91702092009-03-12 23:59:55 +0000348 }
Neil Booth4ed401b2007-10-14 10:16:12 +0000349
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000350 if (p != end) {
Erick Tryzelaarda666c82009-08-20 23:30:43 +0000351 assert((*p == 'e' || *p == 'E') && "Invalid character in significand");
352 assert(p != begin && "Significand has no digits");
353 assert((dot == end || p - begin != 1) && "Significand has no digits");
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000354
355 /* p points to the first non-digit in the string */
Erick Tryzelaarda666c82009-08-20 23:30:43 +0000356 D->exponent = readExponent(p + 1, end);
Neil Booth4ed401b2007-10-14 10:16:12 +0000357
Chris Lattner91702092009-03-12 23:59:55 +0000358 /* Implied decimal point? */
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000359 if (dot == end)
Chris Lattner91702092009-03-12 23:59:55 +0000360 dot = p;
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000361 }
Neil Booth4ed401b2007-10-14 10:16:12 +0000362
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000363 /* If number is all zeroes accept any exponent. */
364 if (p != D->firstSigDigit) {
Chris Lattner91702092009-03-12 23:59:55 +0000365 /* Drop insignificant trailing zeroes. */
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000366 if (p != begin) {
Neil Booth4ed401b2007-10-14 10:16:12 +0000367 do
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000368 do
369 p--;
370 while (p != begin && *p == '0');
371 while (p != begin && *p == '.');
372 }
Neil Booth4ed401b2007-10-14 10:16:12 +0000373
Chris Lattner91702092009-03-12 23:59:55 +0000374 /* Adjust the exponents for any decimal point. */
Michael Gottesman9dc98332013-06-24 04:06:23 +0000375 D->exponent += static_cast<APFloat::ExponentType>((dot - p) - (dot > p));
Chris Lattner91702092009-03-12 23:59:55 +0000376 D->normalizedExponent = (D->exponent +
Michael Gottesman9dc98332013-06-24 04:06:23 +0000377 static_cast<APFloat::ExponentType>((p - D->firstSigDigit)
Chris Lattner91702092009-03-12 23:59:55 +0000378 - (dot > D->firstSigDigit && dot < p)));
Neil Booth4ed401b2007-10-14 10:16:12 +0000379 }
380
Chris Lattner91702092009-03-12 23:59:55 +0000381 D->lastSigDigit = p;
382}
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000383
Chris Lattner91702092009-03-12 23:59:55 +0000384/* Return the trailing fraction of a hexadecimal number.
385 DIGITVALUE is the first hex digit of the fraction, P points to
386 the next digit. */
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000387static lostFraction
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000388trailingHexadecimalFraction(StringRef::iterator p, StringRef::iterator end,
389 unsigned int digitValue)
Chris Lattner91702092009-03-12 23:59:55 +0000390{
391 unsigned int hexDigit;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000392
Chris Lattner91702092009-03-12 23:59:55 +0000393 /* If the first trailing digit isn't 0 or 8 we can work out the
394 fraction immediately. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000395 if (digitValue > 8)
Chris Lattner91702092009-03-12 23:59:55 +0000396 return lfMoreThanHalf;
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000397 else if (digitValue < 8 && digitValue > 0)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000398 return lfLessThanHalf;
Chris Lattner91702092009-03-12 23:59:55 +0000399
Eli Friedmand2eb07a2013-07-17 22:17:29 +0000400 // Otherwise we need to find the first non-zero digit.
401 while (p != end && (*p == '0' || *p == '.'))
Chris Lattner91702092009-03-12 23:59:55 +0000402 p++;
403
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000404 assert(p != end && "Invalid trailing hexadecimal fraction!");
405
Chris Lattner91702092009-03-12 23:59:55 +0000406 hexDigit = hexDigitValue(*p);
407
408 /* If we ran off the end it is exactly zero or one-half, otherwise
409 a little more. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000410 if (hexDigit == -1U)
Chris Lattner91702092009-03-12 23:59:55 +0000411 return digitValue == 0 ? lfExactlyZero: lfExactlyHalf;
412 else
413 return digitValue == 0 ? lfLessThanHalf: lfMoreThanHalf;
414}
415
416/* Return the fraction lost were a bignum truncated losing the least
417 significant BITS bits. */
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000418static lostFraction
Chris Lattner91702092009-03-12 23:59:55 +0000419lostFractionThroughTruncation(const integerPart *parts,
420 unsigned int partCount,
421 unsigned int bits)
422{
423 unsigned int lsb;
424
425 lsb = APInt::tcLSB(parts, partCount);
426
427 /* Note this is guaranteed true if bits == 0, or LSB == -1U. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000428 if (bits <= lsb)
Chris Lattner91702092009-03-12 23:59:55 +0000429 return lfExactlyZero;
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000430 if (bits == lsb + 1)
Chris Lattner91702092009-03-12 23:59:55 +0000431 return lfExactlyHalf;
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000432 if (bits <= partCount * integerPartWidth &&
433 APInt::tcExtractBit(parts, bits - 1))
Chris Lattner91702092009-03-12 23:59:55 +0000434 return lfMoreThanHalf;
435
436 return lfLessThanHalf;
437}
438
439/* Shift DST right BITS bits noting lost fraction. */
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000440static lostFraction
Chris Lattner91702092009-03-12 23:59:55 +0000441shiftRight(integerPart *dst, unsigned int parts, unsigned int bits)
442{
443 lostFraction lost_fraction;
444
445 lost_fraction = lostFractionThroughTruncation(dst, parts, bits);
446
447 APInt::tcShiftRight(dst, parts, bits);
448
449 return lost_fraction;
450}
451
452/* Combine the effect of two lost fractions. */
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000453static lostFraction
Chris Lattner91702092009-03-12 23:59:55 +0000454combineLostFractions(lostFraction moreSignificant,
455 lostFraction lessSignificant)
456{
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000457 if (lessSignificant != lfExactlyZero) {
458 if (moreSignificant == lfExactlyZero)
Chris Lattner91702092009-03-12 23:59:55 +0000459 moreSignificant = lfLessThanHalf;
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000460 else if (moreSignificant == lfExactlyHalf)
Chris Lattner91702092009-03-12 23:59:55 +0000461 moreSignificant = lfMoreThanHalf;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000462 }
463
Chris Lattner91702092009-03-12 23:59:55 +0000464 return moreSignificant;
465}
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000466
Chris Lattner91702092009-03-12 23:59:55 +0000467/* The error from the true value, in half-ulps, on multiplying two
468 floating point numbers, which differ from the value they
469 approximate by at most HUE1 and HUE2 half-ulps, is strictly less
470 than the returned value.
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000471
Chris Lattner91702092009-03-12 23:59:55 +0000472 See "How to Read Floating Point Numbers Accurately" by William D
473 Clinger. */
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000474static unsigned int
Chris Lattner91702092009-03-12 23:59:55 +0000475HUerrBound(bool inexactMultiply, unsigned int HUerr1, unsigned int HUerr2)
476{
477 assert(HUerr1 < 2 || HUerr2 < 2 || (HUerr1 + HUerr2 < 8));
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000478
Chris Lattner91702092009-03-12 23:59:55 +0000479 if (HUerr1 + HUerr2 == 0)
480 return inexactMultiply * 2; /* <= inexactMultiply half-ulps. */
481 else
482 return inexactMultiply + 2 * (HUerr1 + HUerr2);
483}
Neil Booth8f1946f2007-10-03 22:26:02 +0000484
Chris Lattner91702092009-03-12 23:59:55 +0000485/* The number of ulps from the boundary (zero, or half if ISNEAREST)
486 when the least significant BITS are truncated. BITS cannot be
487 zero. */
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000488static integerPart
Chris Lattner91702092009-03-12 23:59:55 +0000489ulpsFromBoundary(const integerPart *parts, unsigned int bits, bool isNearest)
490{
491 unsigned int count, partBits;
492 integerPart part, boundary;
Neil Boothd3985922007-10-07 08:51:21 +0000493
Evan Cheng67c90212009-10-27 21:35:42 +0000494 assert(bits != 0);
Neil Booth8f1946f2007-10-03 22:26:02 +0000495
Chris Lattner91702092009-03-12 23:59:55 +0000496 bits--;
497 count = bits / integerPartWidth;
498 partBits = bits % integerPartWidth + 1;
Neil Boothb93d90e2007-10-12 16:02:31 +0000499
Chris Lattner91702092009-03-12 23:59:55 +0000500 part = parts[count] & (~(integerPart) 0 >> (integerPartWidth - partBits));
Neil Boothb93d90e2007-10-12 16:02:31 +0000501
Chris Lattner91702092009-03-12 23:59:55 +0000502 if (isNearest)
503 boundary = (integerPart) 1 << (partBits - 1);
504 else
505 boundary = 0;
506
507 if (count == 0) {
508 if (part - boundary <= boundary - part)
509 return part - boundary;
Neil Boothb93d90e2007-10-12 16:02:31 +0000510 else
Chris Lattner91702092009-03-12 23:59:55 +0000511 return boundary - part;
Neil Boothb93d90e2007-10-12 16:02:31 +0000512 }
513
Chris Lattner91702092009-03-12 23:59:55 +0000514 if (part == boundary) {
515 while (--count)
516 if (parts[count])
517 return ~(integerPart) 0; /* A lot. */
Neil Boothb93d90e2007-10-12 16:02:31 +0000518
Chris Lattner91702092009-03-12 23:59:55 +0000519 return parts[0];
520 } else if (part == boundary - 1) {
521 while (--count)
522 if (~parts[count])
523 return ~(integerPart) 0; /* A lot. */
Neil Boothb93d90e2007-10-12 16:02:31 +0000524
Chris Lattner91702092009-03-12 23:59:55 +0000525 return -parts[0];
526 }
Neil Boothb93d90e2007-10-12 16:02:31 +0000527
Chris Lattner91702092009-03-12 23:59:55 +0000528 return ~(integerPart) 0; /* A lot. */
529}
Neil Boothb93d90e2007-10-12 16:02:31 +0000530
Chris Lattner91702092009-03-12 23:59:55 +0000531/* Place pow(5, power) in DST, and return the number of parts used.
532 DST must be at least one part larger than size of the answer. */
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000533static unsigned int
Chris Lattner91702092009-03-12 23:59:55 +0000534powerOf5(integerPart *dst, unsigned int power)
535{
536 static const integerPart firstEightPowers[] = { 1, 5, 25, 125, 625, 3125,
537 15625, 78125 };
Chris Lattnerb858c0e2009-03-13 00:24:01 +0000538 integerPart pow5s[maxPowerOfFiveParts * 2 + 5];
539 pow5s[0] = 78125 * 5;
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000540
Chris Lattner0bf18692009-03-13 00:03:51 +0000541 unsigned int partsCount[16] = { 1 };
Chris Lattner91702092009-03-12 23:59:55 +0000542 integerPart scratch[maxPowerOfFiveParts], *p1, *p2, *pow5;
543 unsigned int result;
Chris Lattner91702092009-03-12 23:59:55 +0000544 assert(power <= maxExponent);
545
546 p1 = dst;
547 p2 = scratch;
548
549 *p1 = firstEightPowers[power & 7];
550 power >>= 3;
551
552 result = 1;
553 pow5 = pow5s;
554
555 for (unsigned int n = 0; power; power >>= 1, n++) {
556 unsigned int pc;
557
558 pc = partsCount[n];
559
560 /* Calculate pow(5,pow(2,n+3)) if we haven't yet. */
561 if (pc == 0) {
562 pc = partsCount[n - 1];
563 APInt::tcFullMultiply(pow5, pow5 - pc, pow5 - pc, pc, pc);
564 pc *= 2;
565 if (pow5[pc - 1] == 0)
566 pc--;
567 partsCount[n] = pc;
Neil Boothb93d90e2007-10-12 16:02:31 +0000568 }
569
Chris Lattner91702092009-03-12 23:59:55 +0000570 if (power & 1) {
571 integerPart *tmp;
Neil Boothb93d90e2007-10-12 16:02:31 +0000572
Chris Lattner91702092009-03-12 23:59:55 +0000573 APInt::tcFullMultiply(p2, p1, pow5, result, pc);
574 result += pc;
575 if (p2[result - 1] == 0)
576 result--;
Neil Boothb93d90e2007-10-12 16:02:31 +0000577
Chris Lattner91702092009-03-12 23:59:55 +0000578 /* Now result is in p1 with partsCount parts and p2 is scratch
579 space. */
Richard Trieu7a083812016-02-18 22:09:30 +0000580 tmp = p1;
581 p1 = p2;
582 p2 = tmp;
Neil Boothb93d90e2007-10-12 16:02:31 +0000583 }
584
Chris Lattner91702092009-03-12 23:59:55 +0000585 pow5 += pc;
Neil Boothb93d90e2007-10-12 16:02:31 +0000586 }
587
Chris Lattner91702092009-03-12 23:59:55 +0000588 if (p1 != dst)
589 APInt::tcAssign(dst, p1, result);
Neil Boothb93d90e2007-10-12 16:02:31 +0000590
Chris Lattner91702092009-03-12 23:59:55 +0000591 return result;
592}
Neil Boothb93d90e2007-10-12 16:02:31 +0000593
Chris Lattner91702092009-03-12 23:59:55 +0000594/* Zero at the end to avoid modular arithmetic when adding one; used
595 when rounding up during hexadecimal output. */
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000596static const char hexDigitsLower[] = "0123456789abcdef0";
597static const char hexDigitsUpper[] = "0123456789ABCDEF0";
598static const char infinityL[] = "infinity";
599static const char infinityU[] = "INFINITY";
600static const char NaNL[] = "nan";
601static const char NaNU[] = "NAN";
Neil Boothb93d90e2007-10-12 16:02:31 +0000602
Chris Lattner91702092009-03-12 23:59:55 +0000603/* Write out an integerPart in hexadecimal, starting with the most
604 significant nibble. Write out exactly COUNT hexdigits, return
605 COUNT. */
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000606static unsigned int
Chris Lattner91702092009-03-12 23:59:55 +0000607partAsHex (char *dst, integerPart part, unsigned int count,
608 const char *hexDigitChars)
609{
610 unsigned int result = count;
Neil Boothb93d90e2007-10-12 16:02:31 +0000611
Evan Cheng67c90212009-10-27 21:35:42 +0000612 assert(count != 0 && count <= integerPartWidth / 4);
Neil Boothb93d90e2007-10-12 16:02:31 +0000613
Chris Lattner91702092009-03-12 23:59:55 +0000614 part >>= (integerPartWidth - 4 * count);
615 while (count--) {
616 dst[count] = hexDigitChars[part & 0xf];
617 part >>= 4;
Neil Boothb93d90e2007-10-12 16:02:31 +0000618 }
619
Chris Lattner91702092009-03-12 23:59:55 +0000620 return result;
621}
Neil Booth8f1946f2007-10-03 22:26:02 +0000622
Chris Lattner91702092009-03-12 23:59:55 +0000623/* Write out an unsigned decimal integer. */
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000624static char *
Chris Lattner91702092009-03-12 23:59:55 +0000625writeUnsignedDecimal (char *dst, unsigned int n)
626{
627 char buff[40], *p;
Neil Booth8f1946f2007-10-03 22:26:02 +0000628
Chris Lattner91702092009-03-12 23:59:55 +0000629 p = buff;
630 do
631 *p++ = '0' + n % 10;
632 while (n /= 10);
Neil Booth8f1946f2007-10-03 22:26:02 +0000633
Chris Lattner91702092009-03-12 23:59:55 +0000634 do
635 *dst++ = *--p;
636 while (p != buff);
Neil Booth8f1946f2007-10-03 22:26:02 +0000637
Chris Lattner91702092009-03-12 23:59:55 +0000638 return dst;
639}
Neil Booth8f1946f2007-10-03 22:26:02 +0000640
Chris Lattner91702092009-03-12 23:59:55 +0000641/* Write out a signed decimal integer. */
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000642static char *
Chris Lattner91702092009-03-12 23:59:55 +0000643writeSignedDecimal (char *dst, int value)
644{
645 if (value < 0) {
646 *dst++ = '-';
647 dst = writeUnsignedDecimal(dst, -(unsigned) value);
648 } else
649 dst = writeUnsignedDecimal(dst, value);
Neil Booth8f1946f2007-10-03 22:26:02 +0000650
Chris Lattner91702092009-03-12 23:59:55 +0000651 return dst;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000652}
653
Tim Shen85de51d2016-10-25 19:55:59 +0000654namespace detail {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000655/* Constructors. */
Tim Shen85de51d2016-10-25 19:55:59 +0000656void IEEEFloat::initialize(const fltSemantics *ourSemantics) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000657 unsigned int count;
658
659 semantics = ourSemantics;
660 count = partCount();
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000661 if (count > 1)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000662 significand.parts = new integerPart[count];
663}
664
Tim Shen85de51d2016-10-25 19:55:59 +0000665void IEEEFloat::freeSignificand() {
Manuel Klimekd0cf5b22013-06-03 13:03:05 +0000666 if (needsCleanup())
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000667 delete [] significand.parts;
668}
669
Tim Shen85de51d2016-10-25 19:55:59 +0000670void IEEEFloat::assign(const IEEEFloat &rhs) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000671 assert(semantics == rhs.semantics);
672
673 sign = rhs.sign;
674 category = rhs.category;
675 exponent = rhs.exponent;
Michael Gottesman8136c382013-06-26 23:17:28 +0000676 if (isFiniteNonZero() || category == fcNaN)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000677 copySignificand(rhs);
678}
679
Tim Shen85de51d2016-10-25 19:55:59 +0000680void IEEEFloat::copySignificand(const IEEEFloat &rhs) {
Michael Gottesman8136c382013-06-26 23:17:28 +0000681 assert(isFiniteNonZero() || category == fcNaN);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000682 assert(rhs.partCount() >= partCount());
683
684 APInt::tcAssign(significandParts(), rhs.significandParts(),
Neil Booth9acbf5a2007-09-26 21:33:42 +0000685 partCount());
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000686}
687
Neil Booth5fe658b2007-10-14 10:39:51 +0000688/* Make this number a NaN, with an arbitrary but deterministic value
Dale Johannesen1f864982009-01-21 20:32:55 +0000689 for the significand. If double or longer, this is a signalling NaN,
Mike Stump799bf582009-05-30 03:49:43 +0000690 which may not be ideal. If float, this is QNaN(0). */
Tim Shen85de51d2016-10-25 19:55:59 +0000691void IEEEFloat::makeNaN(bool SNaN, bool Negative, const APInt *fill) {
Neil Booth5fe658b2007-10-14 10:39:51 +0000692 category = fcNaN;
John McCalldcb9a7a2010-02-28 02:51:25 +0000693 sign = Negative;
694
John McCallc12b1332010-02-28 12:49:50 +0000695 integerPart *significand = significandParts();
696 unsigned numParts = partCount();
697
John McCalldcb9a7a2010-02-28 02:51:25 +0000698 // Set the significand bits to the fill.
John McCallc12b1332010-02-28 12:49:50 +0000699 if (!fill || fill->getNumWords() < numParts)
700 APInt::tcSet(significand, 0, numParts);
701 if (fill) {
John McCallc6dbe302010-03-01 18:38:45 +0000702 APInt::tcAssign(significand, fill->getRawData(),
703 std::min(fill->getNumWords(), numParts));
John McCallc12b1332010-02-28 12:49:50 +0000704
705 // Zero out the excess bits of the significand.
706 unsigned bitsToPreserve = semantics->precision - 1;
707 unsigned part = bitsToPreserve / 64;
708 bitsToPreserve %= 64;
709 significand[part] &= ((1ULL << bitsToPreserve) - 1);
710 for (part++; part != numParts; ++part)
711 significand[part] = 0;
712 }
713
714 unsigned QNaNBit = semantics->precision - 2;
John McCalldcb9a7a2010-02-28 02:51:25 +0000715
716 if (SNaN) {
717 // We always have to clear the QNaN bit to make it an SNaN.
John McCallc12b1332010-02-28 12:49:50 +0000718 APInt::tcClearBit(significand, QNaNBit);
John McCalldcb9a7a2010-02-28 02:51:25 +0000719
720 // If there are no bits set in the payload, we have to set
721 // *something* to make it a NaN instead of an infinity;
722 // conventionally, this is the next bit down from the QNaN bit.
John McCallc12b1332010-02-28 12:49:50 +0000723 if (APInt::tcIsZero(significand, numParts))
724 APInt::tcSetBit(significand, QNaNBit - 1);
John McCalldcb9a7a2010-02-28 02:51:25 +0000725 } else {
726 // We always have to set the QNaN bit to make it a QNaN.
John McCallc12b1332010-02-28 12:49:50 +0000727 APInt::tcSetBit(significand, QNaNBit);
John McCalldcb9a7a2010-02-28 02:51:25 +0000728 }
John McCallc12b1332010-02-28 12:49:50 +0000729
730 // For x87 extended precision, we want to make a NaN, not a
731 // pseudo-NaN. Maybe we should expose the ability to make
732 // pseudo-NaNs?
Stephan Bergmann17c7f702016-12-14 11:57:17 +0000733 if (semantics == &semX87DoubleExtended)
John McCallc12b1332010-02-28 12:49:50 +0000734 APInt::tcSetBit(significand, QNaNBit + 1);
John McCalldcb9a7a2010-02-28 02:51:25 +0000735}
736
Tim Shen85de51d2016-10-25 19:55:59 +0000737IEEEFloat &IEEEFloat::operator=(const IEEEFloat &rhs) {
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000738 if (this != &rhs) {
739 if (semantics != rhs.semantics) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000740 freeSignificand();
741 initialize(rhs.semantics);
742 }
743 assign(rhs);
744 }
745
746 return *this;
747}
748
Tim Shen85de51d2016-10-25 19:55:59 +0000749IEEEFloat &IEEEFloat::operator=(IEEEFloat &&rhs) {
Benjamin Kramer06f47782014-03-04 20:26:51 +0000750 freeSignificand();
751
752 semantics = rhs.semantics;
753 significand = rhs.significand;
754 exponent = rhs.exponent;
755 category = rhs.category;
756 sign = rhs.sign;
757
Stephan Bergmann17c7f702016-12-14 11:57:17 +0000758 rhs.semantics = &semBogus;
Benjamin Kramer06f47782014-03-04 20:26:51 +0000759 return *this;
760}
761
Tim Shen85de51d2016-10-25 19:55:59 +0000762bool IEEEFloat::isDenormal() const {
Michael Gottesman3cb77ab2013-06-19 21:23:18 +0000763 return isFiniteNonZero() && (exponent == semantics->minExponent) &&
Shuxin Yang4fb504f2013-01-07 18:59:35 +0000764 (APInt::tcExtractBit(significandParts(),
765 semantics->precision - 1) == 0);
766}
767
Tim Shen85de51d2016-10-25 19:55:59 +0000768bool IEEEFloat::isSmallest() const {
Michael Gottesman0c622ea2013-05-30 18:07:13 +0000769 // The smallest number by magnitude in our format will be the smallest
Michael Gottesmana7cc1242013-06-19 07:34:21 +0000770 // denormal, i.e. the floating point number with exponent being minimum
Michael Gottesman0c622ea2013-05-30 18:07:13 +0000771 // exponent and significand bitwise equal to 1 (i.e. with MSB equal to 0).
Michael Gottesman3cb77ab2013-06-19 21:23:18 +0000772 return isFiniteNonZero() && exponent == semantics->minExponent &&
Michael Gottesman0c622ea2013-05-30 18:07:13 +0000773 significandMSB() == 0;
774}
775
Tim Shen85de51d2016-10-25 19:55:59 +0000776bool IEEEFloat::isSignificandAllOnes() const {
Michael Gottesman0c622ea2013-05-30 18:07:13 +0000777 // Test if the significand excluding the integral bit is all ones. This allows
778 // us to test for binade boundaries.
779 const integerPart *Parts = significandParts();
780 const unsigned PartCount = partCount();
781 for (unsigned i = 0; i < PartCount - 1; i++)
782 if (~Parts[i])
783 return false;
784
785 // Set the unused high bits to all ones when we compare.
786 const unsigned NumHighBits =
787 PartCount*integerPartWidth - semantics->precision + 1;
788 assert(NumHighBits <= integerPartWidth && "Can not have more high bits to "
789 "fill than integerPartWidth");
790 const integerPart HighBitFill =
791 ~integerPart(0) << (integerPartWidth - NumHighBits);
792 if (~(Parts[PartCount - 1] | HighBitFill))
793 return false;
794
795 return true;
796}
797
Tim Shen85de51d2016-10-25 19:55:59 +0000798bool IEEEFloat::isSignificandAllZeros() const {
Michael Gottesman0c622ea2013-05-30 18:07:13 +0000799 // Test if the significand excluding the integral bit is all zeros. This
800 // allows us to test for binade boundaries.
801 const integerPart *Parts = significandParts();
802 const unsigned PartCount = partCount();
803
804 for (unsigned i = 0; i < PartCount - 1; i++)
805 if (Parts[i])
806 return false;
807
808 const unsigned NumHighBits =
809 PartCount*integerPartWidth - semantics->precision + 1;
810 assert(NumHighBits <= integerPartWidth && "Can not have more high bits to "
811 "clear than integerPartWidth");
812 const integerPart HighBitMask = ~integerPart(0) >> NumHighBits;
813
814 if (Parts[PartCount - 1] & HighBitMask)
815 return false;
816
817 return true;
818}
819
Tim Shen85de51d2016-10-25 19:55:59 +0000820bool IEEEFloat::isLargest() const {
Michael Gottesman0c622ea2013-05-30 18:07:13 +0000821 // The largest number by magnitude in our format will be the floating point
822 // number with maximum exponent and with significand that is all ones.
Michael Gottesman3cb77ab2013-06-19 21:23:18 +0000823 return isFiniteNonZero() && exponent == semantics->maxExponent
Michael Gottesman0c622ea2013-05-30 18:07:13 +0000824 && isSignificandAllOnes();
825}
826
Tim Shen85de51d2016-10-25 19:55:59 +0000827bool IEEEFloat::isInteger() const {
Stephen Canon1bfc89b2015-11-16 21:52:48 +0000828 // This could be made more efficient; I'm going for obviously correct.
829 if (!isFinite()) return false;
Tim Shen85de51d2016-10-25 19:55:59 +0000830 IEEEFloat truncated = *this;
Stephen Canon1bfc89b2015-11-16 21:52:48 +0000831 truncated.roundToIntegral(rmTowardZero);
832 return compare(truncated) == cmpEqual;
833}
834
Tim Shen85de51d2016-10-25 19:55:59 +0000835bool IEEEFloat::bitwiseIsEqual(const IEEEFloat &rhs) const {
Dale Johannesena719a602007-08-24 00:56:33 +0000836 if (this == &rhs)
837 return true;
838 if (semantics != rhs.semantics ||
Dale Johannesen3cf889f2007-08-31 04:03:46 +0000839 category != rhs.category ||
840 sign != rhs.sign)
Dale Johannesena719a602007-08-24 00:56:33 +0000841 return false;
Dale Johannesen3cf889f2007-08-31 04:03:46 +0000842 if (category==fcZero || category==fcInfinity)
Dale Johannesena719a602007-08-24 00:56:33 +0000843 return true;
Benjamin Kramer103fc942015-08-21 16:44:52 +0000844
845 if (isFiniteNonZero() && exponent != rhs.exponent)
Dale Johannesen3cf889f2007-08-31 04:03:46 +0000846 return false;
Benjamin Kramer103fc942015-08-21 16:44:52 +0000847
848 return std::equal(significandParts(), significandParts() + partCount(),
849 rhs.significandParts());
Dale Johannesena719a602007-08-24 00:56:33 +0000850}
851
Tim Shen85de51d2016-10-25 19:55:59 +0000852IEEEFloat::IEEEFloat(const fltSemantics &ourSemantics, integerPart value) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000853 initialize(&ourSemantics);
854 sign = 0;
Michael Gottesman30a90eb2013-07-27 21:49:21 +0000855 category = fcNormal;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000856 zeroSignificand();
857 exponent = ourSemantics.precision - 1;
858 significandParts()[0] = value;
859 normalize(rmNearestTiesToEven, lfExactlyZero);
860}
861
Tim Shen85de51d2016-10-25 19:55:59 +0000862IEEEFloat::IEEEFloat(const fltSemantics &ourSemantics) {
Chris Lattnerac6271e2009-09-17 01:08:43 +0000863 initialize(&ourSemantics);
864 category = fcZero;
865 sign = false;
866}
867
Tim Shenb49915482016-10-28 22:45:33 +0000868// Delegate to the previous constructor, because later copy constructor may
869// actually inspects category, which can't be garbage.
870IEEEFloat::IEEEFloat(const fltSemantics &ourSemantics, uninitializedTag tag)
Tim Shen1bab9cf2016-10-29 00:51:41 +0000871 : IEEEFloat(ourSemantics) {}
Chris Lattnerac6271e2009-09-17 01:08:43 +0000872
Tim Shen85de51d2016-10-25 19:55:59 +0000873IEEEFloat::IEEEFloat(const IEEEFloat &rhs) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000874 initialize(rhs.semantics);
875 assign(rhs);
876}
877
Stephan Bergmann17c7f702016-12-14 11:57:17 +0000878IEEEFloat::IEEEFloat(IEEEFloat &&rhs) : semantics(&semBogus) {
Benjamin Kramer06f47782014-03-04 20:26:51 +0000879 *this = std::move(rhs);
880}
881
Tim Shen85de51d2016-10-25 19:55:59 +0000882IEEEFloat::~IEEEFloat() { freeSignificand(); }
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000883
Tim Shen85de51d2016-10-25 19:55:59 +0000884unsigned int IEEEFloat::partCount() const {
Dale Johannesen146a0ea2007-09-20 23:47:58 +0000885 return partCountForBits(semantics->precision + 1);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000886}
887
Tim Shen85de51d2016-10-25 19:55:59 +0000888const integerPart *IEEEFloat::significandParts() const {
889 return const_cast<IEEEFloat *>(this)->significandParts();
JF Bastiena1d3c242015-08-26 02:32:45 +0000890}
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000891
Tim Shen85de51d2016-10-25 19:55:59 +0000892integerPart *IEEEFloat::significandParts() {
Evan Cheng67c90212009-10-27 21:35:42 +0000893 if (partCount() > 1)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000894 return significand.parts;
895 else
896 return &significand.part;
897}
898
Tim Shen85de51d2016-10-25 19:55:59 +0000899void IEEEFloat::zeroSignificand() {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000900 APInt::tcSet(significandParts(), 0, partCount());
901}
902
903/* Increment an fcNormal floating point number's significand. */
Tim Shen85de51d2016-10-25 19:55:59 +0000904void IEEEFloat::incrementSignificand() {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000905 integerPart carry;
906
907 carry = APInt::tcIncrement(significandParts(), partCount());
908
909 /* Our callers should never cause us to overflow. */
910 assert(carry == 0);
Duncan Sandsa41634e2011-08-12 14:54:45 +0000911 (void)carry;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000912}
913
914/* Add the significand of the RHS. Returns the carry flag. */
Tim Shen85de51d2016-10-25 19:55:59 +0000915integerPart IEEEFloat::addSignificand(const IEEEFloat &rhs) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000916 integerPart *parts;
917
918 parts = significandParts();
919
920 assert(semantics == rhs.semantics);
921 assert(exponent == rhs.exponent);
922
923 return APInt::tcAdd(parts, rhs.significandParts(), 0, partCount());
924}
925
926/* Subtract the significand of the RHS with a borrow flag. Returns
927 the borrow flag. */
Tim Shen85de51d2016-10-25 19:55:59 +0000928integerPart IEEEFloat::subtractSignificand(const IEEEFloat &rhs,
929 integerPart borrow) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000930 integerPart *parts;
931
932 parts = significandParts();
933
934 assert(semantics == rhs.semantics);
935 assert(exponent == rhs.exponent);
936
937 return APInt::tcSubtract(parts, rhs.significandParts(), borrow,
Neil Booth9acbf5a2007-09-26 21:33:42 +0000938 partCount());
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000939}
940
941/* Multiply the significand of the RHS. If ADDEND is non-NULL, add it
942 on to the full-precision result of the multiplication. Returns the
943 lost fraction. */
Tim Shen85de51d2016-10-25 19:55:59 +0000944lostFraction IEEEFloat::multiplySignificand(const IEEEFloat &rhs,
945 const IEEEFloat *addend) {
Neil Booth9acbf5a2007-09-26 21:33:42 +0000946 unsigned int omsb; // One, not zero, based MSB.
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000947 unsigned int partsCount, newPartsCount, precision;
948 integerPart *lhsSignificand;
949 integerPart scratch[4];
950 integerPart *fullSignificand;
951 lostFraction lost_fraction;
Dale Johannesen4f0bd682008-10-09 23:00:39 +0000952 bool ignored;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000953
954 assert(semantics == rhs.semantics);
955
956 precision = semantics->precision;
Lang Hames56c0eb22014-11-19 19:15:41 +0000957
958 // Allocate space for twice as many bits as the original significand, plus one
959 // extra bit for the addition to overflow into.
960 newPartsCount = partCountForBits(precision * 2 + 1);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000961
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000962 if (newPartsCount > 4)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000963 fullSignificand = new integerPart[newPartsCount];
964 else
965 fullSignificand = scratch;
966
967 lhsSignificand = significandParts();
968 partsCount = partCount();
969
970 APInt::tcFullMultiply(fullSignificand, lhsSignificand,
Neil Booth0ea72a92007-10-06 00:24:48 +0000971 rhs.significandParts(), partsCount, partsCount);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000972
973 lost_fraction = lfExactlyZero;
974 omsb = APInt::tcMSB(fullSignificand, newPartsCount) + 1;
975 exponent += rhs.exponent;
976
Shuxin Yangbbddbac2013-05-13 18:03:12 +0000977 // Assume the operands involved in the multiplication are single-precision
978 // FP, and the two multiplicants are:
979 // *this = a23 . a22 ... a0 * 2^e1
980 // rhs = b23 . b22 ... b0 * 2^e2
981 // the result of multiplication is:
Lang Hames56c0eb22014-11-19 19:15:41 +0000982 // *this = c48 c47 c46 . c45 ... c0 * 2^(e1+e2)
983 // Note that there are three significant bits at the left-hand side of the
984 // radix point: two for the multiplication, and an overflow bit for the
985 // addition (that will always be zero at this point). Move the radix point
986 // toward left by two bits, and adjust exponent accordingly.
987 exponent += 2;
Shuxin Yangbbddbac2013-05-13 18:03:12 +0000988
Hal Finkel171c2ec2014-10-14 19:23:07 +0000989 if (addend && addend->isNonZero()) {
Shuxin Yangbbddbac2013-05-13 18:03:12 +0000990 // The intermediate result of the multiplication has "2 * precision"
991 // signicant bit; adjust the addend to be consistent with mul result.
992 //
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000993 Significand savedSignificand = significand;
994 const fltSemantics *savedSemantics = semantics;
995 fltSemantics extendedSemantics;
996 opStatus status;
997 unsigned int extendedPrecision;
998
Lang Hames56c0eb22014-11-19 19:15:41 +0000999 // Normalize our MSB to one below the top bit to allow for overflow.
1000 extendedPrecision = 2 * precision + 1;
1001 if (omsb != extendedPrecision - 1) {
Shuxin Yangbbddbac2013-05-13 18:03:12 +00001002 assert(extendedPrecision > omsb);
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001003 APInt::tcShiftLeft(fullSignificand, newPartsCount,
Lang Hames56c0eb22014-11-19 19:15:41 +00001004 (extendedPrecision - 1) - omsb);
1005 exponent -= (extendedPrecision - 1) - omsb;
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001006 }
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001007
1008 /* Create new semantics. */
1009 extendedSemantics = *semantics;
1010 extendedSemantics.precision = extendedPrecision;
1011
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001012 if (newPartsCount == 1)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001013 significand.part = fullSignificand[0];
1014 else
1015 significand.parts = fullSignificand;
1016 semantics = &extendedSemantics;
1017
Tim Shen85de51d2016-10-25 19:55:59 +00001018 IEEEFloat extendedAddend(*addend);
Dale Johannesen4f0bd682008-10-09 23:00:39 +00001019 status = extendedAddend.convert(extendedSemantics, rmTowardZero, &ignored);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001020 assert(status == opOK);
Duncan Sandsa41634e2011-08-12 14:54:45 +00001021 (void)status;
Lang Hames56c0eb22014-11-19 19:15:41 +00001022
1023 // Shift the significand of the addend right by one bit. This guarantees
1024 // that the high bit of the significand is zero (same as fullSignificand),
1025 // so the addition will overflow (if it does overflow at all) into the top bit.
1026 lost_fraction = extendedAddend.shiftSignificandRight(1);
1027 assert(lost_fraction == lfExactlyZero &&
1028 "Lost precision while shifting addend for fused-multiply-add.");
1029
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001030 lost_fraction = addOrSubtractSignificand(extendedAddend, false);
1031
1032 /* Restore our state. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001033 if (newPartsCount == 1)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001034 fullSignificand[0] = significand.part;
1035 significand = savedSignificand;
1036 semantics = savedSemantics;
1037
1038 omsb = APInt::tcMSB(fullSignificand, newPartsCount) + 1;
1039 }
1040
Shuxin Yangbbddbac2013-05-13 18:03:12 +00001041 // Convert the result having "2 * precision" significant-bits back to the one
1042 // having "precision" significant-bits. First, move the radix point from
1043 // poision "2*precision - 1" to "precision - 1". The exponent need to be
1044 // adjusted by "2*precision - 1" - "precision - 1" = "precision".
Lang Hames56c0eb22014-11-19 19:15:41 +00001045 exponent -= precision + 1;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001046
Shuxin Yangbbddbac2013-05-13 18:03:12 +00001047 // In case MSB resides at the left-hand side of radix point, shift the
1048 // mantissa right by some amount to make sure the MSB reside right before
1049 // the radix point (i.e. "MSB . rest-significant-bits").
1050 //
1051 // Note that the result is not normalized when "omsb < precision". So, the
Tim Shen85de51d2016-10-25 19:55:59 +00001052 // caller needs to call IEEEFloat::normalize() if normalized value is
1053 // expected.
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001054 if (omsb > precision) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001055 unsigned int bits, significantParts;
1056 lostFraction lf;
1057
1058 bits = omsb - precision;
1059 significantParts = partCountForBits(omsb);
1060 lf = shiftRight(fullSignificand, significantParts, bits);
1061 lost_fraction = combineLostFractions(lf, lost_fraction);
1062 exponent += bits;
1063 }
1064
1065 APInt::tcAssign(lhsSignificand, fullSignificand, partsCount);
1066
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001067 if (newPartsCount > 4)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001068 delete [] fullSignificand;
1069
1070 return lost_fraction;
1071}
1072
1073/* Multiply the significands of LHS and RHS to DST. */
Tim Shen85de51d2016-10-25 19:55:59 +00001074lostFraction IEEEFloat::divideSignificand(const IEEEFloat &rhs) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001075 unsigned int bit, i, partsCount;
1076 const integerPart *rhsSignificand;
1077 integerPart *lhsSignificand, *dividend, *divisor;
1078 integerPart scratch[4];
1079 lostFraction lost_fraction;
1080
1081 assert(semantics == rhs.semantics);
1082
1083 lhsSignificand = significandParts();
1084 rhsSignificand = rhs.significandParts();
1085 partsCount = partCount();
1086
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001087 if (partsCount > 2)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001088 dividend = new integerPart[partsCount * 2];
1089 else
1090 dividend = scratch;
1091
1092 divisor = dividend + partsCount;
1093
1094 /* Copy the dividend and divisor as they will be modified in-place. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001095 for (i = 0; i < partsCount; i++) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001096 dividend[i] = lhsSignificand[i];
1097 divisor[i] = rhsSignificand[i];
1098 lhsSignificand[i] = 0;
1099 }
1100
1101 exponent -= rhs.exponent;
1102
1103 unsigned int precision = semantics->precision;
1104
1105 /* Normalize the divisor. */
1106 bit = precision - APInt::tcMSB(divisor, partsCount) - 1;
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001107 if (bit) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001108 exponent += bit;
1109 APInt::tcShiftLeft(divisor, partsCount, bit);
1110 }
1111
1112 /* Normalize the dividend. */
1113 bit = precision - APInt::tcMSB(dividend, partsCount) - 1;
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001114 if (bit) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001115 exponent -= bit;
1116 APInt::tcShiftLeft(dividend, partsCount, bit);
1117 }
1118
Neil Boothb93d90e2007-10-12 16:02:31 +00001119 /* Ensure the dividend >= divisor initially for the loop below.
1120 Incidentally, this means that the division loop below is
1121 guaranteed to set the integer bit to one. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001122 if (APInt::tcCompare(dividend, divisor, partsCount) < 0) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001123 exponent--;
1124 APInt::tcShiftLeft(dividend, partsCount, 1);
1125 assert(APInt::tcCompare(dividend, divisor, partsCount) >= 0);
1126 }
1127
1128 /* Long division. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001129 for (bit = precision; bit; bit -= 1) {
1130 if (APInt::tcCompare(dividend, divisor, partsCount) >= 0) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001131 APInt::tcSubtract(dividend, divisor, 0, partsCount);
1132 APInt::tcSetBit(lhsSignificand, bit - 1);
1133 }
1134
1135 APInt::tcShiftLeft(dividend, partsCount, 1);
1136 }
1137
1138 /* Figure out the lost fraction. */
1139 int cmp = APInt::tcCompare(dividend, divisor, partsCount);
1140
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001141 if (cmp > 0)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001142 lost_fraction = lfMoreThanHalf;
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001143 else if (cmp == 0)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001144 lost_fraction = lfExactlyHalf;
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001145 else if (APInt::tcIsZero(dividend, partsCount))
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001146 lost_fraction = lfExactlyZero;
1147 else
1148 lost_fraction = lfLessThanHalf;
1149
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001150 if (partsCount > 2)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001151 delete [] dividend;
1152
1153 return lost_fraction;
1154}
1155
Tim Shen85de51d2016-10-25 19:55:59 +00001156unsigned int IEEEFloat::significandMSB() const {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001157 return APInt::tcMSB(significandParts(), partCount());
1158}
1159
Tim Shen85de51d2016-10-25 19:55:59 +00001160unsigned int IEEEFloat::significandLSB() const {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001161 return APInt::tcLSB(significandParts(), partCount());
1162}
1163
1164/* Note that a zero result is NOT normalized to fcZero. */
Tim Shen85de51d2016-10-25 19:55:59 +00001165lostFraction IEEEFloat::shiftSignificandRight(unsigned int bits) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001166 /* Our exponent should not overflow. */
Michael Gottesman9dc98332013-06-24 04:06:23 +00001167 assert((ExponentType) (exponent + bits) >= exponent);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001168
1169 exponent += bits;
1170
1171 return shiftRight(significandParts(), partCount(), bits);
1172}
1173
1174/* Shift the significand left BITS bits, subtract BITS from its exponent. */
Tim Shen85de51d2016-10-25 19:55:59 +00001175void IEEEFloat::shiftSignificandLeft(unsigned int bits) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001176 assert(bits < semantics->precision);
1177
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001178 if (bits) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001179 unsigned int partsCount = partCount();
1180
1181 APInt::tcShiftLeft(significandParts(), partsCount, bits);
1182 exponent -= bits;
1183
1184 assert(!APInt::tcIsZero(significandParts(), partsCount));
1185 }
1186}
1187
Tim Shen85de51d2016-10-25 19:55:59 +00001188IEEEFloat::cmpResult
1189IEEEFloat::compareAbsoluteValue(const IEEEFloat &rhs) const {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001190 int compare;
1191
1192 assert(semantics == rhs.semantics);
Michael Gottesman8136c382013-06-26 23:17:28 +00001193 assert(isFiniteNonZero());
1194 assert(rhs.isFiniteNonZero());
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001195
1196 compare = exponent - rhs.exponent;
1197
1198 /* If exponents are equal, do an unsigned bignum comparison of the
1199 significands. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001200 if (compare == 0)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001201 compare = APInt::tcCompare(significandParts(), rhs.significandParts(),
Neil Booth9acbf5a2007-09-26 21:33:42 +00001202 partCount());
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001203
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001204 if (compare > 0)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001205 return cmpGreaterThan;
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001206 else if (compare < 0)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001207 return cmpLessThan;
1208 else
1209 return cmpEqual;
1210}
1211
1212/* Handle overflow. Sign is preserved. We either become infinity or
1213 the largest finite number. */
Tim Shen85de51d2016-10-25 19:55:59 +00001214IEEEFloat::opStatus IEEEFloat::handleOverflow(roundingMode rounding_mode) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001215 /* Infinity? */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001216 if (rounding_mode == rmNearestTiesToEven ||
1217 rounding_mode == rmNearestTiesToAway ||
1218 (rounding_mode == rmTowardPositive && !sign) ||
1219 (rounding_mode == rmTowardNegative && sign)) {
1220 category = fcInfinity;
1221 return (opStatus) (opOverflow | opInexact);
1222 }
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001223
1224 /* Otherwise we become the largest finite number. */
1225 category = fcNormal;
1226 exponent = semantics->maxExponent;
1227 APInt::tcSetLeastSignificantBits(significandParts(), partCount(),
Neil Booth9acbf5a2007-09-26 21:33:42 +00001228 semantics->precision);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001229
1230 return opInexact;
1231}
1232
Neil Booth1ca1f802007-10-03 15:16:41 +00001233/* Returns TRUE if, when truncating the current number, with BIT the
1234 new LSB, with the given lost fraction and rounding mode, the result
1235 would need to be rounded away from zero (i.e., by increasing the
1236 signficand). This routine must work for fcZero of both signs, and
1237 fcNormal numbers. */
Tim Shen85de51d2016-10-25 19:55:59 +00001238bool IEEEFloat::roundAwayFromZero(roundingMode rounding_mode,
1239 lostFraction lost_fraction,
1240 unsigned int bit) const {
Dale Johannesen3cf889f2007-08-31 04:03:46 +00001241 /* NaNs and infinities should not have lost fractions. */
Michael Gottesman8136c382013-06-26 23:17:28 +00001242 assert(isFiniteNonZero() || category == fcZero);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001243
Neil Booth1ca1f802007-10-03 15:16:41 +00001244 /* Current callers never pass this so we don't handle it. */
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001245 assert(lost_fraction != lfExactlyZero);
1246
Mike Stump889285d2009-05-13 23:23:20 +00001247 switch (rounding_mode) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001248 case rmNearestTiesToAway:
1249 return lost_fraction == lfExactlyHalf || lost_fraction == lfMoreThanHalf;
1250
1251 case rmNearestTiesToEven:
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001252 if (lost_fraction == lfMoreThanHalf)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001253 return true;
1254
1255 /* Our zeroes don't have a significand to test. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001256 if (lost_fraction == lfExactlyHalf && category != fcZero)
Neil Booth1ca1f802007-10-03 15:16:41 +00001257 return APInt::tcExtractBit(significandParts(), bit);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001258
1259 return false;
1260
1261 case rmTowardZero:
1262 return false;
1263
1264 case rmTowardPositive:
David Blaikiedc3f01e2015-03-09 01:57:13 +00001265 return !sign;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001266
1267 case rmTowardNegative:
David Blaikiedc3f01e2015-03-09 01:57:13 +00001268 return sign;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001269 }
Chandler Carruthf3e85022012-01-10 18:08:01 +00001270 llvm_unreachable("Invalid rounding mode found");
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001271}
1272
Tim Shen85de51d2016-10-25 19:55:59 +00001273IEEEFloat::opStatus IEEEFloat::normalize(roundingMode rounding_mode,
1274 lostFraction lost_fraction) {
Neil Booth9acbf5a2007-09-26 21:33:42 +00001275 unsigned int omsb; /* One, not zero, based MSB. */
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001276 int exponentChange;
1277
Michael Gottesman8136c382013-06-26 23:17:28 +00001278 if (!isFiniteNonZero())
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001279 return opOK;
1280
1281 /* Before rounding normalize the exponent of fcNormal numbers. */
1282 omsb = significandMSB() + 1;
1283
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001284 if (omsb) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001285 /* OMSB is numbered from 1. We want to place it in the integer
Nick Lewyckyf66daac2011-10-03 21:30:08 +00001286 bit numbered PRECISION if possible, with a compensating change in
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001287 the exponent. */
1288 exponentChange = omsb - semantics->precision;
1289
1290 /* If the resulting exponent is too high, overflow according to
1291 the rounding mode. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001292 if (exponent + exponentChange > semantics->maxExponent)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001293 return handleOverflow(rounding_mode);
1294
1295 /* Subnormal numbers have exponent minExponent, and their MSB
1296 is forced based on that. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001297 if (exponent + exponentChange < semantics->minExponent)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001298 exponentChange = semantics->minExponent - exponent;
1299
1300 /* Shifting left is easy as we don't lose precision. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001301 if (exponentChange < 0) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001302 assert(lost_fraction == lfExactlyZero);
1303
1304 shiftSignificandLeft(-exponentChange);
1305
1306 return opOK;
1307 }
1308
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001309 if (exponentChange > 0) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001310 lostFraction lf;
1311
1312 /* Shift right and capture any new lost fraction. */
1313 lf = shiftSignificandRight(exponentChange);
1314
1315 lost_fraction = combineLostFractions(lf, lost_fraction);
1316
1317 /* Keep OMSB up-to-date. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001318 if (omsb > (unsigned) exponentChange)
Neil Boothb93d90e2007-10-12 16:02:31 +00001319 omsb -= exponentChange;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001320 else
Neil Booth9acbf5a2007-09-26 21:33:42 +00001321 omsb = 0;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001322 }
1323 }
1324
1325 /* Now round the number according to rounding_mode given the lost
1326 fraction. */
1327
1328 /* As specified in IEEE 754, since we do not trap we do not report
1329 underflow for exact results. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001330 if (lost_fraction == lfExactlyZero) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001331 /* Canonicalize zeroes. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001332 if (omsb == 0)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001333 category = fcZero;
1334
1335 return opOK;
1336 }
1337
1338 /* Increment the significand if we're rounding away from zero. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001339 if (roundAwayFromZero(rounding_mode, lost_fraction, 0)) {
1340 if (omsb == 0)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001341 exponent = semantics->minExponent;
1342
1343 incrementSignificand();
1344 omsb = significandMSB() + 1;
1345
1346 /* Did the significand increment overflow? */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001347 if (omsb == (unsigned) semantics->precision + 1) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001348 /* Renormalize by incrementing the exponent and shifting our
Neil Booth9acbf5a2007-09-26 21:33:42 +00001349 significand right one. However if we already have the
1350 maximum exponent we overflow to infinity. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001351 if (exponent == semantics->maxExponent) {
Neil Booth9acbf5a2007-09-26 21:33:42 +00001352 category = fcInfinity;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001353
Neil Booth9acbf5a2007-09-26 21:33:42 +00001354 return (opStatus) (opOverflow | opInexact);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001355 }
1356
1357 shiftSignificandRight(1);
1358
1359 return opInexact;
1360 }
1361 }
1362
1363 /* The normal case - we were and are not denormal, and any
1364 significand increment above didn't overflow. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001365 if (omsb == semantics->precision)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001366 return opInexact;
1367
1368 /* We have a non-zero denormal. */
1369 assert(omsb < semantics->precision);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001370
1371 /* Canonicalize zeroes. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001372 if (omsb == 0)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001373 category = fcZero;
1374
1375 /* The fcZero case is a denormal that underflowed to zero. */
1376 return (opStatus) (opUnderflow | opInexact);
1377}
1378
Tim Shen85de51d2016-10-25 19:55:59 +00001379IEEEFloat::opStatus IEEEFloat::addOrSubtractSpecials(const IEEEFloat &rhs,
1380 bool subtract) {
Michael Gottesman9b877e12013-06-24 09:57:57 +00001381 switch (PackCategoriesIntoKey(category, rhs.category)) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001382 default:
Craig Topper2617dcc2014-04-15 06:32:26 +00001383 llvm_unreachable(nullptr);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001384
Michael Gottesman9b877e12013-06-24 09:57:57 +00001385 case PackCategoriesIntoKey(fcNaN, fcZero):
1386 case PackCategoriesIntoKey(fcNaN, fcNormal):
1387 case PackCategoriesIntoKey(fcNaN, fcInfinity):
1388 case PackCategoriesIntoKey(fcNaN, fcNaN):
1389 case PackCategoriesIntoKey(fcNormal, fcZero):
1390 case PackCategoriesIntoKey(fcInfinity, fcNormal):
1391 case PackCategoriesIntoKey(fcInfinity, fcZero):
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001392 return opOK;
1393
Michael Gottesman9b877e12013-06-24 09:57:57 +00001394 case PackCategoriesIntoKey(fcZero, fcNaN):
1395 case PackCategoriesIntoKey(fcNormal, fcNaN):
1396 case PackCategoriesIntoKey(fcInfinity, fcNaN):
Stephen Canond3278282014-06-08 16:53:31 +00001397 // We need to be sure to flip the sign here for subtraction because we
1398 // don't have a separate negate operation so -NaN becomes 0 - NaN here.
1399 sign = rhs.sign ^ subtract;
Dale Johannesen3cf889f2007-08-31 04:03:46 +00001400 category = fcNaN;
1401 copySignificand(rhs);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001402 return opOK;
1403
Michael Gottesman9b877e12013-06-24 09:57:57 +00001404 case PackCategoriesIntoKey(fcNormal, fcInfinity):
1405 case PackCategoriesIntoKey(fcZero, fcInfinity):
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001406 category = fcInfinity;
1407 sign = rhs.sign ^ subtract;
1408 return opOK;
1409
Michael Gottesman9b877e12013-06-24 09:57:57 +00001410 case PackCategoriesIntoKey(fcZero, fcNormal):
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001411 assign(rhs);
1412 sign = rhs.sign ^ subtract;
1413 return opOK;
1414
Michael Gottesman9b877e12013-06-24 09:57:57 +00001415 case PackCategoriesIntoKey(fcZero, fcZero):
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001416 /* Sign depends on rounding mode; handled by caller. */
1417 return opOK;
1418
Michael Gottesman9b877e12013-06-24 09:57:57 +00001419 case PackCategoriesIntoKey(fcInfinity, fcInfinity):
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001420 /* Differently signed infinities can only be validly
1421 subtracted. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001422 if (((sign ^ rhs.sign)!=0) != subtract) {
Neil Booth5fe658b2007-10-14 10:39:51 +00001423 makeNaN();
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001424 return opInvalidOp;
1425 }
1426
1427 return opOK;
1428
Michael Gottesman9b877e12013-06-24 09:57:57 +00001429 case PackCategoriesIntoKey(fcNormal, fcNormal):
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001430 return opDivByZero;
1431 }
1432}
1433
1434/* Add or subtract two normal numbers. */
Tim Shen85de51d2016-10-25 19:55:59 +00001435lostFraction IEEEFloat::addOrSubtractSignificand(const IEEEFloat &rhs,
1436 bool subtract) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001437 integerPart carry;
1438 lostFraction lost_fraction;
1439 int bits;
1440
1441 /* Determine if the operation on the absolute values is effectively
1442 an addition or subtraction. */
Aaron Ballmand5cc45f2015-03-24 12:47:51 +00001443 subtract ^= static_cast<bool>(sign ^ rhs.sign);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001444
1445 /* Are we bigger exponent-wise than the RHS? */
1446 bits = exponent - rhs.exponent;
1447
1448 /* Subtraction is more subtle than one might naively expect. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001449 if (subtract) {
Tim Shen85de51d2016-10-25 19:55:59 +00001450 IEEEFloat temp_rhs(rhs);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001451 bool reverse;
1452
Chris Lattner3da18eb2007-08-24 03:02:34 +00001453 if (bits == 0) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001454 reverse = compareAbsoluteValue(temp_rhs) == cmpLessThan;
1455 lost_fraction = lfExactlyZero;
Chris Lattner3da18eb2007-08-24 03:02:34 +00001456 } else if (bits > 0) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001457 lost_fraction = temp_rhs.shiftSignificandRight(bits - 1);
1458 shiftSignificandLeft(1);
1459 reverse = false;
Chris Lattner3da18eb2007-08-24 03:02:34 +00001460 } else {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001461 lost_fraction = shiftSignificandRight(-bits - 1);
1462 temp_rhs.shiftSignificandLeft(1);
1463 reverse = true;
1464 }
1465
Chris Lattner3da18eb2007-08-24 03:02:34 +00001466 if (reverse) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001467 carry = temp_rhs.subtractSignificand
Neil Booth9acbf5a2007-09-26 21:33:42 +00001468 (*this, lost_fraction != lfExactlyZero);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001469 copySignificand(temp_rhs);
1470 sign = !sign;
1471 } else {
1472 carry = subtractSignificand
Neil Booth9acbf5a2007-09-26 21:33:42 +00001473 (temp_rhs, lost_fraction != lfExactlyZero);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001474 }
1475
1476 /* Invert the lost fraction - it was on the RHS and
1477 subtracted. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001478 if (lost_fraction == lfLessThanHalf)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001479 lost_fraction = lfMoreThanHalf;
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001480 else if (lost_fraction == lfMoreThanHalf)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001481 lost_fraction = lfLessThanHalf;
1482
1483 /* The code above is intended to ensure that no borrow is
1484 necessary. */
1485 assert(!carry);
Duncan Sandsa41634e2011-08-12 14:54:45 +00001486 (void)carry;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001487 } else {
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001488 if (bits > 0) {
Tim Shen85de51d2016-10-25 19:55:59 +00001489 IEEEFloat temp_rhs(rhs);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001490
1491 lost_fraction = temp_rhs.shiftSignificandRight(bits);
1492 carry = addSignificand(temp_rhs);
1493 } else {
1494 lost_fraction = shiftSignificandRight(-bits);
1495 carry = addSignificand(rhs);
1496 }
1497
1498 /* We have a guard bit; generating a carry cannot happen. */
1499 assert(!carry);
Duncan Sandsa41634e2011-08-12 14:54:45 +00001500 (void)carry;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001501 }
1502
1503 return lost_fraction;
1504}
1505
Tim Shen85de51d2016-10-25 19:55:59 +00001506IEEEFloat::opStatus IEEEFloat::multiplySpecials(const IEEEFloat &rhs) {
Michael Gottesman9b877e12013-06-24 09:57:57 +00001507 switch (PackCategoriesIntoKey(category, rhs.category)) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001508 default:
Craig Topper2617dcc2014-04-15 06:32:26 +00001509 llvm_unreachable(nullptr);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001510
Michael Gottesman9b877e12013-06-24 09:57:57 +00001511 case PackCategoriesIntoKey(fcNaN, fcZero):
1512 case PackCategoriesIntoKey(fcNaN, fcNormal):
1513 case PackCategoriesIntoKey(fcNaN, fcInfinity):
1514 case PackCategoriesIntoKey(fcNaN, fcNaN):
Michael Gottesmanb0e688e2013-07-27 21:49:25 +00001515 sign = false;
Dale Johannesen3cf889f2007-08-31 04:03:46 +00001516 return opOK;
1517
Michael Gottesman9b877e12013-06-24 09:57:57 +00001518 case PackCategoriesIntoKey(fcZero, fcNaN):
1519 case PackCategoriesIntoKey(fcNormal, fcNaN):
1520 case PackCategoriesIntoKey(fcInfinity, fcNaN):
Michael Gottesmanb0e688e2013-07-27 21:49:25 +00001521 sign = false;
Dale Johannesen3cf889f2007-08-31 04:03:46 +00001522 category = fcNaN;
1523 copySignificand(rhs);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001524 return opOK;
1525
Michael Gottesman9b877e12013-06-24 09:57:57 +00001526 case PackCategoriesIntoKey(fcNormal, fcInfinity):
1527 case PackCategoriesIntoKey(fcInfinity, fcNormal):
1528 case PackCategoriesIntoKey(fcInfinity, fcInfinity):
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001529 category = fcInfinity;
1530 return opOK;
1531
Michael Gottesman9b877e12013-06-24 09:57:57 +00001532 case PackCategoriesIntoKey(fcZero, fcNormal):
1533 case PackCategoriesIntoKey(fcNormal, fcZero):
1534 case PackCategoriesIntoKey(fcZero, fcZero):
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001535 category = fcZero;
1536 return opOK;
1537
Michael Gottesman9b877e12013-06-24 09:57:57 +00001538 case PackCategoriesIntoKey(fcZero, fcInfinity):
1539 case PackCategoriesIntoKey(fcInfinity, fcZero):
Neil Booth5fe658b2007-10-14 10:39:51 +00001540 makeNaN();
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001541 return opInvalidOp;
1542
Michael Gottesman9b877e12013-06-24 09:57:57 +00001543 case PackCategoriesIntoKey(fcNormal, fcNormal):
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001544 return opOK;
1545 }
1546}
1547
Tim Shen85de51d2016-10-25 19:55:59 +00001548IEEEFloat::opStatus IEEEFloat::divideSpecials(const IEEEFloat &rhs) {
Michael Gottesman9b877e12013-06-24 09:57:57 +00001549 switch (PackCategoriesIntoKey(category, rhs.category)) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001550 default:
Craig Topper2617dcc2014-04-15 06:32:26 +00001551 llvm_unreachable(nullptr);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001552
Michael Gottesman9b877e12013-06-24 09:57:57 +00001553 case PackCategoriesIntoKey(fcZero, fcNaN):
1554 case PackCategoriesIntoKey(fcNormal, fcNaN):
1555 case PackCategoriesIntoKey(fcInfinity, fcNaN):
Dale Johannesen3cf889f2007-08-31 04:03:46 +00001556 category = fcNaN;
1557 copySignificand(rhs);
Michael Gottesmanb0e688e2013-07-27 21:49:25 +00001558 case PackCategoriesIntoKey(fcNaN, fcZero):
1559 case PackCategoriesIntoKey(fcNaN, fcNormal):
1560 case PackCategoriesIntoKey(fcNaN, fcInfinity):
1561 case PackCategoriesIntoKey(fcNaN, fcNaN):
1562 sign = false;
1563 case PackCategoriesIntoKey(fcInfinity, fcZero):
1564 case PackCategoriesIntoKey(fcInfinity, fcNormal):
1565 case PackCategoriesIntoKey(fcZero, fcInfinity):
1566 case PackCategoriesIntoKey(fcZero, fcNormal):
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001567 return opOK;
1568
Michael Gottesman9b877e12013-06-24 09:57:57 +00001569 case PackCategoriesIntoKey(fcNormal, fcInfinity):
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001570 category = fcZero;
1571 return opOK;
1572
Michael Gottesman9b877e12013-06-24 09:57:57 +00001573 case PackCategoriesIntoKey(fcNormal, fcZero):
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001574 category = fcInfinity;
1575 return opDivByZero;
1576
Michael Gottesman9b877e12013-06-24 09:57:57 +00001577 case PackCategoriesIntoKey(fcInfinity, fcInfinity):
1578 case PackCategoriesIntoKey(fcZero, fcZero):
Neil Booth5fe658b2007-10-14 10:39:51 +00001579 makeNaN();
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001580 return opInvalidOp;
1581
Michael Gottesman9b877e12013-06-24 09:57:57 +00001582 case PackCategoriesIntoKey(fcNormal, fcNormal):
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001583 return opOK;
1584 }
1585}
1586
Tim Shen85de51d2016-10-25 19:55:59 +00001587IEEEFloat::opStatus IEEEFloat::modSpecials(const IEEEFloat &rhs) {
Michael Gottesman9b877e12013-06-24 09:57:57 +00001588 switch (PackCategoriesIntoKey(category, rhs.category)) {
Dale Johannesenb5721632009-01-21 00:35:19 +00001589 default:
Craig Topper2617dcc2014-04-15 06:32:26 +00001590 llvm_unreachable(nullptr);
Dale Johannesenb5721632009-01-21 00:35:19 +00001591
Michael Gottesman9b877e12013-06-24 09:57:57 +00001592 case PackCategoriesIntoKey(fcNaN, fcZero):
1593 case PackCategoriesIntoKey(fcNaN, fcNormal):
1594 case PackCategoriesIntoKey(fcNaN, fcInfinity):
1595 case PackCategoriesIntoKey(fcNaN, fcNaN):
1596 case PackCategoriesIntoKey(fcZero, fcInfinity):
1597 case PackCategoriesIntoKey(fcZero, fcNormal):
1598 case PackCategoriesIntoKey(fcNormal, fcInfinity):
Dale Johannesenb5721632009-01-21 00:35:19 +00001599 return opOK;
1600
Michael Gottesman9b877e12013-06-24 09:57:57 +00001601 case PackCategoriesIntoKey(fcZero, fcNaN):
1602 case PackCategoriesIntoKey(fcNormal, fcNaN):
1603 case PackCategoriesIntoKey(fcInfinity, fcNaN):
Michael Gottesmanb0e688e2013-07-27 21:49:25 +00001604 sign = false;
Dale Johannesenb5721632009-01-21 00:35:19 +00001605 category = fcNaN;
1606 copySignificand(rhs);
1607 return opOK;
1608
Michael Gottesman9b877e12013-06-24 09:57:57 +00001609 case PackCategoriesIntoKey(fcNormal, fcZero):
1610 case PackCategoriesIntoKey(fcInfinity, fcZero):
1611 case PackCategoriesIntoKey(fcInfinity, fcNormal):
1612 case PackCategoriesIntoKey(fcInfinity, fcInfinity):
1613 case PackCategoriesIntoKey(fcZero, fcZero):
Dale Johannesenb5721632009-01-21 00:35:19 +00001614 makeNaN();
1615 return opInvalidOp;
1616
Michael Gottesman9b877e12013-06-24 09:57:57 +00001617 case PackCategoriesIntoKey(fcNormal, fcNormal):
Dale Johannesenb5721632009-01-21 00:35:19 +00001618 return opOK;
1619 }
1620}
1621
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001622/* Change sign. */
Tim Shen85de51d2016-10-25 19:55:59 +00001623void IEEEFloat::changeSign() {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001624 /* Look mummy, this one's easy. */
1625 sign = !sign;
1626}
1627
1628/* Normalized addition or subtraction. */
Tim Shen85de51d2016-10-25 19:55:59 +00001629IEEEFloat::opStatus IEEEFloat::addOrSubtract(const IEEEFloat &rhs,
1630 roundingMode rounding_mode,
1631 bool subtract) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001632 opStatus fs;
1633
1634 fs = addOrSubtractSpecials(rhs, subtract);
1635
1636 /* This return code means it was not a simple case. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001637 if (fs == opDivByZero) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001638 lostFraction lost_fraction;
1639
1640 lost_fraction = addOrSubtractSignificand(rhs, subtract);
1641 fs = normalize(rounding_mode, lost_fraction);
1642
1643 /* Can only be zero if we lost no fraction. */
1644 assert(category != fcZero || lost_fraction == lfExactlyZero);
1645 }
1646
1647 /* If two numbers add (exactly) to zero, IEEE 754 decrees it is a
1648 positive zero unless rounding to minus infinity, except that
1649 adding two like-signed zeroes gives that zero. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001650 if (category == fcZero) {
1651 if (rhs.category != fcZero || (sign == rhs.sign) == subtract)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001652 sign = (rounding_mode == rmTowardNegative);
1653 }
1654
1655 return fs;
1656}
1657
1658/* Normalized addition. */
Tim Shen85de51d2016-10-25 19:55:59 +00001659IEEEFloat::opStatus IEEEFloat::add(const IEEEFloat &rhs,
1660 roundingMode rounding_mode) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001661 return addOrSubtract(rhs, rounding_mode, false);
1662}
1663
1664/* Normalized subtraction. */
Tim Shen85de51d2016-10-25 19:55:59 +00001665IEEEFloat::opStatus IEEEFloat::subtract(const IEEEFloat &rhs,
1666 roundingMode rounding_mode) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001667 return addOrSubtract(rhs, rounding_mode, true);
1668}
1669
1670/* Normalized multiply. */
Tim Shen85de51d2016-10-25 19:55:59 +00001671IEEEFloat::opStatus IEEEFloat::multiply(const IEEEFloat &rhs,
1672 roundingMode rounding_mode) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001673 opStatus fs;
1674
1675 sign ^= rhs.sign;
1676 fs = multiplySpecials(rhs);
1677
Michael Gottesman8136c382013-06-26 23:17:28 +00001678 if (isFiniteNonZero()) {
Craig Topperc10719f2014-04-07 04:17:22 +00001679 lostFraction lost_fraction = multiplySignificand(rhs, nullptr);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001680 fs = normalize(rounding_mode, lost_fraction);
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001681 if (lost_fraction != lfExactlyZero)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001682 fs = (opStatus) (fs | opInexact);
1683 }
1684
1685 return fs;
1686}
1687
1688/* Normalized divide. */
Tim Shen85de51d2016-10-25 19:55:59 +00001689IEEEFloat::opStatus IEEEFloat::divide(const IEEEFloat &rhs,
1690 roundingMode rounding_mode) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001691 opStatus fs;
1692
1693 sign ^= rhs.sign;
1694 fs = divideSpecials(rhs);
1695
Michael Gottesman8136c382013-06-26 23:17:28 +00001696 if (isFiniteNonZero()) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001697 lostFraction lost_fraction = divideSignificand(rhs);
1698 fs = normalize(rounding_mode, lost_fraction);
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001699 if (lost_fraction != lfExactlyZero)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001700 fs = (opStatus) (fs | opInexact);
1701 }
1702
1703 return fs;
1704}
1705
Dale Johannesenfe750172009-01-20 18:35:05 +00001706/* Normalized remainder. This is not currently correct in all cases. */
Tim Shen85de51d2016-10-25 19:55:59 +00001707IEEEFloat::opStatus IEEEFloat::remainder(const IEEEFloat &rhs) {
Dale Johannesenfe750172009-01-20 18:35:05 +00001708 opStatus fs;
Tim Shen85de51d2016-10-25 19:55:59 +00001709 IEEEFloat V = *this;
Dale Johannesenfe750172009-01-20 18:35:05 +00001710 unsigned int origSign = sign;
1711
Dale Johannesenfe750172009-01-20 18:35:05 +00001712 fs = V.divide(rhs, rmNearestTiesToEven);
1713 if (fs == opDivByZero)
1714 return fs;
1715
1716 int parts = partCount();
Dylan Noblesmith4e69e292014-08-26 02:03:33 +00001717 integerPart *x = new integerPart[parts];
Dale Johannesenfe750172009-01-20 18:35:05 +00001718 bool ignored;
1719 fs = V.convertToInteger(x, parts * integerPartWidth, true,
1720 rmNearestTiesToEven, &ignored);
Sylvestre Ledru3ce346d2016-11-08 10:00:45 +00001721 if (fs==opInvalidOp) {
1722 delete[] x;
Dale Johannesenfe750172009-01-20 18:35:05 +00001723 return fs;
Sylvestre Ledru3ce346d2016-11-08 10:00:45 +00001724 }
Dale Johannesenfe750172009-01-20 18:35:05 +00001725
1726 fs = V.convertFromZeroExtendedInteger(x, parts * integerPartWidth, true,
1727 rmNearestTiesToEven);
1728 assert(fs==opOK); // should always work
1729
1730 fs = V.multiply(rhs, rmNearestTiesToEven);
1731 assert(fs==opOK || fs==opInexact); // should not overflow or underflow
1732
1733 fs = subtract(V, rmNearestTiesToEven);
1734 assert(fs==opOK || fs==opInexact); // likewise
1735
1736 if (isZero())
1737 sign = origSign; // IEEE754 requires this
Dylan Noblesmith4e69e292014-08-26 02:03:33 +00001738 delete[] x;
Dale Johannesenfe750172009-01-20 18:35:05 +00001739 return fs;
1740}
1741
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001742/* Normalized llvm frem (C fmod).
Dale Johannesenfe750172009-01-20 18:35:05 +00001743 This is not currently correct in all cases. */
Tim Shen85de51d2016-10-25 19:55:59 +00001744IEEEFloat::opStatus IEEEFloat::mod(const IEEEFloat &rhs) {
Dale Johannesen689d17d2007-08-31 23:35:31 +00001745 opStatus fs;
Dale Johannesenb5721632009-01-21 00:35:19 +00001746 fs = modSpecials(rhs);
Dale Johannesen689d17d2007-08-31 23:35:31 +00001747
Michael Gottesman8136c382013-06-26 23:17:28 +00001748 if (isFiniteNonZero() && rhs.isFiniteNonZero()) {
Tim Shen85de51d2016-10-25 19:55:59 +00001749 IEEEFloat V = *this;
Dale Johannesenb5721632009-01-21 00:35:19 +00001750 unsigned int origSign = sign;
Dale Johannesen689d17d2007-08-31 23:35:31 +00001751
Dale Johannesenb5721632009-01-21 00:35:19 +00001752 fs = V.divide(rhs, rmNearestTiesToEven);
1753 if (fs == opDivByZero)
1754 return fs;
Dale Johannesen728687c2007-09-05 20:39:49 +00001755
Dale Johannesenb5721632009-01-21 00:35:19 +00001756 int parts = partCount();
Dylan Noblesmith4e69e292014-08-26 02:03:33 +00001757 integerPart *x = new integerPart[parts];
Dale Johannesenb5721632009-01-21 00:35:19 +00001758 bool ignored;
1759 fs = V.convertToInteger(x, parts * integerPartWidth, true,
1760 rmTowardZero, &ignored);
Sylvestre Ledru3ce346d2016-11-08 10:00:45 +00001761 if (fs==opInvalidOp) {
1762 delete[] x;
Dale Johannesenb5721632009-01-21 00:35:19 +00001763 return fs;
Sylvestre Ledru3ce346d2016-11-08 10:00:45 +00001764 }
Dale Johannesen728687c2007-09-05 20:39:49 +00001765
Dale Johannesenb5721632009-01-21 00:35:19 +00001766 fs = V.convertFromZeroExtendedInteger(x, parts * integerPartWidth, true,
1767 rmNearestTiesToEven);
1768 assert(fs==opOK); // should always work
Dale Johannesen728687c2007-09-05 20:39:49 +00001769
Stephen Canonb12db0e2015-09-21 19:29:25 +00001770 fs = V.multiply(rhs, rmNearestTiesToEven);
Dale Johannesenb5721632009-01-21 00:35:19 +00001771 assert(fs==opOK || fs==opInexact); // should not overflow or underflow
1772
Stephen Canonb12db0e2015-09-21 19:29:25 +00001773 fs = subtract(V, rmNearestTiesToEven);
Dale Johannesenb5721632009-01-21 00:35:19 +00001774 assert(fs==opOK || fs==opInexact); // likewise
1775
1776 if (isZero())
1777 sign = origSign; // IEEE754 requires this
Dylan Noblesmith4e69e292014-08-26 02:03:33 +00001778 delete[] x;
Dale Johannesenb5721632009-01-21 00:35:19 +00001779 }
Dale Johannesen689d17d2007-08-31 23:35:31 +00001780 return fs;
1781}
1782
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001783/* Normalized fused-multiply-add. */
Tim Shen85de51d2016-10-25 19:55:59 +00001784IEEEFloat::opStatus IEEEFloat::fusedMultiplyAdd(const IEEEFloat &multiplicand,
1785 const IEEEFloat &addend,
1786 roundingMode rounding_mode) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001787 opStatus fs;
1788
1789 /* Post-multiplication sign, before addition. */
1790 sign ^= multiplicand.sign;
1791
1792 /* If and only if all arguments are normal do we need to do an
1793 extended-precision calculation. */
Michael Gottesman8136c382013-06-26 23:17:28 +00001794 if (isFiniteNonZero() &&
1795 multiplicand.isFiniteNonZero() &&
Hal Finkel171c2ec2014-10-14 19:23:07 +00001796 addend.isFinite()) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001797 lostFraction lost_fraction;
1798
1799 lost_fraction = multiplySignificand(multiplicand, &addend);
1800 fs = normalize(rounding_mode, lost_fraction);
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001801 if (lost_fraction != lfExactlyZero)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001802 fs = (opStatus) (fs | opInexact);
1803
1804 /* If two numbers add (exactly) to zero, IEEE 754 decrees it is a
1805 positive zero unless rounding to minus infinity, except that
1806 adding two like-signed zeroes gives that zero. */
Lang Hames12b12e82015-01-04 01:20:55 +00001807 if (category == fcZero && !(fs & opUnderflow) && sign != addend.sign)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001808 sign = (rounding_mode == rmTowardNegative);
1809 } else {
1810 fs = multiplySpecials(multiplicand);
1811
1812 /* FS can only be opOK or opInvalidOp. There is no more work
1813 to do in the latter case. The IEEE-754R standard says it is
1814 implementation-defined in this case whether, if ADDEND is a
Dale Johannesen3cf889f2007-08-31 04:03:46 +00001815 quiet NaN, we raise invalid op; this implementation does so.
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001816
1817 If we need to do the addition we can do so with normal
1818 precision. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001819 if (fs == opOK)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001820 fs = addOrSubtract(addend, rounding_mode, false);
1821 }
1822
1823 return fs;
1824}
1825
Owen Andersona40319b2012-08-13 23:32:49 +00001826/* Rounding-mode corrrect round to integral value. */
Tim Shen85de51d2016-10-25 19:55:59 +00001827IEEEFloat::opStatus IEEEFloat::roundToIntegral(roundingMode rounding_mode) {
Owen Andersona40319b2012-08-13 23:32:49 +00001828 opStatus fs;
Owen Andersona40319b2012-08-13 23:32:49 +00001829
Owen Anderson352dfff2012-08-15 18:28:45 +00001830 // If the exponent is large enough, we know that this value is already
1831 // integral, and the arithmetic below would potentially cause it to saturate
1832 // to +/-Inf. Bail out early instead.
Michael Gottesman8136c382013-06-26 23:17:28 +00001833 if (isFiniteNonZero() && exponent+1 >= (int)semanticsPrecision(*semantics))
Owen Anderson352dfff2012-08-15 18:28:45 +00001834 return opOK;
1835
Owen Andersona40319b2012-08-13 23:32:49 +00001836 // The algorithm here is quite simple: we add 2^(p-1), where p is the
1837 // precision of our format, and then subtract it back off again. The choice
1838 // of rounding modes for the addition/subtraction determines the rounding mode
1839 // for our integral rounding as well.
Owen Andersonbe7e2972012-08-15 16:42:53 +00001840 // NOTE: When the input value is negative, we do subtraction followed by
Owen Anderson1ff74b02012-08-15 05:39:46 +00001841 // addition instead.
Owen Anderson0b357222012-08-14 18:51:15 +00001842 APInt IntegerConstant(NextPowerOf2(semanticsPrecision(*semantics)), 1);
1843 IntegerConstant <<= semanticsPrecision(*semantics)-1;
Tim Shen85de51d2016-10-25 19:55:59 +00001844 IEEEFloat MagicConstant(*semantics);
Owen Andersona40319b2012-08-13 23:32:49 +00001845 fs = MagicConstant.convertFromAPInt(IntegerConstant, false,
1846 rmNearestTiesToEven);
Tim Shenfd1e5aa2017-01-23 22:39:35 +00001847 MagicConstant.sign = sign;
Owen Anderson1ff74b02012-08-15 05:39:46 +00001848
Owen Andersona40319b2012-08-13 23:32:49 +00001849 if (fs != opOK)
1850 return fs;
1851
Owen Anderson1ff74b02012-08-15 05:39:46 +00001852 // Preserve the input sign so that we can handle 0.0/-0.0 cases correctly.
1853 bool inputSign = isNegative();
1854
Owen Andersona40319b2012-08-13 23:32:49 +00001855 fs = add(MagicConstant, rounding_mode);
1856 if (fs != opOK && fs != opInexact)
1857 return fs;
1858
1859 fs = subtract(MagicConstant, rounding_mode);
Owen Anderson1ff74b02012-08-15 05:39:46 +00001860
1861 // Restore the input sign.
1862 if (inputSign != isNegative())
1863 changeSign();
1864
Owen Andersona40319b2012-08-13 23:32:49 +00001865 return fs;
1866}
1867
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +00001868
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001869/* Comparison requires normalized numbers. */
Tim Shen85de51d2016-10-25 19:55:59 +00001870IEEEFloat::cmpResult IEEEFloat::compare(const IEEEFloat &rhs) const {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001871 cmpResult result;
1872
1873 assert(semantics == rhs.semantics);
1874
Michael Gottesman9b877e12013-06-24 09:57:57 +00001875 switch (PackCategoriesIntoKey(category, rhs.category)) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001876 default:
Craig Topper2617dcc2014-04-15 06:32:26 +00001877 llvm_unreachable(nullptr);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001878
Michael Gottesman9b877e12013-06-24 09:57:57 +00001879 case PackCategoriesIntoKey(fcNaN, fcZero):
1880 case PackCategoriesIntoKey(fcNaN, fcNormal):
1881 case PackCategoriesIntoKey(fcNaN, fcInfinity):
1882 case PackCategoriesIntoKey(fcNaN, fcNaN):
1883 case PackCategoriesIntoKey(fcZero, fcNaN):
1884 case PackCategoriesIntoKey(fcNormal, fcNaN):
1885 case PackCategoriesIntoKey(fcInfinity, fcNaN):
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001886 return cmpUnordered;
1887
Michael Gottesman9b877e12013-06-24 09:57:57 +00001888 case PackCategoriesIntoKey(fcInfinity, fcNormal):
1889 case PackCategoriesIntoKey(fcInfinity, fcZero):
1890 case PackCategoriesIntoKey(fcNormal, fcZero):
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001891 if (sign)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001892 return cmpLessThan;
1893 else
1894 return cmpGreaterThan;
1895
Michael Gottesman9b877e12013-06-24 09:57:57 +00001896 case PackCategoriesIntoKey(fcNormal, fcInfinity):
1897 case PackCategoriesIntoKey(fcZero, fcInfinity):
1898 case PackCategoriesIntoKey(fcZero, fcNormal):
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001899 if (rhs.sign)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001900 return cmpGreaterThan;
1901 else
1902 return cmpLessThan;
1903
Michael Gottesman9b877e12013-06-24 09:57:57 +00001904 case PackCategoriesIntoKey(fcInfinity, fcInfinity):
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001905 if (sign == rhs.sign)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001906 return cmpEqual;
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001907 else if (sign)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001908 return cmpLessThan;
1909 else
1910 return cmpGreaterThan;
1911
Michael Gottesman9b877e12013-06-24 09:57:57 +00001912 case PackCategoriesIntoKey(fcZero, fcZero):
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001913 return cmpEqual;
1914
Michael Gottesman9b877e12013-06-24 09:57:57 +00001915 case PackCategoriesIntoKey(fcNormal, fcNormal):
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001916 break;
1917 }
1918
1919 /* Two normal numbers. Do they have the same sign? */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001920 if (sign != rhs.sign) {
1921 if (sign)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001922 result = cmpLessThan;
1923 else
1924 result = cmpGreaterThan;
1925 } else {
1926 /* Compare absolute values; invert result if negative. */
1927 result = compareAbsoluteValue(rhs);
1928
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001929 if (sign) {
1930 if (result == cmpLessThan)
Neil Booth9acbf5a2007-09-26 21:33:42 +00001931 result = cmpGreaterThan;
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001932 else if (result == cmpGreaterThan)
Neil Booth9acbf5a2007-09-26 21:33:42 +00001933 result = cmpLessThan;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001934 }
1935 }
1936
1937 return result;
1938}
1939
Tim Shen85de51d2016-10-25 19:55:59 +00001940/// IEEEFloat::convert - convert a value of one floating point type to another.
Dale Johannesen4f0bd682008-10-09 23:00:39 +00001941/// The return value corresponds to the IEEE754 exceptions. *losesInfo
1942/// records whether the transformation lost information, i.e. whether
1943/// converting the result back to the original type will produce the
1944/// original value (this is almost the same as return value==fsOK, but there
1945/// are edge cases where this is not so).
1946
Tim Shen85de51d2016-10-25 19:55:59 +00001947IEEEFloat::opStatus IEEEFloat::convert(const fltSemantics &toSemantics,
1948 roundingMode rounding_mode,
1949 bool *losesInfo) {
Neil Bootha8d72692007-09-22 02:56:19 +00001950 lostFraction lostFraction;
1951 unsigned int newPartCount, oldPartCount;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001952 opStatus fs;
Eli Friedmana84ad7d2011-11-26 03:38:02 +00001953 int shift;
1954 const fltSemantics &fromSemantics = *semantics;
Neil Booth9acbf5a2007-09-26 21:33:42 +00001955
Neil Bootha8d72692007-09-22 02:56:19 +00001956 lostFraction = lfExactlyZero;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001957 newPartCount = partCountForBits(toSemantics.precision + 1);
Neil Bootha8d72692007-09-22 02:56:19 +00001958 oldPartCount = partCount();
Eli Friedmana84ad7d2011-11-26 03:38:02 +00001959 shift = toSemantics.precision - fromSemantics.precision;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001960
Eli Friedmana84ad7d2011-11-26 03:38:02 +00001961 bool X86SpecialNan = false;
Stephan Bergmann17c7f702016-12-14 11:57:17 +00001962 if (&fromSemantics == &semX87DoubleExtended &&
1963 &toSemantics != &semX87DoubleExtended && category == fcNaN &&
Eli Friedmana84ad7d2011-11-26 03:38:02 +00001964 (!(*significandParts() & 0x8000000000000000ULL) ||
1965 !(*significandParts() & 0x4000000000000000ULL))) {
1966 // x86 has some unusual NaNs which cannot be represented in any other
1967 // format; note them here.
1968 X86SpecialNan = true;
1969 }
1970
Ulrich Weigand1d4dbda2013-07-16 13:03:25 +00001971 // If this is a truncation of a denormal number, and the target semantics
1972 // has larger exponent range than the source semantics (this can happen
1973 // when truncating from PowerPC double-double to double format), the
1974 // right shift could lose result mantissa bits. Adjust exponent instead
1975 // of performing excessive shift.
1976 if (shift < 0 && isFiniteNonZero()) {
1977 int exponentChange = significandMSB() + 1 - fromSemantics.precision;
1978 if (exponent + exponentChange < toSemantics.minExponent)
1979 exponentChange = toSemantics.minExponent - exponent;
1980 if (exponentChange < shift)
1981 exponentChange = shift;
1982 if (exponentChange < 0) {
1983 shift -= exponentChange;
1984 exponent += exponentChange;
1985 }
1986 }
1987
Eli Friedmana84ad7d2011-11-26 03:38:02 +00001988 // If this is a truncation, perform the shift before we narrow the storage.
Michael Gottesman8136c382013-06-26 23:17:28 +00001989 if (shift < 0 && (isFiniteNonZero() || category==fcNaN))
Eli Friedmana84ad7d2011-11-26 03:38:02 +00001990 lostFraction = shiftRight(significandParts(), oldPartCount, -shift);
1991
1992 // Fix the storage so it can hold to new value.
Neil Bootha8d72692007-09-22 02:56:19 +00001993 if (newPartCount > oldPartCount) {
Eli Friedmana84ad7d2011-11-26 03:38:02 +00001994 // The new type requires more storage; make it available.
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001995 integerPart *newParts;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001996 newParts = new integerPart[newPartCount];
1997 APInt::tcSet(newParts, 0, newPartCount);
Michael Gottesman8136c382013-06-26 23:17:28 +00001998 if (isFiniteNonZero() || category==fcNaN)
Dale Johannesen4f55d9f2007-09-25 17:25:00 +00001999 APInt::tcAssign(newParts, significandParts(), oldPartCount);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002000 freeSignificand();
2001 significand.parts = newParts;
Eli Friedmana84ad7d2011-11-26 03:38:02 +00002002 } else if (newPartCount == 1 && oldPartCount != 1) {
2003 // Switch to built-in storage for a single part.
2004 integerPart newPart = 0;
Michael Gottesman8136c382013-06-26 23:17:28 +00002005 if (isFiniteNonZero() || category==fcNaN)
Eli Friedmana84ad7d2011-11-26 03:38:02 +00002006 newPart = significandParts()[0];
2007 freeSignificand();
2008 significand.part = newPart;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002009 }
2010
Eli Friedmana84ad7d2011-11-26 03:38:02 +00002011 // Now that we have the right storage, switch the semantics.
2012 semantics = &toSemantics;
2013
2014 // If this is an extension, perform the shift now that the storage is
2015 // available.
Michael Gottesman8136c382013-06-26 23:17:28 +00002016 if (shift > 0 && (isFiniteNonZero() || category==fcNaN))
Eli Friedmana84ad7d2011-11-26 03:38:02 +00002017 APInt::tcShiftLeft(significandParts(), newPartCount, shift);
2018
Michael Gottesman8136c382013-06-26 23:17:28 +00002019 if (isFiniteNonZero()) {
Neil Bootha8d72692007-09-22 02:56:19 +00002020 fs = normalize(rounding_mode, lostFraction);
Dale Johannesen4f0bd682008-10-09 23:00:39 +00002021 *losesInfo = (fs != opOK);
Dale Johannesen4f55d9f2007-09-25 17:25:00 +00002022 } else if (category == fcNaN) {
Eli Friedmana84ad7d2011-11-26 03:38:02 +00002023 *losesInfo = lostFraction != lfExactlyZero || X86SpecialNan;
Benjamin Kramerb361adb2013-01-25 17:01:00 +00002024
2025 // For x87 extended precision, we want to make a NaN, not a special NaN if
2026 // the input wasn't special either.
Stephan Bergmann17c7f702016-12-14 11:57:17 +00002027 if (!X86SpecialNan && semantics == &semX87DoubleExtended)
Benjamin Kramerb361adb2013-01-25 17:01:00 +00002028 APInt::tcSetBit(significandParts(), semantics->precision - 1);
2029
Dale Johannesen4f55d9f2007-09-25 17:25:00 +00002030 // gcc forces the Quiet bit on, which means (float)(double)(float_sNan)
2031 // does not give you back the same bits. This is dubious, and we
2032 // don't currently do it. You're really supposed to get
2033 // an invalid operation signal at runtime, but nobody does that.
Dale Johannesen4f0bd682008-10-09 23:00:39 +00002034 fs = opOK;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002035 } else {
Dale Johannesen4f0bd682008-10-09 23:00:39 +00002036 *losesInfo = false;
Eli Friedman31f01162011-11-28 18:50:37 +00002037 fs = opOK;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002038 }
2039
2040 return fs;
2041}
2042
2043/* Convert a floating point number to an integer according to the
2044 rounding mode. If the rounded integer value is out of range this
Neil Booth618d0fc2007-11-01 22:43:37 +00002045 returns an invalid operation exception and the contents of the
2046 destination parts are unspecified. If the rounded value is in
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002047 range but the floating point number is not the exact integer, the C
2048 standard doesn't require an inexact exception to be raised. IEEE
2049 854 does require it so we do that.
2050
2051 Note that for conversions to integer type the C standard requires
2052 round-to-zero to always be used. */
Tim Shen85de51d2016-10-25 19:55:59 +00002053IEEEFloat::opStatus IEEEFloat::convertToSignExtendedInteger(
2054 integerPart *parts, unsigned int width, bool isSigned,
2055 roundingMode rounding_mode, bool *isExact) const {
Neil Booth618d0fc2007-11-01 22:43:37 +00002056 lostFraction lost_fraction;
2057 const integerPart *src;
2058 unsigned int dstPartsCount, truncatedBits;
2059
Dale Johannesen4f0bd682008-10-09 23:00:39 +00002060 *isExact = false;
2061
Neil Booth618d0fc2007-11-01 22:43:37 +00002062 /* Handle the three special cases first. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002063 if (category == fcInfinity || category == fcNaN)
Neil Booth618d0fc2007-11-01 22:43:37 +00002064 return opInvalidOp;
2065
2066 dstPartsCount = partCountForBits(width);
2067
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002068 if (category == fcZero) {
Neil Booth618d0fc2007-11-01 22:43:37 +00002069 APInt::tcSet(parts, 0, dstPartsCount);
Dale Johannesen7221af32008-10-07 00:40:01 +00002070 // Negative zero can't be represented as an int.
Dale Johannesen4f0bd682008-10-09 23:00:39 +00002071 *isExact = !sign;
2072 return opOK;
Neil Booth618d0fc2007-11-01 22:43:37 +00002073 }
2074
2075 src = significandParts();
2076
2077 /* Step 1: place our absolute value, with any fraction truncated, in
2078 the destination. */
2079 if (exponent < 0) {
2080 /* Our absolute value is less than one; truncate everything. */
2081 APInt::tcSet(parts, 0, dstPartsCount);
Dale Johannesen740e9872009-01-19 21:17:05 +00002082 /* For exponent -1 the integer bit represents .5, look at that.
2083 For smaller exponents leftmost truncated bit is 0. */
2084 truncatedBits = semantics->precision -1U - exponent;
Neil Booth618d0fc2007-11-01 22:43:37 +00002085 } else {
2086 /* We want the most significant (exponent + 1) bits; the rest are
2087 truncated. */
2088 unsigned int bits = exponent + 1U;
2089
2090 /* Hopelessly large in magnitude? */
2091 if (bits > width)
2092 return opInvalidOp;
2093
2094 if (bits < semantics->precision) {
2095 /* We truncate (semantics->precision - bits) bits. */
2096 truncatedBits = semantics->precision - bits;
2097 APInt::tcExtract(parts, dstPartsCount, src, bits, truncatedBits);
2098 } else {
2099 /* We want at least as many bits as are available. */
2100 APInt::tcExtract(parts, dstPartsCount, src, semantics->precision, 0);
2101 APInt::tcShiftLeft(parts, dstPartsCount, bits - semantics->precision);
2102 truncatedBits = 0;
2103 }
2104 }
2105
2106 /* Step 2: work out any lost fraction, and increment the absolute
2107 value if we would round away from zero. */
2108 if (truncatedBits) {
2109 lost_fraction = lostFractionThroughTruncation(src, partCount(),
2110 truncatedBits);
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002111 if (lost_fraction != lfExactlyZero &&
2112 roundAwayFromZero(rounding_mode, lost_fraction, truncatedBits)) {
Neil Booth618d0fc2007-11-01 22:43:37 +00002113 if (APInt::tcIncrement(parts, dstPartsCount))
2114 return opInvalidOp; /* Overflow. */
2115 }
2116 } else {
2117 lost_fraction = lfExactlyZero;
2118 }
2119
2120 /* Step 3: check if we fit in the destination. */
2121 unsigned int omsb = APInt::tcMSB(parts, dstPartsCount) + 1;
2122
2123 if (sign) {
2124 if (!isSigned) {
2125 /* Negative numbers cannot be represented as unsigned. */
2126 if (omsb != 0)
2127 return opInvalidOp;
2128 } else {
2129 /* It takes omsb bits to represent the unsigned integer value.
2130 We lose a bit for the sign, but care is needed as the
2131 maximally negative integer is a special case. */
2132 if (omsb == width && APInt::tcLSB(parts, dstPartsCount) + 1 != omsb)
2133 return opInvalidOp;
2134
2135 /* This case can happen because of rounding. */
2136 if (omsb > width)
2137 return opInvalidOp;
2138 }
2139
2140 APInt::tcNegate (parts, dstPartsCount);
2141 } else {
2142 if (omsb >= width + !isSigned)
2143 return opInvalidOp;
2144 }
2145
Dale Johannesen4f0bd682008-10-09 23:00:39 +00002146 if (lost_fraction == lfExactlyZero) {
2147 *isExact = true;
Neil Booth618d0fc2007-11-01 22:43:37 +00002148 return opOK;
Dale Johannesen4f0bd682008-10-09 23:00:39 +00002149 } else
Neil Booth618d0fc2007-11-01 22:43:37 +00002150 return opInexact;
2151}
2152
2153/* Same as convertToSignExtendedInteger, except we provide
2154 deterministic values in case of an invalid operation exception,
2155 namely zero for NaNs and the minimal or maximal value respectively
Dale Johannesen4f0bd682008-10-09 23:00:39 +00002156 for underflow or overflow.
2157 The *isExact output tells whether the result is exact, in the sense
2158 that converting it back to the original floating point type produces
2159 the original value. This is almost equivalent to result==opOK,
2160 except for negative zeroes.
2161*/
Tim Shen85de51d2016-10-25 19:55:59 +00002162IEEEFloat::opStatus IEEEFloat::convertToInteger(integerPart *parts,
2163 unsigned int width,
2164 bool isSigned,
2165 roundingMode rounding_mode,
2166 bool *isExact) const {
Neil Booth618d0fc2007-11-01 22:43:37 +00002167 opStatus fs;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002168
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002169 fs = convertToSignExtendedInteger(parts, width, isSigned, rounding_mode,
Dale Johannesen4f0bd682008-10-09 23:00:39 +00002170 isExact);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002171
Neil Booth618d0fc2007-11-01 22:43:37 +00002172 if (fs == opInvalidOp) {
2173 unsigned int bits, dstPartsCount;
2174
2175 dstPartsCount = partCountForBits(width);
2176
2177 if (category == fcNaN)
2178 bits = 0;
2179 else if (sign)
2180 bits = isSigned;
2181 else
2182 bits = width - isSigned;
2183
2184 APInt::tcSetLeastSignificantBits(parts, dstPartsCount, bits);
2185 if (sign && isSigned)
2186 APInt::tcShiftLeft(parts, dstPartsCount, width - 1);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002187 }
2188
Neil Booth618d0fc2007-11-01 22:43:37 +00002189 return fs;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002190}
2191
Neil Booth6c1c8582007-10-07 12:07:53 +00002192/* Convert an unsigned integer SRC to a floating point number,
2193 rounding according to ROUNDING_MODE. The sign of the floating
2194 point number is not modified. */
Tim Shen85de51d2016-10-25 19:55:59 +00002195IEEEFloat::opStatus IEEEFloat::convertFromUnsignedParts(
2196 const integerPart *src, unsigned int srcCount, roundingMode rounding_mode) {
Neil Booth49c6aab2007-10-08 14:39:42 +00002197 unsigned int omsb, precision, dstCount;
Neil Booth6c1c8582007-10-07 12:07:53 +00002198 integerPart *dst;
Neil Booth49c6aab2007-10-08 14:39:42 +00002199 lostFraction lost_fraction;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002200
2201 category = fcNormal;
Neil Booth49c6aab2007-10-08 14:39:42 +00002202 omsb = APInt::tcMSB(src, srcCount) + 1;
Neil Booth6c1c8582007-10-07 12:07:53 +00002203 dst = significandParts();
2204 dstCount = partCount();
Neil Booth49c6aab2007-10-08 14:39:42 +00002205 precision = semantics->precision;
Neil Booth6c1c8582007-10-07 12:07:53 +00002206
Nick Lewyckyf66daac2011-10-03 21:30:08 +00002207 /* We want the most significant PRECISION bits of SRC. There may not
Neil Booth49c6aab2007-10-08 14:39:42 +00002208 be that many; extract what we can. */
2209 if (precision <= omsb) {
2210 exponent = omsb - 1;
Neil Booth6c1c8582007-10-07 12:07:53 +00002211 lost_fraction = lostFractionThroughTruncation(src, srcCount,
Neil Booth49c6aab2007-10-08 14:39:42 +00002212 omsb - precision);
2213 APInt::tcExtract(dst, dstCount, src, precision, omsb - precision);
2214 } else {
2215 exponent = precision - 1;
2216 lost_fraction = lfExactlyZero;
2217 APInt::tcExtract(dst, dstCount, src, omsb, 0);
Neil Booth6c1c8582007-10-07 12:07:53 +00002218 }
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002219
2220 return normalize(rounding_mode, lost_fraction);
2221}
2222
Tim Shen85de51d2016-10-25 19:55:59 +00002223IEEEFloat::opStatus IEEEFloat::convertFromAPInt(const APInt &Val, bool isSigned,
2224 roundingMode rounding_mode) {
Dan Gohman35723eb2008-02-29 01:26:11 +00002225 unsigned int partCount = Val.getNumWords();
2226 APInt api = Val;
2227
2228 sign = false;
2229 if (isSigned && api.isNegative()) {
2230 sign = true;
2231 api = -api;
2232 }
2233
2234 return convertFromUnsignedParts(api.getRawData(), partCount, rounding_mode);
2235}
2236
Neil Booth03f58ab2007-10-07 12:15:41 +00002237/* Convert a two's complement integer SRC to a floating point number,
2238 rounding according to ROUNDING_MODE. ISSIGNED is true if the
2239 integer is signed, in which case it must be sign-extended. */
Tim Shen85de51d2016-10-25 19:55:59 +00002240IEEEFloat::opStatus
2241IEEEFloat::convertFromSignExtendedInteger(const integerPart *src,
2242 unsigned int srcCount, bool isSigned,
2243 roundingMode rounding_mode) {
Neil Booth03f58ab2007-10-07 12:15:41 +00002244 opStatus status;
2245
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002246 if (isSigned &&
2247 APInt::tcExtractBit(src, srcCount * integerPartWidth - 1)) {
Dylan Noblesmith4e69e292014-08-26 02:03:33 +00002248 integerPart *copy;
Neil Booth03f58ab2007-10-07 12:15:41 +00002249
2250 /* If we're signed and negative negate a copy. */
2251 sign = true;
Dylan Noblesmith4e69e292014-08-26 02:03:33 +00002252 copy = new integerPart[srcCount];
Neil Booth03f58ab2007-10-07 12:15:41 +00002253 APInt::tcAssign(copy, src, srcCount);
2254 APInt::tcNegate(copy, srcCount);
2255 status = convertFromUnsignedParts(copy, srcCount, rounding_mode);
Dylan Noblesmith4e69e292014-08-26 02:03:33 +00002256 delete [] copy;
Neil Booth03f58ab2007-10-07 12:15:41 +00002257 } else {
2258 sign = false;
2259 status = convertFromUnsignedParts(src, srcCount, rounding_mode);
2260 }
2261
2262 return status;
2263}
2264
Neil Booth5f009732007-10-07 11:45:55 +00002265/* FIXME: should this just take a const APInt reference? */
Tim Shen85de51d2016-10-25 19:55:59 +00002266IEEEFloat::opStatus
2267IEEEFloat::convertFromZeroExtendedInteger(const integerPart *parts,
2268 unsigned int width, bool isSigned,
2269 roundingMode rounding_mode) {
Dale Johannesen42305122007-09-21 22:09:37 +00002270 unsigned int partCount = partCountForBits(width);
Jeffrey Yasskin7a162882011-07-18 21:45:40 +00002271 APInt api = APInt(width, makeArrayRef(parts, partCount));
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002272
2273 sign = false;
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002274 if (isSigned && APInt::tcExtractBit(parts, width - 1)) {
Dale Johannesen28a2c4a2007-09-30 18:17:01 +00002275 sign = true;
2276 api = -api;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002277 }
2278
Neil Boothba205222007-10-07 12:10:57 +00002279 return convertFromUnsignedParts(api.getRawData(), partCount, rounding_mode);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002280}
2281
Tim Shen85de51d2016-10-25 19:55:59 +00002282IEEEFloat::opStatus
2283IEEEFloat::convertFromHexadecimalString(StringRef s,
2284 roundingMode rounding_mode) {
Erick Tryzelaara9680df2009-08-18 18:20:37 +00002285 lostFraction lost_fraction = lfExactlyZero;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002286
Michael Gottesman30a90eb2013-07-27 21:49:21 +00002287 category = fcNormal;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002288 zeroSignificand();
2289 exponent = 0;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002290
Eli Friedmand2eb07a2013-07-17 22:17:29 +00002291 integerPart *significand = significandParts();
2292 unsigned partsCount = partCount();
2293 unsigned bitPos = partsCount * integerPartWidth;
2294 bool computedTrailingFraction = false;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002295
Eli Friedmand2eb07a2013-07-17 22:17:29 +00002296 // Skip leading zeroes and any (hexa)decimal point.
Erick Tryzelaarda666c82009-08-20 23:30:43 +00002297 StringRef::iterator begin = s.begin();
2298 StringRef::iterator end = s.end();
Eli Friedmand2eb07a2013-07-17 22:17:29 +00002299 StringRef::iterator dot;
Erick Tryzelaarda666c82009-08-20 23:30:43 +00002300 StringRef::iterator p = skipLeadingZeroesAndAnyDot(begin, end, &dot);
Eli Friedmand2eb07a2013-07-17 22:17:29 +00002301 StringRef::iterator firstSignificantDigit = p;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002302
Eli Friedmand2eb07a2013-07-17 22:17:29 +00002303 while (p != end) {
Dale Johannesenfa483722008-05-14 22:53:25 +00002304 integerPart hex_value;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002305
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002306 if (*p == '.') {
Erick Tryzelaarda666c82009-08-20 23:30:43 +00002307 assert(dot == end && "String contains multiple dots");
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002308 dot = p++;
Eli Friedmand2eb07a2013-07-17 22:17:29 +00002309 continue;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002310 }
2311
2312 hex_value = hexDigitValue(*p);
Eli Friedmand2eb07a2013-07-17 22:17:29 +00002313 if (hex_value == -1U)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002314 break;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002315
2316 p++;
2317
Eli Friedmand2eb07a2013-07-17 22:17:29 +00002318 // Store the number while we have space.
2319 if (bitPos) {
2320 bitPos -= 4;
2321 hex_value <<= bitPos % integerPartWidth;
2322 significand[bitPos / integerPartWidth] |= hex_value;
2323 } else if (!computedTrailingFraction) {
2324 lost_fraction = trailingHexadecimalFraction(p, end, hex_value);
2325 computedTrailingFraction = true;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002326 }
2327 }
2328
2329 /* Hex floats require an exponent but not a hexadecimal point. */
Erick Tryzelaarda666c82009-08-20 23:30:43 +00002330 assert(p != end && "Hex strings require an exponent");
2331 assert((*p == 'p' || *p == 'P') && "Invalid character in significand");
2332 assert(p != begin && "Significand has no digits");
2333 assert((dot == end || p - begin != 1) && "Significand has no digits");
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002334
2335 /* Ignore the exponent if we are zero. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002336 if (p != firstSignificantDigit) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002337 int expAdjustment;
2338
2339 /* Implicit hexadecimal point? */
Erick Tryzelaarda666c82009-08-20 23:30:43 +00002340 if (dot == end)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002341 dot = p;
2342
2343 /* Calculate the exponent adjustment implicit in the number of
2344 significant digits. */
Evan Cheng82b9e962008-05-02 21:15:08 +00002345 expAdjustment = static_cast<int>(dot - firstSignificantDigit);
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002346 if (expAdjustment < 0)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002347 expAdjustment++;
2348 expAdjustment = expAdjustment * 4 - 1;
2349
2350 /* Adjust for writing the significand starting at the most
2351 significant nibble. */
2352 expAdjustment += semantics->precision;
2353 expAdjustment -= partsCount * integerPartWidth;
2354
2355 /* Adjust for the given exponent. */
Erick Tryzelaarda666c82009-08-20 23:30:43 +00002356 exponent = totalExponent(p + 1, end, expAdjustment);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002357 }
2358
2359 return normalize(rounding_mode, lost_fraction);
2360}
2361
Tim Shen85de51d2016-10-25 19:55:59 +00002362IEEEFloat::opStatus
2363IEEEFloat::roundSignificandWithExponent(const integerPart *decSigParts,
2364 unsigned sigPartCount, int exp,
2365 roundingMode rounding_mode) {
Neil Boothb93d90e2007-10-12 16:02:31 +00002366 unsigned int parts, pow5PartCount;
Tamas Berghammerb6b0ddf2015-07-09 10:13:39 +00002367 fltSemantics calcSemantics = { 32767, -32767, 0, 0 };
Neil Boothb93d90e2007-10-12 16:02:31 +00002368 integerPart pow5Parts[maxPowerOfFiveParts];
2369 bool isNearest;
2370
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002371 isNearest = (rounding_mode == rmNearestTiesToEven ||
2372 rounding_mode == rmNearestTiesToAway);
Neil Boothb93d90e2007-10-12 16:02:31 +00002373
2374 parts = partCountForBits(semantics->precision + 11);
2375
2376 /* Calculate pow(5, abs(exp)). */
2377 pow5PartCount = powerOf5(pow5Parts, exp >= 0 ? exp: -exp);
2378
2379 for (;; parts *= 2) {
2380 opStatus sigStatus, powStatus;
2381 unsigned int excessPrecision, truncatedBits;
2382
2383 calcSemantics.precision = parts * integerPartWidth - 1;
2384 excessPrecision = calcSemantics.precision - semantics->precision;
2385 truncatedBits = excessPrecision;
2386
Tim Shen139a58f2016-10-27 22:52:40 +00002387 IEEEFloat decSig(calcSemantics, uninitialized);
2388 decSig.makeZero(sign);
Tim Shen85de51d2016-10-25 19:55:59 +00002389 IEEEFloat pow5(calcSemantics);
Neil Boothb93d90e2007-10-12 16:02:31 +00002390
2391 sigStatus = decSig.convertFromUnsignedParts(decSigParts, sigPartCount,
2392 rmNearestTiesToEven);
2393 powStatus = pow5.convertFromUnsignedParts(pow5Parts, pow5PartCount,
2394 rmNearestTiesToEven);
2395 /* Add exp, as 10^n = 5^n * 2^n. */
2396 decSig.exponent += exp;
2397
2398 lostFraction calcLostFraction;
Evan Cheng82b9e962008-05-02 21:15:08 +00002399 integerPart HUerr, HUdistance;
2400 unsigned int powHUerr;
Neil Boothb93d90e2007-10-12 16:02:31 +00002401
2402 if (exp >= 0) {
2403 /* multiplySignificand leaves the precision-th bit set to 1. */
Craig Topperc10719f2014-04-07 04:17:22 +00002404 calcLostFraction = decSig.multiplySignificand(pow5, nullptr);
Neil Boothb93d90e2007-10-12 16:02:31 +00002405 powHUerr = powStatus != opOK;
2406 } else {
2407 calcLostFraction = decSig.divideSignificand(pow5);
2408 /* Denormal numbers have less precision. */
2409 if (decSig.exponent < semantics->minExponent) {
2410 excessPrecision += (semantics->minExponent - decSig.exponent);
2411 truncatedBits = excessPrecision;
2412 if (excessPrecision > calcSemantics.precision)
2413 excessPrecision = calcSemantics.precision;
2414 }
2415 /* Extra half-ulp lost in reciprocal of exponent. */
Evan Cheng82b9e962008-05-02 21:15:08 +00002416 powHUerr = (powStatus == opOK && calcLostFraction == lfExactlyZero) ? 0:2;
Neil Boothb93d90e2007-10-12 16:02:31 +00002417 }
2418
2419 /* Both multiplySignificand and divideSignificand return the
2420 result with the integer bit set. */
Evan Cheng67c90212009-10-27 21:35:42 +00002421 assert(APInt::tcExtractBit
2422 (decSig.significandParts(), calcSemantics.precision - 1) == 1);
Neil Boothb93d90e2007-10-12 16:02:31 +00002423
2424 HUerr = HUerrBound(calcLostFraction != lfExactlyZero, sigStatus != opOK,
2425 powHUerr);
2426 HUdistance = 2 * ulpsFromBoundary(decSig.significandParts(),
2427 excessPrecision, isNearest);
2428
2429 /* Are we guaranteed to round correctly if we truncate? */
2430 if (HUdistance >= HUerr) {
2431 APInt::tcExtract(significandParts(), partCount(), decSig.significandParts(),
2432 calcSemantics.precision - excessPrecision,
2433 excessPrecision);
2434 /* Take the exponent of decSig. If we tcExtract-ed less bits
2435 above we must adjust our exponent to compensate for the
2436 implicit right shift. */
2437 exponent = (decSig.exponent + semantics->precision
2438 - (calcSemantics.precision - excessPrecision));
2439 calcLostFraction = lostFractionThroughTruncation(decSig.significandParts(),
2440 decSig.partCount(),
2441 truncatedBits);
2442 return normalize(rounding_mode, calcLostFraction);
2443 }
2444 }
2445}
2446
Tim Shen85de51d2016-10-25 19:55:59 +00002447IEEEFloat::opStatus
2448IEEEFloat::convertFromDecimalString(StringRef str, roundingMode rounding_mode) {
Neil Booth4ed401b2007-10-14 10:16:12 +00002449 decimalInfo D;
Neil Boothb93d90e2007-10-12 16:02:31 +00002450 opStatus fs;
2451
Neil Booth4ed401b2007-10-14 10:16:12 +00002452 /* Scan the text. */
Erick Tryzelaar19f63b22009-08-16 23:36:19 +00002453 StringRef::iterator p = str.begin();
2454 interpretDecimal(p, str.end(), &D);
Neil Boothb93d90e2007-10-12 16:02:31 +00002455
Neil Booth91305512007-10-15 15:00:55 +00002456 /* Handle the quick cases. First the case of no significant digits,
2457 i.e. zero, and then exponents that are obviously too large or too
2458 small. Writing L for log 10 / log 2, a number d.ddddd*10^exp
2459 definitely overflows if
2460
2461 (exp - 1) * L >= maxExponent
2462
2463 and definitely underflows to zero where
2464
2465 (exp + 1) * L <= minExponent - precision
2466
2467 With integer arithmetic the tightest bounds for L are
2468
2469 93/28 < L < 196/59 [ numerator <= 256 ]
2470 42039/12655 < L < 28738/8651 [ numerator <= 65536 ]
2471 */
2472
Michael Gottesman228156c2013-07-01 23:54:08 +00002473 // Test if we have a zero number allowing for strings with no null terminators
2474 // and zero decimals with non-zero exponents.
2475 //
2476 // We computed firstSigDigit by ignoring all zeros and dots. Thus if
2477 // D->firstSigDigit equals str.end(), every digit must be a zero and there can
2478 // be at most one dot. On the other hand, if we have a zero with a non-zero
2479 // exponent, then we know that D.firstSigDigit will be non-numeric.
Michael Gottesman94d61952013-07-02 15:50:05 +00002480 if (D.firstSigDigit == str.end() || decDigitValue(*D.firstSigDigit) >= 10U) {
Neil Boothb93d90e2007-10-12 16:02:31 +00002481 category = fcZero;
2482 fs = opOK;
John McCallb42cc682010-02-26 22:20:41 +00002483
2484 /* Check whether the normalized exponent is high enough to overflow
2485 max during the log-rebasing in the max-exponent check below. */
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +00002486 } else if (D.normalizedExponent - 1 > INT_MAX / 42039) {
John McCallb42cc682010-02-26 22:20:41 +00002487 fs = handleOverflow(rounding_mode);
2488
2489 /* If it wasn't, then it also wasn't high enough to overflow max
2490 during the log-rebasing in the min-exponent check. Check that it
2491 won't overflow min in either check, then perform the min-exponent
2492 check. */
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +00002493 } else if (D.normalizedExponent - 1 < INT_MIN / 42039 ||
John McCallb42cc682010-02-26 22:20:41 +00002494 (D.normalizedExponent + 1) * 28738 <=
2495 8651 * (semantics->minExponent - (int) semantics->precision)) {
Neil Booth91305512007-10-15 15:00:55 +00002496 /* Underflow to zero and round. */
Michael Gottesman30a90eb2013-07-27 21:49:21 +00002497 category = fcNormal;
Neil Booth91305512007-10-15 15:00:55 +00002498 zeroSignificand();
2499 fs = normalize(rounding_mode, lfLessThanHalf);
John McCallb42cc682010-02-26 22:20:41 +00002500
2501 /* We can finally safely perform the max-exponent check. */
Neil Booth91305512007-10-15 15:00:55 +00002502 } else if ((D.normalizedExponent - 1) * 42039
2503 >= 12655 * semantics->maxExponent) {
2504 /* Overflow and round. */
2505 fs = handleOverflow(rounding_mode);
Neil Boothb93d90e2007-10-12 16:02:31 +00002506 } else {
Dylan Noblesmith4e69e292014-08-26 02:03:33 +00002507 integerPart *decSignificand;
Neil Booth4ed401b2007-10-14 10:16:12 +00002508 unsigned int partCount;
Neil Boothb93d90e2007-10-12 16:02:31 +00002509
Neil Booth4ed401b2007-10-14 10:16:12 +00002510 /* A tight upper bound on number of bits required to hold an
Neil Booth91305512007-10-15 15:00:55 +00002511 N-digit decimal integer is N * 196 / 59. Allocate enough space
Neil Booth4ed401b2007-10-14 10:16:12 +00002512 to hold the full significand, and an extra part required by
2513 tcMultiplyPart. */
Evan Cheng82b9e962008-05-02 21:15:08 +00002514 partCount = static_cast<unsigned int>(D.lastSigDigit - D.firstSigDigit) + 1;
Neil Booth91305512007-10-15 15:00:55 +00002515 partCount = partCountForBits(1 + 196 * partCount / 59);
Dylan Noblesmith4e69e292014-08-26 02:03:33 +00002516 decSignificand = new integerPart[partCount + 1];
Neil Booth4ed401b2007-10-14 10:16:12 +00002517 partCount = 0;
Neil Boothb93d90e2007-10-12 16:02:31 +00002518
Neil Booth4ed401b2007-10-14 10:16:12 +00002519 /* Convert to binary efficiently - we do almost all multiplication
2520 in an integerPart. When this would overflow do we do a single
2521 bignum multiplication, and then revert again to multiplication
2522 in an integerPart. */
2523 do {
2524 integerPart decValue, val, multiplier;
2525
2526 val = 0;
2527 multiplier = 1;
2528
2529 do {
Erick Tryzelaar19f63b22009-08-16 23:36:19 +00002530 if (*p == '.') {
Neil Booth4ed401b2007-10-14 10:16:12 +00002531 p++;
Erick Tryzelaar19f63b22009-08-16 23:36:19 +00002532 if (p == str.end()) {
2533 break;
2534 }
2535 }
Neil Booth4ed401b2007-10-14 10:16:12 +00002536 decValue = decDigitValue(*p++);
Erick Tryzelaarda666c82009-08-20 23:30:43 +00002537 assert(decValue < 10U && "Invalid character in significand");
Neil Booth4ed401b2007-10-14 10:16:12 +00002538 multiplier *= 10;
2539 val = val * 10 + decValue;
2540 /* The maximum number that can be multiplied by ten with any
2541 digit added without overflowing an integerPart. */
2542 } while (p <= D.lastSigDigit && multiplier <= (~ (integerPart) 0 - 9) / 10);
2543
2544 /* Multiply out the current part. */
2545 APInt::tcMultiplyPart(decSignificand, decSignificand, multiplier, val,
2546 partCount, partCount + 1, false);
2547
2548 /* If we used another part (likely but not guaranteed), increase
2549 the count. */
2550 if (decSignificand[partCount])
2551 partCount++;
2552 } while (p <= D.lastSigDigit);
Neil Boothb93d90e2007-10-12 16:02:31 +00002553
Neil Boothae077d22007-11-01 22:51:07 +00002554 category = fcNormal;
Neil Boothb93d90e2007-10-12 16:02:31 +00002555 fs = roundSignificandWithExponent(decSignificand, partCount,
Neil Booth4ed401b2007-10-14 10:16:12 +00002556 D.exponent, rounding_mode);
Dylan Noblesmith4e69e292014-08-26 02:03:33 +00002557
2558 delete [] decSignificand;
Neil Booth4ed401b2007-10-14 10:16:12 +00002559 }
Neil Boothb93d90e2007-10-12 16:02:31 +00002560
2561 return fs;
2562}
2563
Tim Shen85de51d2016-10-25 19:55:59 +00002564bool IEEEFloat::convertFromStringSpecials(StringRef str) {
Michael Gottesman40e8a182013-06-24 09:58:05 +00002565 if (str.equals("inf") || str.equals("INFINITY")) {
2566 makeInf(false);
2567 return true;
2568 }
2569
2570 if (str.equals("-inf") || str.equals("-INFINITY")) {
2571 makeInf(true);
2572 return true;
2573 }
2574
2575 if (str.equals("nan") || str.equals("NaN")) {
2576 makeNaN(false, false);
2577 return true;
2578 }
2579
2580 if (str.equals("-nan") || str.equals("-NaN")) {
2581 makeNaN(false, true);
2582 return true;
2583 }
2584
2585 return false;
2586}
2587
Tim Shen85de51d2016-10-25 19:55:59 +00002588IEEEFloat::opStatus IEEEFloat::convertFromString(StringRef str,
2589 roundingMode rounding_mode) {
Erick Tryzelaar19f63b22009-08-16 23:36:19 +00002590 assert(!str.empty() && "Invalid string length");
Neil Booth06077e72007-10-14 10:29:28 +00002591
Michael Gottesman40e8a182013-06-24 09:58:05 +00002592 // Handle special cases.
2593 if (convertFromStringSpecials(str))
2594 return opOK;
2595
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002596 /* Handle a leading minus sign. */
Erick Tryzelaar19f63b22009-08-16 23:36:19 +00002597 StringRef::iterator p = str.begin();
2598 size_t slen = str.size();
Erick Tryzelaarda666c82009-08-20 23:30:43 +00002599 sign = *p == '-' ? 1 : 0;
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002600 if (*p == '-' || *p == '+') {
Erick Tryzelaar19f63b22009-08-16 23:36:19 +00002601 p++;
2602 slen--;
Erick Tryzelaarda666c82009-08-20 23:30:43 +00002603 assert(slen && "String has no digits");
Erick Tryzelaar19f63b22009-08-16 23:36:19 +00002604 }
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002605
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002606 if (slen >= 2 && p[0] == '0' && (p[1] == 'x' || p[1] == 'X')) {
Erick Tryzelaar19f63b22009-08-16 23:36:19 +00002607 assert(slen - 2 && "Invalid string");
Erick Tryzelaarda666c82009-08-20 23:30:43 +00002608 return convertFromHexadecimalString(StringRef(p + 2, slen - 2),
Erick Tryzelaar19f63b22009-08-16 23:36:19 +00002609 rounding_mode);
2610 }
Bill Wendlingc6075402008-11-27 08:00:12 +00002611
Erick Tryzelaarda666c82009-08-20 23:30:43 +00002612 return convertFromDecimalString(StringRef(p, slen), rounding_mode);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002613}
Dale Johannesena719a602007-08-24 00:56:33 +00002614
Neil Booth8f1946f2007-10-03 22:26:02 +00002615/* Write out a hexadecimal representation of the floating point value
2616 to DST, which must be of sufficient size, in the C99 form
2617 [-]0xh.hhhhp[+-]d. Return the number of characters written,
2618 excluding the terminating NUL.
2619
2620 If UPPERCASE, the output is in upper case, otherwise in lower case.
2621
2622 HEXDIGITS digits appear altogether, rounding the value if
2623 necessary. If HEXDIGITS is 0, the minimal precision to display the
2624 number precisely is used instead. If nothing would appear after
2625 the decimal point it is suppressed.
2626
2627 The decimal exponent is always printed and has at least one digit.
2628 Zero values display an exponent of zero. Infinities and NaNs
2629 appear as "infinity" or "nan" respectively.
2630
2631 The above rules are as specified by C99. There is ambiguity about
2632 what the leading hexadecimal digit should be. This implementation
2633 uses whatever is necessary so that the exponent is displayed as
2634 stored. This implies the exponent will fall within the IEEE format
2635 range, and the leading hexadecimal digit will be 0 (for denormals),
2636 1 (normal numbers) or 2 (normal numbers rounded-away-from-zero with
2637 any other digits zero).
2638*/
Tim Shen85de51d2016-10-25 19:55:59 +00002639unsigned int IEEEFloat::convertToHexString(char *dst, unsigned int hexDigits,
2640 bool upperCase,
2641 roundingMode rounding_mode) const {
Neil Booth8f1946f2007-10-03 22:26:02 +00002642 char *p;
2643
2644 p = dst;
2645 if (sign)
2646 *dst++ = '-';
2647
2648 switch (category) {
2649 case fcInfinity:
2650 memcpy (dst, upperCase ? infinityU: infinityL, sizeof infinityU - 1);
2651 dst += sizeof infinityL - 1;
2652 break;
2653
2654 case fcNaN:
2655 memcpy (dst, upperCase ? NaNU: NaNL, sizeof NaNU - 1);
2656 dst += sizeof NaNU - 1;
2657 break;
2658
2659 case fcZero:
2660 *dst++ = '0';
2661 *dst++ = upperCase ? 'X': 'x';
2662 *dst++ = '0';
2663 if (hexDigits > 1) {
2664 *dst++ = '.';
2665 memset (dst, '0', hexDigits - 1);
2666 dst += hexDigits - 1;
2667 }
2668 *dst++ = upperCase ? 'P': 'p';
2669 *dst++ = '0';
2670 break;
2671
2672 case fcNormal:
2673 dst = convertNormalToHexString (dst, hexDigits, upperCase, rounding_mode);
2674 break;
2675 }
2676
2677 *dst = 0;
2678
Evan Cheng82b9e962008-05-02 21:15:08 +00002679 return static_cast<unsigned int>(dst - p);
Neil Booth8f1946f2007-10-03 22:26:02 +00002680}
2681
2682/* Does the hard work of outputting the correctly rounded hexadecimal
2683 form of a normal floating point number with the specified number of
2684 hexadecimal digits. If HEXDIGITS is zero the minimum number of
2685 digits necessary to print the value precisely is output. */
Tim Shen85de51d2016-10-25 19:55:59 +00002686char *IEEEFloat::convertNormalToHexString(char *dst, unsigned int hexDigits,
2687 bool upperCase,
2688 roundingMode rounding_mode) const {
Neil Booth8f1946f2007-10-03 22:26:02 +00002689 unsigned int count, valueBits, shift, partsCount, outputDigits;
2690 const char *hexDigitChars;
2691 const integerPart *significand;
2692 char *p;
2693 bool roundUp;
2694
2695 *dst++ = '0';
2696 *dst++ = upperCase ? 'X': 'x';
2697
2698 roundUp = false;
2699 hexDigitChars = upperCase ? hexDigitsUpper: hexDigitsLower;
2700
2701 significand = significandParts();
2702 partsCount = partCount();
2703
2704 /* +3 because the first digit only uses the single integer bit, so
2705 we have 3 virtual zero most-significant-bits. */
2706 valueBits = semantics->precision + 3;
2707 shift = integerPartWidth - valueBits % integerPartWidth;
2708
2709 /* The natural number of digits required ignoring trailing
2710 insignificant zeroes. */
2711 outputDigits = (valueBits - significandLSB () + 3) / 4;
2712
2713 /* hexDigits of zero means use the required number for the
2714 precision. Otherwise, see if we are truncating. If we are,
Neil Booth0ea72a92007-10-06 00:24:48 +00002715 find out if we need to round away from zero. */
Neil Booth8f1946f2007-10-03 22:26:02 +00002716 if (hexDigits) {
2717 if (hexDigits < outputDigits) {
2718 /* We are dropping non-zero bits, so need to check how to round.
2719 "bits" is the number of dropped bits. */
2720 unsigned int bits;
2721 lostFraction fraction;
2722
2723 bits = valueBits - hexDigits * 4;
2724 fraction = lostFractionThroughTruncation (significand, partsCount, bits);
2725 roundUp = roundAwayFromZero(rounding_mode, fraction, bits);
2726 }
2727 outputDigits = hexDigits;
2728 }
2729
2730 /* Write the digits consecutively, and start writing in the location
2731 of the hexadecimal point. We move the most significant digit
2732 left and add the hexadecimal point later. */
2733 p = ++dst;
2734
2735 count = (valueBits + integerPartWidth - 1) / integerPartWidth;
2736
2737 while (outputDigits && count) {
2738 integerPart part;
2739
2740 /* Put the most significant integerPartWidth bits in "part". */
2741 if (--count == partsCount)
2742 part = 0; /* An imaginary higher zero part. */
2743 else
2744 part = significand[count] << shift;
2745
2746 if (count && shift)
2747 part |= significand[count - 1] >> (integerPartWidth - shift);
2748
2749 /* Convert as much of "part" to hexdigits as we can. */
2750 unsigned int curDigits = integerPartWidth / 4;
2751
2752 if (curDigits > outputDigits)
2753 curDigits = outputDigits;
2754 dst += partAsHex (dst, part, curDigits, hexDigitChars);
2755 outputDigits -= curDigits;
2756 }
2757
2758 if (roundUp) {
2759 char *q = dst;
2760
2761 /* Note that hexDigitChars has a trailing '0'. */
2762 do {
2763 q--;
2764 *q = hexDigitChars[hexDigitValue (*q) + 1];
Neil Booth0ea72a92007-10-06 00:24:48 +00002765 } while (*q == '0');
Evan Cheng67c90212009-10-27 21:35:42 +00002766 assert(q >= p);
Neil Booth8f1946f2007-10-03 22:26:02 +00002767 } else {
2768 /* Add trailing zeroes. */
2769 memset (dst, '0', outputDigits);
2770 dst += outputDigits;
2771 }
2772
2773 /* Move the most significant digit to before the point, and if there
2774 is something after the decimal point add it. This must come
2775 after rounding above. */
2776 p[-1] = p[0];
2777 if (dst -1 == p)
2778 dst--;
2779 else
2780 p[0] = '.';
2781
2782 /* Finally output the exponent. */
2783 *dst++ = upperCase ? 'P': 'p';
2784
Neil Booth32897f52007-10-06 07:29:25 +00002785 return writeSignedDecimal (dst, exponent);
Neil Booth8f1946f2007-10-03 22:26:02 +00002786}
2787
Tim Shen85de51d2016-10-25 19:55:59 +00002788hash_code hash_value(const IEEEFloat &Arg) {
Michael Gottesman8136c382013-06-26 23:17:28 +00002789 if (!Arg.isFiniteNonZero())
Chandler Carruth71bd7d12012-03-04 12:02:57 +00002790 return hash_combine((uint8_t)Arg.category,
2791 // NaN has no sign, fix it at zero.
2792 Arg.isNaN() ? (uint8_t)0 : (uint8_t)Arg.sign,
2793 Arg.semantics->precision);
2794
2795 // Normal floats need their exponent and significand hashed.
2796 return hash_combine((uint8_t)Arg.category, (uint8_t)Arg.sign,
2797 Arg.semantics->precision, Arg.exponent,
2798 hash_combine_range(
2799 Arg.significandParts(),
2800 Arg.significandParts() + Arg.partCount()));
Dale Johannesena719a602007-08-24 00:56:33 +00002801}
2802
2803// Conversion from APFloat to/from host float/double. It may eventually be
2804// possible to eliminate these and have everybody deal with APFloats, but that
2805// will take a while. This approach will not easily extend to long double.
Dale Johannesen146a0ea2007-09-20 23:47:58 +00002806// Current implementation requires integerPartWidth==64, which is correct at
2807// the moment but could be made more general.
Dale Johannesena719a602007-08-24 00:56:33 +00002808
Dale Johannesen728687c2007-09-05 20:39:49 +00002809// Denormals have exponent minExponent in APFloat, but minExponent-1 in
Dale Johannesen146a0ea2007-09-20 23:47:58 +00002810// the actual IEEE respresentations. We compensate for that here.
Dale Johannesen728687c2007-09-05 20:39:49 +00002811
Tim Shen85de51d2016-10-25 19:55:59 +00002812APInt IEEEFloat::convertF80LongDoubleAPFloatToAPInt() const {
Stephan Bergmann17c7f702016-12-14 11:57:17 +00002813 assert(semantics == (const llvm::fltSemantics*)&semX87DoubleExtended);
Evan Cheng67c90212009-10-27 21:35:42 +00002814 assert(partCount()==2);
Dale Johannesen245dceb2007-09-11 18:32:33 +00002815
2816 uint64_t myexponent, mysignificand;
2817
Michael Gottesman8136c382013-06-26 23:17:28 +00002818 if (isFiniteNonZero()) {
Dale Johannesen245dceb2007-09-11 18:32:33 +00002819 myexponent = exponent+16383; //bias
Dale Johannesen146a0ea2007-09-20 23:47:58 +00002820 mysignificand = significandParts()[0];
Dale Johannesen245dceb2007-09-11 18:32:33 +00002821 if (myexponent==1 && !(mysignificand & 0x8000000000000000ULL))
2822 myexponent = 0; // denormal
2823 } else if (category==fcZero) {
2824 myexponent = 0;
2825 mysignificand = 0;
2826 } else if (category==fcInfinity) {
2827 myexponent = 0x7fff;
2828 mysignificand = 0x8000000000000000ULL;
Chris Lattner2a9bcb92007-10-06 06:13:42 +00002829 } else {
2830 assert(category == fcNaN && "Unknown category");
Dale Johannesen245dceb2007-09-11 18:32:33 +00002831 myexponent = 0x7fff;
Dale Johannesen146a0ea2007-09-20 23:47:58 +00002832 mysignificand = significandParts()[0];
Chris Lattner2a9bcb92007-10-06 06:13:42 +00002833 }
Dale Johannesen245dceb2007-09-11 18:32:33 +00002834
2835 uint64_t words[2];
Dale Johannesen93eefa02009-03-23 21:16:53 +00002836 words[0] = mysignificand;
2837 words[1] = ((uint64_t)(sign & 1) << 15) |
2838 (myexponent & 0x7fffLL);
Jeffrey Yasskin7a162882011-07-18 21:45:40 +00002839 return APInt(80, words);
Dale Johannesen245dceb2007-09-11 18:32:33 +00002840}
2841
Tim Shen85de51d2016-10-25 19:55:59 +00002842APInt IEEEFloat::convertPPCDoubleDoubleAPFloatToAPInt() const {
Tim Shenfd1e5aa2017-01-23 22:39:35 +00002843 assert(semantics == (const llvm::fltSemantics *)&semPPCDoubleDoubleLegacy);
Evan Cheng67c90212009-10-27 21:35:42 +00002844 assert(partCount()==2);
Dale Johannesen007aa372007-10-11 18:07:22 +00002845
Ulrich Weigandd9f7e252012-10-29 18:09:01 +00002846 uint64_t words[2];
2847 opStatus fs;
2848 bool losesInfo;
Dale Johannesen007aa372007-10-11 18:07:22 +00002849
Ulrich Weigandd9f7e252012-10-29 18:09:01 +00002850 // Convert number to double. To avoid spurious underflows, we re-
2851 // normalize against the "double" minExponent first, and only *then*
2852 // truncate the mantissa. The result of that second conversion
2853 // may be inexact, but should never underflow.
Alexey Samsonov2b431d92012-11-30 22:27:54 +00002854 // Declare fltSemantics before APFloat that uses it (and
2855 // saves pointer to it) to ensure correct destruction order.
Ulrich Weigandd9f7e252012-10-29 18:09:01 +00002856 fltSemantics extendedSemantics = *semantics;
Stephan Bergmann17c7f702016-12-14 11:57:17 +00002857 extendedSemantics.minExponent = semIEEEdouble.minExponent;
Tim Shen85de51d2016-10-25 19:55:59 +00002858 IEEEFloat extended(*this);
Ulrich Weigandd9f7e252012-10-29 18:09:01 +00002859 fs = extended.convert(extendedSemantics, rmNearestTiesToEven, &losesInfo);
2860 assert(fs == opOK && !losesInfo);
2861 (void)fs;
2862
Tim Shen85de51d2016-10-25 19:55:59 +00002863 IEEEFloat u(extended);
Stephan Bergmann17c7f702016-12-14 11:57:17 +00002864 fs = u.convert(semIEEEdouble, rmNearestTiesToEven, &losesInfo);
Ulrich Weigandd9f7e252012-10-29 18:09:01 +00002865 assert(fs == opOK || fs == opInexact);
2866 (void)fs;
2867 words[0] = *u.convertDoubleAPFloatToAPInt().getRawData();
2868
2869 // If conversion was exact or resulted in a special case, we're done;
2870 // just set the second double to zero. Otherwise, re-convert back to
2871 // the extended format and compute the difference. This now should
2872 // convert exactly to double.
Michael Gottesman8136c382013-06-26 23:17:28 +00002873 if (u.isFiniteNonZero() && losesInfo) {
Ulrich Weigandd9f7e252012-10-29 18:09:01 +00002874 fs = u.convert(extendedSemantics, rmNearestTiesToEven, &losesInfo);
2875 assert(fs == opOK && !losesInfo);
2876 (void)fs;
2877
Tim Shen85de51d2016-10-25 19:55:59 +00002878 IEEEFloat v(extended);
Ulrich Weigandd9f7e252012-10-29 18:09:01 +00002879 v.subtract(u, rmNearestTiesToEven);
Stephan Bergmann17c7f702016-12-14 11:57:17 +00002880 fs = v.convert(semIEEEdouble, rmNearestTiesToEven, &losesInfo);
Ulrich Weigandd9f7e252012-10-29 18:09:01 +00002881 assert(fs == opOK && !losesInfo);
2882 (void)fs;
2883 words[1] = *v.convertDoubleAPFloatToAPInt().getRawData();
Dale Johannesen007aa372007-10-11 18:07:22 +00002884 } else {
Ulrich Weigandd9f7e252012-10-29 18:09:01 +00002885 words[1] = 0;
Dale Johannesen007aa372007-10-11 18:07:22 +00002886 }
2887
Jeffrey Yasskin7a162882011-07-18 21:45:40 +00002888 return APInt(128, words);
Dale Johannesen007aa372007-10-11 18:07:22 +00002889}
2890
Tim Shen85de51d2016-10-25 19:55:59 +00002891APInt IEEEFloat::convertQuadrupleAPFloatToAPInt() const {
Stephan Bergmann17c7f702016-12-14 11:57:17 +00002892 assert(semantics == (const llvm::fltSemantics*)&semIEEEquad);
Evan Cheng67c90212009-10-27 21:35:42 +00002893 assert(partCount()==2);
Anton Korobeynikov13e8c7e2009-08-21 22:10:30 +00002894
2895 uint64_t myexponent, mysignificand, mysignificand2;
2896
Michael Gottesman8136c382013-06-26 23:17:28 +00002897 if (isFiniteNonZero()) {
Anton Korobeynikov13e8c7e2009-08-21 22:10:30 +00002898 myexponent = exponent+16383; //bias
2899 mysignificand = significandParts()[0];
2900 mysignificand2 = significandParts()[1];
2901 if (myexponent==1 && !(mysignificand2 & 0x1000000000000LL))
2902 myexponent = 0; // denormal
2903 } else if (category==fcZero) {
2904 myexponent = 0;
2905 mysignificand = mysignificand2 = 0;
2906 } else if (category==fcInfinity) {
2907 myexponent = 0x7fff;
2908 mysignificand = mysignificand2 = 0;
2909 } else {
2910 assert(category == fcNaN && "Unknown category!");
2911 myexponent = 0x7fff;
2912 mysignificand = significandParts()[0];
2913 mysignificand2 = significandParts()[1];
2914 }
2915
2916 uint64_t words[2];
2917 words[0] = mysignificand;
2918 words[1] = ((uint64_t)(sign & 1) << 63) |
2919 ((myexponent & 0x7fff) << 48) |
Anton Korobeynikov876955c2009-08-21 23:09:47 +00002920 (mysignificand2 & 0xffffffffffffLL);
Anton Korobeynikov13e8c7e2009-08-21 22:10:30 +00002921
Jeffrey Yasskin7a162882011-07-18 21:45:40 +00002922 return APInt(128, words);
Anton Korobeynikov13e8c7e2009-08-21 22:10:30 +00002923}
2924
Tim Shen85de51d2016-10-25 19:55:59 +00002925APInt IEEEFloat::convertDoubleAPFloatToAPInt() const {
Stephan Bergmann17c7f702016-12-14 11:57:17 +00002926 assert(semantics == (const llvm::fltSemantics*)&semIEEEdouble);
Evan Cheng67c90212009-10-27 21:35:42 +00002927 assert(partCount()==1);
Dale Johannesena719a602007-08-24 00:56:33 +00002928
Dale Johannesen3cf889f2007-08-31 04:03:46 +00002929 uint64_t myexponent, mysignificand;
Dale Johannesena719a602007-08-24 00:56:33 +00002930
Michael Gottesman8136c382013-06-26 23:17:28 +00002931 if (isFiniteNonZero()) {
Dale Johannesena719a602007-08-24 00:56:33 +00002932 myexponent = exponent+1023; //bias
Dale Johannesen728687c2007-09-05 20:39:49 +00002933 mysignificand = *significandParts();
2934 if (myexponent==1 && !(mysignificand & 0x10000000000000LL))
2935 myexponent = 0; // denormal
Dale Johannesena719a602007-08-24 00:56:33 +00002936 } else if (category==fcZero) {
Dale Johannesena719a602007-08-24 00:56:33 +00002937 myexponent = 0;
2938 mysignificand = 0;
2939 } else if (category==fcInfinity) {
Dale Johannesena719a602007-08-24 00:56:33 +00002940 myexponent = 0x7ff;
2941 mysignificand = 0;
Chris Lattner2a9bcb92007-10-06 06:13:42 +00002942 } else {
2943 assert(category == fcNaN && "Unknown category!");
Dale Johannesena719a602007-08-24 00:56:33 +00002944 myexponent = 0x7ff;
Dale Johannesen3cf889f2007-08-31 04:03:46 +00002945 mysignificand = *significandParts();
Chris Lattner2a9bcb92007-10-06 06:13:42 +00002946 }
Dale Johannesena719a602007-08-24 00:56:33 +00002947
Evan Cheng82b9e962008-05-02 21:15:08 +00002948 return APInt(64, ((((uint64_t)(sign & 1) << 63) |
Chris Lattner2a9bcb92007-10-06 06:13:42 +00002949 ((myexponent & 0x7ff) << 52) |
2950 (mysignificand & 0xfffffffffffffLL))));
Dale Johannesena719a602007-08-24 00:56:33 +00002951}
2952
Tim Shen85de51d2016-10-25 19:55:59 +00002953APInt IEEEFloat::convertFloatAPFloatToAPInt() const {
Stephan Bergmann17c7f702016-12-14 11:57:17 +00002954 assert(semantics == (const llvm::fltSemantics*)&semIEEEsingle);
Evan Cheng67c90212009-10-27 21:35:42 +00002955 assert(partCount()==1);
Neil Booth9acbf5a2007-09-26 21:33:42 +00002956
Dale Johannesen3cf889f2007-08-31 04:03:46 +00002957 uint32_t myexponent, mysignificand;
Dale Johannesena719a602007-08-24 00:56:33 +00002958
Michael Gottesman8136c382013-06-26 23:17:28 +00002959 if (isFiniteNonZero()) {
Dale Johannesena719a602007-08-24 00:56:33 +00002960 myexponent = exponent+127; //bias
Evan Cheng82b9e962008-05-02 21:15:08 +00002961 mysignificand = (uint32_t)*significandParts();
Dale Johannesen06a10df2007-11-17 01:02:27 +00002962 if (myexponent == 1 && !(mysignificand & 0x800000))
Dale Johannesen728687c2007-09-05 20:39:49 +00002963 myexponent = 0; // denormal
Dale Johannesena719a602007-08-24 00:56:33 +00002964 } else if (category==fcZero) {
Dale Johannesena719a602007-08-24 00:56:33 +00002965 myexponent = 0;
2966 mysignificand = 0;
2967 } else if (category==fcInfinity) {
Dale Johannesena719a602007-08-24 00:56:33 +00002968 myexponent = 0xff;
2969 mysignificand = 0;
Chris Lattner2a9bcb92007-10-06 06:13:42 +00002970 } else {
2971 assert(category == fcNaN && "Unknown category!");
Dale Johannesen728687c2007-09-05 20:39:49 +00002972 myexponent = 0xff;
Evan Cheng82b9e962008-05-02 21:15:08 +00002973 mysignificand = (uint32_t)*significandParts();
Chris Lattner2a9bcb92007-10-06 06:13:42 +00002974 }
Dale Johannesena719a602007-08-24 00:56:33 +00002975
Chris Lattner2a9bcb92007-10-06 06:13:42 +00002976 return APInt(32, (((sign&1) << 31) | ((myexponent&0xff) << 23) |
2977 (mysignificand & 0x7fffff)));
Dale Johannesena719a602007-08-24 00:56:33 +00002978}
2979
Tim Shen85de51d2016-10-25 19:55:59 +00002980APInt IEEEFloat::convertHalfAPFloatToAPInt() const {
Stephan Bergmann17c7f702016-12-14 11:57:17 +00002981 assert(semantics == (const llvm::fltSemantics*)&semIEEEhalf);
Evan Cheng67c90212009-10-27 21:35:42 +00002982 assert(partCount()==1);
Chris Lattner4794b2b2009-10-16 02:13:51 +00002983
2984 uint32_t myexponent, mysignificand;
2985
Michael Gottesman8136c382013-06-26 23:17:28 +00002986 if (isFiniteNonZero()) {
Chris Lattner4794b2b2009-10-16 02:13:51 +00002987 myexponent = exponent+15; //bias
2988 mysignificand = (uint32_t)*significandParts();
2989 if (myexponent == 1 && !(mysignificand & 0x400))
2990 myexponent = 0; // denormal
2991 } else if (category==fcZero) {
2992 myexponent = 0;
2993 mysignificand = 0;
2994 } else if (category==fcInfinity) {
Dale Johannesen0d670b52009-10-23 04:02:51 +00002995 myexponent = 0x1f;
Chris Lattner4794b2b2009-10-16 02:13:51 +00002996 mysignificand = 0;
2997 } else {
2998 assert(category == fcNaN && "Unknown category!");
Dale Johannesen0d670b52009-10-23 04:02:51 +00002999 myexponent = 0x1f;
Chris Lattner4794b2b2009-10-16 02:13:51 +00003000 mysignificand = (uint32_t)*significandParts();
3001 }
3002
3003 return APInt(16, (((sign&1) << 15) | ((myexponent&0x1f) << 10) |
3004 (mysignificand & 0x3ff)));
3005}
3006
Dale Johannesen007aa372007-10-11 18:07:22 +00003007// This function creates an APInt that is just a bit map of the floating
3008// point constant as it would appear in memory. It is not a conversion,
3009// and treating the result as a normal integer is unlikely to be useful.
3010
Tim Shen85de51d2016-10-25 19:55:59 +00003011APInt IEEEFloat::bitcastToAPInt() const {
Stephan Bergmann17c7f702016-12-14 11:57:17 +00003012 if (semantics == (const llvm::fltSemantics*)&semIEEEhalf)
Chris Lattner4794b2b2009-10-16 02:13:51 +00003013 return convertHalfAPFloatToAPInt();
3014
Stephan Bergmann17c7f702016-12-14 11:57:17 +00003015 if (semantics == (const llvm::fltSemantics*)&semIEEEsingle)
Dale Johannesen245dceb2007-09-11 18:32:33 +00003016 return convertFloatAPFloatToAPInt();
Anton Korobeynikov13e8c7e2009-08-21 22:10:30 +00003017
Stephan Bergmann17c7f702016-12-14 11:57:17 +00003018 if (semantics == (const llvm::fltSemantics*)&semIEEEdouble)
Dale Johannesen245dceb2007-09-11 18:32:33 +00003019 return convertDoubleAPFloatToAPInt();
Neil Booth9acbf5a2007-09-26 21:33:42 +00003020
Stephan Bergmann17c7f702016-12-14 11:57:17 +00003021 if (semantics == (const llvm::fltSemantics*)&semIEEEquad)
Anton Korobeynikov13e8c7e2009-08-21 22:10:30 +00003022 return convertQuadrupleAPFloatToAPInt();
3023
Tim Shenfd1e5aa2017-01-23 22:39:35 +00003024 if (semantics == (const llvm::fltSemantics *)&semPPCDoubleDoubleLegacy)
Dale Johannesen007aa372007-10-11 18:07:22 +00003025 return convertPPCDoubleDoubleAPFloatToAPInt();
3026
Stephan Bergmann17c7f702016-12-14 11:57:17 +00003027 assert(semantics == (const llvm::fltSemantics*)&semX87DoubleExtended &&
Chris Lattner2a9bcb92007-10-06 06:13:42 +00003028 "unknown format!");
3029 return convertF80LongDoubleAPFloatToAPInt();
Dale Johannesen245dceb2007-09-11 18:32:33 +00003030}
3031
Tim Shen85de51d2016-10-25 19:55:59 +00003032float IEEEFloat::convertToFloat() const {
Stephan Bergmann17c7f702016-12-14 11:57:17 +00003033 assert(semantics == (const llvm::fltSemantics*)&semIEEEsingle &&
Chris Lattner688f9912009-09-24 21:44:20 +00003034 "Float semantics are not IEEEsingle");
Dale Johannesen54306fe2008-10-09 18:53:47 +00003035 APInt api = bitcastToAPInt();
Dale Johannesen245dceb2007-09-11 18:32:33 +00003036 return api.bitsToFloat();
3037}
3038
Tim Shen85de51d2016-10-25 19:55:59 +00003039double IEEEFloat::convertToDouble() const {
Stephan Bergmann17c7f702016-12-14 11:57:17 +00003040 assert(semantics == (const llvm::fltSemantics*)&semIEEEdouble &&
Chris Lattner688f9912009-09-24 21:44:20 +00003041 "Float semantics are not IEEEdouble");
Dale Johannesen54306fe2008-10-09 18:53:47 +00003042 APInt api = bitcastToAPInt();
Dale Johannesen245dceb2007-09-11 18:32:33 +00003043 return api.bitsToDouble();
3044}
3045
Dale Johannesenfff29952008-10-06 18:22:29 +00003046/// Integer bit is explicit in this format. Intel hardware (387 and later)
3047/// does not support these bit patterns:
3048/// exponent = all 1's, integer bit 0, significand 0 ("pseudoinfinity")
3049/// exponent = all 1's, integer bit 0, significand nonzero ("pseudoNaN")
3050/// exponent = 0, integer bit 1 ("pseudodenormal")
3051/// exponent!=0 nor all 1's, integer bit 0 ("unnormal")
3052/// At the moment, the first two are treated as NaNs, the second two as Normal.
Tim Shen85de51d2016-10-25 19:55:59 +00003053void IEEEFloat::initFromF80LongDoubleAPInt(const APInt &api) {
Dale Johannesen245dceb2007-09-11 18:32:33 +00003054 assert(api.getBitWidth()==80);
3055 uint64_t i1 = api.getRawData()[0];
3056 uint64_t i2 = api.getRawData()[1];
Dale Johannesen93eefa02009-03-23 21:16:53 +00003057 uint64_t myexponent = (i2 & 0x7fff);
3058 uint64_t mysignificand = i1;
Dale Johannesen245dceb2007-09-11 18:32:33 +00003059
Stephan Bergmann17c7f702016-12-14 11:57:17 +00003060 initialize(&semX87DoubleExtended);
Dale Johannesen146a0ea2007-09-20 23:47:58 +00003061 assert(partCount()==2);
Dale Johannesen245dceb2007-09-11 18:32:33 +00003062
Dale Johannesen93eefa02009-03-23 21:16:53 +00003063 sign = static_cast<unsigned int>(i2>>15);
Dale Johannesen245dceb2007-09-11 18:32:33 +00003064 if (myexponent==0 && mysignificand==0) {
3065 // exponent, significand meaningless
3066 category = fcZero;
3067 } else if (myexponent==0x7fff && mysignificand==0x8000000000000000ULL) {
3068 // exponent, significand meaningless
3069 category = fcInfinity;
3070 } else if (myexponent==0x7fff && mysignificand!=0x8000000000000000ULL) {
3071 // exponent meaningless
3072 category = fcNaN;
Dale Johannesen146a0ea2007-09-20 23:47:58 +00003073 significandParts()[0] = mysignificand;
3074 significandParts()[1] = 0;
Dale Johannesen245dceb2007-09-11 18:32:33 +00003075 } else {
3076 category = fcNormal;
3077 exponent = myexponent - 16383;
Dale Johannesen146a0ea2007-09-20 23:47:58 +00003078 significandParts()[0] = mysignificand;
3079 significandParts()[1] = 0;
Dale Johannesen245dceb2007-09-11 18:32:33 +00003080 if (myexponent==0) // denormal
3081 exponent = -16382;
Neil Booth9acbf5a2007-09-26 21:33:42 +00003082 }
Dale Johannesen245dceb2007-09-11 18:32:33 +00003083}
3084
Tim Shen85de51d2016-10-25 19:55:59 +00003085void IEEEFloat::initFromPPCDoubleDoubleAPInt(const APInt &api) {
Dale Johannesen007aa372007-10-11 18:07:22 +00003086 assert(api.getBitWidth()==128);
3087 uint64_t i1 = api.getRawData()[0];
3088 uint64_t i2 = api.getRawData()[1];
Ulrich Weigandd9f7e252012-10-29 18:09:01 +00003089 opStatus fs;
3090 bool losesInfo;
Dale Johannesen007aa372007-10-11 18:07:22 +00003091
Ulrich Weigandd9f7e252012-10-29 18:09:01 +00003092 // Get the first double and convert to our format.
3093 initFromDoubleAPInt(APInt(64, i1));
Tim Shenfd1e5aa2017-01-23 22:39:35 +00003094 fs = convert(semPPCDoubleDoubleLegacy, rmNearestTiesToEven, &losesInfo);
Ulrich Weigandd9f7e252012-10-29 18:09:01 +00003095 assert(fs == opOK && !losesInfo);
3096 (void)fs;
Dale Johannesen007aa372007-10-11 18:07:22 +00003097
Ulrich Weigandd9f7e252012-10-29 18:09:01 +00003098 // Unless we have a special case, add in second double.
Michael Gottesman8136c382013-06-26 23:17:28 +00003099 if (isFiniteNonZero()) {
Stephan Bergmann17c7f702016-12-14 11:57:17 +00003100 IEEEFloat v(semIEEEdouble, APInt(64, i2));
Tim Shenfd1e5aa2017-01-23 22:39:35 +00003101 fs = v.convert(semPPCDoubleDoubleLegacy, rmNearestTiesToEven, &losesInfo);
Ulrich Weigandd9f7e252012-10-29 18:09:01 +00003102 assert(fs == opOK && !losesInfo);
3103 (void)fs;
3104
3105 add(v, rmNearestTiesToEven);
Dale Johannesen007aa372007-10-11 18:07:22 +00003106 }
3107}
3108
Tim Shen85de51d2016-10-25 19:55:59 +00003109void IEEEFloat::initFromQuadrupleAPInt(const APInt &api) {
Anton Korobeynikov13e8c7e2009-08-21 22:10:30 +00003110 assert(api.getBitWidth()==128);
3111 uint64_t i1 = api.getRawData()[0];
3112 uint64_t i2 = api.getRawData()[1];
3113 uint64_t myexponent = (i2 >> 48) & 0x7fff;
3114 uint64_t mysignificand = i1;
3115 uint64_t mysignificand2 = i2 & 0xffffffffffffLL;
3116
Stephan Bergmann17c7f702016-12-14 11:57:17 +00003117 initialize(&semIEEEquad);
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +00003118 assert(partCount()==2);
Anton Korobeynikov13e8c7e2009-08-21 22:10:30 +00003119
3120 sign = static_cast<unsigned int>(i2>>63);
3121 if (myexponent==0 &&
3122 (mysignificand==0 && mysignificand2==0)) {
3123 // exponent, significand meaningless
3124 category = fcZero;
3125 } else if (myexponent==0x7fff &&
3126 (mysignificand==0 && mysignificand2==0)) {
3127 // exponent, significand meaningless
3128 category = fcInfinity;
3129 } else if (myexponent==0x7fff &&
3130 (mysignificand!=0 || mysignificand2 !=0)) {
3131 // exponent meaningless
3132 category = fcNaN;
3133 significandParts()[0] = mysignificand;
3134 significandParts()[1] = mysignificand2;
3135 } else {
3136 category = fcNormal;
3137 exponent = myexponent - 16383;
3138 significandParts()[0] = mysignificand;
3139 significandParts()[1] = mysignificand2;
3140 if (myexponent==0) // denormal
3141 exponent = -16382;
3142 else
3143 significandParts()[1] |= 0x1000000000000LL; // integer bit
3144 }
3145}
3146
Tim Shen85de51d2016-10-25 19:55:59 +00003147void IEEEFloat::initFromDoubleAPInt(const APInt &api) {
Dale Johannesen245dceb2007-09-11 18:32:33 +00003148 assert(api.getBitWidth()==64);
3149 uint64_t i = *api.getRawData();
Dale Johannesen918c33c2007-08-24 05:08:11 +00003150 uint64_t myexponent = (i >> 52) & 0x7ff;
3151 uint64_t mysignificand = i & 0xfffffffffffffLL;
3152
Stephan Bergmann17c7f702016-12-14 11:57:17 +00003153 initialize(&semIEEEdouble);
Dale Johannesena719a602007-08-24 00:56:33 +00003154 assert(partCount()==1);
3155
Evan Cheng82b9e962008-05-02 21:15:08 +00003156 sign = static_cast<unsigned int>(i>>63);
Dale Johannesena719a602007-08-24 00:56:33 +00003157 if (myexponent==0 && mysignificand==0) {
3158 // exponent, significand meaningless
3159 category = fcZero;
Dale Johannesena719a602007-08-24 00:56:33 +00003160 } else if (myexponent==0x7ff && mysignificand==0) {
3161 // exponent, significand meaningless
3162 category = fcInfinity;
Dale Johannesen3cf889f2007-08-31 04:03:46 +00003163 } else if (myexponent==0x7ff && mysignificand!=0) {
3164 // exponent meaningless
3165 category = fcNaN;
3166 *significandParts() = mysignificand;
Dale Johannesena719a602007-08-24 00:56:33 +00003167 } else {
Dale Johannesena719a602007-08-24 00:56:33 +00003168 category = fcNormal;
3169 exponent = myexponent - 1023;
Dale Johannesen728687c2007-09-05 20:39:49 +00003170 *significandParts() = mysignificand;
3171 if (myexponent==0) // denormal
3172 exponent = -1022;
3173 else
3174 *significandParts() |= 0x10000000000000LL; // integer bit
Neil Booth9acbf5a2007-09-26 21:33:42 +00003175 }
Dale Johannesena719a602007-08-24 00:56:33 +00003176}
3177
Tim Shen85de51d2016-10-25 19:55:59 +00003178void IEEEFloat::initFromFloatAPInt(const APInt &api) {
Dale Johannesen245dceb2007-09-11 18:32:33 +00003179 assert(api.getBitWidth()==32);
3180 uint32_t i = (uint32_t)*api.getRawData();
Dale Johannesen918c33c2007-08-24 05:08:11 +00003181 uint32_t myexponent = (i >> 23) & 0xff;
3182 uint32_t mysignificand = i & 0x7fffff;
3183
Stephan Bergmann17c7f702016-12-14 11:57:17 +00003184 initialize(&semIEEEsingle);
Dale Johannesena719a602007-08-24 00:56:33 +00003185 assert(partCount()==1);
3186
Dale Johannesen3cf889f2007-08-31 04:03:46 +00003187 sign = i >> 31;
Dale Johannesena719a602007-08-24 00:56:33 +00003188 if (myexponent==0 && mysignificand==0) {
3189 // exponent, significand meaningless
3190 category = fcZero;
Dale Johannesena719a602007-08-24 00:56:33 +00003191 } else if (myexponent==0xff && mysignificand==0) {
3192 // exponent, significand meaningless
3193 category = fcInfinity;
Dale Johannesen4f55d9f2007-09-25 17:25:00 +00003194 } else if (myexponent==0xff && mysignificand!=0) {
Dale Johannesena719a602007-08-24 00:56:33 +00003195 // sign, exponent, significand meaningless
Dale Johannesen3cf889f2007-08-31 04:03:46 +00003196 category = fcNaN;
3197 *significandParts() = mysignificand;
Dale Johannesena719a602007-08-24 00:56:33 +00003198 } else {
3199 category = fcNormal;
Dale Johannesena719a602007-08-24 00:56:33 +00003200 exponent = myexponent - 127; //bias
Dale Johannesen728687c2007-09-05 20:39:49 +00003201 *significandParts() = mysignificand;
3202 if (myexponent==0) // denormal
3203 exponent = -126;
3204 else
3205 *significandParts() |= 0x800000; // integer bit
Dale Johannesena719a602007-08-24 00:56:33 +00003206 }
3207}
Dale Johannesen245dceb2007-09-11 18:32:33 +00003208
Tim Shen85de51d2016-10-25 19:55:59 +00003209void IEEEFloat::initFromHalfAPInt(const APInt &api) {
Chris Lattner4794b2b2009-10-16 02:13:51 +00003210 assert(api.getBitWidth()==16);
3211 uint32_t i = (uint32_t)*api.getRawData();
Dale Johannesen0d670b52009-10-23 04:02:51 +00003212 uint32_t myexponent = (i >> 10) & 0x1f;
Chris Lattner4794b2b2009-10-16 02:13:51 +00003213 uint32_t mysignificand = i & 0x3ff;
3214
Stephan Bergmann17c7f702016-12-14 11:57:17 +00003215 initialize(&semIEEEhalf);
Chris Lattner4794b2b2009-10-16 02:13:51 +00003216 assert(partCount()==1);
3217
3218 sign = i >> 15;
3219 if (myexponent==0 && mysignificand==0) {
3220 // exponent, significand meaningless
3221 category = fcZero;
3222 } else if (myexponent==0x1f && mysignificand==0) {
3223 // exponent, significand meaningless
3224 category = fcInfinity;
3225 } else if (myexponent==0x1f && mysignificand!=0) {
3226 // sign, exponent, significand meaningless
3227 category = fcNaN;
3228 *significandParts() = mysignificand;
3229 } else {
3230 category = fcNormal;
3231 exponent = myexponent - 15; //bias
3232 *significandParts() = mysignificand;
3233 if (myexponent==0) // denormal
3234 exponent = -14;
3235 else
3236 *significandParts() |= 0x400; // integer bit
3237 }
3238}
3239
Dale Johannesen245dceb2007-09-11 18:32:33 +00003240/// Treat api as containing the bits of a floating point number. Currently
Dale Johannesen007aa372007-10-11 18:07:22 +00003241/// we infer the floating point type from the size of the APInt. The
3242/// isIEEE argument distinguishes between PPC128 and IEEE128 (not meaningful
3243/// when the size is anything else).
Tim Shen85de51d2016-10-25 19:55:59 +00003244void IEEEFloat::initFromAPInt(const fltSemantics *Sem, const APInt &api) {
Stephan Bergmann17c7f702016-12-14 11:57:17 +00003245 if (Sem == &semIEEEhalf)
Chris Lattner4794b2b2009-10-16 02:13:51 +00003246 return initFromHalfAPInt(api);
Stephan Bergmann17c7f702016-12-14 11:57:17 +00003247 if (Sem == &semIEEEsingle)
Dale Johannesen245dceb2007-09-11 18:32:33 +00003248 return initFromFloatAPInt(api);
Stephan Bergmann17c7f702016-12-14 11:57:17 +00003249 if (Sem == &semIEEEdouble)
Dale Johannesen245dceb2007-09-11 18:32:33 +00003250 return initFromDoubleAPInt(api);
Stephan Bergmann17c7f702016-12-14 11:57:17 +00003251 if (Sem == &semX87DoubleExtended)
Dale Johannesen245dceb2007-09-11 18:32:33 +00003252 return initFromF80LongDoubleAPInt(api);
Stephan Bergmann17c7f702016-12-14 11:57:17 +00003253 if (Sem == &semIEEEquad)
Tim Northover29178a32013-01-22 09:46:31 +00003254 return initFromQuadrupleAPInt(api);
Tim Shenfd1e5aa2017-01-23 22:39:35 +00003255 if (Sem == &semPPCDoubleDoubleLegacy)
Tim Northover29178a32013-01-22 09:46:31 +00003256 return initFromPPCDoubleDoubleAPInt(api);
3257
Craig Topper2617dcc2014-04-15 06:32:26 +00003258 llvm_unreachable(nullptr);
Dale Johannesen245dceb2007-09-11 18:32:33 +00003259}
3260
Michael Gottesman0c622ea2013-05-30 18:07:13 +00003261/// Make this number the largest magnitude normal number in the given
3262/// semantics.
Tim Shen85de51d2016-10-25 19:55:59 +00003263void IEEEFloat::makeLargest(bool Negative) {
John McCall29b5c282009-12-24 08:56:26 +00003264 // We want (in interchange format):
3265 // sign = {Negative}
3266 // exponent = 1..10
3267 // significand = 1..1
Michael Gottesman0c622ea2013-05-30 18:07:13 +00003268 category = fcNormal;
3269 sign = Negative;
3270 exponent = semantics->maxExponent;
John McCall29b5c282009-12-24 08:56:26 +00003271
Michael Gottesman0c622ea2013-05-30 18:07:13 +00003272 // Use memset to set all but the highest integerPart to all ones.
3273 integerPart *significand = significandParts();
3274 unsigned PartCount = partCount();
3275 memset(significand, 0xFF, sizeof(integerPart)*(PartCount - 1));
John McCall29b5c282009-12-24 08:56:26 +00003276
Michael Gottesman0c622ea2013-05-30 18:07:13 +00003277 // Set the high integerPart especially setting all unused top bits for
3278 // internal consistency.
3279 const unsigned NumUnusedHighBits =
3280 PartCount*integerPartWidth - semantics->precision;
Alexey Samsonovba1ecbc2014-09-06 00:41:19 +00003281 significand[PartCount - 1] = (NumUnusedHighBits < integerPartWidth)
3282 ? (~integerPart(0) >> NumUnusedHighBits)
3283 : 0;
John McCall29b5c282009-12-24 08:56:26 +00003284}
3285
Michael Gottesman0c622ea2013-05-30 18:07:13 +00003286/// Make this number the smallest magnitude denormal number in the given
3287/// semantics.
Tim Shen85de51d2016-10-25 19:55:59 +00003288void IEEEFloat::makeSmallest(bool Negative) {
John McCall29b5c282009-12-24 08:56:26 +00003289 // We want (in interchange format):
3290 // sign = {Negative}
3291 // exponent = 0..0
3292 // significand = 0..01
Michael Gottesman0c622ea2013-05-30 18:07:13 +00003293 category = fcNormal;
3294 sign = Negative;
3295 exponent = semantics->minExponent;
3296 APInt::tcSet(significandParts(), 1, partCount());
3297}
John McCall29b5c282009-12-24 08:56:26 +00003298
Tim Shen139a58f2016-10-27 22:52:40 +00003299void IEEEFloat::makeSmallestNormalized(bool Negative) {
John McCall29b5c282009-12-24 08:56:26 +00003300 // We want (in interchange format):
3301 // sign = {Negative}
3302 // exponent = 0..0
3303 // significand = 10..0
3304
Tim Shen139a58f2016-10-27 22:52:40 +00003305 category = fcNormal;
3306 zeroSignificand();
3307 sign = Negative;
3308 exponent = semantics->minExponent;
3309 significandParts()[partCountForBits(semantics->precision) - 1] |=
3310 (((integerPart)1) << ((semantics->precision - 1) % integerPartWidth));
John McCall29b5c282009-12-24 08:56:26 +00003311}
3312
Tim Shen85de51d2016-10-25 19:55:59 +00003313IEEEFloat::IEEEFloat(const fltSemantics &Sem, const APInt &API) {
Tim Northover29178a32013-01-22 09:46:31 +00003314 initFromAPInt(&Sem, API);
Dale Johannesen245dceb2007-09-11 18:32:33 +00003315}
3316
Tim Shen85de51d2016-10-25 19:55:59 +00003317IEEEFloat::IEEEFloat(float f) {
Stephan Bergmann17c7f702016-12-14 11:57:17 +00003318 initFromAPInt(&semIEEEsingle, APInt::floatToBits(f));
Dale Johannesen245dceb2007-09-11 18:32:33 +00003319}
3320
Tim Shen85de51d2016-10-25 19:55:59 +00003321IEEEFloat::IEEEFloat(double d) {
Stephan Bergmann17c7f702016-12-14 11:57:17 +00003322 initFromAPInt(&semIEEEdouble, APInt::doubleToBits(d));
Dale Johannesen245dceb2007-09-11 18:32:33 +00003323}
John McCall29b5c282009-12-24 08:56:26 +00003324
3325namespace {
David Blaikie70fdf722012-07-25 18:04:24 +00003326 void append(SmallVectorImpl<char> &Buffer, StringRef Str) {
3327 Buffer.append(Str.begin(), Str.end());
John McCall29b5c282009-12-24 08:56:26 +00003328 }
3329
John McCalle6212ace2009-12-24 12:16:56 +00003330 /// Removes data from the given significand until it is no more
3331 /// precise than is required for the desired precision.
3332 void AdjustToPrecision(APInt &significand,
3333 int &exp, unsigned FormatPrecision) {
3334 unsigned bits = significand.getActiveBits();
3335
3336 // 196/59 is a very slight overestimate of lg_2(10).
3337 unsigned bitsRequired = (FormatPrecision * 196 + 58) / 59;
3338
3339 if (bits <= bitsRequired) return;
3340
3341 unsigned tensRemovable = (bits - bitsRequired) * 59 / 196;
3342 if (!tensRemovable) return;
3343
3344 exp += tensRemovable;
3345
3346 APInt divisor(significand.getBitWidth(), 1);
3347 APInt powten(significand.getBitWidth(), 10);
3348 while (true) {
3349 if (tensRemovable & 1)
3350 divisor *= powten;
3351 tensRemovable >>= 1;
3352 if (!tensRemovable) break;
3353 powten *= powten;
3354 }
3355
3356 significand = significand.udiv(divisor);
3357
Hao Liube99cc32013-03-20 01:46:36 +00003358 // Truncate the significand down to its active bit count.
3359 significand = significand.trunc(significand.getActiveBits());
John McCalle6212ace2009-12-24 12:16:56 +00003360 }
3361
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +00003362
John McCall29b5c282009-12-24 08:56:26 +00003363 void AdjustToPrecision(SmallVectorImpl<char> &buffer,
3364 int &exp, unsigned FormatPrecision) {
3365 unsigned N = buffer.size();
3366 if (N <= FormatPrecision) return;
3367
3368 // The most significant figures are the last ones in the buffer.
3369 unsigned FirstSignificant = N - FormatPrecision;
3370
3371 // Round.
3372 // FIXME: this probably shouldn't use 'round half up'.
3373
3374 // Rounding down is just a truncation, except we also want to drop
3375 // trailing zeros from the new result.
3376 if (buffer[FirstSignificant - 1] < '5') {
NAKAMURA Takumi5adeb932012-02-19 03:18:29 +00003377 while (FirstSignificant < N && buffer[FirstSignificant] == '0')
John McCall29b5c282009-12-24 08:56:26 +00003378 FirstSignificant++;
3379
3380 exp += FirstSignificant;
3381 buffer.erase(&buffer[0], &buffer[FirstSignificant]);
3382 return;
3383 }
3384
3385 // Rounding up requires a decimal add-with-carry. If we continue
3386 // the carry, the newly-introduced zeros will just be truncated.
3387 for (unsigned I = FirstSignificant; I != N; ++I) {
3388 if (buffer[I] == '9') {
3389 FirstSignificant++;
3390 } else {
3391 buffer[I]++;
3392 break;
3393 }
3394 }
3395
3396 // If we carried through, we have exactly one digit of precision.
3397 if (FirstSignificant == N) {
3398 exp += FirstSignificant;
3399 buffer.clear();
3400 buffer.push_back('1');
3401 return;
3402 }
3403
3404 exp += FirstSignificant;
3405 buffer.erase(&buffer[0], &buffer[FirstSignificant]);
3406 }
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +00003407}
John McCall29b5c282009-12-24 08:56:26 +00003408
Tim Shen85de51d2016-10-25 19:55:59 +00003409void IEEEFloat::toString(SmallVectorImpl<char> &Str, unsigned FormatPrecision,
3410 unsigned FormatMaxPadding) const {
John McCall29b5c282009-12-24 08:56:26 +00003411 switch (category) {
3412 case fcInfinity:
3413 if (isNegative())
3414 return append(Str, "-Inf");
3415 else
3416 return append(Str, "+Inf");
3417
3418 case fcNaN: return append(Str, "NaN");
3419
3420 case fcZero:
3421 if (isNegative())
3422 Str.push_back('-');
3423
3424 if (!FormatMaxPadding)
3425 append(Str, "0.0E+0");
3426 else
3427 Str.push_back('0');
3428 return;
3429
3430 case fcNormal:
3431 break;
3432 }
3433
3434 if (isNegative())
3435 Str.push_back('-');
3436
3437 // Decompose the number into an APInt and an exponent.
3438 int exp = exponent - ((int) semantics->precision - 1);
3439 APInt significand(semantics->precision,
Jeffrey Yasskin7a162882011-07-18 21:45:40 +00003440 makeArrayRef(significandParts(),
3441 partCountForBits(semantics->precision)));
John McCall29b5c282009-12-24 08:56:26 +00003442
John McCalldd5044a2009-12-24 23:18:09 +00003443 // Set FormatPrecision if zero. We want to do this before we
3444 // truncate trailing zeros, as those are part of the precision.
3445 if (!FormatPrecision) {
Eli Friedmane72f1322013-08-29 23:44:34 +00003446 // We use enough digits so the number can be round-tripped back to an
3447 // APFloat. The formula comes from "How to Print Floating-Point Numbers
3448 // Accurately" by Steele and White.
3449 // FIXME: Using a formula based purely on the precision is conservative;
3450 // we can print fewer digits depending on the actual value being printed.
John McCalldd5044a2009-12-24 23:18:09 +00003451
Eli Friedmane72f1322013-08-29 23:44:34 +00003452 // FormatPrecision = 2 + floor(significandBits / lg_2(10))
3453 FormatPrecision = 2 + semantics->precision * 59 / 196;
John McCalldd5044a2009-12-24 23:18:09 +00003454 }
3455
John McCall29b5c282009-12-24 08:56:26 +00003456 // Ignore trailing binary zeros.
3457 int trailingZeros = significand.countTrailingZeros();
3458 exp += trailingZeros;
3459 significand = significand.lshr(trailingZeros);
3460
3461 // Change the exponent from 2^e to 10^e.
3462 if (exp == 0) {
3463 // Nothing to do.
3464 } else if (exp > 0) {
3465 // Just shift left.
Jay Foad583abbc2010-12-07 08:25:19 +00003466 significand = significand.zext(semantics->precision + exp);
John McCall29b5c282009-12-24 08:56:26 +00003467 significand <<= exp;
3468 exp = 0;
3469 } else { /* exp < 0 */
3470 int texp = -exp;
3471
3472 // We transform this using the identity:
3473 // (N)(2^-e) == (N)(5^e)(10^-e)
3474 // This means we have to multiply N (the significand) by 5^e.
3475 // To avoid overflow, we have to operate on numbers large
3476 // enough to store N * 5^e:
3477 // log2(N * 5^e) == log2(N) + e * log2(5)
John McCalldd5044a2009-12-24 23:18:09 +00003478 // <= semantics->precision + e * 137 / 59
3479 // (log_2(5) ~ 2.321928 < 2.322034 ~ 137/59)
Dan Gohmanb452d4e2010-03-24 19:38:02 +00003480
Eli Friedman19546412011-10-07 23:40:49 +00003481 unsigned precision = semantics->precision + (137 * texp + 136) / 59;
John McCall29b5c282009-12-24 08:56:26 +00003482
3483 // Multiply significand by 5^e.
3484 // N * 5^0101 == N * 5^(1*1) * 5^(0*2) * 5^(1*4) * 5^(0*8)
Jay Foad583abbc2010-12-07 08:25:19 +00003485 significand = significand.zext(precision);
John McCall29b5c282009-12-24 08:56:26 +00003486 APInt five_to_the_i(precision, 5);
3487 while (true) {
3488 if (texp & 1) significand *= five_to_the_i;
Dan Gohmanb452d4e2010-03-24 19:38:02 +00003489
John McCall29b5c282009-12-24 08:56:26 +00003490 texp >>= 1;
3491 if (!texp) break;
3492 five_to_the_i *= five_to_the_i;
3493 }
3494 }
3495
John McCalle6212ace2009-12-24 12:16:56 +00003496 AdjustToPrecision(significand, exp, FormatPrecision);
3497
Dmitri Gribenko226fea52013-01-13 16:01:15 +00003498 SmallVector<char, 256> buffer;
John McCall29b5c282009-12-24 08:56:26 +00003499
3500 // Fill the buffer.
3501 unsigned precision = significand.getBitWidth();
3502 APInt ten(precision, 10);
3503 APInt digit(precision, 0);
3504
3505 bool inTrail = true;
3506 while (significand != 0) {
3507 // digit <- significand % 10
3508 // significand <- significand / 10
3509 APInt::udivrem(significand, ten, significand, digit);
3510
3511 unsigned d = digit.getZExtValue();
3512
3513 // Drop trailing zeros.
3514 if (inTrail && !d) exp++;
3515 else {
3516 buffer.push_back((char) ('0' + d));
3517 inTrail = false;
3518 }
3519 }
3520
3521 assert(!buffer.empty() && "no characters in buffer!");
3522
3523 // Drop down to FormatPrecision.
3524 // TODO: don't do more precise calculations above than are required.
3525 AdjustToPrecision(buffer, exp, FormatPrecision);
3526
3527 unsigned NDigits = buffer.size();
3528
John McCalldd5044a2009-12-24 23:18:09 +00003529 // Check whether we should use scientific notation.
John McCall29b5c282009-12-24 08:56:26 +00003530 bool FormatScientific;
3531 if (!FormatMaxPadding)
3532 FormatScientific = true;
3533 else {
John McCall29b5c282009-12-24 08:56:26 +00003534 if (exp >= 0) {
John McCalldd5044a2009-12-24 23:18:09 +00003535 // 765e3 --> 765000
3536 // ^^^
3537 // But we shouldn't make the number look more precise than it is.
3538 FormatScientific = ((unsigned) exp > FormatMaxPadding ||
3539 NDigits + (unsigned) exp > FormatPrecision);
John McCall29b5c282009-12-24 08:56:26 +00003540 } else {
John McCalldd5044a2009-12-24 23:18:09 +00003541 // Power of the most significant digit.
3542 int MSD = exp + (int) (NDigits - 1);
3543 if (MSD >= 0) {
John McCall29b5c282009-12-24 08:56:26 +00003544 // 765e-2 == 7.65
John McCalldd5044a2009-12-24 23:18:09 +00003545 FormatScientific = false;
John McCall29b5c282009-12-24 08:56:26 +00003546 } else {
3547 // 765e-5 == 0.00765
3548 // ^ ^^
John McCalldd5044a2009-12-24 23:18:09 +00003549 FormatScientific = ((unsigned) -MSD) > FormatMaxPadding;
John McCall29b5c282009-12-24 08:56:26 +00003550 }
3551 }
John McCall29b5c282009-12-24 08:56:26 +00003552 }
3553
3554 // Scientific formatting is pretty straightforward.
3555 if (FormatScientific) {
3556 exp += (NDigits - 1);
3557
3558 Str.push_back(buffer[NDigits-1]);
3559 Str.push_back('.');
3560 if (NDigits == 1)
3561 Str.push_back('0');
3562 else
3563 for (unsigned I = 1; I != NDigits; ++I)
3564 Str.push_back(buffer[NDigits-1-I]);
3565 Str.push_back('E');
3566
3567 Str.push_back(exp >= 0 ? '+' : '-');
3568 if (exp < 0) exp = -exp;
3569 SmallVector<char, 6> expbuf;
3570 do {
3571 expbuf.push_back((char) ('0' + (exp % 10)));
3572 exp /= 10;
3573 } while (exp);
3574 for (unsigned I = 0, E = expbuf.size(); I != E; ++I)
3575 Str.push_back(expbuf[E-1-I]);
3576 return;
3577 }
3578
3579 // Non-scientific, positive exponents.
3580 if (exp >= 0) {
3581 for (unsigned I = 0; I != NDigits; ++I)
3582 Str.push_back(buffer[NDigits-1-I]);
3583 for (unsigned I = 0; I != (unsigned) exp; ++I)
3584 Str.push_back('0');
3585 return;
3586 }
3587
3588 // Non-scientific, negative exponents.
3589
3590 // The number of digits to the left of the decimal point.
3591 int NWholeDigits = exp + (int) NDigits;
3592
3593 unsigned I = 0;
3594 if (NWholeDigits > 0) {
3595 for (; I != (unsigned) NWholeDigits; ++I)
3596 Str.push_back(buffer[NDigits-I-1]);
3597 Str.push_back('.');
3598 } else {
3599 unsigned NZeros = 1 + (unsigned) -NWholeDigits;
3600
3601 Str.push_back('0');
3602 Str.push_back('.');
3603 for (unsigned Z = 1; Z != NZeros; ++Z)
3604 Str.push_back('0');
3605 }
3606
3607 for (; I != NDigits; ++I)
3608 Str.push_back(buffer[NDigits-I-1]);
3609}
Benjamin Kramer03fd6722011-03-30 15:42:27 +00003610
Tim Shenfd1e5aa2017-01-23 22:39:35 +00003611bool IEEEFloat::getExactInverse(APFloat *inv) const {
Benjamin Kramer03fd6722011-03-30 15:42:27 +00003612 // Special floats and denormals have no exact inverse.
Michael Gottesman8136c382013-06-26 23:17:28 +00003613 if (!isFiniteNonZero())
Benjamin Kramer03fd6722011-03-30 15:42:27 +00003614 return false;
3615
3616 // Check that the number is a power of two by making sure that only the
3617 // integer bit is set in the significand.
3618 if (significandLSB() != semantics->precision - 1)
3619 return false;
3620
3621 // Get the inverse.
Tim Shen85de51d2016-10-25 19:55:59 +00003622 IEEEFloat reciprocal(*semantics, 1ULL);
Benjamin Kramer03fd6722011-03-30 15:42:27 +00003623 if (reciprocal.divide(*this, rmNearestTiesToEven) != opOK)
3624 return false;
3625
Benjamin Krameraf0ed952011-03-30 17:02:54 +00003626 // Avoid multiplication with a denormal, it is not safe on all platforms and
3627 // may be slower than a normal division.
Benjamin Kramer6bef24f2013-06-01 11:26:33 +00003628 if (reciprocal.isDenormal())
Benjamin Krameraf0ed952011-03-30 17:02:54 +00003629 return false;
3630
Michael Gottesman8136c382013-06-26 23:17:28 +00003631 assert(reciprocal.isFiniteNonZero() &&
Benjamin Krameraf0ed952011-03-30 17:02:54 +00003632 reciprocal.significandLSB() == reciprocal.semantics->precision - 1);
3633
Benjamin Kramer03fd6722011-03-30 15:42:27 +00003634 if (inv)
Tim Shenfd1e5aa2017-01-23 22:39:35 +00003635 *inv = APFloat(reciprocal, *semantics);
Benjamin Kramer03fd6722011-03-30 15:42:27 +00003636
3637 return true;
3638}
Michael Gottesman0c622ea2013-05-30 18:07:13 +00003639
Tim Shen85de51d2016-10-25 19:55:59 +00003640bool IEEEFloat::isSignaling() const {
Michael Gottesman0c622ea2013-05-30 18:07:13 +00003641 if (!isNaN())
3642 return false;
3643
3644 // IEEE-754R 2008 6.2.1: A signaling NaN bit string should be encoded with the
3645 // first bit of the trailing significand being 0.
3646 return !APInt::tcExtractBit(significandParts(), semantics->precision - 2);
3647}
3648
3649/// IEEE-754R 2008 5.3.1: nextUp/nextDown.
3650///
3651/// *NOTE* since nextDown(x) = -nextUp(-x), we only implement nextUp with
3652/// appropriate sign switching before/after the computation.
Tim Shen85de51d2016-10-25 19:55:59 +00003653IEEEFloat::opStatus IEEEFloat::next(bool nextDown) {
Michael Gottesman0c622ea2013-05-30 18:07:13 +00003654 // If we are performing nextDown, swap sign so we have -x.
3655 if (nextDown)
3656 changeSign();
3657
3658 // Compute nextUp(x)
3659 opStatus result = opOK;
3660
3661 // Handle each float category separately.
3662 switch (category) {
3663 case fcInfinity:
3664 // nextUp(+inf) = +inf
3665 if (!isNegative())
3666 break;
3667 // nextUp(-inf) = -getLargest()
3668 makeLargest(true);
3669 break;
3670 case fcNaN:
3671 // IEEE-754R 2008 6.2 Par 2: nextUp(sNaN) = qNaN. Set Invalid flag.
3672 // IEEE-754R 2008 6.2: nextUp(qNaN) = qNaN. Must be identity so we do not
3673 // change the payload.
3674 if (isSignaling()) {
3675 result = opInvalidOp;
Alp Tokercb402912014-01-24 17:20:08 +00003676 // For consistency, propagate the sign of the sNaN to the qNaN.
Craig Topperc10719f2014-04-07 04:17:22 +00003677 makeNaN(false, isNegative(), nullptr);
Michael Gottesman0c622ea2013-05-30 18:07:13 +00003678 }
3679 break;
3680 case fcZero:
3681 // nextUp(pm 0) = +getSmallest()
3682 makeSmallest(false);
3683 break;
3684 case fcNormal:
3685 // nextUp(-getSmallest()) = -0
3686 if (isSmallest() && isNegative()) {
3687 APInt::tcSet(significandParts(), 0, partCount());
3688 category = fcZero;
3689 exponent = 0;
3690 break;
3691 }
3692
3693 // nextUp(getLargest()) == INFINITY
3694 if (isLargest() && !isNegative()) {
3695 APInt::tcSet(significandParts(), 0, partCount());
3696 category = fcInfinity;
3697 exponent = semantics->maxExponent + 1;
3698 break;
3699 }
3700
3701 // nextUp(normal) == normal + inc.
3702 if (isNegative()) {
3703 // If we are negative, we need to decrement the significand.
3704
3705 // We only cross a binade boundary that requires adjusting the exponent
3706 // if:
3707 // 1. exponent != semantics->minExponent. This implies we are not in the
3708 // smallest binade or are dealing with denormals.
3709 // 2. Our significand excluding the integral bit is all zeros.
3710 bool WillCrossBinadeBoundary =
3711 exponent != semantics->minExponent && isSignificandAllZeros();
3712
3713 // Decrement the significand.
3714 //
3715 // We always do this since:
Alp Tokerf907b892013-12-05 05:44:44 +00003716 // 1. If we are dealing with a non-binade decrement, by definition we
Michael Gottesman0c622ea2013-05-30 18:07:13 +00003717 // just decrement the significand.
3718 // 2. If we are dealing with a normal -> normal binade decrement, since
3719 // we have an explicit integral bit the fact that all bits but the
3720 // integral bit are zero implies that subtracting one will yield a
3721 // significand with 0 integral bit and 1 in all other spots. Thus we
3722 // must just adjust the exponent and set the integral bit to 1.
3723 // 3. If we are dealing with a normal -> denormal binade decrement,
3724 // since we set the integral bit to 0 when we represent denormals, we
3725 // just decrement the significand.
3726 integerPart *Parts = significandParts();
3727 APInt::tcDecrement(Parts, partCount());
3728
3729 if (WillCrossBinadeBoundary) {
3730 // Our result is a normal number. Do the following:
3731 // 1. Set the integral bit to 1.
3732 // 2. Decrement the exponent.
3733 APInt::tcSetBit(Parts, semantics->precision - 1);
3734 exponent--;
3735 }
3736 } else {
3737 // If we are positive, we need to increment the significand.
3738
3739 // We only cross a binade boundary that requires adjusting the exponent if
3740 // the input is not a denormal and all of said input's significand bits
3741 // are set. If all of said conditions are true: clear the significand, set
3742 // the integral bit to 1, and increment the exponent. If we have a
3743 // denormal always increment since moving denormals and the numbers in the
3744 // smallest normal binade have the same exponent in our representation.
3745 bool WillCrossBinadeBoundary = !isDenormal() && isSignificandAllOnes();
3746
3747 if (WillCrossBinadeBoundary) {
3748 integerPart *Parts = significandParts();
3749 APInt::tcSet(Parts, 0, partCount());
3750 APInt::tcSetBit(Parts, semantics->precision - 1);
3751 assert(exponent != semantics->maxExponent &&
3752 "We can not increment an exponent beyond the maxExponent allowed"
3753 " by the given floating point semantics.");
3754 exponent++;
3755 } else {
3756 incrementSignificand();
3757 }
3758 }
3759 break;
3760 }
3761
3762 // If we are performing nextDown, swap sign so we have -nextUp(-x)
3763 if (nextDown)
3764 changeSign();
3765
3766 return result;
3767}
Michael Gottesmanc4facdf2013-06-24 09:58:02 +00003768
Tim Shen85de51d2016-10-25 19:55:59 +00003769void IEEEFloat::makeInf(bool Negative) {
Michael Gottesmanc4facdf2013-06-24 09:58:02 +00003770 category = fcInfinity;
3771 sign = Negative;
3772 exponent = semantics->maxExponent + 1;
3773 APInt::tcSet(significandParts(), 0, partCount());
3774}
3775
Tim Shen85de51d2016-10-25 19:55:59 +00003776void IEEEFloat::makeZero(bool Negative) {
Michael Gottesmanc4facdf2013-06-24 09:58:02 +00003777 category = fcZero;
3778 sign = Negative;
3779 exponent = semantics->minExponent-1;
Matt Arsenaultc25a7112016-03-21 16:49:16 +00003780 APInt::tcSet(significandParts(), 0, partCount());
3781}
3782
Tim Shen85de51d2016-10-25 19:55:59 +00003783void IEEEFloat::makeQuiet() {
Matt Arsenaultc25a7112016-03-21 16:49:16 +00003784 assert(isNaN());
3785 APInt::tcSetBit(significandParts(), semantics->precision - 2);
Michael Gottesmanc4facdf2013-06-24 09:58:02 +00003786}
Chandler Carruthd9edd1e2014-10-10 04:54:30 +00003787
Tim Shen85de51d2016-10-25 19:55:59 +00003788int ilogb(const IEEEFloat &Arg) {
Matt Arsenault69fdf9b2016-03-13 05:12:32 +00003789 if (Arg.isNaN())
Tim Shen85de51d2016-10-25 19:55:59 +00003790 return IEEEFloat::IEK_NaN;
Matt Arsenault69fdf9b2016-03-13 05:12:32 +00003791 if (Arg.isZero())
Tim Shen85de51d2016-10-25 19:55:59 +00003792 return IEEEFloat::IEK_Zero;
Matt Arsenault69fdf9b2016-03-13 05:12:32 +00003793 if (Arg.isInfinity())
Tim Shen85de51d2016-10-25 19:55:59 +00003794 return IEEEFloat::IEK_Inf;
Matt Arsenault69fdf9b2016-03-13 05:12:32 +00003795 if (!Arg.isDenormal())
3796 return Arg.exponent;
3797
Tim Shen85de51d2016-10-25 19:55:59 +00003798 IEEEFloat Normalized(Arg);
Matt Arsenault69fdf9b2016-03-13 05:12:32 +00003799 int SignificandBits = Arg.getSemantics().precision - 1;
3800
3801 Normalized.exponent += SignificandBits;
Tim Shen85de51d2016-10-25 19:55:59 +00003802 Normalized.normalize(IEEEFloat::rmNearestTiesToEven, lfExactlyZero);
Matt Arsenault69fdf9b2016-03-13 05:12:32 +00003803 return Normalized.exponent - SignificandBits;
3804}
3805
Tim Shen85de51d2016-10-25 19:55:59 +00003806IEEEFloat scalbn(IEEEFloat X, int Exp, IEEEFloat::roundingMode RoundingMode) {
Chandler Carruthd9edd1e2014-10-10 04:54:30 +00003807 auto MaxExp = X.getSemantics().maxExponent;
3808 auto MinExp = X.getSemantics().minExponent;
Chandler Carruthd9edd1e2014-10-10 04:54:30 +00003809
Matt Arsenaultafa31cf2016-03-13 05:11:51 +00003810 // If Exp is wildly out-of-scale, simply adding it to X.exponent will
3811 // overflow; clamp it to a safe range before adding, but ensure that the range
3812 // is large enough that the clamp does not change the result. The range we
3813 // need to support is the difference between the largest possible exponent and
3814 // the normalized exponent of half the smallest denormal.
3815
3816 int SignificandBits = X.getSemantics().precision - 1;
3817 int MaxIncrement = MaxExp - (MinExp - SignificandBits) + 1;
3818
3819 // Clamp to one past the range ends to let normalize handle overlflow.
3820 X.exponent += std::min(std::max(Exp, -MaxIncrement - 1), MaxIncrement);
3821 X.normalize(RoundingMode, lfExactlyZero);
Matt Arsenaultea00b492016-03-23 23:51:45 +00003822 if (X.isNaN())
3823 X.makeQuiet();
Richard Trieu6ae37962015-04-30 23:07:00 +00003824 return X;
Chandler Carruthd9edd1e2014-10-10 04:54:30 +00003825}
Matt Arsenaultc25a7112016-03-21 16:49:16 +00003826
Tim Shen85de51d2016-10-25 19:55:59 +00003827IEEEFloat frexp(const IEEEFloat &Val, int &Exp, IEEEFloat::roundingMode RM) {
Matt Arsenaultc25a7112016-03-21 16:49:16 +00003828 Exp = ilogb(Val);
3829
3830 // Quiet signalling nans.
Tim Shen85de51d2016-10-25 19:55:59 +00003831 if (Exp == IEEEFloat::IEK_NaN) {
3832 IEEEFloat Quiet(Val);
Matt Arsenaultc25a7112016-03-21 16:49:16 +00003833 Quiet.makeQuiet();
3834 return Quiet;
3835 }
3836
Tim Shen85de51d2016-10-25 19:55:59 +00003837 if (Exp == IEEEFloat::IEK_Inf)
Matt Arsenaultc25a7112016-03-21 16:49:16 +00003838 return Val;
3839
3840 // 1 is added because frexp is defined to return a normalized fraction in
3841 // +/-[0.5, 1.0), rather than the usual +/-[1.0, 2.0).
Tim Shen85de51d2016-10-25 19:55:59 +00003842 Exp = Exp == IEEEFloat::IEK_Zero ? 0 : Exp + 1;
Matt Arsenaultc25a7112016-03-21 16:49:16 +00003843 return scalbn(Val, -Exp, RM);
3844}
Tim Shen85de51d2016-10-25 19:55:59 +00003845
Tim Shen139a58f2016-10-27 22:52:40 +00003846DoubleAPFloat::DoubleAPFloat(const fltSemantics &S)
Tim Shenfd1e5aa2017-01-23 22:39:35 +00003847 : Semantics(&S),
3848 Floats(new APFloat[2]{APFloat(semIEEEdouble), APFloat(semIEEEdouble)}) {
Stephan Bergmann17c7f702016-12-14 11:57:17 +00003849 assert(Semantics == &semPPCDoubleDouble);
Tim Shen139a58f2016-10-27 22:52:40 +00003850}
3851
3852DoubleAPFloat::DoubleAPFloat(const fltSemantics &S, uninitializedTag)
3853 : Semantics(&S),
Tim Shenfd1e5aa2017-01-23 22:39:35 +00003854 Floats(new APFloat[2]{APFloat(semIEEEdouble, uninitialized),
Stephan Bergmann17c7f702016-12-14 11:57:17 +00003855 APFloat(semIEEEdouble, uninitialized)}) {
3856 assert(Semantics == &semPPCDoubleDouble);
Tim Shen139a58f2016-10-27 22:52:40 +00003857}
3858
3859DoubleAPFloat::DoubleAPFloat(const fltSemantics &S, integerPart I)
Tim Shenfd1e5aa2017-01-23 22:39:35 +00003860 : Semantics(&S), Floats(new APFloat[2]{APFloat(semIEEEdouble, I),
Stephan Bergmann17c7f702016-12-14 11:57:17 +00003861 APFloat(semIEEEdouble)}) {
3862 assert(Semantics == &semPPCDoubleDouble);
Tim Shen139a58f2016-10-27 22:52:40 +00003863}
3864
3865DoubleAPFloat::DoubleAPFloat(const fltSemantics &S, const APInt &I)
Tim Shenfd1e5aa2017-01-23 22:39:35 +00003866 : Semantics(&S),
3867 Floats(new APFloat[2]{
3868 APFloat(semIEEEdouble, APInt(64, I.getRawData()[0])),
3869 APFloat(semIEEEdouble, APInt(64, I.getRawData()[1]))}) {
Stephan Bergmann17c7f702016-12-14 11:57:17 +00003870 assert(Semantics == &semPPCDoubleDouble);
Tim Shen139a58f2016-10-27 22:52:40 +00003871}
3872
3873DoubleAPFloat::DoubleAPFloat(const fltSemantics &S, APFloat &&First,
3874 APFloat &&Second)
3875 : Semantics(&S),
3876 Floats(new APFloat[2]{std::move(First), std::move(Second)}) {
Stephan Bergmann17c7f702016-12-14 11:57:17 +00003877 assert(Semantics == &semPPCDoubleDouble);
Tim Shenfd1e5aa2017-01-23 22:39:35 +00003878 assert(&Floats[0].getSemantics() == &semIEEEdouble);
Stephan Bergmann17c7f702016-12-14 11:57:17 +00003879 assert(&Floats[1].getSemantics() == &semIEEEdouble);
Tim Shen139a58f2016-10-27 22:52:40 +00003880}
3881
3882DoubleAPFloat::DoubleAPFloat(const DoubleAPFloat &RHS)
3883 : Semantics(RHS.Semantics),
Tim Shenb49915482016-10-28 22:45:33 +00003884 Floats(RHS.Floats ? new APFloat[2]{APFloat(RHS.Floats[0]),
3885 APFloat(RHS.Floats[1])}
3886 : nullptr) {
Stephan Bergmann17c7f702016-12-14 11:57:17 +00003887 assert(Semantics == &semPPCDoubleDouble);
Tim Shen139a58f2016-10-27 22:52:40 +00003888}
3889
3890DoubleAPFloat::DoubleAPFloat(DoubleAPFloat &&RHS)
3891 : Semantics(RHS.Semantics), Floats(std::move(RHS.Floats)) {
Stephan Bergmann17c7f702016-12-14 11:57:17 +00003892 RHS.Semantics = &semBogus;
3893 assert(Semantics == &semPPCDoubleDouble);
Tim Shen139a58f2016-10-27 22:52:40 +00003894}
3895
3896DoubleAPFloat &DoubleAPFloat::operator=(const DoubleAPFloat &RHS) {
Tim Shenb49915482016-10-28 22:45:33 +00003897 if (Semantics == RHS.Semantics && RHS.Floats) {
Tim Shen139a58f2016-10-27 22:52:40 +00003898 Floats[0] = RHS.Floats[0];
3899 Floats[1] = RHS.Floats[1];
3900 } else if (this != &RHS) {
3901 this->~DoubleAPFloat();
3902 new (this) DoubleAPFloat(RHS);
3903 }
3904 return *this;
3905}
3906
Tim Shen7f127622017-01-24 00:19:45 +00003907// Implement addition, subtraction, multiplication and division based on:
Tim Shen44bde892016-12-12 21:59:30 +00003908// "Software for Doubled-Precision Floating-Point Computations",
3909// by Seppo Linnainmaa, ACM TOMS vol 7 no 3, September 1981, pages 272-283.
3910APFloat::opStatus DoubleAPFloat::addImpl(const APFloat &a, const APFloat &aa,
3911 const APFloat &c, const APFloat &cc,
3912 roundingMode RM) {
3913 int Status = opOK;
3914 APFloat z = a;
3915 Status |= z.add(c, RM);
3916 if (!z.isFinite()) {
3917 if (!z.isInfinity()) {
3918 Floats[0] = std::move(z);
Tim Shen7117e692017-01-26 00:11:07 +00003919 Floats[1].makeZero(/* Neg = */ false);
Tim Shen44bde892016-12-12 21:59:30 +00003920 return (opStatus)Status;
3921 }
3922 Status = opOK;
3923 auto AComparedToC = a.compareAbsoluteValue(c);
3924 z = cc;
3925 Status |= z.add(aa, RM);
3926 if (AComparedToC == APFloat::cmpGreaterThan) {
3927 // z = cc + aa + c + a;
3928 Status |= z.add(c, RM);
3929 Status |= z.add(a, RM);
3930 } else {
3931 // z = cc + aa + a + c;
3932 Status |= z.add(a, RM);
3933 Status |= z.add(c, RM);
3934 }
3935 if (!z.isFinite()) {
3936 Floats[0] = std::move(z);
Tim Shen7117e692017-01-26 00:11:07 +00003937 Floats[1].makeZero(/* Neg = */ false);
Tim Shen44bde892016-12-12 21:59:30 +00003938 return (opStatus)Status;
3939 }
3940 Floats[0] = z;
3941 APFloat zz = aa;
3942 Status |= zz.add(cc, RM);
3943 if (AComparedToC == APFloat::cmpGreaterThan) {
3944 // Floats[1] = a - z + c + zz;
3945 Floats[1] = a;
3946 Status |= Floats[1].subtract(z, RM);
3947 Status |= Floats[1].add(c, RM);
3948 Status |= Floats[1].add(zz, RM);
3949 } else {
3950 // Floats[1] = c - z + a + zz;
3951 Floats[1] = c;
3952 Status |= Floats[1].subtract(z, RM);
3953 Status |= Floats[1].add(a, RM);
3954 Status |= Floats[1].add(zz, RM);
3955 }
3956 } else {
3957 // q = a - z;
3958 APFloat q = a;
3959 Status |= q.subtract(z, RM);
3960
3961 // zz = q + c + (a - (q + z)) + aa + cc;
3962 // Compute a - (q + z) as -((q + z) - a) to avoid temporary copies.
3963 auto zz = q;
3964 Status |= zz.add(c, RM);
3965 Status |= q.add(z, RM);
3966 Status |= q.subtract(a, RM);
3967 q.changeSign();
3968 Status |= zz.add(q, RM);
3969 Status |= zz.add(aa, RM);
3970 Status |= zz.add(cc, RM);
3971 if (zz.isZero() && !zz.isNegative()) {
3972 Floats[0] = std::move(z);
Tim Shen7117e692017-01-26 00:11:07 +00003973 Floats[1].makeZero(/* Neg = */ false);
Tim Shen44bde892016-12-12 21:59:30 +00003974 return opOK;
3975 }
3976 Floats[0] = z;
3977 Status |= Floats[0].add(zz, RM);
3978 if (!Floats[0].isFinite()) {
Tim Shen7117e692017-01-26 00:11:07 +00003979 Floats[1].makeZero(/* Neg = */ false);
Tim Shen44bde892016-12-12 21:59:30 +00003980 return (opStatus)Status;
3981 }
3982 Floats[1] = std::move(z);
3983 Status |= Floats[1].subtract(Floats[0], RM);
3984 Status |= Floats[1].add(zz, RM);
3985 }
3986 return (opStatus)Status;
3987}
3988
3989APFloat::opStatus DoubleAPFloat::addWithSpecial(const DoubleAPFloat &LHS,
3990 const DoubleAPFloat &RHS,
3991 DoubleAPFloat &Out,
3992 roundingMode RM) {
3993 if (LHS.getCategory() == fcNaN) {
3994 Out = LHS;
3995 return opOK;
3996 }
3997 if (RHS.getCategory() == fcNaN) {
3998 Out = RHS;
3999 return opOK;
4000 }
4001 if (LHS.getCategory() == fcZero) {
4002 Out = RHS;
4003 return opOK;
4004 }
4005 if (RHS.getCategory() == fcZero) {
4006 Out = LHS;
4007 return opOK;
4008 }
4009 if (LHS.getCategory() == fcInfinity && RHS.getCategory() == fcInfinity &&
4010 LHS.isNegative() != RHS.isNegative()) {
4011 Out.makeNaN(false, Out.isNegative(), nullptr);
4012 return opInvalidOp;
4013 }
4014 if (LHS.getCategory() == fcInfinity) {
4015 Out = LHS;
4016 return opOK;
4017 }
4018 if (RHS.getCategory() == fcInfinity) {
4019 Out = RHS;
4020 return opOK;
4021 }
4022 assert(LHS.getCategory() == fcNormal && RHS.getCategory() == fcNormal);
4023
Tim Shenfd1e5aa2017-01-23 22:39:35 +00004024 APFloat A(LHS.Floats[0]), AA(LHS.Floats[1]), C(RHS.Floats[0]),
Tim Shen44bde892016-12-12 21:59:30 +00004025 CC(RHS.Floats[1]);
Tim Shenfd1e5aa2017-01-23 22:39:35 +00004026 assert(&A.getSemantics() == &semIEEEdouble);
Stephan Bergmann17c7f702016-12-14 11:57:17 +00004027 assert(&AA.getSemantics() == &semIEEEdouble);
Tim Shenfd1e5aa2017-01-23 22:39:35 +00004028 assert(&C.getSemantics() == &semIEEEdouble);
Stephan Bergmann17c7f702016-12-14 11:57:17 +00004029 assert(&CC.getSemantics() == &semIEEEdouble);
Tim Shenfd1e5aa2017-01-23 22:39:35 +00004030 assert(&Out.Floats[0].getSemantics() == &semIEEEdouble);
Stephan Bergmann17c7f702016-12-14 11:57:17 +00004031 assert(&Out.Floats[1].getSemantics() == &semIEEEdouble);
Tim Shenfd1e5aa2017-01-23 22:39:35 +00004032 return Out.addImpl(A, AA, C, CC, RM);
Tim Shen44bde892016-12-12 21:59:30 +00004033}
4034
4035APFloat::opStatus DoubleAPFloat::add(const DoubleAPFloat &RHS,
4036 roundingMode RM) {
4037 return addWithSpecial(*this, RHS, *this, RM);
4038}
4039
4040APFloat::opStatus DoubleAPFloat::subtract(const DoubleAPFloat &RHS,
4041 roundingMode RM) {
4042 changeSign();
4043 auto Ret = add(RHS, RM);
4044 changeSign();
4045 return Ret;
4046}
4047
Tim Shenfd1e5aa2017-01-23 22:39:35 +00004048APFloat::opStatus DoubleAPFloat::multiply(const DoubleAPFloat &RHS,
4049 APFloat::roundingMode RM) {
Tim Shen7f127622017-01-24 00:19:45 +00004050 const auto &LHS = *this;
4051 auto &Out = *this;
4052 /* Interesting observation: For special categories, finding the lowest
4053 common ancestor of the following layered graph gives the correct
4054 return category:
4055
4056 NaN
4057 / \
4058 Zero Inf
4059 \ /
4060 Normal
4061
4062 e.g. NaN * NaN = NaN
4063 Zero * Inf = NaN
4064 Normal * Zero = Zero
4065 Normal * Inf = Inf
4066 */
4067 if (LHS.getCategory() == fcNaN) {
4068 Out = LHS;
4069 return opOK;
4070 }
4071 if (RHS.getCategory() == fcNaN) {
4072 Out = RHS;
4073 return opOK;
4074 }
4075 if ((LHS.getCategory() == fcZero && RHS.getCategory() == fcInfinity) ||
4076 (LHS.getCategory() == fcInfinity && RHS.getCategory() == fcZero)) {
4077 Out.makeNaN(false, false, nullptr);
4078 return opOK;
4079 }
4080 if (LHS.getCategory() == fcZero || LHS.getCategory() == fcInfinity) {
4081 Out = LHS;
4082 return opOK;
4083 }
4084 if (RHS.getCategory() == fcZero || RHS.getCategory() == fcInfinity) {
4085 Out = RHS;
4086 return opOK;
4087 }
4088 assert(LHS.getCategory() == fcNormal && RHS.getCategory() == fcNormal &&
4089 "Special cases not handled exhaustively");
4090
4091 int Status = opOK;
4092 APFloat A = Floats[0], B = Floats[1], C = RHS.Floats[0], D = RHS.Floats[1];
4093 // t = a * c
4094 APFloat T = A;
4095 Status |= T.multiply(C, RM);
4096 if (!T.isFiniteNonZero()) {
4097 Floats[0] = T;
Tim Shen7117e692017-01-26 00:11:07 +00004098 Floats[1].makeZero(/* Neg = */ false);
Tim Shen7f127622017-01-24 00:19:45 +00004099 return (opStatus)Status;
4100 }
4101
4102 // tau = fmsub(a, c, t), that is -fmadd(-a, c, t).
4103 APFloat Tau = A;
4104 T.changeSign();
4105 Status |= Tau.fusedMultiplyAdd(C, T, RM);
4106 T.changeSign();
4107 {
4108 // v = a * d
4109 APFloat V = A;
4110 Status |= V.multiply(D, RM);
4111 // w = b * c
4112 APFloat W = B;
4113 Status |= W.multiply(C, RM);
4114 Status |= V.add(W, RM);
4115 // tau += v + w
4116 Status |= Tau.add(V, RM);
4117 }
4118 // u = t + tau
4119 APFloat U = T;
4120 Status |= U.add(Tau, RM);
4121
4122 Floats[0] = U;
4123 if (!U.isFinite()) {
Tim Shen7117e692017-01-26 00:11:07 +00004124 Floats[1].makeZero(/* Neg = */ false);
Tim Shen7f127622017-01-24 00:19:45 +00004125 } else {
4126 // Floats[1] = (t - u) + tau
4127 Status |= T.subtract(U, RM);
4128 Status |= T.add(Tau, RM);
4129 Floats[1] = T;
4130 }
4131 return (opStatus)Status;
Tim Shenfd1e5aa2017-01-23 22:39:35 +00004132}
4133
4134APFloat::opStatus DoubleAPFloat::divide(const DoubleAPFloat &RHS,
4135 APFloat::roundingMode RM) {
4136 assert(Semantics == &semPPCDoubleDouble && "Unexpected Semantics");
4137 APFloat Tmp(semPPCDoubleDoubleLegacy, bitcastToAPInt());
4138 auto Ret =
4139 Tmp.divide(APFloat(semPPCDoubleDoubleLegacy, RHS.bitcastToAPInt()), RM);
4140 *this = DoubleAPFloat(semPPCDoubleDouble, Tmp.bitcastToAPInt());
4141 return Ret;
4142}
4143
4144APFloat::opStatus DoubleAPFloat::remainder(const DoubleAPFloat &RHS) {
4145 assert(Semantics == &semPPCDoubleDouble && "Unexpected Semantics");
4146 APFloat Tmp(semPPCDoubleDoubleLegacy, bitcastToAPInt());
4147 auto Ret =
4148 Tmp.remainder(APFloat(semPPCDoubleDoubleLegacy, RHS.bitcastToAPInt()));
4149 *this = DoubleAPFloat(semPPCDoubleDouble, Tmp.bitcastToAPInt());
4150 return Ret;
4151}
4152
4153APFloat::opStatus DoubleAPFloat::mod(const DoubleAPFloat &RHS) {
4154 assert(Semantics == &semPPCDoubleDouble && "Unexpected Semantics");
4155 APFloat Tmp(semPPCDoubleDoubleLegacy, bitcastToAPInt());
4156 auto Ret = Tmp.mod(APFloat(semPPCDoubleDoubleLegacy, RHS.bitcastToAPInt()));
4157 *this = DoubleAPFloat(semPPCDoubleDouble, Tmp.bitcastToAPInt());
4158 return Ret;
4159}
4160
4161APFloat::opStatus
4162DoubleAPFloat::fusedMultiplyAdd(const DoubleAPFloat &Multiplicand,
4163 const DoubleAPFloat &Addend,
4164 APFloat::roundingMode RM) {
4165 assert(Semantics == &semPPCDoubleDouble && "Unexpected Semantics");
4166 APFloat Tmp(semPPCDoubleDoubleLegacy, bitcastToAPInt());
4167 auto Ret = Tmp.fusedMultiplyAdd(
4168 APFloat(semPPCDoubleDoubleLegacy, Multiplicand.bitcastToAPInt()),
4169 APFloat(semPPCDoubleDoubleLegacy, Addend.bitcastToAPInt()), RM);
4170 *this = DoubleAPFloat(semPPCDoubleDouble, Tmp.bitcastToAPInt());
4171 return Ret;
4172}
4173
4174APFloat::opStatus DoubleAPFloat::roundToIntegral(APFloat::roundingMode RM) {
4175 assert(Semantics == &semPPCDoubleDouble && "Unexpected Semantics");
4176 APFloat Tmp(semPPCDoubleDoubleLegacy, bitcastToAPInt());
4177 auto Ret = Tmp.roundToIntegral(RM);
4178 *this = DoubleAPFloat(semPPCDoubleDouble, Tmp.bitcastToAPInt());
4179 return Ret;
4180}
4181
Tim Shen44bde892016-12-12 21:59:30 +00004182void DoubleAPFloat::changeSign() {
4183 Floats[0].changeSign();
4184 Floats[1].changeSign();
4185}
4186
4187APFloat::cmpResult
4188DoubleAPFloat::compareAbsoluteValue(const DoubleAPFloat &RHS) const {
4189 auto Result = Floats[0].compareAbsoluteValue(RHS.Floats[0]);
4190 if (Result != cmpEqual)
4191 return Result;
4192 Result = Floats[1].compareAbsoluteValue(RHS.Floats[1]);
4193 if (Result == cmpLessThan || Result == cmpGreaterThan) {
4194 auto Against = Floats[0].isNegative() ^ Floats[1].isNegative();
4195 auto RHSAgainst = RHS.Floats[0].isNegative() ^ RHS.Floats[1].isNegative();
4196 if (Against && !RHSAgainst)
4197 return cmpLessThan;
4198 if (!Against && RHSAgainst)
4199 return cmpGreaterThan;
4200 if (!Against && !RHSAgainst)
4201 return Result;
4202 if (Against && RHSAgainst)
4203 return (cmpResult)(cmpLessThan + cmpGreaterThan - Result);
4204 }
4205 return Result;
4206}
4207
4208APFloat::fltCategory DoubleAPFloat::getCategory() const {
4209 return Floats[0].getCategory();
4210}
4211
4212bool DoubleAPFloat::isNegative() const { return Floats[0].isNegative(); }
4213
4214void DoubleAPFloat::makeInf(bool Neg) {
4215 Floats[0].makeInf(Neg);
Tim Shen7117e692017-01-26 00:11:07 +00004216 Floats[1].makeZero(/* Neg = */ false);
Tim Shen44bde892016-12-12 21:59:30 +00004217}
4218
Tim Shenfd1e5aa2017-01-23 22:39:35 +00004219void DoubleAPFloat::makeZero(bool Neg) {
4220 Floats[0].makeZero(Neg);
Tim Shen7117e692017-01-26 00:11:07 +00004221 Floats[1].makeZero(/* Neg = */ false);
Tim Shenfd1e5aa2017-01-23 22:39:35 +00004222}
4223
4224void DoubleAPFloat::makeLargest(bool Neg) {
4225 assert(Semantics == &semPPCDoubleDouble && "Unexpected Semantics");
4226 Floats[0] = APFloat(semIEEEdouble, APInt(64, 0x7fefffffffffffffull));
4227 Floats[1] = APFloat(semIEEEdouble, APInt(64, 0x7c8ffffffffffffeull));
4228 if (Neg)
4229 changeSign();
4230}
4231
4232void DoubleAPFloat::makeSmallest(bool Neg) {
4233 assert(Semantics == &semPPCDoubleDouble && "Unexpected Semantics");
4234 Floats[0].makeSmallest(Neg);
Tim Shen7117e692017-01-26 00:11:07 +00004235 Floats[1].makeZero(/* Neg = */ false);
Tim Shenfd1e5aa2017-01-23 22:39:35 +00004236}
4237
4238void DoubleAPFloat::makeSmallestNormalized(bool Neg) {
4239 assert(Semantics == &semPPCDoubleDouble && "Unexpected Semantics");
4240 Floats[0] = APFloat(semIEEEdouble, APInt(64, 0x0360000000000000ull));
4241 if (Neg)
4242 Floats[0].changeSign();
Tim Shen7117e692017-01-26 00:11:07 +00004243 Floats[1].makeZero(/* Neg = */ false);
Tim Shenfd1e5aa2017-01-23 22:39:35 +00004244}
4245
Tim Shen44bde892016-12-12 21:59:30 +00004246void DoubleAPFloat::makeNaN(bool SNaN, bool Neg, const APInt *fill) {
4247 Floats[0].makeNaN(SNaN, Neg, fill);
Tim Shen7117e692017-01-26 00:11:07 +00004248 Floats[1].makeZero(/* Neg = */ false);
Tim Shen44bde892016-12-12 21:59:30 +00004249}
4250
Tim Shenfd1e5aa2017-01-23 22:39:35 +00004251APFloat::cmpResult DoubleAPFloat::compare(const DoubleAPFloat &RHS) const {
4252 auto Result = Floats[0].compare(RHS.Floats[0]);
Tim Shen7117e692017-01-26 00:11:07 +00004253 // |Float[0]| > |Float[1]|
Tim Shenfd1e5aa2017-01-23 22:39:35 +00004254 if (Result == APFloat::cmpEqual)
4255 return Floats[1].compare(RHS.Floats[1]);
4256 return Result;
4257}
4258
4259bool DoubleAPFloat::bitwiseIsEqual(const DoubleAPFloat &RHS) const {
4260 return Floats[0].bitwiseIsEqual(RHS.Floats[0]) &&
4261 Floats[1].bitwiseIsEqual(RHS.Floats[1]);
4262}
4263
4264hash_code hash_value(const DoubleAPFloat &Arg) {
4265 if (Arg.Floats)
4266 return hash_combine(hash_value(Arg.Floats[0]), hash_value(Arg.Floats[1]));
4267 return hash_combine(Arg.Semantics);
4268}
4269
4270APInt DoubleAPFloat::bitcastToAPInt() const {
4271 assert(Semantics == &semPPCDoubleDouble && "Unexpected Semantics");
4272 uint64_t Data[] = {
4273 Floats[0].bitcastToAPInt().getRawData()[0],
4274 Floats[1].bitcastToAPInt().getRawData()[0],
4275 };
4276 return APInt(128, 2, Data);
4277}
4278
4279APFloat::opStatus DoubleAPFloat::convertFromString(StringRef S,
4280 roundingMode RM) {
4281 assert(Semantics == &semPPCDoubleDouble && "Unexpected Semantics");
4282 APFloat Tmp(semPPCDoubleDoubleLegacy);
4283 auto Ret = Tmp.convertFromString(S, RM);
4284 *this = DoubleAPFloat(semPPCDoubleDouble, Tmp.bitcastToAPInt());
4285 return Ret;
4286}
4287
4288APFloat::opStatus DoubleAPFloat::next(bool nextDown) {
4289 assert(Semantics == &semPPCDoubleDouble && "Unexpected Semantics");
4290 APFloat Tmp(semPPCDoubleDoubleLegacy, bitcastToAPInt());
4291 auto Ret = Tmp.next(nextDown);
4292 *this = DoubleAPFloat(semPPCDoubleDouble, Tmp.bitcastToAPInt());
4293 return Ret;
4294}
4295
4296APFloat::opStatus DoubleAPFloat::convertToInteger(integerPart *Input,
4297 unsigned int Width,
4298 bool IsSigned,
4299 roundingMode RM,
4300 bool *IsExact) const {
4301 assert(Semantics == &semPPCDoubleDouble && "Unexpected Semantics");
4302 return APFloat(semPPCDoubleDoubleLegacy, bitcastToAPInt())
4303 .convertToInteger(Input, Width, IsSigned, RM, IsExact);
4304}
4305
4306APFloat::opStatus DoubleAPFloat::convertFromAPInt(const APInt &Input,
4307 bool IsSigned,
4308 roundingMode RM) {
4309 assert(Semantics == &semPPCDoubleDouble && "Unexpected Semantics");
4310 APFloat Tmp(semPPCDoubleDoubleLegacy);
4311 auto Ret = Tmp.convertFromAPInt(Input, IsSigned, RM);
4312 *this = DoubleAPFloat(semPPCDoubleDouble, Tmp.bitcastToAPInt());
4313 return Ret;
4314}
4315
4316APFloat::opStatus
4317DoubleAPFloat::convertFromSignExtendedInteger(const integerPart *Input,
4318 unsigned int InputSize,
4319 bool IsSigned, roundingMode RM) {
4320 assert(Semantics == &semPPCDoubleDouble && "Unexpected Semantics");
4321 APFloat Tmp(semPPCDoubleDoubleLegacy);
4322 auto Ret = Tmp.convertFromSignExtendedInteger(Input, InputSize, IsSigned, RM);
4323 *this = DoubleAPFloat(semPPCDoubleDouble, Tmp.bitcastToAPInt());
4324 return Ret;
4325}
4326
4327APFloat::opStatus
4328DoubleAPFloat::convertFromZeroExtendedInteger(const integerPart *Input,
4329 unsigned int InputSize,
4330 bool IsSigned, roundingMode RM) {
4331 assert(Semantics == &semPPCDoubleDouble && "Unexpected Semantics");
4332 APFloat Tmp(semPPCDoubleDoubleLegacy);
4333 auto Ret = Tmp.convertFromZeroExtendedInteger(Input, InputSize, IsSigned, RM);
4334 *this = DoubleAPFloat(semPPCDoubleDouble, Tmp.bitcastToAPInt());
4335 return Ret;
4336}
4337
4338unsigned int DoubleAPFloat::convertToHexString(char *DST,
4339 unsigned int HexDigits,
4340 bool UpperCase,
4341 roundingMode RM) const {
4342 assert(Semantics == &semPPCDoubleDouble && "Unexpected Semantics");
4343 return APFloat(semPPCDoubleDoubleLegacy, bitcastToAPInt())
4344 .convertToHexString(DST, HexDigits, UpperCase, RM);
4345}
4346
4347bool DoubleAPFloat::isDenormal() const {
4348 return getCategory() == fcNormal &&
4349 (Floats[0].isDenormal() || Floats[1].isDenormal() ||
Tim Shen7117e692017-01-26 00:11:07 +00004350 // (double)(Hi + Lo) == Hi defines a normal number.
Tim Shenfd1e5aa2017-01-23 22:39:35 +00004351 Floats[0].compare(Floats[0] + Floats[1]) != cmpEqual);
4352}
4353
4354bool DoubleAPFloat::isSmallest() const {
4355 if (getCategory() != fcNormal)
4356 return false;
4357 DoubleAPFloat Tmp(*this);
4358 Tmp.makeSmallest(this->isNegative());
4359 return Tmp.compare(*this) == cmpEqual;
4360}
4361
4362bool DoubleAPFloat::isLargest() const {
4363 if (getCategory() != fcNormal)
4364 return false;
4365 DoubleAPFloat Tmp(*this);
4366 Tmp.makeLargest(this->isNegative());
4367 return Tmp.compare(*this) == cmpEqual;
4368}
4369
4370bool DoubleAPFloat::isInteger() const {
4371 assert(Semantics == &semPPCDoubleDouble && "Unexpected Semantics");
4372 APFloat Tmp(semPPCDoubleDoubleLegacy);
4373 (void)Tmp.add(Floats[0], rmNearestTiesToEven);
4374 (void)Tmp.add(Floats[1], rmNearestTiesToEven);
4375 return Tmp.isInteger();
4376}
4377
4378void DoubleAPFloat::toString(SmallVectorImpl<char> &Str,
4379 unsigned FormatPrecision,
4380 unsigned FormatMaxPadding) const {
4381 assert(Semantics == &semPPCDoubleDouble && "Unexpected Semantics");
4382 APFloat(semPPCDoubleDoubleLegacy, bitcastToAPInt())
4383 .toString(Str, FormatPrecision, FormatMaxPadding);
4384}
4385
4386bool DoubleAPFloat::getExactInverse(APFloat *inv) const {
4387 assert(Semantics == &semPPCDoubleDouble && "Unexpected Semantics");
4388 APFloat Tmp(semPPCDoubleDoubleLegacy, bitcastToAPInt());
4389 if (!inv)
4390 return Tmp.getExactInverse(nullptr);
4391 APFloat Inv(semPPCDoubleDoubleLegacy);
4392 auto Ret = Tmp.getExactInverse(&Inv);
4393 *inv = APFloat(semPPCDoubleDouble, Inv.bitcastToAPInt());
4394 return Ret;
4395}
4396
4397DoubleAPFloat scalbn(DoubleAPFloat Arg, int Exp, APFloat::roundingMode RM) {
4398 assert(Arg.Semantics == &semPPCDoubleDouble && "Unexpected Semantics");
4399 return DoubleAPFloat(semPPCDoubleDouble, scalbn(Arg.Floats[0], Exp, RM),
4400 scalbn(Arg.Floats[1], Exp, RM));
4401}
4402
4403DoubleAPFloat frexp(const DoubleAPFloat &Arg, int &Exp,
4404 APFloat::roundingMode RM) {
4405 assert(Arg.Semantics == &semPPCDoubleDouble && "Unexpected Semantics");
4406 APFloat First = frexp(Arg.Floats[0], Exp, RM);
4407 APFloat Second = Arg.Floats[1];
4408 if (Arg.getCategory() == APFloat::fcNormal)
4409 Second = scalbn(Second, -Exp, RM);
4410 return DoubleAPFloat(semPPCDoubleDouble, std::move(First), std::move(Second));
4411}
4412
Tim Shen85de51d2016-10-25 19:55:59 +00004413} // End detail namespace
4414
Tim Shen398f90f2016-11-06 07:38:37 +00004415APFloat::Storage::Storage(IEEEFloat F, const fltSemantics &Semantics) {
4416 if (usesLayout<IEEEFloat>(Semantics)) {
4417 new (&IEEE) IEEEFloat(std::move(F));
Tim Shen7b57ac42016-12-21 02:39:21 +00004418 return;
4419 }
4420 if (usesLayout<DoubleAPFloat>(Semantics)) {
Tim Shen398f90f2016-11-06 07:38:37 +00004421 new (&Double)
4422 DoubleAPFloat(Semantics, APFloat(std::move(F), F.getSemantics()),
Stephan Bergmann17c7f702016-12-14 11:57:17 +00004423 APFloat(semIEEEdouble));
Tim Shen7b57ac42016-12-21 02:39:21 +00004424 return;
Tim Shen398f90f2016-11-06 07:38:37 +00004425 }
Tim Shen7b57ac42016-12-21 02:39:21 +00004426 llvm_unreachable("Unexpected semantics");
Tim Shen398f90f2016-11-06 07:38:37 +00004427}
4428
Tim Shen85de51d2016-10-25 19:55:59 +00004429APFloat::opStatus APFloat::convertFromString(StringRef Str, roundingMode RM) {
Tim Shen601ba8c2017-01-27 02:11:07 +00004430 APFLOAT_DISPATCH_ON_SEMANTICS(convertFromString(Str, RM));
Tim Shen85de51d2016-10-25 19:55:59 +00004431}
4432
Tim Shenfd1e5aa2017-01-23 22:39:35 +00004433hash_code hash_value(const APFloat &Arg) {
4434 if (APFloat::usesLayout<detail::IEEEFloat>(Arg.getSemantics()))
4435 return hash_value(Arg.U.IEEE);
4436 if (APFloat::usesLayout<detail::DoubleAPFloat>(Arg.getSemantics()))
4437 return hash_value(Arg.U.Double);
4438 llvm_unreachable("Unexpected semantics");
4439}
Tim Shen85de51d2016-10-25 19:55:59 +00004440
4441APFloat::APFloat(const fltSemantics &Semantics, StringRef S)
Tim Shen139a58f2016-10-27 22:52:40 +00004442 : APFloat(Semantics) {
4443 convertFromString(S, rmNearestTiesToEven);
4444}
4445
4446APFloat::opStatus APFloat::convert(const fltSemantics &ToSemantics,
4447 roundingMode RM, bool *losesInfo) {
4448 if (&getSemantics() == &ToSemantics)
4449 return opOK;
4450 if (usesLayout<IEEEFloat>(getSemantics()) &&
Tim Shen7b57ac42016-12-21 02:39:21 +00004451 usesLayout<IEEEFloat>(ToSemantics))
Tim Shen139a58f2016-10-27 22:52:40 +00004452 return U.IEEE.convert(ToSemantics, RM, losesInfo);
Tim Shen7b57ac42016-12-21 02:39:21 +00004453 if (usesLayout<IEEEFloat>(getSemantics()) &&
4454 usesLayout<DoubleAPFloat>(ToSemantics)) {
Stephan Bergmann17c7f702016-12-14 11:57:17 +00004455 assert(&ToSemantics == &semPPCDoubleDouble);
Tim Shenfd1e5aa2017-01-23 22:39:35 +00004456 auto Ret = U.IEEE.convert(semPPCDoubleDoubleLegacy, RM, losesInfo);
4457 *this = APFloat(ToSemantics, U.IEEE.bitcastToAPInt());
Tim Shen139a58f2016-10-27 22:52:40 +00004458 return Ret;
Tim Shen7b57ac42016-12-21 02:39:21 +00004459 }
4460 if (usesLayout<DoubleAPFloat>(getSemantics()) &&
4461 usesLayout<IEEEFloat>(ToSemantics)) {
Tim Shen139a58f2016-10-27 22:52:40 +00004462 auto Ret = getIEEE().convert(ToSemantics, RM, losesInfo);
Tim Shen398f90f2016-11-06 07:38:37 +00004463 *this = APFloat(std::move(getIEEE()), ToSemantics);
Tim Shen139a58f2016-10-27 22:52:40 +00004464 return Ret;
Tim Shen139a58f2016-10-27 22:52:40 +00004465 }
Tim Shen7b57ac42016-12-21 02:39:21 +00004466 llvm_unreachable("Unexpected semantics");
Tim Shen139a58f2016-10-27 22:52:40 +00004467}
Tim Shen85de51d2016-10-25 19:55:59 +00004468
Tim Shen398f90f2016-11-06 07:38:37 +00004469APFloat APFloat::getAllOnesValue(unsigned BitWidth, bool isIEEE) {
4470 if (isIEEE) {
4471 switch (BitWidth) {
4472 case 16:
Stephan Bergmann17c7f702016-12-14 11:57:17 +00004473 return APFloat(semIEEEhalf, APInt::getAllOnesValue(BitWidth));
Tim Shen398f90f2016-11-06 07:38:37 +00004474 case 32:
Stephan Bergmann17c7f702016-12-14 11:57:17 +00004475 return APFloat(semIEEEsingle, APInt::getAllOnesValue(BitWidth));
Tim Shen398f90f2016-11-06 07:38:37 +00004476 case 64:
Stephan Bergmann17c7f702016-12-14 11:57:17 +00004477 return APFloat(semIEEEdouble, APInt::getAllOnesValue(BitWidth));
Tim Shen398f90f2016-11-06 07:38:37 +00004478 case 80:
Stephan Bergmann17c7f702016-12-14 11:57:17 +00004479 return APFloat(semX87DoubleExtended, APInt::getAllOnesValue(BitWidth));
Tim Shen398f90f2016-11-06 07:38:37 +00004480 case 128:
Stephan Bergmann17c7f702016-12-14 11:57:17 +00004481 return APFloat(semIEEEquad, APInt::getAllOnesValue(BitWidth));
Tim Shen398f90f2016-11-06 07:38:37 +00004482 default:
4483 llvm_unreachable("Unknown floating bit width");
4484 }
4485 } else {
4486 assert(BitWidth == 128);
Stephan Bergmann17c7f702016-12-14 11:57:17 +00004487 return APFloat(semPPCDoubleDouble, APInt::getAllOnesValue(BitWidth));
Tim Shen398f90f2016-11-06 07:38:37 +00004488 }
4489}
4490
Tim Shen44bde892016-12-12 21:59:30 +00004491void APFloat::print(raw_ostream &OS) const {
4492 SmallVector<char, 16> Buffer;
4493 toString(Buffer);
4494 OS << Buffer << "\n";
4495}
4496
4497void APFloat::dump() const { print(dbgs()); }
4498
Tim Shenfd1e5aa2017-01-23 22:39:35 +00004499void APFloat::Profile(FoldingSetNodeID &NID) const {
4500 NID.Add(bitcastToAPInt());
4501}
4502
4503/* Same as convertToInteger(integerPart*, ...), except the result is returned in
4504 an APSInt, whose initial bit-width and signed-ness are used to determine the
4505 precision of the conversion.
4506 */
4507APFloat::opStatus APFloat::convertToInteger(APSInt &result,
4508 roundingMode rounding_mode,
4509 bool *isExact) const {
4510 unsigned bitWidth = result.getBitWidth();
4511 SmallVector<uint64_t, 4> parts(result.getNumWords());
4512 opStatus status = convertToInteger(parts.data(), bitWidth, result.isSigned(),
4513 rounding_mode, isExact);
4514 // Keeps the original signed-ness.
4515 result = APInt(bitWidth, parts);
4516 return status;
4517}
4518
Tim Shen85de51d2016-10-25 19:55:59 +00004519} // End llvm namespace
Tim Shen601ba8c2017-01-27 02:11:07 +00004520
4521#undef APFLOAT_DISPATCH_ON_SEMANTICS