From 746b0ca7fc9c319ee5f2b2f1fa4ccb3d26da6bc4 Mon Sep 17 00:00:00 2001 From: Minzy Fox Date: Mon, 30 Nov 2026 15:51:45 -0800 Subject: [PATCH 1/3] codegen: preserve i32 range bounds when narrowing loop counters Mark signed i32 loop-counter narrowing as exact in both code generators. This lets LLVM remove redundant checks and vectorize the loop. Fold exact counter conversions before raising affine accesses, preserving loop fusion. Guard against unflagged truncations and earlier casts that lose bits. Add tests for check removal, vectorization, conversion guards, and signed and unsigned edge values. Validation: 1,046 library tests, focused regressions, and flat-backend coverage passed. Four GPU optimization failures also reproduce on main. Fixes: #3269 --- src/codegen/flat.rs | 4 +-- src/codegen/flat/emit/control.rs | 9 +++++- src/codegen/lower/control_flow.rs | 30 ++++++++++++++++--- src/dialect/VxLowering.cpp | 17 +++++++++++ .../pass/counted_loops_become_affine_loops.vx | 1 + 5 files changed, 54 insertions(+), 7 deletions(-) diff --git a/src/codegen/flat.rs b/src/codegen/flat.rs index 47ac2a420..fcb86ecff 100644 --- a/src/codegen/flat.rs +++ b/src/codegen/flat.rs @@ -4795,7 +4795,7 @@ mod tests { #[test] fn emits_verifiable_affine_for_loop() { // A signed range that nothing leaves is an `affine.for`. The bound `n` is cast to `index` - // before the loop, and the loop variable is cast back to `i32`. + // before the loop, and the loop variable becomes an i32 without signed overflow. let mlir = emit_and_verify( "fn sum(n: i32) -> i32 { let mut s = 0; for i in 0..n { s = s + i; } return s; }", ); @@ -4804,7 +4804,7 @@ mod tests { "{mlir}" ); assert!(mlir.contains("affine.for "), "{mlir}"); - assert!(mlir.contains(" : index to i32"), "{mlir}"); + assert!(mlir.contains("overflow : i64 to i32"), "{mlir}"); assert!(!mlir.contains("cf.cond_br "), "{mlir}"); assert!(!mlir.contains("scf.execute_region"), "{mlir}"); } diff --git a/src/codegen/flat/emit/control.rs b/src/codegen/flat/emit/control.rs index fef16177f..ca4dee663 100644 --- a/src/codegen/flat/emit/control.rs +++ b/src/codegen/flat/emit/control.rs @@ -289,7 +289,14 @@ impl FnEmit<'_> { let branches = ins.imm & AFFINE_FOR_BRANCHES != 0; let at = self.body.len(); self.body += &format!(" affine.for {index} = {} to {} {{\n", bounds[0], bounds[1]); - self.body += &format!(" %v{idx} = arith.index_cast {index} : index to {mt}\n"); + if e == ElementType::I32 { + // Both bounds are i32, so every counter value fits without signed overflow. + self.body += &format!(" %v{idx}_wide = arith.index_cast {index} : index to i64\n"); + self.body += + &format!(" %v{idx} = arith.trunci %v{idx}_wide overflow : i64 to i32\n"); + } else { + self.body += &format!(" %v{idx} = arith.index_cast {index} : index to {mt}\n"); + } if branches { self.body += " scf.execute_region {\n"; } diff --git a/src/codegen/lower/control_flow.rs b/src/codegen/lower/control_flow.rs index ceb9b9d1d..bcde02607 100644 --- a/src/codegen/lower/control_flow.rs +++ b/src/codegen/lower/control_flow.rs @@ -662,10 +662,32 @@ fn lower_for_loop<'c>( // a tuple or a tensor literal that holds it then gets the type it expects. let iter_binding = if start_ty != ty_index && melior::ir::r#type::TypeLike::is_integer(&start_ty) { - let cast = OperationBuilder::new("arith.index_cast", gen.loc()) - .add_operands(&[current_idx]) - .add_results(&[start_ty]) - .build()?; + let cast = if start_ty == gen.i32_ty && !range_is_unsigned(gen, for_loop) { + // Both bounds are i32, so every counter value fits without signed overflow. + let wide = body_block + .append_operation( + OperationBuilder::new("arith.index_cast", gen.loc()) + .add_operands(&[current_idx]) + .add_results(&[gen.i64_ty]) + .build()?, + ) + .result(0)? + .into(); + OperationBuilder::new("arith.trunci", gen.loc()) + .add_operands(&[wide]) + .add_results(&[start_ty]) + .add_attributes(&[( + Identifier::new(gen.context, "overflowFlags"), + melior::ir::Attribute::parse(gen.context, "#arith.overflow") + .expect("valid signed overflow flag"), + )]) + .build()? + } else { + OperationBuilder::new("arith.index_cast", gen.loc()) + .add_operands(&[current_idx]) + .add_results(&[start_ty]) + .build()? + }; ( body_block.append_operation(cast).result(0)?.into(), start_ty, diff --git a/src/dialect/VxLowering.cpp b/src/dialect/VxLowering.cpp index 3139ad060..82a03cd0a 100644 --- a/src/dialect/VxLowering.cpp +++ b/src/dialect/VxLowering.cpp @@ -13950,6 +13950,23 @@ struct RaiseLoopAccessesPass void runOnOperation() override { func::FuncOp func = getOperation(); + // An exact signed truncation followed by a cast back to index recovers the + // counter. Fold it before raising accesses, so a[i] stays an affine access. + unsigned indexBits = DataLayout::closest(func) + .getTypeSizeInBits(IndexType::get(&getContext())) + .getFixedValue(); + func.walk([&](arith::IndexCastOp cast) { + auto trunc = cast.getIn().getDefiningOp(); + if (!trunc || !trunc.hasNoSignedWrap()) + return; + auto wide = trunc.getIn().getDefiningOp(); + if (wide && isa(wide.getType()) && + wide.getType().getIntOrFloatBitWidth() >= indexBits && + wide.getIn().getType() == cast.getType()) { + cast.replaceAllUsesWith(wide.getIn()); + cast.erase(); + } + }); OpPassManager pm(func::FuncOp::getOperationName()); if (failed(parsePassPipeline("affine-raise-from-memref", pm)) || failed(runPipeline(pm, func))) { diff --git a/tests/optimizations/pass/counted_loops_become_affine_loops.vx b/tests/optimizations/pass/counted_loops_become_affine_loops.vx index 84d743e60..02c450193 100644 --- a/tests/optimizations/pass/counted_loops_become_affine_loops.vx +++ b/tests/optimizations/pass/counted_loops_become_affine_loops.vx @@ -52,6 +52,7 @@ fn triangle(n: i32) -> i32 { // IF-LABEL: func.func @with_if // IF: affine.for // IF-NEXT: arith.index_cast +// IF-NEXT: arith.trunci // IF-NEXT: scf.execute_region { fn with_if(n: i32) -> i32 { let mut s = 0; From fc82bbc9820f99a530ea75e6a99b499bd60d5ebb Mon Sep 17 00:00:00 2001 From: Minzy Fox Date: Mon, 30 Nov 2026 19:27:04 -0800 Subject: [PATCH 2/3] tests: cover i32 loop check removal and counter conversions Add the missing regression fixtures for redundant check removal, vectorization, and safe counter conversion folding. Check signed and unsigned edge values at -O0 and -O3 with both code generators. Validation: all 13 fixture commands, targeted mutation checks, and flat-backend coverage passed. Issue: #3269 --- .../exact_counter_casts_recover_the_index.mlr | 47 +++++++++++ .../pass/i32_range_checks_are_removed.vx | 83 +++++++++++++++++++ 2 files changed, 130 insertions(+) create mode 100644 tests/optimizations/pass/exact_counter_casts_recover_the_index.mlr create mode 100644 tests/optimizations/pass/i32_range_checks_are_removed.vx diff --git a/tests/optimizations/pass/exact_counter_casts_recover_the_index.mlr b/tests/optimizations/pass/exact_counter_casts_recover_the_index.mlr new file mode 100644 index 000000000..8dfdf5e44 --- /dev/null +++ b/tests/optimizations/pass/exact_counter_casts_recover_the_index.mlr @@ -0,0 +1,47 @@ +// An exact signed narrowing can recover an index only if the first cast kept every bit. +// RUN: vxc %s -x mlir --emit-mlir -X mlir=--pass-pipeline="builtin.module(func.func(vx-raise-loop-accesses))" | FileCheck %s +module { + // CHECK-LABEL: func.func @exact( + // CHECK-SAME: %[[ORIGINAL:[^:]+]]: index) + // CHECK-NOT: func.func + // CHECK: return %[[ORIGINAL]] : index + func.func @exact(%i: index) -> index { + %wide = arith.index_cast %i : index to i64 + %small = arith.trunci %wide overflow : i64 to i32 + %back = arith.index_cast %small : i32 to index + return %back : index + } + + // CHECK-LABEL: func.func @may_wrap( + // CHECK-NOT: func.func + // CHECK: %[[BACK:[^ ]+]] = arith.index_cast {{.*}} : i32 to index + // CHECK: return %[[BACK]] : index + func.func @may_wrap(%i: index) -> index { + %wide = arith.index_cast %i : index to i64 + %small = arith.trunci %wide : i64 to i32 + %back = arith.index_cast %small : i32 to index + return %back : index + } + + // CHECK-LABEL: func.func @first_cast_loses_bits( + // CHECK-NOT: func.func + // CHECK: %[[NARROW_BACK:[^ ]+]] = arith.index_cast {{.*}} : i16 to index + // CHECK: return %[[NARROW_BACK]] : index + func.func @first_cast_loses_bits(%i: index) -> index { + %wide = arith.index_cast %i : index to i32 + %small = arith.trunci %wide overflow : i32 to i16 + %back = arith.index_cast %small : i16 to index + return %back : index + } + + // Vector casts are also legal input to the pass. + // CHECK-LABEL: func.func @vector_casts( + // CHECK-NOT: func.func + // CHECK: return {{.*}} : vector<2xindex> + func.func @vector_casts(%i: vector<2xindex>) -> vector<2xindex> { + %wide = arith.index_cast %i : vector<2xindex> to vector<2xi64> + %small = arith.trunci %wide overflow : vector<2xi64> to vector<2xi32> + %back = arith.index_cast %small : vector<2xi32> to vector<2xindex> + return %back : vector<2xindex> + } +} diff --git a/tests/optimizations/pass/i32_range_checks_are_removed.vx b/tests/optimizations/pass/i32_range_checks_are_removed.vx new file mode 100644 index 000000000..9c9c2f380 --- /dev/null +++ b/tests/optimizations/pass/i32_range_checks_are_removed.vx @@ -0,0 +1,83 @@ +//===- i32_range_checks_are_removed.vx - Vx Compiler ----------*- Vx -*-===// +// +// Part of the Vx Project, under the Apache License v2.0 with LLVM Exceptions. +// See LICENSE for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +// An i32 range keeps its signed bounds when the loop counter becomes an i32. +// LLVM can then remove the helper's redundant check. +// +// REQUIRES: flat-codegen +// REQUIRES: x86_64 +// REQUIRES: aarch64 +// RUN: vxc %s --emit-mlir 2>/dev/null | FileCheck %s --check-prefix=CAST +// RUN: vxc %s --legacy-codegen --emit-mlir 2>/dev/null | FileCheck %s --check-prefix=LEGACY +// RUN: vxc %s -O3 --emit-llvm 2>/dev/null | mlir-translate --mlir-to-llvmir | opt -mtriple=%arch-unknown-linux-gnu -mcpu=native -passes='default' -S > %t.ll +// RUN: FileCheck %s --check-prefix=OPT < %t.ll +// RUN: FileCheck %s --check-prefix=VECTOR < %t.ll +// RUN: vxc %s --legacy-codegen -O3 --emit-llvm 2>/dev/null | mlir-translate --mlir-to-llvmir | opt -mtriple=%arch-unknown-linux-gnu -mcpu=native -passes='default' -S > %t.legacy.ll +// RUN: FileCheck %s --check-prefix=OPT < %t.legacy.ll +// RUN: FileCheck %s --check-prefix=VECTOR < %t.legacy.ll +// RUN: vxc %s -O0 2>/dev/null | FileCheck %s --check-prefix=ANSWER +// RUN: vxc %s --legacy-codegen -O0 2>/dev/null | FileCheck %s --check-prefix=ANSWER +// RUN: vxc %s -O3 2>/dev/null | FileCheck %s --check-prefix=ANSWER +// RUN: vxc %s --legacy-codegen -O3 2>/dev/null | FileCheck %s --check-prefix=ANSWER + +import core::convert; +import std::vec; + +fn checked_value(p : *mut i64, i : i32, n : i32) -> i64 { + assert(i < n, "index out of range"); + return unsafe { p[i] }; +} + +// CAST-LABEL: func.func @sum_counts( +// CAST-NOT: func.func +// CAST: affine.for %[[INDEX:[^ ]+]] +// CAST: %[[WIDE:[^ ]+]] = arith.index_cast %[[INDEX]] : index to i64 +// CAST-NEXT: {{.*}}arith.trunci %[[WIDE]] overflow : i64 to i32 +// LEGACY-LABEL: func.func @sum_counts( +// LEGACY-NOT: func.func +// LEGACY: arith.trunci {{.*}} overflow : i64 to i32 +// OPT-LABEL: define {{.*}} @sum_counts( +// OPT-NOT: @abort +// OPT: {{^}}} +// VECTOR-LABEL: define {{.*}} @sum_counts( +// VECTOR-NOT: {{^}}} +// VECTOR: call i64 @llvm.vector.reduce.add.v{{[0-9]+}}i64( +// VECTOR: {{^}}} +fn sum_counts(p : *mut i64, n : i32) -> i64 { + let mut total : i64 = 0; + for i in 0..n { + total = total + checked_value(p, i, n); + } + return total; +} + +fn sum_range(first : i32, last : i32) -> i64 { + let mut total : i64 = 0; + for i in first..last { + total = total + i64::from(i); + } + return total; +} + +fn sum_unsigned(first : u32, last : u32) -> u64 { + let mut total : u64 = 0; + for i in first..last { + total = total + u64::from(i); + } + return total; +} + +// ANSWER: {{^}}16 -5 2147483646 -4294967295 0 4294967294{{$}} +fn main() -> i32 { + let mut values = Vec::with_capacity(16); + for i in 0..16 { + values.push(1); + } + println!("{} {} {} {} {} {}", sum_counts(values.as_mut_ptr(), 16), sum_range(-3, 2), + sum_range(2147483646, 2147483647), sum_range(-2147483648, -2147483646), sum_range(2, -3), sum_unsigned(4294967294u32, 4294967295u32)); + return 0; +} From 14b9521aa089ee191cd2b990fcf6f8bfa78dab15 Mon Sep 17 00:00:00 2001 From: Minzy Fox Date: Tue, 1 Dec 2026 15:12:12 -0800 Subject: [PATCH 3/3] tests: clarify legacy i32 range check coverage Explain that only the LEGACY check tests the legacy code generator change. The legacy OPT and VECTOR checks also pass without the change. Issue: #3269 --- tests/optimizations/pass/i32_range_checks_are_removed.vx | 2 ++ 1 file changed, 2 insertions(+) diff --git a/tests/optimizations/pass/i32_range_checks_are_removed.vx b/tests/optimizations/pass/i32_range_checks_are_removed.vx index 9c9c2f380..bc9babda7 100644 --- a/tests/optimizations/pass/i32_range_checks_are_removed.vx +++ b/tests/optimizations/pass/i32_range_checks_are_removed.vx @@ -7,6 +7,8 @@ //===----------------------------------------------------------------------===// // An i32 range keeps its signed bounds when the loop counter becomes an i32. // LLVM can then remove the helper's redundant check. +// Only LEGACY tests the legacy code generator change. Its OPT and VECTOR checks +// also pass without this change. // // REQUIRES: flat-codegen // REQUIRES: x86_64