[llvm] r292179 - [InstCombine] Fold ((C1-zext(X)) & C2) -> zext((C1-X) & C2)
David Majnemer via llvm-commits
llvm-commits at lists.llvm.org
Mon Jan 16 16:45:57 PST 2017
Author: majnemer
Date: Mon Jan 16 18:45:57 2017
New Revision: 292179
URL: http://llvm.org/viewvc/llvm-project?rev=292179&view=rev
Log:
[InstCombine] Fold ((C1-zext(X)) & C2) -> zext((C1-X) & C2)
This is valid if C2 fits within the bitwidth of X thanks to two's
complement modulo arithmetic.
Modified:
llvm/trunk/lib/Transforms/InstCombine/InstCombineAndOrXor.cpp
llvm/trunk/test/Transforms/InstCombine/and.ll
Modified: llvm/trunk/lib/Transforms/InstCombine/InstCombineAndOrXor.cpp
URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/Transforms/InstCombine/InstCombineAndOrXor.cpp?rev=292179&r1=292178&r2=292179&view=diff
==============================================================================
--- llvm/trunk/lib/Transforms/InstCombine/InstCombineAndOrXor.cpp (original)
+++ llvm/trunk/lib/Transforms/InstCombine/InstCombineAndOrXor.cpp Mon Jan 16 18:45:57 2017
@@ -1331,6 +1331,21 @@ Instruction *InstCombiner::visitAnd(Bina
if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
return BinaryOperator::CreateAnd(V, AndRHS);
+ // ((C1-zext(X)) & C2) -> zext((C1-X) & C2) if C2 fits in the bitwidth
+ // of X.
+ if (auto *ZI = dyn_cast<ZExtInst>(Op0RHS)) {
+ auto *X = ZI->getOperand(0);
+ ConstantInt *C1;
+ if (match(Op0LHS, m_ConstantInt(C1)) &&
+ AndRHSMask.isIntN(X->getType()->getScalarSizeInBits())) {
+ auto *TruncC1 = ConstantExpr::getTrunc(C1, X->getType());
+ auto *Sub = Builder->CreateSub(TruncC1, X);
+ auto *TruncC2 = ConstantExpr::getTrunc(AndRHS, X->getType());
+ auto *And = Builder->CreateAnd(Sub, TruncC2);
+ return new ZExtInst(And, I.getType());
+ }
+ }
+
// -x & 1 -> x & 1
if (AndRHSMask == 1 && match(Op0LHS, m_Zero()))
return BinaryOperator::CreateAnd(Op0RHS, AndRHS);
Modified: llvm/trunk/test/Transforms/InstCombine/and.ll
URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/test/Transforms/InstCombine/and.ll?rev=292179&r1=292178&r2=292179&view=diff
==============================================================================
--- llvm/trunk/test/Transforms/InstCombine/and.ll (original)
+++ llvm/trunk/test/Transforms/InstCombine/and.ll Mon Jan 16 18:45:57 2017
@@ -425,3 +425,14 @@ define <2 x i32> @PR24942(<2 x i32> %x)
ret <2 x i32> %and
}
+define i64 @test35(i32 %X) {
+; CHECK-LABEL: @test35(
+; CHECK-NEXT: %[[sub:.*]] = sub i32 0, %X
+; CHECK-NEXT: %[[and:.*]] = and i32 %[[sub]], 240
+; CHECK-NEXT: %[[cst:.*]] = zext i32 %[[and]] to i64
+; CHECK-NEXT: ret i64 %[[cst]]
+ %zext = zext i32 %X to i64
+ %zsub = sub i64 0, %zext
+ %res = and i64 %zsub, 240
+ ret i64 %res
+}
More information about the llvm-commits
mailing list