diff --git a/llvm/lib/Transforms/InstCombine/InstCombineAndOrXor.cpp b/llvm/lib/Transforms/InstCombine/InstCombineAndOrXor.cpp index a3749a1581bd..7b32812a2c13 100644 --- a/llvm/lib/Transforms/InstCombine/InstCombineAndOrXor.cpp +++ b/llvm/lib/Transforms/InstCombine/InstCombineAndOrXor.cpp @@ -2422,11 +2422,17 @@ Instruction *InstCombiner::visitXor(BinaryOperator &I) { if (ConstantInt *RHSC = dyn_cast(Op1)) { if (BinaryOperator *Op0I = dyn_cast(Op0)) { // ~(c-X) == X-c-1 == X+(-c-1) - if (Op0I->getOpcode() == Instruction::Sub && RHSC->isMinusOne()) - if (Constant *Op0I0C = dyn_cast(Op0I->getOperand(0))) { - Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C); - return BinaryOperator::CreateAdd(Op0I->getOperand(1), - SubOne(NegOp0I0C)); + if (Op0I->getOpcode() == Instruction::Sub) + if (ConstantInt *Op0I0C = dyn_cast(Op0I->getOperand(0))) { + if (RHSC->isMinusOne()) { + Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C); + return BinaryOperator::CreateAdd(Op0I->getOperand(1), + SubOne(NegOp0I0C)); + } else if (RHSC->getValue().isSignMask()) { + // (C - X) ^ signmask -> (C + signmask - X) + Constant *C = Builder.getInt(RHSC->getValue() + Op0I0C->getValue()); + return BinaryOperator::CreateSub(C, Op0I->getOperand(1)); + } } if (ConstantInt *Op0CI = dyn_cast(Op0I->getOperand(1))) { @@ -2440,7 +2446,6 @@ Instruction *InstCombiner::visitXor(BinaryOperator &I) { // (X + C) ^ signmask -> (X + C + signmask) Constant *C = Builder.getInt(RHSC->getValue() + Op0CI->getValue()); return BinaryOperator::CreateAdd(Op0I->getOperand(0), C); - } } else if (Op0I->getOpcode() == Instruction::Or) { // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0 diff --git a/llvm/test/Transforms/InstCombine/xor.ll b/llvm/test/Transforms/InstCombine/xor.ll index 570155b16232..2e42f1c9480d 100644 --- a/llvm/test/Transforms/InstCombine/xor.ll +++ b/llvm/test/Transforms/InstCombine/xor.ll @@ -353,6 +353,15 @@ define i32 @test28(i32 %indvar) { ret i32 %t214 } +define i32 @test28_sub(i32 %indvar) { +; CHECK-LABEL: @test28_sub( +; CHECK-NEXT: ret i32 -2147483648 +; + %t7 = sub i32 -2147483647, %indvar + %t214 = xor i32 %t7, -2147483648 + ret i32 %t214 +} + define i32 @test29(i1 %C) { ; CHECK-LABEL: @test29( ; CHECK-NEXT: [[V:%.*]] = select i1 [[C:%.*]], i32 915, i32 113