InstCombine: Don't miscompile X % ((Pow2 << A) >>u B)

We assumed that A must be greater than B because the right hand side of
a remainder operator must be nonzero.

However, it is possible for A to be less than B if Pow2 is a power of
two greater than 1.

Take for example:
i32 %A = 0
i32 %B = 31
i32 Pow2 = 2147483648

((Pow2 << 0) >>u 31) is non-zero but A is less than B.

This fixes PR21274.

git-svn-id: https://llvm.org/svn/llvm-project/llvm/trunk@219713 91177308-0d34-0410-b5e6-96231b3b80d8
This commit is contained in:
David Majnemer 2014-10-14 20:28:40 +00:00
parent d6315ea5a5
commit 505187a9bd
2 changed files with 17 additions and 8 deletions

View File

@ -36,14 +36,11 @@ static Value *simplifyValueKnownNonZero(Value *V, InstCombiner &IC,
// ((1 << A) >>u B) --> (1 << (A-B))
// Because V cannot be zero, we know that B is less than A.
Value *A = nullptr, *B = nullptr, *PowerOf2 = nullptr;
if (match(V, m_LShr(m_OneUse(m_Shl(m_Value(PowerOf2), m_Value(A))),
m_Value(B))) &&
// The "1" can be any value known to be a power of 2.
isKnownToBeAPowerOfTwo(PowerOf2, false, 0, IC.getAssumptionTracker(),
CxtI, IC.getDominatorTree())) {
Value *A = nullptr, *B = nullptr, *One = nullptr;
if (match(V, m_LShr(m_OneUse(m_Shl(m_Value(One), m_Value(A))), m_Value(B))) &&
match(One, m_One())) {
A = IC.Builder->CreateSub(A, B);
return IC.Builder->CreateShl(PowerOf2, A);
return IC.Builder->CreateShl(One, A);
}
// (PowerOfTwo >>u B) --> isExact since shifting out the result would make it

View File

@ -265,7 +265,7 @@ define i32 @test30(i32 %a) {
; CHECK-NEXT: ret i32 %a
}
define <2 x i32> @test31(<2 x i32> %x) nounwind {
define <2 x i32> @test31(<2 x i32> %x) {
%shr = lshr <2 x i32> %x, <i32 31, i32 31>
%div = udiv <2 x i32> %shr, <i32 2147483647, i32 2147483647>
ret <2 x i32> %div
@ -274,3 +274,15 @@ define <2 x i32> @test31(<2 x i32> %x) nounwind {
; CHECK-NEXT: udiv <2 x i32> %[[shr]], <i32 2147483647, i32 2147483647>
; CHECK-NEXT: ret <2 x i32>
}
define i32 @test32(i32 %a, i32 %b) {
%shl = shl i32 2, %b
%div = lshr i32 %shl, 2
%div2 = udiv i32 %a, %div
ret i32 %div2
; CHECK-LABEL: @test32(
; CHECK-NEXT: %[[shl:.*]] = shl i32 2, %b
; CHECK-NEXT: %[[shr:.*]] = lshr i32 %[[shl]], 2
; CHECK-NEXT: %[[div:.*]] = udiv i32 %a, %[[shr]]
; CHECK-NEXT: ret i32
}