[llvm] r278280 - Fix UB in APInt::ashr
Jonathan Roelofs via llvm-commits
llvm-commits at lists.llvm.org
Wed Aug 10 12:50:15 PDT 2016
Author: jroelofs
Date: Wed Aug 10 14:50:14 2016
New Revision: 278280
URL: http://llvm.org/viewvc/llvm-project?rev=278280&view=rev
Log:
Fix UB in APInt::ashr
i64 -1, whose sign bit is the 0th one, can't be left shifted without invoking UB.
https://reviews.llvm.org/D23362
Modified:
llvm/trunk/lib/Support/APInt.cpp
llvm/trunk/unittests/ADT/APIntTest.cpp
Modified: llvm/trunk/lib/Support/APInt.cpp
URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/Support/APInt.cpp?rev=278280&r1=278279&r2=278280&view=diff
==============================================================================
--- llvm/trunk/lib/Support/APInt.cpp (original)
+++ llvm/trunk/lib/Support/APInt.cpp Wed Aug 10 14:50:14 2016
@@ -1042,11 +1042,7 @@ APInt APInt::ashr(unsigned shiftAmt) con
if (isSingleWord()) {
if (shiftAmt == BitWidth)
return APInt(BitWidth, 0); // undefined
- else {
- unsigned SignBit = APINT_BITS_PER_WORD - BitWidth;
- return APInt(BitWidth,
- (((int64_t(VAL) << SignBit) >> SignBit) >> shiftAmt));
- }
+ return APInt(BitWidth, SignExtend64(VAL, BitWidth) >> shiftAmt);
}
// If all the bits were shifted out, the result is, technically, undefined.
Modified: llvm/trunk/unittests/ADT/APIntTest.cpp
URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/unittests/ADT/APIntTest.cpp?rev=278280&r1=278279&r2=278280&view=diff
==============================================================================
--- llvm/trunk/unittests/ADT/APIntTest.cpp (original)
+++ llvm/trunk/unittests/ADT/APIntTest.cpp Wed Aug 10 14:50:14 2016
@@ -32,6 +32,11 @@ TEST(APIntTest, ShiftLeftByZero) {
EXPECT_FALSE(Shl[1]);
}
+TEST(APIntTest, i64_ArithmeticRightShiftNegative) {
+ const APInt neg_one(64, static_cast<uint64_t>(-1), true);
+ EXPECT_EQ(neg_one, neg_one.ashr(7));
+}
+
TEST(APIntTest, i128_NegativeCount) {
APInt Minus3(128, static_cast<uint64_t>(-3), true);
EXPECT_EQ(126u, Minus3.countLeadingOnes());
More information about the llvm-commits
mailing list