From 39390d8317003ffc0627a30ae913bba3b3616efb Mon Sep 17 00:00:00 2001 From: Roman Lebedev Date: Fri, 31 May 2019 09:47:16 +0000 Subject: [PATCH] [InstCombine] 'C-(C2-X) --> X+(C-C2)' constant-fold It looks this fold was already partially happening, indirectly via some other folds, but with one-use limitation. No other fold here has that restriction. https://rise4fun.com/Alive/ftR llvm-svn: 362217 --- llvm/lib/Transforms/InstCombine/InstCombineAddSub.cpp | 7 ++++++- .../test/Transforms/InstCombine/addsub-constant-folding.ll | 4 ++-- 2 files changed, 8 insertions(+), 3 deletions(-) diff --git a/llvm/lib/Transforms/InstCombine/InstCombineAddSub.cpp b/llvm/lib/Transforms/InstCombine/InstCombineAddSub.cpp index d422b07d49fe..e6b32ba13a4a 100644 --- a/llvm/lib/Transforms/InstCombine/InstCombineAddSub.cpp +++ b/llvm/lib/Transforms/InstCombine/InstCombineAddSub.cpp @@ -1609,8 +1609,13 @@ Instruction *InstCombiner::visitSub(BinaryOperator &I) { if (Instruction *R = foldOpIntoPhi(I, PN)) return R; - // C-(X+C2) --> (C-C2)-X Constant *C2; + + // C-(C2-X) --> X+(C-C2) + if (match(Op1, m_Sub(m_Constant(C2), m_Value(X)))) + return BinaryOperator::CreateAdd(X, ConstantExpr::getSub(C, C2)); + + // C-(X+C2) --> (C-C2)-X if (match(Op1, m_Add(m_Value(X), m_Constant(C2)))) return BinaryOperator::CreateSub(ConstantExpr::getSub(C, C2), X); } diff --git a/llvm/test/Transforms/InstCombine/addsub-constant-folding.ll b/llvm/test/Transforms/InstCombine/addsub-constant-folding.ll index 66c1e6e91684..2d9918737d2a 100644 --- a/llvm/test/Transforms/InstCombine/addsub-constant-folding.ll +++ b/llvm/test/Transforms/InstCombine/addsub-constant-folding.ll @@ -485,7 +485,7 @@ define i32 @const_sub_const_sub_extrause(i32 %arg) { ; CHECK-LABEL: @const_sub_const_sub_extrause( ; CHECK-NEXT: [[T0:%.*]] = sub i32 8, [[ARG:%.*]] ; CHECK-NEXT: call void @use(i32 [[T0]]) -; CHECK-NEXT: [[T1:%.*]] = sub i32 2, [[T0]] +; CHECK-NEXT: [[T1:%.*]] = add i32 [[ARG]], -6 ; CHECK-NEXT: ret i32 [[T1]] ; %t0 = sub i32 8, %arg @@ -508,7 +508,7 @@ define <4 x i32> @vec_const_sub_const_sub_extrause(<4 x i32> %arg) { ; CHECK-LABEL: @vec_const_sub_const_sub_extrause( ; CHECK-NEXT: [[T0:%.*]] = sub <4 x i32> , [[ARG:%.*]] ; CHECK-NEXT: call void @vec_use(<4 x i32> [[T0]]) -; CHECK-NEXT: [[T1:%.*]] = sub <4 x i32> , [[T0]] +; CHECK-NEXT: [[T1:%.*]] = add <4 x i32> [[ARG]], ; CHECK-NEXT: ret <4 x i32> [[T1]] ; %t0 = sub <4 x i32> , %arg