From a54d88f97dfeb35e4f6c14e5563ec686e68fd244 Mon Sep 17 00:00:00 2001 From: Yingwei Zheng Date: Tue, 15 Oct 2024 13:35:50 +0800 Subject: [PATCH] [APFloat] Fix `APFloat::getOne` (#112308) `APFloat::APFloat(const fltSemantics &Semantics, integerPart I)` interprets 'I' as a unsigned integer. Fix the bug found in https://github.com/llvm/llvm-project/pull/112113#discussion_r1799744541. --- llvm/include/llvm/ADT/APFloat.h | 5 ++++- llvm/unittests/ADT/APFloatTest.cpp | 7 +++++++ 2 files changed, 11 insertions(+), 1 deletion(-) diff --git a/llvm/include/llvm/ADT/APFloat.h b/llvm/include/llvm/ADT/APFloat.h index 6f1e24e5da33a9..97547fb577e0ec 100644 --- a/llvm/include/llvm/ADT/APFloat.h +++ b/llvm/include/llvm/ADT/APFloat.h @@ -1046,7 +1046,10 @@ class APFloat : public APFloatBase { /// /// \param Negative True iff the number should be negative. static APFloat getOne(const fltSemantics &Sem, bool Negative = false) { - return APFloat(Sem, Negative ? -1 : 1); + APFloat Val(Sem, 1U); + if (Negative) + Val.changeSign(); + return Val; } /// Factory for Positive and Negative Infinity. diff --git a/llvm/unittests/ADT/APFloatTest.cpp b/llvm/unittests/ADT/APFloatTest.cpp index 6008f00e42a989..665cff9c424594 100644 --- a/llvm/unittests/ADT/APFloatTest.cpp +++ b/llvm/unittests/ADT/APFloatTest.cpp @@ -892,6 +892,13 @@ TEST(APFloatTest, Zero) { EXPECT_EQ(fcNegZero, APFloat(-0.0).classify()); } +TEST(APFloatTest, getOne) { + EXPECT_EQ(APFloat::getOne(APFloat::IEEEsingle(), false).convertToFloat(), + 1.0f); + EXPECT_EQ(APFloat::getOne(APFloat::IEEEsingle(), true).convertToFloat(), + -1.0f); +} + TEST(APFloatTest, DecimalStringsWithoutNullTerminators) { // Make sure that we can parse strings without null terminators. // rdar://14323230.