Index: llvm/lib/Analysis/DemandedBits.cpp =================================================================== --- llvm/lib/Analysis/DemandedBits.cpp +++ llvm/lib/Analysis/DemandedBits.cpp @@ -173,7 +173,30 @@ } break; case Instruction::Add: - case Instruction::Sub: + case Instruction::Sub: { + ComputeKnownBits(BitWidth, UserI->getOperand(0), UserI->getOperand(1)); + // When Bound == 0, this should behave just like + // AB = APInt::getLowBitsSet(BitWidth, AOut.getActiveBits()); + APInt Bound1; + if (UserI->getOpcode() == Instruction::Add) + Bound1 = Known.Zero; + else + Bound1 = Known.One; + APInt Bound2 = Known2.Zero; + APInt Bound = Bound1 & Bound2; + APInt RBound = Bound.reverseBits(); + APInt RAOut = AOut.reverseBits(); + APInt RProp = RAOut + (RAOut | ~RBound); + APInt RQ = (RProp ^ ~(RAOut | RBound)); + APInt Q = RQ.reverseBits(); + APInt U; + if (OperandNo == 0) + U = Bound1 | ~Bound2; + else + U = Bound2 | ~Bound1; + AB = AOut | (Q & (U | (Bound1 + Bound2 + 1))); + break; + } case Instruction::Mul: // Find the highest live output bit. We don't need any more input // bits than that (adds, and thus subtracts, ripple only to the Index: llvm/test/Analysis/DemandedBits/add.ll =================================================================== --- /dev/null +++ llvm/test/Analysis/DemandedBits/add.ll @@ -0,0 +1,18 @@ +; RUN: opt -S -demanded-bits -analyze < %s | FileCheck %s +; RUN: opt -S -disable-output -passes="print" < %s 2>&1 | FileCheck %s + +; CHECK-DAG: DemandedBits: 0x1e for %1 = and i32 %a, 9 +; CHECK-DAG: DemandedBits: 0x1a for %2 = and i32 %b, 9 +; CHECK-DAG: DemandedBits: 0x1a for %3 = and i32 %c, 13 +; CHECK-DAG: DemandedBits: 0x1a for %4 = and i32 %d, 4 +define i32 @test_add(i32 %a, i32 %b, i32 %c, i32 %d) { + %1 = and i32 %a, 9 + %2 = and i32 %b, 9 + %3 = and i32 %c, 13 + %4 = and i32 %d, 4 ; dead + %5 = or i32 %2, %3 + %6 = or i32 %4, %5 + %7 = add i32 %1, %6 + %8 = and i32 %7, 16 + ret i32 %8 +}