diff options
author | Peter Rong <PeterRong96@gmail.com> | 2022-12-08 16:59:22 -0800 |
---|---|---|
committer | Peter Rong <PeterRong96@gmail.com> | 2022-12-15 10:06:26 -0800 |
commit | 55968109d1f9c8655d30928b9fde9993e341c97f (patch) | |
tree | 3aa06cbc7a948176b4c935edfc3c6297355acae1 /llvm/unittests/ADT/APIntTest.cpp | |
parent | 80f2f1eabc491cde39d543e4ebda93e2d2974d1f (diff) | |
download | llvm-55968109d1f9c8655d30928b9fde9993e341c97f.zip llvm-55968109d1f9c8655d30928b9fde9993e341c97f.tar.gz llvm-55968109d1f9c8655d30928b9fde9993e341c97f.tar.bz2 |
[APInt] provide a safe API for zext value and sext value.
Currently, APInt::getSExtValue and getZExtValue crashes on values with more than 64 bits.
Users may accidently crash the compiler with this setting when the integer may be i128.
As shown in https://github.com/llvm/llvm-project/issues/59316
In this patch we provide a trySExtValue and tryZExtValue to return an Optional, the user
needs to explictly unwrap it and condsier the possibility where there my no value in it.
Reviewed By: RKSimon
Differential Revision: https://reviews.llvm.org/D139683
Diffstat (limited to 'llvm/unittests/ADT/APIntTest.cpp')
-rw-r--r-- | llvm/unittests/ADT/APIntTest.cpp | 21 |
1 files changed, 21 insertions, 0 deletions
diff --git a/llvm/unittests/ADT/APIntTest.cpp b/llvm/unittests/ADT/APIntTest.cpp index 3055581..09c9c8d 100644 --- a/llvm/unittests/ADT/APIntTest.cpp +++ b/llvm/unittests/ADT/APIntTest.cpp @@ -3134,4 +3134,25 @@ TEST(APIntTest, DenseMap) { Map.find(ZeroWidthInt); } +TEST(APIntTest, TryExt) { + APInt small(32, 42); + APInt large(128, {0xffff, 0xffff}); + ASSERT_TRUE(small.tryZExtValue().has_value()); + ASSERT_TRUE(small.trySExtValue().has_value()); + ASSERT_FALSE(large.tryZExtValue().has_value()); + ASSERT_FALSE(large.trySExtValue().has_value()); + ASSERT_EQ(small.trySExtValue().value_or(41), 42); + ASSERT_EQ(large.trySExtValue().value_or(41), 41); + + APInt negOne32(32, 0); + negOne32.setAllBits(); + ASSERT_EQ(negOne32.trySExtValue().value_or(42), -1); + APInt negOne64(64, 0); + negOne64.setAllBits(); + ASSERT_EQ(negOne64.trySExtValue().value_or(42), -1); + APInt negOne128(128, 0); + negOne128.setAllBits(); + ASSERT_EQ(negOne128.trySExtValue().value_or(42), 42); +} + } // end anonymous namespace |