diff --git a/llvm/lib/IR/ConstantRange.cpp b/llvm/lib/IR/ConstantRange.cpp index e9344a8815c08..d22d56e40c08f 100644 --- a/llvm/lib/IR/ConstantRange.cpp +++ b/llvm/lib/IR/ConstantRange.cpp @@ -1477,6 +1477,13 @@ ConstantRange::shl(const ConstantRange &Other) const { } APInt OtherMax = Other.getUnsignedMax(); + if (isAllNegative() && OtherMax.ule(Min.countl_one())) { + // For negative numbers, if the shift does not overflow in a signed sense, + // a larger shift will make the number smaller. + Max <<= Other.getUnsignedMin(); + Min <<= OtherMax; + return ConstantRange::getNonEmpty(std::move(Min), std::move(Max) + 1); + } // There's overflow! if (OtherMax.ugt(Max.countl_zero())) diff --git a/llvm/test/Transforms/SCCP/and-add-shl.ll b/llvm/test/Transforms/SCCP/and-add-shl.ll index 427372c2d670f..7c037ffa6bf64 100644 --- a/llvm/test/Transforms/SCCP/and-add-shl.ll +++ b/llvm/test/Transforms/SCCP/and-add-shl.ll @@ -30,8 +30,7 @@ define i8 @and_not_shl(i8 %x) { ; CHECK-NEXT: call void @llvm.assume(i1 [[OP1_P2]]) ; CHECK-NEXT: [[SHIFT:%.*]] = shl nsw i8 -1, [[X]] ; CHECK-NEXT: [[NOT:%.*]] = xor i8 [[SHIFT]], -1 -; CHECK-NEXT: [[R:%.*]] = and i8 [[NOT]], 32 -; CHECK-NEXT: ret i8 [[R]] +; CHECK-NEXT: ret i8 0 ; %op1_p2 = icmp ule i8 %x, 5 call void @llvm.assume(i1 %op1_p2) @@ -48,8 +47,7 @@ define i8 @and_not_shl_1(i8 %x) { ; CHECK-NEXT: call void @llvm.assume(i1 [[OP1_P2]]) ; CHECK-NEXT: [[SHIFT:%.*]] = shl nsw i8 -1, [[X]] ; CHECK-NEXT: [[NOT:%.*]] = xor i8 [[SHIFT]], -1 -; CHECK-NEXT: [[R:%.*]] = and i8 [[NOT]], 48 -; CHECK-NEXT: ret i8 [[R]] +; CHECK-NEXT: ret i8 0 ; %op1_p2 = icmp ule i8 %x, 4 call void @llvm.assume(i1 %op1_p2) diff --git a/llvm/unittests/IR/ConstantRangeTest.cpp b/llvm/unittests/IR/ConstantRangeTest.cpp index 38d1119e7f85b..1cb358a26062c 100644 --- a/llvm/unittests/IR/ConstantRangeTest.cpp +++ b/llvm/unittests/IR/ConstantRangeTest.cpp @@ -1373,6 +1373,13 @@ TEST_F(ConstantRangeTest, Shl) { ConstantRange(APInt(16, 0xfff << 0x1), APInt(16, 0x7fff << 0x1) + 1)); EXPECT_EQ(One.shl(WrapNullMax), Full); + ConstantRange NegOne(APInt(16, 0xffff)); + EXPECT_EQ(NegOne.shl(ConstantRange(APInt(16, 0), APInt(16, 5))), + ConstantRange(APInt(16, 0xfff0), APInt(16, 0))); + EXPECT_EQ(ConstantRange(APInt(16, 0xfffe), APInt(16, 0)) + .shl(ConstantRange(APInt(16, 0), APInt(16, 5))), + ConstantRange(APInt(16, 0xffe0), APInt(16, 0))); + TestBinaryOpExhaustive( [](const ConstantRange &CR1, const ConstantRange &CR2) { return CR1.shl(CR2);