Author: Kerry McLaughlin Date: 2020-11-23T11:27:30Z New Revision: d3a0f9b9ec88ce0737470652330262f8ed46daa7
URL: https://github.com/llvm/llvm-project/commit/d3a0f9b9ec88ce0737470652330262f8ed46daa7 DIFF: https://github.com/llvm/llvm-project/commit/d3a0f9b9ec88ce0737470652330262f8ed46daa7.diff LOG: [APInt] Add the truncOrSelf resizing operator to APInt Truncates the APInt if the bit width is greater than the width specified, otherwise do nothing Reviewed By: RKSimon Differential Revision: https://reviews.llvm.org/D91445 Added: Modified: llvm/include/llvm/ADT/APInt.h llvm/lib/Support/APInt.cpp llvm/unittests/ADT/APIntTest.cpp Removed: ################################################################################ diff --git a/llvm/include/llvm/ADT/APInt.h b/llvm/include/llvm/ADT/APInt.h index f5860f6c7517..b97ea2cd9aee 100644 --- a/llvm/include/llvm/ADT/APInt.h +++ b/llvm/include/llvm/ADT/APInt.h @@ -1403,6 +1403,12 @@ class LLVM_NODISCARD APInt { /// extended, truncated, or left alone to make it that width. APInt zextOrTrunc(unsigned width) const; + /// Truncate to width + /// + /// Make this APInt have the bit width given by \p width. The value is + /// truncated or left alone to make it that width. + APInt truncOrSelf(unsigned width) const; + /// Sign extend or truncate to width /// /// Make this APInt have the bit width given by \p width. The value is sign diff --git a/llvm/lib/Support/APInt.cpp b/llvm/lib/Support/APInt.cpp index fc339de45af4..12ceb2df112e 100644 --- a/llvm/lib/Support/APInt.cpp +++ b/llvm/lib/Support/APInt.cpp @@ -961,6 +961,12 @@ APInt APInt::sextOrTrunc(unsigned width) const { return *this; } +APInt APInt::truncOrSelf(unsigned width) const { + if (BitWidth > width) + return trunc(width); + return *this; +} + APInt APInt::zextOrSelf(unsigned width) const { if (BitWidth < width) return zext(width); diff --git a/llvm/unittests/ADT/APIntTest.cpp b/llvm/unittests/ADT/APIntTest.cpp index 673a2110af09..ef5423e332e1 100644 --- a/llvm/unittests/ADT/APIntTest.cpp +++ b/llvm/unittests/ADT/APIntTest.cpp @@ -2598,6 +2598,13 @@ TEST(APIntTest, sext) { EXPECT_EQ(63U, i32_neg1.countPopulation()); } +TEST(APIntTest, truncOrSelf) { + APInt val(32, 0xFFFFFFFF); + EXPECT_EQ(0xFFFF, val.truncOrSelf(16)); + EXPECT_EQ(0xFFFFFFFF, val.truncOrSelf(32)); + EXPECT_EQ(0xFFFFFFFF, val.truncOrSelf(64)); +} + TEST(APIntTest, multiply) { APInt i64(64, 1234); _______________________________________________ llvm-branch-commits mailing list llvm-branch-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-branch-commits