Index: llvm/include/llvm/ADT/APInt.h =================================================================== --- llvm/include/llvm/ADT/APInt.h +++ llvm/include/llvm/ADT/APInt.h @@ -1391,6 +1391,12 @@ /// than or equal to the current width. APInt zext(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 Index: llvm/lib/Support/APInt.cpp =================================================================== --- llvm/lib/Support/APInt.cpp +++ llvm/lib/Support/APInt.cpp @@ -945,6 +945,12 @@ return Result; } +APInt APInt::truncOrSelf(unsigned width) const { + if (BitWidth > width) + return trunc(width); + return *this; +} + APInt APInt::zextOrTrunc(unsigned width) const { if (BitWidth < width) return zext(width); Index: llvm/unittests/ADT/APIntTest.cpp =================================================================== --- llvm/unittests/ADT/APIntTest.cpp +++ llvm/unittests/ADT/APIntTest.cpp @@ -2598,6 +2598,13 @@ 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);