[llvm] [InstCombine] Fold adds + shifts with nsw and nuw flags (PR #88193)

Matt Arsenault via llvm-commits llvm-commits at lists.llvm.org
Sun Apr 21 09:47:50 PDT 2024


================
@@ -360,8 +360,64 @@ define <3 x i14> @mul_splat_fold_vec(<3 x i14> %x) {
   ret <3 x i14> %t
 }
 
+define i32 @mul_times_3_div_2 (i32 %x) {
+; CHECK-LABEL: @mul_times_3_div_2(
+; CHECK-NEXT:    [[TMP2:%.*]] = lshr i32 [[TMP1:%.*]], 1
+; CHECK-NEXT:    [[TMP3:%.*]] = add nuw nsw i32 [[TMP2]], [[TMP1]]
+; CHECK-NEXT:    ret i32 [[TMP3]]
+;
+  %2 = mul nsw nuw i32 %x, 3
+  %3 = lshr i32 %2, 1
+  ret i32 %3
+}
+
+  define i32 @shl_add_lshr (i32 %x, i32 %c, i32 %y) {
+; CHECK-LABEL: @shl_add_lshr(
+; CHECK-NEXT:    [[TMP3:%.*]] = lshr exact i32 [[TMP2:%.*]], [[C:%.*]]
+; CHECK-NEXT:    [[TMP4:%.*]] = add nuw nsw i32 [[TMP3]], [[X:%.*]]
+; CHECK-NEXT:    ret i32 [[TMP4]]
+;
+  %2 = shl nuw i32 %x, %c
+  %3 = add nuw nsw i32 %2, %y
+  %4 = lshr exact i32 %3, %c
+  ret i32 %4
+}
+
+  define i32 @ashr_mul_times_3_div_2 (i32 %0) {
+; CHECK-LABEL: @ashr_mul_times_3_div_2(
+; CHECK-NEXT:    [[TMP2:%.*]] = lshr i32 [[TMP0:%.*]], 1
+; CHECK-NEXT:    [[TMP3:%.*]] = add nuw nsw i32 [[TMP2]], [[TMP0]]
+; CHECK-NEXT:    ret i32 [[TMP3]]
+;
+  %2 = mul nsw nuw i32 %0, 3
+  %3 = ashr i32 %2, 1
+  ret i32 %3
+}
+
+define i32 @ashr_mul_times_3_div_2_exact (i32 %0) {
+; CHECK-LABEL: @ashr_mul_times_3_div_2_exact(
+; CHECK-NEXT:    [[TMP3:%.*]] = ashr exact i32 [[TMP2:%.*]], 1
+; CHECK-NEXT:    [[TMP4:%.*]] = add nsw i32 [[TMP3]], [[TMP2]]
+; CHECK-NEXT:    ret i32 [[TMP4]]
+;
+  %2 = mul nsw i32 %0, 3
+  %3 = ashr exact i32 %2, 1
+  ret i32 %3
+}
+
 ; Negative test
 
+define i32 @mul_times_3_div_2_no_nsw (i32 %x) {
+; CHECK-LABEL: @mul_times_3_div_2_no_nsw(
+; CHECK-NEXT:    [[TMP1:%.*]] = mul i32 [[X:%.*]], 3
+; CHECK-NEXT:    [[TMP2:%.*]] = lshr i32 [[TMP1]], 1
+; CHECK-NEXT:    ret i32 [[TMP2]]
+;
+  %2 = mul i32 %x, 3
+  %3 = lshr i32 %2, 1
+  ret i32 %3
+}
+
----------------
arsenm wrote:

Missing negative tests for multiple uses and individual flag missing cases 

https://github.com/llvm/llvm-project/pull/88193


More information about the llvm-commits mailing list