<table border="1" cellspacing="0" cellpadding="8">
<tr>
<th>Issue</th>
<td>
<a href=https://github.com/llvm/llvm-project/issues/107563>107563</a>
</td>
</tr>
<tr>
<th>Summary</th>
<td>
`lea` with following `sub` of same register should be optimized into `mov`
</td>
</tr>
<tr>
<th>Labels</th>
<td>
new issue
</td>
</tr>
<tr>
<th>Assignees</th>
<td>
</td>
</tr>
<tr>
<th>Reporter</th>
<td>
blaumeise20
</td>
</tr>
</table>
<pre>
With the following Rust (1.80.0) code on Godbolt:
```rs
#[no_mangle]
pub fn example(start: usize, test: u8) -> usize {
let mut new = start;
no_inline();
new += 1;
if test >= 0b11000000 {
no_inline();
new += 1;
if test >= 0b11100000 {
no_inline();
new += 1;
if test >= 0b11110000 {
no_inline();
new += 1;
}
}
}
new - start
}
#[inline(never)]
fn no_inline() {}
```
the following assembly is produced:
```asm
example:
cmp sil, -65
jbe .LBB1_1
cmp sil, -32
jb .LBB1_4
cmp sil, -16
mov rax, rdi
sbb rax, -1
add rax, 3
sub rax, rdi
ret
.LBB1_1:
lea rax, [rdi + 1]
sub rax, rdi
ret
.LBB1_4:
lea rax, [rdi + 2]
sub rax, rdi
ret
```
To me it seems very unnecessary to have those separate `lea` and `sub` instructions which take up 7 bytes in the machine code, they could be replaced with `mov al, 1/2`, which only takes up 2 bytes. Also I'm not 100% sure, but probably the `mov rax, rdi` and `sub rax, rdi` in the first block could be removed and the `sbb` turned into a different instruction.
For context, this happened to me while working on optimizing UTF-8 reading using `String::chars().next()` and reading the length using `chars.as_str()` and pointer arithmetic.
</pre>
<img width="1px" height="1px" alt="" src="http://email.email.llvm.org/o/eJyUVsGOozgQ_RrnUgoyJiHJgUNnerJaaU-7s9pjy0AleMbYyGWSznz9yoZ0IKvunkURyH5UvXquRymSSJ0MYsHWe7Z-XsjeN9YVpZZ9i4pQ8EVp62vxj_IN-AbhaLW2F2VO8GdPHpjYpsmWJ5yJHVS2RrAGfrN1abVn2RPjz4w_sZwPP0fjhsjYem_sSyvNSSNbP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