Index: llvm/lib/Transforms/InstCombine/InstCombineMulDivRem.cpp =================================================================== --- llvm/lib/Transforms/InstCombine/InstCombineMulDivRem.cpp +++ llvm/lib/Transforms/InstCombine/InstCombineMulDivRem.cpp @@ -1021,6 +1021,12 @@ return new SExtInst(NarrowOp, Op0->getType()); } } + + // -X / Y --> -(X / Y) + Value *Y; + if (match(&I, m_SDiv(m_OneUse(m_NSWSub(m_Zero(), m_Value(X))), m_Value(Y)))) + return BinaryOperator::CreateNeg( + Builder.CreateSDiv(X, Y, I.getName(), I.isExact())); if (Constant *RHS = dyn_cast(Op1)) { // X/INT_MIN -> X == INT_MIN Index: llvm/test/Transforms/InstCombine/sdiv-canonicalize.ll =================================================================== --- llvm/test/Transforms/InstCombine/sdiv-canonicalize.ll +++ llvm/test/Transforms/InstCombine/sdiv-canonicalize.ll @@ -3,8 +3,8 @@ define i32 @test_sdiv_canonicalize_op0(i32 %x, i32 %y) { ; CHECK-LABEL: @test_sdiv_canonicalize_op0( -; CHECK-NEXT: [[NEG:%.*]] = sub nsw i32 0, [[X:%.*]] -; CHECK-NEXT: [[SDIV:%.*]] = sdiv i32 [[NEG]], [[Y:%.*]] +; CHECK-NEXT: [[SDIV1:%.*]] = sdiv i32 [[X:%.*]], [[Y:%.*]] +; CHECK-NEXT: [[SDIV:%.*]] = sub i32 0, [[SDIV1]] ; CHECK-NEXT: ret i32 [[SDIV]] ; %neg = sub nsw i32 0, %x @@ -12,6 +12,7 @@ ret i32 %sdiv } +; (X/-Y) is not equal to -(X/Y), don't canonicalize. define i32 @test_sdiv_canonicalize_op1(i32 %x, i32 %z) { ; CHECK-LABEL: @test_sdiv_canonicalize_op1( ; CHECK-NEXT: [[Y:%.*]] = mul i32 [[Z:%.*]], 3 @@ -38,8 +39,8 @@ define <2 x i32> @test_sdiv_canonicalize_vec(<2 x i32> %x, <2 x i32> %y) { ; CHECK-LABEL: @test_sdiv_canonicalize_vec( -; CHECK-NEXT: [[NEG:%.*]] = sub nsw <2 x i32> zeroinitializer, [[X:%.*]] -; CHECK-NEXT: [[SDIV:%.*]] = sdiv <2 x i32> [[NEG]], [[Y:%.*]] +; CHECK-NEXT: [[SDIV1:%.*]] = sdiv <2 x i32> [[X:%.*]], [[Y:%.*]] +; CHECK-NEXT: [[SDIV:%.*]] = sub <2 x i32> zeroinitializer, [[SDIV1]] ; CHECK-NEXT: ret <2 x i32> [[SDIV]] ; %neg = sub nsw <2 x i32> , %x @@ -60,9 +61,8 @@ ret i32 %sdiv2 } -; There is combination: (X/-CE) -> -(X/CE) -; There is another combination: -(X/CE) -> (X/-CE) -; Make sure don't combine them endless. +; There is combination: -(X/CE) -> (X/-CE). +; If combines (X/-CE) to -(X/CE), make sure don't combine them endless. @X = global i32 5