llvm-project icon indicating copy to clipboard operation
llvm-project copied to clipboard

[MLIR] Missed Optimization: Mixed `index_cast` and `index_castui` round trips are not folded

Open dev-816 opened this issue 2 months ago • 3 comments

arith-int-range-narrowing appears to miss a redundant round trip combining arith.index_cast and arith.index_castui.

When index is at least 8 bits wide, extending an i8 value to index and truncating it back preserves its original bits. Both casts can therefore be removed. However, FoldIndexCastChain only matches chains containing two casts of the same operation type.

Code Example

func.func @mixed_cast(%arg: i8) -> i8 {
  %idx = arith.index_cast %arg : i8 to index
  %r = arith.index_castui %idx : index to i8
  return %r : i8
}

Command

mlir-opt --arith-int-range-narrowing='int-bitwidths-supported=8'

Version: 6f54fe6b6fb22f8a335fd19b94049fc769dfea25

dev-816 avatar Sep 20 '26 13:09 dev-816

@llvm/issue-subscribers-mlir

Author: CC_Fans (dev-816)

`arith-int-range-narrowing` appears to miss a redundant round trip combining `arith.index_cast` and `arith.index_castui`.

When index is at least 8 bits wide, extending an i8 value to index and truncating it back preserves its original bits. Both casts can therefore be removed. However, FoldIndexCastChain only matches chains containing two casts of the same operation type.

Code Example

func.func @<!-- -->mixed_cast(%arg: i8) -&gt; i8 {
  %idx = arith.index_cast %arg : i8 to index
  %r = arith.index_castui %idx : index to i8
  return %r : i8
}

Command

mlir-opt --arith-int-range-narrowing='int-bitwidths-supported=8'

Version: 6f54fe6b6fb22f8a335fd19b94049fc769dfea25

I'll pick this one up, will raise a PR soon

pranavalavandi avatar Sep 21 '26 00:09 pranavalavandi

@pranavalavandi Hi Pranav, I also have a local fix with tests for both mixed-cast directions. Have you started the PR yet? Happy to coordinate and avoid duplicate work.

AmanPandey28 avatar Sep 21 '26 14:09 AmanPandey28