Skip to content

Commit cce5dac

Browse files
chenglin.bifengfeng09
authored andcommitted
[InstCombine] Add pattern 'if (C1 & C2) == C2 then (X & C1) - (X & C2) -> X & (C1 ^ C2)'
https://alive2.llvm.org/ce/z/BveKM5
1 parent 312c90d commit cce5dac

File tree

2 files changed

+10
-3
lines changed

2 files changed

+10
-3
lines changed

llvm/lib/Transforms/InstCombine/InstCombineAddSub.cpp

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2280,6 +2280,15 @@ Instruction *InstCombinerImpl::visitSub(BinaryOperator &I) {
22802280
if (match(Op0, m_OneUse(m_Add(m_Value(X), m_AllOnes()))))
22812281
return BinaryOperator::CreateAdd(Builder.CreateNot(Op1), X);
22822282

2283+
const APInt *C1, *C2;
2284+
// if (C1 & C2) == C2 then (X & C1) - (X & C2) -> X & (C1 ^ C2)
2285+
if (match(Op0, m_And(m_Value(X), m_APInt(C1))) &&
2286+
match(Op1, m_And(m_Specific(X), m_APInt(C2)))) {
2287+
if (C2->eq(*C1 & *C2))
2288+
return BinaryOperator::CreateAnd(
2289+
X, ConstantInt::get(I.getType(), *C1 ^ *C2));
2290+
}
2291+
22832292
// Reassociate sub/add sequences to create more add instructions and
22842293
// reduce dependency chains:
22852294
// ((X - Y) + Z) - Op1 --> (X + Z) - (Y + Op1)

llvm/test/Transforms/InstCombine/X86/and-sub-combine.ll

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3,9 +3,7 @@
33

44
define i8 @and_sub(i8 %a) {
55
; CHECK-LABEL: @and_sub(
6-
; CHECK-NEXT: [[AND1:%.*]] = and i8 [[A:%.*]], 15
7-
; CHECK-NEXT: [[AND2:%.*]] = and i8 [[A]], 3
8-
; CHECK-NEXT: [[RET:%.*]] = sub nsw i8 [[AND1]], [[AND2]]
6+
; CHECK-NEXT: [[RET:%.*]] = and i8 [[A:%.*]], 12
97
; CHECK-NEXT: ret i8 [[RET]]
108
;
119
%and1 = and i8 %a, 15

0 commit comments

Comments
 (0)