Skip to content

Commit

Permalink
[ValueTracking] Add better support for ConstantRange(And)
Browse files Browse the repository at this point in the history
The fairly common power of two pattern `X & -X` can be capped at the
highest power of 2 (signbit set).
  • Loading branch information
goldsteinn committed Oct 12, 2023
1 parent 0f8b40a commit 50ece4c
Show file tree
Hide file tree
Showing 2 changed files with 7 additions and 10 deletions.
5 changes: 5 additions & 0 deletions llvm/lib/Analysis/ValueTracking.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -8492,6 +8492,11 @@ static void setLimitsForBinOp(const BinaryOperator &BO, APInt &Lower,
if (match(BO.getOperand(1), m_APInt(C)))
// 'and x, C' produces [0, C].
Upper = *C + 1;
// X & -X is a power of two or zero. So we can cap the value at max power of
// two.
if (match(BO.getOperand(0), m_Neg(m_Specific(BO.getOperand(1)))) ||
match(BO.getOperand(1), m_Neg(m_Specific(BO.getOperand(0)))))
Upper = APInt::getSignedMinValue(Width) + 1;
break;

case Instruction::Or:
Expand Down
12 changes: 2 additions & 10 deletions llvm/test/Analysis/ValueTracking/constant-ranges.ll
Original file line number Diff line number Diff line change
Expand Up @@ -96,11 +96,7 @@ define i1 @shl_X_C_ugt_fail2(i8 %x) {

define i1 @and_ugt(i8 %xx) {
; CHECK-LABEL: @and_ugt(
; CHECK-NEXT: [[X:%.*]] = mul i8 [[XX:%.*]], [[XX]]
; CHECK-NEXT: [[NEGX:%.*]] = sub i8 0, [[X]]
; CHECK-NEXT: [[X_P2:%.*]] = and i8 [[NEGX]], [[X]]
; CHECK-NEXT: [[R:%.*]] = icmp ugt i8 [[X_P2]], -128
; CHECK-NEXT: ret i1 [[R]]
; CHECK-NEXT: ret i1 false
;
%x = mul i8 %xx, %xx ; thwart complexity-based canonicalization
%negx = sub i8 0, %x
Expand All @@ -111,11 +107,7 @@ define i1 @and_ugt(i8 %xx) {

define i1 @and_ugt2(i8 %xx) {
; CHECK-LABEL: @and_ugt2(
; CHECK-NEXT: [[X:%.*]] = mul i8 [[XX:%.*]], [[XX]]
; CHECK-NEXT: [[NEGX:%.*]] = sub i8 0, [[X]]
; CHECK-NEXT: [[X_P2:%.*]] = and i8 [[X]], [[NEGX]]
; CHECK-NEXT: [[R:%.*]] = icmp ugt i8 [[X_P2]], -128
; CHECK-NEXT: ret i1 [[R]]
; CHECK-NEXT: ret i1 false
;
%x = mul i8 %xx, %xx ; thwart complexity-based canonicalization
%negx = sub i8 0, %x
Expand Down

0 comments on commit 50ece4c

Please sign in to comment.