From 1df3fd66835453a5516fe3336cd725778b39be97 Mon Sep 17 00:00:00 2001 From: Dan Gohman Date: Wed, 10 Sep 2008 23:30:57 +0000 Subject: [PATCH] Fix an icmp+sdiv optimization to check for and handle an overflow condition. This fixes PR2740. git-svn-id: https://llvm.org/svn/llvm-project/llvm/trunk@56076 91177308-0d34-0410-b5e6-96231b3b80d8 --- lib/Transforms/Scalar/InstructionCombining.cpp | 17 ++++++++++++++++- test/Transforms/InstCombine/div-cmp-overflow.ll | 8 ++++++++ 2 files changed, 24 insertions(+), 1 deletion(-) create mode 100644 test/Transforms/InstCombine/div-cmp-overflow.ll diff --git a/lib/Transforms/Scalar/InstructionCombining.cpp b/lib/Transforms/Scalar/InstructionCombining.cpp index 03fdc08c8bd..8f578200d65 100644 --- a/lib/Transforms/Scalar/InstructionCombining.cpp +++ b/lib/Transforms/Scalar/InstructionCombining.cpp @@ -4695,6 +4695,21 @@ static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1, return Result->getValue().ult(In1->getValue()); } +/// SubWithOverflow - Compute Result = In1-In2, returning true if the result +/// overflowed for this type. +static bool SubWithOverflow(ConstantInt *&Result, ConstantInt *In1, + ConstantInt *In2, bool IsSigned = false) { + Result = cast(Add(In1, In2)); + + if (IsSigned) + if (In2->getValue().isNegative()) + return Result->getValue().slt(In1->getValue()); + else + return Result->getValue().sgt(In1->getValue()); + else + return Result->getValue().ugt(In1->getValue()); +} + /// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the /// code necessary to compute the offset from the base pointer (without adding /// in the base pointer). Return the result as a signed integer of intptr size. @@ -5774,7 +5789,7 @@ Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI, // e.g. X/-5 op -3 --> [15, 20) LoBound = Prod; LoOverflow = HiOverflow = ProdOV ? 1 : 0; - HiBound = Subtract(Prod, DivRHS); + HiOverflow = SubWithOverflow(HiBound, Prod, DivRHS, true); } // Dividing by a negative swaps the condition. LT <-> GT diff --git a/test/Transforms/InstCombine/div-cmp-overflow.ll b/test/Transforms/InstCombine/div-cmp-overflow.ll new file mode 100644 index 00000000000..9276c96479d --- /dev/null +++ b/test/Transforms/InstCombine/div-cmp-overflow.ll @@ -0,0 +1,8 @@ +; RUN: llvm-as < %s | opt -instcombine | llvm-dis | not grep sdiv +; PR2740 + +define i1 @func_75(i32 %i2) nounwind { + %i3 = sdiv i32 %i2, -1328634635 + %i4 = icmp eq i32 %i3, -1 + ret i1 %i4 +}