From 5be2920149a96a17d8d4e08d36466fac0d624fa4 Mon Sep 17 00:00:00 2001 From: Nick Lewycky Date: Sun, 3 Feb 2008 16:33:09 +0000 Subject: [PATCH] There are some cases where icmp(add) can be folded into a new icmp. Handle them. git-svn-id: https://llvm.org/svn/llvm-project/llvm/trunk@46687 91177308-0d34-0410-b5e6-96231b3b80d8 --- .../Scalar/InstructionCombining.cpp | 32 +++++++++++++++++++ .../InstCombine/2008-01-29-AddICmp.ll | 19 +++++++++++ 2 files changed, 51 insertions(+) create mode 100644 test/Transforms/InstCombine/2008-01-29-AddICmp.ll diff --git a/lib/Transforms/Scalar/InstructionCombining.cpp b/lib/Transforms/Scalar/InstructionCombining.cpp index 404b53db863..f55aff31255 100644 --- a/lib/Transforms/Scalar/InstructionCombining.cpp +++ b/lib/Transforms/Scalar/InstructionCombining.cpp @@ -45,6 +45,7 @@ #include "llvm/Transforms/Utils/BasicBlockUtils.h" #include "llvm/Transforms/Utils/Local.h" #include "llvm/Support/CallSite.h" +#include "llvm/Support/ConstantRange.h" #include "llvm/Support/Debug.h" #include "llvm/Support/GetElementPtrTypeIterator.h" #include "llvm/Support/InstVisitor.h" @@ -5704,6 +5705,37 @@ Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI, DivRHS)) return R; break; + + case Instruction::Add: + // Fold: icmp pred (add, X, C1), C2 + + if (!ICI.isEquality()) { + ConstantInt *LHSC = dyn_cast(LHSI->getOperand(1)); + if (!LHSC) break; + const APInt &LHSV = LHSC->getValue(); + + ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV) + .subtract(LHSV); + + if (ICI.isSignedPredicate()) { + if (CR.getLower().isSignBit()) { + return new ICmpInst(ICmpInst::ICMP_SLT, LHSI->getOperand(0), + ConstantInt::get(CR.getUpper())); + } else if (CR.getUpper().isSignBit()) { + return new ICmpInst(ICmpInst::ICMP_SGE, LHSI->getOperand(0), + ConstantInt::get(CR.getLower())); + } + } else { + if (CR.getLower().isMinValue()) { + return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0), + ConstantInt::get(CR.getUpper())); + } else if (CR.getUpper().isMinValue()) { + return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0), + ConstantInt::get(CR.getLower())); + } + } + } + break; } // Simplify icmp_eq and icmp_ne instructions with integer constant RHS. diff --git a/test/Transforms/InstCombine/2008-01-29-AddICmp.ll b/test/Transforms/InstCombine/2008-01-29-AddICmp.ll new file mode 100644 index 00000000000..43604b8b130 --- /dev/null +++ b/test/Transforms/InstCombine/2008-01-29-AddICmp.ll @@ -0,0 +1,19 @@ +; RUN: llvm-as < %s | opt -instcombine | llvm-dis | not grep {a.off} + +define i1 @test1(i32 %a) { + %a.off = add i32 %a, 4 ; [#uses=1] + %C = icmp ult i32 %a.off, 4 ; [#uses=1] + ret i1 %C +} + +define i1 @test2(i32 %a) { + %a.off = sub i32 %a, 4 ; [#uses=1] + %C = icmp ugt i32 %a.off, -5 ; [#uses=1] + ret i1 %C +} + +define i1 @test3(i32 %a) { + %a.off = add i32 %a, 4 ; [#uses=1] + %C = icmp slt i32 %a.off, 2147483652 ; [#uses=1] + ret i1 %C +} -- 2.34.1