<table border="1" cellspacing="0" cellpadding="8">
<tr>
<th>Issue</th>
<td>
<a href=https://github.com/llvm/llvm-project/issues/115444>115444</a>
</td>
</tr>
<tr>
<th>Summary</th>
<td>
[RISCV] Suboptimal switch code generation
</td>
</tr>
<tr>
<th>Labels</th>
<td>
new issue
</td>
</tr>
<tr>
<th>Assignees</th>
<td>
</td>
</tr>
<tr>
<th>Reporter</th>
<td>
WojciechMula
</td>
</tr>
</table>
<pre>
Version `clang version 20.0.0git (https://github.com/llvm/llvm-project.git 5b697ef5dd6b3e29e257e6099014bf8d8e77ac9a)`
Arguments: `-O3`
The following switch is nicely compiled:
```c++
bool one_of(int num) {
switch (num) {
case 0:
case 1:
case 3:
case 4:
case 6:
case 10:
return true;
default:
return false;
}
```
```asm
one_of(int):
sltiu a1, a0, 11
li a2, 1115
srl a0, a2, a0
and a0, a0, a1
ret
```
However, changing the return type from `bool` to `int` changes the generated code dramatically.
```c++
int one_of_int(int num) {
switch (num) {
case 0:
case 1:
case 3:
case 4:
case 6:
case 10:
return 1;
default:
return 0;
}
}
```
```asm
one_of_int(int):
li a1, 10
bltu a1, a0, .LBB1_2
slli a0, a0, 2
.Lpcrel_hi0:
auipc a1, %pcrel_hi(.Lswitch.table.one_of_int(int))
addi a1, a1, %pcrel_lo(.Lpcrel_hi0)
add a0, a0, a1
lw a0, 0(a0)
ret
.LBB1_2:
li a0, 0
ret
.Lswitch.table.one_of_int(int):
.word 1
.word 1
.word 0
.word 1
.word 1
.word 0
.word 1
.word 0
.word 0
.word 0
.word 1
```
godbolt: https://godbolt.org/z/jqs1zr385
</pre>
<img width="1px" height="1px" alt="" src="http://email.email.llvm.org/o/eJy0Vl1vpDYU_TXmxVpkm-8HHpKNRq2UqlK32j5Gxr4Djgye2iaj7K-vDDMThmGT7qpFiBHX5xxfX449lzun2gGgRtk9yh4iPvrO2Pov8ywUiO63UfOoMfK1_grWKTNglBOh-dDil1OAkZjEpFUeI1Z23h8cSu4Q2yG2a5XvxiYWpkdsp_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