diff --git a/llvm/lib/Transforms/InstCombine/InstCombineMulDivRem.cpp b/llvm/lib/Transforms/InstCombine/InstCombineMulDivRem.cpp --- a/llvm/lib/Transforms/InstCombine/InstCombineMulDivRem.cpp +++ b/llvm/lib/Transforms/InstCombine/InstCombineMulDivRem.cpp @@ -888,9 +888,13 @@ auto *Shl0 = cast(Op0); auto *Shl1 = cast(Op1); - // For unsigned div, we need 'nuw' on both shifts. + // For unsigned div, we need 'nuw' on both shifts or + // 'nsw' on both shifts + 'nuw' on the dividend. // (X << Z) / (Y << Z) --> X / Y - if (!IsSigned && Shl0->hasNoUnsignedWrap() && Shl1->hasNoUnsignedWrap()) + if (!IsSigned && + ((Shl0->hasNoUnsignedWrap() && Shl1->hasNoUnsignedWrap()) || + (Shl0->hasNoUnsignedWrap() && Shl0->hasNoSignedWrap() && + Shl1->hasNoSignedWrap()))) Ret = BinaryOperator::CreateUDiv(X, Y); // For signed div, we need 'nsw' on both shifts + 'nuw' on the divisor. diff --git a/llvm/test/Transforms/InstCombine/div-shift.ll b/llvm/test/Transforms/InstCombine/div-shift.ll --- a/llvm/test/Transforms/InstCombine/div-shift.ll +++ b/llvm/test/Transforms/InstCombine/div-shift.ll @@ -951,13 +951,9 @@ ret i8 %d } -; TODO: This could fold. - define i8 @udiv_shl_shl_nuw_nsw2(i8 %x, i8 %y, i8 %z) { ; CHECK-LABEL: @udiv_shl_shl_nuw_nsw2( -; CHECK-NEXT: [[XZ:%.*]] = shl nuw nsw i8 [[X:%.*]], [[Z:%.*]] -; CHECK-NEXT: [[YZ:%.*]] = shl nsw i8 [[Y:%.*]], [[Z]] -; CHECK-NEXT: [[D:%.*]] = udiv i8 [[XZ]], [[YZ]] +; CHECK-NEXT: [[D:%.*]] = udiv i8 [[X:%.*]], [[Y:%.*]] ; CHECK-NEXT: ret i8 [[D]] ; %xz = shl nuw nsw i8 %x, %z