Movatterモバイル変換


[0]ホーム

URL:


LLVM 20.0.0git
APFloat.cpp
Go to the documentation of this file.
1//===-- APFloat.cpp - Implement APFloat class -----------------------------===//
2//
3// 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
6//
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
14#include "llvm/ADT/APFloat.h"
15#include "llvm/ADT/APSInt.h"
16#include "llvm/ADT/ArrayRef.h"
17#include "llvm/ADT/FloatingPointMode.h"
18#include "llvm/ADT/FoldingSet.h"
19#include "llvm/ADT/Hashing.h"
20#include "llvm/ADT/STLExtras.h"
21#include "llvm/ADT/StringExtras.h"
22#include "llvm/ADT/StringRef.h"
23#include "llvm/Config/llvm-config.h"
24#include "llvm/Support/Debug.h"
25#include "llvm/Support/Error.h"
26#include "llvm/Support/MathExtras.h"
27#include "llvm/Support/raw_ostream.h"
28#include <cstring>
29#include <limits.h>
30
31#define APFLOAT_DISPATCH_ON_SEMANTICS(METHOD_CALL) \
32 do { \
33 if (usesLayout<IEEEFloat>(getSemantics())) \
34 return U.IEEE.METHOD_CALL; \
35 if (usesLayout<DoubleAPFloat>(getSemantics())) \
36 return U.Double.METHOD_CALL; \
37 llvm_unreachable("Unexpected semantics"); \
38 } while (false)
39
40using namespacellvm;
41
42/// A macro used to combine two fcCategory enums into one key which can be used
43/// in a switch statement to classify how the interaction of two APFloat's
44/// categories affects an operation.
45///
46/// TODO: If clang source code is ever allowed to use constexpr in its own
47/// codebase, change this into a static inline function.
48#define PackCategoriesIntoKey(_lhs, _rhs) ((_lhs) * 4 + (_rhs))
49
50/* Assumed in hexadecimal significand parsing, and conversion to
51 hexadecimal strings. */
52static_assert(APFloatBase::integerPartWidth % 4 == 0,"Part width must be divisible by 4!");
53
54namespacellvm {
55
56// How the nonfinite values Inf and NaN are represented.
57enum classfltNonfiniteBehavior {
58// Represents standard IEEE 754 behavior. A value is nonfinite if the
59// exponent field is all 1s. In such cases, a value is Inf if the
60// significand bits are all zero, and NaN otherwise
61IEEE754,
62
63// This behavior is present in the Float8ExMyFN* types (Float8E4M3FN,
64// Float8E5M2FNUZ, Float8E4M3FNUZ, and Float8E4M3B11FNUZ). There is no
65// representation for Inf, and operations that would ordinarily produce Inf
66// produce NaN instead.
67// The details of the NaN representation(s) in this form are determined by the
68// `fltNanEncoding` enum. We treat all NaNs as quiet, as the available
69// encodings do not distinguish between signalling and quiet NaN.
70NanOnly,
71
72// This behavior is present in Float6E3M2FN, Float6E2M3FN, and
73// Float4E2M1FN types, which do not support Inf or NaN values.
74FiniteOnly,
75};
76
77// How NaN values are represented. This is curently only used in combination
78// with fltNonfiniteBehavior::NanOnly, and using a variant other than IEEE
79// while having IEEE non-finite behavior is liable to lead to unexpected
80// results.
81enum classfltNanEncoding {
82// Represents the standard IEEE behavior where a value is NaN if its
83// exponent is all 1s and the significand is non-zero.
84IEEE,
85
86// Represents the behavior in the Float8E4M3FN floating point type where NaN
87// is represented by having the exponent and mantissa set to all 1s.
88// This behavior matches the FP8 E4M3 type described in
89// https://arxiv.org/abs/2209.05433. We treat both signed and unsigned NaNs
90// as non-signalling, although the paper does not state whether the NaN
91// values are signalling or not.
92AllOnes,
93
94// Represents the behavior in Float8E{5,4}E{2,3}FNUZ floating point types
95// where NaN is represented by a sign bit of 1 and all 0s in the exponent
96// and mantissa (i.e. the negative zero encoding in a IEEE float). Since
97// there is only one NaN value, it is treated as quiet NaN. This matches the
98// behavior described in https://arxiv.org/abs/2206.02915 .
99NegativeZero,
100};
101
102/* Represents floating point arithmetic semantics. */
103structfltSemantics {
104/* The largest E such that 2^E is representable; this matches the
105 definition of IEEE 754. */
106APFloatBase::ExponentTypemaxExponent;
107
108/* The smallest E such that 2^E is a normalized number; this
109 matches the definition of IEEE 754. */
110APFloatBase::ExponentTypeminExponent;
111
112/* Number of bits in the significand. This includes the integer
113 bit. */
114unsignedintprecision;
115
116/* Number of bits actually used in the semantics. */
117unsignedintsizeInBits;
118
119fltNonfiniteBehaviornonFiniteBehavior =fltNonfiniteBehavior::IEEE754;
120
121fltNanEncodingnanEncoding =fltNanEncoding::IEEE;
122
123/* Whether this semantics has an encoding for Zero */
124boolhasZero =true;
125
126/* Whether this semantics can represent signed values */
127boolhasSignedRepr =true;
128};
129
130staticconstexprfltSemanticssemIEEEhalf = {15, -14, 11, 16};
131staticconstexprfltSemanticssemBFloat = {127, -126, 8, 16};
132staticconstexprfltSemanticssemIEEEsingle = {127, -126, 24, 32};
133staticconstexprfltSemanticssemIEEEdouble = {1023, -1022, 53, 64};
134staticconstexprfltSemanticssemIEEEquad = {16383, -16382, 113, 128};
135staticconstexprfltSemanticssemFloat8E5M2 = {15, -14, 3, 8};
136staticconstexprfltSemanticssemFloat8E5M2FNUZ = {
137 15, -15, 3, 8,fltNonfiniteBehavior::NanOnly,fltNanEncoding::NegativeZero};
138staticconstexprfltSemanticssemFloat8E4M3 = {7, -6, 4, 8};
139staticconstexprfltSemanticssemFloat8E4M3FN = {
140 8, -6, 4, 8,fltNonfiniteBehavior::NanOnly,fltNanEncoding::AllOnes};
141staticconstexprfltSemanticssemFloat8E4M3FNUZ = {
142 7, -7, 4, 8,fltNonfiniteBehavior::NanOnly,fltNanEncoding::NegativeZero};
143staticconstexprfltSemanticssemFloat8E4M3B11FNUZ = {
144 4, -10, 4, 8,fltNonfiniteBehavior::NanOnly,fltNanEncoding::NegativeZero};
145staticconstexprfltSemanticssemFloat8E3M4 = {3, -2, 5, 8};
146staticconstexprfltSemanticssemFloatTF32 = {127, -126, 11, 19};
147staticconstexprfltSemanticssemFloat8E8M0FNU = {
148 127, -127, 1, 8,fltNonfiniteBehavior::NanOnly,fltNanEncoding::AllOnes,
149false,false};
150
151staticconstexprfltSemanticssemFloat6E3M2FN = {
152 4, -2, 3, 6,fltNonfiniteBehavior::FiniteOnly};
153staticconstexprfltSemanticssemFloat6E2M3FN = {
154 2, 0, 4, 6,fltNonfiniteBehavior::FiniteOnly};
155staticconstexprfltSemanticssemFloat4E2M1FN = {
156 2, 0, 2, 4,fltNonfiniteBehavior::FiniteOnly};
157staticconstexprfltSemanticssemX87DoubleExtended = {16383, -16382, 64, 80};
158staticconstexprfltSemanticssemBogus = {0, 0, 0, 0};
159staticconstexprfltSemanticssemPPCDoubleDouble = {-1, 0, 0, 128};
160staticconstexprfltSemanticssemPPCDoubleDoubleLegacy = {1023, -1022 + 53,
161 53 + 53, 128};
162
163constllvm::fltSemantics &APFloatBase::EnumToSemantics(Semantics S) {
164switch (S) {
165caseS_IEEEhalf:
166returnIEEEhalf();
167caseS_BFloat:
168returnBFloat();
169caseS_IEEEsingle:
170returnIEEEsingle();
171caseS_IEEEdouble:
172returnIEEEdouble();
173caseS_IEEEquad:
174returnIEEEquad();
175caseS_PPCDoubleDouble:
176returnPPCDoubleDouble();
177caseS_PPCDoubleDoubleLegacy:
178returnPPCDoubleDoubleLegacy();
179caseS_Float8E5M2:
180returnFloat8E5M2();
181caseS_Float8E5M2FNUZ:
182returnFloat8E5M2FNUZ();
183caseS_Float8E4M3:
184returnFloat8E4M3();
185caseS_Float8E4M3FN:
186returnFloat8E4M3FN();
187caseS_Float8E4M3FNUZ:
188returnFloat8E4M3FNUZ();
189caseS_Float8E4M3B11FNUZ:
190returnFloat8E4M3B11FNUZ();
191caseS_Float8E3M4:
192returnFloat8E3M4();
193caseS_FloatTF32:
194returnFloatTF32();
195caseS_Float8E8M0FNU:
196returnFloat8E8M0FNU();
197caseS_Float6E3M2FN:
198returnFloat6E3M2FN();
199caseS_Float6E2M3FN:
200returnFloat6E2M3FN();
201caseS_Float4E2M1FN:
202returnFloat4E2M1FN();
203caseS_x87DoubleExtended:
204returnx87DoubleExtended();
205 }
206llvm_unreachable("Unrecognised floating semantics");
207}
208
209APFloatBase::Semantics
210APFloatBase::SemanticsToEnum(constllvm::fltSemantics &Sem) {
211if (&Sem == &llvm::APFloat::IEEEhalf())
212returnS_IEEEhalf;
213elseif (&Sem == &llvm::APFloat::BFloat())
214returnS_BFloat;
215elseif (&Sem == &llvm::APFloat::IEEEsingle())
216returnS_IEEEsingle;
217elseif (&Sem == &llvm::APFloat::IEEEdouble())
218returnS_IEEEdouble;
219elseif (&Sem == &llvm::APFloat::IEEEquad())
220returnS_IEEEquad;
221elseif (&Sem == &llvm::APFloat::PPCDoubleDouble())
222returnS_PPCDoubleDouble;
223elseif (&Sem == &llvm::APFloat::PPCDoubleDoubleLegacy())
224returnS_PPCDoubleDoubleLegacy;
225elseif (&Sem == &llvm::APFloat::Float8E5M2())
226returnS_Float8E5M2;
227elseif (&Sem == &llvm::APFloat::Float8E5M2FNUZ())
228returnS_Float8E5M2FNUZ;
229elseif (&Sem == &llvm::APFloat::Float8E4M3())
230returnS_Float8E4M3;
231elseif (&Sem == &llvm::APFloat::Float8E4M3FN())
232returnS_Float8E4M3FN;
233elseif (&Sem == &llvm::APFloat::Float8E4M3FNUZ())
234returnS_Float8E4M3FNUZ;
235elseif (&Sem == &llvm::APFloat::Float8E4M3B11FNUZ())
236returnS_Float8E4M3B11FNUZ;
237elseif (&Sem == &llvm::APFloat::Float8E3M4())
238returnS_Float8E3M4;
239elseif (&Sem == &llvm::APFloat::FloatTF32())
240returnS_FloatTF32;
241elseif (&Sem == &llvm::APFloat::Float8E8M0FNU())
242returnS_Float8E8M0FNU;
243elseif (&Sem == &llvm::APFloat::Float6E3M2FN())
244returnS_Float6E3M2FN;
245elseif (&Sem == &llvm::APFloat::Float6E2M3FN())
246returnS_Float6E2M3FN;
247elseif (&Sem == &llvm::APFloat::Float4E2M1FN())
248returnS_Float4E2M1FN;
249elseif (&Sem == &llvm::APFloat::x87DoubleExtended())
250returnS_x87DoubleExtended;
251else
252llvm_unreachable("Unknown floating semantics");
253}
254
255constfltSemantics &APFloatBase::IEEEhalf() {returnsemIEEEhalf; }
256constfltSemantics &APFloatBase::BFloat() {returnsemBFloat; }
257constfltSemantics &APFloatBase::IEEEsingle() {returnsemIEEEsingle; }
258constfltSemantics &APFloatBase::IEEEdouble() {returnsemIEEEdouble; }
259constfltSemantics &APFloatBase::IEEEquad() {returnsemIEEEquad; }
260constfltSemantics &APFloatBase::PPCDoubleDouble() {
261returnsemPPCDoubleDouble;
262}
263constfltSemantics &APFloatBase::PPCDoubleDoubleLegacy() {
264returnsemPPCDoubleDoubleLegacy;
265}
266constfltSemantics &APFloatBase::Float8E5M2() {returnsemFloat8E5M2; }
267constfltSemantics &APFloatBase::Float8E5M2FNUZ() {returnsemFloat8E5M2FNUZ; }
268constfltSemantics &APFloatBase::Float8E4M3() {returnsemFloat8E4M3; }
269constfltSemantics &APFloatBase::Float8E4M3FN() {returnsemFloat8E4M3FN; }
270constfltSemantics &APFloatBase::Float8E4M3FNUZ() {returnsemFloat8E4M3FNUZ; }
271constfltSemantics &APFloatBase::Float8E4M3B11FNUZ() {
272returnsemFloat8E4M3B11FNUZ;
273}
274constfltSemantics &APFloatBase::Float8E3M4() {returnsemFloat8E3M4; }
275constfltSemantics &APFloatBase::FloatTF32() {returnsemFloatTF32; }
276constfltSemantics &APFloatBase::Float8E8M0FNU() {returnsemFloat8E8M0FNU; }
277constfltSemantics &APFloatBase::Float6E3M2FN() {returnsemFloat6E3M2FN; }
278constfltSemantics &APFloatBase::Float6E2M3FN() {returnsemFloat6E2M3FN; }
279constfltSemantics &APFloatBase::Float4E2M1FN() {returnsemFloat4E2M1FN; }
280constfltSemantics &APFloatBase::x87DoubleExtended() {
281returnsemX87DoubleExtended;
282}
283constfltSemantics &APFloatBase::Bogus() {returnsemBogus; }
284
285boolAPFloatBase::isRepresentableBy(constfltSemantics &A,
286constfltSemantics &B) {
287returnA.maxExponent <=B.maxExponent &&A.minExponent >=B.minExponent &&
288A.precision <=B.precision;
289}
290
291constexprRoundingModeAPFloatBase::rmNearestTiesToEven;
292constexprRoundingModeAPFloatBase::rmTowardPositive;
293constexprRoundingModeAPFloatBase::rmTowardNegative;
294constexprRoundingModeAPFloatBase::rmTowardZero;
295constexprRoundingModeAPFloatBase::rmNearestTiesToAway;
296
297/* A tight upper bound on number of parts required to hold the value
298 pow(5, power) is
299
300 power * 815 / (351 * integerPartWidth) + 1
301
302 However, whilst the result may require only this many parts,
303 because we are multiplying two values to get it, the
304 multiplication may require an extra part with the excess part
305 being zero (consider the trivial case of 1 * 1, tcFullMultiply
306 requires two parts to hold the single-part result). So we add an
307 extra one to guarantee enough space whilst multiplying. */
308constunsignedintmaxExponent = 16383;
309constunsignedintmaxPrecision = 113;
310constunsignedintmaxPowerOfFiveExponent =maxExponent +maxPrecision - 1;
311constunsignedintmaxPowerOfFiveParts =
312 2 +
313 ((maxPowerOfFiveExponent * 815) / (351 *APFloatBase::integerPartWidth));
314
315unsignedintAPFloatBase::semanticsPrecision(constfltSemantics &semantics) {
316return semantics.precision;
317}
318APFloatBase::ExponentType
319APFloatBase::semanticsMaxExponent(constfltSemantics &semantics) {
320return semantics.maxExponent;
321}
322APFloatBase::ExponentType
323APFloatBase::semanticsMinExponent(constfltSemantics &semantics) {
324return semantics.minExponent;
325}
326unsignedintAPFloatBase::semanticsSizeInBits(constfltSemantics &semantics) {
327return semantics.sizeInBits;
328}
329unsignedintAPFloatBase::semanticsIntSizeInBits(constfltSemantics &semantics,
330boolisSigned) {
331// The max FP value is pow(2, MaxExponent) * (1 + MaxFraction), so we need
332// at least one more bit than the MaxExponent to hold the max FP value.
333unsignedint MinBitWidth =semanticsMaxExponent(semantics) + 1;
334// Extra sign bit needed.
335if (isSigned)
336 ++MinBitWidth;
337return MinBitWidth;
338}
339
340boolAPFloatBase::semanticsHasZero(constfltSemantics &semantics) {
341return semantics.hasZero;
342}
343
344boolAPFloatBase::semanticsHasSignedRepr(constfltSemantics &semantics) {
345return semantics.hasSignedRepr;
346}
347
348boolAPFloatBase::semanticsHasInf(constfltSemantics &semantics) {
349return semantics.nonFiniteBehavior ==fltNonfiniteBehavior::IEEE754;
350}
351
352boolAPFloatBase::semanticsHasNaN(constfltSemantics &semantics) {
353return semantics.nonFiniteBehavior !=fltNonfiniteBehavior::FiniteOnly;
354}
355
356boolAPFloatBase::isRepresentableAsNormalIn(constfltSemantics &Src,
357constfltSemantics &Dst) {
358// Exponent range must be larger.
359if (Src.maxExponent >= Dst.maxExponent || Src.minExponent <= Dst.minExponent)
360returnfalse;
361
362// If the mantissa is long enough, the result value could still be denormal
363// with a larger exponent range.
364//
365// FIXME: This condition is probably not accurate but also shouldn't be a
366// practical concern with existing types.
367return Dst.precision >= Src.precision;
368}
369
370unsignedAPFloatBase::getSizeInBits(constfltSemantics &Sem) {
371return Sem.sizeInBits;
372}
373
374staticconstexprAPFloatBase::ExponentType
375exponentZero(constfltSemantics &semantics) {
376return semantics.minExponent - 1;
377}
378
379staticconstexprAPFloatBase::ExponentType
380exponentInf(constfltSemantics &semantics) {
381return semantics.maxExponent + 1;
382}
383
384staticconstexprAPFloatBase::ExponentType
385exponentNaN(constfltSemantics &semantics) {
386if (semantics.nonFiniteBehavior ==fltNonfiniteBehavior::NanOnly) {
387if (semantics.nanEncoding ==fltNanEncoding::NegativeZero)
388returnexponentZero(semantics);
389if (semantics.hasSignedRepr)
390return semantics.maxExponent;
391 }
392return semantics.maxExponent + 1;
393}
394
395/* A bunch of private, handy routines. */
396
397staticinlineErrorcreateError(constTwine &Err) {
398return make_error<StringError>(Err,inconvertibleErrorCode());
399}
400
401staticconstexprinlineunsignedintpartCountForBits(unsignedint bits) {
402return std::max(1u, (bits +APFloatBase::integerPartWidth - 1) /
403APFloatBase::integerPartWidth);
404}
405
406/* Returns 0U-9U. Return values >= 10U are not digits. */
407staticinlineunsignedint
408decDigitValue(unsignedint c)
409{
410return c -'0';
411}
412
413/* Return the value of a decimal exponent of the form
414 [+-]ddddddd.
415
416 If the exponent overflows, returns a large exponent with the
417 appropriate sign. */
418staticExpected<int>readExponent(StringRef::iterator begin,
419StringRef::iterator end) {
420bool isNegative;
421unsignedint absExponent;
422constunsignedint overlargeExponent = 24000;/* FIXME. */
423StringRef::iterator p = begin;
424
425// Treat no exponent as 0 to match binutils
426if (p == end || ((*p =='-' || *p =='+') && (p + 1) == end)) {
427return 0;
428 }
429
430 isNegative = (*p =='-');
431if (*p =='-' || *p =='+') {
432 p++;
433if (p == end)
434returncreateError("Exponent has no digits");
435 }
436
437 absExponent =decDigitValue(*p++);
438if (absExponent >= 10U)
439returncreateError("Invalid character in exponent");
440
441for (; p != end; ++p) {
442unsignedintvalue;
443
444value =decDigitValue(*p);
445if (value >= 10U)
446returncreateError("Invalid character in exponent");
447
448 absExponent = absExponent * 10U +value;
449if (absExponent >= overlargeExponent) {
450 absExponent = overlargeExponent;
451break;
452 }
453 }
454
455if (isNegative)
456return -(int) absExponent;
457else
458return (int) absExponent;
459}
460
461/* This is ugly and needs cleaning up, but I don't immediately see
462 how whilst remaining safe. */
463staticExpected<int>totalExponent(StringRef::iterator p,
464StringRef::iterator end,
465int exponentAdjustment) {
466int unsignedExponent;
467bool negative, overflow;
468int exponent = 0;
469
470if (p == end)
471returncreateError("Exponent has no digits");
472
473 negative = *p =='-';
474if (*p =='-' || *p =='+') {
475 p++;
476if (p == end)
477returncreateError("Exponent has no digits");
478 }
479
480 unsignedExponent = 0;
481 overflow =false;
482for (; p != end; ++p) {
483unsignedintvalue;
484
485value =decDigitValue(*p);
486if (value >= 10U)
487returncreateError("Invalid character in exponent");
488
489 unsignedExponent = unsignedExponent * 10 +value;
490if (unsignedExponent > 32767) {
491 overflow =true;
492break;
493 }
494 }
495
496if (exponentAdjustment > 32767 || exponentAdjustment < -32768)
497 overflow =true;
498
499if (!overflow) {
500 exponent = unsignedExponent;
501if (negative)
502 exponent = -exponent;
503 exponent += exponentAdjustment;
504if (exponent > 32767 || exponent < -32768)
505 overflow =true;
506 }
507
508if (overflow)
509 exponent = negative ? -32768: 32767;
510
511return exponent;
512}
513
514staticExpected<StringRef::iterator>
515skipLeadingZeroesAndAnyDot(StringRef::iterator begin,StringRef::iterator end,
516StringRef::iterator *dot) {
517StringRef::iterator p = begin;
518 *dot = end;
519while (p != end && *p =='0')
520 p++;
521
522if (p != end && *p =='.') {
523 *dot = p++;
524
525if (end - begin == 1)
526returncreateError("Significand has no digits");
527
528while (p != end && *p =='0')
529 p++;
530 }
531
532return p;
533}
534
535/* Given a normal decimal floating point number of the form
536
537 dddd.dddd[eE][+-]ddd
538
539 where the decimal point and exponent are optional, fill out the
540 structure D. Exponent is appropriate if the significand is
541 treated as an integer, and normalizedExponent if the significand
542 is taken to have the decimal point after a single leading
543 non-zero digit.
544
545 If the value is zero, V->firstSigDigit points to a non-digit, and
546 the return exponent is zero.
547*/
548structdecimalInfo {
549constchar *firstSigDigit;
550constchar *lastSigDigit;
551intexponent;
552intnormalizedExponent;
553};
554
555staticErrorinterpretDecimal(StringRef::iterator begin,
556StringRef::iterator end,decimalInfo *D) {
557StringRef::iterator dot = end;
558
559auto PtrOrErr =skipLeadingZeroesAndAnyDot(begin, end, &dot);
560if (!PtrOrErr)
561return PtrOrErr.takeError();
562StringRef::iterator p = *PtrOrErr;
563
564D->firstSigDigit = p;
565D->exponent = 0;
566D->normalizedExponent = 0;
567
568for (; p != end; ++p) {
569if (*p =='.') {
570if (dot != end)
571returncreateError("String contains multiple dots");
572 dot = p++;
573if (p == end)
574break;
575 }
576if (decDigitValue(*p) >= 10U)
577break;
578 }
579
580if (p != end) {
581if (*p !='e' && *p !='E')
582returncreateError("Invalid character in significand");
583if (p == begin)
584returncreateError("Significand has no digits");
585if (dot != end && p - begin == 1)
586returncreateError("Significand has no digits");
587
588/* p points to the first non-digit in the string */
589auto ExpOrErr =readExponent(p + 1, end);
590if (!ExpOrErr)
591return ExpOrErr.takeError();
592D->exponent = *ExpOrErr;
593
594/* Implied decimal point? */
595if (dot == end)
596 dot = p;
597 }
598
599/* If number is all zeroes accept any exponent. */
600if (p !=D->firstSigDigit) {
601/* Drop insignificant trailing zeroes. */
602if (p != begin) {
603do
604do
605 p--;
606while (p != begin && *p =='0');
607while (p != begin && *p =='.');
608 }
609
610/* Adjust the exponents for any decimal point. */
611D->exponent +=static_cast<APFloat::ExponentType>((dot - p) - (dot > p));
612D->normalizedExponent = (D->exponent +
613static_cast<APFloat::ExponentType>((p -D->firstSigDigit)
614 - (dot >D->firstSigDigit && dot < p)));
615 }
616
617D->lastSigDigit = p;
618returnError::success();
619}
620
621/* Return the trailing fraction of a hexadecimal number.
622 DIGITVALUE is the first hex digit of the fraction, P points to
623 the next digit. */
624staticExpected<lostFraction>
625trailingHexadecimalFraction(StringRef::iterator p,StringRef::iterator end,
626unsignedint digitValue) {
627unsignedint hexDigit;
628
629/* If the first trailing digit isn't 0 or 8 we can work out the
630 fraction immediately. */
631if (digitValue > 8)
632returnlfMoreThanHalf;
633elseif (digitValue < 8 && digitValue > 0)
634returnlfLessThanHalf;
635
636// Otherwise we need to find the first non-zero digit.
637while (p != end && (*p =='0' || *p =='.'))
638 p++;
639
640if (p == end)
641returncreateError("Invalid trailing hexadecimal fraction!");
642
643 hexDigit = hexDigitValue(*p);
644
645/* If we ran off the end it is exactly zero or one-half, otherwise
646 a little more. */
647if (hexDigit == UINT_MAX)
648return digitValue == 0 ?lfExactlyZero:lfExactlyHalf;
649else
650return digitValue == 0 ?lfLessThanHalf:lfMoreThanHalf;
651}
652
653/* Return the fraction lost were a bignum truncated losing the least
654 significant BITS bits. */
655staticlostFraction
656lostFractionThroughTruncation(constAPFloatBase::integerPart *parts,
657unsignedint partCount,
658unsignedint bits)
659{
660unsignedint lsb;
661
662 lsb =APInt::tcLSB(parts, partCount);
663
664/* Note this is guaranteed true if bits == 0, or LSB == UINT_MAX. */
665if (bits <= lsb)
666returnlfExactlyZero;
667if (bits == lsb + 1)
668returnlfExactlyHalf;
669if (bits <= partCount *APFloatBase::integerPartWidth &&
670APInt::tcExtractBit(parts, bits - 1))
671returnlfMoreThanHalf;
672
673returnlfLessThanHalf;
674}
675
676/* Shift DST right BITS bits noting lost fraction. */
677staticlostFraction
678shiftRight(APFloatBase::integerPart *dst,unsignedint parts,unsignedint bits)
679{
680lostFraction lost_fraction;
681
682 lost_fraction =lostFractionThroughTruncation(dst, parts, bits);
683
684APInt::tcShiftRight(dst, parts, bits);
685
686return lost_fraction;
687}
688
689/* Combine the effect of two lost fractions. */
690staticlostFraction
691combineLostFractions(lostFraction moreSignificant,
692lostFraction lessSignificant)
693{
694if (lessSignificant !=lfExactlyZero) {
695if (moreSignificant ==lfExactlyZero)
696 moreSignificant =lfLessThanHalf;
697elseif (moreSignificant ==lfExactlyHalf)
698 moreSignificant =lfMoreThanHalf;
699 }
700
701return moreSignificant;
702}
703
704/* The error from the true value, in half-ulps, on multiplying two
705 floating point numbers, which differ from the value they
706 approximate by at most HUE1 and HUE2 half-ulps, is strictly less
707 than the returned value.
708
709 See "How to Read Floating Point Numbers Accurately" by William D
710 Clinger. */
711staticunsignedint
712HUerrBound(bool inexactMultiply,unsignedint HUerr1,unsignedint HUerr2)
713{
714assert(HUerr1 < 2 || HUerr2 < 2 || (HUerr1 + HUerr2 < 8));
715
716if (HUerr1 + HUerr2 == 0)
717return inexactMultiply * 2;/* <= inexactMultiply half-ulps. */
718else
719return inexactMultiply + 2 * (HUerr1 + HUerr2);
720}
721
722/* The number of ulps from the boundary (zero, or half if ISNEAREST)
723 when the least significant BITS are truncated. BITS cannot be
724 zero. */
725staticAPFloatBase::integerPart
726ulpsFromBoundary(constAPFloatBase::integerPart *parts,unsignedint bits,
727bool isNearest) {
728unsignedintcount, partBits;
729APFloatBase::integerPart part, boundary;
730
731assert(bits != 0);
732
733 bits--;
734count = bits /APFloatBase::integerPartWidth;
735 partBits = bits %APFloatBase::integerPartWidth + 1;
736
737 part = parts[count] & (~(APFloatBase::integerPart) 0 >> (APFloatBase::integerPartWidth - partBits));
738
739if (isNearest)
740 boundary = (APFloatBase::integerPart) 1 << (partBits - 1);
741else
742 boundary = 0;
743
744if (count == 0) {
745if (part - boundary <= boundary - part)
746return part - boundary;
747else
748return boundary - part;
749 }
750
751if (part == boundary) {
752while (--count)
753if (parts[count])
754return ~(APFloatBase::integerPart) 0;/* A lot. */
755
756return parts[0];
757 }elseif (part == boundary - 1) {
758while (--count)
759if (~parts[count])
760return ~(APFloatBase::integerPart) 0;/* A lot. */
761
762return -parts[0];
763 }
764
765return ~(APFloatBase::integerPart) 0;/* A lot. */
766}
767
768/* Place pow(5, power) in DST, and return the number of parts used.
769 DST must be at least one part larger than size of the answer. */
770staticunsignedint
771powerOf5(APFloatBase::integerPart *dst,unsignedint power) {
772staticconstAPFloatBase::integerPart firstEightPowers[] = { 1, 5, 25, 125, 625, 3125, 15625, 78125 };
773APFloatBase::integerPart pow5s[maxPowerOfFiveParts * 2 + 5];
774 pow5s[0] = 78125 * 5;
775
776unsignedint partsCount = 1;
777APFloatBase::integerPart scratch[maxPowerOfFiveParts], *p1, *p2, *pow5;
778unsignedint result;
779assert(power <=maxExponent);
780
781 p1 = dst;
782 p2 = scratch;
783
784 *p1 = firstEightPowers[power & 7];
785 power >>= 3;
786
787 result = 1;
788 pow5 = pow5s;
789
790for (unsignedint n = 0; power; power >>= 1, n++) {
791/* Calculate pow(5,pow(2,n+3)) if we haven't yet. */
792if (n != 0) {
793APInt::tcFullMultiply(pow5, pow5 - partsCount, pow5 - partsCount,
794 partsCount, partsCount);
795 partsCount *= 2;
796if (pow5[partsCount - 1] == 0)
797 partsCount--;
798 }
799
800if (power & 1) {
801APFloatBase::integerPart *tmp;
802
803APInt::tcFullMultiply(p2, p1, pow5, result, partsCount);
804 result += partsCount;
805if (p2[result - 1] == 0)
806 result--;
807
808/* Now result is in p1 with partsCount parts and p2 is scratch
809 space. */
810 tmp = p1;
811 p1 = p2;
812 p2 = tmp;
813 }
814
815 pow5 += partsCount;
816 }
817
818if (p1 != dst)
819APInt::tcAssign(dst, p1, result);
820
821return result;
822}
823
824/* Zero at the end to avoid modular arithmetic when adding one; used
825 when rounding up during hexadecimal output. */
826staticconstcharhexDigitsLower[] ="0123456789abcdef0";
827staticconstcharhexDigitsUpper[] ="0123456789ABCDEF0";
828staticconstcharinfinityL[] ="infinity";
829staticconstcharinfinityU[] ="INFINITY";
830staticconstcharNaNL[] ="nan";
831staticconstcharNaNU[] ="NAN";
832
833/* Write out an integerPart in hexadecimal, starting with the most
834 significant nibble. Write out exactly COUNT hexdigits, return
835 COUNT. */
836staticunsignedint
837partAsHex (char *dst,APFloatBase::integerPart part,unsignedintcount,
838constchar *hexDigitChars)
839{
840unsignedint result =count;
841
842assert(count != 0 &&count <=APFloatBase::integerPartWidth / 4);
843
844 part >>= (APFloatBase::integerPartWidth - 4 *count);
845while (count--) {
846 dst[count] = hexDigitChars[part & 0xf];
847 part >>= 4;
848 }
849
850return result;
851}
852
853/* Write out an unsigned decimal integer. */
854staticchar *
855writeUnsignedDecimal (char *dst,unsignedint n)
856{
857char buff[40], *p;
858
859 p = buff;
860do
861 *p++ ='0' + n % 10;
862while (n /= 10);
863
864do
865 *dst++ = *--p;
866while (p != buff);
867
868return dst;
869}
870
871/* Write out a signed decimal integer. */
872staticchar *
873writeSignedDecimal (char *dst,intvalue)
874{
875if (value < 0) {
876 *dst++ ='-';
877 dst =writeUnsignedDecimal(dst, -(unsigned)value);
878 }else
879 dst =writeUnsignedDecimal(dst,value);
880
881return dst;
882}
883
884namespacedetail {
885/* Constructors. */
886void IEEEFloat::initialize(constfltSemantics *ourSemantics) {
887unsignedintcount;
888
889 semantics = ourSemantics;
890count = partCount();
891if (count > 1)
892 significand.parts =newintegerPart[count];
893}
894
895void IEEEFloat::freeSignificand() {
896if (needsCleanup())
897delete [] significand.parts;
898}
899
900void IEEEFloat::assign(const IEEEFloat &rhs) {
901assert(semantics == rhs.semantics);
902
903 sign = rhs.sign;
904 category = rhs.category;
905 exponent = rhs.exponent;
906if (isFiniteNonZero() || category ==fcNaN)
907 copySignificand(rhs);
908}
909
910void IEEEFloat::copySignificand(const IEEEFloat &rhs) {
911assert(isFiniteNonZero() || category ==fcNaN);
912assert(rhs.partCount() >= partCount());
913
914APInt::tcAssign(significandParts(), rhs.significandParts(),
915 partCount());
916}
917
918/* Make this number a NaN, with an arbitrary but deterministic value
919 for the significand. If double or longer, this is a signalling NaN,
920 which may not be ideal. If float, this is QNaN(0). */
921voidIEEEFloat::makeNaN(bool SNaN,bool Negative,constAPInt *fill) {
922if (semantics->nonFiniteBehavior ==fltNonfiniteBehavior::FiniteOnly)
923llvm_unreachable("This floating point format does not support NaN");
924
925if (Negative && !semantics->hasSignedRepr)
926llvm_unreachable(
927"This floating point format does not support signed values");
928
929 category =fcNaN;
930 sign = Negative;
931 exponent = exponentNaN();
932
933integerPart *significand = significandParts();
934unsigned numParts = partCount();
935
936APInt fill_storage;
937if (semantics->nonFiniteBehavior ==fltNonfiniteBehavior::NanOnly) {
938// Finite-only types do not distinguish signalling and quiet NaN, so
939// make them all signalling.
940 SNaN =false;
941if (semantics->nanEncoding ==fltNanEncoding::NegativeZero) {
942 sign =true;
943 fill_storage =APInt::getZero(semantics->precision - 1);
944 }else {
945 fill_storage =APInt::getAllOnes(semantics->precision - 1);
946 }
947 fill = &fill_storage;
948 }
949
950// Set the significand bits to the fill.
951if (!fill || fill->getNumWords() < numParts)
952APInt::tcSet(significand, 0, numParts);
953if (fill) {
954APInt::tcAssign(significand, fill->getRawData(),
955 std::min(fill->getNumWords(), numParts));
956
957// Zero out the excess bits of the significand.
958unsigned bitsToPreserve = semantics->precision - 1;
959unsigned part = bitsToPreserve / 64;
960 bitsToPreserve %= 64;
961 significand[part] &= ((1ULL << bitsToPreserve) - 1);
962for (part++; part != numParts; ++part)
963 significand[part] = 0;
964 }
965
966unsigned QNaNBit =
967 (semantics->precision >= 2) ? (semantics->precision - 2) : 0;
968
969if (SNaN) {
970// We always have to clear the QNaN bit to make it an SNaN.
971APInt::tcClearBit(significand, QNaNBit);
972
973// If there are no bits set in the payload, we have to set
974// *something* to make it a NaN instead of an infinity;
975// conventionally, this is the next bit down from the QNaN bit.
976if (APInt::tcIsZero(significand, numParts))
977APInt::tcSetBit(significand, QNaNBit - 1);
978 }elseif (semantics->nanEncoding ==fltNanEncoding::NegativeZero) {
979// The only NaN is a quiet NaN, and it has no bits sets in the significand.
980// Do nothing.
981 }else {
982// We always have to set the QNaN bit to make it a QNaN.
983APInt::tcSetBit(significand, QNaNBit);
984 }
985
986// For x87 extended precision, we want to make a NaN, not a
987// pseudo-NaN. Maybe we should expose the ability to make
988// pseudo-NaNs?
989if (semantics == &semX87DoubleExtended)
990APInt::tcSetBit(significand, QNaNBit + 1);
991}
992
993IEEEFloat &IEEEFloat::operator=(constIEEEFloat &rhs) {
994if (this != &rhs) {
995if (semantics != rhs.semantics) {
996 freeSignificand();
997 initialize(rhs.semantics);
998 }
999 assign(rhs);
1000 }
1001
1002return *this;
1003}
1004
1005IEEEFloat &IEEEFloat::operator=(IEEEFloat &&rhs) {
1006 freeSignificand();
1007
1008 semantics = rhs.semantics;
1009 significand = rhs.significand;
1010 exponent = rhs.exponent;
1011 category = rhs.category;
1012 sign = rhs.sign;
1013
1014 rhs.semantics = &semBogus;
1015return *this;
1016}
1017
1018boolIEEEFloat::isDenormal() const{
1019returnisFiniteNonZero() && (exponent == semantics->minExponent) &&
1020 (APInt::tcExtractBit(significandParts(),
1021 semantics->precision - 1) == 0);
1022}
1023
1024boolIEEEFloat::isSmallest() const{
1025// The smallest number by magnitude in our format will be the smallest
1026// denormal, i.e. the floating point number with exponent being minimum
1027// exponent and significand bitwise equal to 1 (i.e. with MSB equal to 0).
1028returnisFiniteNonZero() && exponent == semantics->minExponent &&
1029 significandMSB() == 0;
1030}
1031
1032boolIEEEFloat::isSmallestNormalized() const{
1033returngetCategory() ==fcNormal && exponent == semantics->minExponent &&
1034 isSignificandAllZerosExceptMSB();
1035}
1036
1037unsignedint IEEEFloat::getNumHighBits() const{
1038constunsignedint PartCount =partCountForBits(semantics->precision);
1039constunsignedint Bits = PartCount *integerPartWidth;
1040
1041// Compute how many bits are used in the final word.
1042// When precision is just 1, it represents the 'Pth'
1043// Precision bit and not the actual significand bit.
1044constunsignedint NumHighBits = (semantics->precision > 1)
1045 ? (Bits - semantics->precision + 1)
1046 : (Bits - semantics->precision);
1047return NumHighBits;
1048}
1049
1050bool IEEEFloat::isSignificandAllOnes() const{
1051// Test if the significand excluding the integral bit is all ones. This allows
1052// us to test for binade boundaries.
1053constintegerPart *Parts = significandParts();
1054constunsigned PartCount =partCountForBits(semantics->precision);
1055for (unsigned i = 0; i < PartCount - 1; i++)
1056if (~Parts[i])
1057returnfalse;
1058
1059// Set the unused high bits to all ones when we compare.
1060constunsigned NumHighBits = getNumHighBits();
1061assert(NumHighBits <= integerPartWidth && NumHighBits > 0 &&
1062"Can not have more high bits to fill than integerPartWidth");
1063constintegerPart HighBitFill =
1064 ~integerPart(0) << (integerPartWidth - NumHighBits);
1065if ((semantics->precision <= 1) || (~(Parts[PartCount - 1] | HighBitFill)))
1066returnfalse;
1067
1068returntrue;
1069}
1070
1071bool IEEEFloat::isSignificandAllOnesExceptLSB() const{
1072// Test if the significand excluding the integral bit is all ones except for
1073// the least significant bit.
1074constintegerPart *Parts = significandParts();
1075
1076if (Parts[0] & 1)
1077returnfalse;
1078
1079constunsigned PartCount =partCountForBits(semantics->precision);
1080for (unsigned i = 0; i < PartCount - 1; i++) {
1081if (~Parts[i] & ~unsigned{!i})
1082returnfalse;
1083 }
1084
1085// Set the unused high bits to all ones when we compare.
1086constunsigned NumHighBits = getNumHighBits();
1087assert(NumHighBits <= integerPartWidth && NumHighBits > 0 &&
1088"Can not have more high bits to fill than integerPartWidth");
1089constintegerPart HighBitFill = ~integerPart(0)
1090 << (integerPartWidth - NumHighBits);
1091if (~(Parts[PartCount - 1] | HighBitFill | 0x1))
1092returnfalse;
1093
1094returntrue;
1095}
1096
1097bool IEEEFloat::isSignificandAllZeros() const{
1098// Test if the significand excluding the integral bit is all zeros. This
1099// allows us to test for binade boundaries.
1100constintegerPart *Parts = significandParts();
1101constunsigned PartCount =partCountForBits(semantics->precision);
1102
1103for (unsigned i = 0; i < PartCount - 1; i++)
1104if (Parts[i])
1105returnfalse;
1106
1107// Compute how many bits are used in the final word.
1108constunsigned NumHighBits = getNumHighBits();
1109assert(NumHighBits <integerPartWidth &&"Can not have more high bits to "
1110"clear than integerPartWidth");
1111constintegerPart HighBitMask = ~integerPart(0) >> NumHighBits;
1112
1113if ((semantics->precision > 1) && (Parts[PartCount - 1] & HighBitMask))
1114returnfalse;
1115
1116returntrue;
1117}
1118
1119bool IEEEFloat::isSignificandAllZerosExceptMSB() const{
1120constintegerPart *Parts = significandParts();
1121constunsigned PartCount =partCountForBits(semantics->precision);
1122
1123for (unsigned i = 0; i < PartCount - 1; i++) {
1124if (Parts[i])
1125returnfalse;
1126 }
1127
1128constunsigned NumHighBits = getNumHighBits();
1129constintegerPart MSBMask =integerPart(1)
1130 << (integerPartWidth - NumHighBits);
1131return ((semantics->precision <= 1) || (Parts[PartCount - 1] == MSBMask));
1132}
1133
1134boolIEEEFloat::isLargest() const{
1135bool IsMaxExp =isFiniteNonZero() && exponent == semantics->maxExponent;
1136if (semantics->nonFiniteBehavior ==fltNonfiniteBehavior::NanOnly &&
1137 semantics->nanEncoding ==fltNanEncoding::AllOnes) {
1138// The largest number by magnitude in our format will be the floating point
1139// number with maximum exponent and with significand that is all ones except
1140// the LSB.
1141return (IsMaxExp &&APFloat::hasSignificand(*semantics))
1142 ? isSignificandAllOnesExceptLSB()
1143 : IsMaxExp;
1144 }else {
1145// The largest number by magnitude in our format will be the floating point
1146// number with maximum exponent and with significand that is all ones.
1147return IsMaxExp && isSignificandAllOnes();
1148 }
1149}
1150
1151boolIEEEFloat::isInteger() const{
1152// This could be made more efficient; I'm going for obviously correct.
1153if (!isFinite())returnfalse;
1154IEEEFloattruncated = *this;
1155truncated.roundToIntegral(rmTowardZero);
1156returncompare(truncated) ==cmpEqual;
1157}
1158
1159boolIEEEFloat::bitwiseIsEqual(constIEEEFloat &rhs) const{
1160if (this == &rhs)
1161returntrue;
1162if (semantics != rhs.semantics ||
1163 category != rhs.category ||
1164 sign != rhs.sign)
1165returnfalse;
1166if (category==fcZero || category==fcInfinity)
1167returntrue;
1168
1169if (isFiniteNonZero() && exponent != rhs.exponent)
1170returnfalse;
1171
1172return std::equal(significandParts(), significandParts() + partCount(),
1173 rhs.significandParts());
1174}
1175
1176IEEEFloat::IEEEFloat(constfltSemantics &ourSemantics,integerPartvalue) {
1177 initialize(&ourSemantics);
1178 sign = 0;
1179 category =fcNormal;
1180 zeroSignificand();
1181 exponent = ourSemantics.precision - 1;
1182 significandParts()[0] =value;
1183 normalize(rmNearestTiesToEven,lfExactlyZero);
1184}
1185
1186IEEEFloat::IEEEFloat(constfltSemantics &ourSemantics) {
1187 initialize(&ourSemantics);
1188// The Float8E8MOFNU format does not have a representation
1189// for zero. So, use the closest representation instead.
1190// Moreover, the all-zero encoding represents a valid
1191// normal value (which is the smallestNormalized here).
1192// Hence, we call makeSmallestNormalized (where category is
1193// 'fcNormal') instead of makeZero (where category is 'fcZero').
1194 ourSemantics.hasZero ?makeZero(false) :makeSmallestNormalized(false);
1195}
1196
1197// Delegate to the previous constructor, because later copy constructor may
1198// actually inspects category, which can't be garbage.
1199IEEEFloat::IEEEFloat(constfltSemantics &ourSemantics,uninitializedTag tag)
1200 :IEEEFloat(ourSemantics) {}
1201
1202IEEEFloat::IEEEFloat(constIEEEFloat &rhs) {
1203 initialize(rhs.semantics);
1204 assign(rhs);
1205}
1206
1207IEEEFloat::IEEEFloat(IEEEFloat &&rhs) : semantics(&semBogus) {
1208 *this = std::move(rhs);
1209}
1210
1211IEEEFloat::~IEEEFloat() { freeSignificand(); }
1212
1213unsignedint IEEEFloat::partCount() const{
1214returnpartCountForBits(semantics->precision + 1);
1215}
1216
1217constAPFloat::integerPart *IEEEFloat::significandParts() const{
1218returnconst_cast<IEEEFloat *>(this)->significandParts();
1219}
1220
1221APFloat::integerPart *IEEEFloat::significandParts() {
1222if (partCount() > 1)
1223return significand.parts;
1224else
1225return &significand.part;
1226}
1227
1228void IEEEFloat::zeroSignificand() {
1229APInt::tcSet(significandParts(), 0, partCount());
1230}
1231
1232/* Increment an fcNormal floating point number's significand. */
1233void IEEEFloat::incrementSignificand() {
1234integerPart carry;
1235
1236 carry =APInt::tcIncrement(significandParts(), partCount());
1237
1238/* Our callers should never cause us to overflow. */
1239assert(carry == 0);
1240 (void)carry;
1241}
1242
1243/* Add the significand of the RHS. Returns the carry flag. */
1244APFloat::integerPart IEEEFloat::addSignificand(const IEEEFloat &rhs) {
1245integerPart *parts;
1246
1247 parts = significandParts();
1248
1249assert(semantics == rhs.semantics);
1250assert(exponent == rhs.exponent);
1251
1252returnAPInt::tcAdd(parts, rhs.significandParts(), 0, partCount());
1253}
1254
1255/* Subtract the significand of the RHS with a borrow flag. Returns
1256 the borrow flag. */
1257APFloat::integerPart IEEEFloat::subtractSignificand(const IEEEFloat &rhs,
1258integerPart borrow) {
1259integerPart *parts;
1260
1261 parts = significandParts();
1262
1263assert(semantics == rhs.semantics);
1264assert(exponent == rhs.exponent);
1265
1266returnAPInt::tcSubtract(parts, rhs.significandParts(), borrow,
1267 partCount());
1268}
1269
1270/* Multiply the significand of the RHS. If ADDEND is non-NULL, add it
1271 on to the full-precision result of the multiplication. Returns the
1272 lost fraction. */
1273lostFraction IEEEFloat::multiplySignificand(const IEEEFloat &rhs,
1274 IEEEFloat addend,
1275bool ignoreAddend) {
1276unsignedint omsb;// One, not zero, based MSB.
1277unsignedint partsCount, newPartsCount, precision;
1278integerPart *lhsSignificand;
1279integerPart scratch[4];
1280integerPart *fullSignificand;
1281lostFraction lost_fraction;
1282boolignored;
1283
1284assert(semantics == rhs.semantics);
1285
1286 precision = semantics->precision;
1287
1288// Allocate space for twice as many bits as the original significand, plus one
1289// extra bit for the addition to overflow into.
1290 newPartsCount =partCountForBits(precision * 2 + 1);
1291
1292if (newPartsCount > 4)
1293 fullSignificand =newintegerPart[newPartsCount];
1294else
1295 fullSignificand = scratch;
1296
1297 lhsSignificand = significandParts();
1298 partsCount = partCount();
1299
1300APInt::tcFullMultiply(fullSignificand, lhsSignificand,
1301 rhs.significandParts(), partsCount, partsCount);
1302
1303 lost_fraction =lfExactlyZero;
1304 omsb =APInt::tcMSB(fullSignificand, newPartsCount) + 1;
1305 exponent += rhs.exponent;
1306
1307// Assume the operands involved in the multiplication are single-precision
1308// FP, and the two multiplicants are:
1309// *this = a23 . a22 ... a0 * 2^e1
1310// rhs = b23 . b22 ... b0 * 2^e2
1311// the result of multiplication is:
1312// *this = c48 c47 c46 . c45 ... c0 * 2^(e1+e2)
1313// Note that there are three significant bits at the left-hand side of the
1314// radix point: two for the multiplication, and an overflow bit for the
1315// addition (that will always be zero at this point). Move the radix point
1316// toward left by two bits, and adjust exponent accordingly.
1317 exponent += 2;
1318
1319if (!ignoreAddend && addend.isNonZero()) {
1320// The intermediate result of the multiplication has "2 * precision"
1321// signicant bit; adjust the addend to be consistent with mul result.
1322//
1323 Significand savedSignificand = significand;
1324constfltSemantics *savedSemantics = semantics;
1325fltSemantics extendedSemantics;
1326opStatusstatus;
1327unsignedint extendedPrecision;
1328
1329// Normalize our MSB to one below the top bit to allow for overflow.
1330 extendedPrecision = 2 * precision + 1;
1331if (omsb != extendedPrecision - 1) {
1332assert(extendedPrecision > omsb);
1333APInt::tcShiftLeft(fullSignificand, newPartsCount,
1334 (extendedPrecision - 1) - omsb);
1335 exponent -= (extendedPrecision - 1) - omsb;
1336 }
1337
1338/* Create new semantics. */
1339 extendedSemantics = *semantics;
1340 extendedSemantics.precision = extendedPrecision;
1341
1342if (newPartsCount == 1)
1343 significand.part = fullSignificand[0];
1344else
1345 significand.parts = fullSignificand;
1346 semantics = &extendedSemantics;
1347
1348// Make a copy so we can convert it to the extended semantics.
1349// Note that we cannot convert the addend directly, as the extendedSemantics
1350// is a local variable (which we take a reference to).
1351IEEEFloat extendedAddend(addend);
1352status = extendedAddend.convert(extendedSemantics,APFloat::rmTowardZero,
1353 &ignored);
1354assert(status ==APFloat::opOK);
1355 (void)status;
1356
1357// Shift the significand of the addend right by one bit. This guarantees
1358// that the high bit of the significand is zero (same as fullSignificand),
1359// so the addition will overflow (if it does overflow at all) into the top bit.
1360 lost_fraction = extendedAddend.shiftSignificandRight(1);
1361assert(lost_fraction ==lfExactlyZero &&
1362"Lost precision while shifting addend for fused-multiply-add.");
1363
1364 lost_fraction = addOrSubtractSignificand(extendedAddend,false);
1365
1366/* Restore our state. */
1367if (newPartsCount == 1)
1368 fullSignificand[0] = significand.part;
1369 significand = savedSignificand;
1370 semantics = savedSemantics;
1371
1372 omsb =APInt::tcMSB(fullSignificand, newPartsCount) + 1;
1373 }
1374
1375// Convert the result having "2 * precision" significant-bits back to the one
1376// having "precision" significant-bits. First, move the radix point from
1377// poision "2*precision - 1" to "precision - 1". The exponent need to be
1378// adjusted by "2*precision - 1" - "precision - 1" = "precision".
1379 exponent -= precision + 1;
1380
1381// In case MSB resides at the left-hand side of radix point, shift the
1382// mantissa right by some amount to make sure the MSB reside right before
1383// the radix point (i.e. "MSB . rest-significant-bits").
1384//
1385// Note that the result is not normalized when "omsb < precision". So, the
1386// caller needs to call IEEEFloat::normalize() if normalized value is
1387// expected.
1388if (omsb > precision) {
1389unsignedint bits, significantParts;
1390lostFraction lf;
1391
1392 bits = omsb - precision;
1393 significantParts =partCountForBits(omsb);
1394 lf =shiftRight(fullSignificand, significantParts, bits);
1395 lost_fraction =combineLostFractions(lf, lost_fraction);
1396 exponent += bits;
1397 }
1398
1399APInt::tcAssign(lhsSignificand, fullSignificand, partsCount);
1400
1401if (newPartsCount > 4)
1402delete [] fullSignificand;
1403
1404return lost_fraction;
1405}
1406
1407lostFraction IEEEFloat::multiplySignificand(const IEEEFloat &rhs) {
1408// When the given semantics has zero, the addend here is a zero.
1409// i.e . it belongs to the 'fcZero' category.
1410// But when the semantics does not support zero, we need to
1411// explicitly convey that this addend should be ignored
1412// for multiplication.
1413return multiplySignificand(rhs,IEEEFloat(*semantics), !semantics->hasZero);
1414}
1415
1416/* Multiply the significands of LHS and RHS to DST. */
1417lostFraction IEEEFloat::divideSignificand(const IEEEFloat &rhs) {
1418unsignedint bit, i, partsCount;
1419constintegerPart *rhsSignificand;
1420integerPart *lhsSignificand, *dividend, *divisor;
1421integerPart scratch[4];
1422lostFraction lost_fraction;
1423
1424assert(semantics == rhs.semantics);
1425
1426 lhsSignificand = significandParts();
1427 rhsSignificand = rhs.significandParts();
1428 partsCount = partCount();
1429
1430if (partsCount > 2)
1431 dividend =newintegerPart[partsCount * 2];
1432else
1433 dividend = scratch;
1434
1435 divisor = dividend + partsCount;
1436
1437/* Copy the dividend and divisor as they will be modified in-place. */
1438for (i = 0; i < partsCount; i++) {
1439 dividend[i] = lhsSignificand[i];
1440 divisor[i] = rhsSignificand[i];
1441 lhsSignificand[i] = 0;
1442 }
1443
1444 exponent -= rhs.exponent;
1445
1446unsignedint precision = semantics->precision;
1447
1448/* Normalize the divisor. */
1449 bit = precision -APInt::tcMSB(divisor, partsCount) - 1;
1450if (bit) {
1451 exponent += bit;
1452APInt::tcShiftLeft(divisor, partsCount, bit);
1453 }
1454
1455/* Normalize the dividend. */
1456 bit = precision -APInt::tcMSB(dividend, partsCount) - 1;
1457if (bit) {
1458 exponent -= bit;
1459APInt::tcShiftLeft(dividend, partsCount, bit);
1460 }
1461
1462/* Ensure the dividend >= divisor initially for the loop below.
1463 Incidentally, this means that the division loop below is
1464 guaranteed to set the integer bit to one. */
1465if (APInt::tcCompare(dividend, divisor, partsCount) < 0) {
1466 exponent--;
1467APInt::tcShiftLeft(dividend, partsCount, 1);
1468assert(APInt::tcCompare(dividend, divisor, partsCount) >= 0);
1469 }
1470
1471/* Long division. */
1472for (bit = precision; bit; bit -= 1) {
1473if (APInt::tcCompare(dividend, divisor, partsCount) >= 0) {
1474APInt::tcSubtract(dividend, divisor, 0, partsCount);
1475APInt::tcSetBit(lhsSignificand, bit - 1);
1476 }
1477
1478APInt::tcShiftLeft(dividend, partsCount, 1);
1479 }
1480
1481/* Figure out the lost fraction. */
1482int cmp =APInt::tcCompare(dividend, divisor, partsCount);
1483
1484if (cmp > 0)
1485 lost_fraction =lfMoreThanHalf;
1486elseif (cmp == 0)
1487 lost_fraction =lfExactlyHalf;
1488elseif (APInt::tcIsZero(dividend, partsCount))
1489 lost_fraction =lfExactlyZero;
1490else
1491 lost_fraction =lfLessThanHalf;
1492
1493if (partsCount > 2)
1494delete [] dividend;
1495
1496return lost_fraction;
1497}
1498
1499unsignedint IEEEFloat::significandMSB() const{
1500returnAPInt::tcMSB(significandParts(), partCount());
1501}
1502
1503unsignedint IEEEFloat::significandLSB() const{
1504returnAPInt::tcLSB(significandParts(), partCount());
1505}
1506
1507/* Note that a zero result is NOT normalized to fcZero. */
1508lostFraction IEEEFloat::shiftSignificandRight(unsignedint bits) {
1509/* Our exponent should not overflow. */
1510assert((ExponentType) (exponent + bits) >= exponent);
1511
1512 exponent += bits;
1513
1514returnshiftRight(significandParts(), partCount(), bits);
1515}
1516
1517/* Shift the significand left BITS bits, subtract BITS from its exponent. */
1518void IEEEFloat::shiftSignificandLeft(unsignedint bits) {
1519assert(bits < semantics->precision ||
1520 (semantics->precision == 1 && bits <= 1));
1521
1522if (bits) {
1523unsignedint partsCount = partCount();
1524
1525APInt::tcShiftLeft(significandParts(), partsCount, bits);
1526 exponent -= bits;
1527
1528assert(!APInt::tcIsZero(significandParts(), partsCount));
1529 }
1530}
1531
1532APFloat::cmpResultIEEEFloat::compareAbsoluteValue(constIEEEFloat &rhs) const{
1533intcompare;
1534
1535assert(semantics == rhs.semantics);
1536assert(isFiniteNonZero());
1537assert(rhs.isFiniteNonZero());
1538
1539compare = exponent - rhs.exponent;
1540
1541/* If exponents are equal, do an unsigned bignum comparison of the
1542 significands. */
1543if (compare == 0)
1544compare =APInt::tcCompare(significandParts(), rhs.significandParts(),
1545 partCount());
1546
1547if (compare > 0)
1548returncmpGreaterThan;
1549elseif (compare < 0)
1550returncmpLessThan;
1551else
1552returncmpEqual;
1553}
1554
1555/* Set the least significant BITS bits of a bignum, clear the
1556 rest. */
1557staticvoidtcSetLeastSignificantBits(APInt::WordType *dst,unsigned parts,
1558unsigned bits) {
1559unsigned i = 0;
1560while (bits >APInt::APINT_BITS_PER_WORD) {
1561 dst[i++] = ~(APInt::WordType)0;
1562 bits -=APInt::APINT_BITS_PER_WORD;
1563 }
1564
1565if (bits)
1566 dst[i++] = ~(APInt::WordType)0 >> (APInt::APINT_BITS_PER_WORD - bits);
1567
1568while (i < parts)
1569 dst[i++] = 0;
1570}
1571
1572/* Handle overflow. Sign is preserved. We either become infinity or
1573 the largest finite number. */
1574APFloat::opStatus IEEEFloat::handleOverflow(roundingMode rounding_mode) {
1575if (semantics->nonFiniteBehavior !=fltNonfiniteBehavior::FiniteOnly) {
1576/* Infinity? */
1577if (rounding_mode ==rmNearestTiesToEven ||
1578 rounding_mode ==rmNearestTiesToAway ||
1579 (rounding_mode ==rmTowardPositive && !sign) ||
1580 (rounding_mode ==rmTowardNegative && sign)) {
1581if (semantics->nonFiniteBehavior ==fltNonfiniteBehavior::NanOnly)
1582makeNaN(false, sign);
1583else
1584 category =fcInfinity;
1585returnstatic_cast<opStatus>(opOverflow |opInexact);
1586 }
1587 }
1588
1589/* Otherwise we become the largest finite number. */
1590 category =fcNormal;
1591 exponent = semantics->maxExponent;
1592tcSetLeastSignificantBits(significandParts(), partCount(),
1593 semantics->precision);
1594if (semantics->nonFiniteBehavior ==fltNonfiniteBehavior::NanOnly &&
1595 semantics->nanEncoding ==fltNanEncoding::AllOnes)
1596APInt::tcClearBit(significandParts(), 0);
1597
1598returnopInexact;
1599}
1600
1601/* Returns TRUE if, when truncating the current number, with BIT the
1602 new LSB, with the given lost fraction and rounding mode, the result
1603 would need to be rounded away from zero (i.e., by increasing the
1604 signficand). This routine must work for fcZero of both signs, and
1605 fcNormal numbers. */
1606bool IEEEFloat::roundAwayFromZero(roundingMode rounding_mode,
1607lostFraction lost_fraction,
1608unsignedint bit) const{
1609/* NaNs and infinities should not have lost fractions. */
1610assert(isFiniteNonZero() || category ==fcZero);
1611
1612/* Current callers never pass this so we don't handle it. */
1613assert(lost_fraction !=lfExactlyZero);
1614
1615switch (rounding_mode) {
1616casermNearestTiesToAway:
1617return lost_fraction ==lfExactlyHalf || lost_fraction ==lfMoreThanHalf;
1618
1619casermNearestTiesToEven:
1620if (lost_fraction ==lfMoreThanHalf)
1621returntrue;
1622
1623/* Our zeroes don't have a significand to test. */
1624if (lost_fraction ==lfExactlyHalf && category !=fcZero)
1625returnAPInt::tcExtractBit(significandParts(), bit);
1626
1627returnfalse;
1628
1629casermTowardZero:
1630returnfalse;
1631
1632casermTowardPositive:
1633return !sign;
1634
1635casermTowardNegative:
1636return sign;
1637
1638default:
1639break;
1640 }
1641llvm_unreachable("Invalid rounding mode found");
1642}
1643
1644APFloat::opStatus IEEEFloat::normalize(roundingMode rounding_mode,
1645lostFraction lost_fraction) {
1646unsignedint omsb;/* One, not zero, based MSB. */
1647int exponentChange;
1648
1649if (!isFiniteNonZero())
1650returnopOK;
1651
1652/* Before rounding normalize the exponent of fcNormal numbers. */
1653 omsb = significandMSB() + 1;
1654
1655if (omsb) {
1656/* OMSB is numbered from 1. We want to place it in the integer
1657 bit numbered PRECISION if possible, with a compensating change in
1658 the exponent. */
1659 exponentChange = omsb - semantics->precision;
1660
1661/* If the resulting exponent is too high, overflow according to
1662 the rounding mode. */
1663if (exponent + exponentChange > semantics->maxExponent)
1664return handleOverflow(rounding_mode);
1665
1666/* Subnormal numbers have exponent minExponent, and their MSB
1667 is forced based on that. */
1668if (exponent + exponentChange < semantics->minExponent)
1669 exponentChange = semantics->minExponent - exponent;
1670
1671/* Shifting left is easy as we don't lose precision. */
1672if (exponentChange < 0) {
1673assert(lost_fraction ==lfExactlyZero);
1674
1675 shiftSignificandLeft(-exponentChange);
1676
1677returnopOK;
1678 }
1679
1680if (exponentChange > 0) {
1681lostFraction lf;
1682
1683/* Shift right and capture any new lost fraction. */
1684 lf = shiftSignificandRight(exponentChange);
1685
1686 lost_fraction =combineLostFractions(lf, lost_fraction);
1687
1688/* Keep OMSB up-to-date. */
1689if (omsb > (unsigned) exponentChange)
1690 omsb -= exponentChange;
1691else
1692 omsb = 0;
1693 }
1694 }
1695
1696// The all-ones values is an overflow if NaN is all ones. If NaN is
1697// represented by negative zero, then it is a valid finite value.
1698if (semantics->nonFiniteBehavior ==fltNonfiniteBehavior::NanOnly &&
1699 semantics->nanEncoding ==fltNanEncoding::AllOnes &&
1700 exponent == semantics->maxExponent && isSignificandAllOnes())
1701return handleOverflow(rounding_mode);
1702
1703/* Now round the number according to rounding_mode given the lost
1704 fraction. */
1705
1706/* As specified in IEEE 754, since we do not trap we do not report
1707 underflow for exact results. */
1708if (lost_fraction ==lfExactlyZero) {
1709/* Canonicalize zeroes. */
1710if (omsb == 0) {
1711 category =fcZero;
1712if (semantics->nanEncoding ==fltNanEncoding::NegativeZero)
1713 sign =false;
1714if (!semantics->hasZero)
1715makeSmallestNormalized(false);
1716 }
1717
1718returnopOK;
1719 }
1720
1721/* Increment the significand if we're rounding away from zero. */
1722if (roundAwayFromZero(rounding_mode, lost_fraction, 0)) {
1723if (omsb == 0)
1724 exponent = semantics->minExponent;
1725
1726 incrementSignificand();
1727 omsb = significandMSB() + 1;
1728
1729/* Did the significand increment overflow? */
1730if (omsb == (unsigned) semantics->precision + 1) {
1731/* Renormalize by incrementing the exponent and shifting our
1732 significand right one. However if we already have the
1733 maximum exponent we overflow to infinity. */
1734if (exponent == semantics->maxExponent)
1735// Invoke overflow handling with a rounding mode that will guarantee
1736// that the result gets turned into the correct infinity representation.
1737// This is needed instead of just setting the category to infinity to
1738// account for 8-bit floating point types that have no inf, only NaN.
1739return handleOverflow(sign ?rmTowardNegative :rmTowardPositive);
1740
1741 shiftSignificandRight(1);
1742
1743returnopInexact;
1744 }
1745
1746// The all-ones values is an overflow if NaN is all ones. If NaN is
1747// represented by negative zero, then it is a valid finite value.
1748if (semantics->nonFiniteBehavior ==fltNonfiniteBehavior::NanOnly &&
1749 semantics->nanEncoding ==fltNanEncoding::AllOnes &&
1750 exponent == semantics->maxExponent && isSignificandAllOnes())
1751return handleOverflow(rounding_mode);
1752 }
1753
1754/* The normal case - we were and are not denormal, and any
1755 significand increment above didn't overflow. */
1756if (omsb == semantics->precision)
1757returnopInexact;
1758
1759/* We have a non-zero denormal. */
1760assert(omsb < semantics->precision);
1761
1762/* Canonicalize zeroes. */
1763if (omsb == 0) {
1764 category =fcZero;
1765if (semantics->nanEncoding ==fltNanEncoding::NegativeZero)
1766 sign =false;
1767// This condition handles the case where the semantics
1768// does not have zero but uses the all-zero encoding
1769// to represent the smallest normal value.
1770if (!semantics->hasZero)
1771makeSmallestNormalized(false);
1772 }
1773
1774/* The fcZero case is a denormal that underflowed to zero. */
1775return (opStatus) (opUnderflow |opInexact);
1776}
1777
1778APFloat::opStatus IEEEFloat::addOrSubtractSpecials(const IEEEFloat &rhs,
1779bool subtract) {
1780switch (PackCategoriesIntoKey(category, rhs.category)) {
1781default:
1782llvm_unreachable(nullptr);
1783
1784casePackCategoriesIntoKey(fcZero,fcNaN):
1785 casePackCategoriesIntoKey(fcNormal,fcNaN):
1786 casePackCategoriesIntoKey(fcInfinity,fcNaN):
1787 assign(rhs);
1788 [[fallthrough]];
1789casePackCategoriesIntoKey(fcNaN,fcZero):
1790 casePackCategoriesIntoKey(fcNaN,fcNormal):
1791 casePackCategoriesIntoKey(fcNaN,fcInfinity):
1792 casePackCategoriesIntoKey(fcNaN,fcNaN):
1793if (isSignaling()) {
1794makeQuiet();
1795returnopInvalidOp;
1796 }
1797return rhs.isSignaling() ?opInvalidOp :opOK;
1798
1799casePackCategoriesIntoKey(fcNormal,fcZero):
1800 casePackCategoriesIntoKey(fcInfinity,fcNormal):
1801 casePackCategoriesIntoKey(fcInfinity,fcZero):
1802 returnopOK;
1803
1804casePackCategoriesIntoKey(fcNormal,fcInfinity):
1805 casePackCategoriesIntoKey(fcZero,fcInfinity):
1806 category =fcInfinity;
1807 sign = rhs.sign ^subtract;
1808returnopOK;
1809
1810casePackCategoriesIntoKey(fcZero,fcNormal):
1811 assign(rhs);
1812 sign = rhs.sign ^subtract;
1813returnopOK;
1814
1815casePackCategoriesIntoKey(fcZero,fcZero):
1816/* Sign depends on rounding mode; handled by caller. */
1817 returnopOK;
1818
1819casePackCategoriesIntoKey(fcInfinity,fcInfinity):
1820/* Differently signed infinities can only be validly
1821 subtracted. */
1822if (((sign ^ rhs.sign)!=0) !=subtract) {
1823makeNaN();
1824returnopInvalidOp;
1825 }
1826
1827returnopOK;
1828
1829casePackCategoriesIntoKey(fcNormal,fcNormal):
1830 returnopDivByZero;
1831 }
1832}
1833
1834/* Add or subtract two normal numbers. */
1835lostFraction IEEEFloat::addOrSubtractSignificand(const IEEEFloat &rhs,
1836bool subtract) {
1837integerPart carry;
1838lostFraction lost_fraction;
1839int bits;
1840
1841/* Determine if the operation on the absolute values is effectively
1842 an addition or subtraction. */
1843subtract ^=static_cast<bool>(sign ^ rhs.sign);
1844
1845/* Are we bigger exponent-wise than the RHS? */
1846 bits = exponent - rhs.exponent;
1847
1848/* Subtraction is more subtle than one might naively expect. */
1849if (subtract) {
1850if ((bits < 0) && !semantics->hasSignedRepr)
1851llvm_unreachable(
1852"This floating point format does not support signed values");
1853
1854IEEEFloat temp_rhs(rhs);
1855
1856if (bits == 0)
1857 lost_fraction =lfExactlyZero;
1858elseif (bits > 0) {
1859 lost_fraction = temp_rhs.shiftSignificandRight(bits - 1);
1860 shiftSignificandLeft(1);
1861 }else {
1862 lost_fraction = shiftSignificandRight(-bits - 1);
1863 temp_rhs.shiftSignificandLeft(1);
1864 }
1865
1866// Should we reverse the subtraction.
1867if (compareAbsoluteValue(temp_rhs) ==cmpLessThan) {
1868 carry = temp_rhs.subtractSignificand
1869 (*this, lost_fraction !=lfExactlyZero);
1870 copySignificand(temp_rhs);
1871 sign = !sign;
1872 }else {
1873 carry = subtractSignificand
1874 (temp_rhs, lost_fraction !=lfExactlyZero);
1875 }
1876
1877/* Invert the lost fraction - it was on the RHS and
1878 subtracted. */
1879if (lost_fraction ==lfLessThanHalf)
1880 lost_fraction =lfMoreThanHalf;
1881elseif (lost_fraction ==lfMoreThanHalf)
1882 lost_fraction =lfLessThanHalf;
1883
1884/* The code above is intended to ensure that no borrow is
1885 necessary. */
1886assert(!carry);
1887 (void)carry;
1888 }else {
1889if (bits > 0) {
1890IEEEFloat temp_rhs(rhs);
1891
1892 lost_fraction = temp_rhs.shiftSignificandRight(bits);
1893 carry = addSignificand(temp_rhs);
1894 }else {
1895 lost_fraction = shiftSignificandRight(-bits);
1896 carry = addSignificand(rhs);
1897 }
1898
1899/* We have a guard bit; generating a carry cannot happen. */
1900assert(!carry);
1901 (void)carry;
1902 }
1903
1904return lost_fraction;
1905}
1906
1907APFloat::opStatus IEEEFloat::multiplySpecials(const IEEEFloat &rhs) {
1908switch (PackCategoriesIntoKey(category, rhs.category)) {
1909default:
1910llvm_unreachable(nullptr);
1911
1912casePackCategoriesIntoKey(fcZero,fcNaN):
1913 casePackCategoriesIntoKey(fcNormal,fcNaN):
1914 casePackCategoriesIntoKey(fcInfinity,fcNaN):
1915 assign(rhs);
1916 sign =false;
1917 [[fallthrough]];
1918casePackCategoriesIntoKey(fcNaN,fcZero):
1919 casePackCategoriesIntoKey(fcNaN,fcNormal):
1920 casePackCategoriesIntoKey(fcNaN,fcInfinity):
1921 casePackCategoriesIntoKey(fcNaN,fcNaN):
1922 sign ^= rhs.sign;// restore the original sign
1923if (isSignaling()) {
1924makeQuiet();
1925returnopInvalidOp;
1926 }
1927return rhs.isSignaling() ?opInvalidOp :opOK;
1928
1929casePackCategoriesIntoKey(fcNormal,fcInfinity):
1930 casePackCategoriesIntoKey(fcInfinity,fcNormal):
1931 casePackCategoriesIntoKey(fcInfinity,fcInfinity):
1932 category =fcInfinity;
1933returnopOK;
1934
1935casePackCategoriesIntoKey(fcZero,fcNormal):
1936 casePackCategoriesIntoKey(fcNormal,fcZero):
1937 casePackCategoriesIntoKey(fcZero,fcZero):
1938 category =fcZero;
1939returnopOK;
1940
1941casePackCategoriesIntoKey(fcZero,fcInfinity):
1942 casePackCategoriesIntoKey(fcInfinity,fcZero):
1943makeNaN();
1944returnopInvalidOp;
1945
1946casePackCategoriesIntoKey(fcNormal,fcNormal):
1947 returnopOK;
1948 }
1949}
1950
1951APFloat::opStatus IEEEFloat::divideSpecials(const IEEEFloat &rhs) {
1952switch (PackCategoriesIntoKey(category, rhs.category)) {
1953default:
1954llvm_unreachable(nullptr);
1955
1956casePackCategoriesIntoKey(fcZero,fcNaN):
1957 casePackCategoriesIntoKey(fcNormal,fcNaN):
1958 casePackCategoriesIntoKey(fcInfinity,fcNaN):
1959 assign(rhs);
1960 sign =false;
1961 [[fallthrough]];
1962casePackCategoriesIntoKey(fcNaN,fcZero):
1963 casePackCategoriesIntoKey(fcNaN,fcNormal):
1964 casePackCategoriesIntoKey(fcNaN,fcInfinity):
1965 casePackCategoriesIntoKey(fcNaN,fcNaN):
1966 sign ^= rhs.sign;// restore the original sign
1967if (isSignaling()) {
1968makeQuiet();
1969returnopInvalidOp;
1970 }
1971return rhs.isSignaling() ?opInvalidOp :opOK;
1972
1973casePackCategoriesIntoKey(fcInfinity,fcZero):
1974 casePackCategoriesIntoKey(fcInfinity,fcNormal):
1975 casePackCategoriesIntoKey(fcZero,fcInfinity):
1976 casePackCategoriesIntoKey(fcZero,fcNormal):
1977 returnopOK;
1978
1979casePackCategoriesIntoKey(fcNormal,fcInfinity):
1980 category =fcZero;
1981returnopOK;
1982
1983casePackCategoriesIntoKey(fcNormal,fcZero):
1984if (semantics->nonFiniteBehavior ==fltNonfiniteBehavior::NanOnly)
1985makeNaN(false, sign);
1986else
1987 category =fcInfinity;
1988returnopDivByZero;
1989
1990casePackCategoriesIntoKey(fcInfinity,fcInfinity):
1991 casePackCategoriesIntoKey(fcZero,fcZero):
1992makeNaN();
1993returnopInvalidOp;
1994
1995casePackCategoriesIntoKey(fcNormal,fcNormal):
1996 returnopOK;
1997 }
1998}
1999
2000APFloat::opStatus IEEEFloat::modSpecials(const IEEEFloat &rhs) {
2001switch (PackCategoriesIntoKey(category, rhs.category)) {
2002default:
2003llvm_unreachable(nullptr);
2004
2005casePackCategoriesIntoKey(fcZero,fcNaN):
2006 casePackCategoriesIntoKey(fcNormal,fcNaN):
2007 casePackCategoriesIntoKey(fcInfinity,fcNaN):
2008 assign(rhs);
2009 [[fallthrough]];
2010casePackCategoriesIntoKey(fcNaN,fcZero):
2011 casePackCategoriesIntoKey(fcNaN,fcNormal):
2012 casePackCategoriesIntoKey(fcNaN,fcInfinity):
2013 casePackCategoriesIntoKey(fcNaN,fcNaN):
2014if (isSignaling()) {
2015makeQuiet();
2016returnopInvalidOp;
2017 }
2018return rhs.isSignaling() ?opInvalidOp :opOK;
2019
2020casePackCategoriesIntoKey(fcZero,fcInfinity):
2021 casePackCategoriesIntoKey(fcZero,fcNormal):
2022 casePackCategoriesIntoKey(fcNormal,fcInfinity):
2023 returnopOK;
2024
2025casePackCategoriesIntoKey(fcNormal,fcZero):
2026 casePackCategoriesIntoKey(fcInfinity,fcZero):
2027 casePackCategoriesIntoKey(fcInfinity,fcNormal):
2028 casePackCategoriesIntoKey(fcInfinity,fcInfinity):
2029 casePackCategoriesIntoKey(fcZero,fcZero):
2030makeNaN();
2031returnopInvalidOp;
2032
2033casePackCategoriesIntoKey(fcNormal,fcNormal):
2034 returnopOK;
2035 }
2036}
2037
2038APFloat::opStatus IEEEFloat::remainderSpecials(const IEEEFloat &rhs) {
2039switch (PackCategoriesIntoKey(category, rhs.category)) {
2040default:
2041llvm_unreachable(nullptr);
2042
2043casePackCategoriesIntoKey(fcZero,fcNaN):
2044 casePackCategoriesIntoKey(fcNormal,fcNaN):
2045 casePackCategoriesIntoKey(fcInfinity,fcNaN):
2046 assign(rhs);
2047 [[fallthrough]];
2048casePackCategoriesIntoKey(fcNaN,fcZero):
2049 casePackCategoriesIntoKey(fcNaN,fcNormal):
2050 casePackCategoriesIntoKey(fcNaN,fcInfinity):
2051 casePackCategoriesIntoKey(fcNaN,fcNaN):
2052if (isSignaling()) {
2053makeQuiet();
2054returnopInvalidOp;
2055 }
2056return rhs.isSignaling() ?opInvalidOp :opOK;
2057
2058casePackCategoriesIntoKey(fcZero,fcInfinity):
2059 casePackCategoriesIntoKey(fcZero,fcNormal):
2060 casePackCategoriesIntoKey(fcNormal,fcInfinity):
2061 returnopOK;
2062
2063casePackCategoriesIntoKey(fcNormal,fcZero):
2064 casePackCategoriesIntoKey(fcInfinity,fcZero):
2065 casePackCategoriesIntoKey(fcInfinity,fcNormal):
2066 casePackCategoriesIntoKey(fcInfinity,fcInfinity):
2067 casePackCategoriesIntoKey(fcZero,fcZero):
2068makeNaN();
2069returnopInvalidOp;
2070
2071casePackCategoriesIntoKey(fcNormal,fcNormal):
2072 returnopDivByZero;// fake status, indicating this is not a special case
2073 }
2074}
2075
2076/* Change sign. */
2077voidIEEEFloat::changeSign() {
2078// With NaN-as-negative-zero, neither NaN or negative zero can change
2079// their signs.
2080if (semantics->nanEncoding ==fltNanEncoding::NegativeZero &&
2081 (isZero() ||isNaN()))
2082return;
2083/* Look mummy, this one's easy. */
2084 sign = !sign;
2085}
2086
2087/* Normalized addition or subtraction. */
2088APFloat::opStatus IEEEFloat::addOrSubtract(constIEEEFloat &rhs,
2089roundingMode rounding_mode,
2090bool subtract) {
2091opStatus fs;
2092
2093 fs = addOrSubtractSpecials(rhs,subtract);
2094
2095/* This return code means it was not a simple case. */
2096if (fs ==opDivByZero) {
2097lostFraction lost_fraction;
2098
2099 lost_fraction = addOrSubtractSignificand(rhs,subtract);
2100 fs = normalize(rounding_mode, lost_fraction);
2101
2102/* Can only be zero if we lost no fraction. */
2103assert(category !=fcZero || lost_fraction ==lfExactlyZero);
2104 }
2105
2106/* If two numbers add (exactly) to zero, IEEE 754 decrees it is a
2107 positive zero unless rounding to minus infinity, except that
2108 adding two like-signed zeroes gives that zero. */
2109if (category ==fcZero) {
2110if (rhs.category !=fcZero || (sign == rhs.sign) ==subtract)
2111 sign = (rounding_mode ==rmTowardNegative);
2112// NaN-in-negative-zero means zeros need to be normalized to +0.
2113if (semantics->nanEncoding ==fltNanEncoding::NegativeZero)
2114 sign =false;
2115 }
2116
2117return fs;
2118}
2119
2120/* Normalized addition. */
2121APFloat::opStatusIEEEFloat::add(constIEEEFloat &rhs,
2122roundingMode rounding_mode) {
2123return addOrSubtract(rhs, rounding_mode,false);
2124}
2125
2126/* Normalized subtraction. */
2127APFloat::opStatusIEEEFloat::subtract(constIEEEFloat &rhs,
2128roundingMode rounding_mode) {
2129return addOrSubtract(rhs, rounding_mode,true);
2130}
2131
2132/* Normalized multiply. */
2133APFloat::opStatusIEEEFloat::multiply(constIEEEFloat &rhs,
2134roundingMode rounding_mode) {
2135opStatus fs;
2136
2137 sign ^= rhs.sign;
2138 fs = multiplySpecials(rhs);
2139
2140if (isZero() && semantics->nanEncoding ==fltNanEncoding::NegativeZero)
2141 sign =false;
2142if (isFiniteNonZero()) {
2143lostFraction lost_fraction = multiplySignificand(rhs);
2144 fs = normalize(rounding_mode, lost_fraction);
2145if (lost_fraction !=lfExactlyZero)
2146 fs = (opStatus) (fs |opInexact);
2147 }
2148
2149return fs;
2150}
2151
2152/* Normalized divide. */
2153APFloat::opStatusIEEEFloat::divide(constIEEEFloat &rhs,
2154roundingMode rounding_mode) {
2155opStatus fs;
2156
2157 sign ^= rhs.sign;
2158 fs = divideSpecials(rhs);
2159
2160if (isZero() && semantics->nanEncoding ==fltNanEncoding::NegativeZero)
2161 sign =false;
2162if (isFiniteNonZero()) {
2163lostFraction lost_fraction = divideSignificand(rhs);
2164 fs = normalize(rounding_mode, lost_fraction);
2165if (lost_fraction !=lfExactlyZero)
2166 fs = (opStatus) (fs |opInexact);
2167 }
2168
2169return fs;
2170}
2171
2172/* Normalized remainder. */
2173APFloat::opStatusIEEEFloat::remainder(constIEEEFloat &rhs) {
2174opStatus fs;
2175unsignedint origSign = sign;
2176
2177// First handle the special cases.
2178 fs = remainderSpecials(rhs);
2179if (fs !=opDivByZero)
2180return fs;
2181
2182 fs =opOK;
2183
2184// Make sure the current value is less than twice the denom. If the addition
2185// did not succeed (an overflow has happened), which means that the finite
2186// value we currently posses must be less than twice the denom (as we are
2187// using the same semantics).
2188IEEEFloat P2 = rhs;
2189if (P2.add(rhs,rmNearestTiesToEven) ==opOK) {
2190 fs =mod(P2);
2191assert(fs ==opOK);
2192 }
2193
2194// Lets work with absolute numbers.
2195IEEEFloatP = rhs;
2196P.sign =false;
2197 sign =false;
2198
2199//
2200// To calculate the remainder we use the following scheme.
2201//
2202// The remainder is defained as follows:
2203//
2204// remainder = numer - rquot * denom = x - r * p
2205//
2206// Where r is the result of: x/p, rounded toward the nearest integral value
2207// (with halfway cases rounded toward the even number).
2208//
2209// Currently, (after x mod 2p):
2210// r is the number of 2p's present inside x, which is inherently, an even
2211// number of p's.
2212//
2213// We may split the remaining calculation into 4 options:
2214// - if x < 0.5p then we round to the nearest number with is 0, and are done.
2215// - if x == 0.5p then we round to the nearest even number which is 0, and we
2216// are done as well.
2217// - if 0.5p < x < p then we round to nearest number which is 1, and we have
2218// to subtract 1p at least once.
2219// - if x >= p then we must subtract p at least once, as x must be a
2220// remainder.
2221//
2222// By now, we were done, or we added 1 to r, which in turn, now an odd number.
2223//
2224// We can now split the remaining calculation to the following 3 options:
2225// - if x < 0.5p then we round to the nearest number with is 0, and are done.
2226// - if x == 0.5p then we round to the nearest even number. As r is odd, we
2227// must round up to the next even number. so we must subtract p once more.
2228// - if x > 0.5p (and inherently x < p) then we must round r up to the next
2229// integral, and subtract p once more.
2230//
2231
2232// Extend the semantics to prevent an overflow/underflow or inexact result.
2233bool losesInfo;
2234fltSemantics extendedSemantics = *semantics;
2235 extendedSemantics.maxExponent++;
2236 extendedSemantics.minExponent--;
2237 extendedSemantics.precision += 2;
2238
2239IEEEFloat VEx = *this;
2240 fs = VEx.convert(extendedSemantics,rmNearestTiesToEven, &losesInfo);
2241assert(fs ==opOK && !losesInfo);
2242IEEEFloat PEx =P;
2243 fs = PEx.convert(extendedSemantics,rmNearestTiesToEven, &losesInfo);
2244assert(fs ==opOK && !losesInfo);
2245
2246// It is simpler to work with 2x instead of 0.5p, and we do not need to lose
2247// any fraction.
2248 fs = VEx.add(VEx,rmNearestTiesToEven);
2249assert(fs ==opOK);
2250
2251if (VEx.compare(PEx) ==cmpGreaterThan) {
2252 fs =subtract(P,rmNearestTiesToEven);
2253assert(fs ==opOK);
2254
2255// Make VEx = this.add(this), but because we have different semantics, we do
2256// not want to `convert` again, so we just subtract PEx twice (which equals
2257// to the desired value).
2258 fs = VEx.subtract(PEx,rmNearestTiesToEven);
2259assert(fs ==opOK);
2260 fs = VEx.subtract(PEx,rmNearestTiesToEven);
2261assert(fs ==opOK);
2262
2263cmpResult result = VEx.compare(PEx);
2264if (result ==cmpGreaterThan || result ==cmpEqual) {
2265 fs =subtract(P,rmNearestTiesToEven);
2266assert(fs ==opOK);
2267 }
2268 }
2269
2270if (isZero()) {
2271 sign = origSign;// IEEE754 requires this
2272if (semantics->nanEncoding ==fltNanEncoding::NegativeZero)
2273// But some 8-bit floats only have positive 0.
2274 sign =false;
2275 }
2276
2277else
2278 sign ^= origSign;
2279return fs;
2280}
2281
2282/* Normalized llvm frem (C fmod). */
2283APFloat::opStatusIEEEFloat::mod(constIEEEFloat &rhs) {
2284opStatus fs;
2285 fs = modSpecials(rhs);
2286unsignedint origSign = sign;
2287
2288while (isFiniteNonZero() && rhs.isFiniteNonZero() &&
2289compareAbsoluteValue(rhs) !=cmpLessThan) {
2290int Exp =ilogb(*this) -ilogb(rhs);
2291IEEEFloat V =scalbn(rhs, Exp,rmNearestTiesToEven);
2292// V can overflow to NaN with fltNonfiniteBehavior::NanOnly, so explicitly
2293// check for it.
2294if (V.isNaN() ||compareAbsoluteValue(V) ==cmpLessThan)
2295 V =scalbn(rhs, Exp - 1,rmNearestTiesToEven);
2296 V.sign = sign;
2297
2298 fs =subtract(V,rmNearestTiesToEven);
2299
2300// When the semantics supports zero, this loop's
2301// exit-condition is handled by the 'isFiniteNonZero'
2302// category check above. However, when the semantics
2303// does not have 'fcZero' and we have reached the
2304// minimum possible value, (and any further subtract
2305// will underflow to the same value) explicitly
2306// provide an exit-path here.
2307if (!semantics->hasZero && this->isSmallest())
2308break;
2309
2310assert(fs==opOK);
2311 }
2312if (isZero()) {
2313 sign = origSign;// fmod requires this
2314if (semantics->nanEncoding ==fltNanEncoding::NegativeZero)
2315 sign =false;
2316 }
2317return fs;
2318}
2319
2320/* Normalized fused-multiply-add. */
2321APFloat::opStatusIEEEFloat::fusedMultiplyAdd(constIEEEFloat &multiplicand,
2322constIEEEFloat &addend,
2323roundingMode rounding_mode) {
2324opStatus fs;
2325
2326/* Post-multiplication sign, before addition. */
2327 sign ^= multiplicand.sign;
2328
2329/* If and only if all arguments are normal do we need to do an
2330 extended-precision calculation. */
2331if (isFiniteNonZero() &&
2332 multiplicand.isFiniteNonZero() &&
2333 addend.isFinite()) {
2334lostFraction lost_fraction;
2335
2336 lost_fraction = multiplySignificand(multiplicand, addend);
2337 fs = normalize(rounding_mode, lost_fraction);
2338if (lost_fraction !=lfExactlyZero)
2339 fs = (opStatus) (fs |opInexact);
2340
2341/* If two numbers add (exactly) to zero, IEEE 754 decrees it is a
2342 positive zero unless rounding to minus infinity, except that
2343 adding two like-signed zeroes gives that zero. */
2344if (category ==fcZero && !(fs &opUnderflow) && sign != addend.sign) {
2345 sign = (rounding_mode ==rmTowardNegative);
2346if (semantics->nanEncoding ==fltNanEncoding::NegativeZero)
2347 sign =false;
2348 }
2349 }else {
2350 fs = multiplySpecials(multiplicand);
2351
2352/* FS can only be opOK or opInvalidOp. There is no more work
2353 to do in the latter case. The IEEE-754R standard says it is
2354 implementation-defined in this case whether, if ADDEND is a
2355 quiet NaN, we raise invalid op; this implementation does so.
2356
2357 If we need to do the addition we can do so with normal
2358 precision. */
2359if (fs ==opOK)
2360 fs = addOrSubtract(addend, rounding_mode,false);
2361 }
2362
2363return fs;
2364}
2365
2366/* Rounding-mode correct round to integral value. */
2367APFloat::opStatusIEEEFloat::roundToIntegral(roundingMode rounding_mode) {
2368opStatus fs;
2369
2370if (isInfinity())
2371// [IEEE Std 754-2008 6.1]:
2372// The behavior of infinity in floating-point arithmetic is derived from the
2373// limiting cases of real arithmetic with operands of arbitrarily
2374// large magnitude, when such a limit exists.
2375// ...
2376// Operations on infinite operands are usually exact and therefore signal no
2377// exceptions ...
2378returnopOK;
2379
2380if (isNaN()) {
2381if (isSignaling()) {
2382// [IEEE Std 754-2008 6.2]:
2383// Under default exception handling, any operation signaling an invalid
2384// operation exception and for which a floating-point result is to be
2385// delivered shall deliver a quiet NaN.
2386makeQuiet();
2387// [IEEE Std 754-2008 6.2]:
2388// Signaling NaNs shall be reserved operands that, under default exception
2389// handling, signal the invalid operation exception(see 7.2) for every
2390// general-computational and signaling-computational operation except for
2391// the conversions described in 5.12.
2392returnopInvalidOp;
2393 }else {
2394// [IEEE Std 754-2008 6.2]:
2395// For an operation with quiet NaN inputs, other than maximum and minimum
2396// operations, if a floating-point result is to be delivered the result
2397// shall be a quiet NaN which should be one of the input NaNs.
2398// ...
2399// Every general-computational and quiet-computational operation involving
2400// one or more input NaNs, none of them signaling, shall signal no
2401// exception, except fusedMultiplyAdd might signal the invalid operation
2402// exception(see 7.2).
2403returnopOK;
2404 }
2405 }
2406
2407if (isZero()) {
2408// [IEEE Std 754-2008 6.3]:
2409// ... the sign of the result of conversions, the quantize operation, the
2410// roundToIntegral operations, and the roundToIntegralExact(see 5.3.1) is
2411// the sign of the first or only operand.
2412returnopOK;
2413 }
2414
2415// If the exponent is large enough, we know that this value is already
2416// integral, and the arithmetic below would potentially cause it to saturate
2417// to +/-Inf. Bail out early instead.
2418if (exponent + 1 >= (int)APFloat::semanticsPrecision(*semantics))
2419returnopOK;
2420
2421// The algorithm here is quite simple: we add 2^(p-1), where p is the
2422// precision of our format, and then subtract it back off again. The choice
2423// of rounding modes for the addition/subtraction determines the rounding mode
2424// for our integral rounding as well.
2425// NOTE: When the input value is negative, we do subtraction followed by
2426// addition instead.
2427APInt IntegerConstant(NextPowerOf2(APFloat::semanticsPrecision(*semantics)),
2428 1);
2429 IntegerConstant <<=APFloat::semanticsPrecision(*semantics) - 1;
2430IEEEFloat MagicConstant(*semantics);
2431 fs = MagicConstant.convertFromAPInt(IntegerConstant,false,
2432rmNearestTiesToEven);
2433assert(fs ==opOK);
2434 MagicConstant.sign = sign;
2435
2436// Preserve the input sign so that we can handle the case of zero result
2437// correctly.
2438bool inputSign =isNegative();
2439
2440 fs =add(MagicConstant, rounding_mode);
2441
2442// Current value and 'MagicConstant' are both integers, so the result of the
2443// subtraction is always exact according to Sterbenz' lemma.
2444subtract(MagicConstant, rounding_mode);
2445
2446// Restore the input sign.
2447if (inputSign !=isNegative())
2448changeSign();
2449
2450return fs;
2451}
2452
2453/* Comparison requires normalized numbers. */
2454APFloat::cmpResultIEEEFloat::compare(constIEEEFloat &rhs) const{
2455cmpResult result;
2456
2457assert(semantics == rhs.semantics);
2458
2459switch (PackCategoriesIntoKey(category, rhs.category)) {
2460default:
2461llvm_unreachable(nullptr);
2462
2463casePackCategoriesIntoKey(fcNaN,fcZero):
2464casePackCategoriesIntoKey(fcNaN,fcNormal):
2465casePackCategoriesIntoKey(fcNaN,fcInfinity):
2466casePackCategoriesIntoKey(fcNaN,fcNaN):
2467casePackCategoriesIntoKey(fcZero,fcNaN):
2468casePackCategoriesIntoKey(fcNormal,fcNaN):
2469casePackCategoriesIntoKey(fcInfinity,fcNaN):
2470returncmpUnordered;
2471
2472casePackCategoriesIntoKey(fcInfinity,fcNormal):
2473casePackCategoriesIntoKey(fcInfinity,fcZero):
2474casePackCategoriesIntoKey(fcNormal,fcZero):
2475if (sign)
2476returncmpLessThan;
2477else
2478returncmpGreaterThan;
2479
2480casePackCategoriesIntoKey(fcNormal,fcInfinity):
2481casePackCategoriesIntoKey(fcZero,fcInfinity):
2482casePackCategoriesIntoKey(fcZero,fcNormal):
2483if (rhs.sign)
2484returncmpGreaterThan;
2485else
2486returncmpLessThan;
2487
2488casePackCategoriesIntoKey(fcInfinity,fcInfinity):
2489if (sign == rhs.sign)
2490returncmpEqual;
2491elseif (sign)
2492returncmpLessThan;
2493else
2494returncmpGreaterThan;
2495
2496casePackCategoriesIntoKey(fcZero,fcZero):
2497returncmpEqual;
2498
2499casePackCategoriesIntoKey(fcNormal,fcNormal):
2500break;
2501 }
2502
2503/* Two normal numbers. Do they have the same sign? */
2504if (sign != rhs.sign) {
2505if (sign)
2506 result =cmpLessThan;
2507else
2508 result =cmpGreaterThan;
2509 }else {
2510/* Compare absolute values; invert result if negative. */
2511 result =compareAbsoluteValue(rhs);
2512
2513if (sign) {
2514if (result ==cmpLessThan)
2515 result =cmpGreaterThan;
2516elseif (result ==cmpGreaterThan)
2517 result =cmpLessThan;
2518 }
2519 }
2520
2521return result;
2522}
2523
2524/// IEEEFloat::convert - convert a value of one floating point type to another.
2525/// The return value corresponds to the IEEE754 exceptions. *losesInfo
2526/// records whether the transformation lost information, i.e. whether
2527/// converting the result back to the original type will produce the
2528/// original value (this is almost the same as return value==fsOK, but there
2529/// are edge cases where this is not so).
2530
2531APFloat::opStatusIEEEFloat::convert(constfltSemantics &toSemantics,
2532roundingMode rounding_mode,
2533bool *losesInfo) {
2534lostFractionlostFraction;
2535unsignedint newPartCount, oldPartCount;
2536opStatus fs;
2537int shift;
2538constfltSemantics &fromSemantics = *semantics;
2539bool is_signaling =isSignaling();
2540
2541lostFraction =lfExactlyZero;
2542 newPartCount =partCountForBits(toSemantics.precision + 1);
2543 oldPartCount = partCount();
2544 shift = toSemantics.precision - fromSemantics.precision;
2545
2546bool X86SpecialNan =false;
2547if (&fromSemantics == &semX87DoubleExtended &&
2548 &toSemantics != &semX87DoubleExtended && category ==fcNaN &&
2549 (!(*significandParts() & 0x8000000000000000ULL) ||
2550 !(*significandParts() & 0x4000000000000000ULL))) {
2551// x86 has some unusual NaNs which cannot be represented in any other
2552// format; note them here.
2553 X86SpecialNan =true;
2554 }
2555
2556// If this is a truncation of a denormal number, and the target semantics
2557// has larger exponent range than the source semantics (this can happen
2558// when truncating from PowerPC double-double to double format), the
2559// right shift could lose result mantissa bits. Adjust exponent instead
2560// of performing excessive shift.
2561// Also do a similar trick in case shifting denormal would produce zero
2562// significand as this case isn't handled correctly by normalize.
2563if (shift < 0 &&isFiniteNonZero()) {
2564int omsb = significandMSB() + 1;
2565int exponentChange = omsb - fromSemantics.precision;
2566if (exponent + exponentChange < toSemantics.minExponent)
2567 exponentChange = toSemantics.minExponent - exponent;
2568if (exponentChange < shift)
2569 exponentChange = shift;
2570if (exponentChange < 0) {
2571 shift -= exponentChange;
2572 exponent += exponentChange;
2573 }elseif (omsb <= -shift) {
2574 exponentChange = omsb + shift - 1;// leave at least one bit set
2575 shift -= exponentChange;
2576 exponent += exponentChange;
2577 }
2578 }
2579
2580// If this is a truncation, perform the shift before we narrow the storage.
2581if (shift < 0 && (isFiniteNonZero() ||
2582 (category ==fcNaN && semantics->nonFiniteBehavior !=
2583fltNonfiniteBehavior::NanOnly)))
2584lostFraction =shiftRight(significandParts(), oldPartCount, -shift);
2585
2586// Fix the storage so it can hold to new value.
2587if (newPartCount > oldPartCount) {
2588// The new type requires more storage; make it available.
2589integerPart *newParts;
2590 newParts =newintegerPart[newPartCount];
2591APInt::tcSet(newParts, 0, newPartCount);
2592if (isFiniteNonZero() || category==fcNaN)
2593APInt::tcAssign(newParts, significandParts(), oldPartCount);
2594 freeSignificand();
2595 significand.parts = newParts;
2596 }elseif (newPartCount == 1 && oldPartCount != 1) {
2597// Switch to built-in storage for a single part.
2598integerPart newPart = 0;
2599if (isFiniteNonZero() || category==fcNaN)
2600 newPart = significandParts()[0];
2601 freeSignificand();
2602 significand.part = newPart;
2603 }
2604
2605// Now that we have the right storage, switch the semantics.
2606 semantics = &toSemantics;
2607
2608// If this is an extension, perform the shift now that the storage is
2609// available.
2610if (shift > 0 && (isFiniteNonZero() || category==fcNaN))
2611APInt::tcShiftLeft(significandParts(), newPartCount, shift);
2612
2613if (isFiniteNonZero()) {
2614 fs = normalize(rounding_mode,lostFraction);
2615 *losesInfo = (fs !=opOK);
2616 }elseif (category ==fcNaN) {
2617if (semantics->nonFiniteBehavior ==fltNonfiniteBehavior::NanOnly) {
2618 *losesInfo =
2619 fromSemantics.nonFiniteBehavior !=fltNonfiniteBehavior::NanOnly;
2620makeNaN(false, sign);
2621return is_signaling ?opInvalidOp :opOK;
2622 }
2623
2624// If NaN is negative zero, we need to create a new NaN to avoid converting
2625// NaN to -Inf.
2626if (fromSemantics.nanEncoding ==fltNanEncoding::NegativeZero &&
2627 semantics->nanEncoding !=fltNanEncoding::NegativeZero)
2628makeNaN(false,false);
2629
2630 *losesInfo =lostFraction !=lfExactlyZero || X86SpecialNan;
2631
2632// For x87 extended precision, we want to make a NaN, not a special NaN if
2633// the input wasn't special either.
2634if (!X86SpecialNan && semantics == &semX87DoubleExtended)
2635APInt::tcSetBit(significandParts(), semantics->precision - 1);
2636
2637// Convert of sNaN creates qNaN and raises an exception (invalid op).
2638// This also guarantees that a sNaN does not become Inf on a truncation
2639// that loses all payload bits.
2640if (is_signaling) {
2641makeQuiet();
2642 fs =opInvalidOp;
2643 }else {
2644 fs =opOK;
2645 }
2646 }elseif (category ==fcInfinity &&
2647 semantics->nonFiniteBehavior ==fltNonfiniteBehavior::NanOnly) {
2648makeNaN(false, sign);
2649 *losesInfo =true;
2650 fs =opInexact;
2651 }elseif (category ==fcZero &&
2652 semantics->nanEncoding ==fltNanEncoding::NegativeZero) {
2653// Negative zero loses info, but positive zero doesn't.
2654 *losesInfo =
2655 fromSemantics.nanEncoding !=fltNanEncoding::NegativeZero && sign;
2656 fs = *losesInfo ?opInexact :opOK;
2657// NaN is negative zero means -0 -> +0, which can lose information
2658 sign =false;
2659 }else {
2660 *losesInfo =false;
2661 fs =opOK;
2662 }
2663
2664if (category ==fcZero && !semantics->hasZero)
2665makeSmallestNormalized(false);
2666return fs;
2667}
2668
2669/* Convert a floating point number to an integer according to the
2670 rounding mode. If the rounded integer value is out of range this
2671 returns an invalid operation exception and the contents of the
2672 destination parts are unspecified. If the rounded value is in
2673 range but the floating point number is not the exact integer, the C
2674 standard doesn't require an inexact exception to be raised. IEEE
2675 854 does require it so we do that.
2676
2677 Note that for conversions to integer type the C standard requires
2678 round-to-zero to always be used. */
2679APFloat::opStatus IEEEFloat::convertToSignExtendedInteger(
2680MutableArrayRef<integerPart> parts,unsignedint width,boolisSigned,
2681roundingMode rounding_mode,bool *isExact) const{
2682lostFraction lost_fraction;
2683constintegerPart *src;
2684unsignedint dstPartsCount, truncatedBits;
2685
2686 *isExact =false;
2687
2688/* Handle the three special cases first. */
2689if (category ==fcInfinity || category ==fcNaN)
2690returnopInvalidOp;
2691
2692 dstPartsCount =partCountForBits(width);
2693assert(dstPartsCount <= parts.size() &&"Integer too big");
2694
2695if (category ==fcZero) {
2696APInt::tcSet(parts.data(), 0, dstPartsCount);
2697// Negative zero can't be represented as an int.
2698 *isExact = !sign;
2699returnopOK;
2700 }
2701
2702 src = significandParts();
2703
2704/* Step 1: place our absolute value, with any fraction truncated, in
2705 the destination. */
2706if (exponent < 0) {
2707/* Our absolute value is less than one; truncate everything. */
2708APInt::tcSet(parts.data(), 0, dstPartsCount);
2709/* For exponent -1 the integer bit represents .5, look at that.
2710 For smaller exponents leftmost truncated bit is 0. */
2711 truncatedBits = semantics->precision -1U - exponent;
2712 }else {
2713/* We want the most significant (exponent + 1) bits; the rest are
2714 truncated. */
2715unsignedint bits = exponent + 1U;
2716
2717/* Hopelessly large in magnitude? */
2718if (bits > width)
2719returnopInvalidOp;
2720
2721if (bits < semantics->precision) {
2722/* We truncate (semantics->precision - bits) bits. */
2723 truncatedBits = semantics->precision - bits;
2724APInt::tcExtract(parts.data(), dstPartsCount, src, bits, truncatedBits);
2725 }else {
2726/* We want at least as many bits as are available. */
2727APInt::tcExtract(parts.data(), dstPartsCount, src, semantics->precision,
2728 0);
2729APInt::tcShiftLeft(parts.data(), dstPartsCount,
2730 bits - semantics->precision);
2731 truncatedBits = 0;
2732 }
2733 }
2734
2735/* Step 2: work out any lost fraction, and increment the absolute
2736 value if we would round away from zero. */
2737if (truncatedBits) {
2738 lost_fraction =lostFractionThroughTruncation(src, partCount(),
2739 truncatedBits);
2740if (lost_fraction !=lfExactlyZero &&
2741 roundAwayFromZero(rounding_mode, lost_fraction, truncatedBits)) {
2742if (APInt::tcIncrement(parts.data(), dstPartsCount))
2743returnopInvalidOp;/* Overflow. */
2744 }
2745 }else {
2746 lost_fraction =lfExactlyZero;
2747 }
2748
2749/* Step 3: check if we fit in the destination. */
2750unsignedint omsb =APInt::tcMSB(parts.data(), dstPartsCount) + 1;
2751
2752if (sign) {
2753if (!isSigned) {
2754/* Negative numbers cannot be represented as unsigned. */
2755if (omsb != 0)
2756returnopInvalidOp;
2757 }else {
2758/* It takes omsb bits to represent the unsigned integer value.
2759 We lose a bit for the sign, but care is needed as the
2760 maximally negative integer is a special case. */
2761if (omsb == width &&
2762APInt::tcLSB(parts.data(), dstPartsCount) + 1 != omsb)
2763returnopInvalidOp;
2764
2765/* This case can happen because of rounding. */
2766if (omsb > width)
2767returnopInvalidOp;
2768 }
2769
2770APInt::tcNegate (parts.data(), dstPartsCount);
2771 }else {
2772if (omsb >= width + !isSigned)
2773returnopInvalidOp;
2774 }
2775
2776if (lost_fraction ==lfExactlyZero) {
2777 *isExact =true;
2778returnopOK;
2779 }else
2780returnopInexact;
2781}
2782
2783/* Same as convertToSignExtendedInteger, except we provide
2784 deterministic values in case of an invalid operation exception,
2785 namely zero for NaNs and the minimal or maximal value respectively
2786 for underflow or overflow.
2787 The *isExact output tells whether the result is exact, in the sense
2788 that converting it back to the original floating point type produces
2789 the original value. This is almost equivalent to result==opOK,
2790 except for negative zeroes.
2791*/
2792APFloat::opStatus
2793IEEEFloat::convertToInteger(MutableArrayRef<integerPart> parts,
2794unsignedint width,boolisSigned,
2795roundingMode rounding_mode,bool *isExact) const{
2796opStatus fs;
2797
2798 fs = convertToSignExtendedInteger(parts, width,isSigned, rounding_mode,
2799 isExact);
2800
2801if (fs ==opInvalidOp) {
2802unsignedint bits, dstPartsCount;
2803
2804 dstPartsCount =partCountForBits(width);
2805assert(dstPartsCount <= parts.size() &&"Integer too big");
2806
2807if (category ==fcNaN)
2808 bits = 0;
2809elseif (sign)
2810 bits =isSigned;
2811else
2812 bits = width -isSigned;
2813
2814tcSetLeastSignificantBits(parts.data(), dstPartsCount, bits);
2815if (sign &&isSigned)
2816APInt::tcShiftLeft(parts.data(), dstPartsCount, width - 1);
2817 }
2818
2819return fs;
2820}
2821
2822/* Convert an unsigned integer SRC to a floating point number,
2823 rounding according to ROUNDING_MODE. The sign of the floating
2824 point number is not modified. */
2825APFloat::opStatus IEEEFloat::convertFromUnsignedParts(
2826constintegerPart *src,unsignedint srcCount,roundingMode rounding_mode) {
2827unsignedint omsb, precision, dstCount;
2828integerPart *dst;
2829lostFraction lost_fraction;
2830
2831 category =fcNormal;
2832 omsb =APInt::tcMSB(src, srcCount) + 1;
2833 dst = significandParts();
2834 dstCount = partCount();
2835 precision = semantics->precision;
2836
2837/* We want the most significant PRECISION bits of SRC. There may not
2838 be that many; extract what we can. */
2839if (precision <= omsb) {
2840 exponent = omsb - 1;
2841 lost_fraction =lostFractionThroughTruncation(src, srcCount,
2842 omsb - precision);
2843APInt::tcExtract(dst, dstCount, src, precision, omsb - precision);
2844 }else {
2845 exponent = precision - 1;
2846 lost_fraction =lfExactlyZero;
2847APInt::tcExtract(dst, dstCount, src, omsb, 0);
2848 }
2849
2850return normalize(rounding_mode, lost_fraction);
2851}
2852
2853APFloat::opStatusIEEEFloat::convertFromAPInt(constAPInt &Val,boolisSigned,
2854roundingMode rounding_mode) {
2855unsignedint partCount = Val.getNumWords();
2856APInt api = Val;
2857
2858 sign =false;
2859if (isSigned && api.isNegative()) {
2860 sign =true;
2861 api = -api;
2862 }
2863
2864return convertFromUnsignedParts(api.getRawData(), partCount, rounding_mode);
2865}
2866
2867/* Convert a two's complement integer SRC to a floating point number,
2868 rounding according to ROUNDING_MODE. ISSIGNED is true if the
2869 integer is signed, in which case it must be sign-extended. */
2870APFloat::opStatus
2871IEEEFloat::convertFromSignExtendedInteger(constintegerPart *src,
2872unsignedint srcCount,boolisSigned,
2873roundingMode rounding_mode) {
2874opStatus status;
2875
2876if (isSigned &&
2877APInt::tcExtractBit(src, srcCount *integerPartWidth - 1)) {
2878integerPart *copy;
2879
2880/* If we're signed and negative negate a copy. */
2881 sign =true;
2882copy =newintegerPart[srcCount];
2883APInt::tcAssign(copy, src, srcCount);
2884APInt::tcNegate(copy, srcCount);
2885 status = convertFromUnsignedParts(copy, srcCount, rounding_mode);
2886delete []copy;
2887 }else {
2888 sign =false;
2889 status = convertFromUnsignedParts(src, srcCount, rounding_mode);
2890 }
2891
2892return status;
2893}
2894
2895/* FIXME: should this just take a const APInt reference? */
2896APFloat::opStatus
2897IEEEFloat::convertFromZeroExtendedInteger(constintegerPart *parts,
2898unsignedint width,boolisSigned,
2899roundingMode rounding_mode) {
2900unsignedint partCount =partCountForBits(width);
2901APInt api =APInt(width,ArrayRef(parts, partCount));
2902
2903 sign =false;
2904if (isSigned &&APInt::tcExtractBit(parts, width - 1)) {
2905 sign =true;
2906 api = -api;
2907 }
2908
2909return convertFromUnsignedParts(api.getRawData(), partCount, rounding_mode);
2910}
2911
2912Expected<APFloat::opStatus>
2913IEEEFloat::convertFromHexadecimalString(StringRef s,
2914roundingMode rounding_mode) {
2915lostFraction lost_fraction =lfExactlyZero;
2916
2917 category =fcNormal;
2918 zeroSignificand();
2919 exponent = 0;
2920
2921integerPart *significand = significandParts();
2922unsigned partsCount = partCount();
2923unsigned bitPos = partsCount *integerPartWidth;
2924bool computedTrailingFraction =false;
2925
2926// Skip leading zeroes and any (hexa)decimal point.
2927StringRef::iterator begin = s.begin();
2928StringRef::iterator end = s.end();
2929StringRef::iterator dot;
2930auto PtrOrErr =skipLeadingZeroesAndAnyDot(begin, end, &dot);
2931if (!PtrOrErr)
2932return PtrOrErr.takeError();
2933StringRef::iterator p = *PtrOrErr;
2934StringRef::iterator firstSignificantDigit = p;
2935
2936while (p != end) {
2937integerPart hex_value;
2938
2939if (*p =='.') {
2940if (dot != end)
2941returncreateError("String contains multiple dots");
2942 dot = p++;
2943continue;
2944 }
2945
2946 hex_value = hexDigitValue(*p);
2947if (hex_value == UINT_MAX)
2948break;
2949
2950 p++;
2951
2952// Store the number while we have space.
2953if (bitPos) {
2954 bitPos -= 4;
2955 hex_value <<= bitPos %integerPartWidth;
2956 significand[bitPos /integerPartWidth] |= hex_value;
2957 }elseif (!computedTrailingFraction) {
2958auto FractOrErr =trailingHexadecimalFraction(p, end, hex_value);
2959if (!FractOrErr)
2960return FractOrErr.takeError();
2961 lost_fraction = *FractOrErr;
2962 computedTrailingFraction =true;
2963 }
2964 }
2965
2966/* Hex floats require an exponent but not a hexadecimal point. */
2967if (p == end)
2968returncreateError("Hex strings require an exponent");
2969if (*p !='p' && *p !='P')
2970returncreateError("Invalid character in significand");
2971if (p == begin)
2972returncreateError("Significand has no digits");
2973if (dot != end && p - begin == 1)
2974returncreateError("Significand has no digits");
2975
2976/* Ignore the exponent if we are zero. */
2977if (p != firstSignificantDigit) {
2978int expAdjustment;
2979
2980/* Implicit hexadecimal point? */
2981if (dot == end)
2982dot =p;
2983
2984/* Calculate the exponent adjustment implicit in the number of
2985 significant digits. */
2986 expAdjustment =static_cast<int>(dot - firstSignificantDigit);
2987if (expAdjustment < 0)
2988 expAdjustment++;
2989 expAdjustment = expAdjustment * 4 - 1;
2990
2991/* Adjust for writing the significand starting at the most
2992 significant nibble. */
2993 expAdjustment += semantics->precision;
2994 expAdjustment -= partsCount *integerPartWidth;
2995
2996/* Adjust for the given exponent. */
2997auto ExpOrErr =totalExponent(p + 1, end, expAdjustment);
2998if (!ExpOrErr)
2999return ExpOrErr.takeError();
3000 exponent = *ExpOrErr;
3001 }
3002
3003return normalize(rounding_mode, lost_fraction);
3004}
3005
3006APFloat::opStatus
3007IEEEFloat::roundSignificandWithExponent(constintegerPart *decSigParts,
3008unsigned sigPartCount,int exp,
3009roundingMode rounding_mode) {
3010unsignedint parts, pow5PartCount;
3011fltSemantics calcSemantics = { 32767, -32767, 0, 0 };
3012integerPart pow5Parts[maxPowerOfFiveParts];
3013bool isNearest;
3014
3015 isNearest = (rounding_mode ==rmNearestTiesToEven ||
3016 rounding_mode ==rmNearestTiesToAway);
3017
3018 parts =partCountForBits(semantics->precision + 11);
3019
3020/* Calculate pow(5, abs(exp)). */
3021 pow5PartCount =powerOf5(pow5Parts, exp >= 0 ? exp: -exp);
3022
3023for (;; parts *= 2) {
3024opStatus sigStatus, powStatus;
3025unsignedint excessPrecision, truncatedBits;
3026
3027 calcSemantics.precision = parts *integerPartWidth - 1;
3028 excessPrecision = calcSemantics.precision - semantics->precision;
3029 truncatedBits = excessPrecision;
3030
3031IEEEFloat decSig(calcSemantics,uninitialized);
3032 decSig.makeZero(sign);
3033IEEEFloat pow5(calcSemantics);
3034
3035 sigStatus = decSig.convertFromUnsignedParts(decSigParts, sigPartCount,
3036rmNearestTiesToEven);
3037 powStatus = pow5.convertFromUnsignedParts(pow5Parts, pow5PartCount,
3038rmNearestTiesToEven);
3039/* Add exp, as 10^n = 5^n * 2^n. */
3040 decSig.exponent += exp;
3041
3042lostFraction calcLostFraction;
3043integerPart HUerr, HUdistance;
3044unsignedint powHUerr;
3045
3046if (exp >= 0) {
3047/* multiplySignificand leaves the precision-th bit set to 1. */
3048 calcLostFraction = decSig.multiplySignificand(pow5);
3049 powHUerr = powStatus !=opOK;
3050 }else {
3051 calcLostFraction = decSig.divideSignificand(pow5);
3052/* Denormal numbers have less precision. */
3053if (decSig.exponent < semantics->minExponent) {
3054 excessPrecision += (semantics->minExponent - decSig.exponent);
3055 truncatedBits = excessPrecision;
3056if (excessPrecision > calcSemantics.precision)
3057 excessPrecision = calcSemantics.precision;
3058 }
3059/* Extra half-ulp lost in reciprocal of exponent. */
3060 powHUerr = (powStatus ==opOK && calcLostFraction ==lfExactlyZero) ? 0:2;
3061 }
3062
3063/* Both multiplySignificand and divideSignificand return the
3064 result with the integer bit set. */
3065assert(APInt::tcExtractBit
3066 (decSig.significandParts(), calcSemantics.precision - 1) == 1);
3067
3068 HUerr =HUerrBound(calcLostFraction !=lfExactlyZero, sigStatus !=opOK,
3069 powHUerr);
3070 HUdistance = 2 *ulpsFromBoundary(decSig.significandParts(),
3071 excessPrecision, isNearest);
3072
3073/* Are we guaranteed to round correctly if we truncate? */
3074if (HUdistance >= HUerr) {
3075APInt::tcExtract(significandParts(), partCount(), decSig.significandParts(),
3076 calcSemantics.precision - excessPrecision,
3077 excessPrecision);
3078/* Take the exponent of decSig. If we tcExtract-ed less bits
3079 above we must adjust our exponent to compensate for the
3080 implicit right shift. */
3081 exponent = (decSig.exponent + semantics->precision
3082 - (calcSemantics.precision - excessPrecision));
3083 calcLostFraction =lostFractionThroughTruncation(decSig.significandParts(),
3084 decSig.partCount(),
3085 truncatedBits);
3086return normalize(rounding_mode, calcLostFraction);
3087 }
3088 }
3089}
3090
3091Expected<APFloat::opStatus>
3092IEEEFloat::convertFromDecimalString(StringRef str,roundingMode rounding_mode) {
3093decimalInfoD;
3094opStatus fs;
3095
3096/* Scan the text. */
3097StringRef::iteratorp = str.begin();
3098if (Error Err =interpretDecimal(p, str.end(), &D))
3099return std::move(Err);
3100
3101/* Handle the quick cases. First the case of no significant digits,
3102 i.e. zero, and then exponents that are obviously too large or too
3103 small. Writing L for log 10 / log 2, a number d.ddddd*10^exp
3104 definitely overflows if
3105
3106 (exp - 1) * L >= maxExponent
3107
3108 and definitely underflows to zero where
3109
3110 (exp + 1) * L <= minExponent - precision
3111
3112 With integer arithmetic the tightest bounds for L are
3113
3114 93/28 < L < 196/59 [ numerator <= 256 ]
3115 42039/12655 < L < 28738/8651 [ numerator <= 65536 ]
3116 */
3117
3118// Test if we have a zero number allowing for strings with no null terminators
3119// and zero decimals with non-zero exponents.
3120//
3121// We computed firstSigDigit by ignoring all zeros and dots. Thus if
3122// D->firstSigDigit equals str.end(), every digit must be a zero and there can
3123// be at most one dot. On the other hand, if we have a zero with a non-zero
3124// exponent, then we know that D.firstSigDigit will be non-numeric.
3125if (D.firstSigDigit == str.end() ||decDigitValue(*D.firstSigDigit) >= 10U) {
3126 category =fcZero;
3127 fs =opOK;
3128if (semantics->nanEncoding ==fltNanEncoding::NegativeZero)
3129 sign =false;
3130if (!semantics->hasZero)
3131makeSmallestNormalized(false);
3132
3133/* Check whether the normalized exponent is high enough to overflow
3134 max during the log-rebasing in the max-exponent check below. */
3135 }elseif (D.normalizedExponent - 1 > INT_MAX / 42039) {
3136 fs = handleOverflow(rounding_mode);
3137
3138/* If it wasn't, then it also wasn't high enough to overflow max
3139 during the log-rebasing in the min-exponent check. Check that it
3140 won't overflow min in either check, then perform the min-exponent
3141 check. */
3142 }elseif (D.normalizedExponent - 1 < INT_MIN / 42039 ||
3143 (D.normalizedExponent + 1) * 28738 <=
3144 8651 * (semantics->minExponent - (int) semantics->precision)) {
3145/* Underflow to zero and round. */
3146 category =fcNormal;
3147 zeroSignificand();
3148 fs = normalize(rounding_mode,lfLessThanHalf);
3149
3150/* We can finally safely perform the max-exponent check. */
3151 }elseif ((D.normalizedExponent - 1) * 42039
3152 >= 12655 * semantics->maxExponent) {
3153/* Overflow and round. */
3154 fs = handleOverflow(rounding_mode);
3155 }else {
3156integerPart *decSignificand;
3157unsignedint partCount;
3158
3159/* A tight upper bound on number of bits required to hold an
3160 N-digit decimal integer is N * 196 / 59. Allocate enough space
3161 to hold the full significand, and an extra part required by
3162 tcMultiplyPart. */
3163 partCount =static_cast<unsignedint>(D.lastSigDigit -D.firstSigDigit) + 1;
3164 partCount =partCountForBits(1 + 196 * partCount / 59);
3165 decSignificand =newintegerPart[partCount + 1];
3166 partCount = 0;
3167
3168/* Convert to binary efficiently - we do almost all multiplication
3169 in an integerPart. When this would overflow do we do a single
3170 bignum multiplication, and then revert again to multiplication
3171 in an integerPart. */
3172do {
3173integerPart decValue, val, multiplier;
3174
3175 val = 0;
3176 multiplier = 1;
3177
3178do {
3179if (*p =='.') {
3180p++;
3181if (p == str.end()) {
3182break;
3183 }
3184 }
3185 decValue =decDigitValue(*p++);
3186if (decValue >= 10U) {
3187delete[] decSignificand;
3188returncreateError("Invalid character in significand");
3189 }
3190 multiplier *= 10;
3191 val = val * 10 + decValue;
3192/* The maximum number that can be multiplied by ten with any
3193 digit added without overflowing an integerPart. */
3194 }while (p <=D.lastSigDigit && multiplier <= (~ (integerPart) 0 - 9) / 10);
3195
3196/* Multiply out the current part. */
3197APInt::tcMultiplyPart(decSignificand, decSignificand, multiplier, val,
3198 partCount, partCount + 1,false);
3199
3200/* If we used another part (likely but not guaranteed), increase
3201 the count. */
3202if (decSignificand[partCount])
3203 partCount++;
3204 }while (p <=D.lastSigDigit);
3205
3206 category =fcNormal;
3207 fs = roundSignificandWithExponent(decSignificand, partCount,
3208D.exponent, rounding_mode);
3209
3210delete [] decSignificand;
3211 }
3212
3213return fs;
3214}
3215
3216bool IEEEFloat::convertFromStringSpecials(StringRef str) {
3217constsize_t MIN_NAME_SIZE = 3;
3218
3219if (str.size() < MIN_NAME_SIZE)
3220returnfalse;
3221
3222if (str =="inf" || str =="INFINITY" || str =="+Inf") {
3223makeInf(false);
3224returntrue;
3225 }
3226
3227bool IsNegative = str.front() =='-';
3228if (IsNegative) {
3229 str = str.drop_front();
3230if (str.size() < MIN_NAME_SIZE)
3231returnfalse;
3232
3233if (str =="inf" || str =="INFINITY" || str =="Inf") {
3234makeInf(true);
3235returntrue;
3236 }
3237 }
3238
3239// If we have a 's' (or 'S') prefix, then this is a Signaling NaN.
3240bool IsSignaling = str.front() =='s' || str.front() =='S';
3241if (IsSignaling) {
3242 str = str.drop_front();
3243if (str.size() < MIN_NAME_SIZE)
3244returnfalse;
3245 }
3246
3247if (str.starts_with("nan") || str.starts_with("NaN")) {
3248 str = str.drop_front(3);
3249
3250// A NaN without payload.
3251if (str.empty()) {
3252makeNaN(IsSignaling, IsNegative);
3253returntrue;
3254 }
3255
3256// Allow the payload to be inside parentheses.
3257if (str.front() =='(') {
3258// Parentheses should be balanced (and not empty).
3259if (str.size() <= 2 || str.back() !=')')
3260returnfalse;
3261
3262 str = str.slice(1, str.size() - 1);
3263 }
3264
3265// Determine the payload number's radix.
3266unsigned Radix = 10;
3267if (str[0] =='0') {
3268if (str.size() > 1 && tolower(str[1]) =='x') {
3269 str = str.drop_front(2);
3270 Radix = 16;
3271 }else
3272 Radix = 8;
3273 }
3274
3275// Parse the payload and make the NaN.
3276APInt Payload;
3277if (!str.getAsInteger(Radix, Payload)) {
3278makeNaN(IsSignaling, IsNegative, &Payload);
3279returntrue;
3280 }
3281 }
3282
3283returnfalse;
3284}
3285
3286Expected<APFloat::opStatus>
3287IEEEFloat::convertFromString(StringRef str,roundingMode rounding_mode) {
3288if (str.empty())
3289returncreateError("Invalid string length");
3290
3291// Handle special cases.
3292if (convertFromStringSpecials(str))
3293returnopOK;
3294
3295/* Handle a leading minus sign. */
3296StringRef::iterator p = str.begin();
3297size_t slen = str.size();
3298 sign = *p =='-' ? 1 : 0;
3299if (sign && !semantics->hasSignedRepr)
3300llvm_unreachable(
3301"This floating point format does not support signed values");
3302
3303if (*p =='-' || *p =='+') {
3304 p++;
3305 slen--;
3306if (!slen)
3307returncreateError("String has no digits");
3308 }
3309
3310if (slen >= 2 && p[0] =='0' && (p[1] =='x' || p[1] =='X')) {
3311if (slen == 2)
3312returncreateError("Invalid string");
3313return convertFromHexadecimalString(StringRef(p + 2, slen - 2),
3314 rounding_mode);
3315 }
3316
3317return convertFromDecimalString(StringRef(p, slen), rounding_mode);
3318}
3319
3320/* Write out a hexadecimal representation of the floating point value
3321 to DST, which must be of sufficient size, in the C99 form
3322 [-]0xh.hhhhp[+-]d. Return the number of characters written,
3323 excluding the terminating NUL.
3324
3325 If UPPERCASE, the output is in upper case, otherwise in lower case.
3326
3327 HEXDIGITS digits appear altogether, rounding the value if
3328 necessary. If HEXDIGITS is 0, the minimal precision to display the
3329 number precisely is used instead. If nothing would appear after
3330 the decimal point it is suppressed.
3331
3332 The decimal exponent is always printed and has at least one digit.
3333 Zero values display an exponent of zero. Infinities and NaNs
3334 appear as "infinity" or "nan" respectively.
3335
3336 The above rules are as specified by C99. There is ambiguity about
3337 what the leading hexadecimal digit should be. This implementation
3338 uses whatever is necessary so that the exponent is displayed as
3339 stored. This implies the exponent will fall within the IEEE format
3340 range, and the leading hexadecimal digit will be 0 (for denormals),
3341 1 (normal numbers) or 2 (normal numbers rounded-away-from-zero with
3342 any other digits zero).
3343*/
3344unsignedintIEEEFloat::convertToHexString(char *dst,unsignedint hexDigits,
3345bool upperCase,
3346roundingMode rounding_mode) const{
3347char *p;
3348
3349 p = dst;
3350if (sign)
3351 *dst++ ='-';
3352
3353switch (category) {
3354casefcInfinity:
3355 memcpy (dst, upperCase ?infinityU:infinityL,sizeofinfinityU - 1);
3356 dst +=sizeofinfinityL - 1;
3357break;
3358
3359casefcNaN:
3360 memcpy (dst, upperCase ?NaNU:NaNL,sizeofNaNU - 1);
3361 dst +=sizeofNaNU - 1;
3362break;
3363
3364casefcZero:
3365 *dst++ ='0';
3366 *dst++ = upperCase ?'X':'x';
3367 *dst++ ='0';
3368if (hexDigits > 1) {
3369 *dst++ ='.';
3370 memset (dst,'0', hexDigits - 1);
3371 dst += hexDigits - 1;
3372 }
3373 *dst++ = upperCase ?'P':'p';
3374 *dst++ ='0';
3375break;
3376
3377casefcNormal:
3378 dst = convertNormalToHexString (dst, hexDigits, upperCase, rounding_mode);
3379break;
3380 }
3381
3382 *dst = 0;
3383
3384returnstatic_cast<unsignedint>(dst - p);
3385}
3386
3387/* Does the hard work of outputting the correctly rounded hexadecimal
3388 form of a normal floating point number with the specified number of
3389 hexadecimal digits. If HEXDIGITS is zero the minimum number of
3390 digits necessary to print the value precisely is output. */
3391char *IEEEFloat::convertNormalToHexString(char *dst,unsignedint hexDigits,
3392bool upperCase,
3393roundingMode rounding_mode) const{
3394unsignedintcount, valueBits, shift, partsCount, outputDigits;
3395constchar *hexDigitChars;
3396constintegerPart *significand;
3397char *p;
3398bool roundUp;
3399
3400 *dst++ ='0';
3401 *dst++ = upperCase ?'X':'x';
3402
3403 roundUp =false;
3404 hexDigitChars = upperCase ?hexDigitsUpper:hexDigitsLower;
3405
3406 significand = significandParts();
3407 partsCount = partCount();
3408
3409/* +3 because the first digit only uses the single integer bit, so
3410 we have 3 virtual zero most-significant-bits. */
3411 valueBits = semantics->precision + 3;
3412 shift =integerPartWidth - valueBits %integerPartWidth;
3413
3414/* The natural number of digits required ignoring trailing
3415 insignificant zeroes. */
3416 outputDigits = (valueBits - significandLSB () + 3) / 4;
3417
3418/* hexDigits of zero means use the required number for the
3419 precision. Otherwise, see if we are truncating. If we are,
3420 find out if we need to round away from zero. */
3421if (hexDigits) {
3422if (hexDigits < outputDigits) {
3423/* We are dropping non-zero bits, so need to check how to round.
3424 "bits" is the number of dropped bits. */
3425unsignedint bits;
3426lostFraction fraction;
3427
3428 bits = valueBits - hexDigits * 4;
3429 fraction =lostFractionThroughTruncation (significand, partsCount, bits);
3430 roundUp = roundAwayFromZero(rounding_mode, fraction, bits);
3431 }
3432 outputDigits = hexDigits;
3433 }
3434
3435/* Write the digits consecutively, and start writing in the location
3436 of the hexadecimal point. We move the most significant digit
3437 left and add the hexadecimal point later. */
3438 p = ++dst;
3439
3440count = (valueBits +integerPartWidth - 1) /integerPartWidth;
3441
3442while (outputDigits &&count) {
3443integerPart part;
3444
3445/* Put the most significant integerPartWidth bits in "part". */
3446if (--count == partsCount)
3447 part = 0;/* An imaginary higher zero part. */
3448else
3449 part = significand[count] << shift;
3450
3451if (count && shift)
3452 part |= significand[count - 1] >> (integerPartWidth - shift);
3453
3454/* Convert as much of "part" to hexdigits as we can. */
3455unsignedint curDigits =integerPartWidth / 4;
3456
3457if (curDigits > outputDigits)
3458 curDigits = outputDigits;
3459 dst +=partAsHex (dst, part, curDigits, hexDigitChars);
3460 outputDigits -= curDigits;
3461 }
3462
3463if (roundUp) {
3464char *q = dst;
3465
3466/* Note that hexDigitChars has a trailing '0'. */
3467do {
3468q--;
3469 *q = hexDigitChars[hexDigitValue (*q) + 1];
3470 }while (*q =='0');
3471assert(q >= p);
3472 }else {
3473/* Add trailing zeroes. */
3474 memset (dst,'0', outputDigits);
3475 dst += outputDigits;
3476 }
3477
3478/* Move the most significant digit to before the point, and if there
3479 is something after the decimal point add it. This must come
3480 after rounding above. */
3481p[-1] =p[0];
3482if (dst -1 == p)
3483 dst--;
3484else
3485p[0] ='.';
3486
3487/* Finally output the exponent. */
3488 *dst++ = upperCase ?'P':'p';
3489
3490returnwriteSignedDecimal (dst, exponent);
3491}
3492
3493hash_codehash_value(constIEEEFloat &Arg) {
3494if (!Arg.isFiniteNonZero())
3495returnhash_combine((uint8_t)Arg.category,
3496// NaN has no sign, fix it at zero.
3497 Arg.isNaN() ? (uint8_t)0 : (uint8_t)Arg.sign,
3498 Arg.semantics->precision);
3499
3500// Normal floats need their exponent and significand hashed.
3501returnhash_combine((uint8_t)Arg.category, (uint8_t)Arg.sign,
3502 Arg.semantics->precision, Arg.exponent,
3503hash_combine_range(
3504 Arg.significandParts(),
3505 Arg.significandParts() + Arg.partCount()));
3506}
3507
3508// Conversion from APFloat to/from host float/double. It may eventually be
3509// possible to eliminate these and have everybody deal with APFloats, but that
3510// will take a while. This approach will not easily extend to long double.
3511// Current implementation requires integerPartWidth==64, which is correct at
3512// the moment but could be made more general.
3513
3514// Denormals have exponent minExponent in APFloat, but minExponent-1 in
3515// the actual IEEE respresentations. We compensate for that here.
3516
3517APInt IEEEFloat::convertF80LongDoubleAPFloatToAPInt() const{
3518assert(semantics == (constllvm::fltSemantics*)&semX87DoubleExtended);
3519assert(partCount()==2);
3520
3521uint64_t myexponent, mysignificand;
3522
3523if (isFiniteNonZero()) {
3524 myexponent = exponent+16383;//bias
3525 mysignificand = significandParts()[0];
3526if (myexponent==1 && !(mysignificand & 0x8000000000000000ULL))
3527 myexponent = 0;// denormal
3528 }elseif (category==fcZero) {
3529 myexponent = 0;
3530 mysignificand = 0;
3531 }elseif (category==fcInfinity) {
3532 myexponent = 0x7fff;
3533 mysignificand = 0x8000000000000000ULL;
3534 }else {
3535assert(category ==fcNaN &&"Unknown category");
3536 myexponent = 0x7fff;
3537 mysignificand = significandParts()[0];
3538 }
3539
3540uint64_t words[2];
3541 words[0] = mysignificand;
3542 words[1] = ((uint64_t)(sign & 1) << 15) |
3543 (myexponent & 0x7fffLL);
3544returnAPInt(80, words);
3545}
3546
3547APInt IEEEFloat::convertPPCDoubleDoubleLegacyAPFloatToAPInt() const{
3548assert(semantics == (constllvm::fltSemantics *)&semPPCDoubleDoubleLegacy);
3549assert(partCount()==2);
3550
3551uint64_t words[2];
3552opStatus fs;
3553bool losesInfo;
3554
3555// Convert number to double. To avoid spurious underflows, we re-
3556// normalize against the "double" minExponent first, and only *then*
3557// truncate the mantissa. The result of that second conversion
3558// may be inexact, but should never underflow.
3559// Declare fltSemantics before APFloat that uses it (and
3560// saves pointer to it) to ensure correct destruction order.
3561fltSemantics extendedSemantics = *semantics;
3562 extendedSemantics.minExponent =semIEEEdouble.minExponent;
3563IEEEFloat extended(*this);
3564 fs = extended.convert(extendedSemantics,rmNearestTiesToEven, &losesInfo);
3565assert(fs ==opOK && !losesInfo);
3566 (void)fs;
3567
3568IEEEFloatu(extended);
3569 fs =u.convert(semIEEEdouble,rmNearestTiesToEven, &losesInfo);
3570assert(fs ==opOK || fs ==opInexact);
3571 (void)fs;
3572 words[0] = *u.convertDoubleAPFloatToAPInt().getRawData();
3573
3574// If conversion was exact or resulted in a special case, we're done;
3575// just set the second double to zero. Otherwise, re-convert back to
3576// the extended format and compute the difference. This now should
3577// convert exactly to double.
3578if (u.isFiniteNonZero() && losesInfo) {
3579 fs =u.convert(extendedSemantics,rmNearestTiesToEven, &losesInfo);
3580assert(fs ==opOK && !losesInfo);
3581 (void)fs;
3582
3583IEEEFloatv(extended);
3584v.subtract(u,rmNearestTiesToEven);
3585 fs =v.convert(semIEEEdouble,rmNearestTiesToEven, &losesInfo);
3586assert(fs ==opOK && !losesInfo);
3587 (void)fs;
3588 words[1] = *v.convertDoubleAPFloatToAPInt().getRawData();
3589 }else {
3590 words[1] = 0;
3591 }
3592
3593returnAPInt(128, words);
3594}
3595
3596template <const fltSemantics &S>
3597APInt IEEEFloat::convertIEEEFloatToAPInt() const{
3598assert(semantics == &S);
3599constint bias =
3600 (semantics == &semFloat8E8M0FNU) ? -S.minExponent : -(S.minExponent - 1);
3601constexprunsignedint trailing_significand_bits = S.precision - 1;
3602constexprint integer_bit_part = trailing_significand_bits /integerPartWidth;
3603constexprintegerPart integer_bit =
3604integerPart{1} << (trailing_significand_bits %integerPartWidth);
3605constexpruint64_t significand_mask = integer_bit - 1;
3606constexprunsignedint exponent_bits =
3607 trailing_significand_bits ? (S.sizeInBits - 1 - trailing_significand_bits)
3608 : S.sizeInBits;
3609static_assert(exponent_bits < 64);
3610constexpruint64_t exponent_mask = (uint64_t{1} << exponent_bits) - 1;
3611
3612uint64_t myexponent;
3613 std::array<integerPart,partCountForBits(trailing_significand_bits)>
3614 mysignificand;
3615
3616if (isFiniteNonZero()) {
3617 myexponent = exponent + bias;
3618 std::copy_n(significandParts(), mysignificand.size(),
3619 mysignificand.begin());
3620if (myexponent == 1 &&
3621 !(significandParts()[integer_bit_part] & integer_bit))
3622 myexponent = 0;// denormal
3623 }elseif (category ==fcZero) {
3624if (!S.hasZero)
3625llvm_unreachable("semantics does not support zero!");
3626 myexponent = ::exponentZero(S) + bias;
3627 mysignificand.fill(0);
3628 }elseif (category ==fcInfinity) {
3629if (S.nonFiniteBehavior ==fltNonfiniteBehavior::NanOnly ||
3630 S.nonFiniteBehavior ==fltNonfiniteBehavior::FiniteOnly)
3631llvm_unreachable("semantics don't support inf!");
3632 myexponent = ::exponentInf(S) + bias;
3633 mysignificand.fill(0);
3634 }else {
3635assert(category ==fcNaN &&"Unknown category!");
3636if (S.nonFiniteBehavior ==fltNonfiniteBehavior::FiniteOnly)
3637llvm_unreachable("semantics don't support NaN!");
3638 myexponent = ::exponentNaN(S) + bias;
3639 std::copy_n(significandParts(), mysignificand.size(),
3640 mysignificand.begin());
3641 }
3642 std::array<uint64_t, (S.sizeInBits + 63) / 64> words;
3643auto words_iter =
3644 std::copy_n(mysignificand.begin(), mysignificand.size(), words.begin());
3645ifconstexpr (significand_mask != 0 || trailing_significand_bits == 0) {
3646// Clear the integer bit.
3647 words[mysignificand.size() - 1] &= significand_mask;
3648 }
3649 std::fill(words_iter, words.end(),uint64_t{0});
3650constexprsize_t last_word = words.size() - 1;
3651uint64_t shifted_sign =static_cast<uint64_t>(sign & 1)
3652 << ((S.sizeInBits - 1) % 64);
3653 words[last_word] |= shifted_sign;
3654uint64_t shifted_exponent = (myexponent & exponent_mask)
3655 << (trailing_significand_bits % 64);
3656 words[last_word] |= shifted_exponent;
3657ifconstexpr (last_word == 0) {
3658returnAPInt(S.sizeInBits, words[0]);
3659 }
3660returnAPInt(S.sizeInBits, words);
3661}
3662
3663APInt IEEEFloat::convertQuadrupleAPFloatToAPInt() const{
3664assert(partCount() == 2);
3665return convertIEEEFloatToAPInt<semIEEEquad>();
3666}
3667
3668APInt IEEEFloat::convertDoubleAPFloatToAPInt() const{
3669assert(partCount()==1);
3670return convertIEEEFloatToAPInt<semIEEEdouble>();
3671}
3672
3673APInt IEEEFloat::convertFloatAPFloatToAPInt() const{
3674assert(partCount()==1);
3675return convertIEEEFloatToAPInt<semIEEEsingle>();
3676}
3677
3678APInt IEEEFloat::convertBFloatAPFloatToAPInt() const{
3679assert(partCount() == 1);
3680return convertIEEEFloatToAPInt<semBFloat>();
3681}
3682
3683APInt IEEEFloat::convertHalfAPFloatToAPInt() const{
3684assert(partCount()==1);
3685return convertIEEEFloatToAPInt<semIEEEhalf>();
3686}
3687
3688APInt IEEEFloat::convertFloat8E5M2APFloatToAPInt() const{
3689assert(partCount() == 1);
3690return convertIEEEFloatToAPInt<semFloat8E5M2>();
3691}
3692
3693APInt IEEEFloat::convertFloat8E5M2FNUZAPFloatToAPInt() const{
3694assert(partCount() == 1);
3695return convertIEEEFloatToAPInt<semFloat8E5M2FNUZ>();
3696}
3697
3698APInt IEEEFloat::convertFloat8E4M3APFloatToAPInt() const{
3699assert(partCount() == 1);
3700return convertIEEEFloatToAPInt<semFloat8E4M3>();
3701}
3702
3703APInt IEEEFloat::convertFloat8E4M3FNAPFloatToAPInt() const{
3704assert(partCount() == 1);
3705return convertIEEEFloatToAPInt<semFloat8E4M3FN>();
3706}
3707
3708APInt IEEEFloat::convertFloat8E4M3FNUZAPFloatToAPInt() const{
3709assert(partCount() == 1);
3710return convertIEEEFloatToAPInt<semFloat8E4M3FNUZ>();
3711}
3712
3713APInt IEEEFloat::convertFloat8E4M3B11FNUZAPFloatToAPInt() const{
3714assert(partCount() == 1);
3715return convertIEEEFloatToAPInt<semFloat8E4M3B11FNUZ>();
3716}
3717
3718APInt IEEEFloat::convertFloat8E3M4APFloatToAPInt() const{
3719assert(partCount() == 1);
3720return convertIEEEFloatToAPInt<semFloat8E3M4>();
3721}
3722
3723APInt IEEEFloat::convertFloatTF32APFloatToAPInt() const{
3724assert(partCount() == 1);
3725return convertIEEEFloatToAPInt<semFloatTF32>();
3726}
3727
3728APInt IEEEFloat::convertFloat8E8M0FNUAPFloatToAPInt() const{
3729assert(partCount() == 1);
3730return convertIEEEFloatToAPInt<semFloat8E8M0FNU>();
3731}
3732
3733APInt IEEEFloat::convertFloat6E3M2FNAPFloatToAPInt() const{
3734assert(partCount() == 1);
3735return convertIEEEFloatToAPInt<semFloat6E3M2FN>();
3736}
3737
3738APInt IEEEFloat::convertFloat6E2M3FNAPFloatToAPInt() const{
3739assert(partCount() == 1);
3740return convertIEEEFloatToAPInt<semFloat6E2M3FN>();
3741}
3742
3743APInt IEEEFloat::convertFloat4E2M1FNAPFloatToAPInt() const{
3744assert(partCount() == 1);
3745return convertIEEEFloatToAPInt<semFloat4E2M1FN>();
3746}
3747
3748// This function creates an APInt that is just a bit map of the floating
3749// point constant as it would appear in memory. It is not a conversion,
3750// and treating the result as a normal integer is unlikely to be useful.
3751
3752APIntIEEEFloat::bitcastToAPInt() const{
3753if (semantics == (constllvm::fltSemantics*)&semIEEEhalf)
3754return convertHalfAPFloatToAPInt();
3755
3756if (semantics == (constllvm::fltSemantics *)&semBFloat)
3757return convertBFloatAPFloatToAPInt();
3758
3759if (semantics == (constllvm::fltSemantics*)&semIEEEsingle)
3760return convertFloatAPFloatToAPInt();
3761
3762if (semantics == (constllvm::fltSemantics*)&semIEEEdouble)
3763return convertDoubleAPFloatToAPInt();
3764
3765if (semantics == (constllvm::fltSemantics*)&semIEEEquad)
3766return convertQuadrupleAPFloatToAPInt();
3767
3768if (semantics == (constllvm::fltSemantics *)&semPPCDoubleDoubleLegacy)
3769return convertPPCDoubleDoubleLegacyAPFloatToAPInt();
3770
3771if (semantics == (constllvm::fltSemantics *)&semFloat8E5M2)
3772return convertFloat8E5M2APFloatToAPInt();
3773
3774if (semantics == (constllvm::fltSemantics *)&semFloat8E5M2FNUZ)
3775return convertFloat8E5M2FNUZAPFloatToAPInt();
3776
3777if (semantics == (constllvm::fltSemantics *)&semFloat8E4M3)
3778return convertFloat8E4M3APFloatToAPInt();
3779
3780if (semantics == (constllvm::fltSemantics *)&semFloat8E4M3FN)
3781return convertFloat8E4M3FNAPFloatToAPInt();
3782
3783if (semantics == (constllvm::fltSemantics *)&semFloat8E4M3FNUZ)
3784return convertFloat8E4M3FNUZAPFloatToAPInt();
3785
3786if (semantics == (constllvm::fltSemantics *)&semFloat8E4M3B11FNUZ)
3787return convertFloat8E4M3B11FNUZAPFloatToAPInt();
3788
3789if (semantics == (constllvm::fltSemantics *)&semFloat8E3M4)
3790return convertFloat8E3M4APFloatToAPInt();
3791
3792if (semantics == (constllvm::fltSemantics *)&semFloatTF32)
3793return convertFloatTF32APFloatToAPInt();
3794
3795if (semantics == (constllvm::fltSemantics *)&semFloat8E8M0FNU)
3796return convertFloat8E8M0FNUAPFloatToAPInt();
3797
3798if (semantics == (constllvm::fltSemantics *)&semFloat6E3M2FN)
3799return convertFloat6E3M2FNAPFloatToAPInt();
3800
3801if (semantics == (constllvm::fltSemantics *)&semFloat6E2M3FN)
3802return convertFloat6E2M3FNAPFloatToAPInt();
3803
3804if (semantics == (constllvm::fltSemantics *)&semFloat4E2M1FN)
3805return convertFloat4E2M1FNAPFloatToAPInt();
3806
3807assert(semantics == (constllvm::fltSemantics*)&semX87DoubleExtended &&
3808"unknown format!");
3809return convertF80LongDoubleAPFloatToAPInt();
3810}
3811
3812floatIEEEFloat::convertToFloat() const{
3813assert(semantics == (constllvm::fltSemantics*)&semIEEEsingle &&
3814"Float semantics are not IEEEsingle");
3815APInt api =bitcastToAPInt();
3816return api.bitsToFloat();
3817}
3818
3819doubleIEEEFloat::convertToDouble() const{
3820assert(semantics == (constllvm::fltSemantics*)&semIEEEdouble &&
3821"Float semantics are not IEEEdouble");
3822APInt api =bitcastToAPInt();
3823return api.bitsToDouble();
3824}
3825
3826#ifdef HAS_IEE754_FLOAT128
3827float128 IEEEFloat::convertToQuad() const{
3828assert(semantics == (constllvm::fltSemantics *)&semIEEEquad &&
3829"Float semantics are not IEEEquads");
3830APInt api =bitcastToAPInt();
3831return api.bitsToQuad();
3832}
3833#endif
3834
3835/// Integer bit is explicit in this format. Intel hardware (387 and later)
3836/// does not support these bit patterns:
3837/// exponent = all 1's, integer bit 0, significand 0 ("pseudoinfinity")
3838/// exponent = all 1's, integer bit 0, significand nonzero ("pseudoNaN")
3839/// exponent!=0 nor all 1's, integer bit 0 ("unnormal")
3840/// exponent = 0, integer bit 1 ("pseudodenormal")
3841/// At the moment, the first three are treated as NaNs, the last one as Normal.
3842void IEEEFloat::initFromF80LongDoubleAPInt(constAPInt &api) {
3843uint64_t i1 = api.getRawData()[0];
3844uint64_t i2 = api.getRawData()[1];
3845uint64_t myexponent = (i2 & 0x7fff);
3846uint64_t mysignificand = i1;
3847uint8_t myintegerbit = mysignificand >> 63;
3848
3849 initialize(&semX87DoubleExtended);
3850assert(partCount()==2);
3851
3852 sign =static_cast<unsignedint>(i2>>15);
3853if (myexponent == 0 && mysignificand == 0) {
3854makeZero(sign);
3855 }elseif (myexponent==0x7fff && mysignificand==0x8000000000000000ULL) {
3856makeInf(sign);
3857 }elseif ((myexponent == 0x7fff && mysignificand != 0x8000000000000000ULL) ||
3858 (myexponent != 0x7fff && myexponent != 0 && myintegerbit == 0)) {
3859 category =fcNaN;
3860 exponent = exponentNaN();
3861 significandParts()[0] = mysignificand;
3862 significandParts()[1] = 0;
3863 }else {
3864 category =fcNormal;
3865 exponent = myexponent - 16383;
3866 significandParts()[0] = mysignificand;
3867 significandParts()[1] = 0;
3868if (myexponent==0)// denormal
3869 exponent = -16382;
3870 }
3871}
3872
3873void IEEEFloat::initFromPPCDoubleDoubleLegacyAPInt(constAPInt &api) {
3874uint64_t i1 = api.getRawData()[0];
3875uint64_t i2 = api.getRawData()[1];
3876opStatus fs;
3877bool losesInfo;
3878
3879// Get the first double and convert to our format.
3880 initFromDoubleAPInt(APInt(64, i1));
3881 fs =convert(semPPCDoubleDoubleLegacy,rmNearestTiesToEven, &losesInfo);
3882assert(fs ==opOK && !losesInfo);
3883 (void)fs;
3884
3885// Unless we have a special case, add in second double.
3886if (isFiniteNonZero()) {
3887IEEEFloatv(semIEEEdouble,APInt(64, i2));
3888 fs =v.convert(semPPCDoubleDoubleLegacy,rmNearestTiesToEven, &losesInfo);
3889assert(fs ==opOK && !losesInfo);
3890 (void)fs;
3891
3892add(v,rmNearestTiesToEven);
3893 }
3894}
3895
3896// The E8M0 format has the following characteristics:
3897// It is an 8-bit unsigned format with only exponents (no actual significand).
3898// No encodings for {zero, infinities or denorms}.
3899// NaN is represented by all 1's.
3900// Bias is 127.
3901void IEEEFloat::initFromFloat8E8M0FNUAPInt(constAPInt &api) {
3902constuint64_t exponent_mask = 0xff;
3903uint64_t val = api.getRawData()[0];
3904uint64_t myexponent = (val & exponent_mask);
3905
3906 initialize(&semFloat8E8M0FNU);
3907assert(partCount() == 1);
3908
3909// This format has unsigned representation only
3910 sign = 0;
3911
3912// Set the significand
3913// This format does not have any significand but the 'Pth' precision bit is
3914// always set to 1 for consistency in APFloat's internal representation.
3915uint64_t mysignificand = 1;
3916 significandParts()[0] = mysignificand;
3917
3918// This format can either have a NaN or fcNormal
3919// All 1's i.e. 255 is a NaN
3920if (val == exponent_mask) {
3921 category =fcNaN;
3922 exponent = exponentNaN();
3923return;
3924 }
3925// Handle fcNormal...
3926 category =fcNormal;
3927 exponent = myexponent - 127;// 127 is bias
3928}
3929template <const fltSemantics &S>
3930void IEEEFloat::initFromIEEEAPInt(constAPInt &api) {
3931assert(api.getBitWidth() == S.sizeInBits);
3932constexprintegerPart integer_bit =integerPart{1}
3933 << ((S.precision - 1) %integerPartWidth);
3934constexpruint64_t significand_mask = integer_bit - 1;
3935constexprunsignedint trailing_significand_bits = S.precision - 1;
3936constexprunsignedint stored_significand_parts =
3937partCountForBits(trailing_significand_bits);
3938constexprunsignedint exponent_bits =
3939 S.sizeInBits - 1 - trailing_significand_bits;
3940static_assert(exponent_bits < 64);
3941constexpruint64_t exponent_mask = (uint64_t{1} << exponent_bits) - 1;
3942constexprint bias = -(S.minExponent - 1);
3943
3944// Copy the bits of the significand. We need to clear out the exponent and
3945// sign bit in the last word.
3946 std::array<integerPart, stored_significand_parts> mysignificand;
3947 std::copy_n(api.getRawData(), mysignificand.size(), mysignificand.begin());
3948ifconstexpr (significand_mask != 0) {
3949 mysignificand[mysignificand.size() - 1] &= significand_mask;
3950 }
3951
3952// We assume the last word holds the sign bit, the exponent, and potentially
3953// some of the trailing significand field.
3954uint64_t last_word = api.getRawData()[api.getNumWords() - 1];
3955uint64_t myexponent =
3956 (last_word >> (trailing_significand_bits % 64)) & exponent_mask;
3957
3958 initialize(&S);
3959assert(partCount() == mysignificand.size());
3960
3961 sign =static_cast<unsignedint>(last_word >> ((S.sizeInBits - 1) % 64));
3962
3963bool all_zero_significand =
3964llvm::all_of(mysignificand, [](integerPart bits) {return bits == 0; });
3965
3966boolis_zero = myexponent == 0 && all_zero_significand;
3967
3968ifconstexpr (S.nonFiniteBehavior ==fltNonfiniteBehavior::IEEE754) {
3969if (myexponent - bias == ::exponentInf(S) && all_zero_significand) {
3970makeInf(sign);
3971return;
3972 }
3973 }
3974
3975boolis_nan =false;
3976
3977ifconstexpr (S.nanEncoding ==fltNanEncoding::IEEE) {
3978is_nan = myexponent - bias == ::exponentNaN(S) && !all_zero_significand;
3979 }elseifconstexpr (S.nanEncoding ==fltNanEncoding::AllOnes) {
3980bool all_ones_significand =
3981 std::all_of(mysignificand.begin(), mysignificand.end() - 1,
3982 [](integerPart bits) { return bits == ~integerPart{0}; }) &&
3983 (!significand_mask ||
3984 mysignificand[mysignificand.size() - 1] == significand_mask);
3985is_nan = myexponent - bias == ::exponentNaN(S) && all_ones_significand;
3986 }elseifconstexpr (S.nanEncoding ==fltNanEncoding::NegativeZero) {
3987is_nan =is_zero && sign;
3988 }
3989
3990if (is_nan) {
3991 category =fcNaN;
3992 exponent =::exponentNaN(S);
3993 std::copy_n(mysignificand.begin(), mysignificand.size(),
3994 significandParts());
3995return;
3996 }
3997
3998if (is_zero) {
3999 makeZero(sign);
4000return;
4001 }
4002
4003 category =fcNormal;
4004 exponent = myexponent - bias;
4005 std::copy_n(mysignificand.begin(), mysignificand.size(), significandParts());
4006if (myexponent == 0)// denormal
4007 exponent = S.minExponent;
4008else
4009 significandParts()[mysignificand.size()-1] |= integer_bit;// integer bit
4010}
4011
4012void IEEEFloat::initFromQuadrupleAPInt(constAPInt &api) {
4013 initFromIEEEAPInt<semIEEEquad>(api);
4014}
4015
4016void IEEEFloat::initFromDoubleAPInt(constAPInt &api) {
4017 initFromIEEEAPInt<semIEEEdouble>(api);
4018}
4019
4020void IEEEFloat::initFromFloatAPInt(constAPInt &api) {
4021 initFromIEEEAPInt<semIEEEsingle>(api);
4022}
4023
4024void IEEEFloat::initFromBFloatAPInt(constAPInt &api) {
4025 initFromIEEEAPInt<semBFloat>(api);
4026}
4027
4028void IEEEFloat::initFromHalfAPInt(constAPInt &api) {
4029 initFromIEEEAPInt<semIEEEhalf>(api);
4030}
4031
4032void IEEEFloat::initFromFloat8E5M2APInt(constAPInt &api) {
4033 initFromIEEEAPInt<semFloat8E5M2>(api);
4034}
4035
4036void IEEEFloat::initFromFloat8E5M2FNUZAPInt(constAPInt &api) {
4037 initFromIEEEAPInt<semFloat8E5M2FNUZ>(api);
4038}
4039
4040void IEEEFloat::initFromFloat8E4M3APInt(constAPInt &api) {
4041 initFromIEEEAPInt<semFloat8E4M3>(api);
4042}
4043
4044void IEEEFloat::initFromFloat8E4M3FNAPInt(constAPInt &api) {
4045 initFromIEEEAPInt<semFloat8E4M3FN>(api);
4046}
4047
4048void IEEEFloat::initFromFloat8E4M3FNUZAPInt(constAPInt &api) {
4049 initFromIEEEAPInt<semFloat8E4M3FNUZ>(api);
4050}
4051
4052void IEEEFloat::initFromFloat8E4M3B11FNUZAPInt(constAPInt &api) {
4053 initFromIEEEAPInt<semFloat8E4M3B11FNUZ>(api);
4054}
4055
4056void IEEEFloat::initFromFloat8E3M4APInt(constAPInt &api) {
4057 initFromIEEEAPInt<semFloat8E3M4>(api);
4058}
4059
4060void IEEEFloat::initFromFloatTF32APInt(constAPInt &api) {
4061 initFromIEEEAPInt<semFloatTF32>(api);
4062}
4063
4064void IEEEFloat::initFromFloat6E3M2FNAPInt(constAPInt &api) {
4065 initFromIEEEAPInt<semFloat6E3M2FN>(api);
4066}
4067
4068void IEEEFloat::initFromFloat6E2M3FNAPInt(constAPInt &api) {
4069 initFromIEEEAPInt<semFloat6E2M3FN>(api);
4070}
4071
4072void IEEEFloat::initFromFloat4E2M1FNAPInt(constAPInt &api) {
4073 initFromIEEEAPInt<semFloat4E2M1FN>(api);
4074}
4075
4076/// Treat api as containing the bits of a floating point number.
4077void IEEEFloat::initFromAPInt(constfltSemantics *Sem,constAPInt &api) {
4078assert(api.getBitWidth() == Sem->sizeInBits);
4079if (Sem == &semIEEEhalf)
4080return initFromHalfAPInt(api);
4081if (Sem == &semBFloat)
4082return initFromBFloatAPInt(api);
4083if (Sem == &semIEEEsingle)
4084return initFromFloatAPInt(api);
4085if (Sem == &semIEEEdouble)
4086return initFromDoubleAPInt(api);
4087if (Sem == &semX87DoubleExtended)
4088return initFromF80LongDoubleAPInt(api);
4089if (Sem == &semIEEEquad)
4090return initFromQuadrupleAPInt(api);
4091if (Sem == &semPPCDoubleDoubleLegacy)
4092return initFromPPCDoubleDoubleLegacyAPInt(api);
4093if (Sem == &semFloat8E5M2)
4094return initFromFloat8E5M2APInt(api);
4095if (Sem == &semFloat8E5M2FNUZ)
4096return initFromFloat8E5M2FNUZAPInt(api);
4097if (Sem == &semFloat8E4M3)
4098return initFromFloat8E4M3APInt(api);
4099if (Sem == &semFloat8E4M3FN)
4100return initFromFloat8E4M3FNAPInt(api);
4101if (Sem == &semFloat8E4M3FNUZ)
4102return initFromFloat8E4M3FNUZAPInt(api);
4103if (Sem == &semFloat8E4M3B11FNUZ)
4104return initFromFloat8E4M3B11FNUZAPInt(api);
4105if (Sem == &semFloat8E3M4)
4106return initFromFloat8E3M4APInt(api);
4107if (Sem == &semFloatTF32)
4108return initFromFloatTF32APInt(api);
4109if (Sem == &semFloat8E8M0FNU)
4110return initFromFloat8E8M0FNUAPInt(api);
4111if (Sem == &semFloat6E3M2FN)
4112return initFromFloat6E3M2FNAPInt(api);
4113if (Sem == &semFloat6E2M3FN)
4114return initFromFloat6E2M3FNAPInt(api);
4115if (Sem == &semFloat4E2M1FN)
4116return initFromFloat4E2M1FNAPInt(api);
4117
4118llvm_unreachable("unsupported semantics");
4119}
4120
4121/// Make this number the largest magnitude normal number in the given
4122/// semantics.
4123void IEEEFloat::makeLargest(bool Negative) {
4124if (Negative && !semantics->hasSignedRepr)
4125llvm_unreachable(
4126"This floating point format does not support signed values");
4127// We want (in interchange format):
4128// sign = {Negative}
4129// exponent = 1..10
4130// significand = 1..1
4131 category =fcNormal;
4132 sign = Negative;
4133 exponent = semantics->maxExponent;
4134
4135// Use memset to set all but the highest integerPart to all ones.
4136integerPart *significand = significandParts();
4137unsigned PartCount = partCount();
4138 memset(significand, 0xFF,sizeof(integerPart)*(PartCount - 1));
4139
4140// Set the high integerPart especially setting all unused top bits for
4141// internal consistency.
4142constunsigned NumUnusedHighBits =
4143 PartCount*integerPartWidth - semantics->precision;
4144 significand[PartCount - 1] = (NumUnusedHighBits < integerPartWidth)
4145 ? (~integerPart(0) >> NumUnusedHighBits)
4146 : 0;
4147if (semantics->nonFiniteBehavior ==fltNonfiniteBehavior::NanOnly &&
4148 semantics->nanEncoding ==fltNanEncoding::AllOnes &&
4149 (semantics->precision > 1))
4150 significand[0] &= ~integerPart(1);
4151}
4152
4153/// Make this number the smallest magnitude denormal number in the given
4154/// semantics.
4155void IEEEFloat::makeSmallest(bool Negative) {
4156if (Negative && !semantics->hasSignedRepr)
4157llvm_unreachable(
4158"This floating point format does not support signed values");
4159// We want (in interchange format):
4160// sign = {Negative}
4161// exponent = 0..0
4162// significand = 0..01
4163 category =fcNormal;
4164 sign = Negative;
4165 exponent = semantics->minExponent;
4166APInt::tcSet(significandParts(), 1, partCount());
4167}
4168
4169void IEEEFloat::makeSmallestNormalized(bool Negative) {
4170if (Negative && !semantics->hasSignedRepr)
4171llvm_unreachable(
4172"This floating point format does not support signed values");
4173// We want (in interchange format):
4174// sign = {Negative}
4175// exponent = 0..0
4176// significand = 10..0
4177
4178 category =fcNormal;
4179 zeroSignificand();
4180 sign = Negative;
4181 exponent = semantics->minExponent;
4182APInt::tcSetBit(significandParts(), semantics->precision - 1);
4183}
4184
4185IEEEFloat::IEEEFloat(constfltSemantics &Sem,constAPInt &API) {
4186 initFromAPInt(&Sem, API);
4187}
4188
4189IEEEFloat::IEEEFloat(float f) {
4190 initFromAPInt(&semIEEEsingle,APInt::floatToBits(f));
4191}
4192
4193IEEEFloat::IEEEFloat(double d) {
4194 initFromAPInt(&semIEEEdouble,APInt::doubleToBits(d));
4195}
4196
4197namespace{
4198void append(SmallVectorImpl<char> &Buffer,StringRef Str) {
4199 Buffer.append(Str.begin(), Str.end());
4200 }
4201
4202 /// Removes data from the given significand until it is no more
4203 /// precise than is required for the desired precision.
4204void AdjustToPrecision(APInt &significand,
4205int &exp,unsigned FormatPrecision) {
4206unsigned bits = significand.getActiveBits();
4207
4208// 196/59 is a very slight overestimate of lg_2(10).
4209unsigned bitsRequired = (FormatPrecision * 196 + 58) / 59;
4210
4211if (bits <= bitsRequired)return;
4212
4213unsigned tensRemovable = (bits - bitsRequired) * 59 / 196;
4214if (!tensRemovable)return;
4215
4216 exp += tensRemovable;
4217
4218APInt divisor(significand.getBitWidth(), 1);
4219APInt powten(significand.getBitWidth(), 10);
4220while (true) {
4221if (tensRemovable & 1)
4222 divisor *= powten;
4223 tensRemovable >>= 1;
4224if (!tensRemovable)break;
4225 powten *= powten;
4226 }
4227
4228 significand = significand.udiv(divisor);
4229
4230// Truncate the significand down to its active bit count.
4231 significand = significand.trunc(significand.getActiveBits());
4232 }
4233
4234
4235void AdjustToPrecision(SmallVectorImpl<char> &buffer,
4236int &exp,unsigned FormatPrecision) {
4237unsignedN = buffer.size();
4238if (N <= FormatPrecision)return;
4239
4240// The most significant figures are the last ones in the buffer.
4241unsigned FirstSignificant =N - FormatPrecision;
4242
4243// Round.
4244// FIXME: this probably shouldn't use 'round half up'.
4245
4246// Rounding down is just a truncation, except we also want to drop
4247// trailing zeros from the new result.
4248if (buffer[FirstSignificant - 1] <'5') {
4249while (FirstSignificant <N && buffer[FirstSignificant] =='0')
4250 FirstSignificant++;
4251
4252 exp += FirstSignificant;
4253 buffer.erase(&buffer[0], &buffer[FirstSignificant]);
4254return;
4255 }
4256
4257// Rounding up requires a decimal add-with-carry. If we continue
4258// the carry, the newly-introduced zeros will just be truncated.
4259for (unsignedI = FirstSignificant;I !=N; ++I) {
4260if (buffer[I] =='9') {
4261 FirstSignificant++;
4262 }else {
4263 buffer[I]++;
4264break;
4265 }
4266 }
4267
4268// If we carried through, we have exactly one digit of precision.
4269if (FirstSignificant ==N) {
4270 exp += FirstSignificant;
4271 buffer.clear();
4272 buffer.push_back('1');
4273return;
4274 }
4275
4276 exp += FirstSignificant;
4277 buffer.erase(&buffer[0], &buffer[FirstSignificant]);
4278 }
4279
4280void toStringImpl(SmallVectorImpl<char> &Str,constboolisNeg,int exp,
4281APInt significand,unsigned FormatPrecision,
4282unsigned FormatMaxPadding,bool TruncateZero) {
4283constint semanticsPrecision = significand.getBitWidth();
4284
4285if (isNeg)
4286 Str.push_back('-');
4287
4288// Set FormatPrecision if zero. We want to do this before we
4289// truncate trailing zeros, as those are part of the precision.
4290if (!FormatPrecision) {
4291// We use enough digits so the number can be round-tripped back to an
4292// APFloat. The formula comes from "How to Print Floating-Point Numbers
4293// Accurately" by Steele and White.
4294// FIXME: Using a formula based purely on the precision is conservative;
4295// we can print fewer digits depending on the actual value being printed.
4296
4297// FormatPrecision = 2 + floor(significandBits / lg_2(10))
4298 FormatPrecision = 2 + semanticsPrecision * 59 / 196;
4299 }
4300
4301// Ignore trailing binary zeros.
4302int trailingZeros = significand.countr_zero();
4303 exp += trailingZeros;
4304 significand.lshrInPlace(trailingZeros);
4305
4306// Change the exponent from 2^e to 10^e.
4307if (exp == 0) {
4308// Nothing to do.
4309 }elseif (exp > 0) {
4310// Just shift left.
4311 significand = significand.zext(semanticsPrecision + exp);
4312 significand <<= exp;
4313 exp = 0;
4314 }else {/* exp < 0 */
4315int texp = -exp;
4316
4317// We transform this using the identity:
4318// (N)(2^-e) == (N)(5^e)(10^-e)
4319// This means we have to multiply N (the significand) by 5^e.
4320// To avoid overflow, we have to operate on numbers large
4321// enough to store N * 5^e:
4322// log2(N * 5^e) == log2(N) + e * log2(5)
4323// <= semantics->precision + e * 137 / 59
4324// (log_2(5) ~ 2.321928 < 2.322034 ~ 137/59)
4325
4326unsigned precision = semanticsPrecision + (137 * texp + 136) / 59;
4327
4328// Multiply significand by 5^e.
4329// N * 5^0101 == N * 5^(1*1) * 5^(0*2) * 5^(1*4) * 5^(0*8)
4330 significand = significand.zext(precision);
4331APInt five_to_the_i(precision, 5);
4332while (true) {
4333if (texp & 1)
4334 significand *= five_to_the_i;
4335
4336 texp >>= 1;
4337if (!texp)
4338break;
4339 five_to_the_i *= five_to_the_i;
4340 }
4341 }
4342
4343 AdjustToPrecision(significand, exp, FormatPrecision);
4344
4345SmallVector<char, 256> buffer;
4346
4347// Fill the buffer.
4348unsigned precision = significand.getBitWidth();
4349if (precision < 4) {
4350// We need enough precision to store the value 10.
4351 precision = 4;
4352 significand = significand.zext(precision);
4353 }
4354APInt ten(precision, 10);
4355APInt digit(precision, 0);
4356
4357bool inTrail =true;
4358while (significand != 0) {
4359// digit <- significand % 10
4360// significand <- significand / 10
4361APInt::udivrem(significand, ten, significand, digit);
4362
4363unsigned d = digit.getZExtValue();
4364
4365// Drop trailing zeros.
4366if (inTrail && !d)
4367 exp++;
4368else {
4369 buffer.push_back((char) ('0' + d));
4370 inTrail =false;
4371 }
4372 }
4373
4374assert(!buffer.empty() &&"no characters in buffer!");
4375
4376// Drop down to FormatPrecision.
4377// TODO: don't do more precise calculations above than are required.
4378 AdjustToPrecision(buffer, exp, FormatPrecision);
4379
4380unsigned NDigits = buffer.size();
4381
4382// Check whether we should use scientific notation.
4383bool FormatScientific;
4384if (!FormatMaxPadding)
4385 FormatScientific =true;
4386else {
4387if (exp >= 0) {
4388// 765e3 --> 765000
4389// ^^^
4390// But we shouldn't make the number look more precise than it is.
4391 FormatScientific = ((unsigned) exp > FormatMaxPadding ||
4392 NDigits + (unsigned) exp > FormatPrecision);
4393 }else {
4394// Power of the most significant digit.
4395int MSD = exp + (int) (NDigits - 1);
4396if (MSD >= 0) {
4397// 765e-2 == 7.65
4398 FormatScientific =false;
4399 }else {
4400// 765e-5 == 0.00765
4401// ^ ^^
4402 FormatScientific = ((unsigned) -MSD) > FormatMaxPadding;
4403 }
4404 }
4405 }
4406
4407// Scientific formatting is pretty straightforward.
4408if (FormatScientific) {
4409 exp += (NDigits - 1);
4410
4411 Str.push_back(buffer[NDigits-1]);
4412 Str.push_back('.');
4413if (NDigits == 1 && TruncateZero)
4414 Str.push_back('0');
4415else
4416for (unsignedI = 1;I != NDigits; ++I)
4417 Str.push_back(buffer[NDigits-1-I]);
4418// Fill with zeros up to FormatPrecision.
4419if (!TruncateZero && FormatPrecision > NDigits - 1)
4420 Str.append(FormatPrecision - NDigits + 1,'0');
4421// For !TruncateZero we use lower 'e'.
4422 Str.push_back(TruncateZero ?'E' :'e');
4423
4424 Str.push_back(exp >= 0 ?'+' :'-');
4425if (exp < 0)
4426 exp = -exp;
4427SmallVector<char, 6> expbuf;
4428do {
4429 expbuf.push_back((char) ('0' + (exp % 10)));
4430 exp /= 10;
4431 }while (exp);
4432// Exponent always at least two digits if we do not truncate zeros.
4433if (!TruncateZero && expbuf.size() < 2)
4434 expbuf.push_back('0');
4435for (unsignedI = 0, E = expbuf.size();I != E; ++I)
4436 Str.push_back(expbuf[E-1-I]);
4437return;
4438 }
4439
4440// Non-scientific, positive exponents.
4441if (exp >= 0) {
4442for (unsignedI = 0;I != NDigits; ++I)
4443 Str.push_back(buffer[NDigits-1-I]);
4444for (unsignedI = 0;I != (unsigned) exp; ++I)
4445 Str.push_back('0');
4446return;
4447 }
4448
4449// Non-scientific, negative exponents.
4450
4451// The number of digits to the left of the decimal point.
4452int NWholeDigits = exp + (int) NDigits;
4453
4454unsignedI = 0;
4455if (NWholeDigits > 0) {
4456for (;I != (unsigned) NWholeDigits; ++I)
4457 Str.push_back(buffer[NDigits-I-1]);
4458 Str.push_back('.');
4459 }else {
4460unsigned NZeros = 1 + (unsigned) -NWholeDigits;
4461
4462 Str.push_back('0');
4463 Str.push_back('.');
4464for (unsigned Z = 1;Z != NZeros; ++Z)
4465 Str.push_back('0');
4466 }
4467
4468for (;I != NDigits; ++I)
4469 Str.push_back(buffer[NDigits-I-1]);
4470
4471 }
4472}// namespace
4473
4474void IEEEFloat::toString(SmallVectorImpl<char> &Str,unsigned FormatPrecision,
4475unsigned FormatMaxPadding,bool TruncateZero) const{
4476switch (category) {
4477case fcInfinity:
4478if (isNegative())
4479return append(Str,"-Inf");
4480else
4481return append(Str,"+Inf");
4482
4483case fcNaN:return append(Str,"NaN");
4484
4485casefcZero:
4486if (isNegative())
4487 Str.push_back('-');
4488
4489if (!FormatMaxPadding) {
4490if (TruncateZero)
4491 append(Str,"0.0E+0");
4492else {
4493 append(Str,"0.0");
4494if (FormatPrecision > 1)
4495 Str.append(FormatPrecision - 1,'0');
4496 append(Str,"e+00");
4497 }
4498 }else
4499 Str.push_back('0');
4500return;
4501
4502casefcNormal:
4503break;
4504 }
4505
4506// Decompose the number into an APInt and an exponent.
4507int exp = exponent - ((int) semantics->precision - 1);
4508APInt significand(
4509 semantics->precision,
4510ArrayRef(significandParts(),partCountForBits(semantics->precision)));
4511
4512 toStringImpl(Str, isNegative(), exp, significand, FormatPrecision,
4513 FormatMaxPadding, TruncateZero);
4514
4515}
4516
4517bool IEEEFloat::getExactInverse(APFloat *inv) const{
4518// Special floats and denormals have no exact inverse.
4519if (!isFiniteNonZero())
4520returnfalse;
4521
4522// Check that the number is a power of two by making sure that only the
4523// integer bit is set in the significand.
4524if (significandLSB() != semantics->precision - 1)
4525returnfalse;
4526
4527// Get the inverse.
4528IEEEFloat reciprocal(*semantics, 1ULL);
4529if (reciprocal.divide(*this, rmNearestTiesToEven) != opOK)
4530returnfalse;
4531
4532// Avoid multiplication with a denormal, it is not safe on all platforms and
4533// may be slower than a normal division.
4534if (reciprocal.isDenormal())
4535returnfalse;
4536
4537assert(reciprocal.isFiniteNonZero() &&
4538 reciprocal.significandLSB() == reciprocal.semantics->precision - 1);
4539
4540if (inv)
4541 *inv =APFloat(reciprocal, *semantics);
4542
4543returntrue;
4544}
4545
4546int IEEEFloat::getExactLog2Abs() const{
4547if (!isFinite() ||isZero())
4548return INT_MIN;
4549
4550constintegerPart *Parts = significandParts();
4551constint PartCount =partCountForBits(semantics->precision);
4552
4553int PopCount = 0;
4554for (int i = 0; i < PartCount; ++i) {
4555 PopCount +=llvm::popcount(Parts[i]);
4556if (PopCount > 1)
4557return INT_MIN;
4558 }
4559
4560if (exponent != semantics->minExponent)
4561return exponent;
4562
4563int CountrParts = 0;
4564for (int i = 0; i < PartCount;
4565 ++i, CountrParts +=APInt::APINT_BITS_PER_WORD) {
4566if (Parts[i] != 0) {
4567return exponent - semantics->precision + CountrParts +
4568llvm::countr_zero(Parts[i]) + 1;
4569 }
4570 }
4571
4572llvm_unreachable("didn't find the set bit");
4573}
4574
4575bool IEEEFloat::isSignaling() const{
4576if (!isNaN())
4577returnfalse;
4578if (semantics->nonFiniteBehavior ==fltNonfiniteBehavior::NanOnly ||
4579 semantics->nonFiniteBehavior ==fltNonfiniteBehavior::FiniteOnly)
4580returnfalse;
4581
4582// IEEE-754R 2008 6.2.1: A signaling NaN bit string should be encoded with the
4583// first bit of the trailing significand being 0.
4584return !APInt::tcExtractBit(significandParts(), semantics->precision - 2);
4585}
4586
4587/// IEEE-754R 2008 5.3.1: nextUp/nextDown.
4588///
4589/// *NOTE* since nextDown(x) = -nextUp(-x), we only implement nextUp with
4590/// appropriate sign switching before/after the computation.
4591APFloat::opStatus IEEEFloat::next(bool nextDown) {
4592// If we are performing nextDown, swap sign so we have -x.
4593if (nextDown)
4594 changeSign();
4595
4596// Compute nextUp(x)
4597opStatus result = opOK;
4598
4599// Handle each float category separately.
4600switch (category) {
4601case fcInfinity:
4602// nextUp(+inf) = +inf
4603if (!isNegative())
4604break;
4605// nextUp(-inf) = -getLargest()
4606 makeLargest(true);
4607break;
4608case fcNaN:
4609// IEEE-754R 2008 6.2 Par 2: nextUp(sNaN) = qNaN. Set Invalid flag.
4610// IEEE-754R 2008 6.2: nextUp(qNaN) = qNaN. Must be identity so we do not
4611// change the payload.
4612if (isSignaling()) {
4613 result = opInvalidOp;
4614// For consistency, propagate the sign of the sNaN to the qNaN.
4615 makeNaN(false, isNegative(),nullptr);
4616 }
4617break;
4618casefcZero:
4619// nextUp(pm 0) = +getSmallest()
4620 makeSmallest(false);
4621break;
4622casefcNormal:
4623// nextUp(-getSmallest()) = -0
4624if (isSmallest() && isNegative()) {
4625APInt::tcSet(significandParts(), 0, partCount());
4626 category =fcZero;
4627 exponent = 0;
4628if (semantics->nanEncoding ==fltNanEncoding::NegativeZero)
4629 sign =false;
4630if (!semantics->hasZero)
4631 makeSmallestNormalized(false);
4632break;
4633 }
4634
4635if (isLargest() && !isNegative()) {
4636if (semantics->nonFiniteBehavior ==fltNonfiniteBehavior::NanOnly) {
4637// nextUp(getLargest()) == NAN
4638 makeNaN();
4639break;
4640 }elseif (semantics->nonFiniteBehavior ==
4641fltNonfiniteBehavior::FiniteOnly) {
4642// nextUp(getLargest()) == getLargest()
4643break;
4644 }else {
4645// nextUp(getLargest()) == INFINITY
4646APInt::tcSet(significandParts(), 0, partCount());
4647 category = fcInfinity;
4648 exponent = semantics->maxExponent + 1;
4649break;
4650 }
4651 }
4652
4653// nextUp(normal) == normal + inc.
4654if (isNegative()) {
4655// If we are negative, we need to decrement the significand.
4656
4657// We only cross a binade boundary that requires adjusting the exponent
4658// if:
4659// 1. exponent != semantics->minExponent. This implies we are not in the
4660// smallest binade or are dealing with denormals.
4661// 2. Our significand excluding the integral bit is all zeros.
4662bool WillCrossBinadeBoundary =
4663 exponent != semantics->minExponent && isSignificandAllZeros();
4664
4665// Decrement the significand.
4666//
4667// We always do this since:
4668// 1. If we are dealing with a non-binade decrement, by definition we
4669// just decrement the significand.
4670// 2. If we are dealing with a normal -> normal binade decrement, since
4671// we have an explicit integral bit the fact that all bits but the
4672// integral bit are zero implies that subtracting one will yield a
4673// significand with 0 integral bit and 1 in all other spots. Thus we
4674// must just adjust the exponent and set the integral bit to 1.
4675// 3. If we are dealing with a normal -> denormal binade decrement,
4676// since we set the integral bit to 0 when we represent denormals, we
4677// just decrement the significand.
4678integerPart *Parts = significandParts();
4679APInt::tcDecrement(Parts, partCount());
4680
4681if (WillCrossBinadeBoundary) {
4682// Our result is a normal number. Do the following:
4683// 1. Set the integral bit to 1.
4684// 2. Decrement the exponent.
4685APInt::tcSetBit(Parts, semantics->precision - 1);
4686 exponent--;
4687 }
4688 }else {
4689// If we are positive, we need to increment the significand.
4690
4691// We only cross a binade boundary that requires adjusting the exponent if
4692// the input is not a denormal and all of said input's significand bits
4693// are set. If all of said conditions are true: clear the significand, set
4694// the integral bit to 1, and increment the exponent. If we have a
4695// denormal always increment since moving denormals and the numbers in the
4696// smallest normal binade have the same exponent in our representation.
4697// If there are only exponents, any increment always crosses the
4698// BinadeBoundary.
4699bool WillCrossBinadeBoundary = !APFloat::hasSignificand(*semantics) ||
4700 (!isDenormal() && isSignificandAllOnes());
4701
4702if (WillCrossBinadeBoundary) {
4703integerPart *Parts = significandParts();
4704APInt::tcSet(Parts, 0, partCount());
4705APInt::tcSetBit(Parts, semantics->precision - 1);
4706assert(exponent != semantics->maxExponent &&
4707"We can not increment an exponent beyond the maxExponent allowed"
4708" by the given floating point semantics.");
4709 exponent++;
4710 }else {
4711 incrementSignificand();
4712 }
4713 }
4714break;
4715 }
4716
4717// If we are performing nextDown, swap sign so we have -nextUp(-x)
4718if (nextDown)
4719 changeSign();
4720
4721return result;
4722}
4723
4724APFloatBase::ExponentType IEEEFloat::exponentNaN() const{
4725 return ::exponentNaN(*semantics);
4726}
4727
4728APFloatBase::ExponentType IEEEFloat::exponentInf() const{
4729 return ::exponentInf(*semantics);
4730}
4731
4732APFloatBase::ExponentType IEEEFloat::exponentZero() const{
4733 return ::exponentZero(*semantics);
4734}
4735
4736void IEEEFloat::makeInf(bool Negative) {
4737if (semantics->nonFiniteBehavior ==fltNonfiniteBehavior::FiniteOnly)
4738llvm_unreachable("This floating point format does not support Inf");
4739
4740if (semantics->nonFiniteBehavior ==fltNonfiniteBehavior::NanOnly) {
4741// There is no Inf, so make NaN instead.
4742 makeNaN(false, Negative);
4743return;
4744 }
4745 category = fcInfinity;
4746 sign = Negative;
4747 exponent =exponentInf();
4748APInt::tcSet(significandParts(), 0, partCount());
4749}
4750
4751void IEEEFloat::makeZero(bool Negative) {
4752if (!semantics->hasZero)
4753llvm_unreachable("This floating point format does not support Zero");
4754
4755 category =fcZero;
4756 sign = Negative;
4757if (semantics->nanEncoding ==fltNanEncoding::NegativeZero) {
4758// Merge negative zero to positive because 0b10000...000 is used for NaN
4759 sign =false;
4760 }
4761 exponent =exponentZero();
4762APInt::tcSet(significandParts(), 0, partCount());
4763}
4764
4765void IEEEFloat::makeQuiet() {
4766assert(isNaN());
4767if (semantics->nonFiniteBehavior !=fltNonfiniteBehavior::NanOnly)
4768APInt::tcSetBit(significandParts(), semantics->precision - 2);
4769}
4770
4771intilogb(constIEEEFloat &Arg) {
4772if (Arg.isNaN())
4773returnAPFloat::IEK_NaN;
4774if (Arg.isZero())
4775returnAPFloat::IEK_Zero;
4776if (Arg.isInfinity())
4777returnAPFloat::IEK_Inf;
4778if (!Arg.isDenormal())
4779return Arg.exponent;
4780
4781IEEEFloat Normalized(Arg);
4782int SignificandBits = Arg.getSemantics().precision - 1;
4783
4784 Normalized.exponent += SignificandBits;
4785 Normalized.normalize(APFloat::rmNearestTiesToEven,lfExactlyZero);
4786return Normalized.exponent - SignificandBits;
4787}
4788
4789IEEEFloatscalbn(IEEEFloatX,int Exp,roundingModeRoundingMode) {
4790auto MaxExp =X.getSemantics().maxExponent;
4791auto MinExp =X.getSemantics().minExponent;
4792
4793// If Exp is wildly out-of-scale, simply adding it to X.exponent will
4794// overflow; clamp it to a safe range before adding, but ensure that the range
4795// is large enough that the clamp does not change the result. The range we
4796// need to support is the difference between the largest possible exponent and
4797// the normalized exponent of half the smallest denormal.
4798
4799int SignificandBits =X.getSemantics().precision - 1;
4800int MaxIncrement = MaxExp - (MinExp - SignificandBits) + 1;
4801
4802// Clamp to one past the range ends to let normalize handle overlflow.
4803X.exponent += std::clamp(Exp, -MaxIncrement - 1, MaxIncrement);
4804X.normalize(RoundingMode,lfExactlyZero);
4805if (X.isNaN())
4806X.makeQuiet();
4807returnX;
4808}
4809
4810IEEEFloatfrexp(constIEEEFloat &Val,int &Exp,roundingMode RM) {
4811 Exp =ilogb(Val);
4812
4813// Quiet signalling nans.
4814if (Exp ==APFloat::IEK_NaN) {
4815IEEEFloatQuiet(Val);
4816Quiet.makeQuiet();
4817returnQuiet;
4818 }
4819
4820if (Exp ==APFloat::IEK_Inf)
4821return Val;
4822
4823// 1 is added because frexp is defined to return a normalized fraction in
4824// +/-[0.5, 1.0), rather than the usual +/-[1.0, 2.0).
4825 Exp = Exp ==APFloat::IEK_Zero ? 0 : Exp + 1;
4826returnscalbn(Val, -Exp, RM);
4827}
4828
4829DoubleAPFloat::DoubleAPFloat(constfltSemantics &S)
4830 : Semantics(&S),
4831 Floats(newAPFloat[2]{APFloat(semIEEEdouble),APFloat(semIEEEdouble)}) {
4832assert(Semantics == &semPPCDoubleDouble);
4833}
4834
4835DoubleAPFloat::DoubleAPFloat(constfltSemantics &S,uninitializedTag)
4836 : Semantics(&S),
4837 Floats(newAPFloat[2]{APFloat(semIEEEdouble,uninitialized),
4838APFloat(semIEEEdouble,uninitialized)}) {
4839assert(Semantics == &semPPCDoubleDouble);
4840}
4841
4842DoubleAPFloat::DoubleAPFloat(constfltSemantics &S,integerPartI)
4843 : Semantics(&S), Floats(newAPFloat[2]{APFloat(semIEEEdouble,I),
4844APFloat(semIEEEdouble)}) {
4845assert(Semantics == &semPPCDoubleDouble);
4846}
4847
4848DoubleAPFloat::DoubleAPFloat(constfltSemantics &S,constAPInt &I)
4849 : Semantics(&S),
4850 Floats(newAPFloat[2]{
4851APFloat(semIEEEdouble,APInt(64,I.getRawData()[0])),
4852APFloat(semIEEEdouble,APInt(64,I.getRawData()[1]))}) {
4853assert(Semantics == &semPPCDoubleDouble);
4854}
4855
4856DoubleAPFloat::DoubleAPFloat(constfltSemantics &S,APFloat &&First,
4857APFloat &&Second)
4858 : Semantics(&S),
4859 Floats(newAPFloat[2]{std::move(First), std::move(Second)}) {
4860assert(Semantics == &semPPCDoubleDouble);
4861assert(&Floats[0].getSemantics() == &semIEEEdouble);
4862assert(&Floats[1].getSemantics() == &semIEEEdouble);
4863}
4864
4865DoubleAPFloat::DoubleAPFloat(constDoubleAPFloat &RHS)
4866 : Semantics(RHS.Semantics),
4867 Floats(RHS.Floats ? newAPFloat[2]{APFloat(RHS.Floats[0]),
4868APFloat(RHS.Floats[1])}
4869 :nullptr) {
4870assert(Semantics == &semPPCDoubleDouble);
4871}
4872
4873DoubleAPFloat::DoubleAPFloat(DoubleAPFloat &&RHS)
4874 : Semantics(RHS.Semantics), Floats(std::move(RHS.Floats)) {
4875RHS.Semantics = &semBogus;
4876assert(Semantics == &semPPCDoubleDouble);
4877}
4878
4879DoubleAPFloat &DoubleAPFloat::operator=(constDoubleAPFloat &RHS) {
4880if (Semantics ==RHS.Semantics &&RHS.Floats) {
4881 Floats[0] =RHS.Floats[0];
4882 Floats[1] =RHS.Floats[1];
4883 }elseif (this != &RHS) {
4884 this->~DoubleAPFloat();
4885new (this)DoubleAPFloat(RHS);
4886 }
4887return *this;
4888}
4889
4890// Implement addition, subtraction, multiplication and division based on:
4891// "Software for Doubled-Precision Floating-Point Computations",
4892// by Seppo Linnainmaa, ACM TOMS vol 7 no 3, September 1981, pages 272-283.
4893APFloat::opStatus DoubleAPFloat::addImpl(constAPFloat &a,constAPFloat &aa,
4894constAPFloat &c,constAPFloat &cc,
4895roundingMode RM) {
4896intStatus =opOK;
4897APFloat z = a;
4898Status |= z.add(c, RM);
4899if (!z.isFinite()) {
4900if (!z.isInfinity()) {
4901 Floats[0] = std::move(z);
4902 Floats[1].makeZero(/* Neg = */false);
4903return (opStatus)Status;
4904 }
4905Status =opOK;
4906auto AComparedToC = a.compareAbsoluteValue(c);
4907 z = cc;
4908Status |= z.add(aa, RM);
4909if (AComparedToC ==APFloat::cmpGreaterThan) {
4910// z = cc + aa + c + a;
4911Status |= z.add(c, RM);
4912Status |= z.add(a, RM);
4913 }else {
4914// z = cc + aa + a + c;
4915Status |= z.add(a, RM);
4916Status |= z.add(c, RM);
4917 }
4918if (!z.isFinite()) {
4919 Floats[0] = std::move(z);
4920 Floats[1].makeZero(/* Neg = */false);
4921return (opStatus)Status;
4922 }
4923 Floats[0] = z;
4924APFloat zz =aa;
4925Status |= zz.add(cc, RM);
4926if (AComparedToC ==APFloat::cmpGreaterThan) {
4927// Floats[1] = a - z + c + zz;
4928 Floats[1] = a;
4929Status |= Floats[1].subtract(z, RM);
4930Status |= Floats[1].add(c, RM);
4931Status |= Floats[1].add(zz, RM);
4932 }else {
4933// Floats[1] = c - z + a + zz;
4934 Floats[1] = c;
4935Status |= Floats[1].subtract(z, RM);
4936Status |= Floats[1].add(a, RM);
4937Status |= Floats[1].add(zz, RM);
4938 }
4939 }else {
4940// q = a - z;
4941APFloatq = a;
4942Status |=q.subtract(z, RM);
4943
4944// zz = q + c + (a - (q + z)) + aa + cc;
4945// Compute a - (q + z) as -((q + z) - a) to avoid temporary copies.
4946auto zz =q;
4947Status |= zz.add(c, RM);
4948Status |=q.add(z, RM);
4949Status |=q.subtract(a, RM);
4950q.changeSign();
4951Status |= zz.add(q, RM);
4952Status |= zz.add(aa, RM);
4953Status |= zz.add(cc, RM);
4954if (zz.isZero() && !zz.isNegative()) {
4955 Floats[0] = std::move(z);
4956 Floats[1].makeZero(/* Neg = */false);
4957returnopOK;
4958 }
4959 Floats[0] = z;
4960Status |= Floats[0].add(zz, RM);
4961if (!Floats[0].isFinite()) {
4962 Floats[1].makeZero(/* Neg = */false);
4963return (opStatus)Status;
4964 }
4965 Floats[1] = std::move(z);
4966Status |= Floats[1].subtract(Floats[0], RM);
4967Status |= Floats[1].add(zz, RM);
4968 }
4969return (opStatus)Status;
4970}
4971
4972APFloat::opStatus DoubleAPFloat::addWithSpecial(const DoubleAPFloat &LHS,
4973const DoubleAPFloat &RHS,
4974 DoubleAPFloat &Out,
4975roundingMode RM) {
4976if (LHS.getCategory() ==fcNaN) {
4977 Out =LHS;
4978returnopOK;
4979 }
4980if (RHS.getCategory() ==fcNaN) {
4981 Out =RHS;
4982returnopOK;
4983 }
4984if (LHS.getCategory() ==fcZero) {
4985 Out =RHS;
4986returnopOK;
4987 }
4988if (RHS.getCategory() ==fcZero) {
4989 Out =LHS;
4990returnopOK;
4991 }
4992if (LHS.getCategory() ==fcInfinity &&RHS.getCategory() ==fcInfinity &&
4993LHS.isNegative() !=RHS.isNegative()) {
4994 Out.makeNaN(false, Out.isNegative(),nullptr);
4995returnopInvalidOp;
4996 }
4997if (LHS.getCategory() ==fcInfinity) {
4998 Out =LHS;
4999returnopOK;
5000 }
5001if (RHS.getCategory() ==fcInfinity) {
5002 Out =RHS;
5003returnopOK;
5004 }
5005assert(LHS.getCategory() ==fcNormal &&RHS.getCategory() ==fcNormal);
5006
5007APFloatA(LHS.Floats[0]), AA(LHS.Floats[1]),C(RHS.Floats[0]),
5008CC(RHS.Floats[1]);
5009assert(&A.getSemantics() == &semIEEEdouble);
5010assert(&AA.getSemantics() == &semIEEEdouble);
5011assert(&C.getSemantics() == &semIEEEdouble);
5012assert(&CC.getSemantics() == &semIEEEdouble);
5013assert(&Out.Floats[0].getSemantics() == &semIEEEdouble);
5014assert(&Out.Floats[1].getSemantics() == &semIEEEdouble);
5015return Out.addImpl(A, AA,C,CC, RM);
5016}
5017
5018APFloat::opStatusDoubleAPFloat::add(constDoubleAPFloat &RHS,
5019roundingMode RM) {
5020return addWithSpecial(*this,RHS, *this, RM);
5021}
5022
5023APFloat::opStatusDoubleAPFloat::subtract(constDoubleAPFloat &RHS,
5024roundingMode RM) {
5025changeSign();
5026auto Ret =add(RHS, RM);
5027changeSign();
5028return Ret;
5029}
5030
5031APFloat::opStatusDoubleAPFloat::multiply(constDoubleAPFloat &RHS,
5032APFloat::roundingMode RM) {
5033constauto &LHS = *this;
5034auto &Out = *this;
5035/* Interesting observation: For special categories, finding the lowest
5036 common ancestor of the following layered graph gives the correct
5037 return category:
5038
5039 NaN
5040 / \
5041 Zero Inf
5042 \ /
5043 Normal
5044
5045 e.g. NaN * NaN = NaN
5046 Zero * Inf = NaN
5047 Normal * Zero = Zero
5048 Normal * Inf = Inf
5049 */
5050if (LHS.getCategory() ==fcNaN) {
5051 Out =LHS;
5052returnopOK;
5053 }
5054if (RHS.getCategory() ==fcNaN) {
5055 Out =RHS;
5056returnopOK;
5057 }
5058if ((LHS.getCategory() ==fcZero &&RHS.getCategory() ==fcInfinity) ||
5059 (LHS.getCategory() ==fcInfinity &&RHS.getCategory() ==fcZero)) {
5060 Out.makeNaN(false,false,nullptr);
5061returnopOK;
5062 }
5063if (LHS.getCategory() ==fcZero ||LHS.getCategory() ==fcInfinity) {
5064 Out =LHS;
5065returnopOK;
5066 }
5067if (RHS.getCategory() ==fcZero ||RHS.getCategory() ==fcInfinity) {
5068 Out =RHS;
5069returnopOK;
5070 }
5071assert(LHS.getCategory() ==fcNormal &&RHS.getCategory() ==fcNormal &&
5072"Special cases not handled exhaustively");
5073
5074intStatus =opOK;
5075APFloatA = Floats[0],B = Floats[1],C =RHS.Floats[0],D =RHS.Floats[1];
5076// t = a * c
5077APFloatT =A;
5078Status |=T.multiply(C, RM);
5079if (!T.isFiniteNonZero()) {
5080 Floats[0] =T;
5081 Floats[1].makeZero(/* Neg = */false);
5082return (opStatus)Status;
5083 }
5084
5085// tau = fmsub(a, c, t), that is -fmadd(-a, c, t).
5086APFloat Tau =A;
5087T.changeSign();
5088Status |= Tau.fusedMultiplyAdd(C,T, RM);
5089T.changeSign();
5090 {
5091// v = a * d
5092APFloat V =A;
5093Status |= V.multiply(D, RM);
5094// w = b * c
5095APFloat W =B;
5096Status |= W.multiply(C, RM);
5097Status |= V.add(W, RM);
5098// tau += v + w
5099Status |= Tau.add(V, RM);
5100 }
5101// u = t + tau
5102APFloat U =T;
5103Status |= U.add(Tau, RM);
5104
5105 Floats[0] = U;
5106if (!U.isFinite()) {
5107 Floats[1].makeZero(/* Neg = */false);
5108 }else {
5109// Floats[1] = (t - u) + tau
5110Status |=T.subtract(U, RM);
5111Status |=T.add(Tau, RM);
5112 Floats[1] =T;
5113 }
5114return (opStatus)Status;
5115}
5116
5117APFloat::opStatusDoubleAPFloat::divide(constDoubleAPFloat &RHS,
5118APFloat::roundingMode RM) {
5119assert(Semantics == &semPPCDoubleDouble &&"Unexpected Semantics");
5120APFloat Tmp(semPPCDoubleDoubleLegacy,bitcastToAPInt());
5121auto Ret =
5122 Tmp.divide(APFloat(semPPCDoubleDoubleLegacy,RHS.bitcastToAPInt()), RM);
5123 *this =DoubleAPFloat(semPPCDoubleDouble, Tmp.bitcastToAPInt());
5124return Ret;
5125}
5126
5127APFloat::opStatusDoubleAPFloat::remainder(constDoubleAPFloat &RHS) {
5128assert(Semantics == &semPPCDoubleDouble &&"Unexpected Semantics");
5129APFloat Tmp(semPPCDoubleDoubleLegacy,bitcastToAPInt());
5130auto Ret =
5131 Tmp.remainder(APFloat(semPPCDoubleDoubleLegacy,RHS.bitcastToAPInt()));
5132 *this =DoubleAPFloat(semPPCDoubleDouble, Tmp.bitcastToAPInt());
5133return Ret;
5134}
5135
5136APFloat::opStatusDoubleAPFloat::mod(constDoubleAPFloat &RHS) {
5137assert(Semantics == &semPPCDoubleDouble &&"Unexpected Semantics");
5138APFloat Tmp(semPPCDoubleDoubleLegacy,bitcastToAPInt());
5139auto Ret = Tmp.mod(APFloat(semPPCDoubleDoubleLegacy,RHS.bitcastToAPInt()));
5140 *this =DoubleAPFloat(semPPCDoubleDouble, Tmp.bitcastToAPInt());
5141return Ret;
5142}
5143
5144APFloat::opStatus
5145DoubleAPFloat::fusedMultiplyAdd(constDoubleAPFloat &Multiplicand,
5146constDoubleAPFloat &Addend,
5147APFloat::roundingMode RM) {
5148assert(Semantics == &semPPCDoubleDouble &&"Unexpected Semantics");
5149APFloat Tmp(semPPCDoubleDoubleLegacy,bitcastToAPInt());
5150auto Ret = Tmp.fusedMultiplyAdd(
5151APFloat(semPPCDoubleDoubleLegacy, Multiplicand.bitcastToAPInt()),
5152APFloat(semPPCDoubleDoubleLegacy, Addend.bitcastToAPInt()), RM);
5153 *this =DoubleAPFloat(semPPCDoubleDouble, Tmp.bitcastToAPInt());
5154return Ret;
5155}
5156
5157APFloat::opStatusDoubleAPFloat::roundToIntegral(APFloat::roundingMode RM) {
5158assert(Semantics == &semPPCDoubleDouble &&"Unexpected Semantics");
5159APFloat Tmp(semPPCDoubleDoubleLegacy,bitcastToAPInt());
5160auto Ret = Tmp.roundToIntegral(RM);
5161 *this =DoubleAPFloat(semPPCDoubleDouble, Tmp.bitcastToAPInt());
5162return Ret;
5163}
5164
5165voidDoubleAPFloat::changeSign() {
5166 Floats[0].changeSign();
5167 Floats[1].changeSign();
5168}
5169
5170APFloat::cmpResult
5171DoubleAPFloat::compareAbsoluteValue(constDoubleAPFloat &RHS) const{
5172auto Result = Floats[0].compareAbsoluteValue(RHS.Floats[0]);
5173if (Result !=cmpEqual)
5174return Result;
5175 Result = Floats[1].compareAbsoluteValue(RHS.Floats[1]);
5176if (Result ==cmpLessThan || Result ==cmpGreaterThan) {
5177auto Against = Floats[0].isNegative() ^ Floats[1].isNegative();
5178auto RHSAgainst =RHS.Floats[0].isNegative() ^RHS.Floats[1].isNegative();
5179if (Against && !RHSAgainst)
5180returncmpLessThan;
5181if (!Against && RHSAgainst)
5182returncmpGreaterThan;
5183if (!Against && !RHSAgainst)
5184return Result;
5185if (Against && RHSAgainst)
5186return (cmpResult)(cmpLessThan +cmpGreaterThan - Result);
5187 }
5188return Result;
5189}
5190
5191APFloat::fltCategoryDoubleAPFloat::getCategory() const{
5192return Floats[0].getCategory();
5193}
5194
5195boolDoubleAPFloat::isNegative() const{return Floats[0].isNegative(); }
5196
5197voidDoubleAPFloat::makeInf(bool Neg) {
5198 Floats[0].makeInf(Neg);
5199 Floats[1].makeZero(/* Neg = */false);
5200}
5201
5202voidDoubleAPFloat::makeZero(bool Neg) {
5203 Floats[0].makeZero(Neg);
5204 Floats[1].makeZero(/* Neg = */false);
5205}
5206
5207voidDoubleAPFloat::makeLargest(bool Neg) {
5208assert(Semantics == &semPPCDoubleDouble &&"Unexpected Semantics");
5209 Floats[0] =APFloat(semIEEEdouble,APInt(64, 0x7fefffffffffffffull));
5210 Floats[1] =APFloat(semIEEEdouble,APInt(64, 0x7c8ffffffffffffeull));
5211if (Neg)
5212changeSign();
5213}
5214
5215voidDoubleAPFloat::makeSmallest(bool Neg) {
5216assert(Semantics == &semPPCDoubleDouble &&"Unexpected Semantics");
5217 Floats[0].makeSmallest(Neg);
5218 Floats[1].makeZero(/* Neg = */false);
5219}
5220
5221voidDoubleAPFloat::makeSmallestNormalized(bool Neg) {
5222assert(Semantics == &semPPCDoubleDouble &&"Unexpected Semantics");
5223 Floats[0] =APFloat(semIEEEdouble,APInt(64, 0x0360000000000000ull));
5224if (Neg)
5225 Floats[0].changeSign();
5226 Floats[1].makeZero(/* Neg = */false);
5227}
5228
5229voidDoubleAPFloat::makeNaN(bool SNaN,bool Neg,constAPInt *fill) {
5230 Floats[0].makeNaN(SNaN, Neg, fill);
5231 Floats[1].makeZero(/* Neg = */false);
5232}
5233
5234APFloat::cmpResultDoubleAPFloat::compare(constDoubleAPFloat &RHS) const{
5235auto Result = Floats[0].compare(RHS.Floats[0]);
5236// |Float[0]| > |Float[1]|
5237if (Result ==APFloat::cmpEqual)
5238return Floats[1].compare(RHS.Floats[1]);
5239return Result;
5240}
5241
5242boolDoubleAPFloat::bitwiseIsEqual(constDoubleAPFloat &RHS) const{
5243return Floats[0].bitwiseIsEqual(RHS.Floats[0]) &&
5244 Floats[1].bitwiseIsEqual(RHS.Floats[1]);
5245}
5246
5247hash_codehash_value(constDoubleAPFloat &Arg) {
5248if (Arg.Floats)
5249returnhash_combine(hash_value(Arg.Floats[0]),hash_value(Arg.Floats[1]));
5250returnhash_combine(Arg.Semantics);
5251}
5252
5253APIntDoubleAPFloat::bitcastToAPInt() const{
5254assert(Semantics == &semPPCDoubleDouble &&"Unexpected Semantics");
5255uint64_tData[] = {
5256 Floats[0].bitcastToAPInt().getRawData()[0],
5257 Floats[1].bitcastToAPInt().getRawData()[0],
5258 };
5259returnAPInt(128, 2,Data);
5260}
5261
5262Expected<APFloat::opStatus>DoubleAPFloat::convertFromString(StringRef S,
5263roundingMode RM) {
5264assert(Semantics == &semPPCDoubleDouble &&"Unexpected Semantics");
5265APFloat Tmp(semPPCDoubleDoubleLegacy);
5266auto Ret = Tmp.convertFromString(S, RM);
5267 *this =DoubleAPFloat(semPPCDoubleDouble, Tmp.bitcastToAPInt());
5268return Ret;
5269}
5270
5271APFloat::opStatusDoubleAPFloat::next(bool nextDown) {
5272assert(Semantics == &semPPCDoubleDouble &&"Unexpected Semantics");
5273APFloat Tmp(semPPCDoubleDoubleLegacy,bitcastToAPInt());
5274auto Ret = Tmp.next(nextDown);
5275 *this =DoubleAPFloat(semPPCDoubleDouble, Tmp.bitcastToAPInt());
5276return Ret;
5277}
5278
5279APFloat::opStatus
5280DoubleAPFloat::convertToInteger(MutableArrayRef<integerPart> Input,
5281unsignedint Width,bool IsSigned,
5282roundingMode RM,bool *IsExact) const{
5283assert(Semantics == &semPPCDoubleDouble &&"Unexpected Semantics");
5284returnAPFloat(semPPCDoubleDoubleLegacy,bitcastToAPInt())
5285 .convertToInteger(Input, Width, IsSigned, RM, IsExact);
5286}
5287
5288APFloat::opStatusDoubleAPFloat::convertFromAPInt(constAPInt &Input,
5289bool IsSigned,
5290roundingMode RM) {
5291assert(Semantics == &semPPCDoubleDouble &&"Unexpected Semantics");
5292APFloat Tmp(semPPCDoubleDoubleLegacy);
5293auto Ret = Tmp.convertFromAPInt(Input, IsSigned, RM);
5294 *this =DoubleAPFloat(semPPCDoubleDouble, Tmp.bitcastToAPInt());
5295return Ret;
5296}
5297
5298APFloat::opStatus
5299DoubleAPFloat::convertFromSignExtendedInteger(constintegerPart *Input,
5300unsignedint InputSize,
5301bool IsSigned,roundingMode RM) {
5302assert(Semantics == &semPPCDoubleDouble &&"Unexpected Semantics");
5303APFloat Tmp(semPPCDoubleDoubleLegacy);
5304auto Ret = Tmp.convertFromSignExtendedInteger(Input, InputSize, IsSigned, RM);
5305 *this =DoubleAPFloat(semPPCDoubleDouble, Tmp.bitcastToAPInt());
5306return Ret;
5307}
5308
5309APFloat::opStatus
5310DoubleAPFloat::convertFromZeroExtendedInteger(constintegerPart *Input,
5311unsignedint InputSize,
5312bool IsSigned,roundingMode RM) {
5313assert(Semantics == &semPPCDoubleDouble &&"Unexpected Semantics");
5314APFloat Tmp(semPPCDoubleDoubleLegacy);
5315auto Ret = Tmp.convertFromZeroExtendedInteger(Input, InputSize, IsSigned, RM);
5316 *this =DoubleAPFloat(semPPCDoubleDouble, Tmp.bitcastToAPInt());
5317return Ret;
5318}
5319
5320unsignedintDoubleAPFloat::convertToHexString(char *DST,
5321unsignedint HexDigits,
5322bool UpperCase,
5323roundingMode RM) const{
5324assert(Semantics == &semPPCDoubleDouble &&"Unexpected Semantics");
5325returnAPFloat(semPPCDoubleDoubleLegacy,bitcastToAPInt())
5326 .convertToHexString(DST, HexDigits, UpperCase, RM);
5327}
5328
5329boolDoubleAPFloat::isDenormal() const{
5330returngetCategory() ==fcNormal &&
5331 (Floats[0].isDenormal() || Floats[1].isDenormal() ||
5332// (double)(Hi + Lo) == Hi defines a normal number.
5333 Floats[0] != Floats[0] + Floats[1]);
5334}
5335
5336boolDoubleAPFloat::isSmallest() const{
5337if (getCategory() !=fcNormal)
5338returnfalse;
5339DoubleAPFloat Tmp(*this);
5340 Tmp.makeSmallest(this->isNegative());
5341return Tmp.compare(*this) ==cmpEqual;
5342}
5343
5344boolDoubleAPFloat::isSmallestNormalized() const{
5345if (getCategory() !=fcNormal)
5346returnfalse;
5347
5348DoubleAPFloat Tmp(*this);
5349 Tmp.makeSmallestNormalized(this->isNegative());
5350return Tmp.compare(*this) ==cmpEqual;
5351}
5352
5353boolDoubleAPFloat::isLargest() const{
5354if (getCategory() !=fcNormal)
5355returnfalse;
5356DoubleAPFloat Tmp(*this);
5357 Tmp.makeLargest(this->isNegative());
5358return Tmp.compare(*this) ==cmpEqual;
5359}
5360
5361boolDoubleAPFloat::isInteger() const{
5362assert(Semantics == &semPPCDoubleDouble &&"Unexpected Semantics");
5363return Floats[0].isInteger() && Floats[1].isInteger();
5364}
5365
5366voidDoubleAPFloat::toString(SmallVectorImpl<char> &Str,
5367unsigned FormatPrecision,
5368unsigned FormatMaxPadding,
5369bool TruncateZero) const{
5370assert(Semantics == &semPPCDoubleDouble &&"Unexpected Semantics");
5371APFloat(semPPCDoubleDoubleLegacy,bitcastToAPInt())
5372 .toString(Str, FormatPrecision, FormatMaxPadding, TruncateZero);
5373}
5374
5375boolDoubleAPFloat::getExactInverse(APFloat *inv) const{
5376assert(Semantics == &semPPCDoubleDouble &&"Unexpected Semantics");
5377APFloat Tmp(semPPCDoubleDoubleLegacy,bitcastToAPInt());
5378if (!inv)
5379return Tmp.getExactInverse(nullptr);
5380APFloat Inv(semPPCDoubleDoubleLegacy);
5381auto Ret = Tmp.getExactInverse(&Inv);
5382 *inv =APFloat(semPPCDoubleDouble, Inv.bitcastToAPInt());
5383return Ret;
5384}
5385
5386intDoubleAPFloat::getExactLog2() const{
5387// TODO: Implement me
5388return INT_MIN;
5389}
5390
5391intDoubleAPFloat::getExactLog2Abs() const{
5392// TODO: Implement me
5393return INT_MIN;
5394}
5395
5396DoubleAPFloatscalbn(constDoubleAPFloat &Arg,int Exp,
5397APFloat::roundingMode RM) {
5398assert(Arg.Semantics == &semPPCDoubleDouble &&"Unexpected Semantics");
5399returnDoubleAPFloat(semPPCDoubleDouble,scalbn(Arg.Floats[0], Exp, RM),
5400scalbn(Arg.Floats[1], Exp, RM));
5401}
5402
5403DoubleAPFloatfrexp(constDoubleAPFloat &Arg,int &Exp,
5404APFloat::roundingMode RM) {
5405assert(Arg.Semantics == &semPPCDoubleDouble &&"Unexpected Semantics");
5406APFloatFirst =frexp(Arg.Floats[0], Exp, RM);
5407APFloat Second = Arg.Floats[1];
5408if (Arg.getCategory() ==APFloat::fcNormal)
5409 Second =scalbn(Second, -Exp, RM);
5410returnDoubleAPFloat(semPPCDoubleDouble, std::move(First), std::move(Second));
5411}
5412
5413}// namespace detail
5414
5415APFloat::Storage::Storage(IEEEFloatF,constfltSemantics &Semantics) {
5416if (usesLayout<IEEEFloat>(Semantics)) {
5417new (&IEEE) IEEEFloat(std::move(F));
5418return;
5419 }
5420if (usesLayout<DoubleAPFloat>(Semantics)) {
5421constfltSemantics& S =F.getSemantics();
5422new (&Double)
5423 DoubleAPFloat(Semantics,APFloat(std::move(F), S),
5424APFloat(semIEEEdouble));
5425return;
5426 }
5427llvm_unreachable("Unexpected semantics");
5428}
5429
5430Expected<APFloat::opStatus>APFloat::convertFromString(StringRef Str,
5431roundingMode RM) {
5432APFLOAT_DISPATCH_ON_SEMANTICS(convertFromString(Str, RM));
5433}
5434
5435hash_codehash_value(constAPFloat &Arg) {
5436if (APFloat::usesLayout<detail::IEEEFloat>(Arg.getSemantics()))
5437returnhash_value(Arg.U.IEEE);
5438if (APFloat::usesLayout<detail::DoubleAPFloat>(Arg.getSemantics()))
5439returnhash_value(Arg.U.Double);
5440llvm_unreachable("Unexpected semantics");
5441}
5442
5443APFloat::APFloat(constfltSemantics &Semantics,StringRef S)
5444 :APFloat(Semantics) {
5445auto StatusOrErr =convertFromString(S,rmNearestTiesToEven);
5446assert(StatusOrErr &&"Invalid floating point representation");
5447consumeError(StatusOrErr.takeError());
5448}
5449
5450FPClassTestAPFloat::classify() const{
5451if (isZero())
5452returnisNegative() ?fcNegZero :fcPosZero;
5453if (isNormal())
5454returnisNegative() ?fcNegNormal :fcPosNormal;
5455if (isDenormal())
5456returnisNegative() ?fcNegSubnormal :fcPosSubnormal;
5457if (isInfinity())
5458returnisNegative() ?fcNegInf :fcPosInf;
5459assert(isNaN() &&"Other class of FP constant");
5460returnisSignaling() ?fcSNan :fcQNan;
5461}
5462
5463APFloat::opStatusAPFloat::convert(constfltSemantics &ToSemantics,
5464roundingMode RM,bool *losesInfo) {
5465if (&getSemantics() == &ToSemantics) {
5466 *losesInfo =false;
5467returnopOK;
5468 }
5469if (usesLayout<IEEEFloat>(getSemantics()) &&
5470 usesLayout<IEEEFloat>(ToSemantics))
5471return U.IEEE.convert(ToSemantics, RM, losesInfo);
5472if (usesLayout<IEEEFloat>(getSemantics()) &&
5473 usesLayout<DoubleAPFloat>(ToSemantics)) {
5474assert(&ToSemantics == &semPPCDoubleDouble);
5475auto Ret = U.IEEE.convert(semPPCDoubleDoubleLegacy, RM, losesInfo);
5476 *this =APFloat(ToSemantics, U.IEEE.bitcastToAPInt());
5477return Ret;
5478 }
5479if (usesLayout<DoubleAPFloat>(getSemantics()) &&
5480 usesLayout<IEEEFloat>(ToSemantics)) {
5481auto Ret = getIEEE().convert(ToSemantics, RM, losesInfo);
5482 *this =APFloat(std::move(getIEEE()), ToSemantics);
5483return Ret;
5484 }
5485llvm_unreachable("Unexpected semantics");
5486}
5487
5488APFloatAPFloat::getAllOnesValue(constfltSemantics &Semantics) {
5489returnAPFloat(Semantics,APInt::getAllOnes(Semantics.sizeInBits));
5490}
5491
5492voidAPFloat::print(raw_ostream &OS) const{
5493SmallVector<char, 16> Buffer;
5494toString(Buffer);
5495OS << Buffer;
5496}
5497
5498#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
5499LLVM_DUMP_METHODvoidAPFloat::dump() const{
5500print(dbgs());
5501dbgs() <<'\n';
5502}
5503#endif
5504
5505voidAPFloat::Profile(FoldingSetNodeID &NID) const{
5506 NID.Add(bitcastToAPInt());
5507}
5508
5509/* Same as convertToInteger(integerPart*, ...), except the result is returned in
5510 an APSInt, whose initial bit-width and signed-ness are used to determine the
5511 precision of the conversion.
5512 */
5513APFloat::opStatusAPFloat::convertToInteger(APSInt &result,
5514roundingMode rounding_mode,
5515bool *isExact) const{
5516unsigned bitWidth = result.getBitWidth();
5517SmallVector<uint64_t, 4> parts(result.getNumWords());
5518opStatus status =convertToInteger(parts, bitWidth, result.isSigned(),
5519 rounding_mode, isExact);
5520// Keeps the original signed-ness.
5521 result =APInt(bitWidth, parts);
5522return status;
5523}
5524
5525doubleAPFloat::convertToDouble() const{
5526if (&getSemantics() == (constllvm::fltSemantics *)&semIEEEdouble)
5527return getIEEE().convertToDouble();
5528assert(isRepresentableBy(getSemantics(),semIEEEdouble) &&
5529"Float semantics is not representable by IEEEdouble");
5530APFloat Temp = *this;
5531bool LosesInfo;
5532opStatus St = Temp.convert(semIEEEdouble,rmNearestTiesToEven, &LosesInfo);
5533assert(!(St &opInexact) && !LosesInfo &&"Unexpected imprecision");
5534 (void)St;
5535return Temp.getIEEE().convertToDouble();
5536}
5537
5538#ifdef HAS_IEE754_FLOAT128
5539float128 APFloat::convertToQuad() const{
5540if (&getSemantics() == (constllvm::fltSemantics *)&semIEEEquad)
5541return getIEEE().convertToQuad();
5542assert(isRepresentableBy(getSemantics(),semIEEEquad) &&
5543"Float semantics is not representable by IEEEquad");
5544APFloat Temp = *this;
5545bool LosesInfo;
5546opStatus St = Temp.convert(semIEEEquad,rmNearestTiesToEven, &LosesInfo);
5547assert(!(St &opInexact) && !LosesInfo &&"Unexpected imprecision");
5548 (void)St;
5549return Temp.getIEEE().convertToQuad();
5550}
5551#endif
5552
5553floatAPFloat::convertToFloat() const{
5554if (&getSemantics() == (constllvm::fltSemantics *)&semIEEEsingle)
5555return getIEEE().convertToFloat();
5556assert(isRepresentableBy(getSemantics(),semIEEEsingle) &&
5557"Float semantics is not representable by IEEEsingle");
5558APFloat Temp = *this;
5559bool LosesInfo;
5560opStatus St = Temp.convert(semIEEEsingle,rmNearestTiesToEven, &LosesInfo);
5561assert(!(St &opInexact) && !LosesInfo &&"Unexpected imprecision");
5562 (void)St;
5563return Temp.getIEEE().convertToFloat();
5564}
5565
5566}// namespace llvm
5567
5568#undef APFLOAT_DISPATCH_ON_SEMANTICS
PackCategoriesIntoKey
#define PackCategoriesIntoKey(_lhs, _rhs)
A macro used to combine two fcCategory enums into one key which can be used in a switch statement to ...
Definition:APFloat.cpp:48
APFloat.h
This file declares a class to represent arbitrary precision floating point values and provide a varie...
APFLOAT_DISPATCH_ON_SEMANTICS
#define APFLOAT_DISPATCH_ON_SEMANTICS(METHOD_CALL)
Definition:APFloat.h:25
APSInt.h
This file implements the APSInt class, which is a simple class that represents an arbitrary sized int...
aa
aa
Definition:AliasAnalysis.cpp:730
ArrayRef.h
B
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
A
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
D
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
LLVM_DUMP_METHOD
#define LLVM_DUMP_METHOD
Mark debug helper function definitions like dump() that should not be stripped from debug builds.
Definition:Compiler.h:622
isNeg
static bool isNeg(Value *V)
Returns true if the operation is a negation of V, and it works for both integers and floats.
Definition:ComplexDeinterleavingPass.cpp:535
ignored
Looks at all the uses of the given value Returns the Liveness deduced from the uses of this value Adds all uses that cause the result to be MaybeLive to MaybeLiveRetUses If the result is MaybeLiveUses might be modified but its content should be ignored(since it might not be complete). DeadArgumentEliminationPass
Definition:DeadArgumentElimination.cpp:473
value
Given that RA is a live value
Definition:DeadArgumentElimination.cpp:716
Debug.h
X
static GCMetadataPrinterRegistry::Add< ErlangGCPrinter > X("erlang", "erlang-compatible garbage collector")
isSigned
static bool isSigned(unsigned int Opcode)
Definition:ExpandLargeDivRem.cpp:52
convert
expand large fp convert
Definition:ExpandLargeFpConvert.cpp:702
FloatingPointMode.h
Utilities for dealing with flags related to floating point properties and mode controls.
FoldingSet.h
This file defines a hash set that can be used to remove duplication of nodes in a graph.
Hashing.h
isZero
static bool isZero(Value *V, const DataLayout &DL, DominatorTree *DT, AssumptionCache *AC)
Definition:Lint.cpp:557
F
#define F(x, y, z)
Definition:MD5.cpp:55
I
#define I(x, y, z)
Definition:MD5.cpp:58
MathExtras.h
P
#define P(N)
if
if(PassOpts->AAPipeline)
Definition:PassBuilderBindings.cpp:64
CC
auto CC
Definition:RISCVRedundantCopyElimination.cpp:79
assert
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
STLExtras.h
This file contains some templates that are useful if you are working with the STL at all.
OS
raw_pwrite_stream & OS
Definition:SampleProfWriter.cpp:51
StringExtras.h
This file contains some functions that are useful when dealing with strings.
StringRef.h
RHS
Value * RHS
Definition:X86PartialReduction.cpp:74
LHS
Value * LHS
Definition:X86PartialReduction.cpp:73
T
char
llvm::APFloat
Definition:APFloat.h:904
llvm::APFloat::Profile
void Profile(FoldingSetNodeID &NID) const
Used to insert APFloat objects, or objects that contain APFloat objects, into FoldingSets.
Definition:APFloat.cpp:5505
llvm::APFloat::divide
opStatus divide(const APFloat &RHS, roundingMode RM)
Definition:APFloat.h:1210
llvm::APFloat::getExactInverse
bool getExactInverse(APFloat *inv) const
Definition:APFloat.h:1484
llvm::APFloat::convert
opStatus convert(const fltSemantics &ToSemantics, roundingMode RM, bool *losesInfo)
Definition:APFloat.cpp:5463
llvm::APFloat::isNegative
bool isNegative() const
Definition:APFloat.h:1445
llvm::APFloat::convertToDouble
double convertToDouble() const
Converts this APFloat to host double value.
Definition:APFloat.cpp:5525
llvm::APFloat::toString
void toString(SmallVectorImpl< char > &Str, unsigned FormatPrecision=0, unsigned FormatMaxPadding=3, bool TruncateZero=true) const
Definition:APFloat.h:1475
llvm::APFloat::isNormal
bool isNormal() const
Definition:APFloat.h:1449
llvm::APFloat::isDenormal
bool isDenormal() const
Definition:APFloat.h:1446
llvm::APFloat::add
opStatus add(const APFloat &RHS, roundingMode RM)
Definition:APFloat.h:1183
llvm::APFloat::getAllOnesValue
static APFloat getAllOnesValue(const fltSemantics &Semantics)
Returns a float which is bitcasted from an all one value int.
Definition:APFloat.cpp:5488
llvm::APFloat::getSemantics
const fltSemantics & getSemantics() const
Definition:APFloat.h:1453
llvm::APFloat::convertFromSignExtendedInteger
opStatus convertFromSignExtendedInteger(const integerPart *Input, unsigned int InputSize, bool IsSigned, roundingMode RM)
Definition:APFloat.h:1338
llvm::APFloat::isFinite
bool isFinite() const
Definition:APFloat.h:1450
llvm::APFloat::isNaN
bool isNaN() const
Definition:APFloat.h:1443
llvm::APFloat::convertFromAPInt
opStatus convertFromAPInt(const APInt &Input, bool IsSigned, roundingMode RM)
Definition:APFloat.h:1334
llvm::APFloat::convertToHexString
unsigned int convertToHexString(char *DST, unsigned int HexDigits, bool UpperCase, roundingMode RM) const
Definition:APFloat.h:1435
llvm::APFloat::convertToFloat
float convertToFloat() const
Converts this APFloat to host float value.
Definition:APFloat.cpp:5553
llvm::APFloat::isSignaling
bool isSignaling() const
Definition:APFloat.h:1447
llvm::APFloat::fusedMultiplyAdd
opStatus fusedMultiplyAdd(const APFloat &Multiplicand, const APFloat &Addend, roundingMode RM)
Definition:APFloat.h:1237
llvm::APFloat::remainder
opStatus remainder(const APFloat &RHS)
Definition:APFloat.h:1219
llvm::APFloat::isZero
bool isZero() const
Definition:APFloat.h:1441
llvm::APFloat::bitcastToAPInt
APInt bitcastToAPInt() const
Definition:APFloat.h:1351
llvm::APFloat::convertToInteger
opStatus convertToInteger(MutableArrayRef< integerPart > Input, unsigned int Width, bool IsSigned, roundingMode RM, bool *IsExact) const
Definition:APFloat.h:1326
llvm::APFloat::next
opStatus next(bool nextDown)
Definition:APFloat.h:1256
llvm::APFloat::classify
FPClassTest classify() const
Return the FPClassTest which will return true for the value.
Definition:APFloat.cpp:5450
llvm::APFloat::mod
opStatus mod(const APFloat &RHS)
Definition:APFloat.h:1228
llvm::APFloat::convertFromString
Expected< opStatus > convertFromString(StringRef, roundingMode)
Definition:APFloat.cpp:5430
llvm::APFloat::dump
void dump() const
Definition:APFloat.cpp:5499
llvm::APFloat::print
void print(raw_ostream &) const
Definition:APFloat.cpp:5492
llvm::APFloat::roundToIntegral
opStatus roundToIntegral(roundingMode RM)
Definition:APFloat.h:1250
llvm::APFloat::hasSignificand
static bool hasSignificand(const fltSemantics &Sem)
Returns true if the given semantics has actual significand.
Definition:APFloat.h:1175
llvm::APFloat::convertFromZeroExtendedInteger
opStatus convertFromZeroExtendedInteger(const integerPart *Input, unsigned int InputSize, bool IsSigned, roundingMode RM)
Definition:APFloat.h:1344
llvm::APFloat::isInfinity
bool isInfinity() const
Definition:APFloat.h:1442
llvm::APInt
Class for arbitrary precision integers.
Definition:APInt.h:78
llvm::APInt::udiv
APInt udiv(const APInt &RHS) const
Unsigned division operation.
Definition:APInt.cpp:1547
llvm::APInt::tcSetBit
static void tcSetBit(WordType *, unsigned bit)
Set the given bit of a bignum. Zero-based.
Definition:APInt.cpp:2342
llvm::APInt::getAllOnes
static APInt getAllOnes(unsigned numBits)
Return an APInt of a specified width with all bits set.
Definition:APInt.h:234
llvm::APInt::tcSet
static void tcSet(WordType *, WordType, unsigned)
Sets the least significant part of a bignum to the input value, and zeroes out higher parts.
Definition:APInt.cpp:2314
llvm::APInt::udivrem
static void udivrem(const APInt &LHS, const APInt &RHS, APInt &Quotient, APInt &Remainder)
Dual division/remainder interface.
Definition:APInt.cpp:1732
llvm::APInt::tcExtractBit
static int tcExtractBit(const WordType *, unsigned bit)
Extract the given bit of a bignum; returns 0 or 1. Zero-based.
Definition:APInt.cpp:2337
llvm::APInt::zext
APInt zext(unsigned width) const
Zero extend to a new width.
Definition:APInt.cpp:986
llvm::APInt::tcAdd
static WordType tcAdd(WordType *, const WordType *, WordType carry, unsigned)
DST += RHS + CARRY where CARRY is zero or one. Returns the carry flag.
Definition:APInt.cpp:2416
llvm::APInt::tcExtract
static void tcExtract(WordType *, unsigned dstCount, const WordType *, unsigned srcBits, unsigned srcLSB)
Copy the bit vector of width srcBITS from SRC, starting at bit srcLSB, to DST, of dstCOUNT parts,...
Definition:APInt.cpp:2386
llvm::APInt::getActiveBits
unsigned getActiveBits() const
Compute the number of active bits in the value.
Definition:APInt.h:1492
llvm::APInt::trunc
APInt trunc(unsigned width) const
Truncate to new width.
Definition:APInt.cpp:910
llvm::APInt::tcCompare
static int tcCompare(const WordType *, const WordType *, unsigned)
Comparison (unsigned) of two bignums.
Definition:APInt.cpp:2725
llvm::APInt::floatToBits
static APInt floatToBits(float V)
Converts a float to APInt bits.
Definition:APInt.h:1730
llvm::APInt::tcAssign
static void tcAssign(WordType *, const WordType *, unsigned)
Assign one bignum to another.
Definition:APInt.cpp:2322
llvm::APInt::getBitWidth
unsigned getBitWidth() const
Return the number of bits in the APInt.
Definition:APInt.h:1468
llvm::APInt::WordType
uint64_t WordType
Definition:APInt.h:80
llvm::APInt::tcShiftRight
static void tcShiftRight(WordType *, unsigned Words, unsigned Count)
Shift a bignum right Count bits.
Definition:APInt.cpp:2699
llvm::APInt::tcFullMultiply
static void tcFullMultiply(WordType *, const WordType *, const WordType *, unsigned, unsigned)
DST = LHS * RHS, where DST has width the sum of the widths of the operands.
Definition:APInt.cpp:2605
llvm::APInt::getNumWords
unsigned getNumWords() const
Get the number of words.
Definition:APInt.h:1475
llvm::APInt::isNegative
bool isNegative() const
Determine sign of this APInt.
Definition:APInt.h:329
llvm::APInt::tcClearBit
static void tcClearBit(WordType *, unsigned bit)
Clear the given bit of a bignum. Zero-based.
Definition:APInt.cpp:2347
llvm::APInt::tcDecrement
static WordType tcDecrement(WordType *dst, unsigned parts)
Decrement a bignum in-place. Return the borrow flag.
Definition:APInt.h:1892
llvm::APInt::countr_zero
unsigned countr_zero() const
Count the number of trailing zero bits.
Definition:APInt.h:1618
llvm::APInt::tcLSB
static unsigned tcLSB(const WordType *, unsigned n)
Returns the bit number of the least or most significant set bit of a number.
Definition:APInt.cpp:2353
llvm::APInt::tcShiftLeft
static void tcShiftLeft(WordType *, unsigned Words, unsigned Count)
Shift a bignum left Count bits.
Definition:APInt.cpp:2672
llvm::APInt::tcIsZero
static bool tcIsZero(const WordType *, unsigned)
Returns true if a bignum is zero, false otherwise.
Definition:APInt.cpp:2328
llvm::APInt::tcMSB
static unsigned tcMSB(const WordType *parts, unsigned n)
Returns the bit number of the most significant set bit of a number.
Definition:APInt.cpp:2366
llvm::APInt::bitsToFloat
float bitsToFloat() const
Converts APInt bits to a float.
Definition:APInt.h:1714
llvm::APInt::tcMultiplyPart
static int tcMultiplyPart(WordType *dst, const WordType *src, WordType multiplier, WordType carry, unsigned srcParts, unsigned dstParts, bool add)
DST += SRC * MULTIPLIER + PART if add is true DST = SRC * MULTIPLIER + PART if add is false.
Definition:APInt.cpp:2504
llvm::APInt::APINT_BITS_PER_WORD
static constexpr unsigned APINT_BITS_PER_WORD
Bits in a word.
Definition:APInt.h:86
llvm::APInt::tcSubtract
static WordType tcSubtract(WordType *, const WordType *, WordType carry, unsigned)
DST -= RHS + CARRY where CARRY is zero or one. Returns the carry flag.
Definition:APInt.cpp:2451
llvm::APInt::tcNegate
static void tcNegate(WordType *, unsigned)
Negate a bignum in-place.
Definition:APInt.cpp:2490
llvm::APInt::doubleToBits
static APInt doubleToBits(double V)
Converts a double to APInt bits.
Definition:APInt.h:1722
llvm::APInt::tcIncrement
static WordType tcIncrement(WordType *dst, unsigned parts)
Increment a bignum in-place. Return the carry flag.
Definition:APInt.h:1887
llvm::APInt::bitsToDouble
double bitsToDouble() const
Converts APInt bits to a double.
Definition:APInt.h:1700
llvm::APInt::getRawData
const uint64_t * getRawData() const
This function returns a pointer to the internal storage of the APInt.
Definition:APInt.h:569
llvm::APInt::getZero
static APInt getZero(unsigned numBits)
Get the '0' value for the specified bit-width.
Definition:APInt.h:200
llvm::APInt::lshrInPlace
void lshrInPlace(unsigned ShiftAmt)
Logical right-shift this APInt by ShiftAmt in place.
Definition:APInt.h:858
llvm::APSInt
An arbitrary precision integer that knows its signedness.
Definition:APSInt.h:23
llvm::APSInt::isSigned
bool isSigned() const
Definition:APSInt.h:77
llvm::ArrayRef
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition:ArrayRef.h:41
llvm::ArrayRef::size
size_t size() const
size - Get the array size.
Definition:ArrayRef.h:168
llvm::Error
Lightweight error class with error context and mandatory checking.
Definition:Error.h:160
llvm::Error::success
static ErrorSuccess success()
Create a success value.
Definition:Error.h:337
llvm::Expected
Tagged union holding either a T or a Error.
Definition:Error.h:481
llvm::FoldingSetNodeID
FoldingSetNodeID - This class is used to gather all the unique data bits of a node.
Definition:FoldingSet.h:327
llvm::FoldingSetNodeID::Add
void Add(const T &x)
Definition:FoldingSet.h:371
llvm::MutableArrayRef
MutableArrayRef - Represent a mutable reference to an array (0 or more elements consecutively in memo...
Definition:ArrayRef.h:310
llvm::MutableArrayRef::data
T * data() const
Definition:ArrayRef.h:357
llvm::SmallVectorBase::empty
bool empty() const
Definition:SmallVector.h:81
llvm::SmallVectorBase::size
size_t size() const
Definition:SmallVector.h:78
llvm::SmallVectorImpl
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
Definition:SmallVector.h:573
llvm::SmallVectorImpl::erase
iterator erase(const_iterator CI)
Definition:SmallVector.h:737
llvm::SmallVectorImpl::append
void append(ItTy in_start, ItTy in_end)
Add the specified range to the end of the SmallVector.
Definition:SmallVector.h:683
llvm::SmallVectorImpl::clear
void clear()
Definition:SmallVector.h:610
llvm::SmallVectorTemplateBase::push_back
void push_back(const T &Elt)
Definition:SmallVector.h:413
llvm::SmallVector
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition:SmallVector.h:1196
llvm::StringRef
StringRef - Represent a constant reference to a string, i.e.
Definition:StringRef.h:51
llvm::StringRef::getAsInteger
bool getAsInteger(unsigned Radix, T &Result) const
Parse the current string as an integer of the specified radix.
Definition:StringRef.h:470
llvm::StringRef::starts_with
bool starts_with(StringRef Prefix) const
Check if this string starts with the given Prefix.
Definition:StringRef.h:265
llvm::StringRef::empty
constexpr bool empty() const
empty - Check if the string is empty.
Definition:StringRef.h:147
llvm::StringRef::drop_front
StringRef drop_front(size_t N=1) const
Return a StringRef equal to 'this' but with the first N elements dropped.
Definition:StringRef.h:609
llvm::StringRef::begin
iterator begin() const
Definition:StringRef.h:116
llvm::StringRef::back
char back() const
back - Get the last character in the string.
Definition:StringRef.h:159
llvm::StringRef::slice
StringRef slice(size_t Start, size_t End) const
Return a reference to the substring from [Start, End).
Definition:StringRef.h:684
llvm::StringRef::size
constexpr size_t size() const
size - Get the string size.
Definition:StringRef.h:150
llvm::StringRef::front
char front() const
front - Get the first character in the string.
Definition:StringRef.h:153
llvm::StringRef::end
iterator end() const
Definition:StringRef.h:118
llvm::Twine
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition:Twine.h:81
llvm::detail::DoubleAPFloat
Definition:APFloat.h:804
llvm::detail::DoubleAPFloat::makeSmallestNormalized
void makeSmallestNormalized(bool Neg)
Definition:APFloat.cpp:5221
llvm::detail::DoubleAPFloat::operator=
DoubleAPFloat & operator=(const DoubleAPFloat &RHS)
Definition:APFloat.cpp:4879
llvm::detail::DoubleAPFloat::changeSign
void changeSign()
Definition:APFloat.cpp:5165
llvm::detail::DoubleAPFloat::getExactLog2
LLVM_READONLY int getExactLog2() const
Definition:APFloat.cpp:5386
llvm::detail::DoubleAPFloat::isLargest
bool isLargest() const
Definition:APFloat.cpp:5353
llvm::detail::DoubleAPFloat::remainder
opStatus remainder(const DoubleAPFloat &RHS)
Definition:APFloat.cpp:5127
llvm::detail::DoubleAPFloat::multiply
opStatus multiply(const DoubleAPFloat &RHS, roundingMode RM)
Definition:APFloat.cpp:5031
llvm::detail::DoubleAPFloat::getCategory
fltCategory getCategory() const
Definition:APFloat.cpp:5191
llvm::detail::DoubleAPFloat::bitwiseIsEqual
bool bitwiseIsEqual(const DoubleAPFloat &RHS) const
Definition:APFloat.cpp:5242
llvm::detail::DoubleAPFloat::getExactLog2Abs
LLVM_READONLY int getExactLog2Abs() const
Definition:APFloat.cpp:5391
llvm::detail::DoubleAPFloat::convertFromAPInt
opStatus convertFromAPInt(const APInt &Input, bool IsSigned, roundingMode RM)
Definition:APFloat.cpp:5288
llvm::detail::DoubleAPFloat::convertFromZeroExtendedInteger
opStatus convertFromZeroExtendedInteger(const integerPart *Input, unsigned int InputSize, bool IsSigned, roundingMode RM)
Definition:APFloat.cpp:5310
llvm::detail::DoubleAPFloat::bitcastToAPInt
APInt bitcastToAPInt() const
Definition:APFloat.cpp:5253
llvm::detail::DoubleAPFloat::getExactInverse
bool getExactInverse(APFloat *inv) const
Definition:APFloat.cpp:5375
llvm::detail::DoubleAPFloat::convertFromString
Expected< opStatus > convertFromString(StringRef, roundingMode)
Definition:APFloat.cpp:5262
llvm::detail::DoubleAPFloat::isSmallest
bool isSmallest() const
Definition:APFloat.cpp:5336
llvm::detail::DoubleAPFloat::subtract
opStatus subtract(const DoubleAPFloat &RHS, roundingMode RM)
Definition:APFloat.cpp:5023
llvm::detail::DoubleAPFloat::compareAbsoluteValue
cmpResult compareAbsoluteValue(const DoubleAPFloat &RHS) const
Definition:APFloat.cpp:5171
llvm::detail::DoubleAPFloat::isDenormal
bool isDenormal() const
Definition:APFloat.cpp:5329
llvm::detail::DoubleAPFloat::convertToInteger
opStatus convertToInteger(MutableArrayRef< integerPart > Input, unsigned int Width, bool IsSigned, roundingMode RM, bool *IsExact) const
Definition:APFloat.cpp:5280
llvm::detail::DoubleAPFloat::makeSmallest
void makeSmallest(bool Neg)
Definition:APFloat.cpp:5215
llvm::detail::DoubleAPFloat::next
opStatus next(bool nextDown)
Definition:APFloat.cpp:5271
llvm::detail::DoubleAPFloat::makeInf
void makeInf(bool Neg)
Definition:APFloat.cpp:5197
llvm::detail::DoubleAPFloat::isInteger
bool isInteger() const
Definition:APFloat.cpp:5361
llvm::detail::DoubleAPFloat::makeZero
void makeZero(bool Neg)
Definition:APFloat.cpp:5202
llvm::detail::DoubleAPFloat::divide
opStatus divide(const DoubleAPFloat &RHS, roundingMode RM)
Definition:APFloat.cpp:5117
llvm::detail::DoubleAPFloat::isSmallestNormalized
bool isSmallestNormalized() const
Definition:APFloat.cpp:5344
llvm::detail::DoubleAPFloat::mod
opStatus mod(const DoubleAPFloat &RHS)
Definition:APFloat.cpp:5136
llvm::detail::DoubleAPFloat::DoubleAPFloat
DoubleAPFloat(const fltSemantics &S)
Definition:APFloat.cpp:4829
llvm::detail::DoubleAPFloat::toString
void toString(SmallVectorImpl< char > &Str, unsigned FormatPrecision, unsigned FormatMaxPadding, bool TruncateZero=true) const
Definition:APFloat.cpp:5366
llvm::detail::DoubleAPFloat::makeLargest
void makeLargest(bool Neg)
Definition:APFloat.cpp:5207
llvm::detail::DoubleAPFloat::compare
cmpResult compare(const DoubleAPFloat &RHS) const
Definition:APFloat.cpp:5234
llvm::detail::DoubleAPFloat::roundToIntegral
opStatus roundToIntegral(roundingMode RM)
Definition:APFloat.cpp:5157
llvm::detail::DoubleAPFloat::convertFromSignExtendedInteger
opStatus convertFromSignExtendedInteger(const integerPart *Input, unsigned int InputSize, bool IsSigned, roundingMode RM)
Definition:APFloat.cpp:5299
llvm::detail::DoubleAPFloat::fusedMultiplyAdd
opStatus fusedMultiplyAdd(const DoubleAPFloat &Multiplicand, const DoubleAPFloat &Addend, roundingMode RM)
Definition:APFloat.cpp:5145
llvm::detail::DoubleAPFloat::convertToHexString
unsigned int convertToHexString(char *DST, unsigned int HexDigits, bool UpperCase, roundingMode RM) const
Definition:APFloat.cpp:5320
llvm::detail::DoubleAPFloat::isNegative
bool isNegative() const
Definition:APFloat.cpp:5195
llvm::detail::DoubleAPFloat::add
opStatus add(const DoubleAPFloat &RHS, roundingMode RM)
Definition:APFloat.cpp:5018
llvm::detail::DoubleAPFloat::makeNaN
void makeNaN(bool SNaN, bool Neg, const APInt *fill)
Definition:APFloat.cpp:5229
llvm::detail::IEEEFloat
Definition:APFloat.h:400
llvm::detail::IEEEFloat::convertToHexString
unsigned int convertToHexString(char *dst, unsigned int hexDigits, bool upperCase, roundingMode) const
Write out a hexadecimal representation of the floating point value to DST, which must be of sufficien...
Definition:APFloat.cpp:3344
llvm::detail::IEEEFloat::compareAbsoluteValue
cmpResult compareAbsoluteValue(const IEEEFloat &) const
Definition:APFloat.cpp:1532
llvm::detail::IEEEFloat::mod
opStatus mod(const IEEEFloat &)
C fmod, or llvm frem.
Definition:APFloat.cpp:2283
llvm::detail::IEEEFloat::getCategory
fltCategory getCategory() const
Definition:APFloat.h:531
llvm::detail::IEEEFloat::convertFromAPInt
opStatus convertFromAPInt(const APInt &, bool, roundingMode)
Definition:APFloat.cpp:2853
llvm::detail::IEEEFloat::isFiniteNonZero
bool isFiniteNonZero() const
Definition:APFloat.h:534
llvm::detail::IEEEFloat::needsCleanup
bool needsCleanup() const
Returns whether this instance allocated memory.
Definition:APFloat.h:418
llvm::detail::IEEEFloat::bitcastToAPInt
APInt bitcastToAPInt() const
Definition:APFloat.cpp:3752
llvm::detail::IEEEFloat::compare
cmpResult compare(const IEEEFloat &) const
IEEE comparison with another floating point number (NaNs compare unordered, 0==-0).
Definition:APFloat.cpp:2454
llvm::detail::IEEEFloat::isNegative
bool isNegative() const
IEEE-754R isSignMinus: Returns true if and only if the current value is negative.
Definition:APFloat.h:496
llvm::detail::IEEEFloat::divide
opStatus divide(const IEEEFloat &, roundingMode)
Definition:APFloat.cpp:2153
llvm::detail::IEEEFloat::isNaN
bool isNaN() const
Returns true if and only if the float is a quiet or signaling NaN.
Definition:APFloat.h:521
llvm::detail::IEEEFloat::remainder
opStatus remainder(const IEEEFloat &)
IEEE remainder.
Definition:APFloat.cpp:2173
llvm::detail::IEEEFloat::convertToDouble
double convertToDouble() const
Definition:APFloat.cpp:3819
llvm::detail::IEEEFloat::convertFromSignExtendedInteger
opStatus convertFromSignExtendedInteger(const integerPart *, unsigned int, bool, roundingMode)
Definition:APFloat.cpp:2871
llvm::detail::IEEEFloat::convertToFloat
float convertToFloat() const
Definition:APFloat.cpp:3812
llvm::detail::IEEEFloat::subtract
opStatus subtract(const IEEEFloat &, roundingMode)
Definition:APFloat.cpp:2127
llvm::detail::IEEEFloat::~IEEEFloat
~IEEEFloat()
Definition:APFloat.cpp:1211
llvm::detail::IEEEFloat::makeInf
void makeInf(bool Neg=false)
Definition:APFloat.cpp:4736
llvm::detail::IEEEFloat::convertFromZeroExtendedInteger
opStatus convertFromZeroExtendedInteger(const integerPart *, unsigned int, bool, roundingMode)
Definition:APFloat.cpp:2897
llvm::detail::IEEEFloat::isSmallestNormalized
bool isSmallestNormalized() const
Returns true if this is the smallest (by magnitude) normalized finite number in the given semantics.
Definition:APFloat.cpp:1032
llvm::detail::IEEEFloat::makeQuiet
void makeQuiet()
Definition:APFloat.cpp:4765
llvm::detail::IEEEFloat::isLargest
bool isLargest() const
Returns true if and only if the number has the largest possible finite magnitude in the current seman...
Definition:APFloat.cpp:1134
llvm::detail::IEEEFloat::add
opStatus add(const IEEEFloat &, roundingMode)
Definition:APFloat.cpp:2121
llvm::detail::IEEEFloat::isFinite
bool isFinite() const
Returns true if and only if the current value is zero, subnormal, or normal.
Definition:APFloat.h:508
llvm::detail::IEEEFloat::convertFromString
Expected< opStatus > convertFromString(StringRef, roundingMode)
Definition:APFloat.cpp:3287
llvm::detail::IEEEFloat::makeNaN
void makeNaN(bool SNaN=false, bool Neg=false, const APInt *fill=nullptr)
Definition:APFloat.cpp:921
llvm::detail::IEEEFloat::ilogb
friend int ilogb(const IEEEFloat &Arg)
Returns the exponent of the internal representation of the APFloat.
Definition:APFloat.cpp:4771
llvm::detail::IEEEFloat::multiply
opStatus multiply(const IEEEFloat &, roundingMode)
Definition:APFloat.cpp:2133
llvm::detail::IEEEFloat::roundToIntegral
opStatus roundToIntegral(roundingMode)
Definition:APFloat.cpp:2367
llvm::detail::IEEEFloat::operator=
IEEEFloat & operator=(const IEEEFloat &)
Definition:APFloat.cpp:993
llvm::detail::IEEEFloat::scalbn
friend IEEEFloat scalbn(IEEEFloat X, int Exp, roundingMode)
Returns: X * 2^Exp for integral exponents.
Definition:APFloat.cpp:4789
llvm::detail::IEEEFloat::bitwiseIsEqual
bool bitwiseIsEqual(const IEEEFloat &) const
Bitwise comparison for equality (QNaNs compare equal, 0!=-0).
Definition:APFloat.cpp:1159
llvm::detail::IEEEFloat::makeSmallestNormalized
void makeSmallestNormalized(bool Negative=false)
Returns the smallest (by magnitude) normalized finite number in the given semantics.
Definition:APFloat.cpp:4169
llvm::detail::IEEEFloat::isInteger
bool isInteger() const
Returns true if and only if the number is an exact integer.
Definition:APFloat.cpp:1151
llvm::detail::IEEEFloat::IEEEFloat
IEEEFloat(const fltSemantics &)
Definition:APFloat.cpp:1186
llvm::detail::IEEEFloat::fusedMultiplyAdd
opStatus fusedMultiplyAdd(const IEEEFloat &, const IEEEFloat &, roundingMode)
Definition:APFloat.cpp:2321
llvm::detail::IEEEFloat::isInfinity
bool isInfinity() const
IEEE-754R isInfinite(): Returns true if and only if the float is infinity.
Definition:APFloat.h:518
llvm::detail::IEEEFloat::getSemantics
const fltSemantics & getSemantics() const
Definition:APFloat.h:532
llvm::detail::IEEEFloat::isZero
bool isZero() const
Returns true if and only if the float is plus or minus zero.
Definition:APFloat.h:511
llvm::detail::IEEEFloat::isSignaling
bool isSignaling() const
Returns true if and only if the float is a signaling NaN.
Definition:APFloat.cpp:4575
llvm::detail::IEEEFloat::makeZero
void makeZero(bool Neg=false)
Definition:APFloat.cpp:4751
llvm::detail::IEEEFloat::convert
opStatus convert(const fltSemantics &, roundingMode, bool *)
IEEEFloat::convert - convert a value of one floating point type to another.
Definition:APFloat.cpp:2531
llvm::detail::IEEEFloat::changeSign
void changeSign()
Definition:APFloat.cpp:2077
llvm::detail::IEEEFloat::isDenormal
bool isDenormal() const
IEEE-754R isSubnormal(): Returns true if and only if the float is a denormal.
Definition:APFloat.cpp:1018
llvm::detail::IEEEFloat::convertToInteger
opStatus convertToInteger(MutableArrayRef< integerPart >, unsigned int, bool, roundingMode, bool *) const
Definition:APFloat.cpp:2793
llvm::detail::IEEEFloat::isSmallest
bool isSmallest() const
Returns true if and only if the number has the smallest possible non-zero magnitude in the current se...
Definition:APFloat.cpp:1024
llvm::hash_code
An opaque object representing a hash code.
Definition:Hashing.h:75
llvm::raw_ostream
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition:raw_ostream.h:52
uint64_t
uint8_t
unsigned
llvm_unreachable
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
Definition:ErrorHandling.h:143
Error.h
detail
Definition:ClauseT.h:112
false
Definition:StackSlotColoring.cpp:193
llvm::ARCCC::Z
@ Z
Definition:ARCInfo.h:41
llvm::CallingConv::C
@ C
The default llvm calling convention, compatible with C.
Definition:CallingConv.h:34
llvm::M68k::MemAddrModeKind::q
@ q
llvm::M68k::MemAddrModeKind::u
@ u
llvm::M68k::MemAddrModeKind::p
@ p
llvm::M68k::MemAddrModeKind::v
@ v
llvm::detail::opInexact
static constexpr opStatus opInexact
Definition:APFloat.h:394
llvm::detail::roundingMode
APFloatBase::roundingMode roundingMode
Definition:APFloat.h:371
llvm::detail::fcNaN
static constexpr fltCategory fcNaN
Definition:APFloat.h:396
llvm::detail::opDivByZero
static constexpr opStatus opDivByZero
Definition:APFloat.h:391
llvm::detail::opOverflow
static constexpr opStatus opOverflow
Definition:APFloat.h:392
llvm::detail::cmpLessThan
static constexpr cmpResult cmpLessThan
Definition:APFloat.h:386
llvm::detail::tcSetLeastSignificantBits
static void tcSetLeastSignificantBits(APInt::WordType *dst, unsigned parts, unsigned bits)
Definition:APFloat.cpp:1557
llvm::detail::opStatus
APFloatBase::opStatus opStatus
Definition:APFloat.h:372
llvm::detail::rmTowardPositive
static constexpr roundingMode rmTowardPositive
Definition:APFloat.h:382
llvm::detail::uninitialized
static constexpr uninitializedTag uninitialized
Definition:APFloat.h:376
llvm::detail::fcZero
static constexpr fltCategory fcZero
Definition:APFloat.h:398
llvm::detail::opOK
static constexpr opStatus opOK
Definition:APFloat.h:389
llvm::detail::cmpGreaterThan
static constexpr cmpResult cmpGreaterThan
Definition:APFloat.h:387
llvm::detail::integerPartWidth
static constexpr unsigned integerPartWidth
Definition:APFloat.h:384
llvm::detail::ExponentType
APFloatBase::ExponentType ExponentType
Definition:APFloat.h:375
llvm::detail::hash_value
hash_code hash_value(const IEEEFloat &Arg)
Definition:APFloat.cpp:3493
llvm::detail::fcNormal
static constexpr fltCategory fcNormal
Definition:APFloat.h:397
llvm::detail::opInvalidOp
static constexpr opStatus opInvalidOp
Definition:APFloat.h:390
llvm::detail::scalbn
IEEEFloat scalbn(IEEEFloat X, int Exp, roundingMode)
Definition:APFloat.cpp:4789
llvm::detail::frexp
IEEEFloat frexp(const IEEEFloat &Val, int &Exp, roundingMode RM)
Definition:APFloat.cpp:4810
llvm::detail::integerPart
APFloatBase::integerPart integerPart
Definition:APFloat.h:369
llvm::detail::cmpUnordered
static constexpr cmpResult cmpUnordered
Definition:APFloat.h:388
llvm::detail::rmTowardNegative
static constexpr roundingMode rmTowardNegative
Definition:APFloat.h:381
llvm::detail::fcInfinity
static constexpr fltCategory fcInfinity
Definition:APFloat.h:395
llvm::detail::rmNearestTiesToAway
static constexpr roundingMode rmNearestTiesToAway
Definition:APFloat.h:379
llvm::detail::rmTowardZero
static constexpr roundingMode rmTowardZero
Definition:APFloat.h:383
llvm::detail::opUnderflow
static constexpr opStatus opUnderflow
Definition:APFloat.h:393
llvm::detail::rmNearestTiesToEven
static constexpr roundingMode rmNearestTiesToEven
Definition:APFloat.h:377
llvm::detail::ilogb
int ilogb(const IEEEFloat &Arg)
Definition:APFloat.cpp:4771
llvm::detail::cmpEqual
static constexpr cmpResult cmpEqual
Definition:APFloat.h:385
llvm::pdb::Double
@ Double
Definition:PDBTypes.h:402
llvm::sys::fs::status
std::error_code status(const Twine &path, file_status &result, bool follow=true)
Get file status as if by POSIX stat().
llvm::tgtok::dot
@ dot
Definition:TGLexer.h:51
llvm
This is an optimization pass for GlobalISel generic memory operations.
Definition:AddressRanges.h:18
llvm::partAsHex
static unsigned int partAsHex(char *dst, APFloatBase::integerPart part, unsigned int count, const char *hexDigitChars)
Definition:APFloat.cpp:837
llvm::semBogus
static constexpr fltSemantics semBogus
Definition:APFloat.cpp:158
llvm::infinityL
static const char infinityL[]
Definition:APFloat.cpp:828
llvm::all_of
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
Definition:STLExtras.h:1739
llvm::ChangePrinter::Quiet
@ Quiet
llvm::hash_value
hash_code hash_value(const FixedPointSemantics &Val)
Definition:APFixedPoint.h:136
llvm::popcount
int popcount(T Value) noexcept
Count the number of set bits in a value.
Definition:bit.h:385
llvm::partCountForBits
static constexpr unsigned int partCountForBits(unsigned int bits)
Definition:APFloat.cpp:401
llvm::NaNU
static const char NaNU[]
Definition:APFloat.cpp:831
llvm::semFloat8E8M0FNU
static constexpr fltSemantics semFloat8E8M0FNU
Definition:APFloat.cpp:147
llvm::HUerrBound
static unsigned int HUerrBound(bool inexactMultiply, unsigned int HUerr1, unsigned int HUerr2)
Definition:APFloat.cpp:712
llvm::powerOf5
static unsigned int powerOf5(APFloatBase::integerPart *dst, unsigned int power)
Definition:APFloat.cpp:771
llvm::semFloat6E2M3FN
static constexpr fltSemantics semFloat6E2M3FN
Definition:APFloat.cpp:153
llvm::exponentZero
static constexpr APFloatBase::ExponentType exponentZero(const fltSemantics &semantics)
Definition:APFloat.cpp:375
llvm::totalExponent
static Expected< int > totalExponent(StringRef::iterator p, StringRef::iterator end, int exponentAdjustment)
Definition:APFloat.cpp:463
llvm::inconvertibleErrorCode
std::error_code inconvertibleErrorCode()
The value returned by this function can be returned from convertToErrorCode for Error values where no...
Definition:Error.cpp:98
llvm::semIEEEquad
static constexpr fltSemantics semIEEEquad
Definition:APFloat.cpp:134
llvm::maxPowerOfFiveExponent
const unsigned int maxPowerOfFiveExponent
Definition:APFloat.cpp:310
llvm::semFloat6E3M2FN
static constexpr fltSemantics semFloat6E3M2FN
Definition:APFloat.cpp:151
llvm::writeUnsignedDecimal
static char * writeUnsignedDecimal(char *dst, unsigned int n)
Definition:APFloat.cpp:855
llvm::semFloat8E4M3FNUZ
static constexpr fltSemantics semFloat8E4M3FNUZ
Definition:APFloat.cpp:141
llvm::maxPrecision
const unsigned int maxPrecision
Definition:APFloat.cpp:309
llvm::semIEEEdouble
static constexpr fltSemantics semIEEEdouble
Definition:APFloat.cpp:133
llvm::frexp
APFloat frexp(const APFloat &X, int &Exp, APFloat::roundingMode RM)
Equivalent of C standard library function.
Definition:APFloat.h:1526
llvm::NaNL
static const char NaNL[]
Definition:APFloat.cpp:830
llvm::countr_zero
int countr_zero(T Val)
Count number of 0's from the least significant bit to the most stopping at the first 1.
Definition:bit.h:215
llvm::semFloat8E4M3FN
static constexpr fltSemantics semFloat8E4M3FN
Definition:APFloat.cpp:139
llvm::infinityU
static const char infinityU[]
Definition:APFloat.cpp:829
llvm::lostFraction
lostFraction
Enum that represents what fraction of the LSB truncated bits of an fp number represent.
Definition:APFloat.h:49
llvm::lfMoreThanHalf
@ lfMoreThanHalf
Definition:APFloat.h:53
llvm::lfLessThanHalf
@ lfLessThanHalf
Definition:APFloat.h:51
llvm::lfExactlyHalf
@ lfExactlyHalf
Definition:APFloat.h:52
llvm::lfExactlyZero
@ lfExactlyZero
Definition:APFloat.h:50
llvm::semPPCDoubleDouble
static constexpr fltSemantics semPPCDoubleDouble
Definition:APFloat.cpp:159
llvm::interpretDecimal
static Error interpretDecimal(StringRef::iterator begin, StringRef::iterator end, decimalInfo *D)
Definition:APFloat.cpp:555
llvm::semFloat8E5M2FNUZ
static constexpr fltSemantics semFloat8E5M2FNUZ
Definition:APFloat.cpp:136
llvm::isFinite
bool isFinite(const Loop *L)
Return true if this loop can be assumed to run for a finite number of iterations.
Definition:LoopInfo.cpp:1152
llvm::FPClassTest
FPClassTest
Floating-point class tests, supported by 'is_fpclass' intrinsic.
Definition:FloatingPointMode.h:239
llvm::fcNegSubnormal
@ fcNegSubnormal
Definition:FloatingPointMode.h:246
llvm::fcPosNormal
@ fcPosNormal
Definition:FloatingPointMode.h:250
llvm::fcQNan
@ fcQNan
Definition:FloatingPointMode.h:243
llvm::fcNegZero
@ fcNegZero
Definition:FloatingPointMode.h:247
llvm::fcNegInf
@ fcNegInf
Definition:FloatingPointMode.h:244
llvm::fcPosZero
@ fcPosZero
Definition:FloatingPointMode.h:248
llvm::fcSNan
@ fcSNan
Definition:FloatingPointMode.h:242
llvm::fcNegNormal
@ fcNegNormal
Definition:FloatingPointMode.h:245
llvm::fcZero
@ fcZero
Definition:FloatingPointMode.h:257
llvm::fcPosSubnormal
@ fcPosSubnormal
Definition:FloatingPointMode.h:249
llvm::fcPosInf
@ fcPosInf
Definition:FloatingPointMode.h:251
llvm::fcNormal
@ fcNormal
Definition:FloatingPointMode.h:255
llvm::maxPowerOfFiveParts
const unsigned int maxPowerOfFiveParts
Definition:APFloat.cpp:311
llvm::semIEEEsingle
static constexpr fltSemantics semIEEEsingle
Definition:APFloat.cpp:132
llvm::scalbn
APFloat scalbn(APFloat X, int Exp, APFloat::roundingMode RM)
Definition:APFloat.h:1514
llvm::semFloat4E2M1FN
static constexpr fltSemantics semFloat4E2M1FN
Definition:APFloat.cpp:155
llvm::dbgs
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition:Debug.cpp:163
llvm::exponentNaN
static constexpr APFloatBase::ExponentType exponentNaN(const fltSemantics &semantics)
Definition:APFloat.cpp:385
llvm::createError
static Error createError(const Twine &Err)
Definition:APFloat.cpp:397
llvm::semIEEEhalf
static constexpr fltSemantics semIEEEhalf
Definition:APFloat.cpp:130
llvm::semPPCDoubleDoubleLegacy
static constexpr fltSemantics semPPCDoubleDoubleLegacy
Definition:APFloat.cpp:160
llvm::shiftRight
static lostFraction shiftRight(APFloatBase::integerPart *dst, unsigned int parts, unsigned int bits)
Definition:APFloat.cpp:678
llvm::semFloat8E5M2
static constexpr fltSemantics semFloat8E5M2
Definition:APFloat.cpp:135
llvm::IRMemLocation::First
@ First
Helpers to iterate all locations in the MemoryEffectsBase class.
llvm::hexDigitsUpper
static const char hexDigitsUpper[]
Definition:APFloat.cpp:827
llvm::instrprof_error::truncated
@ truncated
llvm::maxExponent
const unsigned int maxExponent
Definition:APFloat.cpp:308
llvm::decDigitValue
static unsigned int decDigitValue(unsigned int c)
Definition:APFloat.cpp:408
llvm::semFloat8E4M3B11FNUZ
static constexpr fltSemantics semFloat8E4M3B11FNUZ
Definition:APFloat.cpp:143
llvm::fltNonfiniteBehavior
fltNonfiniteBehavior
Definition:APFloat.cpp:57
llvm::fltNonfiniteBehavior::IEEE754
@ IEEE754
llvm::fltNonfiniteBehavior::NanOnly
@ NanOnly
llvm::fltNonfiniteBehavior::FiniteOnly
@ FiniteOnly
llvm::count
auto count(R &&Range, const E &Element)
Wrapper function around std::count to count the number of times an element Element occurs in the give...
Definition:STLExtras.h:1938
llvm::combineLostFractions
static lostFraction combineLostFractions(lostFraction moreSignificant, lostFraction lessSignificant)
Definition:APFloat.cpp:691
llvm::skipLeadingZeroesAndAnyDot
static Expected< StringRef::iterator > skipLeadingZeroesAndAnyDot(StringRef::iterator begin, StringRef::iterator end, StringRef::iterator *dot)
Definition:APFloat.cpp:515
llvm::RoundingMode
RoundingMode
Rounding mode.
Definition:FloatingPointMode.h:37
llvm::copy
OutputIt copy(R &&Range, OutputIt Out)
Definition:STLExtras.h:1841
llvm::semX87DoubleExtended
static constexpr fltSemantics semX87DoubleExtended
Definition:APFloat.cpp:157
llvm::move
OutputIt move(R &&Range, OutputIt Out)
Provide wrappers to std::move which take ranges instead of having to pass begin/end explicitly.
Definition:STLExtras.h:1873
llvm::semFloatTF32
static constexpr fltSemantics semFloatTF32
Definition:APFloat.cpp:146
llvm::exponentInf
static constexpr APFloatBase::ExponentType exponentInf(const fltSemantics &semantics)
Definition:APFloat.cpp:380
llvm::lostFractionThroughTruncation
static lostFraction lostFractionThroughTruncation(const APFloatBase::integerPart *parts, unsigned int partCount, unsigned int bits)
Definition:APFloat.cpp:656
llvm::ulpsFromBoundary
static APFloatBase::integerPart ulpsFromBoundary(const APFloatBase::integerPart *parts, unsigned int bits, bool isNearest)
Definition:APFloat.cpp:726
llvm::writeSignedDecimal
static char * writeSignedDecimal(char *dst, int value)
Definition:APFloat.cpp:873
llvm::hash_combine
hash_code hash_combine(const Ts &...args)
Combine values into a single hash_code.
Definition:Hashing.h:590
llvm::semBFloat
static constexpr fltSemantics semBFloat
Definition:APFloat.cpp:131
llvm::Data
@ Data
Definition:SIMachineScheduler.h:55
llvm::trailingHexadecimalFraction
static Expected< lostFraction > trailingHexadecimalFraction(StringRef::iterator p, StringRef::iterator end, unsigned int digitValue)
Definition:APFloat.cpp:625
llvm::consumeError
void consumeError(Error Err)
Consume a Error without doing anything.
Definition:Error.h:1069
llvm::semFloat8E3M4
static constexpr fltSemantics semFloat8E3M4
Definition:APFloat.cpp:145
llvm::fltNanEncoding
fltNanEncoding
Definition:APFloat.cpp:81
llvm::fltNanEncoding::NegativeZero
@ NegativeZero
llvm::fltNanEncoding::AllOnes
@ AllOnes
llvm::fltNanEncoding::IEEE
@ IEEE
llvm::readExponent
static Expected< int > readExponent(StringRef::iterator begin, StringRef::iterator end)
Definition:APFloat.cpp:418
llvm::hash_combine_range
hash_code hash_combine_range(InputIteratorT first, InputIteratorT last)
Compute a hash_code for a sequence of values.
Definition:Hashing.h:468
llvm::semFloat8E4M3
static constexpr fltSemantics semFloat8E4M3
Definition:APFloat.cpp:138
llvm::NextPowerOf2
constexpr uint64_t NextPowerOf2(uint64_t A)
Returns the next power of two (in 64-bits) that is strictly greater than A.
Definition:MathExtras.h:383
llvm::hexDigitsLower
static const char hexDigitsLower[]
Definition:APFloat.cpp:826
std
Implement std::hash so that hash_code can be used in STL containers.
Definition:BitVector.h:858
raw_ostream.h
N
#define N
Status
Definition:SIModeRegister.cpp:29
llvm::APFloatBase::EnumToSemantics
static const llvm::fltSemantics & EnumToSemantics(Semantics S)
Definition:APFloat.cpp:163
llvm::APFloatBase::IEEEsingle
static const fltSemantics & IEEEsingle() LLVM_READNONE
Definition:APFloat.cpp:257
llvm::APFloatBase::semanticsHasInf
static bool semanticsHasInf(const fltSemantics &)
Definition:APFloat.cpp:348
llvm::APFloatBase::Float6E3M2FN
static const fltSemantics & Float6E3M2FN() LLVM_READNONE
Definition:APFloat.cpp:277
llvm::APFloatBase::rmNearestTiesToAway
static constexpr roundingMode rmNearestTiesToAway
Definition:APFloat.h:307
llvm::APFloatBase::cmpResult
cmpResult
IEEE-754R 5.11: Floating Point Comparison Relations.
Definition:APFloat.h:292
llvm::APFloatBase::cmpEqual
@ cmpEqual
Definition:APFloat.h:294
llvm::APFloatBase::cmpGreaterThan
@ cmpGreaterThan
Definition:APFloat.h:295
llvm::APFloatBase::PPCDoubleDoubleLegacy
static const fltSemantics & PPCDoubleDoubleLegacy() LLVM_READNONE
Definition:APFloat.cpp:263
llvm::APFloatBase::rmTowardNegative
static constexpr roundingMode rmTowardNegative
Definition:APFloat.h:305
llvm::APFloatBase::semanticsMinExponent
static ExponentType semanticsMinExponent(const fltSemantics &)
Definition:APFloat.cpp:323
llvm::APFloatBase::rmNearestTiesToEven
static constexpr roundingMode rmNearestTiesToEven
Definition:APFloat.h:302
llvm::APFloatBase::semanticsSizeInBits
static unsigned int semanticsSizeInBits(const fltSemantics &)
Definition:APFloat.cpp:326
llvm::APFloatBase::semanticsHasSignedRepr
static bool semanticsHasSignedRepr(const fltSemantics &)
Definition:APFloat.cpp:344
llvm::APFloatBase::Float8E4M3
static const fltSemantics & Float8E4M3() LLVM_READNONE
Definition:APFloat.cpp:268
llvm::APFloatBase::getSizeInBits
static unsigned getSizeInBits(const fltSemantics &Sem)
Returns the size of the floating point number (in bits) in the given semantics.
Definition:APFloat.cpp:370
llvm::APFloatBase::Float8E4M3FN
static const fltSemantics & Float8E4M3FN() LLVM_READNONE
Definition:APFloat.cpp:269
llvm::APFloatBase::PPCDoubleDouble
static const fltSemantics & PPCDoubleDouble() LLVM_READNONE
Definition:APFloat.cpp:260
llvm::APFloatBase::rmTowardZero
static constexpr roundingMode rmTowardZero
Definition:APFloat.h:306
llvm::APFloatBase::x87DoubleExtended
static const fltSemantics & x87DoubleExtended() LLVM_READNONE
Definition:APFloat.cpp:280
llvm::APFloatBase::uninitializedTag
uninitializedTag
Convenience enum used to construct an uninitialized APFloat.
Definition:APFloat.h:336
llvm::APFloatBase::IEEEquad
static const fltSemantics & IEEEquad() LLVM_READNONE
Definition:APFloat.cpp:259
llvm::APFloatBase::Float4E2M1FN
static const fltSemantics & Float4E2M1FN() LLVM_READNONE
Definition:APFloat.cpp:279
llvm::APFloatBase::Float8E8M0FNU
static const fltSemantics & Float8E8M0FNU() LLVM_READNONE
Definition:APFloat.cpp:276
llvm::APFloatBase::Float8E4M3B11FNUZ
static const fltSemantics & Float8E4M3B11FNUZ() LLVM_READNONE
Definition:APFloat.cpp:271
llvm::APFloatBase::Bogus
static const fltSemantics & Bogus() LLVM_READNONE
A Pseudo fltsemantic used to construct APFloats that cannot conflict with anything real.
Definition:APFloat.cpp:283
llvm::APFloatBase::semanticsMaxExponent
static ExponentType semanticsMaxExponent(const fltSemantics &)
Definition:APFloat.cpp:319
llvm::APFloatBase::semanticsPrecision
static unsigned int semanticsPrecision(const fltSemantics &)
Definition:APFloat.cpp:315
llvm::APFloatBase::IEEEdouble
static const fltSemantics & IEEEdouble() LLVM_READNONE
Definition:APFloat.cpp:258
llvm::APFloatBase::semanticsHasNaN
static bool semanticsHasNaN(const fltSemantics &)
Definition:APFloat.cpp:352
llvm::APFloatBase::Float8E5M2
static const fltSemantics & Float8E5M2() LLVM_READNONE
Definition:APFloat.cpp:266
llvm::APFloatBase::SemanticsToEnum
static Semantics SemanticsToEnum(const llvm::fltSemantics &Sem)
Definition:APFloat.cpp:210
llvm::APFloatBase::integerPartWidth
static constexpr unsigned integerPartWidth
Definition:APFloat.h:145
llvm::APFloatBase::IEEEhalf
static const fltSemantics & IEEEhalf() LLVM_READNONE
Definition:APFloat.cpp:255
llvm::APFloatBase::integerPart
APInt::WordType integerPart
Definition:APFloat.h:144
llvm::APFloatBase::rmTowardPositive
static constexpr roundingMode rmTowardPositive
Definition:APFloat.h:304
llvm::APFloatBase::semanticsHasZero
static bool semanticsHasZero(const fltSemantics &)
Definition:APFloat.cpp:340
llvm::APFloatBase::isRepresentableAsNormalIn
static bool isRepresentableAsNormalIn(const fltSemantics &Src, const fltSemantics &Dst)
Definition:APFloat.cpp:356
llvm::APFloatBase::Float8E4M3FNUZ
static const fltSemantics & Float8E4M3FNUZ() LLVM_READNONE
Definition:APFloat.cpp:270
llvm::APFloatBase::IEK_NaN
@ IEK_NaN
Definition:APFloat.h:343
llvm::APFloatBase::IEK_Inf
@ IEK_Inf
Definition:APFloat.h:344
llvm::APFloatBase::IEK_Zero
@ IEK_Zero
Definition:APFloat.h:342
llvm::APFloatBase::BFloat
static const fltSemantics & BFloat() LLVM_READNONE
Definition:APFloat.cpp:256
llvm::APFloatBase::FloatTF32
static const fltSemantics & FloatTF32() LLVM_READNONE
Definition:APFloat.cpp:275
llvm::APFloatBase::isRepresentableBy
static bool isRepresentableBy(const fltSemantics &A, const fltSemantics &B)
Definition:APFloat.cpp:285
llvm::APFloatBase::Float8E5M2FNUZ
static const fltSemantics & Float8E5M2FNUZ() LLVM_READNONE
Definition:APFloat.cpp:267
llvm::APFloatBase::Float6E2M3FN
static const fltSemantics & Float6E2M3FN() LLVM_READNONE
Definition:APFloat.cpp:278
llvm::APFloatBase::fltCategory
fltCategory
Category of internally-represented number.
Definition:APFloat.h:328
llvm::APFloatBase::fcNormal
@ fcNormal
Definition:APFloat.h:331
llvm::APFloatBase::Semantics
Semantics
Definition:APFloat.h:152
llvm::APFloatBase::S_Float6E2M3FN
@ S_Float6E2M3FN
Definition:APFloat.h:246
llvm::APFloatBase::S_IEEEsingle
@ S_IEEEsingle
Definition:APFloat.h:155
llvm::APFloatBase::S_Float8E4M3FNUZ
@ S_Float8E4M3FNUZ
Definition:APFloat.h:217
llvm::APFloatBase::S_IEEEhalf
@ S_IEEEhalf
Definition:APFloat.h:153
llvm::APFloatBase::S_BFloat
@ S_BFloat
Definition:APFloat.h:154
llvm::APFloatBase::S_Float8E5M2
@ S_Float8E5M2
Definition:APFloat.h:195
llvm::APFloatBase::S_PPCDoubleDouble
@ S_PPCDoubleDouble
Definition:APFloat.h:167
llvm::APFloatBase::S_Float8E4M3
@ S_Float8E4M3
Definition:APFloat.h:205
llvm::APFloatBase::S_Float4E2M1FN
@ S_Float4E2M1FN
Definition:APFloat.h:250
llvm::APFloatBase::S_IEEEquad
@ S_IEEEquad
Definition:APFloat.h:157
llvm::APFloatBase::S_Float6E3M2FN
@ S_Float6E3M2FN
Definition:APFloat.h:242
llvm::APFloatBase::S_Float8E4M3FN
@ S_Float8E4M3FN
Definition:APFloat.h:210
llvm::APFloatBase::S_FloatTF32
@ S_FloatTF32
Definition:APFloat.h:231
llvm::APFloatBase::S_x87DoubleExtended
@ S_x87DoubleExtended
Definition:APFloat.h:252
llvm::APFloatBase::S_Float8E5M2FNUZ
@ S_Float8E5M2FNUZ
Definition:APFloat.h:202
llvm::APFloatBase::S_Float8E4M3B11FNUZ
@ S_Float8E4M3B11FNUZ
Definition:APFloat.h:224
llvm::APFloatBase::S_Float8E3M4
@ S_Float8E3M4
Definition:APFloat.h:227
llvm::APFloatBase::S_IEEEdouble
@ S_IEEEdouble
Definition:APFloat.h:156
llvm::APFloatBase::S_PPCDoubleDoubleLegacy
@ S_PPCDoubleDoubleLegacy
Definition:APFloat.h:192
llvm::APFloatBase::S_Float8E8M0FNU
@ S_Float8E8M0FNU
Definition:APFloat.h:238
llvm::APFloatBase::Float8E3M4
static const fltSemantics & Float8E3M4() LLVM_READNONE
Definition:APFloat.cpp:274
llvm::APFloatBase::opStatus
opStatus
IEEE-754R 7: Default exception handling.
Definition:APFloat.h:318
llvm::APFloatBase::opOK
@ opOK
Definition:APFloat.h:319
llvm::APFloatBase::opInexact
@ opInexact
Definition:APFloat.h:324
llvm::APFloatBase::ExponentType
int32_t ExponentType
A signed type to represent a floating point numbers unbiased exponent.
Definition:APFloat.h:148
llvm::APFloatBase::semanticsIntSizeInBits
static unsigned int semanticsIntSizeInBits(const fltSemantics &, bool)
Definition:APFloat.cpp:329
llvm::PatternMatch::is_nan
Definition:PatternMatch.h:705
llvm::PatternMatch::is_zero
Definition:PatternMatch.h:603
llvm::decimalInfo
Definition:APFloat.cpp:548
llvm::decimalInfo::normalizedExponent
int normalizedExponent
Definition:APFloat.cpp:552
llvm::decimalInfo::exponent
int exponent
Definition:APFloat.cpp:551
llvm::decimalInfo::lastSigDigit
const char * lastSigDigit
Definition:APFloat.cpp:550
llvm::decimalInfo::firstSigDigit
const char * firstSigDigit
Definition:APFloat.cpp:549
llvm::fltSemantics
Definition:APFloat.cpp:103
llvm::fltSemantics::maxExponent
APFloatBase::ExponentType maxExponent
Definition:APFloat.cpp:106
llvm::fltSemantics::nonFiniteBehavior
fltNonfiniteBehavior nonFiniteBehavior
Definition:APFloat.cpp:119
llvm::fltSemantics::minExponent
APFloatBase::ExponentType minExponent
Definition:APFloat.cpp:110
llvm::fltSemantics::hasSignedRepr
bool hasSignedRepr
Definition:APFloat.cpp:127
llvm::fltSemantics::sizeInBits
unsigned int sizeInBits
Definition:APFloat.cpp:117
llvm::fltSemantics::precision
unsigned int precision
Definition:APFloat.cpp:114
llvm::fltSemantics::hasZero
bool hasZero
Definition:APFloat.cpp:124
llvm::fltSemantics::nanEncoding
fltNanEncoding nanEncoding
Definition:APFloat.cpp:121

Generated on Thu Jul 17 2025 12:37:18 for LLVM by doxygen 1.9.6
[8]ページ先頭

©2009-2025 Movatter.jp