<table border="1" cellspacing="0" cellpadding="8">
<tr>
<th>Issue</th>
<td>
<a href=https://github.com/llvm/llvm-project/issues/134318>134318</a>
</td>
</tr>
<tr>
<th>Summary</th>
<td>
Missed Optimization: Consecutive divisions can be merged into one if intermediate multiplication with sext/zext extention
</td>
</tr>
<tr>
<th>Labels</th>
<td>
new issue
</td>
</tr>
<tr>
<th>Assignees</th>
<td>
</td>
</tr>
<tr>
<th>Reporter</th>
<td>
MaxGraey
</td>
</tr>
</table>
<pre>
Similar to [#132908](https://github.com/llvm/llvm-project/issues/132908#issue-2945981308) we can replace consecutive divisions with one division and one multiplication even if last two operands are overflowing. To do this, we need to apply a `sext` or `zext` for all operands followed by a lowering to the previous width:
```rust
fn src(x: i8, y: i8, z: i8) -> i8 {
x / y / z
}
```
```rust
fn dst(x: i8, y: i8, z: i8) -> i8 {
let x = x as i16;
let y = y as i16;
let z = z as i16;
(x / (y * z)) as i8
}
```
Alive2 proof: https://alive2.llvm.org/ce/z/fR5_nU
```llvm
define i8 @src(i8 %x, i8 %y, i8 %z) {
start:
%_4 = sdiv i8 %x, %y
%_0 = sdiv i8 %_4, %z
ret i8 %_0
}
```
```llvm
define i8 @tgt(i8 %x, i8 %y, i8 %z) {
start:
%_5 = sext i8 %x to i16
%_7 = sext i8 %y to i16
%_8 = sext i8 %z to i16
%_6 = mul nsw i16 %_8, %_7
%_4 = sdiv i16 %_5, %_6
%_0 = trunc i16 %_4 to i8
ret i8 %_0
}
```
</pre>
<img width="1" height="1" alt="" src="http://email.email.llvm.org/o/eJykVU2v6jYQ_TVmM7rI2PlcZMF7t-nqqVI_1lcmnoArY0e2E5L8-soGHrcUVVWfFMHE53jmzNgchPfqaBAbkn8h-ftGjOFkXfNNzD87gcvmYOXS_KbOSgsHwUKkMb7jrKYVyd8Jq04hDJ7wPWEtYe1RhdN42Hb2TFir9XT_ehuc_RO7QFirvB_RE9besjCeVt5YneV1teNxqYYLQicMOBy06BA6azx2Y1ATglST8soaDxcVTmDNYwmEk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