diff --git a/llvm/lib/Transforms/InstCombine/InstCombineCasts.cpp b/llvm/lib/Transforms/InstCombine/InstCombineCasts.cpp --- a/llvm/lib/Transforms/InstCombine/InstCombineCasts.cpp +++ b/llvm/lib/Transforms/InstCombine/InstCombineCasts.cpp @@ -951,15 +951,16 @@ } // trunc (ctlz_i32(zext(A), B) --> add(ctlz_i16(A, B), C) - if (match(Src, m_OneUse(m_Intrinsic( - m_OneUse(m_ZExt(m_Value(A))), m_Value(B))))) { - Value *WidthDiff = - ConstantInt::get(A->getType(), Src->getType()->getScalarSizeInBits() - - A->getType()->getScalarSizeInBits()); - - Value *NarrowCtlz = - Builder.CreateIntrinsic(Intrinsic::ctlz, {Trunc.getType()}, {A, B}); - return BinaryOperator::CreateAdd(NarrowCtlz, WidthDiff); + if (match(Src, m_OneUse(m_Intrinsic(m_ZExt(m_Value(A)), + m_Value(B))))) { + unsigned AWidth = A->getType()->getScalarSizeInBits(); + + if (AWidth == DestWidth && AWidth > 5) { + Value *WidthDiff = ConstantInt::get(A->getType(), SrcWidth - AWidth); + Value *NarrowCtlz = + Builder.CreateIntrinsic(Intrinsic::ctlz, {Trunc.getType()}, {A, B}); + return BinaryOperator::CreateAdd(NarrowCtlz, WidthDiff); + } } return nullptr; } diff --git a/llvm/test/Transforms/InstCombine/zext-ctlz-trunc-to-ctlz-add.ll b/llvm/test/Transforms/InstCombine/zext-ctlz-trunc-to-ctlz-add.ll --- a/llvm/test/Transforms/InstCombine/zext-ctlz-trunc-to-ctlz-add.ll +++ b/llvm/test/Transforms/InstCombine/zext-ctlz-trunc-to-ctlz-add.ll @@ -71,8 +71,8 @@ define @trunc_ctlz_zext_nxv2i16_nxv2i63_multiple_uses( %x) { ; CHECK-LABEL: @trunc_ctlz_zext_nxv2i16_nxv2i63_multiple_uses( ; CHECK-NEXT: [[Z:%.*]] = zext [[X:%.*]] to -; CHECK-NEXT: [[P:%.*]] = call @llvm.ctlz.nxv2i63( [[Z]], i1 true) -; CHECK-NEXT: [[ZZ:%.*]] = trunc [[P]] to +; CHECK-NEXT: [[TMP1:%.*]] = call @llvm.ctlz.nxv2i16( [[X]], i1 true) +; CHECK-NEXT: [[ZZ:%.*]] = add nuw nsw [[TMP1]], shufflevector ( insertelement ( undef, i16 47, i32 0), undef, zeroinitializer) ; CHECK-NEXT: call void @use1( [[Z]]) ; CHECK-NEXT: ret [[ZZ]] ; @@ -83,3 +83,33 @@ ret %zz } +; Negative case where types of x and zz don't match + +define i16 @trunc_ctlz_zext_i10_i32(i10 %x) { +; CHECK-LABEL: @trunc_ctlz_zext_i10_i32( +; CHECK-NEXT: [[Z:%.*]] = zext i10 [[X:%.*]] to i32 +; CHECK-NEXT: [[P:%.*]] = call i32 @llvm.ctlz.i32(i32 [[Z]], i1 false), !range [[RNG1:![0-9]+]] +; CHECK-NEXT: [[ZZ:%.*]] = trunc i32 [[P]] to i16 +; CHECK-NEXT: ret i16 [[ZZ]] +; + %z = zext i10 %x to i32 + %p = call i32 @llvm.ctlz.i32(i32 %z, i1 false) + %zz = trunc i32 %p to i16 + ret i16 %zz +} + +; Negative case where size of x is less than 6 + +define i5 @trunc_ctlz_zext_i5_i32(i5 %x) { +; CHECK-LABEL: @trunc_ctlz_zext_i5_i32( +; CHECK-NEXT: [[Z:%.*]] = zext i5 [[X:%.*]] to i32 +; CHECK-NEXT: [[P:%.*]] = call i32 @llvm.ctlz.i32(i32 [[Z]], i1 false), !range [[RNG2:![0-9]+]] +; CHECK-NEXT: [[ZZ:%.*]] = trunc i32 [[P]] to i5 +; CHECK-NEXT: ret i5 [[ZZ]] +; + %z = zext i5 %x to i32 + %p = call i32 @llvm.ctlz.i32(i32 %z, i1 false) + %zz = trunc i32 %p to i5 + ret i5 %zz +} +