Skip to content

Commit 7476d59

Browse files
reedwmd0k
authored andcommitted
Fix APFloat::toString on Float8E5M2 values.
Before, an APInt with value 10 was created, whose width was the significand width. But 10 cannot fit in Float8E5M2's significand. Differential Revision: https://reviews.llvm.org/D138540
1 parent 492c471 commit 7476d59

File tree

2 files changed

+25
-0
lines changed

2 files changed

+25
-0
lines changed

llvm/lib/Support/APFloat.cpp

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4099,6 +4099,11 @@ void IEEEFloat::toString(SmallVectorImpl<char> &Str, unsigned FormatPrecision,
40994099

41004100
// Fill the buffer.
41014101
unsigned precision = significand.getBitWidth();
4102+
if (precision < 4) {
4103+
// We need enough precision to store the value 10.
4104+
precision = 4;
4105+
significand = significand.zext(precision);
4106+
}
41024107
APInt ten(precision, 10);
41034108
APInt digit(precision, 0);
41044109

llvm/unittests/ADT/APFloatTest.cpp

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5152,6 +5152,26 @@ TEST(APFloatTest, Float8E4M3FNExhaustivePair) {
51525152
}
51535153
}
51545154

5155+
TEST(APFloatTest, F8ToString) {
5156+
for (APFloat::Semantics S :
5157+
{APFloat::S_Float8E5M2, APFloat::S_Float8E4M3FN}) {
5158+
SCOPED_TRACE("Semantics=" + std::to_string(S));
5159+
for (int i = 0; i < 256; i++) {
5160+
SCOPED_TRACE("i=" + std::to_string(i));
5161+
APFloat test(APFloat::Float8E5M2(), APInt(8, i));
5162+
llvm::SmallString<128> str;
5163+
test.toString(str);
5164+
5165+
if (test.isNaN()) {
5166+
EXPECT_EQ(str, "NaN");
5167+
} else {
5168+
APFloat test2(APFloat::Float8E5M2(), str);
5169+
EXPECT_TRUE(test.bitwiseIsEqual(test2));
5170+
}
5171+
}
5172+
}
5173+
}
5174+
51555175
TEST(APFloatTest, IEEEdoubleToDouble) {
51565176
APFloat DPosZero(0.0);
51575177
APFloat DPosZeroToDouble(DPosZero.convertToDouble());

0 commit comments

Comments
 (0)