Commit 40fcc424 authored by Sanjay Patel's avatar Sanjay Patel
Browse files

[InstCombine] fold mul of zext bools to 'and'

The base case only works because we are relying on a
poison-unsafe select transform; if that is fixed, we
would regress on patterns like this.

The extra use tests show that the select transform can't
be applied consistently. So it may be a regression to have
an extra instruction on 1 test, but that result was not
created safely and does not happen reliably.
parent 5d603778
Loading
Loading
Loading
Loading
+8 −0
Original line number Diff line number Diff line
@@ -366,6 +366,14 @@ Instruction *InstCombiner::visitMul(BinaryOperator &I) {
    }
  }

  // (zext bool X) * (zext bool Y) --> zext (and X, Y)
  if (match(Op0, m_ZExt(m_Value(X))) && X->getType()->isIntOrIntVectorTy(1) &&
      match(Op1, m_ZExt(m_Value(Y))) && Y->getType()->isIntOrIntVectorTy(1) &&
      (Op0->hasOneUse() || Op1->hasOneUse())) {
    Value *And = Builder.CreateAnd(X, Y, "mulbool");
    return CastInst::Create(Instruction::ZExt, And, I.getType());
  }

  // (bool X) * Y --> X ? Y : 0
  // Y * (bool X) --> X ? Y : 0
  if (match(Op0, m_ZExt(m_Value(X))) && X->getType()->isIntOrIntVectorTy(1))
+6 −5
Original line number Diff line number Diff line
@@ -129,8 +129,8 @@ define <2 x i32> @mul_bool_vec_commute(<2 x i32> %x, <2 x i1> %y) {

define <3 x i7> @mul_bools(<3 x i1> %x, <3 x i1> %y) {
; CHECK-LABEL: @mul_bools(
; CHECK-NEXT:    [[NARROW:%.*]] = and <3 x i1> [[X:%.*]], [[Y:%.*]]
; CHECK-NEXT:    [[R:%.*]] = zext <3 x i1> [[NARROW]] to <3 x i7>
; CHECK-NEXT:    [[MULBOOL:%.*]] = and <3 x i1> [[X:%.*]], [[Y:%.*]]
; CHECK-NEXT:    [[R:%.*]] = zext <3 x i1> [[MULBOOL]] to <3 x i7>
; CHECK-NEXT:    ret <3 x i7> [[R]]
;
  %zx = zext <3 x i1> %x to <3 x i7>
@@ -143,7 +143,8 @@ define i32 @mul_bools_use1(i1 %x, i1 %y) {
; CHECK-LABEL: @mul_bools_use1(
; CHECK-NEXT:    [[ZY:%.*]] = zext i1 [[Y:%.*]] to i32
; CHECK-NEXT:    call void @use32(i32 [[ZY]])
; CHECK-NEXT:    [[R:%.*]] = select i1 [[X:%.*]], i32 [[ZY]], i32 0
; CHECK-NEXT:    [[MULBOOL:%.*]] = and i1 [[X:%.*]], [[Y]]
; CHECK-NEXT:    [[R:%.*]] = zext i1 [[MULBOOL]] to i32
; CHECK-NEXT:    ret i32 [[R]]
;
  %zx = zext i1 %x to i32
@@ -157,8 +158,8 @@ define i32 @mul_bools_use2(i1 %x, i1 %y) {
; CHECK-LABEL: @mul_bools_use2(
; CHECK-NEXT:    [[ZY:%.*]] = zext i1 [[Y:%.*]] to i32
; CHECK-NEXT:    call void @use32(i32 [[ZY]])
; CHECK-NEXT:    [[NARROW:%.*]] = and i1 [[Y]], [[X:%.*]]
; CHECK-NEXT:    [[R:%.*]] = zext i1 [[NARROW]] to i32
; CHECK-NEXT:    [[MULBOOL:%.*]] = and i1 [[Y]], [[X:%.*]]
; CHECK-NEXT:    [[R:%.*]] = zext i1 [[MULBOOL]] to i32
; CHECK-NEXT:    ret i32 [[R]]
;
  %zx = zext i1 %x to i32