diff --git a/llvm/lib/Transforms/InstCombine/InstCombineShifts.cpp b/llvm/lib/Transforms/InstCombine/InstCombineShifts.cpp index 828002f44d42..627e3390ea14 100644 --- a/llvm/lib/Transforms/InstCombine/InstCombineShifts.cpp +++ b/llvm/lib/Transforms/InstCombine/InstCombineShifts.cpp @@ -402,15 +402,15 @@ Instruction *InstCombinerImpl::commonShiftTransforms(BinaryOperator &I) { return BinaryOperator::Create( I.getOpcode(), Builder.CreateBinOp(I.getOpcode(), Op0, C), A); - // X shift (A srem B) -> X shift (A and B-1) iff B is a power of 2. + // X shift (A srem C) -> X shift (A and (C - 1)) iff C is a power of 2. // Because shifts by negative values (which could occur if A were negative) // are undefined. - const APInt *B; - if (Op1->hasOneUse() && match(Op1, m_SRem(m_Value(A), m_Power2(B)))) { + if (Op1->hasOneUse() && match(Op1, m_SRem(m_Value(A), m_Constant(C))) && + match(C, m_Power2())) { // FIXME: Should this get moved into SimplifyDemandedBits by saying we don't // demand the sign bit (and many others) here?? - Value *Rem = Builder.CreateAnd(A, ConstantInt::get(I.getType(), *B - 1), - Op1->getName()); + Constant *Mask = ConstantExpr::getSub(C, ConstantInt::get(I.getType(), 1)); + Value *Rem = Builder.CreateAnd(A, Mask, Op1->getName()); return replaceOperand(I, 1, Rem); } diff --git a/llvm/test/Transforms/InstCombine/shift.ll b/llvm/test/Transforms/InstCombine/shift.ll index 18aac5ac44b0..70ef9c54c1f6 100644 --- a/llvm/test/Transforms/InstCombine/shift.ll +++ b/llvm/test/Transforms/InstCombine/shift.ll @@ -616,8 +616,8 @@ define <2 x i32> @test38_uniform(<2 x i32> %x) nounwind readnone { define <3 x i32> @test38_nonuniform(<3 x i32> %x) nounwind readnone { ; CHECK-LABEL: @test38_nonuniform( -; CHECK-NEXT: [[REM:%.*]] = srem <3 x i32> [[X:%.*]], -; CHECK-NEXT: [[SHL:%.*]] = shl <3 x i32> , [[REM]] +; CHECK-NEXT: [[REM1:%.*]] = and <3 x i32> [[X:%.*]], +; CHECK-NEXT: [[SHL:%.*]] = shl <3 x i32> , [[REM1]] ; CHECK-NEXT: ret <3 x i32> [[SHL]] ; %rem = srem <3 x i32> %x,