[InstCombine] Fold (x << y) >> y -> x & (-1 >> y)

Summary:
We already do it for splat constants, but not just values.
Also, undef cases are mostly non-functional.

https://bugs.llvm.org/show_bug.cgi?id=37603
https://rise4fun.com/Alive/cplX

Reviewers: spatel, craig.topper

Reviewed By: spatel

Subscribers: llvm-commits

Differential Revision: https://reviews.llvm.org/D47980

llvm-svn: 334371
This commit is contained in:
Roman Lebedev 2018-06-10 20:10:06 +00:00
parent 1e9457ee76
commit 4cdc59ecf2
2 changed files with 14 additions and 6 deletions

View File

@ -802,6 +802,15 @@ Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
return &I;
}
}
// Transform (x << y) >> y to x & (-1 >> y)
Value *X;
if (match(Op0, m_OneUse(m_Shl(m_Value(X), m_Specific(Op1))))) {
Constant *AllOnes = ConstantInt::getAllOnesValue(Ty);
Value *Mask = Builder.CreateLShr(AllOnes, Op1);
return BinaryOperator::CreateAnd(Mask, X);
}
return nullptr;
}

View File

@ -14,8 +14,8 @@
define i32 @positive_samevar(i32 %x, i32 %y) {
; CHECK-LABEL: @positive_samevar(
; CHECK-NEXT: [[TMP0:%.*]] = shl i32 [[X:%.*]], [[Y:%.*]]
; CHECK-NEXT: [[RET:%.*]] = lshr i32 [[TMP0]], [[Y]]
; CHECK-NEXT: [[TMP1:%.*]] = lshr i32 -1, [[Y:%.*]]
; CHECK-NEXT: [[RET:%.*]] = and i32 [[TMP1]], [[X:%.*]]
; CHECK-NEXT: ret i32 [[RET]]
;
%tmp0 = shl i32 %x, %y
@ -124,8 +124,8 @@ define i32 @positive_biggerLshr_shlnuw_lshrexact(i32 %x) {
define <2 x i32> @positive_samevar_vec(<2 x i32> %x, <2 x i32> %y) {
; CHECK-LABEL: @positive_samevar_vec(
; CHECK-NEXT: [[TMP0:%.*]] = shl <2 x i32> [[X:%.*]], [[Y:%.*]]
; CHECK-NEXT: [[RET:%.*]] = lshr <2 x i32> [[TMP0]], [[Y]]
; CHECK-NEXT: [[TMP1:%.*]] = lshr <2 x i32> <i32 -1, i32 -1>, [[Y:%.*]]
; CHECK-NEXT: [[RET:%.*]] = and <2 x i32> [[TMP1]], [[X:%.*]]
; CHECK-NEXT: ret <2 x i32> [[RET]]
;
%tmp0 = shl <2 x i32> %x, %y
@ -171,8 +171,7 @@ define <3 x i32> @positive_sameconst_vec_undef1(<3 x i32> %x) {
define <3 x i32> @positive_sameconst_vec_undef2(<3 x i32> %x) {
; CHECK-LABEL: @positive_sameconst_vec_undef2(
; CHECK-NEXT: [[TMP0:%.*]] = shl <3 x i32> [[X:%.*]], <i32 5, i32 undef, i32 5>
; CHECK-NEXT: [[RET:%.*]] = lshr <3 x i32> [[TMP0]], <i32 5, i32 undef, i32 5>
; CHECK-NEXT: [[RET:%.*]] = and <3 x i32> [[X:%.*]], <i32 134217727, i32 undef, i32 134217727>
; CHECK-NEXT: ret <3 x i32> [[RET]]
;
%tmp0 = shl <3 x i32> %x, <i32 5, i32 undef, i32 5>