blob: 3ebed5b5ab8c2d7a6ea15f2b31a6925e520e1c18 [file] [log] [blame]
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001//===-- APFloat.cpp - Implement APFloat class -----------------------------===//
2//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00006//
7//===----------------------------------------------------------------------===//
8//
9// This file implements a class to represent arbitrary precision floating
10// point values and provide a variety of arithmetic operations on them.
11//
12//===----------------------------------------------------------------------===//
13
Chris Lattnere5256752007-12-08 19:00:03 +000014#include "llvm/ADT/APFloat.h"
Jeffrey Yasskin03b81a22011-07-15 07:04:56 +000015#include "llvm/ADT/APSInt.h"
Mehdi Amini47b292d2016-04-16 07:51:28 +000016#include "llvm/ADT/ArrayRef.h"
Ted Kremenek6f30a072008-02-11 17:24:50 +000017#include "llvm/ADT/FoldingSet.h"
Chandler Carruth71bd7d12012-03-04 12:02:57 +000018#include "llvm/ADT/Hashing.h"
Jordan Rosee1f76582013-01-18 21:45:30 +000019#include "llvm/ADT/StringExtras.h"
Chandler Carruth71bd7d12012-03-04 12:02:57 +000020#include "llvm/ADT/StringRef.h"
Nico Weber432a3882018-04-30 14:59:11 +000021#include "llvm/Config/llvm-config.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. */
Craig Topperc85be522017-06-18 18:15:41 +000050static_assert(APFloatBase::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;
Craig Topperc85be522017-06-18 18:15:41 +0000152 const unsigned int maxPowerOfFiveParts = 2 + ((maxPowerOfFiveExponent * 815) / (351 * APFloatBase::integerPartWidth));
Tim Shen85de51d2016-10-25 19:55:59 +0000153
154 unsigned int APFloatBase::semanticsPrecision(const fltSemantics &semantics) {
155 return semantics.precision;
156 }
157 APFloatBase::ExponentType
158 APFloatBase::semanticsMaxExponent(const fltSemantics &semantics) {
159 return semantics.maxExponent;
160 }
161 APFloatBase::ExponentType
162 APFloatBase::semanticsMinExponent(const fltSemantics &semantics) {
163 return semantics.minExponent;
164 }
165 unsigned int APFloatBase::semanticsSizeInBits(const fltSemantics &semantics) {
166 return semantics.sizeInBits;
167 }
168
169 unsigned APFloatBase::getSizeInBits(const fltSemantics &Sem) {
170 return Sem.sizeInBits;
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000171}
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000172
Chris Lattner91702092009-03-12 23:59:55 +0000173/* A bunch of private, handy routines. */
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000174
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000175static inline unsigned int
Chris Lattner91702092009-03-12 23:59:55 +0000176partCountForBits(unsigned int bits)
177{
Craig Topperc85be522017-06-18 18:15:41 +0000178 return ((bits) + APFloatBase::integerPartWidth - 1) / APFloatBase::integerPartWidth;
Chris Lattner91702092009-03-12 23:59:55 +0000179}
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000180
Chris Lattner91702092009-03-12 23:59:55 +0000181/* Returns 0U-9U. Return values >= 10U are not digits. */
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000182static inline unsigned int
Chris Lattner91702092009-03-12 23:59:55 +0000183decDigitValue(unsigned int c)
184{
185 return c - '0';
186}
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000187
Chris Lattner91702092009-03-12 23:59:55 +0000188/* Return the value of a decimal exponent of the form
189 [+-]ddddddd.
Neil Booth4ed401b2007-10-14 10:16:12 +0000190
Chris Lattner91702092009-03-12 23:59:55 +0000191 If the exponent overflows, returns a large exponent with the
192 appropriate sign. */
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000193static int
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000194readExponent(StringRef::iterator begin, StringRef::iterator end)
Chris Lattner91702092009-03-12 23:59:55 +0000195{
196 bool isNegative;
197 unsigned int absExponent;
198 const unsigned int overlargeExponent = 24000; /* FIXME. */
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000199 StringRef::iterator p = begin;
200
201 assert(p != end && "Exponent has no digits");
Neil Booth4ed401b2007-10-14 10:16:12 +0000202
Chris Lattner91702092009-03-12 23:59:55 +0000203 isNegative = (*p == '-');
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000204 if (*p == '-' || *p == '+') {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000205 p++;
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000206 assert(p != end && "Exponent has no digits");
207 }
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000208
Chris Lattner91702092009-03-12 23:59:55 +0000209 absExponent = decDigitValue(*p++);
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000210 assert(absExponent < 10U && "Invalid character in exponent");
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000211
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000212 for (; p != end; ++p) {
Chris Lattner91702092009-03-12 23:59:55 +0000213 unsigned int value;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000214
Chris Lattner91702092009-03-12 23:59:55 +0000215 value = decDigitValue(*p);
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000216 assert(value < 10U && "Invalid character in exponent");
Chris Lattner91702092009-03-12 23:59:55 +0000217
Chris Lattner91702092009-03-12 23:59:55 +0000218 value += absExponent * 10;
219 if (absExponent >= overlargeExponent) {
220 absExponent = overlargeExponent;
Dale Johannesen370c77c2010-08-19 17:58:35 +0000221 p = end; /* outwit assert below */
Chris Lattner91702092009-03-12 23:59:55 +0000222 break;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000223 }
Chris Lattner91702092009-03-12 23:59:55 +0000224 absExponent = value;
225 }
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000226
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000227 assert(p == end && "Invalid exponent in exponent");
228
Chris Lattner91702092009-03-12 23:59:55 +0000229 if (isNegative)
230 return -(int) absExponent;
231 else
232 return (int) absExponent;
233}
234
235/* This is ugly and needs cleaning up, but I don't immediately see
236 how whilst remaining safe. */
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000237static int
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000238totalExponent(StringRef::iterator p, StringRef::iterator end,
239 int exponentAdjustment)
Chris Lattner91702092009-03-12 23:59:55 +0000240{
241 int unsignedExponent;
242 bool negative, overflow;
Ted Kremenek3c4408c2011-01-23 17:05:06 +0000243 int exponent = 0;
Chris Lattner91702092009-03-12 23:59:55 +0000244
Erick Tryzelaarda666c82009-08-20 23:30:43 +0000245 assert(p != end && "Exponent has no digits");
246
Chris Lattner91702092009-03-12 23:59:55 +0000247 negative = *p == '-';
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000248 if (*p == '-' || *p == '+') {
Chris Lattner91702092009-03-12 23:59:55 +0000249 p++;
Erick Tryzelaarda666c82009-08-20 23:30:43 +0000250 assert(p != end && "Exponent has no digits");
251 }
Chris Lattner91702092009-03-12 23:59:55 +0000252
253 unsignedExponent = 0;
254 overflow = false;
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000255 for (; p != end; ++p) {
Chris Lattner91702092009-03-12 23:59:55 +0000256 unsigned int value;
257
258 value = decDigitValue(*p);
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000259 assert(value < 10U && "Invalid character in exponent");
Chris Lattner91702092009-03-12 23:59:55 +0000260
Chris Lattner91702092009-03-12 23:59:55 +0000261 unsignedExponent = unsignedExponent * 10 + value;
Richard Smith156d9202012-08-24 00:01:19 +0000262 if (unsignedExponent > 32767) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000263 overflow = true;
Richard Smith156d9202012-08-24 00:01:19 +0000264 break;
265 }
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000266 }
267
Abramo Bagnaraa41d7ae2011-01-06 16:55:14 +0000268 if (exponentAdjustment > 32767 || exponentAdjustment < -32768)
Chris Lattner91702092009-03-12 23:59:55 +0000269 overflow = true;
270
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000271 if (!overflow) {
Chris Lattner91702092009-03-12 23:59:55 +0000272 exponent = unsignedExponent;
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000273 if (negative)
Chris Lattner91702092009-03-12 23:59:55 +0000274 exponent = -exponent;
275 exponent += exponentAdjustment;
Abramo Bagnaraa41d7ae2011-01-06 16:55:14 +0000276 if (exponent > 32767 || exponent < -32768)
Chris Lattner91702092009-03-12 23:59:55 +0000277 overflow = true;
278 }
279
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000280 if (overflow)
Abramo Bagnaraa41d7ae2011-01-06 16:55:14 +0000281 exponent = negative ? -32768: 32767;
Chris Lattner91702092009-03-12 23:59:55 +0000282
283 return exponent;
284}
285
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000286static StringRef::iterator
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000287skipLeadingZeroesAndAnyDot(StringRef::iterator begin, StringRef::iterator end,
288 StringRef::iterator *dot)
Chris Lattner91702092009-03-12 23:59:55 +0000289{
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000290 StringRef::iterator p = begin;
291 *dot = end;
Nick Lewycky095b92e2014-09-06 01:16:42 +0000292 while (p != end && *p == '0')
Chris Lattner91702092009-03-12 23:59:55 +0000293 p++;
294
Nick Lewycky095b92e2014-09-06 01:16:42 +0000295 if (p != end && *p == '.') {
Chris Lattner91702092009-03-12 23:59:55 +0000296 *dot = p++;
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000297
Erick Tryzelaarda666c82009-08-20 23:30:43 +0000298 assert(end - begin != 1 && "Significand has no digits");
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000299
Nick Lewycky095b92e2014-09-06 01:16:42 +0000300 while (p != end && *p == '0')
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000301 p++;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000302 }
303
Chris Lattner91702092009-03-12 23:59:55 +0000304 return p;
305}
Neil Booth4ed401b2007-10-14 10:16:12 +0000306
Chris Lattner91702092009-03-12 23:59:55 +0000307/* Given a normal decimal floating point number of the form
Neil Booth4ed401b2007-10-14 10:16:12 +0000308
Chris Lattner91702092009-03-12 23:59:55 +0000309 dddd.dddd[eE][+-]ddd
Neil Booth91305512007-10-15 15:00:55 +0000310
Chris Lattner91702092009-03-12 23:59:55 +0000311 where the decimal point and exponent are optional, fill out the
312 structure D. Exponent is appropriate if the significand is
313 treated as an integer, and normalizedExponent if the significand
314 is taken to have the decimal point after a single leading
315 non-zero digit.
Neil Booth4ed401b2007-10-14 10:16:12 +0000316
Chris Lattner91702092009-03-12 23:59:55 +0000317 If the value is zero, V->firstSigDigit points to a non-digit, and
318 the return exponent is zero.
319*/
320struct decimalInfo {
321 const char *firstSigDigit;
322 const char *lastSigDigit;
323 int exponent;
324 int normalizedExponent;
325};
Neil Booth4ed401b2007-10-14 10:16:12 +0000326
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000327static void
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000328interpretDecimal(StringRef::iterator begin, StringRef::iterator end,
329 decimalInfo *D)
Chris Lattner91702092009-03-12 23:59:55 +0000330{
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000331 StringRef::iterator dot = end;
332 StringRef::iterator p = skipLeadingZeroesAndAnyDot (begin, end, &dot);
Neil Booth4ed401b2007-10-14 10:16:12 +0000333
Chris Lattner91702092009-03-12 23:59:55 +0000334 D->firstSigDigit = p;
335 D->exponent = 0;
336 D->normalizedExponent = 0;
337
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000338 for (; p != end; ++p) {
Chris Lattner91702092009-03-12 23:59:55 +0000339 if (*p == '.') {
Erick Tryzelaarda666c82009-08-20 23:30:43 +0000340 assert(dot == end && "String contains multiple dots");
Chris Lattner91702092009-03-12 23:59:55 +0000341 dot = p++;
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000342 if (p == end)
343 break;
Neil Booth4ed401b2007-10-14 10:16:12 +0000344 }
Chris Lattner91702092009-03-12 23:59:55 +0000345 if (decDigitValue(*p) >= 10U)
346 break;
Chris Lattner91702092009-03-12 23:59:55 +0000347 }
Neil Booth4ed401b2007-10-14 10:16:12 +0000348
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000349 if (p != end) {
Erick Tryzelaarda666c82009-08-20 23:30:43 +0000350 assert((*p == 'e' || *p == 'E') && "Invalid character in significand");
351 assert(p != begin && "Significand has no digits");
352 assert((dot == end || p - begin != 1) && "Significand has no digits");
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000353
354 /* p points to the first non-digit in the string */
Erick Tryzelaarda666c82009-08-20 23:30:43 +0000355 D->exponent = readExponent(p + 1, end);
Neil Booth4ed401b2007-10-14 10:16:12 +0000356
Chris Lattner91702092009-03-12 23:59:55 +0000357 /* Implied decimal point? */
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000358 if (dot == end)
Chris Lattner91702092009-03-12 23:59:55 +0000359 dot = p;
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000360 }
Neil Booth4ed401b2007-10-14 10:16:12 +0000361
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000362 /* If number is all zeroes accept any exponent. */
363 if (p != D->firstSigDigit) {
Chris Lattner91702092009-03-12 23:59:55 +0000364 /* Drop insignificant trailing zeroes. */
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000365 if (p != begin) {
Neil Booth4ed401b2007-10-14 10:16:12 +0000366 do
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000367 do
368 p--;
369 while (p != begin && *p == '0');
370 while (p != begin && *p == '.');
371 }
Neil Booth4ed401b2007-10-14 10:16:12 +0000372
Chris Lattner91702092009-03-12 23:59:55 +0000373 /* Adjust the exponents for any decimal point. */
Michael Gottesman9dc98332013-06-24 04:06:23 +0000374 D->exponent += static_cast<APFloat::ExponentType>((dot - p) - (dot > p));
Chris Lattner91702092009-03-12 23:59:55 +0000375 D->normalizedExponent = (D->exponent +
Michael Gottesman9dc98332013-06-24 04:06:23 +0000376 static_cast<APFloat::ExponentType>((p - D->firstSigDigit)
Chris Lattner91702092009-03-12 23:59:55 +0000377 - (dot > D->firstSigDigit && dot < p)));
Neil Booth4ed401b2007-10-14 10:16:12 +0000378 }
379
Chris Lattner91702092009-03-12 23:59:55 +0000380 D->lastSigDigit = p;
381}
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000382
Chris Lattner91702092009-03-12 23:59:55 +0000383/* Return the trailing fraction of a hexadecimal number.
384 DIGITVALUE is the first hex digit of the fraction, P points to
385 the next digit. */
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000386static lostFraction
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000387trailingHexadecimalFraction(StringRef::iterator p, StringRef::iterator end,
388 unsigned int digitValue)
Chris Lattner91702092009-03-12 23:59:55 +0000389{
390 unsigned int hexDigit;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000391
Chris Lattner91702092009-03-12 23:59:55 +0000392 /* If the first trailing digit isn't 0 or 8 we can work out the
393 fraction immediately. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000394 if (digitValue > 8)
Chris Lattner91702092009-03-12 23:59:55 +0000395 return lfMoreThanHalf;
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000396 else if (digitValue < 8 && digitValue > 0)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000397 return lfLessThanHalf;
Chris Lattner91702092009-03-12 23:59:55 +0000398
Eli Friedmand2eb07a2013-07-17 22:17:29 +0000399 // Otherwise we need to find the first non-zero digit.
400 while (p != end && (*p == '0' || *p == '.'))
Chris Lattner91702092009-03-12 23:59:55 +0000401 p++;
402
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000403 assert(p != end && "Invalid trailing hexadecimal fraction!");
404
Chris Lattner91702092009-03-12 23:59:55 +0000405 hexDigit = hexDigitValue(*p);
406
407 /* If we ran off the end it is exactly zero or one-half, otherwise
408 a little more. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000409 if (hexDigit == -1U)
Chris Lattner91702092009-03-12 23:59:55 +0000410 return digitValue == 0 ? lfExactlyZero: lfExactlyHalf;
411 else
412 return digitValue == 0 ? lfLessThanHalf: lfMoreThanHalf;
413}
414
415/* Return the fraction lost were a bignum truncated losing the least
416 significant BITS bits. */
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000417static lostFraction
Craig Topperc85be522017-06-18 18:15:41 +0000418lostFractionThroughTruncation(const APFloatBase::integerPart *parts,
Chris Lattner91702092009-03-12 23:59:55 +0000419 unsigned int partCount,
420 unsigned int bits)
421{
422 unsigned int lsb;
423
424 lsb = APInt::tcLSB(parts, partCount);
425
426 /* Note this is guaranteed true if bits == 0, or LSB == -1U. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000427 if (bits <= lsb)
Chris Lattner91702092009-03-12 23:59:55 +0000428 return lfExactlyZero;
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000429 if (bits == lsb + 1)
Chris Lattner91702092009-03-12 23:59:55 +0000430 return lfExactlyHalf;
Craig Topperc85be522017-06-18 18:15:41 +0000431 if (bits <= partCount * APFloatBase::integerPartWidth &&
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000432 APInt::tcExtractBit(parts, bits - 1))
Chris Lattner91702092009-03-12 23:59:55 +0000433 return lfMoreThanHalf;
434
435 return lfLessThanHalf;
436}
437
438/* Shift DST right BITS bits noting lost fraction. */
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000439static lostFraction
Craig Topperc85be522017-06-18 18:15:41 +0000440shiftRight(APFloatBase::integerPart *dst, unsigned int parts, unsigned int bits)
Chris Lattner91702092009-03-12 23:59:55 +0000441{
442 lostFraction lost_fraction;
443
444 lost_fraction = lostFractionThroughTruncation(dst, parts, bits);
445
446 APInt::tcShiftRight(dst, parts, bits);
447
448 return lost_fraction;
449}
450
451/* Combine the effect of two lost fractions. */
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000452static lostFraction
Chris Lattner91702092009-03-12 23:59:55 +0000453combineLostFractions(lostFraction moreSignificant,
454 lostFraction lessSignificant)
455{
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000456 if (lessSignificant != lfExactlyZero) {
457 if (moreSignificant == lfExactlyZero)
Chris Lattner91702092009-03-12 23:59:55 +0000458 moreSignificant = lfLessThanHalf;
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000459 else if (moreSignificant == lfExactlyHalf)
Chris Lattner91702092009-03-12 23:59:55 +0000460 moreSignificant = lfMoreThanHalf;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000461 }
462
Chris Lattner91702092009-03-12 23:59:55 +0000463 return moreSignificant;
464}
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000465
Chris Lattner91702092009-03-12 23:59:55 +0000466/* The error from the true value, in half-ulps, on multiplying two
467 floating point numbers, which differ from the value they
468 approximate by at most HUE1 and HUE2 half-ulps, is strictly less
469 than the returned value.
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000470
Chris Lattner91702092009-03-12 23:59:55 +0000471 See "How to Read Floating Point Numbers Accurately" by William D
472 Clinger. */
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000473static unsigned int
Chris Lattner91702092009-03-12 23:59:55 +0000474HUerrBound(bool inexactMultiply, unsigned int HUerr1, unsigned int HUerr2)
475{
476 assert(HUerr1 < 2 || HUerr2 < 2 || (HUerr1 + HUerr2 < 8));
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000477
Chris Lattner91702092009-03-12 23:59:55 +0000478 if (HUerr1 + HUerr2 == 0)
479 return inexactMultiply * 2; /* <= inexactMultiply half-ulps. */
480 else
481 return inexactMultiply + 2 * (HUerr1 + HUerr2);
482}
Neil Booth8f1946f2007-10-03 22:26:02 +0000483
Chris Lattner91702092009-03-12 23:59:55 +0000484/* The number of ulps from the boundary (zero, or half if ISNEAREST)
485 when the least significant BITS are truncated. BITS cannot be
486 zero. */
Craig Topperc85be522017-06-18 18:15:41 +0000487static APFloatBase::integerPart
488ulpsFromBoundary(const APFloatBase::integerPart *parts, unsigned int bits,
489 bool isNearest) {
Chris Lattner91702092009-03-12 23:59:55 +0000490 unsigned int count, partBits;
Craig Topperc85be522017-06-18 18:15:41 +0000491 APFloatBase::integerPart part, boundary;
Neil Boothd3985922007-10-07 08:51:21 +0000492
Evan Cheng67c90212009-10-27 21:35:42 +0000493 assert(bits != 0);
Neil Booth8f1946f2007-10-03 22:26:02 +0000494
Chris Lattner91702092009-03-12 23:59:55 +0000495 bits--;
Craig Topperc85be522017-06-18 18:15:41 +0000496 count = bits / APFloatBase::integerPartWidth;
497 partBits = bits % APFloatBase::integerPartWidth + 1;
Neil Boothb93d90e2007-10-12 16:02:31 +0000498
Craig Topperc85be522017-06-18 18:15:41 +0000499 part = parts[count] & (~(APFloatBase::integerPart) 0 >> (APFloatBase::integerPartWidth - partBits));
Neil Boothb93d90e2007-10-12 16:02:31 +0000500
Chris Lattner91702092009-03-12 23:59:55 +0000501 if (isNearest)
Craig Topperc85be522017-06-18 18:15:41 +0000502 boundary = (APFloatBase::integerPart) 1 << (partBits - 1);
Chris Lattner91702092009-03-12 23:59:55 +0000503 else
504 boundary = 0;
505
506 if (count == 0) {
507 if (part - boundary <= boundary - part)
508 return part - boundary;
Neil Boothb93d90e2007-10-12 16:02:31 +0000509 else
Chris Lattner91702092009-03-12 23:59:55 +0000510 return boundary - part;
Neil Boothb93d90e2007-10-12 16:02:31 +0000511 }
512
Chris Lattner91702092009-03-12 23:59:55 +0000513 if (part == boundary) {
514 while (--count)
515 if (parts[count])
Craig Topperc85be522017-06-18 18:15:41 +0000516 return ~(APFloatBase::integerPart) 0; /* A lot. */
Neil Boothb93d90e2007-10-12 16:02:31 +0000517
Chris Lattner91702092009-03-12 23:59:55 +0000518 return parts[0];
519 } else if (part == boundary - 1) {
520 while (--count)
521 if (~parts[count])
Craig Topperc85be522017-06-18 18:15:41 +0000522 return ~(APFloatBase::integerPart) 0; /* A lot. */
Neil Boothb93d90e2007-10-12 16:02:31 +0000523
Chris Lattner91702092009-03-12 23:59:55 +0000524 return -parts[0];
525 }
Neil Boothb93d90e2007-10-12 16:02:31 +0000526
Craig Topperc85be522017-06-18 18:15:41 +0000527 return ~(APFloatBase::integerPart) 0; /* A lot. */
Chris Lattner91702092009-03-12 23:59:55 +0000528}
Neil Boothb93d90e2007-10-12 16:02:31 +0000529
Chris Lattner91702092009-03-12 23:59:55 +0000530/* Place pow(5, power) in DST, and return the number of parts used.
531 DST must be at least one part larger than size of the answer. */
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000532static unsigned int
Craig Topperc85be522017-06-18 18:15:41 +0000533powerOf5(APFloatBase::integerPart *dst, unsigned int power) {
534 static const APFloatBase::integerPart firstEightPowers[] = { 1, 5, 25, 125, 625, 3125, 15625, 78125 };
535 APFloatBase::integerPart pow5s[maxPowerOfFiveParts * 2 + 5];
Chris Lattnerb858c0e2009-03-13 00:24:01 +0000536 pow5s[0] = 78125 * 5;
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000537
Chris Lattner0bf18692009-03-13 00:03:51 +0000538 unsigned int partsCount[16] = { 1 };
Craig Topperc85be522017-06-18 18:15:41 +0000539 APFloatBase::integerPart scratch[maxPowerOfFiveParts], *p1, *p2, *pow5;
Chris Lattner91702092009-03-12 23:59:55 +0000540 unsigned int result;
Chris Lattner91702092009-03-12 23:59:55 +0000541 assert(power <= maxExponent);
542
543 p1 = dst;
544 p2 = scratch;
545
546 *p1 = firstEightPowers[power & 7];
547 power >>= 3;
548
549 result = 1;
550 pow5 = pow5s;
551
552 for (unsigned int n = 0; power; power >>= 1, n++) {
553 unsigned int pc;
554
555 pc = partsCount[n];
556
557 /* Calculate pow(5,pow(2,n+3)) if we haven't yet. */
558 if (pc == 0) {
559 pc = partsCount[n - 1];
560 APInt::tcFullMultiply(pow5, pow5 - pc, pow5 - pc, pc, pc);
561 pc *= 2;
562 if (pow5[pc - 1] == 0)
563 pc--;
564 partsCount[n] = pc;
Neil Boothb93d90e2007-10-12 16:02:31 +0000565 }
566
Chris Lattner91702092009-03-12 23:59:55 +0000567 if (power & 1) {
Craig Topperc85be522017-06-18 18:15:41 +0000568 APFloatBase::integerPart *tmp;
Neil Boothb93d90e2007-10-12 16:02:31 +0000569
Chris Lattner91702092009-03-12 23:59:55 +0000570 APInt::tcFullMultiply(p2, p1, pow5, result, pc);
571 result += pc;
572 if (p2[result - 1] == 0)
573 result--;
Neil Boothb93d90e2007-10-12 16:02:31 +0000574
Chris Lattner91702092009-03-12 23:59:55 +0000575 /* Now result is in p1 with partsCount parts and p2 is scratch
576 space. */
Richard Trieu7a083812016-02-18 22:09:30 +0000577 tmp = p1;
578 p1 = p2;
579 p2 = tmp;
Neil Boothb93d90e2007-10-12 16:02:31 +0000580 }
581
Chris Lattner91702092009-03-12 23:59:55 +0000582 pow5 += pc;
Neil Boothb93d90e2007-10-12 16:02:31 +0000583 }
584
Chris Lattner91702092009-03-12 23:59:55 +0000585 if (p1 != dst)
586 APInt::tcAssign(dst, p1, result);
Neil Boothb93d90e2007-10-12 16:02:31 +0000587
Chris Lattner91702092009-03-12 23:59:55 +0000588 return result;
589}
Neil Boothb93d90e2007-10-12 16:02:31 +0000590
Chris Lattner91702092009-03-12 23:59:55 +0000591/* Zero at the end to avoid modular arithmetic when adding one; used
592 when rounding up during hexadecimal output. */
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000593static const char hexDigitsLower[] = "0123456789abcdef0";
594static const char hexDigitsUpper[] = "0123456789ABCDEF0";
595static const char infinityL[] = "infinity";
596static const char infinityU[] = "INFINITY";
597static const char NaNL[] = "nan";
598static const char NaNU[] = "NAN";
Neil Boothb93d90e2007-10-12 16:02:31 +0000599
Chris Lattner91702092009-03-12 23:59:55 +0000600/* Write out an integerPart in hexadecimal, starting with the most
601 significant nibble. Write out exactly COUNT hexdigits, return
602 COUNT. */
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000603static unsigned int
Craig Topperc85be522017-06-18 18:15:41 +0000604partAsHex (char *dst, APFloatBase::integerPart part, unsigned int count,
Chris Lattner91702092009-03-12 23:59:55 +0000605 const char *hexDigitChars)
606{
607 unsigned int result = count;
Neil Boothb93d90e2007-10-12 16:02:31 +0000608
Craig Topperc85be522017-06-18 18:15:41 +0000609 assert(count != 0 && count <= APFloatBase::integerPartWidth / 4);
Neil Boothb93d90e2007-10-12 16:02:31 +0000610
Craig Topperc85be522017-06-18 18:15:41 +0000611 part >>= (APFloatBase::integerPartWidth - 4 * count);
Chris Lattner91702092009-03-12 23:59:55 +0000612 while (count--) {
613 dst[count] = hexDigitChars[part & 0xf];
614 part >>= 4;
Neil Boothb93d90e2007-10-12 16:02:31 +0000615 }
616
Chris Lattner91702092009-03-12 23:59:55 +0000617 return result;
618}
Neil Booth8f1946f2007-10-03 22:26:02 +0000619
Chris Lattner91702092009-03-12 23:59:55 +0000620/* Write out an unsigned decimal integer. */
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000621static char *
Chris Lattner91702092009-03-12 23:59:55 +0000622writeUnsignedDecimal (char *dst, unsigned int n)
623{
624 char buff[40], *p;
Neil Booth8f1946f2007-10-03 22:26:02 +0000625
Chris Lattner91702092009-03-12 23:59:55 +0000626 p = buff;
627 do
628 *p++ = '0' + n % 10;
629 while (n /= 10);
Neil Booth8f1946f2007-10-03 22:26:02 +0000630
Chris Lattner91702092009-03-12 23:59:55 +0000631 do
632 *dst++ = *--p;
633 while (p != buff);
Neil Booth8f1946f2007-10-03 22:26:02 +0000634
Chris Lattner91702092009-03-12 23:59:55 +0000635 return dst;
636}
Neil Booth8f1946f2007-10-03 22:26:02 +0000637
Chris Lattner91702092009-03-12 23:59:55 +0000638/* Write out a signed decimal integer. */
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000639static char *
Chris Lattner91702092009-03-12 23:59:55 +0000640writeSignedDecimal (char *dst, int value)
641{
642 if (value < 0) {
643 *dst++ = '-';
644 dst = writeUnsignedDecimal(dst, -(unsigned) value);
645 } else
646 dst = writeUnsignedDecimal(dst, value);
Neil Booth8f1946f2007-10-03 22:26:02 +0000647
Chris Lattner91702092009-03-12 23:59:55 +0000648 return dst;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000649}
650
Tim Shen85de51d2016-10-25 19:55:59 +0000651namespace detail {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000652/* Constructors. */
Tim Shen85de51d2016-10-25 19:55:59 +0000653void IEEEFloat::initialize(const fltSemantics *ourSemantics) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000654 unsigned int count;
655
656 semantics = ourSemantics;
657 count = partCount();
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000658 if (count > 1)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000659 significand.parts = new integerPart[count];
660}
661
Tim Shen85de51d2016-10-25 19:55:59 +0000662void IEEEFloat::freeSignificand() {
Manuel Klimekd0cf5b22013-06-03 13:03:05 +0000663 if (needsCleanup())
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000664 delete [] significand.parts;
665}
666
Tim Shen85de51d2016-10-25 19:55:59 +0000667void IEEEFloat::assign(const IEEEFloat &rhs) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000668 assert(semantics == rhs.semantics);
669
670 sign = rhs.sign;
671 category = rhs.category;
672 exponent = rhs.exponent;
Michael Gottesman8136c382013-06-26 23:17:28 +0000673 if (isFiniteNonZero() || category == fcNaN)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000674 copySignificand(rhs);
675}
676
Tim Shen85de51d2016-10-25 19:55:59 +0000677void IEEEFloat::copySignificand(const IEEEFloat &rhs) {
Michael Gottesman8136c382013-06-26 23:17:28 +0000678 assert(isFiniteNonZero() || category == fcNaN);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000679 assert(rhs.partCount() >= partCount());
680
681 APInt::tcAssign(significandParts(), rhs.significandParts(),
Neil Booth9acbf5a2007-09-26 21:33:42 +0000682 partCount());
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000683}
684
Neil Booth5fe658b2007-10-14 10:39:51 +0000685/* Make this number a NaN, with an arbitrary but deterministic value
Dale Johannesen1f864982009-01-21 20:32:55 +0000686 for the significand. If double or longer, this is a signalling NaN,
Mike Stump799bf582009-05-30 03:49:43 +0000687 which may not be ideal. If float, this is QNaN(0). */
Tim Shen85de51d2016-10-25 19:55:59 +0000688void IEEEFloat::makeNaN(bool SNaN, bool Negative, const APInt *fill) {
Neil Booth5fe658b2007-10-14 10:39:51 +0000689 category = fcNaN;
John McCalldcb9a7a2010-02-28 02:51:25 +0000690 sign = Negative;
691
John McCallc12b1332010-02-28 12:49:50 +0000692 integerPart *significand = significandParts();
693 unsigned numParts = partCount();
694
John McCalldcb9a7a2010-02-28 02:51:25 +0000695 // Set the significand bits to the fill.
John McCallc12b1332010-02-28 12:49:50 +0000696 if (!fill || fill->getNumWords() < numParts)
697 APInt::tcSet(significand, 0, numParts);
698 if (fill) {
John McCallc6dbe302010-03-01 18:38:45 +0000699 APInt::tcAssign(significand, fill->getRawData(),
700 std::min(fill->getNumWords(), numParts));
John McCallc12b1332010-02-28 12:49:50 +0000701
702 // Zero out the excess bits of the significand.
703 unsigned bitsToPreserve = semantics->precision - 1;
704 unsigned part = bitsToPreserve / 64;
705 bitsToPreserve %= 64;
706 significand[part] &= ((1ULL << bitsToPreserve) - 1);
707 for (part++; part != numParts; ++part)
708 significand[part] = 0;
709 }
710
711 unsigned QNaNBit = semantics->precision - 2;
John McCalldcb9a7a2010-02-28 02:51:25 +0000712
713 if (SNaN) {
714 // We always have to clear the QNaN bit to make it an SNaN.
John McCallc12b1332010-02-28 12:49:50 +0000715 APInt::tcClearBit(significand, QNaNBit);
John McCalldcb9a7a2010-02-28 02:51:25 +0000716
717 // If there are no bits set in the payload, we have to set
718 // *something* to make it a NaN instead of an infinity;
719 // conventionally, this is the next bit down from the QNaN bit.
John McCallc12b1332010-02-28 12:49:50 +0000720 if (APInt::tcIsZero(significand, numParts))
721 APInt::tcSetBit(significand, QNaNBit - 1);
John McCalldcb9a7a2010-02-28 02:51:25 +0000722 } else {
723 // We always have to set the QNaN bit to make it a QNaN.
John McCallc12b1332010-02-28 12:49:50 +0000724 APInt::tcSetBit(significand, QNaNBit);
John McCalldcb9a7a2010-02-28 02:51:25 +0000725 }
John McCallc12b1332010-02-28 12:49:50 +0000726
727 // For x87 extended precision, we want to make a NaN, not a
728 // pseudo-NaN. Maybe we should expose the ability to make
729 // pseudo-NaNs?
Stephan Bergmann17c7f702016-12-14 11:57:17 +0000730 if (semantics == &semX87DoubleExtended)
John McCallc12b1332010-02-28 12:49:50 +0000731 APInt::tcSetBit(significand, QNaNBit + 1);
John McCalldcb9a7a2010-02-28 02:51:25 +0000732}
733
Tim Shen85de51d2016-10-25 19:55:59 +0000734IEEEFloat &IEEEFloat::operator=(const IEEEFloat &rhs) {
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000735 if (this != &rhs) {
736 if (semantics != rhs.semantics) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000737 freeSignificand();
738 initialize(rhs.semantics);
739 }
740 assign(rhs);
741 }
742
743 return *this;
744}
745
Tim Shen85de51d2016-10-25 19:55:59 +0000746IEEEFloat &IEEEFloat::operator=(IEEEFloat &&rhs) {
Benjamin Kramer06f47782014-03-04 20:26:51 +0000747 freeSignificand();
748
749 semantics = rhs.semantics;
750 significand = rhs.significand;
751 exponent = rhs.exponent;
752 category = rhs.category;
753 sign = rhs.sign;
754
Stephan Bergmann17c7f702016-12-14 11:57:17 +0000755 rhs.semantics = &semBogus;
Benjamin Kramer06f47782014-03-04 20:26:51 +0000756 return *this;
757}
758
Tim Shen85de51d2016-10-25 19:55:59 +0000759bool IEEEFloat::isDenormal() const {
Michael Gottesman3cb77ab2013-06-19 21:23:18 +0000760 return isFiniteNonZero() && (exponent == semantics->minExponent) &&
Simon Pilgrima2849592017-03-20 13:53:59 +0000761 (APInt::tcExtractBit(significandParts(),
Shuxin Yang4fb504f2013-01-07 18:59:35 +0000762 semantics->precision - 1) == 0);
763}
764
Tim Shen85de51d2016-10-25 19:55:59 +0000765bool IEEEFloat::isSmallest() const {
Michael Gottesman0c622ea2013-05-30 18:07:13 +0000766 // The smallest number by magnitude in our format will be the smallest
Michael Gottesmana7cc1242013-06-19 07:34:21 +0000767 // denormal, i.e. the floating point number with exponent being minimum
Michael Gottesman0c622ea2013-05-30 18:07:13 +0000768 // exponent and significand bitwise equal to 1 (i.e. with MSB equal to 0).
Michael Gottesman3cb77ab2013-06-19 21:23:18 +0000769 return isFiniteNonZero() && exponent == semantics->minExponent &&
Michael Gottesman0c622ea2013-05-30 18:07:13 +0000770 significandMSB() == 0;
771}
772
Tim Shen85de51d2016-10-25 19:55:59 +0000773bool IEEEFloat::isSignificandAllOnes() const {
Michael Gottesman0c622ea2013-05-30 18:07:13 +0000774 // Test if the significand excluding the integral bit is all ones. This allows
775 // us to test for binade boundaries.
776 const integerPart *Parts = significandParts();
777 const unsigned PartCount = partCount();
778 for (unsigned i = 0; i < PartCount - 1; i++)
779 if (~Parts[i])
780 return false;
781
782 // Set the unused high bits to all ones when we compare.
783 const unsigned NumHighBits =
784 PartCount*integerPartWidth - semantics->precision + 1;
785 assert(NumHighBits <= integerPartWidth && "Can not have more high bits to "
786 "fill than integerPartWidth");
787 const integerPart HighBitFill =
788 ~integerPart(0) << (integerPartWidth - NumHighBits);
789 if (~(Parts[PartCount - 1] | HighBitFill))
790 return false;
791
792 return true;
793}
794
Tim Shen85de51d2016-10-25 19:55:59 +0000795bool IEEEFloat::isSignificandAllZeros() const {
Michael Gottesman0c622ea2013-05-30 18:07:13 +0000796 // Test if the significand excluding the integral bit is all zeros. This
797 // allows us to test for binade boundaries.
798 const integerPart *Parts = significandParts();
799 const unsigned PartCount = partCount();
800
801 for (unsigned i = 0; i < PartCount - 1; i++)
802 if (Parts[i])
803 return false;
804
805 const unsigned NumHighBits =
806 PartCount*integerPartWidth - semantics->precision + 1;
807 assert(NumHighBits <= integerPartWidth && "Can not have more high bits to "
808 "clear than integerPartWidth");
809 const integerPart HighBitMask = ~integerPart(0) >> NumHighBits;
810
811 if (Parts[PartCount - 1] & HighBitMask)
812 return false;
813
814 return true;
815}
816
Tim Shen85de51d2016-10-25 19:55:59 +0000817bool IEEEFloat::isLargest() const {
Michael Gottesman0c622ea2013-05-30 18:07:13 +0000818 // The largest number by magnitude in our format will be the floating point
819 // number with maximum exponent and with significand that is all ones.
Michael Gottesman3cb77ab2013-06-19 21:23:18 +0000820 return isFiniteNonZero() && exponent == semantics->maxExponent
Michael Gottesman0c622ea2013-05-30 18:07:13 +0000821 && isSignificandAllOnes();
822}
823
Tim Shen85de51d2016-10-25 19:55:59 +0000824bool IEEEFloat::isInteger() const {
Stephen Canon1bfc89b2015-11-16 21:52:48 +0000825 // This could be made more efficient; I'm going for obviously correct.
826 if (!isFinite()) return false;
Tim Shen85de51d2016-10-25 19:55:59 +0000827 IEEEFloat truncated = *this;
Stephen Canon1bfc89b2015-11-16 21:52:48 +0000828 truncated.roundToIntegral(rmTowardZero);
829 return compare(truncated) == cmpEqual;
830}
831
Tim Shen85de51d2016-10-25 19:55:59 +0000832bool IEEEFloat::bitwiseIsEqual(const IEEEFloat &rhs) const {
Dale Johannesena719a602007-08-24 00:56:33 +0000833 if (this == &rhs)
834 return true;
835 if (semantics != rhs.semantics ||
Dale Johannesen3cf889f2007-08-31 04:03:46 +0000836 category != rhs.category ||
837 sign != rhs.sign)
Dale Johannesena719a602007-08-24 00:56:33 +0000838 return false;
Dale Johannesen3cf889f2007-08-31 04:03:46 +0000839 if (category==fcZero || category==fcInfinity)
Dale Johannesena719a602007-08-24 00:56:33 +0000840 return true;
Benjamin Kramer103fc942015-08-21 16:44:52 +0000841
842 if (isFiniteNonZero() && exponent != rhs.exponent)
Dale Johannesen3cf889f2007-08-31 04:03:46 +0000843 return false;
Benjamin Kramer103fc942015-08-21 16:44:52 +0000844
845 return std::equal(significandParts(), significandParts() + partCount(),
846 rhs.significandParts());
Dale Johannesena719a602007-08-24 00:56:33 +0000847}
848
Tim Shen85de51d2016-10-25 19:55:59 +0000849IEEEFloat::IEEEFloat(const fltSemantics &ourSemantics, integerPart value) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000850 initialize(&ourSemantics);
851 sign = 0;
Michael Gottesman30a90eb2013-07-27 21:49:21 +0000852 category = fcNormal;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000853 zeroSignificand();
854 exponent = ourSemantics.precision - 1;
855 significandParts()[0] = value;
856 normalize(rmNearestTiesToEven, lfExactlyZero);
857}
858
Tim Shen85de51d2016-10-25 19:55:59 +0000859IEEEFloat::IEEEFloat(const fltSemantics &ourSemantics) {
Chris Lattnerac6271e2009-09-17 01:08:43 +0000860 initialize(&ourSemantics);
861 category = fcZero;
862 sign = false;
863}
864
Tim Shenb49915482016-10-28 22:45:33 +0000865// Delegate to the previous constructor, because later copy constructor may
866// actually inspects category, which can't be garbage.
867IEEEFloat::IEEEFloat(const fltSemantics &ourSemantics, uninitializedTag tag)
Tim Shen1bab9cf2016-10-29 00:51:41 +0000868 : IEEEFloat(ourSemantics) {}
Chris Lattnerac6271e2009-09-17 01:08:43 +0000869
Tim Shen85de51d2016-10-25 19:55:59 +0000870IEEEFloat::IEEEFloat(const IEEEFloat &rhs) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000871 initialize(rhs.semantics);
872 assign(rhs);
873}
874
Stephan Bergmann17c7f702016-12-14 11:57:17 +0000875IEEEFloat::IEEEFloat(IEEEFloat &&rhs) : semantics(&semBogus) {
Benjamin Kramer06f47782014-03-04 20:26:51 +0000876 *this = std::move(rhs);
877}
878
Tim Shen85de51d2016-10-25 19:55:59 +0000879IEEEFloat::~IEEEFloat() { freeSignificand(); }
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000880
Tim Shen85de51d2016-10-25 19:55:59 +0000881unsigned int IEEEFloat::partCount() const {
Dale Johannesen146a0ea2007-09-20 23:47:58 +0000882 return partCountForBits(semantics->precision + 1);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000883}
884
Craig Topperc85be522017-06-18 18:15:41 +0000885const IEEEFloat::integerPart *IEEEFloat::significandParts() const {
Tim Shen85de51d2016-10-25 19:55:59 +0000886 return const_cast<IEEEFloat *>(this)->significandParts();
JF Bastiena1d3c242015-08-26 02:32:45 +0000887}
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000888
Craig Topperc85be522017-06-18 18:15:41 +0000889IEEEFloat::integerPart *IEEEFloat::significandParts() {
Evan Cheng67c90212009-10-27 21:35:42 +0000890 if (partCount() > 1)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000891 return significand.parts;
892 else
893 return &significand.part;
894}
895
Tim Shen85de51d2016-10-25 19:55:59 +0000896void IEEEFloat::zeroSignificand() {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000897 APInt::tcSet(significandParts(), 0, partCount());
898}
899
900/* Increment an fcNormal floating point number's significand. */
Tim Shen85de51d2016-10-25 19:55:59 +0000901void IEEEFloat::incrementSignificand() {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000902 integerPart carry;
903
904 carry = APInt::tcIncrement(significandParts(), partCount());
905
906 /* Our callers should never cause us to overflow. */
907 assert(carry == 0);
Duncan Sandsa41634e2011-08-12 14:54:45 +0000908 (void)carry;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000909}
910
911/* Add the significand of the RHS. Returns the carry flag. */
Craig Topperc85be522017-06-18 18:15:41 +0000912IEEEFloat::integerPart IEEEFloat::addSignificand(const IEEEFloat &rhs) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000913 integerPart *parts;
914
915 parts = significandParts();
916
917 assert(semantics == rhs.semantics);
918 assert(exponent == rhs.exponent);
919
920 return APInt::tcAdd(parts, rhs.significandParts(), 0, partCount());
921}
922
923/* Subtract the significand of the RHS with a borrow flag. Returns
924 the borrow flag. */
Craig Topperc85be522017-06-18 18:15:41 +0000925IEEEFloat::integerPart IEEEFloat::subtractSignificand(const IEEEFloat &rhs,
926 integerPart borrow) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000927 integerPart *parts;
928
929 parts = significandParts();
930
931 assert(semantics == rhs.semantics);
932 assert(exponent == rhs.exponent);
933
934 return APInt::tcSubtract(parts, rhs.significandParts(), borrow,
Neil Booth9acbf5a2007-09-26 21:33:42 +0000935 partCount());
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000936}
937
938/* Multiply the significand of the RHS. If ADDEND is non-NULL, add it
939 on to the full-precision result of the multiplication. Returns the
940 lost fraction. */
Tim Shen85de51d2016-10-25 19:55:59 +0000941lostFraction IEEEFloat::multiplySignificand(const IEEEFloat &rhs,
942 const IEEEFloat *addend) {
Neil Booth9acbf5a2007-09-26 21:33:42 +0000943 unsigned int omsb; // One, not zero, based MSB.
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000944 unsigned int partsCount, newPartsCount, precision;
945 integerPart *lhsSignificand;
946 integerPart scratch[4];
947 integerPart *fullSignificand;
948 lostFraction lost_fraction;
Dale Johannesen4f0bd682008-10-09 23:00:39 +0000949 bool ignored;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000950
951 assert(semantics == rhs.semantics);
952
953 precision = semantics->precision;
Lang Hames56c0eb22014-11-19 19:15:41 +0000954
955 // Allocate space for twice as many bits as the original significand, plus one
956 // extra bit for the addition to overflow into.
957 newPartsCount = partCountForBits(precision * 2 + 1);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000958
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000959 if (newPartsCount > 4)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000960 fullSignificand = new integerPart[newPartsCount];
961 else
962 fullSignificand = scratch;
963
964 lhsSignificand = significandParts();
965 partsCount = partCount();
966
967 APInt::tcFullMultiply(fullSignificand, lhsSignificand,
Neil Booth0ea72a92007-10-06 00:24:48 +0000968 rhs.significandParts(), partsCount, partsCount);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000969
970 lost_fraction = lfExactlyZero;
971 omsb = APInt::tcMSB(fullSignificand, newPartsCount) + 1;
972 exponent += rhs.exponent;
973
Shuxin Yangbbddbac2013-05-13 18:03:12 +0000974 // Assume the operands involved in the multiplication are single-precision
975 // FP, and the two multiplicants are:
976 // *this = a23 . a22 ... a0 * 2^e1
977 // rhs = b23 . b22 ... b0 * 2^e2
978 // the result of multiplication is:
Lang Hames56c0eb22014-11-19 19:15:41 +0000979 // *this = c48 c47 c46 . c45 ... c0 * 2^(e1+e2)
Simon Pilgrima2849592017-03-20 13:53:59 +0000980 // Note that there are three significant bits at the left-hand side of the
Lang Hames56c0eb22014-11-19 19:15:41 +0000981 // radix point: two for the multiplication, and an overflow bit for the
982 // addition (that will always be zero at this point). Move the radix point
983 // toward left by two bits, and adjust exponent accordingly.
984 exponent += 2;
Shuxin Yangbbddbac2013-05-13 18:03:12 +0000985
Hal Finkel171c2ec2014-10-14 19:23:07 +0000986 if (addend && addend->isNonZero()) {
Simon Pilgrima2849592017-03-20 13:53:59 +0000987 // The intermediate result of the multiplication has "2 * precision"
Shuxin Yangbbddbac2013-05-13 18:03:12 +0000988 // signicant bit; adjust the addend to be consistent with mul result.
989 //
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000990 Significand savedSignificand = significand;
991 const fltSemantics *savedSemantics = semantics;
992 fltSemantics extendedSemantics;
993 opStatus status;
994 unsigned int extendedPrecision;
995
Lang Hames56c0eb22014-11-19 19:15:41 +0000996 // Normalize our MSB to one below the top bit to allow for overflow.
997 extendedPrecision = 2 * precision + 1;
998 if (omsb != extendedPrecision - 1) {
Shuxin Yangbbddbac2013-05-13 18:03:12 +0000999 assert(extendedPrecision > omsb);
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001000 APInt::tcShiftLeft(fullSignificand, newPartsCount,
Lang Hames56c0eb22014-11-19 19:15:41 +00001001 (extendedPrecision - 1) - omsb);
1002 exponent -= (extendedPrecision - 1) - omsb;
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001003 }
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001004
1005 /* Create new semantics. */
1006 extendedSemantics = *semantics;
1007 extendedSemantics.precision = extendedPrecision;
1008
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001009 if (newPartsCount == 1)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001010 significand.part = fullSignificand[0];
1011 else
1012 significand.parts = fullSignificand;
1013 semantics = &extendedSemantics;
1014
Tim Shen85de51d2016-10-25 19:55:59 +00001015 IEEEFloat extendedAddend(*addend);
Dale Johannesen4f0bd682008-10-09 23:00:39 +00001016 status = extendedAddend.convert(extendedSemantics, rmTowardZero, &ignored);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001017 assert(status == opOK);
Duncan Sandsa41634e2011-08-12 14:54:45 +00001018 (void)status;
Lang Hames56c0eb22014-11-19 19:15:41 +00001019
1020 // Shift the significand of the addend right by one bit. This guarantees
1021 // that the high bit of the significand is zero (same as fullSignificand),
1022 // so the addition will overflow (if it does overflow at all) into the top bit.
1023 lost_fraction = extendedAddend.shiftSignificandRight(1);
1024 assert(lost_fraction == lfExactlyZero &&
1025 "Lost precision while shifting addend for fused-multiply-add.");
1026
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001027 lost_fraction = addOrSubtractSignificand(extendedAddend, false);
1028
1029 /* Restore our state. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001030 if (newPartsCount == 1)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001031 fullSignificand[0] = significand.part;
1032 significand = savedSignificand;
1033 semantics = savedSemantics;
1034
1035 omsb = APInt::tcMSB(fullSignificand, newPartsCount) + 1;
1036 }
1037
Shuxin Yangbbddbac2013-05-13 18:03:12 +00001038 // Convert the result having "2 * precision" significant-bits back to the one
Simon Pilgrima2849592017-03-20 13:53:59 +00001039 // having "precision" significant-bits. First, move the radix point from
Shuxin Yangbbddbac2013-05-13 18:03:12 +00001040 // poision "2*precision - 1" to "precision - 1". The exponent need to be
1041 // adjusted by "2*precision - 1" - "precision - 1" = "precision".
Lang Hames56c0eb22014-11-19 19:15:41 +00001042 exponent -= precision + 1;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001043
Shuxin Yangbbddbac2013-05-13 18:03:12 +00001044 // In case MSB resides at the left-hand side of radix point, shift the
1045 // mantissa right by some amount to make sure the MSB reside right before
1046 // the radix point (i.e. "MSB . rest-significant-bits").
1047 //
1048 // Note that the result is not normalized when "omsb < precision". So, the
Tim Shen85de51d2016-10-25 19:55:59 +00001049 // caller needs to call IEEEFloat::normalize() if normalized value is
1050 // expected.
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001051 if (omsb > precision) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001052 unsigned int bits, significantParts;
1053 lostFraction lf;
1054
1055 bits = omsb - precision;
1056 significantParts = partCountForBits(omsb);
1057 lf = shiftRight(fullSignificand, significantParts, bits);
1058 lost_fraction = combineLostFractions(lf, lost_fraction);
1059 exponent += bits;
1060 }
1061
1062 APInt::tcAssign(lhsSignificand, fullSignificand, partsCount);
1063
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001064 if (newPartsCount > 4)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001065 delete [] fullSignificand;
1066
1067 return lost_fraction;
1068}
1069
1070/* Multiply the significands of LHS and RHS to DST. */
Tim Shen85de51d2016-10-25 19:55:59 +00001071lostFraction IEEEFloat::divideSignificand(const IEEEFloat &rhs) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001072 unsigned int bit, i, partsCount;
1073 const integerPart *rhsSignificand;
1074 integerPart *lhsSignificand, *dividend, *divisor;
1075 integerPart scratch[4];
1076 lostFraction lost_fraction;
1077
1078 assert(semantics == rhs.semantics);
1079
1080 lhsSignificand = significandParts();
1081 rhsSignificand = rhs.significandParts();
1082 partsCount = partCount();
1083
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001084 if (partsCount > 2)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001085 dividend = new integerPart[partsCount * 2];
1086 else
1087 dividend = scratch;
1088
1089 divisor = dividend + partsCount;
1090
1091 /* Copy the dividend and divisor as they will be modified in-place. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001092 for (i = 0; i < partsCount; i++) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001093 dividend[i] = lhsSignificand[i];
1094 divisor[i] = rhsSignificand[i];
1095 lhsSignificand[i] = 0;
1096 }
1097
1098 exponent -= rhs.exponent;
1099
1100 unsigned int precision = semantics->precision;
1101
1102 /* Normalize the divisor. */
1103 bit = precision - APInt::tcMSB(divisor, partsCount) - 1;
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001104 if (bit) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001105 exponent += bit;
1106 APInt::tcShiftLeft(divisor, partsCount, bit);
1107 }
1108
1109 /* Normalize the dividend. */
1110 bit = precision - APInt::tcMSB(dividend, partsCount) - 1;
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001111 if (bit) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001112 exponent -= bit;
1113 APInt::tcShiftLeft(dividend, partsCount, bit);
1114 }
1115
Neil Boothb93d90e2007-10-12 16:02:31 +00001116 /* Ensure the dividend >= divisor initially for the loop below.
1117 Incidentally, this means that the division loop below is
1118 guaranteed to set the integer bit to one. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001119 if (APInt::tcCompare(dividend, divisor, partsCount) < 0) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001120 exponent--;
1121 APInt::tcShiftLeft(dividend, partsCount, 1);
1122 assert(APInt::tcCompare(dividend, divisor, partsCount) >= 0);
1123 }
1124
1125 /* Long division. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001126 for (bit = precision; bit; bit -= 1) {
1127 if (APInt::tcCompare(dividend, divisor, partsCount) >= 0) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001128 APInt::tcSubtract(dividend, divisor, 0, partsCount);
1129 APInt::tcSetBit(lhsSignificand, bit - 1);
1130 }
1131
1132 APInt::tcShiftLeft(dividend, partsCount, 1);
1133 }
1134
1135 /* Figure out the lost fraction. */
1136 int cmp = APInt::tcCompare(dividend, divisor, partsCount);
1137
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001138 if (cmp > 0)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001139 lost_fraction = lfMoreThanHalf;
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001140 else if (cmp == 0)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001141 lost_fraction = lfExactlyHalf;
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001142 else if (APInt::tcIsZero(dividend, partsCount))
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001143 lost_fraction = lfExactlyZero;
1144 else
1145 lost_fraction = lfLessThanHalf;
1146
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001147 if (partsCount > 2)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001148 delete [] dividend;
1149
1150 return lost_fraction;
1151}
1152
Tim Shen85de51d2016-10-25 19:55:59 +00001153unsigned int IEEEFloat::significandMSB() const {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001154 return APInt::tcMSB(significandParts(), partCount());
1155}
1156
Tim Shen85de51d2016-10-25 19:55:59 +00001157unsigned int IEEEFloat::significandLSB() const {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001158 return APInt::tcLSB(significandParts(), partCount());
1159}
1160
1161/* Note that a zero result is NOT normalized to fcZero. */
Tim Shen85de51d2016-10-25 19:55:59 +00001162lostFraction IEEEFloat::shiftSignificandRight(unsigned int bits) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001163 /* Our exponent should not overflow. */
Michael Gottesman9dc98332013-06-24 04:06:23 +00001164 assert((ExponentType) (exponent + bits) >= exponent);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001165
1166 exponent += bits;
1167
1168 return shiftRight(significandParts(), partCount(), bits);
1169}
1170
1171/* Shift the significand left BITS bits, subtract BITS from its exponent. */
Tim Shen85de51d2016-10-25 19:55:59 +00001172void IEEEFloat::shiftSignificandLeft(unsigned int bits) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001173 assert(bits < semantics->precision);
1174
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001175 if (bits) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001176 unsigned int partsCount = partCount();
1177
1178 APInt::tcShiftLeft(significandParts(), partsCount, bits);
1179 exponent -= bits;
1180
1181 assert(!APInt::tcIsZero(significandParts(), partsCount));
1182 }
1183}
1184
Tim Shen85de51d2016-10-25 19:55:59 +00001185IEEEFloat::cmpResult
1186IEEEFloat::compareAbsoluteValue(const IEEEFloat &rhs) const {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001187 int compare;
1188
1189 assert(semantics == rhs.semantics);
Michael Gottesman8136c382013-06-26 23:17:28 +00001190 assert(isFiniteNonZero());
1191 assert(rhs.isFiniteNonZero());
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001192
1193 compare = exponent - rhs.exponent;
1194
1195 /* If exponents are equal, do an unsigned bignum comparison of the
1196 significands. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001197 if (compare == 0)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001198 compare = APInt::tcCompare(significandParts(), rhs.significandParts(),
Neil Booth9acbf5a2007-09-26 21:33:42 +00001199 partCount());
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001200
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001201 if (compare > 0)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001202 return cmpGreaterThan;
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001203 else if (compare < 0)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001204 return cmpLessThan;
1205 else
1206 return cmpEqual;
1207}
1208
1209/* Handle overflow. Sign is preserved. We either become infinity or
1210 the largest finite number. */
Tim Shen85de51d2016-10-25 19:55:59 +00001211IEEEFloat::opStatus IEEEFloat::handleOverflow(roundingMode rounding_mode) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001212 /* Infinity? */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001213 if (rounding_mode == rmNearestTiesToEven ||
1214 rounding_mode == rmNearestTiesToAway ||
1215 (rounding_mode == rmTowardPositive && !sign) ||
1216 (rounding_mode == rmTowardNegative && sign)) {
1217 category = fcInfinity;
1218 return (opStatus) (opOverflow | opInexact);
1219 }
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001220
1221 /* Otherwise we become the largest finite number. */
1222 category = fcNormal;
1223 exponent = semantics->maxExponent;
1224 APInt::tcSetLeastSignificantBits(significandParts(), partCount(),
Neil Booth9acbf5a2007-09-26 21:33:42 +00001225 semantics->precision);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001226
1227 return opInexact;
1228}
1229
Neil Booth1ca1f802007-10-03 15:16:41 +00001230/* Returns TRUE if, when truncating the current number, with BIT the
1231 new LSB, with the given lost fraction and rounding mode, the result
1232 would need to be rounded away from zero (i.e., by increasing the
1233 signficand). This routine must work for fcZero of both signs, and
1234 fcNormal numbers. */
Tim Shen85de51d2016-10-25 19:55:59 +00001235bool IEEEFloat::roundAwayFromZero(roundingMode rounding_mode,
1236 lostFraction lost_fraction,
1237 unsigned int bit) const {
Dale Johannesen3cf889f2007-08-31 04:03:46 +00001238 /* NaNs and infinities should not have lost fractions. */
Michael Gottesman8136c382013-06-26 23:17:28 +00001239 assert(isFiniteNonZero() || category == fcZero);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001240
Neil Booth1ca1f802007-10-03 15:16:41 +00001241 /* Current callers never pass this so we don't handle it. */
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001242 assert(lost_fraction != lfExactlyZero);
1243
Mike Stump889285d2009-05-13 23:23:20 +00001244 switch (rounding_mode) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001245 case rmNearestTiesToAway:
1246 return lost_fraction == lfExactlyHalf || lost_fraction == lfMoreThanHalf;
1247
1248 case rmNearestTiesToEven:
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001249 if (lost_fraction == lfMoreThanHalf)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001250 return true;
1251
1252 /* Our zeroes don't have a significand to test. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001253 if (lost_fraction == lfExactlyHalf && category != fcZero)
Neil Booth1ca1f802007-10-03 15:16:41 +00001254 return APInt::tcExtractBit(significandParts(), bit);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001255
1256 return false;
1257
1258 case rmTowardZero:
1259 return false;
1260
1261 case rmTowardPositive:
David Blaikiedc3f01e2015-03-09 01:57:13 +00001262 return !sign;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001263
1264 case rmTowardNegative:
David Blaikiedc3f01e2015-03-09 01:57:13 +00001265 return sign;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001266 }
Chandler Carruthf3e85022012-01-10 18:08:01 +00001267 llvm_unreachable("Invalid rounding mode found");
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001268}
1269
Tim Shen85de51d2016-10-25 19:55:59 +00001270IEEEFloat::opStatus IEEEFloat::normalize(roundingMode rounding_mode,
1271 lostFraction lost_fraction) {
Neil Booth9acbf5a2007-09-26 21:33:42 +00001272 unsigned int omsb; /* One, not zero, based MSB. */
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001273 int exponentChange;
1274
Michael Gottesman8136c382013-06-26 23:17:28 +00001275 if (!isFiniteNonZero())
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001276 return opOK;
1277
1278 /* Before rounding normalize the exponent of fcNormal numbers. */
1279 omsb = significandMSB() + 1;
1280
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001281 if (omsb) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001282 /* OMSB is numbered from 1. We want to place it in the integer
Nick Lewyckyf66daac2011-10-03 21:30:08 +00001283 bit numbered PRECISION if possible, with a compensating change in
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001284 the exponent. */
1285 exponentChange = omsb - semantics->precision;
1286
1287 /* If the resulting exponent is too high, overflow according to
1288 the rounding mode. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001289 if (exponent + exponentChange > semantics->maxExponent)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001290 return handleOverflow(rounding_mode);
1291
1292 /* Subnormal numbers have exponent minExponent, and their MSB
1293 is forced based on that. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001294 if (exponent + exponentChange < semantics->minExponent)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001295 exponentChange = semantics->minExponent - exponent;
1296
1297 /* Shifting left is easy as we don't lose precision. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001298 if (exponentChange < 0) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001299 assert(lost_fraction == lfExactlyZero);
1300
1301 shiftSignificandLeft(-exponentChange);
1302
1303 return opOK;
1304 }
1305
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001306 if (exponentChange > 0) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001307 lostFraction lf;
1308
1309 /* Shift right and capture any new lost fraction. */
1310 lf = shiftSignificandRight(exponentChange);
1311
1312 lost_fraction = combineLostFractions(lf, lost_fraction);
1313
1314 /* Keep OMSB up-to-date. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001315 if (omsb > (unsigned) exponentChange)
Neil Boothb93d90e2007-10-12 16:02:31 +00001316 omsb -= exponentChange;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001317 else
Neil Booth9acbf5a2007-09-26 21:33:42 +00001318 omsb = 0;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001319 }
1320 }
1321
1322 /* Now round the number according to rounding_mode given the lost
1323 fraction. */
1324
1325 /* As specified in IEEE 754, since we do not trap we do not report
1326 underflow for exact results. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001327 if (lost_fraction == lfExactlyZero) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001328 /* Canonicalize zeroes. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001329 if (omsb == 0)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001330 category = fcZero;
1331
1332 return opOK;
1333 }
1334
1335 /* Increment the significand if we're rounding away from zero. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001336 if (roundAwayFromZero(rounding_mode, lost_fraction, 0)) {
1337 if (omsb == 0)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001338 exponent = semantics->minExponent;
1339
1340 incrementSignificand();
1341 omsb = significandMSB() + 1;
1342
1343 /* Did the significand increment overflow? */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001344 if (omsb == (unsigned) semantics->precision + 1) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001345 /* Renormalize by incrementing the exponent and shifting our
Neil Booth9acbf5a2007-09-26 21:33:42 +00001346 significand right one. However if we already have the
1347 maximum exponent we overflow to infinity. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001348 if (exponent == semantics->maxExponent) {
Neil Booth9acbf5a2007-09-26 21:33:42 +00001349 category = fcInfinity;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001350
Neil Booth9acbf5a2007-09-26 21:33:42 +00001351 return (opStatus) (opOverflow | opInexact);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001352 }
1353
1354 shiftSignificandRight(1);
1355
1356 return opInexact;
1357 }
1358 }
1359
1360 /* The normal case - we were and are not denormal, and any
1361 significand increment above didn't overflow. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001362 if (omsb == semantics->precision)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001363 return opInexact;
1364
1365 /* We have a non-zero denormal. */
1366 assert(omsb < semantics->precision);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001367
1368 /* Canonicalize zeroes. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001369 if (omsb == 0)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001370 category = fcZero;
1371
1372 /* The fcZero case is a denormal that underflowed to zero. */
1373 return (opStatus) (opUnderflow | opInexact);
1374}
1375
Tim Shen85de51d2016-10-25 19:55:59 +00001376IEEEFloat::opStatus IEEEFloat::addOrSubtractSpecials(const IEEEFloat &rhs,
1377 bool subtract) {
Michael Gottesman9b877e12013-06-24 09:57:57 +00001378 switch (PackCategoriesIntoKey(category, rhs.category)) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001379 default:
Craig Topper2617dcc2014-04-15 06:32:26 +00001380 llvm_unreachable(nullptr);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001381
Michael Gottesman9b877e12013-06-24 09:57:57 +00001382 case PackCategoriesIntoKey(fcNaN, fcZero):
1383 case PackCategoriesIntoKey(fcNaN, fcNormal):
1384 case PackCategoriesIntoKey(fcNaN, fcInfinity):
1385 case PackCategoriesIntoKey(fcNaN, fcNaN):
1386 case PackCategoriesIntoKey(fcNormal, fcZero):
1387 case PackCategoriesIntoKey(fcInfinity, fcNormal):
1388 case PackCategoriesIntoKey(fcInfinity, fcZero):
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001389 return opOK;
1390
Michael Gottesman9b877e12013-06-24 09:57:57 +00001391 case PackCategoriesIntoKey(fcZero, fcNaN):
1392 case PackCategoriesIntoKey(fcNormal, fcNaN):
1393 case PackCategoriesIntoKey(fcInfinity, fcNaN):
Stephen Canond3278282014-06-08 16:53:31 +00001394 // We need to be sure to flip the sign here for subtraction because we
1395 // don't have a separate negate operation so -NaN becomes 0 - NaN here.
1396 sign = rhs.sign ^ subtract;
Dale Johannesen3cf889f2007-08-31 04:03:46 +00001397 category = fcNaN;
1398 copySignificand(rhs);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001399 return opOK;
1400
Michael Gottesman9b877e12013-06-24 09:57:57 +00001401 case PackCategoriesIntoKey(fcNormal, fcInfinity):
1402 case PackCategoriesIntoKey(fcZero, fcInfinity):
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001403 category = fcInfinity;
1404 sign = rhs.sign ^ subtract;
1405 return opOK;
1406
Michael Gottesman9b877e12013-06-24 09:57:57 +00001407 case PackCategoriesIntoKey(fcZero, fcNormal):
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001408 assign(rhs);
1409 sign = rhs.sign ^ subtract;
1410 return opOK;
1411
Michael Gottesman9b877e12013-06-24 09:57:57 +00001412 case PackCategoriesIntoKey(fcZero, fcZero):
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001413 /* Sign depends on rounding mode; handled by caller. */
1414 return opOK;
1415
Michael Gottesman9b877e12013-06-24 09:57:57 +00001416 case PackCategoriesIntoKey(fcInfinity, fcInfinity):
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001417 /* Differently signed infinities can only be validly
1418 subtracted. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001419 if (((sign ^ rhs.sign)!=0) != subtract) {
Neil Booth5fe658b2007-10-14 10:39:51 +00001420 makeNaN();
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001421 return opInvalidOp;
1422 }
1423
1424 return opOK;
1425
Michael Gottesman9b877e12013-06-24 09:57:57 +00001426 case PackCategoriesIntoKey(fcNormal, fcNormal):
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001427 return opDivByZero;
1428 }
1429}
1430
1431/* Add or subtract two normal numbers. */
Tim Shen85de51d2016-10-25 19:55:59 +00001432lostFraction IEEEFloat::addOrSubtractSignificand(const IEEEFloat &rhs,
1433 bool subtract) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001434 integerPart carry;
1435 lostFraction lost_fraction;
1436 int bits;
1437
1438 /* Determine if the operation on the absolute values is effectively
1439 an addition or subtraction. */
Aaron Ballmand5cc45f2015-03-24 12:47:51 +00001440 subtract ^= static_cast<bool>(sign ^ rhs.sign);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001441
1442 /* Are we bigger exponent-wise than the RHS? */
1443 bits = exponent - rhs.exponent;
1444
1445 /* Subtraction is more subtle than one might naively expect. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001446 if (subtract) {
Tim Shen85de51d2016-10-25 19:55:59 +00001447 IEEEFloat temp_rhs(rhs);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001448 bool reverse;
1449
Chris Lattner3da18eb2007-08-24 03:02:34 +00001450 if (bits == 0) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001451 reverse = compareAbsoluteValue(temp_rhs) == cmpLessThan;
1452 lost_fraction = lfExactlyZero;
Chris Lattner3da18eb2007-08-24 03:02:34 +00001453 } else if (bits > 0) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001454 lost_fraction = temp_rhs.shiftSignificandRight(bits - 1);
1455 shiftSignificandLeft(1);
1456 reverse = false;
Chris Lattner3da18eb2007-08-24 03:02:34 +00001457 } else {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001458 lost_fraction = shiftSignificandRight(-bits - 1);
1459 temp_rhs.shiftSignificandLeft(1);
1460 reverse = true;
1461 }
1462
Chris Lattner3da18eb2007-08-24 03:02:34 +00001463 if (reverse) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001464 carry = temp_rhs.subtractSignificand
Neil Booth9acbf5a2007-09-26 21:33:42 +00001465 (*this, lost_fraction != lfExactlyZero);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001466 copySignificand(temp_rhs);
1467 sign = !sign;
1468 } else {
1469 carry = subtractSignificand
Neil Booth9acbf5a2007-09-26 21:33:42 +00001470 (temp_rhs, lost_fraction != lfExactlyZero);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001471 }
1472
1473 /* Invert the lost fraction - it was on the RHS and
1474 subtracted. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001475 if (lost_fraction == lfLessThanHalf)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001476 lost_fraction = lfMoreThanHalf;
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001477 else if (lost_fraction == lfMoreThanHalf)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001478 lost_fraction = lfLessThanHalf;
1479
1480 /* The code above is intended to ensure that no borrow is
1481 necessary. */
1482 assert(!carry);
Duncan Sandsa41634e2011-08-12 14:54:45 +00001483 (void)carry;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001484 } else {
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001485 if (bits > 0) {
Tim Shen85de51d2016-10-25 19:55:59 +00001486 IEEEFloat temp_rhs(rhs);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001487
1488 lost_fraction = temp_rhs.shiftSignificandRight(bits);
1489 carry = addSignificand(temp_rhs);
1490 } else {
1491 lost_fraction = shiftSignificandRight(-bits);
1492 carry = addSignificand(rhs);
1493 }
1494
1495 /* We have a guard bit; generating a carry cannot happen. */
1496 assert(!carry);
Duncan Sandsa41634e2011-08-12 14:54:45 +00001497 (void)carry;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001498 }
1499
1500 return lost_fraction;
1501}
1502
Tim Shen85de51d2016-10-25 19:55:59 +00001503IEEEFloat::opStatus IEEEFloat::multiplySpecials(const IEEEFloat &rhs) {
Michael Gottesman9b877e12013-06-24 09:57:57 +00001504 switch (PackCategoriesIntoKey(category, rhs.category)) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001505 default:
Craig Topper2617dcc2014-04-15 06:32:26 +00001506 llvm_unreachable(nullptr);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001507
Michael Gottesman9b877e12013-06-24 09:57:57 +00001508 case PackCategoriesIntoKey(fcNaN, fcZero):
1509 case PackCategoriesIntoKey(fcNaN, fcNormal):
1510 case PackCategoriesIntoKey(fcNaN, fcInfinity):
1511 case PackCategoriesIntoKey(fcNaN, fcNaN):
Michael Gottesmanb0e688e2013-07-27 21:49:25 +00001512 sign = false;
Dale Johannesen3cf889f2007-08-31 04:03:46 +00001513 return opOK;
1514
Michael Gottesman9b877e12013-06-24 09:57:57 +00001515 case PackCategoriesIntoKey(fcZero, fcNaN):
1516 case PackCategoriesIntoKey(fcNormal, fcNaN):
1517 case PackCategoriesIntoKey(fcInfinity, fcNaN):
Michael Gottesmanb0e688e2013-07-27 21:49:25 +00001518 sign = false;
Dale Johannesen3cf889f2007-08-31 04:03:46 +00001519 category = fcNaN;
1520 copySignificand(rhs);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001521 return opOK;
1522
Michael Gottesman9b877e12013-06-24 09:57:57 +00001523 case PackCategoriesIntoKey(fcNormal, fcInfinity):
1524 case PackCategoriesIntoKey(fcInfinity, fcNormal):
1525 case PackCategoriesIntoKey(fcInfinity, fcInfinity):
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001526 category = fcInfinity;
1527 return opOK;
1528
Michael Gottesman9b877e12013-06-24 09:57:57 +00001529 case PackCategoriesIntoKey(fcZero, fcNormal):
1530 case PackCategoriesIntoKey(fcNormal, fcZero):
1531 case PackCategoriesIntoKey(fcZero, fcZero):
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001532 category = fcZero;
1533 return opOK;
1534
Michael Gottesman9b877e12013-06-24 09:57:57 +00001535 case PackCategoriesIntoKey(fcZero, fcInfinity):
1536 case PackCategoriesIntoKey(fcInfinity, fcZero):
Neil Booth5fe658b2007-10-14 10:39:51 +00001537 makeNaN();
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001538 return opInvalidOp;
1539
Michael Gottesman9b877e12013-06-24 09:57:57 +00001540 case PackCategoriesIntoKey(fcNormal, fcNormal):
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001541 return opOK;
1542 }
1543}
1544
Tim Shen85de51d2016-10-25 19:55:59 +00001545IEEEFloat::opStatus IEEEFloat::divideSpecials(const IEEEFloat &rhs) {
Michael Gottesman9b877e12013-06-24 09:57:57 +00001546 switch (PackCategoriesIntoKey(category, rhs.category)) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001547 default:
Craig Topper2617dcc2014-04-15 06:32:26 +00001548 llvm_unreachable(nullptr);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001549
Michael Gottesman9b877e12013-06-24 09:57:57 +00001550 case PackCategoriesIntoKey(fcZero, fcNaN):
1551 case PackCategoriesIntoKey(fcNormal, fcNaN):
1552 case PackCategoriesIntoKey(fcInfinity, fcNaN):
Dale Johannesen3cf889f2007-08-31 04:03:46 +00001553 category = fcNaN;
1554 copySignificand(rhs);
Galina Kistanova5c4f1a92017-05-30 03:30:34 +00001555 LLVM_FALLTHROUGH;
Michael Gottesmanb0e688e2013-07-27 21:49:25 +00001556 case PackCategoriesIntoKey(fcNaN, fcZero):
1557 case PackCategoriesIntoKey(fcNaN, fcNormal):
1558 case PackCategoriesIntoKey(fcNaN, fcInfinity):
1559 case PackCategoriesIntoKey(fcNaN, fcNaN):
1560 sign = false;
Galina Kistanova5c4f1a92017-05-30 03:30:34 +00001561 LLVM_FALLTHROUGH;
Michael Gottesmanb0e688e2013-07-27 21:49:25 +00001562 case PackCategoriesIntoKey(fcInfinity, fcZero):
1563 case PackCategoriesIntoKey(fcInfinity, fcNormal):
1564 case PackCategoriesIntoKey(fcZero, fcInfinity):
1565 case PackCategoriesIntoKey(fcZero, fcNormal):
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001566 return opOK;
1567
Michael Gottesman9b877e12013-06-24 09:57:57 +00001568 case PackCategoriesIntoKey(fcNormal, fcInfinity):
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001569 category = fcZero;
1570 return opOK;
1571
Michael Gottesman9b877e12013-06-24 09:57:57 +00001572 case PackCategoriesIntoKey(fcNormal, fcZero):
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001573 category = fcInfinity;
1574 return opDivByZero;
1575
Michael Gottesman9b877e12013-06-24 09:57:57 +00001576 case PackCategoriesIntoKey(fcInfinity, fcInfinity):
1577 case PackCategoriesIntoKey(fcZero, fcZero):
Neil Booth5fe658b2007-10-14 10:39:51 +00001578 makeNaN();
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001579 return opInvalidOp;
1580
Michael Gottesman9b877e12013-06-24 09:57:57 +00001581 case PackCategoriesIntoKey(fcNormal, fcNormal):
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001582 return opOK;
1583 }
1584}
1585
Tim Shen85de51d2016-10-25 19:55:59 +00001586IEEEFloat::opStatus IEEEFloat::modSpecials(const IEEEFloat &rhs) {
Michael Gottesman9b877e12013-06-24 09:57:57 +00001587 switch (PackCategoriesIntoKey(category, rhs.category)) {
Dale Johannesenb5721632009-01-21 00:35:19 +00001588 default:
Craig Topper2617dcc2014-04-15 06:32:26 +00001589 llvm_unreachable(nullptr);
Dale Johannesenb5721632009-01-21 00:35:19 +00001590
Michael Gottesman9b877e12013-06-24 09:57:57 +00001591 case PackCategoriesIntoKey(fcNaN, fcZero):
1592 case PackCategoriesIntoKey(fcNaN, fcNormal):
1593 case PackCategoriesIntoKey(fcNaN, fcInfinity):
1594 case PackCategoriesIntoKey(fcNaN, fcNaN):
1595 case PackCategoriesIntoKey(fcZero, fcInfinity):
1596 case PackCategoriesIntoKey(fcZero, fcNormal):
1597 case PackCategoriesIntoKey(fcNormal, fcInfinity):
Dale Johannesenb5721632009-01-21 00:35:19 +00001598 return opOK;
1599
Michael Gottesman9b877e12013-06-24 09:57:57 +00001600 case PackCategoriesIntoKey(fcZero, fcNaN):
1601 case PackCategoriesIntoKey(fcNormal, fcNaN):
1602 case PackCategoriesIntoKey(fcInfinity, fcNaN):
Michael Gottesmanb0e688e2013-07-27 21:49:25 +00001603 sign = false;
Dale Johannesenb5721632009-01-21 00:35:19 +00001604 category = fcNaN;
1605 copySignificand(rhs);
1606 return opOK;
1607
Michael Gottesman9b877e12013-06-24 09:57:57 +00001608 case PackCategoriesIntoKey(fcNormal, fcZero):
1609 case PackCategoriesIntoKey(fcInfinity, fcZero):
1610 case PackCategoriesIntoKey(fcInfinity, fcNormal):
1611 case PackCategoriesIntoKey(fcInfinity, fcInfinity):
1612 case PackCategoriesIntoKey(fcZero, fcZero):
Dale Johannesenb5721632009-01-21 00:35:19 +00001613 makeNaN();
1614 return opInvalidOp;
1615
Michael Gottesman9b877e12013-06-24 09:57:57 +00001616 case PackCategoriesIntoKey(fcNormal, fcNormal):
Dale Johannesenb5721632009-01-21 00:35:19 +00001617 return opOK;
1618 }
1619}
1620
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001621/* Change sign. */
Tim Shen85de51d2016-10-25 19:55:59 +00001622void IEEEFloat::changeSign() {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001623 /* Look mummy, this one's easy. */
1624 sign = !sign;
1625}
1626
1627/* Normalized addition or subtraction. */
Tim Shen85de51d2016-10-25 19:55:59 +00001628IEEEFloat::opStatus IEEEFloat::addOrSubtract(const IEEEFloat &rhs,
1629 roundingMode rounding_mode,
1630 bool subtract) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001631 opStatus fs;
1632
1633 fs = addOrSubtractSpecials(rhs, subtract);
1634
1635 /* This return code means it was not a simple case. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001636 if (fs == opDivByZero) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001637 lostFraction lost_fraction;
1638
1639 lost_fraction = addOrSubtractSignificand(rhs, subtract);
1640 fs = normalize(rounding_mode, lost_fraction);
1641
1642 /* Can only be zero if we lost no fraction. */
1643 assert(category != fcZero || lost_fraction == lfExactlyZero);
1644 }
1645
1646 /* If two numbers add (exactly) to zero, IEEE 754 decrees it is a
1647 positive zero unless rounding to minus infinity, except that
1648 adding two like-signed zeroes gives that zero. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001649 if (category == fcZero) {
1650 if (rhs.category != fcZero || (sign == rhs.sign) == subtract)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001651 sign = (rounding_mode == rmTowardNegative);
1652 }
1653
1654 return fs;
1655}
1656
1657/* Normalized addition. */
Tim Shen85de51d2016-10-25 19:55:59 +00001658IEEEFloat::opStatus IEEEFloat::add(const IEEEFloat &rhs,
1659 roundingMode rounding_mode) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001660 return addOrSubtract(rhs, rounding_mode, false);
1661}
1662
1663/* Normalized subtraction. */
Tim Shen85de51d2016-10-25 19:55:59 +00001664IEEEFloat::opStatus IEEEFloat::subtract(const IEEEFloat &rhs,
1665 roundingMode rounding_mode) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001666 return addOrSubtract(rhs, rounding_mode, true);
1667}
1668
1669/* Normalized multiply. */
Tim Shen85de51d2016-10-25 19:55:59 +00001670IEEEFloat::opStatus IEEEFloat::multiply(const IEEEFloat &rhs,
1671 roundingMode rounding_mode) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001672 opStatus fs;
1673
1674 sign ^= rhs.sign;
1675 fs = multiplySpecials(rhs);
1676
Michael Gottesman8136c382013-06-26 23:17:28 +00001677 if (isFiniteNonZero()) {
Craig Topperc10719f2014-04-07 04:17:22 +00001678 lostFraction lost_fraction = multiplySignificand(rhs, nullptr);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001679 fs = normalize(rounding_mode, lost_fraction);
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001680 if (lost_fraction != lfExactlyZero)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001681 fs = (opStatus) (fs | opInexact);
1682 }
1683
1684 return fs;
1685}
1686
1687/* Normalized divide. */
Tim Shen85de51d2016-10-25 19:55:59 +00001688IEEEFloat::opStatus IEEEFloat::divide(const IEEEFloat &rhs,
1689 roundingMode rounding_mode) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001690 opStatus fs;
1691
1692 sign ^= rhs.sign;
1693 fs = divideSpecials(rhs);
1694
Michael Gottesman8136c382013-06-26 23:17:28 +00001695 if (isFiniteNonZero()) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001696 lostFraction lost_fraction = divideSignificand(rhs);
1697 fs = normalize(rounding_mode, lost_fraction);
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001698 if (lost_fraction != lfExactlyZero)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001699 fs = (opStatus) (fs | opInexact);
1700 }
1701
1702 return fs;
1703}
1704
Dale Johannesenfe750172009-01-20 18:35:05 +00001705/* Normalized remainder. This is not currently correct in all cases. */
Tim Shen85de51d2016-10-25 19:55:59 +00001706IEEEFloat::opStatus IEEEFloat::remainder(const IEEEFloat &rhs) {
Dale Johannesenfe750172009-01-20 18:35:05 +00001707 opStatus fs;
Tim Shen85de51d2016-10-25 19:55:59 +00001708 IEEEFloat V = *this;
Dale Johannesenfe750172009-01-20 18:35:05 +00001709 unsigned int origSign = sign;
1710
Dale Johannesenfe750172009-01-20 18:35:05 +00001711 fs = V.divide(rhs, rmNearestTiesToEven);
1712 if (fs == opDivByZero)
1713 return fs;
1714
1715 int parts = partCount();
Dylan Noblesmith4e69e292014-08-26 02:03:33 +00001716 integerPart *x = new integerPart[parts];
Dale Johannesenfe750172009-01-20 18:35:05 +00001717 bool ignored;
Simon Pilgrim00b34992017-03-20 14:40:12 +00001718 fs = V.convertToInteger(makeMutableArrayRef(x, parts),
1719 parts * integerPartWidth, true, rmNearestTiesToEven,
1720 &ignored);
1721 if (fs == opInvalidOp) {
Sylvestre Ledru3ce346d2016-11-08 10:00:45 +00001722 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
Stephen Canon157c8692017-03-31 20:31:33 +00001742/* Normalized llvm frem (C fmod). */
Tim Shen85de51d2016-10-25 19:55:59 +00001743IEEEFloat::opStatus IEEEFloat::mod(const IEEEFloat &rhs) {
Dale Johannesen689d17d2007-08-31 23:35:31 +00001744 opStatus fs;
Dale Johannesenb5721632009-01-21 00:35:19 +00001745 fs = modSpecials(rhs);
Serguei Katkovf2c28512017-11-01 07:56:55 +00001746 unsigned int origSign = sign;
Dale Johannesen689d17d2007-08-31 23:35:31 +00001747
Stephen Canon157c8692017-03-31 20:31:33 +00001748 while (isFiniteNonZero() && rhs.isFiniteNonZero() &&
1749 compareAbsoluteValue(rhs) != cmpLessThan) {
1750 IEEEFloat V = scalbn(rhs, ilogb(*this) - ilogb(rhs), rmNearestTiesToEven);
1751 if (compareAbsoluteValue(V) == cmpLessThan)
1752 V = scalbn(V, -1, rmNearestTiesToEven);
1753 V.sign = sign;
Fangrui Songf78650a2018-07-30 19:41:25 +00001754
Stephen Canonb12db0e2015-09-21 19:29:25 +00001755 fs = subtract(V, rmNearestTiesToEven);
Stephen Canon157c8692017-03-31 20:31:33 +00001756 assert(fs==opOK);
Dale Johannesenb5721632009-01-21 00:35:19 +00001757 }
Serguei Katkovf2c28512017-11-01 07:56:55 +00001758 if (isZero())
1759 sign = origSign; // fmod requires this
Dale Johannesen689d17d2007-08-31 23:35:31 +00001760 return fs;
1761}
1762
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001763/* Normalized fused-multiply-add. */
Tim Shen85de51d2016-10-25 19:55:59 +00001764IEEEFloat::opStatus IEEEFloat::fusedMultiplyAdd(const IEEEFloat &multiplicand,
1765 const IEEEFloat &addend,
1766 roundingMode rounding_mode) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001767 opStatus fs;
1768
1769 /* Post-multiplication sign, before addition. */
1770 sign ^= multiplicand.sign;
1771
1772 /* If and only if all arguments are normal do we need to do an
1773 extended-precision calculation. */
Michael Gottesman8136c382013-06-26 23:17:28 +00001774 if (isFiniteNonZero() &&
1775 multiplicand.isFiniteNonZero() &&
Hal Finkel171c2ec2014-10-14 19:23:07 +00001776 addend.isFinite()) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001777 lostFraction lost_fraction;
1778
1779 lost_fraction = multiplySignificand(multiplicand, &addend);
1780 fs = normalize(rounding_mode, lost_fraction);
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001781 if (lost_fraction != lfExactlyZero)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001782 fs = (opStatus) (fs | opInexact);
1783
1784 /* If two numbers add (exactly) to zero, IEEE 754 decrees it is a
1785 positive zero unless rounding to minus infinity, except that
1786 adding two like-signed zeroes gives that zero. */
Lang Hames12b12e82015-01-04 01:20:55 +00001787 if (category == fcZero && !(fs & opUnderflow) && sign != addend.sign)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001788 sign = (rounding_mode == rmTowardNegative);
1789 } else {
1790 fs = multiplySpecials(multiplicand);
1791
1792 /* FS can only be opOK or opInvalidOp. There is no more work
1793 to do in the latter case. The IEEE-754R standard says it is
1794 implementation-defined in this case whether, if ADDEND is a
Dale Johannesen3cf889f2007-08-31 04:03:46 +00001795 quiet NaN, we raise invalid op; this implementation does so.
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001796
1797 If we need to do the addition we can do so with normal
1798 precision. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001799 if (fs == opOK)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001800 fs = addOrSubtract(addend, rounding_mode, false);
1801 }
1802
1803 return fs;
1804}
1805
Owen Andersona40319b2012-08-13 23:32:49 +00001806/* Rounding-mode corrrect round to integral value. */
Tim Shen85de51d2016-10-25 19:55:59 +00001807IEEEFloat::opStatus IEEEFloat::roundToIntegral(roundingMode rounding_mode) {
Owen Andersona40319b2012-08-13 23:32:49 +00001808 opStatus fs;
Owen Andersona40319b2012-08-13 23:32:49 +00001809
Owen Anderson352dfff2012-08-15 18:28:45 +00001810 // If the exponent is large enough, we know that this value is already
1811 // integral, and the arithmetic below would potentially cause it to saturate
1812 // to +/-Inf. Bail out early instead.
Michael Gottesman8136c382013-06-26 23:17:28 +00001813 if (isFiniteNonZero() && exponent+1 >= (int)semanticsPrecision(*semantics))
Owen Anderson352dfff2012-08-15 18:28:45 +00001814 return opOK;
1815
Owen Andersona40319b2012-08-13 23:32:49 +00001816 // The algorithm here is quite simple: we add 2^(p-1), where p is the
1817 // precision of our format, and then subtract it back off again. The choice
1818 // of rounding modes for the addition/subtraction determines the rounding mode
1819 // for our integral rounding as well.
Owen Andersonbe7e2972012-08-15 16:42:53 +00001820 // NOTE: When the input value is negative, we do subtraction followed by
Owen Anderson1ff74b02012-08-15 05:39:46 +00001821 // addition instead.
Owen Anderson0b357222012-08-14 18:51:15 +00001822 APInt IntegerConstant(NextPowerOf2(semanticsPrecision(*semantics)), 1);
1823 IntegerConstant <<= semanticsPrecision(*semantics)-1;
Tim Shen85de51d2016-10-25 19:55:59 +00001824 IEEEFloat MagicConstant(*semantics);
Owen Andersona40319b2012-08-13 23:32:49 +00001825 fs = MagicConstant.convertFromAPInt(IntegerConstant, false,
1826 rmNearestTiesToEven);
Tim Shenfd1e5aa2017-01-23 22:39:35 +00001827 MagicConstant.sign = sign;
Owen Anderson1ff74b02012-08-15 05:39:46 +00001828
Owen Andersona40319b2012-08-13 23:32:49 +00001829 if (fs != opOK)
1830 return fs;
1831
Owen Anderson1ff74b02012-08-15 05:39:46 +00001832 // Preserve the input sign so that we can handle 0.0/-0.0 cases correctly.
1833 bool inputSign = isNegative();
1834
Owen Andersona40319b2012-08-13 23:32:49 +00001835 fs = add(MagicConstant, rounding_mode);
1836 if (fs != opOK && fs != opInexact)
1837 return fs;
1838
1839 fs = subtract(MagicConstant, rounding_mode);
Owen Anderson1ff74b02012-08-15 05:39:46 +00001840
1841 // Restore the input sign.
1842 if (inputSign != isNegative())
1843 changeSign();
1844
Owen Andersona40319b2012-08-13 23:32:49 +00001845 return fs;
1846}
1847
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +00001848
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001849/* Comparison requires normalized numbers. */
Tim Shen85de51d2016-10-25 19:55:59 +00001850IEEEFloat::cmpResult IEEEFloat::compare(const IEEEFloat &rhs) const {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001851 cmpResult result;
1852
1853 assert(semantics == rhs.semantics);
1854
Michael Gottesman9b877e12013-06-24 09:57:57 +00001855 switch (PackCategoriesIntoKey(category, rhs.category)) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001856 default:
Craig Topper2617dcc2014-04-15 06:32:26 +00001857 llvm_unreachable(nullptr);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001858
Michael Gottesman9b877e12013-06-24 09:57:57 +00001859 case PackCategoriesIntoKey(fcNaN, fcZero):
1860 case PackCategoriesIntoKey(fcNaN, fcNormal):
1861 case PackCategoriesIntoKey(fcNaN, fcInfinity):
1862 case PackCategoriesIntoKey(fcNaN, fcNaN):
1863 case PackCategoriesIntoKey(fcZero, fcNaN):
1864 case PackCategoriesIntoKey(fcNormal, fcNaN):
1865 case PackCategoriesIntoKey(fcInfinity, fcNaN):
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001866 return cmpUnordered;
1867
Michael Gottesman9b877e12013-06-24 09:57:57 +00001868 case PackCategoriesIntoKey(fcInfinity, fcNormal):
1869 case PackCategoriesIntoKey(fcInfinity, fcZero):
1870 case PackCategoriesIntoKey(fcNormal, fcZero):
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001871 if (sign)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001872 return cmpLessThan;
1873 else
1874 return cmpGreaterThan;
1875
Michael Gottesman9b877e12013-06-24 09:57:57 +00001876 case PackCategoriesIntoKey(fcNormal, fcInfinity):
1877 case PackCategoriesIntoKey(fcZero, fcInfinity):
1878 case PackCategoriesIntoKey(fcZero, fcNormal):
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001879 if (rhs.sign)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001880 return cmpGreaterThan;
1881 else
1882 return cmpLessThan;
1883
Michael Gottesman9b877e12013-06-24 09:57:57 +00001884 case PackCategoriesIntoKey(fcInfinity, fcInfinity):
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001885 if (sign == rhs.sign)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001886 return cmpEqual;
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001887 else if (sign)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001888 return cmpLessThan;
1889 else
1890 return cmpGreaterThan;
1891
Michael Gottesman9b877e12013-06-24 09:57:57 +00001892 case PackCategoriesIntoKey(fcZero, fcZero):
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001893 return cmpEqual;
1894
Michael Gottesman9b877e12013-06-24 09:57:57 +00001895 case PackCategoriesIntoKey(fcNormal, fcNormal):
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001896 break;
1897 }
1898
1899 /* Two normal numbers. Do they have the same sign? */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001900 if (sign != rhs.sign) {
1901 if (sign)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001902 result = cmpLessThan;
1903 else
1904 result = cmpGreaterThan;
1905 } else {
1906 /* Compare absolute values; invert result if negative. */
1907 result = compareAbsoluteValue(rhs);
1908
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001909 if (sign) {
1910 if (result == cmpLessThan)
Neil Booth9acbf5a2007-09-26 21:33:42 +00001911 result = cmpGreaterThan;
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001912 else if (result == cmpGreaterThan)
Neil Booth9acbf5a2007-09-26 21:33:42 +00001913 result = cmpLessThan;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001914 }
1915 }
1916
1917 return result;
1918}
1919
Tim Shen85de51d2016-10-25 19:55:59 +00001920/// IEEEFloat::convert - convert a value of one floating point type to another.
Dale Johannesen4f0bd682008-10-09 23:00:39 +00001921/// The return value corresponds to the IEEE754 exceptions. *losesInfo
1922/// records whether the transformation lost information, i.e. whether
1923/// converting the result back to the original type will produce the
1924/// original value (this is almost the same as return value==fsOK, but there
1925/// are edge cases where this is not so).
1926
Tim Shen85de51d2016-10-25 19:55:59 +00001927IEEEFloat::opStatus IEEEFloat::convert(const fltSemantics &toSemantics,
1928 roundingMode rounding_mode,
1929 bool *losesInfo) {
Neil Bootha8d72692007-09-22 02:56:19 +00001930 lostFraction lostFraction;
1931 unsigned int newPartCount, oldPartCount;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001932 opStatus fs;
Eli Friedmana84ad7d2011-11-26 03:38:02 +00001933 int shift;
1934 const fltSemantics &fromSemantics = *semantics;
Neil Booth9acbf5a2007-09-26 21:33:42 +00001935
Neil Bootha8d72692007-09-22 02:56:19 +00001936 lostFraction = lfExactlyZero;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001937 newPartCount = partCountForBits(toSemantics.precision + 1);
Neil Bootha8d72692007-09-22 02:56:19 +00001938 oldPartCount = partCount();
Eli Friedmana84ad7d2011-11-26 03:38:02 +00001939 shift = toSemantics.precision - fromSemantics.precision;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001940
Eli Friedmana84ad7d2011-11-26 03:38:02 +00001941 bool X86SpecialNan = false;
Stephan Bergmann17c7f702016-12-14 11:57:17 +00001942 if (&fromSemantics == &semX87DoubleExtended &&
1943 &toSemantics != &semX87DoubleExtended && category == fcNaN &&
Eli Friedmana84ad7d2011-11-26 03:38:02 +00001944 (!(*significandParts() & 0x8000000000000000ULL) ||
1945 !(*significandParts() & 0x4000000000000000ULL))) {
1946 // x86 has some unusual NaNs which cannot be represented in any other
1947 // format; note them here.
1948 X86SpecialNan = true;
1949 }
1950
Ulrich Weigand1d4dbda2013-07-16 13:03:25 +00001951 // If this is a truncation of a denormal number, and the target semantics
1952 // has larger exponent range than the source semantics (this can happen
1953 // when truncating from PowerPC double-double to double format), the
1954 // right shift could lose result mantissa bits. Adjust exponent instead
1955 // of performing excessive shift.
1956 if (shift < 0 && isFiniteNonZero()) {
1957 int exponentChange = significandMSB() + 1 - fromSemantics.precision;
1958 if (exponent + exponentChange < toSemantics.minExponent)
1959 exponentChange = toSemantics.minExponent - exponent;
1960 if (exponentChange < shift)
1961 exponentChange = shift;
1962 if (exponentChange < 0) {
1963 shift -= exponentChange;
1964 exponent += exponentChange;
1965 }
1966 }
1967
Eli Friedmana84ad7d2011-11-26 03:38:02 +00001968 // If this is a truncation, perform the shift before we narrow the storage.
Michael Gottesman8136c382013-06-26 23:17:28 +00001969 if (shift < 0 && (isFiniteNonZero() || category==fcNaN))
Eli Friedmana84ad7d2011-11-26 03:38:02 +00001970 lostFraction = shiftRight(significandParts(), oldPartCount, -shift);
1971
1972 // Fix the storage so it can hold to new value.
Neil Bootha8d72692007-09-22 02:56:19 +00001973 if (newPartCount > oldPartCount) {
Eli Friedmana84ad7d2011-11-26 03:38:02 +00001974 // The new type requires more storage; make it available.
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001975 integerPart *newParts;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001976 newParts = new integerPart[newPartCount];
1977 APInt::tcSet(newParts, 0, newPartCount);
Michael Gottesman8136c382013-06-26 23:17:28 +00001978 if (isFiniteNonZero() || category==fcNaN)
Dale Johannesen4f55d9f2007-09-25 17:25:00 +00001979 APInt::tcAssign(newParts, significandParts(), oldPartCount);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001980 freeSignificand();
1981 significand.parts = newParts;
Eli Friedmana84ad7d2011-11-26 03:38:02 +00001982 } else if (newPartCount == 1 && oldPartCount != 1) {
1983 // Switch to built-in storage for a single part.
1984 integerPart newPart = 0;
Michael Gottesman8136c382013-06-26 23:17:28 +00001985 if (isFiniteNonZero() || category==fcNaN)
Eli Friedmana84ad7d2011-11-26 03:38:02 +00001986 newPart = significandParts()[0];
1987 freeSignificand();
1988 significand.part = newPart;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001989 }
1990
Eli Friedmana84ad7d2011-11-26 03:38:02 +00001991 // Now that we have the right storage, switch the semantics.
1992 semantics = &toSemantics;
1993
1994 // If this is an extension, perform the shift now that the storage is
1995 // available.
Michael Gottesman8136c382013-06-26 23:17:28 +00001996 if (shift > 0 && (isFiniteNonZero() || category==fcNaN))
Eli Friedmana84ad7d2011-11-26 03:38:02 +00001997 APInt::tcShiftLeft(significandParts(), newPartCount, shift);
1998
Michael Gottesman8136c382013-06-26 23:17:28 +00001999 if (isFiniteNonZero()) {
Neil Bootha8d72692007-09-22 02:56:19 +00002000 fs = normalize(rounding_mode, lostFraction);
Dale Johannesen4f0bd682008-10-09 23:00:39 +00002001 *losesInfo = (fs != opOK);
Dale Johannesen4f55d9f2007-09-25 17:25:00 +00002002 } else if (category == fcNaN) {
Eli Friedmana84ad7d2011-11-26 03:38:02 +00002003 *losesInfo = lostFraction != lfExactlyZero || X86SpecialNan;
Benjamin Kramerb361adb2013-01-25 17:01:00 +00002004
2005 // For x87 extended precision, we want to make a NaN, not a special NaN if
2006 // the input wasn't special either.
Stephan Bergmann17c7f702016-12-14 11:57:17 +00002007 if (!X86SpecialNan && semantics == &semX87DoubleExtended)
Benjamin Kramerb361adb2013-01-25 17:01:00 +00002008 APInt::tcSetBit(significandParts(), semantics->precision - 1);
2009
Dale Johannesen4f55d9f2007-09-25 17:25:00 +00002010 // gcc forces the Quiet bit on, which means (float)(double)(float_sNan)
2011 // does not give you back the same bits. This is dubious, and we
2012 // don't currently do it. You're really supposed to get
2013 // an invalid operation signal at runtime, but nobody does that.
Dale Johannesen4f0bd682008-10-09 23:00:39 +00002014 fs = opOK;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002015 } else {
Dale Johannesen4f0bd682008-10-09 23:00:39 +00002016 *losesInfo = false;
Eli Friedman31f01162011-11-28 18:50:37 +00002017 fs = opOK;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002018 }
2019
2020 return fs;
2021}
2022
2023/* Convert a floating point number to an integer according to the
2024 rounding mode. If the rounded integer value is out of range this
Neil Booth618d0fc2007-11-01 22:43:37 +00002025 returns an invalid operation exception and the contents of the
2026 destination parts are unspecified. If the rounded value is in
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002027 range but the floating point number is not the exact integer, the C
2028 standard doesn't require an inexact exception to be raised. IEEE
2029 854 does require it so we do that.
2030
2031 Note that for conversions to integer type the C standard requires
2032 round-to-zero to always be used. */
Tim Shen85de51d2016-10-25 19:55:59 +00002033IEEEFloat::opStatus IEEEFloat::convertToSignExtendedInteger(
Simon Pilgrim00b34992017-03-20 14:40:12 +00002034 MutableArrayRef<integerPart> parts, unsigned int width, bool isSigned,
Tim Shen85de51d2016-10-25 19:55:59 +00002035 roundingMode rounding_mode, bool *isExact) const {
Neil Booth618d0fc2007-11-01 22:43:37 +00002036 lostFraction lost_fraction;
2037 const integerPart *src;
2038 unsigned int dstPartsCount, truncatedBits;
2039
Dale Johannesen4f0bd682008-10-09 23:00:39 +00002040 *isExact = false;
2041
Neil Booth618d0fc2007-11-01 22:43:37 +00002042 /* Handle the three special cases first. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002043 if (category == fcInfinity || category == fcNaN)
Neil Booth618d0fc2007-11-01 22:43:37 +00002044 return opInvalidOp;
2045
2046 dstPartsCount = partCountForBits(width);
Simon Pilgrim00b34992017-03-20 14:40:12 +00002047 assert(dstPartsCount <= parts.size() && "Integer too big");
Neil Booth618d0fc2007-11-01 22:43:37 +00002048
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002049 if (category == fcZero) {
Simon Pilgrim00b34992017-03-20 14:40:12 +00002050 APInt::tcSet(parts.data(), 0, dstPartsCount);
Dale Johannesen7221af32008-10-07 00:40:01 +00002051 // Negative zero can't be represented as an int.
Dale Johannesen4f0bd682008-10-09 23:00:39 +00002052 *isExact = !sign;
2053 return opOK;
Neil Booth618d0fc2007-11-01 22:43:37 +00002054 }
2055
2056 src = significandParts();
2057
2058 /* Step 1: place our absolute value, with any fraction truncated, in
2059 the destination. */
2060 if (exponent < 0) {
2061 /* Our absolute value is less than one; truncate everything. */
Simon Pilgrim00b34992017-03-20 14:40:12 +00002062 APInt::tcSet(parts.data(), 0, dstPartsCount);
Dale Johannesen740e9872009-01-19 21:17:05 +00002063 /* For exponent -1 the integer bit represents .5, look at that.
2064 For smaller exponents leftmost truncated bit is 0. */
2065 truncatedBits = semantics->precision -1U - exponent;
Neil Booth618d0fc2007-11-01 22:43:37 +00002066 } else {
2067 /* We want the most significant (exponent + 1) bits; the rest are
2068 truncated. */
2069 unsigned int bits = exponent + 1U;
2070
2071 /* Hopelessly large in magnitude? */
2072 if (bits > width)
2073 return opInvalidOp;
2074
2075 if (bits < semantics->precision) {
2076 /* We truncate (semantics->precision - bits) bits. */
2077 truncatedBits = semantics->precision - bits;
Simon Pilgrim00b34992017-03-20 14:40:12 +00002078 APInt::tcExtract(parts.data(), dstPartsCount, src, bits, truncatedBits);
Neil Booth618d0fc2007-11-01 22:43:37 +00002079 } else {
2080 /* We want at least as many bits as are available. */
Simon Pilgrim00b34992017-03-20 14:40:12 +00002081 APInt::tcExtract(parts.data(), dstPartsCount, src, semantics->precision,
2082 0);
2083 APInt::tcShiftLeft(parts.data(), dstPartsCount,
2084 bits - semantics->precision);
Neil Booth618d0fc2007-11-01 22:43:37 +00002085 truncatedBits = 0;
2086 }
2087 }
2088
2089 /* Step 2: work out any lost fraction, and increment the absolute
2090 value if we would round away from zero. */
2091 if (truncatedBits) {
2092 lost_fraction = lostFractionThroughTruncation(src, partCount(),
2093 truncatedBits);
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002094 if (lost_fraction != lfExactlyZero &&
2095 roundAwayFromZero(rounding_mode, lost_fraction, truncatedBits)) {
Simon Pilgrim00b34992017-03-20 14:40:12 +00002096 if (APInt::tcIncrement(parts.data(), dstPartsCount))
Neil Booth618d0fc2007-11-01 22:43:37 +00002097 return opInvalidOp; /* Overflow. */
2098 }
2099 } else {
2100 lost_fraction = lfExactlyZero;
2101 }
2102
2103 /* Step 3: check if we fit in the destination. */
Simon Pilgrim00b34992017-03-20 14:40:12 +00002104 unsigned int omsb = APInt::tcMSB(parts.data(), dstPartsCount) + 1;
Neil Booth618d0fc2007-11-01 22:43:37 +00002105
2106 if (sign) {
2107 if (!isSigned) {
2108 /* Negative numbers cannot be represented as unsigned. */
2109 if (omsb != 0)
2110 return opInvalidOp;
2111 } else {
2112 /* It takes omsb bits to represent the unsigned integer value.
2113 We lose a bit for the sign, but care is needed as the
2114 maximally negative integer is a special case. */
Simon Pilgrim00b34992017-03-20 14:40:12 +00002115 if (omsb == width &&
2116 APInt::tcLSB(parts.data(), dstPartsCount) + 1 != omsb)
Neil Booth618d0fc2007-11-01 22:43:37 +00002117 return opInvalidOp;
2118
2119 /* This case can happen because of rounding. */
2120 if (omsb > width)
2121 return opInvalidOp;
2122 }
2123
Simon Pilgrim00b34992017-03-20 14:40:12 +00002124 APInt::tcNegate (parts.data(), dstPartsCount);
Neil Booth618d0fc2007-11-01 22:43:37 +00002125 } else {
2126 if (omsb >= width + !isSigned)
2127 return opInvalidOp;
2128 }
2129
Dale Johannesen4f0bd682008-10-09 23:00:39 +00002130 if (lost_fraction == lfExactlyZero) {
2131 *isExact = true;
Neil Booth618d0fc2007-11-01 22:43:37 +00002132 return opOK;
Dale Johannesen4f0bd682008-10-09 23:00:39 +00002133 } else
Neil Booth618d0fc2007-11-01 22:43:37 +00002134 return opInexact;
2135}
2136
2137/* Same as convertToSignExtendedInteger, except we provide
2138 deterministic values in case of an invalid operation exception,
2139 namely zero for NaNs and the minimal or maximal value respectively
Dale Johannesen4f0bd682008-10-09 23:00:39 +00002140 for underflow or overflow.
2141 The *isExact output tells whether the result is exact, in the sense
2142 that converting it back to the original floating point type produces
2143 the original value. This is almost equivalent to result==opOK,
2144 except for negative zeroes.
2145*/
Simon Pilgrim00b34992017-03-20 14:40:12 +00002146IEEEFloat::opStatus
2147IEEEFloat::convertToInteger(MutableArrayRef<integerPart> parts,
2148 unsigned int width, bool isSigned,
2149 roundingMode rounding_mode, bool *isExact) const {
Neil Booth618d0fc2007-11-01 22:43:37 +00002150 opStatus fs;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002151
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002152 fs = convertToSignExtendedInteger(parts, width, isSigned, rounding_mode,
Dale Johannesen4f0bd682008-10-09 23:00:39 +00002153 isExact);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002154
Neil Booth618d0fc2007-11-01 22:43:37 +00002155 if (fs == opInvalidOp) {
2156 unsigned int bits, dstPartsCount;
2157
2158 dstPartsCount = partCountForBits(width);
Simon Pilgrim00b34992017-03-20 14:40:12 +00002159 assert(dstPartsCount <= parts.size() && "Integer too big");
Neil Booth618d0fc2007-11-01 22:43:37 +00002160
2161 if (category == fcNaN)
2162 bits = 0;
2163 else if (sign)
2164 bits = isSigned;
2165 else
2166 bits = width - isSigned;
2167
Simon Pilgrim00b34992017-03-20 14:40:12 +00002168 APInt::tcSetLeastSignificantBits(parts.data(), dstPartsCount, bits);
Neil Booth618d0fc2007-11-01 22:43:37 +00002169 if (sign && isSigned)
Simon Pilgrim00b34992017-03-20 14:40:12 +00002170 APInt::tcShiftLeft(parts.data(), dstPartsCount, width - 1);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002171 }
2172
Neil Booth618d0fc2007-11-01 22:43:37 +00002173 return fs;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002174}
2175
Neil Booth6c1c8582007-10-07 12:07:53 +00002176/* Convert an unsigned integer SRC to a floating point number,
2177 rounding according to ROUNDING_MODE. The sign of the floating
2178 point number is not modified. */
Tim Shen85de51d2016-10-25 19:55:59 +00002179IEEEFloat::opStatus IEEEFloat::convertFromUnsignedParts(
2180 const integerPart *src, unsigned int srcCount, roundingMode rounding_mode) {
Neil Booth49c6aab2007-10-08 14:39:42 +00002181 unsigned int omsb, precision, dstCount;
Neil Booth6c1c8582007-10-07 12:07:53 +00002182 integerPart *dst;
Neil Booth49c6aab2007-10-08 14:39:42 +00002183 lostFraction lost_fraction;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002184
2185 category = fcNormal;
Neil Booth49c6aab2007-10-08 14:39:42 +00002186 omsb = APInt::tcMSB(src, srcCount) + 1;
Neil Booth6c1c8582007-10-07 12:07:53 +00002187 dst = significandParts();
2188 dstCount = partCount();
Neil Booth49c6aab2007-10-08 14:39:42 +00002189 precision = semantics->precision;
Neil Booth6c1c8582007-10-07 12:07:53 +00002190
Nick Lewyckyf66daac2011-10-03 21:30:08 +00002191 /* We want the most significant PRECISION bits of SRC. There may not
Neil Booth49c6aab2007-10-08 14:39:42 +00002192 be that many; extract what we can. */
2193 if (precision <= omsb) {
2194 exponent = omsb - 1;
Neil Booth6c1c8582007-10-07 12:07:53 +00002195 lost_fraction = lostFractionThroughTruncation(src, srcCount,
Neil Booth49c6aab2007-10-08 14:39:42 +00002196 omsb - precision);
2197 APInt::tcExtract(dst, dstCount, src, precision, omsb - precision);
2198 } else {
2199 exponent = precision - 1;
2200 lost_fraction = lfExactlyZero;
2201 APInt::tcExtract(dst, dstCount, src, omsb, 0);
Neil Booth6c1c8582007-10-07 12:07:53 +00002202 }
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002203
2204 return normalize(rounding_mode, lost_fraction);
2205}
2206
Tim Shen85de51d2016-10-25 19:55:59 +00002207IEEEFloat::opStatus IEEEFloat::convertFromAPInt(const APInt &Val, bool isSigned,
2208 roundingMode rounding_mode) {
Dan Gohman35723eb2008-02-29 01:26:11 +00002209 unsigned int partCount = Val.getNumWords();
2210 APInt api = Val;
2211
2212 sign = false;
2213 if (isSigned && api.isNegative()) {
2214 sign = true;
2215 api = -api;
2216 }
2217
2218 return convertFromUnsignedParts(api.getRawData(), partCount, rounding_mode);
2219}
2220
Neil Booth03f58ab2007-10-07 12:15:41 +00002221/* Convert a two's complement integer SRC to a floating point number,
2222 rounding according to ROUNDING_MODE. ISSIGNED is true if the
2223 integer is signed, in which case it must be sign-extended. */
Tim Shen85de51d2016-10-25 19:55:59 +00002224IEEEFloat::opStatus
2225IEEEFloat::convertFromSignExtendedInteger(const integerPart *src,
2226 unsigned int srcCount, bool isSigned,
2227 roundingMode rounding_mode) {
Neil Booth03f58ab2007-10-07 12:15:41 +00002228 opStatus status;
2229
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002230 if (isSigned &&
2231 APInt::tcExtractBit(src, srcCount * integerPartWidth - 1)) {
Dylan Noblesmith4e69e292014-08-26 02:03:33 +00002232 integerPart *copy;
Neil Booth03f58ab2007-10-07 12:15:41 +00002233
2234 /* If we're signed and negative negate a copy. */
2235 sign = true;
Dylan Noblesmith4e69e292014-08-26 02:03:33 +00002236 copy = new integerPart[srcCount];
Neil Booth03f58ab2007-10-07 12:15:41 +00002237 APInt::tcAssign(copy, src, srcCount);
2238 APInt::tcNegate(copy, srcCount);
2239 status = convertFromUnsignedParts(copy, srcCount, rounding_mode);
Dylan Noblesmith4e69e292014-08-26 02:03:33 +00002240 delete [] copy;
Neil Booth03f58ab2007-10-07 12:15:41 +00002241 } else {
2242 sign = false;
2243 status = convertFromUnsignedParts(src, srcCount, rounding_mode);
2244 }
2245
2246 return status;
2247}
2248
Neil Booth5f009732007-10-07 11:45:55 +00002249/* FIXME: should this just take a const APInt reference? */
Tim Shen85de51d2016-10-25 19:55:59 +00002250IEEEFloat::opStatus
2251IEEEFloat::convertFromZeroExtendedInteger(const integerPart *parts,
2252 unsigned int width, bool isSigned,
2253 roundingMode rounding_mode) {
Dale Johannesen42305122007-09-21 22:09:37 +00002254 unsigned int partCount = partCountForBits(width);
Jeffrey Yasskin7a162882011-07-18 21:45:40 +00002255 APInt api = APInt(width, makeArrayRef(parts, partCount));
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002256
2257 sign = false;
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002258 if (isSigned && APInt::tcExtractBit(parts, width - 1)) {
Dale Johannesen28a2c4a2007-09-30 18:17:01 +00002259 sign = true;
2260 api = -api;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002261 }
2262
Neil Boothba205222007-10-07 12:10:57 +00002263 return convertFromUnsignedParts(api.getRawData(), partCount, rounding_mode);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002264}
2265
Tim Shen85de51d2016-10-25 19:55:59 +00002266IEEEFloat::opStatus
2267IEEEFloat::convertFromHexadecimalString(StringRef s,
2268 roundingMode rounding_mode) {
Erick Tryzelaara9680df2009-08-18 18:20:37 +00002269 lostFraction lost_fraction = lfExactlyZero;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002270
Michael Gottesman30a90eb2013-07-27 21:49:21 +00002271 category = fcNormal;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002272 zeroSignificand();
2273 exponent = 0;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002274
Eli Friedmand2eb07a2013-07-17 22:17:29 +00002275 integerPart *significand = significandParts();
2276 unsigned partsCount = partCount();
2277 unsigned bitPos = partsCount * integerPartWidth;
2278 bool computedTrailingFraction = false;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002279
Eli Friedmand2eb07a2013-07-17 22:17:29 +00002280 // Skip leading zeroes and any (hexa)decimal point.
Erick Tryzelaarda666c82009-08-20 23:30:43 +00002281 StringRef::iterator begin = s.begin();
2282 StringRef::iterator end = s.end();
Eli Friedmand2eb07a2013-07-17 22:17:29 +00002283 StringRef::iterator dot;
Erick Tryzelaarda666c82009-08-20 23:30:43 +00002284 StringRef::iterator p = skipLeadingZeroesAndAnyDot(begin, end, &dot);
Eli Friedmand2eb07a2013-07-17 22:17:29 +00002285 StringRef::iterator firstSignificantDigit = p;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002286
Eli Friedmand2eb07a2013-07-17 22:17:29 +00002287 while (p != end) {
Dale Johannesenfa483722008-05-14 22:53:25 +00002288 integerPart hex_value;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002289
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002290 if (*p == '.') {
Erick Tryzelaarda666c82009-08-20 23:30:43 +00002291 assert(dot == end && "String contains multiple dots");
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002292 dot = p++;
Eli Friedmand2eb07a2013-07-17 22:17:29 +00002293 continue;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002294 }
2295
2296 hex_value = hexDigitValue(*p);
Eli Friedmand2eb07a2013-07-17 22:17:29 +00002297 if (hex_value == -1U)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002298 break;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002299
2300 p++;
2301
Eli Friedmand2eb07a2013-07-17 22:17:29 +00002302 // Store the number while we have space.
2303 if (bitPos) {
2304 bitPos -= 4;
2305 hex_value <<= bitPos % integerPartWidth;
2306 significand[bitPos / integerPartWidth] |= hex_value;
2307 } else if (!computedTrailingFraction) {
2308 lost_fraction = trailingHexadecimalFraction(p, end, hex_value);
2309 computedTrailingFraction = true;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002310 }
2311 }
2312
2313 /* Hex floats require an exponent but not a hexadecimal point. */
Erick Tryzelaarda666c82009-08-20 23:30:43 +00002314 assert(p != end && "Hex strings require an exponent");
2315 assert((*p == 'p' || *p == 'P') && "Invalid character in significand");
2316 assert(p != begin && "Significand has no digits");
2317 assert((dot == end || p - begin != 1) && "Significand has no digits");
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002318
2319 /* Ignore the exponent if we are zero. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002320 if (p != firstSignificantDigit) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002321 int expAdjustment;
2322
2323 /* Implicit hexadecimal point? */
Erick Tryzelaarda666c82009-08-20 23:30:43 +00002324 if (dot == end)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002325 dot = p;
2326
2327 /* Calculate the exponent adjustment implicit in the number of
2328 significant digits. */
Evan Cheng82b9e962008-05-02 21:15:08 +00002329 expAdjustment = static_cast<int>(dot - firstSignificantDigit);
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002330 if (expAdjustment < 0)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002331 expAdjustment++;
2332 expAdjustment = expAdjustment * 4 - 1;
2333
2334 /* Adjust for writing the significand starting at the most
2335 significant nibble. */
2336 expAdjustment += semantics->precision;
2337 expAdjustment -= partsCount * integerPartWidth;
2338
2339 /* Adjust for the given exponent. */
Erick Tryzelaarda666c82009-08-20 23:30:43 +00002340 exponent = totalExponent(p + 1, end, expAdjustment);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002341 }
2342
2343 return normalize(rounding_mode, lost_fraction);
2344}
2345
Tim Shen85de51d2016-10-25 19:55:59 +00002346IEEEFloat::opStatus
2347IEEEFloat::roundSignificandWithExponent(const integerPart *decSigParts,
2348 unsigned sigPartCount, int exp,
2349 roundingMode rounding_mode) {
Neil Boothb93d90e2007-10-12 16:02:31 +00002350 unsigned int parts, pow5PartCount;
Tamas Berghammerb6b0ddf2015-07-09 10:13:39 +00002351 fltSemantics calcSemantics = { 32767, -32767, 0, 0 };
Neil Boothb93d90e2007-10-12 16:02:31 +00002352 integerPart pow5Parts[maxPowerOfFiveParts];
2353 bool isNearest;
2354
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002355 isNearest = (rounding_mode == rmNearestTiesToEven ||
2356 rounding_mode == rmNearestTiesToAway);
Neil Boothb93d90e2007-10-12 16:02:31 +00002357
2358 parts = partCountForBits(semantics->precision + 11);
2359
2360 /* Calculate pow(5, abs(exp)). */
2361 pow5PartCount = powerOf5(pow5Parts, exp >= 0 ? exp: -exp);
2362
2363 for (;; parts *= 2) {
2364 opStatus sigStatus, powStatus;
2365 unsigned int excessPrecision, truncatedBits;
2366
2367 calcSemantics.precision = parts * integerPartWidth - 1;
2368 excessPrecision = calcSemantics.precision - semantics->precision;
2369 truncatedBits = excessPrecision;
2370
Tim Shen139a58f2016-10-27 22:52:40 +00002371 IEEEFloat decSig(calcSemantics, uninitialized);
2372 decSig.makeZero(sign);
Tim Shen85de51d2016-10-25 19:55:59 +00002373 IEEEFloat pow5(calcSemantics);
Neil Boothb93d90e2007-10-12 16:02:31 +00002374
2375 sigStatus = decSig.convertFromUnsignedParts(decSigParts, sigPartCount,
2376 rmNearestTiesToEven);
2377 powStatus = pow5.convertFromUnsignedParts(pow5Parts, pow5PartCount,
2378 rmNearestTiesToEven);
2379 /* Add exp, as 10^n = 5^n * 2^n. */
2380 decSig.exponent += exp;
2381
2382 lostFraction calcLostFraction;
Evan Cheng82b9e962008-05-02 21:15:08 +00002383 integerPart HUerr, HUdistance;
2384 unsigned int powHUerr;
Neil Boothb93d90e2007-10-12 16:02:31 +00002385
2386 if (exp >= 0) {
2387 /* multiplySignificand leaves the precision-th bit set to 1. */
Craig Topperc10719f2014-04-07 04:17:22 +00002388 calcLostFraction = decSig.multiplySignificand(pow5, nullptr);
Neil Boothb93d90e2007-10-12 16:02:31 +00002389 powHUerr = powStatus != opOK;
2390 } else {
2391 calcLostFraction = decSig.divideSignificand(pow5);
2392 /* Denormal numbers have less precision. */
2393 if (decSig.exponent < semantics->minExponent) {
2394 excessPrecision += (semantics->minExponent - decSig.exponent);
2395 truncatedBits = excessPrecision;
2396 if (excessPrecision > calcSemantics.precision)
2397 excessPrecision = calcSemantics.precision;
2398 }
2399 /* Extra half-ulp lost in reciprocal of exponent. */
Evan Cheng82b9e962008-05-02 21:15:08 +00002400 powHUerr = (powStatus == opOK && calcLostFraction == lfExactlyZero) ? 0:2;
Neil Boothb93d90e2007-10-12 16:02:31 +00002401 }
2402
2403 /* Both multiplySignificand and divideSignificand return the
2404 result with the integer bit set. */
Evan Cheng67c90212009-10-27 21:35:42 +00002405 assert(APInt::tcExtractBit
2406 (decSig.significandParts(), calcSemantics.precision - 1) == 1);
Neil Boothb93d90e2007-10-12 16:02:31 +00002407
2408 HUerr = HUerrBound(calcLostFraction != lfExactlyZero, sigStatus != opOK,
2409 powHUerr);
2410 HUdistance = 2 * ulpsFromBoundary(decSig.significandParts(),
2411 excessPrecision, isNearest);
2412
2413 /* Are we guaranteed to round correctly if we truncate? */
2414 if (HUdistance >= HUerr) {
2415 APInt::tcExtract(significandParts(), partCount(), decSig.significandParts(),
2416 calcSemantics.precision - excessPrecision,
2417 excessPrecision);
2418 /* Take the exponent of decSig. If we tcExtract-ed less bits
2419 above we must adjust our exponent to compensate for the
2420 implicit right shift. */
2421 exponent = (decSig.exponent + semantics->precision
2422 - (calcSemantics.precision - excessPrecision));
2423 calcLostFraction = lostFractionThroughTruncation(decSig.significandParts(),
2424 decSig.partCount(),
2425 truncatedBits);
2426 return normalize(rounding_mode, calcLostFraction);
2427 }
2428 }
2429}
2430
Tim Shen85de51d2016-10-25 19:55:59 +00002431IEEEFloat::opStatus
2432IEEEFloat::convertFromDecimalString(StringRef str, roundingMode rounding_mode) {
Neil Booth4ed401b2007-10-14 10:16:12 +00002433 decimalInfo D;
Neil Boothb93d90e2007-10-12 16:02:31 +00002434 opStatus fs;
2435
Neil Booth4ed401b2007-10-14 10:16:12 +00002436 /* Scan the text. */
Erick Tryzelaar19f63b22009-08-16 23:36:19 +00002437 StringRef::iterator p = str.begin();
2438 interpretDecimal(p, str.end(), &D);
Neil Boothb93d90e2007-10-12 16:02:31 +00002439
Neil Booth91305512007-10-15 15:00:55 +00002440 /* Handle the quick cases. First the case of no significant digits,
2441 i.e. zero, and then exponents that are obviously too large or too
2442 small. Writing L for log 10 / log 2, a number d.ddddd*10^exp
2443 definitely overflows if
2444
2445 (exp - 1) * L >= maxExponent
2446
2447 and definitely underflows to zero where
2448
2449 (exp + 1) * L <= minExponent - precision
2450
2451 With integer arithmetic the tightest bounds for L are
2452
2453 93/28 < L < 196/59 [ numerator <= 256 ]
2454 42039/12655 < L < 28738/8651 [ numerator <= 65536 ]
2455 */
2456
Michael Gottesman228156c2013-07-01 23:54:08 +00002457 // Test if we have a zero number allowing for strings with no null terminators
2458 // and zero decimals with non-zero exponents.
Simon Pilgrima2849592017-03-20 13:53:59 +00002459 //
Michael Gottesman228156c2013-07-01 23:54:08 +00002460 // We computed firstSigDigit by ignoring all zeros and dots. Thus if
2461 // D->firstSigDigit equals str.end(), every digit must be a zero and there can
2462 // be at most one dot. On the other hand, if we have a zero with a non-zero
2463 // exponent, then we know that D.firstSigDigit will be non-numeric.
Michael Gottesman94d61952013-07-02 15:50:05 +00002464 if (D.firstSigDigit == str.end() || decDigitValue(*D.firstSigDigit) >= 10U) {
Neil Boothb93d90e2007-10-12 16:02:31 +00002465 category = fcZero;
2466 fs = opOK;
John McCallb42cc682010-02-26 22:20:41 +00002467
2468 /* Check whether the normalized exponent is high enough to overflow
2469 max during the log-rebasing in the max-exponent check below. */
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +00002470 } else if (D.normalizedExponent - 1 > INT_MAX / 42039) {
John McCallb42cc682010-02-26 22:20:41 +00002471 fs = handleOverflow(rounding_mode);
2472
2473 /* If it wasn't, then it also wasn't high enough to overflow max
2474 during the log-rebasing in the min-exponent check. Check that it
2475 won't overflow min in either check, then perform the min-exponent
2476 check. */
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +00002477 } else if (D.normalizedExponent - 1 < INT_MIN / 42039 ||
John McCallb42cc682010-02-26 22:20:41 +00002478 (D.normalizedExponent + 1) * 28738 <=
2479 8651 * (semantics->minExponent - (int) semantics->precision)) {
Neil Booth91305512007-10-15 15:00:55 +00002480 /* Underflow to zero and round. */
Michael Gottesman30a90eb2013-07-27 21:49:21 +00002481 category = fcNormal;
Neil Booth91305512007-10-15 15:00:55 +00002482 zeroSignificand();
2483 fs = normalize(rounding_mode, lfLessThanHalf);
John McCallb42cc682010-02-26 22:20:41 +00002484
2485 /* We can finally safely perform the max-exponent check. */
Neil Booth91305512007-10-15 15:00:55 +00002486 } else if ((D.normalizedExponent - 1) * 42039
2487 >= 12655 * semantics->maxExponent) {
2488 /* Overflow and round. */
2489 fs = handleOverflow(rounding_mode);
Neil Boothb93d90e2007-10-12 16:02:31 +00002490 } else {
Dylan Noblesmith4e69e292014-08-26 02:03:33 +00002491 integerPart *decSignificand;
Neil Booth4ed401b2007-10-14 10:16:12 +00002492 unsigned int partCount;
Neil Boothb93d90e2007-10-12 16:02:31 +00002493
Neil Booth4ed401b2007-10-14 10:16:12 +00002494 /* A tight upper bound on number of bits required to hold an
Neil Booth91305512007-10-15 15:00:55 +00002495 N-digit decimal integer is N * 196 / 59. Allocate enough space
Neil Booth4ed401b2007-10-14 10:16:12 +00002496 to hold the full significand, and an extra part required by
2497 tcMultiplyPart. */
Evan Cheng82b9e962008-05-02 21:15:08 +00002498 partCount = static_cast<unsigned int>(D.lastSigDigit - D.firstSigDigit) + 1;
Neil Booth91305512007-10-15 15:00:55 +00002499 partCount = partCountForBits(1 + 196 * partCount / 59);
Dylan Noblesmith4e69e292014-08-26 02:03:33 +00002500 decSignificand = new integerPart[partCount + 1];
Neil Booth4ed401b2007-10-14 10:16:12 +00002501 partCount = 0;
Neil Boothb93d90e2007-10-12 16:02:31 +00002502
Neil Booth4ed401b2007-10-14 10:16:12 +00002503 /* Convert to binary efficiently - we do almost all multiplication
2504 in an integerPart. When this would overflow do we do a single
2505 bignum multiplication, and then revert again to multiplication
2506 in an integerPart. */
2507 do {
2508 integerPart decValue, val, multiplier;
2509
2510 val = 0;
2511 multiplier = 1;
2512
2513 do {
Erick Tryzelaar19f63b22009-08-16 23:36:19 +00002514 if (*p == '.') {
Neil Booth4ed401b2007-10-14 10:16:12 +00002515 p++;
Erick Tryzelaar19f63b22009-08-16 23:36:19 +00002516 if (p == str.end()) {
2517 break;
2518 }
2519 }
Neil Booth4ed401b2007-10-14 10:16:12 +00002520 decValue = decDigitValue(*p++);
Erick Tryzelaarda666c82009-08-20 23:30:43 +00002521 assert(decValue < 10U && "Invalid character in significand");
Neil Booth4ed401b2007-10-14 10:16:12 +00002522 multiplier *= 10;
2523 val = val * 10 + decValue;
2524 /* The maximum number that can be multiplied by ten with any
2525 digit added without overflowing an integerPart. */
2526 } while (p <= D.lastSigDigit && multiplier <= (~ (integerPart) 0 - 9) / 10);
2527
2528 /* Multiply out the current part. */
2529 APInt::tcMultiplyPart(decSignificand, decSignificand, multiplier, val,
2530 partCount, partCount + 1, false);
2531
2532 /* If we used another part (likely but not guaranteed), increase
2533 the count. */
2534 if (decSignificand[partCount])
2535 partCount++;
2536 } while (p <= D.lastSigDigit);
Neil Boothb93d90e2007-10-12 16:02:31 +00002537
Neil Boothae077d22007-11-01 22:51:07 +00002538 category = fcNormal;
Neil Boothb93d90e2007-10-12 16:02:31 +00002539 fs = roundSignificandWithExponent(decSignificand, partCount,
Neil Booth4ed401b2007-10-14 10:16:12 +00002540 D.exponent, rounding_mode);
Dylan Noblesmith4e69e292014-08-26 02:03:33 +00002541
2542 delete [] decSignificand;
Neil Booth4ed401b2007-10-14 10:16:12 +00002543 }
Neil Boothb93d90e2007-10-12 16:02:31 +00002544
2545 return fs;
2546}
2547
Tim Shen85de51d2016-10-25 19:55:59 +00002548bool IEEEFloat::convertFromStringSpecials(StringRef str) {
Serguei Katkov768d6dd2017-12-19 04:27:39 +00002549 if (str.equals("inf") || str.equals("INFINITY") || str.equals("+Inf")) {
Michael Gottesman40e8a182013-06-24 09:58:05 +00002550 makeInf(false);
2551 return true;
2552 }
2553
Serguei Katkov768d6dd2017-12-19 04:27:39 +00002554 if (str.equals("-inf") || str.equals("-INFINITY") || str.equals("-Inf")) {
Michael Gottesman40e8a182013-06-24 09:58:05 +00002555 makeInf(true);
2556 return true;
2557 }
2558
2559 if (str.equals("nan") || str.equals("NaN")) {
2560 makeNaN(false, false);
2561 return true;
2562 }
2563
2564 if (str.equals("-nan") || str.equals("-NaN")) {
2565 makeNaN(false, true);
2566 return true;
2567 }
2568
2569 return false;
2570}
2571
Tim Shen85de51d2016-10-25 19:55:59 +00002572IEEEFloat::opStatus IEEEFloat::convertFromString(StringRef str,
2573 roundingMode rounding_mode) {
Erick Tryzelaar19f63b22009-08-16 23:36:19 +00002574 assert(!str.empty() && "Invalid string length");
Neil Booth06077e72007-10-14 10:29:28 +00002575
Michael Gottesman40e8a182013-06-24 09:58:05 +00002576 // Handle special cases.
2577 if (convertFromStringSpecials(str))
2578 return opOK;
2579
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002580 /* Handle a leading minus sign. */
Erick Tryzelaar19f63b22009-08-16 23:36:19 +00002581 StringRef::iterator p = str.begin();
2582 size_t slen = str.size();
Erick Tryzelaarda666c82009-08-20 23:30:43 +00002583 sign = *p == '-' ? 1 : 0;
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002584 if (*p == '-' || *p == '+') {
Erick Tryzelaar19f63b22009-08-16 23:36:19 +00002585 p++;
2586 slen--;
Erick Tryzelaarda666c82009-08-20 23:30:43 +00002587 assert(slen && "String has no digits");
Erick Tryzelaar19f63b22009-08-16 23:36:19 +00002588 }
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002589
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002590 if (slen >= 2 && p[0] == '0' && (p[1] == 'x' || p[1] == 'X')) {
Erick Tryzelaar19f63b22009-08-16 23:36:19 +00002591 assert(slen - 2 && "Invalid string");
Erick Tryzelaarda666c82009-08-20 23:30:43 +00002592 return convertFromHexadecimalString(StringRef(p + 2, slen - 2),
Erick Tryzelaar19f63b22009-08-16 23:36:19 +00002593 rounding_mode);
2594 }
Bill Wendlingc6075402008-11-27 08:00:12 +00002595
Erick Tryzelaarda666c82009-08-20 23:30:43 +00002596 return convertFromDecimalString(StringRef(p, slen), rounding_mode);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002597}
Dale Johannesena719a602007-08-24 00:56:33 +00002598
Neil Booth8f1946f2007-10-03 22:26:02 +00002599/* Write out a hexadecimal representation of the floating point value
2600 to DST, which must be of sufficient size, in the C99 form
2601 [-]0xh.hhhhp[+-]d. Return the number of characters written,
2602 excluding the terminating NUL.
2603
2604 If UPPERCASE, the output is in upper case, otherwise in lower case.
2605
2606 HEXDIGITS digits appear altogether, rounding the value if
2607 necessary. If HEXDIGITS is 0, the minimal precision to display the
2608 number precisely is used instead. If nothing would appear after
2609 the decimal point it is suppressed.
2610
2611 The decimal exponent is always printed and has at least one digit.
2612 Zero values display an exponent of zero. Infinities and NaNs
2613 appear as "infinity" or "nan" respectively.
2614
2615 The above rules are as specified by C99. There is ambiguity about
2616 what the leading hexadecimal digit should be. This implementation
2617 uses whatever is necessary so that the exponent is displayed as
2618 stored. This implies the exponent will fall within the IEEE format
2619 range, and the leading hexadecimal digit will be 0 (for denormals),
2620 1 (normal numbers) or 2 (normal numbers rounded-away-from-zero with
2621 any other digits zero).
2622*/
Tim Shen85de51d2016-10-25 19:55:59 +00002623unsigned int IEEEFloat::convertToHexString(char *dst, unsigned int hexDigits,
2624 bool upperCase,
2625 roundingMode rounding_mode) const {
Neil Booth8f1946f2007-10-03 22:26:02 +00002626 char *p;
2627
2628 p = dst;
2629 if (sign)
2630 *dst++ = '-';
2631
2632 switch (category) {
2633 case fcInfinity:
2634 memcpy (dst, upperCase ? infinityU: infinityL, sizeof infinityU - 1);
2635 dst += sizeof infinityL - 1;
2636 break;
2637
2638 case fcNaN:
2639 memcpy (dst, upperCase ? NaNU: NaNL, sizeof NaNU - 1);
2640 dst += sizeof NaNU - 1;
2641 break;
2642
2643 case fcZero:
2644 *dst++ = '0';
2645 *dst++ = upperCase ? 'X': 'x';
2646 *dst++ = '0';
2647 if (hexDigits > 1) {
2648 *dst++ = '.';
2649 memset (dst, '0', hexDigits - 1);
2650 dst += hexDigits - 1;
2651 }
2652 *dst++ = upperCase ? 'P': 'p';
2653 *dst++ = '0';
2654 break;
2655
2656 case fcNormal:
2657 dst = convertNormalToHexString (dst, hexDigits, upperCase, rounding_mode);
2658 break;
2659 }
2660
2661 *dst = 0;
2662
Evan Cheng82b9e962008-05-02 21:15:08 +00002663 return static_cast<unsigned int>(dst - p);
Neil Booth8f1946f2007-10-03 22:26:02 +00002664}
2665
2666/* Does the hard work of outputting the correctly rounded hexadecimal
2667 form of a normal floating point number with the specified number of
2668 hexadecimal digits. If HEXDIGITS is zero the minimum number of
2669 digits necessary to print the value precisely is output. */
Tim Shen85de51d2016-10-25 19:55:59 +00002670char *IEEEFloat::convertNormalToHexString(char *dst, unsigned int hexDigits,
2671 bool upperCase,
2672 roundingMode rounding_mode) const {
Neil Booth8f1946f2007-10-03 22:26:02 +00002673 unsigned int count, valueBits, shift, partsCount, outputDigits;
2674 const char *hexDigitChars;
2675 const integerPart *significand;
2676 char *p;
2677 bool roundUp;
2678
2679 *dst++ = '0';
2680 *dst++ = upperCase ? 'X': 'x';
2681
2682 roundUp = false;
2683 hexDigitChars = upperCase ? hexDigitsUpper: hexDigitsLower;
2684
2685 significand = significandParts();
2686 partsCount = partCount();
2687
2688 /* +3 because the first digit only uses the single integer bit, so
2689 we have 3 virtual zero most-significant-bits. */
2690 valueBits = semantics->precision + 3;
2691 shift = integerPartWidth - valueBits % integerPartWidth;
2692
2693 /* The natural number of digits required ignoring trailing
2694 insignificant zeroes. */
2695 outputDigits = (valueBits - significandLSB () + 3) / 4;
2696
2697 /* hexDigits of zero means use the required number for the
2698 precision. Otherwise, see if we are truncating. If we are,
Neil Booth0ea72a92007-10-06 00:24:48 +00002699 find out if we need to round away from zero. */
Neil Booth8f1946f2007-10-03 22:26:02 +00002700 if (hexDigits) {
2701 if (hexDigits < outputDigits) {
2702 /* We are dropping non-zero bits, so need to check how to round.
2703 "bits" is the number of dropped bits. */
2704 unsigned int bits;
2705 lostFraction fraction;
2706
2707 bits = valueBits - hexDigits * 4;
2708 fraction = lostFractionThroughTruncation (significand, partsCount, bits);
2709 roundUp = roundAwayFromZero(rounding_mode, fraction, bits);
2710 }
2711 outputDigits = hexDigits;
2712 }
2713
2714 /* Write the digits consecutively, and start writing in the location
2715 of the hexadecimal point. We move the most significant digit
2716 left and add the hexadecimal point later. */
2717 p = ++dst;
2718
2719 count = (valueBits + integerPartWidth - 1) / integerPartWidth;
2720
2721 while (outputDigits && count) {
2722 integerPart part;
2723
2724 /* Put the most significant integerPartWidth bits in "part". */
2725 if (--count == partsCount)
2726 part = 0; /* An imaginary higher zero part. */
2727 else
2728 part = significand[count] << shift;
2729
2730 if (count && shift)
2731 part |= significand[count - 1] >> (integerPartWidth - shift);
2732
2733 /* Convert as much of "part" to hexdigits as we can. */
2734 unsigned int curDigits = integerPartWidth / 4;
2735
2736 if (curDigits > outputDigits)
2737 curDigits = outputDigits;
2738 dst += partAsHex (dst, part, curDigits, hexDigitChars);
2739 outputDigits -= curDigits;
2740 }
2741
2742 if (roundUp) {
2743 char *q = dst;
2744
2745 /* Note that hexDigitChars has a trailing '0'. */
2746 do {
2747 q--;
2748 *q = hexDigitChars[hexDigitValue (*q) + 1];
Neil Booth0ea72a92007-10-06 00:24:48 +00002749 } while (*q == '0');
Evan Cheng67c90212009-10-27 21:35:42 +00002750 assert(q >= p);
Neil Booth8f1946f2007-10-03 22:26:02 +00002751 } else {
2752 /* Add trailing zeroes. */
2753 memset (dst, '0', outputDigits);
2754 dst += outputDigits;
2755 }
2756
2757 /* Move the most significant digit to before the point, and if there
2758 is something after the decimal point add it. This must come
2759 after rounding above. */
2760 p[-1] = p[0];
2761 if (dst -1 == p)
2762 dst--;
2763 else
2764 p[0] = '.';
2765
2766 /* Finally output the exponent. */
2767 *dst++ = upperCase ? 'P': 'p';
2768
Neil Booth32897f52007-10-06 07:29:25 +00002769 return writeSignedDecimal (dst, exponent);
Neil Booth8f1946f2007-10-03 22:26:02 +00002770}
2771
Tim Shen85de51d2016-10-25 19:55:59 +00002772hash_code hash_value(const IEEEFloat &Arg) {
Michael Gottesman8136c382013-06-26 23:17:28 +00002773 if (!Arg.isFiniteNonZero())
Chandler Carruth71bd7d12012-03-04 12:02:57 +00002774 return hash_combine((uint8_t)Arg.category,
2775 // NaN has no sign, fix it at zero.
2776 Arg.isNaN() ? (uint8_t)0 : (uint8_t)Arg.sign,
2777 Arg.semantics->precision);
2778
2779 // Normal floats need their exponent and significand hashed.
2780 return hash_combine((uint8_t)Arg.category, (uint8_t)Arg.sign,
2781 Arg.semantics->precision, Arg.exponent,
2782 hash_combine_range(
2783 Arg.significandParts(),
2784 Arg.significandParts() + Arg.partCount()));
Dale Johannesena719a602007-08-24 00:56:33 +00002785}
2786
2787// Conversion from APFloat to/from host float/double. It may eventually be
2788// possible to eliminate these and have everybody deal with APFloats, but that
2789// will take a while. This approach will not easily extend to long double.
Dale Johannesen146a0ea2007-09-20 23:47:58 +00002790// Current implementation requires integerPartWidth==64, which is correct at
2791// the moment but could be made more general.
Dale Johannesena719a602007-08-24 00:56:33 +00002792
Dale Johannesen728687c2007-09-05 20:39:49 +00002793// Denormals have exponent minExponent in APFloat, but minExponent-1 in
Dale Johannesen146a0ea2007-09-20 23:47:58 +00002794// the actual IEEE respresentations. We compensate for that here.
Dale Johannesen728687c2007-09-05 20:39:49 +00002795
Tim Shen85de51d2016-10-25 19:55:59 +00002796APInt IEEEFloat::convertF80LongDoubleAPFloatToAPInt() const {
Stephan Bergmann17c7f702016-12-14 11:57:17 +00002797 assert(semantics == (const llvm::fltSemantics*)&semX87DoubleExtended);
Evan Cheng67c90212009-10-27 21:35:42 +00002798 assert(partCount()==2);
Dale Johannesen245dceb2007-09-11 18:32:33 +00002799
2800 uint64_t myexponent, mysignificand;
2801
Michael Gottesman8136c382013-06-26 23:17:28 +00002802 if (isFiniteNonZero()) {
Dale Johannesen245dceb2007-09-11 18:32:33 +00002803 myexponent = exponent+16383; //bias
Dale Johannesen146a0ea2007-09-20 23:47:58 +00002804 mysignificand = significandParts()[0];
Dale Johannesen245dceb2007-09-11 18:32:33 +00002805 if (myexponent==1 && !(mysignificand & 0x8000000000000000ULL))
2806 myexponent = 0; // denormal
2807 } else if (category==fcZero) {
2808 myexponent = 0;
2809 mysignificand = 0;
2810 } else if (category==fcInfinity) {
2811 myexponent = 0x7fff;
2812 mysignificand = 0x8000000000000000ULL;
Chris Lattner2a9bcb92007-10-06 06:13:42 +00002813 } else {
2814 assert(category == fcNaN && "Unknown category");
Dale Johannesen245dceb2007-09-11 18:32:33 +00002815 myexponent = 0x7fff;
Dale Johannesen146a0ea2007-09-20 23:47:58 +00002816 mysignificand = significandParts()[0];
Chris Lattner2a9bcb92007-10-06 06:13:42 +00002817 }
Dale Johannesen245dceb2007-09-11 18:32:33 +00002818
2819 uint64_t words[2];
Dale Johannesen93eefa02009-03-23 21:16:53 +00002820 words[0] = mysignificand;
2821 words[1] = ((uint64_t)(sign & 1) << 15) |
2822 (myexponent & 0x7fffLL);
Jeffrey Yasskin7a162882011-07-18 21:45:40 +00002823 return APInt(80, words);
Dale Johannesen245dceb2007-09-11 18:32:33 +00002824}
2825
Tim Shen85de51d2016-10-25 19:55:59 +00002826APInt IEEEFloat::convertPPCDoubleDoubleAPFloatToAPInt() const {
Tim Shenfd1e5aa2017-01-23 22:39:35 +00002827 assert(semantics == (const llvm::fltSemantics *)&semPPCDoubleDoubleLegacy);
Evan Cheng67c90212009-10-27 21:35:42 +00002828 assert(partCount()==2);
Dale Johannesen007aa372007-10-11 18:07:22 +00002829
Ulrich Weigandd9f7e252012-10-29 18:09:01 +00002830 uint64_t words[2];
2831 opStatus fs;
2832 bool losesInfo;
Dale Johannesen007aa372007-10-11 18:07:22 +00002833
Ulrich Weigandd9f7e252012-10-29 18:09:01 +00002834 // Convert number to double. To avoid spurious underflows, we re-
2835 // normalize against the "double" minExponent first, and only *then*
2836 // truncate the mantissa. The result of that second conversion
2837 // may be inexact, but should never underflow.
Alexey Samsonov2b431d92012-11-30 22:27:54 +00002838 // Declare fltSemantics before APFloat that uses it (and
2839 // saves pointer to it) to ensure correct destruction order.
Ulrich Weigandd9f7e252012-10-29 18:09:01 +00002840 fltSemantics extendedSemantics = *semantics;
Stephan Bergmann17c7f702016-12-14 11:57:17 +00002841 extendedSemantics.minExponent = semIEEEdouble.minExponent;
Tim Shen85de51d2016-10-25 19:55:59 +00002842 IEEEFloat extended(*this);
Ulrich Weigandd9f7e252012-10-29 18:09:01 +00002843 fs = extended.convert(extendedSemantics, rmNearestTiesToEven, &losesInfo);
2844 assert(fs == opOK && !losesInfo);
2845 (void)fs;
2846
Tim Shen85de51d2016-10-25 19:55:59 +00002847 IEEEFloat u(extended);
Stephan Bergmann17c7f702016-12-14 11:57:17 +00002848 fs = u.convert(semIEEEdouble, rmNearestTiesToEven, &losesInfo);
Ulrich Weigandd9f7e252012-10-29 18:09:01 +00002849 assert(fs == opOK || fs == opInexact);
2850 (void)fs;
2851 words[0] = *u.convertDoubleAPFloatToAPInt().getRawData();
2852
2853 // If conversion was exact or resulted in a special case, we're done;
2854 // just set the second double to zero. Otherwise, re-convert back to
2855 // the extended format and compute the difference. This now should
2856 // convert exactly to double.
Michael Gottesman8136c382013-06-26 23:17:28 +00002857 if (u.isFiniteNonZero() && losesInfo) {
Ulrich Weigandd9f7e252012-10-29 18:09:01 +00002858 fs = u.convert(extendedSemantics, rmNearestTiesToEven, &losesInfo);
2859 assert(fs == opOK && !losesInfo);
2860 (void)fs;
2861
Tim Shen85de51d2016-10-25 19:55:59 +00002862 IEEEFloat v(extended);
Ulrich Weigandd9f7e252012-10-29 18:09:01 +00002863 v.subtract(u, rmNearestTiesToEven);
Stephan Bergmann17c7f702016-12-14 11:57:17 +00002864 fs = v.convert(semIEEEdouble, rmNearestTiesToEven, &losesInfo);
Ulrich Weigandd9f7e252012-10-29 18:09:01 +00002865 assert(fs == opOK && !losesInfo);
2866 (void)fs;
2867 words[1] = *v.convertDoubleAPFloatToAPInt().getRawData();
Dale Johannesen007aa372007-10-11 18:07:22 +00002868 } else {
Ulrich Weigandd9f7e252012-10-29 18:09:01 +00002869 words[1] = 0;
Dale Johannesen007aa372007-10-11 18:07:22 +00002870 }
2871
Jeffrey Yasskin7a162882011-07-18 21:45:40 +00002872 return APInt(128, words);
Dale Johannesen007aa372007-10-11 18:07:22 +00002873}
2874
Tim Shen85de51d2016-10-25 19:55:59 +00002875APInt IEEEFloat::convertQuadrupleAPFloatToAPInt() const {
Stephan Bergmann17c7f702016-12-14 11:57:17 +00002876 assert(semantics == (const llvm::fltSemantics*)&semIEEEquad);
Evan Cheng67c90212009-10-27 21:35:42 +00002877 assert(partCount()==2);
Anton Korobeynikov13e8c7e2009-08-21 22:10:30 +00002878
2879 uint64_t myexponent, mysignificand, mysignificand2;
2880
Michael Gottesman8136c382013-06-26 23:17:28 +00002881 if (isFiniteNonZero()) {
Anton Korobeynikov13e8c7e2009-08-21 22:10:30 +00002882 myexponent = exponent+16383; //bias
2883 mysignificand = significandParts()[0];
2884 mysignificand2 = significandParts()[1];
2885 if (myexponent==1 && !(mysignificand2 & 0x1000000000000LL))
2886 myexponent = 0; // denormal
2887 } else if (category==fcZero) {
2888 myexponent = 0;
2889 mysignificand = mysignificand2 = 0;
2890 } else if (category==fcInfinity) {
2891 myexponent = 0x7fff;
2892 mysignificand = mysignificand2 = 0;
2893 } else {
2894 assert(category == fcNaN && "Unknown category!");
2895 myexponent = 0x7fff;
2896 mysignificand = significandParts()[0];
2897 mysignificand2 = significandParts()[1];
2898 }
2899
2900 uint64_t words[2];
2901 words[0] = mysignificand;
2902 words[1] = ((uint64_t)(sign & 1) << 63) |
2903 ((myexponent & 0x7fff) << 48) |
Anton Korobeynikov876955c2009-08-21 23:09:47 +00002904 (mysignificand2 & 0xffffffffffffLL);
Anton Korobeynikov13e8c7e2009-08-21 22:10:30 +00002905
Jeffrey Yasskin7a162882011-07-18 21:45:40 +00002906 return APInt(128, words);
Anton Korobeynikov13e8c7e2009-08-21 22:10:30 +00002907}
2908
Tim Shen85de51d2016-10-25 19:55:59 +00002909APInt IEEEFloat::convertDoubleAPFloatToAPInt() const {
Stephan Bergmann17c7f702016-12-14 11:57:17 +00002910 assert(semantics == (const llvm::fltSemantics*)&semIEEEdouble);
Evan Cheng67c90212009-10-27 21:35:42 +00002911 assert(partCount()==1);
Dale Johannesena719a602007-08-24 00:56:33 +00002912
Dale Johannesen3cf889f2007-08-31 04:03:46 +00002913 uint64_t myexponent, mysignificand;
Dale Johannesena719a602007-08-24 00:56:33 +00002914
Michael Gottesman8136c382013-06-26 23:17:28 +00002915 if (isFiniteNonZero()) {
Dale Johannesena719a602007-08-24 00:56:33 +00002916 myexponent = exponent+1023; //bias
Dale Johannesen728687c2007-09-05 20:39:49 +00002917 mysignificand = *significandParts();
2918 if (myexponent==1 && !(mysignificand & 0x10000000000000LL))
2919 myexponent = 0; // denormal
Dale Johannesena719a602007-08-24 00:56:33 +00002920 } else if (category==fcZero) {
Dale Johannesena719a602007-08-24 00:56:33 +00002921 myexponent = 0;
2922 mysignificand = 0;
2923 } else if (category==fcInfinity) {
Dale Johannesena719a602007-08-24 00:56:33 +00002924 myexponent = 0x7ff;
2925 mysignificand = 0;
Chris Lattner2a9bcb92007-10-06 06:13:42 +00002926 } else {
2927 assert(category == fcNaN && "Unknown category!");
Dale Johannesena719a602007-08-24 00:56:33 +00002928 myexponent = 0x7ff;
Dale Johannesen3cf889f2007-08-31 04:03:46 +00002929 mysignificand = *significandParts();
Chris Lattner2a9bcb92007-10-06 06:13:42 +00002930 }
Dale Johannesena719a602007-08-24 00:56:33 +00002931
Evan Cheng82b9e962008-05-02 21:15:08 +00002932 return APInt(64, ((((uint64_t)(sign & 1) << 63) |
Chris Lattner2a9bcb92007-10-06 06:13:42 +00002933 ((myexponent & 0x7ff) << 52) |
2934 (mysignificand & 0xfffffffffffffLL))));
Dale Johannesena719a602007-08-24 00:56:33 +00002935}
2936
Tim Shen85de51d2016-10-25 19:55:59 +00002937APInt IEEEFloat::convertFloatAPFloatToAPInt() const {
Stephan Bergmann17c7f702016-12-14 11:57:17 +00002938 assert(semantics == (const llvm::fltSemantics*)&semIEEEsingle);
Evan Cheng67c90212009-10-27 21:35:42 +00002939 assert(partCount()==1);
Neil Booth9acbf5a2007-09-26 21:33:42 +00002940
Dale Johannesen3cf889f2007-08-31 04:03:46 +00002941 uint32_t myexponent, mysignificand;
Dale Johannesena719a602007-08-24 00:56:33 +00002942
Michael Gottesman8136c382013-06-26 23:17:28 +00002943 if (isFiniteNonZero()) {
Dale Johannesena719a602007-08-24 00:56:33 +00002944 myexponent = exponent+127; //bias
Evan Cheng82b9e962008-05-02 21:15:08 +00002945 mysignificand = (uint32_t)*significandParts();
Dale Johannesen06a10df2007-11-17 01:02:27 +00002946 if (myexponent == 1 && !(mysignificand & 0x800000))
Dale Johannesen728687c2007-09-05 20:39:49 +00002947 myexponent = 0; // denormal
Dale Johannesena719a602007-08-24 00:56:33 +00002948 } else if (category==fcZero) {
Dale Johannesena719a602007-08-24 00:56:33 +00002949 myexponent = 0;
2950 mysignificand = 0;
2951 } else if (category==fcInfinity) {
Dale Johannesena719a602007-08-24 00:56:33 +00002952 myexponent = 0xff;
2953 mysignificand = 0;
Chris Lattner2a9bcb92007-10-06 06:13:42 +00002954 } else {
2955 assert(category == fcNaN && "Unknown category!");
Dale Johannesen728687c2007-09-05 20:39:49 +00002956 myexponent = 0xff;
Evan Cheng82b9e962008-05-02 21:15:08 +00002957 mysignificand = (uint32_t)*significandParts();
Chris Lattner2a9bcb92007-10-06 06:13:42 +00002958 }
Dale Johannesena719a602007-08-24 00:56:33 +00002959
Chris Lattner2a9bcb92007-10-06 06:13:42 +00002960 return APInt(32, (((sign&1) << 31) | ((myexponent&0xff) << 23) |
2961 (mysignificand & 0x7fffff)));
Dale Johannesena719a602007-08-24 00:56:33 +00002962}
2963
Tim Shen85de51d2016-10-25 19:55:59 +00002964APInt IEEEFloat::convertHalfAPFloatToAPInt() const {
Stephan Bergmann17c7f702016-12-14 11:57:17 +00002965 assert(semantics == (const llvm::fltSemantics*)&semIEEEhalf);
Evan Cheng67c90212009-10-27 21:35:42 +00002966 assert(partCount()==1);
Chris Lattner4794b2b2009-10-16 02:13:51 +00002967
2968 uint32_t myexponent, mysignificand;
2969
Michael Gottesman8136c382013-06-26 23:17:28 +00002970 if (isFiniteNonZero()) {
Chris Lattner4794b2b2009-10-16 02:13:51 +00002971 myexponent = exponent+15; //bias
2972 mysignificand = (uint32_t)*significandParts();
2973 if (myexponent == 1 && !(mysignificand & 0x400))
2974 myexponent = 0; // denormal
2975 } else if (category==fcZero) {
2976 myexponent = 0;
2977 mysignificand = 0;
2978 } else if (category==fcInfinity) {
Dale Johannesen0d670b52009-10-23 04:02:51 +00002979 myexponent = 0x1f;
Chris Lattner4794b2b2009-10-16 02:13:51 +00002980 mysignificand = 0;
2981 } else {
2982 assert(category == fcNaN && "Unknown category!");
Dale Johannesen0d670b52009-10-23 04:02:51 +00002983 myexponent = 0x1f;
Chris Lattner4794b2b2009-10-16 02:13:51 +00002984 mysignificand = (uint32_t)*significandParts();
2985 }
2986
2987 return APInt(16, (((sign&1) << 15) | ((myexponent&0x1f) << 10) |
2988 (mysignificand & 0x3ff)));
2989}
2990
Dale Johannesen007aa372007-10-11 18:07:22 +00002991// This function creates an APInt that is just a bit map of the floating
2992// point constant as it would appear in memory. It is not a conversion,
2993// and treating the result as a normal integer is unlikely to be useful.
2994
Tim Shen85de51d2016-10-25 19:55:59 +00002995APInt IEEEFloat::bitcastToAPInt() const {
Stephan Bergmann17c7f702016-12-14 11:57:17 +00002996 if (semantics == (const llvm::fltSemantics*)&semIEEEhalf)
Chris Lattner4794b2b2009-10-16 02:13:51 +00002997 return convertHalfAPFloatToAPInt();
2998
Stephan Bergmann17c7f702016-12-14 11:57:17 +00002999 if (semantics == (const llvm::fltSemantics*)&semIEEEsingle)
Dale Johannesen245dceb2007-09-11 18:32:33 +00003000 return convertFloatAPFloatToAPInt();
Anton Korobeynikov13e8c7e2009-08-21 22:10:30 +00003001
Stephan Bergmann17c7f702016-12-14 11:57:17 +00003002 if (semantics == (const llvm::fltSemantics*)&semIEEEdouble)
Dale Johannesen245dceb2007-09-11 18:32:33 +00003003 return convertDoubleAPFloatToAPInt();
Neil Booth9acbf5a2007-09-26 21:33:42 +00003004
Stephan Bergmann17c7f702016-12-14 11:57:17 +00003005 if (semantics == (const llvm::fltSemantics*)&semIEEEquad)
Anton Korobeynikov13e8c7e2009-08-21 22:10:30 +00003006 return convertQuadrupleAPFloatToAPInt();
3007
Tim Shenfd1e5aa2017-01-23 22:39:35 +00003008 if (semantics == (const llvm::fltSemantics *)&semPPCDoubleDoubleLegacy)
Dale Johannesen007aa372007-10-11 18:07:22 +00003009 return convertPPCDoubleDoubleAPFloatToAPInt();
3010
Stephan Bergmann17c7f702016-12-14 11:57:17 +00003011 assert(semantics == (const llvm::fltSemantics*)&semX87DoubleExtended &&
Chris Lattner2a9bcb92007-10-06 06:13:42 +00003012 "unknown format!");
3013 return convertF80LongDoubleAPFloatToAPInt();
Dale Johannesen245dceb2007-09-11 18:32:33 +00003014}
3015
Tim Shen85de51d2016-10-25 19:55:59 +00003016float IEEEFloat::convertToFloat() const {
Stephan Bergmann17c7f702016-12-14 11:57:17 +00003017 assert(semantics == (const llvm::fltSemantics*)&semIEEEsingle &&
Chris Lattner688f9912009-09-24 21:44:20 +00003018 "Float semantics are not IEEEsingle");
Dale Johannesen54306fe2008-10-09 18:53:47 +00003019 APInt api = bitcastToAPInt();
Dale Johannesen245dceb2007-09-11 18:32:33 +00003020 return api.bitsToFloat();
3021}
3022
Tim Shen85de51d2016-10-25 19:55:59 +00003023double IEEEFloat::convertToDouble() const {
Stephan Bergmann17c7f702016-12-14 11:57:17 +00003024 assert(semantics == (const llvm::fltSemantics*)&semIEEEdouble &&
Chris Lattner688f9912009-09-24 21:44:20 +00003025 "Float semantics are not IEEEdouble");
Dale Johannesen54306fe2008-10-09 18:53:47 +00003026 APInt api = bitcastToAPInt();
Dale Johannesen245dceb2007-09-11 18:32:33 +00003027 return api.bitsToDouble();
3028}
3029
Dale Johannesenfff29952008-10-06 18:22:29 +00003030/// Integer bit is explicit in this format. Intel hardware (387 and later)
3031/// does not support these bit patterns:
3032/// exponent = all 1's, integer bit 0, significand 0 ("pseudoinfinity")
3033/// exponent = all 1's, integer bit 0, significand nonzero ("pseudoNaN")
Dale Johannesenfff29952008-10-06 18:22:29 +00003034/// exponent!=0 nor all 1's, integer bit 0 ("unnormal")
Pavel Labathb1bcafd2018-05-09 15:13:45 +00003035/// exponent = 0, integer bit 1 ("pseudodenormal")
3036/// At the moment, the first three are treated as NaNs, the last one as Normal.
Tim Shen85de51d2016-10-25 19:55:59 +00003037void IEEEFloat::initFromF80LongDoubleAPInt(const APInt &api) {
Dale Johannesen245dceb2007-09-11 18:32:33 +00003038 assert(api.getBitWidth()==80);
3039 uint64_t i1 = api.getRawData()[0];
3040 uint64_t i2 = api.getRawData()[1];
Dale Johannesen93eefa02009-03-23 21:16:53 +00003041 uint64_t myexponent = (i2 & 0x7fff);
3042 uint64_t mysignificand = i1;
Pavel Labathb1bcafd2018-05-09 15:13:45 +00003043 uint8_t myintegerbit = mysignificand >> 63;
Dale Johannesen245dceb2007-09-11 18:32:33 +00003044
Stephan Bergmann17c7f702016-12-14 11:57:17 +00003045 initialize(&semX87DoubleExtended);
Dale Johannesen146a0ea2007-09-20 23:47:58 +00003046 assert(partCount()==2);
Dale Johannesen245dceb2007-09-11 18:32:33 +00003047
Dale Johannesen93eefa02009-03-23 21:16:53 +00003048 sign = static_cast<unsigned int>(i2>>15);
Pavel Labathb1bcafd2018-05-09 15:13:45 +00003049 if (myexponent == 0 && mysignificand == 0) {
Dale Johannesen245dceb2007-09-11 18:32:33 +00003050 // exponent, significand meaningless
3051 category = fcZero;
3052 } else if (myexponent==0x7fff && mysignificand==0x8000000000000000ULL) {
3053 // exponent, significand meaningless
3054 category = fcInfinity;
Pavel Labathb1bcafd2018-05-09 15:13:45 +00003055 } else if ((myexponent == 0x7fff && mysignificand != 0x8000000000000000ULL) ||
3056 (myexponent != 0x7fff && myexponent != 0 && myintegerbit == 0)) {
Dale Johannesen245dceb2007-09-11 18:32:33 +00003057 // exponent meaningless
3058 category = fcNaN;
Dale Johannesen146a0ea2007-09-20 23:47:58 +00003059 significandParts()[0] = mysignificand;
3060 significandParts()[1] = 0;
Dale Johannesen245dceb2007-09-11 18:32:33 +00003061 } else {
3062 category = fcNormal;
3063 exponent = myexponent - 16383;
Dale Johannesen146a0ea2007-09-20 23:47:58 +00003064 significandParts()[0] = mysignificand;
3065 significandParts()[1] = 0;
Dale Johannesen245dceb2007-09-11 18:32:33 +00003066 if (myexponent==0) // denormal
3067 exponent = -16382;
Neil Booth9acbf5a2007-09-26 21:33:42 +00003068 }
Dale Johannesen245dceb2007-09-11 18:32:33 +00003069}
3070
Tim Shen85de51d2016-10-25 19:55:59 +00003071void IEEEFloat::initFromPPCDoubleDoubleAPInt(const APInt &api) {
Dale Johannesen007aa372007-10-11 18:07:22 +00003072 assert(api.getBitWidth()==128);
3073 uint64_t i1 = api.getRawData()[0];
3074 uint64_t i2 = api.getRawData()[1];
Ulrich Weigandd9f7e252012-10-29 18:09:01 +00003075 opStatus fs;
3076 bool losesInfo;
Dale Johannesen007aa372007-10-11 18:07:22 +00003077
Ulrich Weigandd9f7e252012-10-29 18:09:01 +00003078 // Get the first double and convert to our format.
3079 initFromDoubleAPInt(APInt(64, i1));
Tim Shenfd1e5aa2017-01-23 22:39:35 +00003080 fs = convert(semPPCDoubleDoubleLegacy, rmNearestTiesToEven, &losesInfo);
Ulrich Weigandd9f7e252012-10-29 18:09:01 +00003081 assert(fs == opOK && !losesInfo);
3082 (void)fs;
Dale Johannesen007aa372007-10-11 18:07:22 +00003083
Ulrich Weigandd9f7e252012-10-29 18:09:01 +00003084 // Unless we have a special case, add in second double.
Michael Gottesman8136c382013-06-26 23:17:28 +00003085 if (isFiniteNonZero()) {
Stephan Bergmann17c7f702016-12-14 11:57:17 +00003086 IEEEFloat v(semIEEEdouble, APInt(64, i2));
Tim Shenfd1e5aa2017-01-23 22:39:35 +00003087 fs = v.convert(semPPCDoubleDoubleLegacy, rmNearestTiesToEven, &losesInfo);
Ulrich Weigandd9f7e252012-10-29 18:09:01 +00003088 assert(fs == opOK && !losesInfo);
3089 (void)fs;
3090
3091 add(v, rmNearestTiesToEven);
Dale Johannesen007aa372007-10-11 18:07:22 +00003092 }
3093}
3094
Tim Shen85de51d2016-10-25 19:55:59 +00003095void IEEEFloat::initFromQuadrupleAPInt(const APInt &api) {
Anton Korobeynikov13e8c7e2009-08-21 22:10:30 +00003096 assert(api.getBitWidth()==128);
3097 uint64_t i1 = api.getRawData()[0];
3098 uint64_t i2 = api.getRawData()[1];
3099 uint64_t myexponent = (i2 >> 48) & 0x7fff;
3100 uint64_t mysignificand = i1;
3101 uint64_t mysignificand2 = i2 & 0xffffffffffffLL;
3102
Stephan Bergmann17c7f702016-12-14 11:57:17 +00003103 initialize(&semIEEEquad);
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +00003104 assert(partCount()==2);
Anton Korobeynikov13e8c7e2009-08-21 22:10:30 +00003105
3106 sign = static_cast<unsigned int>(i2>>63);
3107 if (myexponent==0 &&
3108 (mysignificand==0 && mysignificand2==0)) {
3109 // exponent, significand meaningless
3110 category = fcZero;
3111 } else if (myexponent==0x7fff &&
3112 (mysignificand==0 && mysignificand2==0)) {
3113 // exponent, significand meaningless
3114 category = fcInfinity;
3115 } else if (myexponent==0x7fff &&
3116 (mysignificand!=0 || mysignificand2 !=0)) {
3117 // exponent meaningless
3118 category = fcNaN;
3119 significandParts()[0] = mysignificand;
3120 significandParts()[1] = mysignificand2;
3121 } else {
3122 category = fcNormal;
3123 exponent = myexponent - 16383;
3124 significandParts()[0] = mysignificand;
3125 significandParts()[1] = mysignificand2;
3126 if (myexponent==0) // denormal
3127 exponent = -16382;
3128 else
3129 significandParts()[1] |= 0x1000000000000LL; // integer bit
3130 }
3131}
3132
Tim Shen85de51d2016-10-25 19:55:59 +00003133void IEEEFloat::initFromDoubleAPInt(const APInt &api) {
Dale Johannesen245dceb2007-09-11 18:32:33 +00003134 assert(api.getBitWidth()==64);
3135 uint64_t i = *api.getRawData();
Dale Johannesen918c33c2007-08-24 05:08:11 +00003136 uint64_t myexponent = (i >> 52) & 0x7ff;
3137 uint64_t mysignificand = i & 0xfffffffffffffLL;
3138
Stephan Bergmann17c7f702016-12-14 11:57:17 +00003139 initialize(&semIEEEdouble);
Dale Johannesena719a602007-08-24 00:56:33 +00003140 assert(partCount()==1);
3141
Evan Cheng82b9e962008-05-02 21:15:08 +00003142 sign = static_cast<unsigned int>(i>>63);
Dale Johannesena719a602007-08-24 00:56:33 +00003143 if (myexponent==0 && mysignificand==0) {
3144 // exponent, significand meaningless
3145 category = fcZero;
Dale Johannesena719a602007-08-24 00:56:33 +00003146 } else if (myexponent==0x7ff && mysignificand==0) {
3147 // exponent, significand meaningless
3148 category = fcInfinity;
Dale Johannesen3cf889f2007-08-31 04:03:46 +00003149 } else if (myexponent==0x7ff && mysignificand!=0) {
3150 // exponent meaningless
3151 category = fcNaN;
3152 *significandParts() = mysignificand;
Dale Johannesena719a602007-08-24 00:56:33 +00003153 } else {
Dale Johannesena719a602007-08-24 00:56:33 +00003154 category = fcNormal;
3155 exponent = myexponent - 1023;
Dale Johannesen728687c2007-09-05 20:39:49 +00003156 *significandParts() = mysignificand;
3157 if (myexponent==0) // denormal
3158 exponent = -1022;
3159 else
3160 *significandParts() |= 0x10000000000000LL; // integer bit
Neil Booth9acbf5a2007-09-26 21:33:42 +00003161 }
Dale Johannesena719a602007-08-24 00:56:33 +00003162}
3163
Tim Shen85de51d2016-10-25 19:55:59 +00003164void IEEEFloat::initFromFloatAPInt(const APInt &api) {
Dale Johannesen245dceb2007-09-11 18:32:33 +00003165 assert(api.getBitWidth()==32);
3166 uint32_t i = (uint32_t)*api.getRawData();
Dale Johannesen918c33c2007-08-24 05:08:11 +00003167 uint32_t myexponent = (i >> 23) & 0xff;
3168 uint32_t mysignificand = i & 0x7fffff;
3169
Stephan Bergmann17c7f702016-12-14 11:57:17 +00003170 initialize(&semIEEEsingle);
Dale Johannesena719a602007-08-24 00:56:33 +00003171 assert(partCount()==1);
3172
Dale Johannesen3cf889f2007-08-31 04:03:46 +00003173 sign = i >> 31;
Dale Johannesena719a602007-08-24 00:56:33 +00003174 if (myexponent==0 && mysignificand==0) {
3175 // exponent, significand meaningless
3176 category = fcZero;
Dale Johannesena719a602007-08-24 00:56:33 +00003177 } else if (myexponent==0xff && mysignificand==0) {
3178 // exponent, significand meaningless
3179 category = fcInfinity;
Dale Johannesen4f55d9f2007-09-25 17:25:00 +00003180 } else if (myexponent==0xff && mysignificand!=0) {
Dale Johannesena719a602007-08-24 00:56:33 +00003181 // sign, exponent, significand meaningless
Dale Johannesen3cf889f2007-08-31 04:03:46 +00003182 category = fcNaN;
3183 *significandParts() = mysignificand;
Dale Johannesena719a602007-08-24 00:56:33 +00003184 } else {
3185 category = fcNormal;
Dale Johannesena719a602007-08-24 00:56:33 +00003186 exponent = myexponent - 127; //bias
Dale Johannesen728687c2007-09-05 20:39:49 +00003187 *significandParts() = mysignificand;
3188 if (myexponent==0) // denormal
3189 exponent = -126;
3190 else
3191 *significandParts() |= 0x800000; // integer bit
Dale Johannesena719a602007-08-24 00:56:33 +00003192 }
3193}
Dale Johannesen245dceb2007-09-11 18:32:33 +00003194
Tim Shen85de51d2016-10-25 19:55:59 +00003195void IEEEFloat::initFromHalfAPInt(const APInt &api) {
Chris Lattner4794b2b2009-10-16 02:13:51 +00003196 assert(api.getBitWidth()==16);
3197 uint32_t i = (uint32_t)*api.getRawData();
Dale Johannesen0d670b52009-10-23 04:02:51 +00003198 uint32_t myexponent = (i >> 10) & 0x1f;
Chris Lattner4794b2b2009-10-16 02:13:51 +00003199 uint32_t mysignificand = i & 0x3ff;
3200
Stephan Bergmann17c7f702016-12-14 11:57:17 +00003201 initialize(&semIEEEhalf);
Chris Lattner4794b2b2009-10-16 02:13:51 +00003202 assert(partCount()==1);
3203
3204 sign = i >> 15;
3205 if (myexponent==0 && mysignificand==0) {
3206 // exponent, significand meaningless
3207 category = fcZero;
3208 } else if (myexponent==0x1f && mysignificand==0) {
3209 // exponent, significand meaningless
3210 category = fcInfinity;
3211 } else if (myexponent==0x1f && mysignificand!=0) {
3212 // sign, exponent, significand meaningless
3213 category = fcNaN;
3214 *significandParts() = mysignificand;
3215 } else {
3216 category = fcNormal;
3217 exponent = myexponent - 15; //bias
3218 *significandParts() = mysignificand;
3219 if (myexponent==0) // denormal
3220 exponent = -14;
3221 else
3222 *significandParts() |= 0x400; // integer bit
3223 }
3224}
3225
Dale Johannesen245dceb2007-09-11 18:32:33 +00003226/// Treat api as containing the bits of a floating point number. Currently
Dale Johannesen007aa372007-10-11 18:07:22 +00003227/// we infer the floating point type from the size of the APInt. The
3228/// isIEEE argument distinguishes between PPC128 and IEEE128 (not meaningful
3229/// when the size is anything else).
Tim Shen85de51d2016-10-25 19:55:59 +00003230void IEEEFloat::initFromAPInt(const fltSemantics *Sem, const APInt &api) {
Stephan Bergmann17c7f702016-12-14 11:57:17 +00003231 if (Sem == &semIEEEhalf)
Chris Lattner4794b2b2009-10-16 02:13:51 +00003232 return initFromHalfAPInt(api);
Stephan Bergmann17c7f702016-12-14 11:57:17 +00003233 if (Sem == &semIEEEsingle)
Dale Johannesen245dceb2007-09-11 18:32:33 +00003234 return initFromFloatAPInt(api);
Stephan Bergmann17c7f702016-12-14 11:57:17 +00003235 if (Sem == &semIEEEdouble)
Dale Johannesen245dceb2007-09-11 18:32:33 +00003236 return initFromDoubleAPInt(api);
Stephan Bergmann17c7f702016-12-14 11:57:17 +00003237 if (Sem == &semX87DoubleExtended)
Dale Johannesen245dceb2007-09-11 18:32:33 +00003238 return initFromF80LongDoubleAPInt(api);
Stephan Bergmann17c7f702016-12-14 11:57:17 +00003239 if (Sem == &semIEEEquad)
Tim Northover29178a32013-01-22 09:46:31 +00003240 return initFromQuadrupleAPInt(api);
Tim Shenfd1e5aa2017-01-23 22:39:35 +00003241 if (Sem == &semPPCDoubleDoubleLegacy)
Tim Northover29178a32013-01-22 09:46:31 +00003242 return initFromPPCDoubleDoubleAPInt(api);
3243
Craig Topper2617dcc2014-04-15 06:32:26 +00003244 llvm_unreachable(nullptr);
Dale Johannesen245dceb2007-09-11 18:32:33 +00003245}
3246
Michael Gottesman0c622ea2013-05-30 18:07:13 +00003247/// Make this number the largest magnitude normal number in the given
3248/// semantics.
Tim Shen85de51d2016-10-25 19:55:59 +00003249void IEEEFloat::makeLargest(bool Negative) {
John McCall29b5c282009-12-24 08:56:26 +00003250 // We want (in interchange format):
3251 // sign = {Negative}
3252 // exponent = 1..10
3253 // significand = 1..1
Michael Gottesman0c622ea2013-05-30 18:07:13 +00003254 category = fcNormal;
3255 sign = Negative;
3256 exponent = semantics->maxExponent;
John McCall29b5c282009-12-24 08:56:26 +00003257
Michael Gottesman0c622ea2013-05-30 18:07:13 +00003258 // Use memset to set all but the highest integerPart to all ones.
3259 integerPart *significand = significandParts();
3260 unsigned PartCount = partCount();
3261 memset(significand, 0xFF, sizeof(integerPart)*(PartCount - 1));
John McCall29b5c282009-12-24 08:56:26 +00003262
Michael Gottesman0c622ea2013-05-30 18:07:13 +00003263 // Set the high integerPart especially setting all unused top bits for
3264 // internal consistency.
3265 const unsigned NumUnusedHighBits =
3266 PartCount*integerPartWidth - semantics->precision;
Alexey Samsonovba1ecbc2014-09-06 00:41:19 +00003267 significand[PartCount - 1] = (NumUnusedHighBits < integerPartWidth)
3268 ? (~integerPart(0) >> NumUnusedHighBits)
3269 : 0;
John McCall29b5c282009-12-24 08:56:26 +00003270}
3271
Michael Gottesman0c622ea2013-05-30 18:07:13 +00003272/// Make this number the smallest magnitude denormal number in the given
3273/// semantics.
Tim Shen85de51d2016-10-25 19:55:59 +00003274void IEEEFloat::makeSmallest(bool Negative) {
John McCall29b5c282009-12-24 08:56:26 +00003275 // We want (in interchange format):
3276 // sign = {Negative}
3277 // exponent = 0..0
3278 // significand = 0..01
Michael Gottesman0c622ea2013-05-30 18:07:13 +00003279 category = fcNormal;
3280 sign = Negative;
3281 exponent = semantics->minExponent;
3282 APInt::tcSet(significandParts(), 1, partCount());
3283}
John McCall29b5c282009-12-24 08:56:26 +00003284
Tim Shen139a58f2016-10-27 22:52:40 +00003285void IEEEFloat::makeSmallestNormalized(bool Negative) {
John McCall29b5c282009-12-24 08:56:26 +00003286 // We want (in interchange format):
3287 // sign = {Negative}
3288 // exponent = 0..0
3289 // significand = 10..0
3290
Tim Shen139a58f2016-10-27 22:52:40 +00003291 category = fcNormal;
3292 zeroSignificand();
3293 sign = Negative;
3294 exponent = semantics->minExponent;
3295 significandParts()[partCountForBits(semantics->precision) - 1] |=
3296 (((integerPart)1) << ((semantics->precision - 1) % integerPartWidth));
John McCall29b5c282009-12-24 08:56:26 +00003297}
3298
Tim Shen85de51d2016-10-25 19:55:59 +00003299IEEEFloat::IEEEFloat(const fltSemantics &Sem, const APInt &API) {
Tim Northover29178a32013-01-22 09:46:31 +00003300 initFromAPInt(&Sem, API);
Dale Johannesen245dceb2007-09-11 18:32:33 +00003301}
3302
Tim Shen85de51d2016-10-25 19:55:59 +00003303IEEEFloat::IEEEFloat(float f) {
Stephan Bergmann17c7f702016-12-14 11:57:17 +00003304 initFromAPInt(&semIEEEsingle, APInt::floatToBits(f));
Dale Johannesen245dceb2007-09-11 18:32:33 +00003305}
3306
Tim Shen85de51d2016-10-25 19:55:59 +00003307IEEEFloat::IEEEFloat(double d) {
Stephan Bergmann17c7f702016-12-14 11:57:17 +00003308 initFromAPInt(&semIEEEdouble, APInt::doubleToBits(d));
Dale Johannesen245dceb2007-09-11 18:32:33 +00003309}
John McCall29b5c282009-12-24 08:56:26 +00003310
3311namespace {
David Blaikie70fdf722012-07-25 18:04:24 +00003312 void append(SmallVectorImpl<char> &Buffer, StringRef Str) {
3313 Buffer.append(Str.begin(), Str.end());
John McCall29b5c282009-12-24 08:56:26 +00003314 }
3315
John McCalle6212ace2009-12-24 12:16:56 +00003316 /// Removes data from the given significand until it is no more
3317 /// precise than is required for the desired precision.
3318 void AdjustToPrecision(APInt &significand,
3319 int &exp, unsigned FormatPrecision) {
3320 unsigned bits = significand.getActiveBits();
3321
3322 // 196/59 is a very slight overestimate of lg_2(10).
3323 unsigned bitsRequired = (FormatPrecision * 196 + 58) / 59;
3324
3325 if (bits <= bitsRequired) return;
3326
3327 unsigned tensRemovable = (bits - bitsRequired) * 59 / 196;
3328 if (!tensRemovable) return;
3329
3330 exp += tensRemovable;
3331
3332 APInt divisor(significand.getBitWidth(), 1);
3333 APInt powten(significand.getBitWidth(), 10);
3334 while (true) {
3335 if (tensRemovable & 1)
3336 divisor *= powten;
3337 tensRemovable >>= 1;
3338 if (!tensRemovable) break;
3339 powten *= powten;
3340 }
3341
3342 significand = significand.udiv(divisor);
3343
Hao Liube99cc32013-03-20 01:46:36 +00003344 // Truncate the significand down to its active bit count.
3345 significand = significand.trunc(significand.getActiveBits());
John McCalle6212ace2009-12-24 12:16:56 +00003346 }
3347
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +00003348
John McCall29b5c282009-12-24 08:56:26 +00003349 void AdjustToPrecision(SmallVectorImpl<char> &buffer,
3350 int &exp, unsigned FormatPrecision) {
3351 unsigned N = buffer.size();
3352 if (N <= FormatPrecision) return;
3353
3354 // The most significant figures are the last ones in the buffer.
3355 unsigned FirstSignificant = N - FormatPrecision;
3356
3357 // Round.
3358 // FIXME: this probably shouldn't use 'round half up'.
3359
3360 // Rounding down is just a truncation, except we also want to drop
3361 // trailing zeros from the new result.
3362 if (buffer[FirstSignificant - 1] < '5') {
NAKAMURA Takumi5adeb932012-02-19 03:18:29 +00003363 while (FirstSignificant < N && buffer[FirstSignificant] == '0')
John McCall29b5c282009-12-24 08:56:26 +00003364 FirstSignificant++;
3365
3366 exp += FirstSignificant;
3367 buffer.erase(&buffer[0], &buffer[FirstSignificant]);
3368 return;
3369 }
3370
3371 // Rounding up requires a decimal add-with-carry. If we continue
3372 // the carry, the newly-introduced zeros will just be truncated.
3373 for (unsigned I = FirstSignificant; I != N; ++I) {
3374 if (buffer[I] == '9') {
3375 FirstSignificant++;
3376 } else {
3377 buffer[I]++;
3378 break;
3379 }
3380 }
3381
3382 // If we carried through, we have exactly one digit of precision.
3383 if (FirstSignificant == N) {
3384 exp += FirstSignificant;
3385 buffer.clear();
3386 buffer.push_back('1');
3387 return;
3388 }
3389
3390 exp += FirstSignificant;
3391 buffer.erase(&buffer[0], &buffer[FirstSignificant]);
3392 }
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +00003393}
John McCall29b5c282009-12-24 08:56:26 +00003394
Tim Shen85de51d2016-10-25 19:55:59 +00003395void IEEEFloat::toString(SmallVectorImpl<char> &Str, unsigned FormatPrecision,
Serguei Katkov3a46eb42017-04-21 02:52:17 +00003396 unsigned FormatMaxPadding, bool TruncateZero) const {
John McCall29b5c282009-12-24 08:56:26 +00003397 switch (category) {
3398 case fcInfinity:
3399 if (isNegative())
3400 return append(Str, "-Inf");
3401 else
3402 return append(Str, "+Inf");
3403
3404 case fcNaN: return append(Str, "NaN");
3405
3406 case fcZero:
3407 if (isNegative())
3408 Str.push_back('-');
3409
Serguei Katkov3a46eb42017-04-21 02:52:17 +00003410 if (!FormatMaxPadding) {
3411 if (TruncateZero)
3412 append(Str, "0.0E+0");
3413 else {
3414 append(Str, "0.0");
3415 if (FormatPrecision > 1)
3416 Str.append(FormatPrecision - 1, '0');
3417 append(Str, "e+00");
3418 }
3419 } else
John McCall29b5c282009-12-24 08:56:26 +00003420 Str.push_back('0');
3421 return;
3422
3423 case fcNormal:
3424 break;
3425 }
3426
3427 if (isNegative())
3428 Str.push_back('-');
3429
3430 // Decompose the number into an APInt and an exponent.
3431 int exp = exponent - ((int) semantics->precision - 1);
3432 APInt significand(semantics->precision,
Jeffrey Yasskin7a162882011-07-18 21:45:40 +00003433 makeArrayRef(significandParts(),
3434 partCountForBits(semantics->precision)));
John McCall29b5c282009-12-24 08:56:26 +00003435
John McCalldd5044a2009-12-24 23:18:09 +00003436 // Set FormatPrecision if zero. We want to do this before we
3437 // truncate trailing zeros, as those are part of the precision.
3438 if (!FormatPrecision) {
Eli Friedmane72f1322013-08-29 23:44:34 +00003439 // We use enough digits so the number can be round-tripped back to an
3440 // APFloat. The formula comes from "How to Print Floating-Point Numbers
3441 // Accurately" by Steele and White.
3442 // FIXME: Using a formula based purely on the precision is conservative;
3443 // we can print fewer digits depending on the actual value being printed.
John McCalldd5044a2009-12-24 23:18:09 +00003444
Eli Friedmane72f1322013-08-29 23:44:34 +00003445 // FormatPrecision = 2 + floor(significandBits / lg_2(10))
3446 FormatPrecision = 2 + semantics->precision * 59 / 196;
John McCalldd5044a2009-12-24 23:18:09 +00003447 }
3448
John McCall29b5c282009-12-24 08:56:26 +00003449 // Ignore trailing binary zeros.
3450 int trailingZeros = significand.countTrailingZeros();
3451 exp += trailingZeros;
Craig Topperfc947bc2017-04-18 17:14:21 +00003452 significand.lshrInPlace(trailingZeros);
John McCall29b5c282009-12-24 08:56:26 +00003453
3454 // Change the exponent from 2^e to 10^e.
3455 if (exp == 0) {
3456 // Nothing to do.
3457 } else if (exp > 0) {
3458 // Just shift left.
Jay Foad583abbc2010-12-07 08:25:19 +00003459 significand = significand.zext(semantics->precision + exp);
John McCall29b5c282009-12-24 08:56:26 +00003460 significand <<= exp;
3461 exp = 0;
3462 } else { /* exp < 0 */
3463 int texp = -exp;
3464
3465 // We transform this using the identity:
3466 // (N)(2^-e) == (N)(5^e)(10^-e)
3467 // This means we have to multiply N (the significand) by 5^e.
3468 // To avoid overflow, we have to operate on numbers large
3469 // enough to store N * 5^e:
3470 // log2(N * 5^e) == log2(N) + e * log2(5)
John McCalldd5044a2009-12-24 23:18:09 +00003471 // <= semantics->precision + e * 137 / 59
3472 // (log_2(5) ~ 2.321928 < 2.322034 ~ 137/59)
Dan Gohmanb452d4e2010-03-24 19:38:02 +00003473
Eli Friedman19546412011-10-07 23:40:49 +00003474 unsigned precision = semantics->precision + (137 * texp + 136) / 59;
John McCall29b5c282009-12-24 08:56:26 +00003475
3476 // Multiply significand by 5^e.
3477 // N * 5^0101 == N * 5^(1*1) * 5^(0*2) * 5^(1*4) * 5^(0*8)
Jay Foad583abbc2010-12-07 08:25:19 +00003478 significand = significand.zext(precision);
John McCall29b5c282009-12-24 08:56:26 +00003479 APInt five_to_the_i(precision, 5);
3480 while (true) {
3481 if (texp & 1) significand *= five_to_the_i;
Dan Gohmanb452d4e2010-03-24 19:38:02 +00003482
John McCall29b5c282009-12-24 08:56:26 +00003483 texp >>= 1;
3484 if (!texp) break;
3485 five_to_the_i *= five_to_the_i;
3486 }
3487 }
3488
John McCalle6212ace2009-12-24 12:16:56 +00003489 AdjustToPrecision(significand, exp, FormatPrecision);
3490
Dmitri Gribenko226fea52013-01-13 16:01:15 +00003491 SmallVector<char, 256> buffer;
John McCall29b5c282009-12-24 08:56:26 +00003492
3493 // Fill the buffer.
3494 unsigned precision = significand.getBitWidth();
3495 APInt ten(precision, 10);
3496 APInt digit(precision, 0);
3497
3498 bool inTrail = true;
3499 while (significand != 0) {
3500 // digit <- significand % 10
3501 // significand <- significand / 10
3502 APInt::udivrem(significand, ten, significand, digit);
3503
3504 unsigned d = digit.getZExtValue();
3505
3506 // Drop trailing zeros.
3507 if (inTrail && !d) exp++;
3508 else {
3509 buffer.push_back((char) ('0' + d));
3510 inTrail = false;
3511 }
3512 }
3513
3514 assert(!buffer.empty() && "no characters in buffer!");
3515
3516 // Drop down to FormatPrecision.
3517 // TODO: don't do more precise calculations above than are required.
3518 AdjustToPrecision(buffer, exp, FormatPrecision);
3519
3520 unsigned NDigits = buffer.size();
3521
John McCalldd5044a2009-12-24 23:18:09 +00003522 // Check whether we should use scientific notation.
John McCall29b5c282009-12-24 08:56:26 +00003523 bool FormatScientific;
3524 if (!FormatMaxPadding)
3525 FormatScientific = true;
3526 else {
John McCall29b5c282009-12-24 08:56:26 +00003527 if (exp >= 0) {
John McCalldd5044a2009-12-24 23:18:09 +00003528 // 765e3 --> 765000
3529 // ^^^
3530 // But we shouldn't make the number look more precise than it is.
3531 FormatScientific = ((unsigned) exp > FormatMaxPadding ||
3532 NDigits + (unsigned) exp > FormatPrecision);
John McCall29b5c282009-12-24 08:56:26 +00003533 } else {
John McCalldd5044a2009-12-24 23:18:09 +00003534 // Power of the most significant digit.
3535 int MSD = exp + (int) (NDigits - 1);
3536 if (MSD >= 0) {
John McCall29b5c282009-12-24 08:56:26 +00003537 // 765e-2 == 7.65
John McCalldd5044a2009-12-24 23:18:09 +00003538 FormatScientific = false;
John McCall29b5c282009-12-24 08:56:26 +00003539 } else {
3540 // 765e-5 == 0.00765
3541 // ^ ^^
John McCalldd5044a2009-12-24 23:18:09 +00003542 FormatScientific = ((unsigned) -MSD) > FormatMaxPadding;
John McCall29b5c282009-12-24 08:56:26 +00003543 }
3544 }
John McCall29b5c282009-12-24 08:56:26 +00003545 }
3546
3547 // Scientific formatting is pretty straightforward.
3548 if (FormatScientific) {
3549 exp += (NDigits - 1);
3550
3551 Str.push_back(buffer[NDigits-1]);
3552 Str.push_back('.');
Serguei Katkov3a46eb42017-04-21 02:52:17 +00003553 if (NDigits == 1 && TruncateZero)
John McCall29b5c282009-12-24 08:56:26 +00003554 Str.push_back('0');
3555 else
3556 for (unsigned I = 1; I != NDigits; ++I)
3557 Str.push_back(buffer[NDigits-1-I]);
Serguei Katkov3a46eb42017-04-21 02:52:17 +00003558 // Fill with zeros up to FormatPrecision.
3559 if (!TruncateZero && FormatPrecision > NDigits - 1)
3560 Str.append(FormatPrecision - NDigits + 1, '0');
3561 // For !TruncateZero we use lower 'e'.
3562 Str.push_back(TruncateZero ? 'E' : 'e');
John McCall29b5c282009-12-24 08:56:26 +00003563
3564 Str.push_back(exp >= 0 ? '+' : '-');
3565 if (exp < 0) exp = -exp;
3566 SmallVector<char, 6> expbuf;
3567 do {
3568 expbuf.push_back((char) ('0' + (exp % 10)));
3569 exp /= 10;
3570 } while (exp);
Serguei Katkov3a46eb42017-04-21 02:52:17 +00003571 // Exponent always at least two digits if we do not truncate zeros.
3572 if (!TruncateZero && expbuf.size() < 2)
3573 expbuf.push_back('0');
John McCall29b5c282009-12-24 08:56:26 +00003574 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
Simon Pilgrim00b34992017-03-20 14:40:12 +00004296APFloat::opStatus
4297DoubleAPFloat::convertToInteger(MutableArrayRef<integerPart> Input,
4298 unsigned int Width, bool IsSigned,
4299 roundingMode RM, bool *IsExact) const {
Tim Shenfd1e5aa2017-01-23 22:39:35 +00004300 assert(Semantics == &semPPCDoubleDouble && "Unexpected Semantics");
4301 return APFloat(semPPCDoubleDoubleLegacy, bitcastToAPInt())
4302 .convertToInteger(Input, Width, IsSigned, RM, IsExact);
4303}
4304
4305APFloat::opStatus DoubleAPFloat::convertFromAPInt(const APInt &Input,
4306 bool IsSigned,
4307 roundingMode RM) {
4308 assert(Semantics == &semPPCDoubleDouble && "Unexpected Semantics");
4309 APFloat Tmp(semPPCDoubleDoubleLegacy);
4310 auto Ret = Tmp.convertFromAPInt(Input, IsSigned, RM);
4311 *this = DoubleAPFloat(semPPCDoubleDouble, Tmp.bitcastToAPInt());
4312 return Ret;
4313}
4314
4315APFloat::opStatus
4316DoubleAPFloat::convertFromSignExtendedInteger(const integerPart *Input,
4317 unsigned int InputSize,
4318 bool IsSigned, roundingMode RM) {
4319 assert(Semantics == &semPPCDoubleDouble && "Unexpected Semantics");
4320 APFloat Tmp(semPPCDoubleDoubleLegacy);
4321 auto Ret = Tmp.convertFromSignExtendedInteger(Input, InputSize, IsSigned, RM);
4322 *this = DoubleAPFloat(semPPCDoubleDouble, Tmp.bitcastToAPInt());
4323 return Ret;
4324}
4325
4326APFloat::opStatus
4327DoubleAPFloat::convertFromZeroExtendedInteger(const integerPart *Input,
4328 unsigned int InputSize,
4329 bool IsSigned, roundingMode RM) {
4330 assert(Semantics == &semPPCDoubleDouble && "Unexpected Semantics");
4331 APFloat Tmp(semPPCDoubleDoubleLegacy);
4332 auto Ret = Tmp.convertFromZeroExtendedInteger(Input, InputSize, IsSigned, RM);
4333 *this = DoubleAPFloat(semPPCDoubleDouble, Tmp.bitcastToAPInt());
4334 return Ret;
4335}
4336
4337unsigned int DoubleAPFloat::convertToHexString(char *DST,
4338 unsigned int HexDigits,
4339 bool UpperCase,
4340 roundingMode RM) const {
4341 assert(Semantics == &semPPCDoubleDouble && "Unexpected Semantics");
4342 return APFloat(semPPCDoubleDoubleLegacy, bitcastToAPInt())
4343 .convertToHexString(DST, HexDigits, UpperCase, RM);
4344}
4345
4346bool DoubleAPFloat::isDenormal() const {
4347 return getCategory() == fcNormal &&
4348 (Floats[0].isDenormal() || Floats[1].isDenormal() ||
Tim Shen7117e692017-01-26 00:11:07 +00004349 // (double)(Hi + Lo) == Hi defines a normal number.
Tim Shenfd1e5aa2017-01-23 22:39:35 +00004350 Floats[0].compare(Floats[0] + Floats[1]) != cmpEqual);
4351}
4352
4353bool DoubleAPFloat::isSmallest() const {
4354 if (getCategory() != fcNormal)
4355 return false;
4356 DoubleAPFloat Tmp(*this);
4357 Tmp.makeSmallest(this->isNegative());
4358 return Tmp.compare(*this) == cmpEqual;
4359}
4360
4361bool DoubleAPFloat::isLargest() const {
4362 if (getCategory() != fcNormal)
4363 return false;
4364 DoubleAPFloat Tmp(*this);
4365 Tmp.makeLargest(this->isNegative());
4366 return Tmp.compare(*this) == cmpEqual;
4367}
4368
4369bool DoubleAPFloat::isInteger() const {
4370 assert(Semantics == &semPPCDoubleDouble && "Unexpected Semantics");
Davide Italiano5a2530d2017-08-21 16:51:54 +00004371 return Floats[0].isInteger() && Floats[1].isInteger();
Tim Shenfd1e5aa2017-01-23 22:39:35 +00004372}
4373
4374void DoubleAPFloat::toString(SmallVectorImpl<char> &Str,
4375 unsigned FormatPrecision,
Serguei Katkov3a46eb42017-04-21 02:52:17 +00004376 unsigned FormatMaxPadding,
4377 bool TruncateZero) const {
Tim Shenfd1e5aa2017-01-23 22:39:35 +00004378 assert(Semantics == &semPPCDoubleDouble && "Unexpected Semantics");
4379 APFloat(semPPCDoubleDoubleLegacy, bitcastToAPInt())
Serguei Katkov3a46eb42017-04-21 02:52:17 +00004380 .toString(Str, FormatPrecision, FormatMaxPadding, TruncateZero);
Tim Shenfd1e5aa2017-01-23 22:39:35 +00004381}
4382
4383bool DoubleAPFloat::getExactInverse(APFloat *inv) const {
4384 assert(Semantics == &semPPCDoubleDouble && "Unexpected Semantics");
4385 APFloat Tmp(semPPCDoubleDoubleLegacy, bitcastToAPInt());
4386 if (!inv)
4387 return Tmp.getExactInverse(nullptr);
4388 APFloat Inv(semPPCDoubleDoubleLegacy);
4389 auto Ret = Tmp.getExactInverse(&Inv);
4390 *inv = APFloat(semPPCDoubleDouble, Inv.bitcastToAPInt());
4391 return Ret;
4392}
4393
4394DoubleAPFloat scalbn(DoubleAPFloat Arg, int Exp, APFloat::roundingMode RM) {
4395 assert(Arg.Semantics == &semPPCDoubleDouble && "Unexpected Semantics");
4396 return DoubleAPFloat(semPPCDoubleDouble, scalbn(Arg.Floats[0], Exp, RM),
4397 scalbn(Arg.Floats[1], Exp, RM));
4398}
4399
4400DoubleAPFloat frexp(const DoubleAPFloat &Arg, int &Exp,
4401 APFloat::roundingMode RM) {
4402 assert(Arg.Semantics == &semPPCDoubleDouble && "Unexpected Semantics");
4403 APFloat First = frexp(Arg.Floats[0], Exp, RM);
4404 APFloat Second = Arg.Floats[1];
4405 if (Arg.getCategory() == APFloat::fcNormal)
4406 Second = scalbn(Second, -Exp, RM);
4407 return DoubleAPFloat(semPPCDoubleDouble, std::move(First), std::move(Second));
4408}
4409
Tim Shen85de51d2016-10-25 19:55:59 +00004410} // End detail namespace
4411
Tim Shen398f90f2016-11-06 07:38:37 +00004412APFloat::Storage::Storage(IEEEFloat F, const fltSemantics &Semantics) {
4413 if (usesLayout<IEEEFloat>(Semantics)) {
4414 new (&IEEE) IEEEFloat(std::move(F));
Tim Shen7b57ac42016-12-21 02:39:21 +00004415 return;
4416 }
4417 if (usesLayout<DoubleAPFloat>(Semantics)) {
Tim Shen398f90f2016-11-06 07:38:37 +00004418 new (&Double)
4419 DoubleAPFloat(Semantics, APFloat(std::move(F), F.getSemantics()),
Stephan Bergmann17c7f702016-12-14 11:57:17 +00004420 APFloat(semIEEEdouble));
Tim Shen7b57ac42016-12-21 02:39:21 +00004421 return;
Tim Shen398f90f2016-11-06 07:38:37 +00004422 }
Tim Shen7b57ac42016-12-21 02:39:21 +00004423 llvm_unreachable("Unexpected semantics");
Tim Shen398f90f2016-11-06 07:38:37 +00004424}
4425
Tim Shen85de51d2016-10-25 19:55:59 +00004426APFloat::opStatus APFloat::convertFromString(StringRef Str, roundingMode RM) {
Tim Shen601ba8c2017-01-27 02:11:07 +00004427 APFLOAT_DISPATCH_ON_SEMANTICS(convertFromString(Str, RM));
Tim Shen85de51d2016-10-25 19:55:59 +00004428}
4429
Tim Shenfd1e5aa2017-01-23 22:39:35 +00004430hash_code hash_value(const APFloat &Arg) {
4431 if (APFloat::usesLayout<detail::IEEEFloat>(Arg.getSemantics()))
4432 return hash_value(Arg.U.IEEE);
4433 if (APFloat::usesLayout<detail::DoubleAPFloat>(Arg.getSemantics()))
4434 return hash_value(Arg.U.Double);
4435 llvm_unreachable("Unexpected semantics");
4436}
Tim Shen85de51d2016-10-25 19:55:59 +00004437
4438APFloat::APFloat(const fltSemantics &Semantics, StringRef S)
Tim Shen139a58f2016-10-27 22:52:40 +00004439 : APFloat(Semantics) {
4440 convertFromString(S, rmNearestTiesToEven);
4441}
4442
4443APFloat::opStatus APFloat::convert(const fltSemantics &ToSemantics,
4444 roundingMode RM, bool *losesInfo) {
Sven van Haastregt5ad5c3c2018-05-11 09:45:42 +00004445 if (&getSemantics() == &ToSemantics) {
4446 *losesInfo = false;
Tim Shen139a58f2016-10-27 22:52:40 +00004447 return opOK;
Sven van Haastregt5ad5c3c2018-05-11 09:45:42 +00004448 }
Tim Shen139a58f2016-10-27 22:52:40 +00004449 if (usesLayout<IEEEFloat>(getSemantics()) &&
Tim Shen7b57ac42016-12-21 02:39:21 +00004450 usesLayout<IEEEFloat>(ToSemantics))
Tim Shen139a58f2016-10-27 22:52:40 +00004451 return U.IEEE.convert(ToSemantics, RM, losesInfo);
Tim Shen7b57ac42016-12-21 02:39:21 +00004452 if (usesLayout<IEEEFloat>(getSemantics()) &&
4453 usesLayout<DoubleAPFloat>(ToSemantics)) {
Stephan Bergmann17c7f702016-12-14 11:57:17 +00004454 assert(&ToSemantics == &semPPCDoubleDouble);
Tim Shenfd1e5aa2017-01-23 22:39:35 +00004455 auto Ret = U.IEEE.convert(semPPCDoubleDoubleLegacy, RM, losesInfo);
4456 *this = APFloat(ToSemantics, U.IEEE.bitcastToAPInt());
Tim Shen139a58f2016-10-27 22:52:40 +00004457 return Ret;
Tim Shen7b57ac42016-12-21 02:39:21 +00004458 }
4459 if (usesLayout<DoubleAPFloat>(getSemantics()) &&
4460 usesLayout<IEEEFloat>(ToSemantics)) {
Tim Shen139a58f2016-10-27 22:52:40 +00004461 auto Ret = getIEEE().convert(ToSemantics, RM, losesInfo);
Tim Shen398f90f2016-11-06 07:38:37 +00004462 *this = APFloat(std::move(getIEEE()), ToSemantics);
Tim Shen139a58f2016-10-27 22:52:40 +00004463 return Ret;
Tim Shen139a58f2016-10-27 22:52:40 +00004464 }
Tim Shen7b57ac42016-12-21 02:39:21 +00004465 llvm_unreachable("Unexpected semantics");
Tim Shen139a58f2016-10-27 22:52:40 +00004466}
Tim Shen85de51d2016-10-25 19:55:59 +00004467
Tim Shen398f90f2016-11-06 07:38:37 +00004468APFloat APFloat::getAllOnesValue(unsigned BitWidth, bool isIEEE) {
4469 if (isIEEE) {
4470 switch (BitWidth) {
4471 case 16:
Stephan Bergmann17c7f702016-12-14 11:57:17 +00004472 return APFloat(semIEEEhalf, APInt::getAllOnesValue(BitWidth));
Tim Shen398f90f2016-11-06 07:38:37 +00004473 case 32:
Stephan Bergmann17c7f702016-12-14 11:57:17 +00004474 return APFloat(semIEEEsingle, APInt::getAllOnesValue(BitWidth));
Tim Shen398f90f2016-11-06 07:38:37 +00004475 case 64:
Stephan Bergmann17c7f702016-12-14 11:57:17 +00004476 return APFloat(semIEEEdouble, APInt::getAllOnesValue(BitWidth));
Tim Shen398f90f2016-11-06 07:38:37 +00004477 case 80:
Stephan Bergmann17c7f702016-12-14 11:57:17 +00004478 return APFloat(semX87DoubleExtended, APInt::getAllOnesValue(BitWidth));
Tim Shen398f90f2016-11-06 07:38:37 +00004479 case 128:
Stephan Bergmann17c7f702016-12-14 11:57:17 +00004480 return APFloat(semIEEEquad, APInt::getAllOnesValue(BitWidth));
Tim Shen398f90f2016-11-06 07:38:37 +00004481 default:
4482 llvm_unreachable("Unknown floating bit width");
4483 }
4484 } else {
4485 assert(BitWidth == 128);
Stephan Bergmann17c7f702016-12-14 11:57:17 +00004486 return APFloat(semPPCDoubleDouble, APInt::getAllOnesValue(BitWidth));
Tim Shen398f90f2016-11-06 07:38:37 +00004487 }
4488}
4489
Tim Shen44bde892016-12-12 21:59:30 +00004490void APFloat::print(raw_ostream &OS) const {
4491 SmallVector<char, 16> Buffer;
4492 toString(Buffer);
4493 OS << Buffer << "\n";
4494}
4495
Aaron Ballman615eb472017-10-15 14:32:27 +00004496#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Matthias Braun8c209aa2017-01-28 02:02:38 +00004497LLVM_DUMP_METHOD void APFloat::dump() const { print(dbgs()); }
4498#endif
Tim Shen44bde892016-12-12 21:59:30 +00004499
Tim Shenfd1e5aa2017-01-23 22:39:35 +00004500void APFloat::Profile(FoldingSetNodeID &NID) const {
4501 NID.Add(bitcastToAPInt());
4502}
4503
4504/* Same as convertToInteger(integerPart*, ...), except the result is returned in
4505 an APSInt, whose initial bit-width and signed-ness are used to determine the
4506 precision of the conversion.
4507 */
4508APFloat::opStatus APFloat::convertToInteger(APSInt &result,
4509 roundingMode rounding_mode,
4510 bool *isExact) const {
4511 unsigned bitWidth = result.getBitWidth();
4512 SmallVector<uint64_t, 4> parts(result.getNumWords());
Simon Pilgrim00b34992017-03-20 14:40:12 +00004513 opStatus status = convertToInteger(parts, bitWidth, result.isSigned(),
Tim Shenfd1e5aa2017-01-23 22:39:35 +00004514 rounding_mode, isExact);
4515 // Keeps the original signed-ness.
4516 result = APInt(bitWidth, parts);
4517 return status;
4518}
4519
Tim Shen85de51d2016-10-25 19:55:59 +00004520} // End llvm namespace
Tim Shen601ba8c2017-01-27 02:11:07 +00004521
4522#undef APFLOAT_DISPATCH_ON_SEMANTICS