<table border="1" cellspacing="0" cellpadding="8">
<tr>
<th>Issue</th>
<td>
<a href=https://github.com/llvm/llvm-project/issues/122442>122442</a>
</td>
</tr>
<tr>
<th>Summary</th>
<td>
Missed optimization: (x % (C1 * C2) / C2) vs. ((x / C2) % C1)
</td>
</tr>
<tr>
<th>Labels</th>
<td>
new issue
</td>
</tr>
<tr>
<th>Assignees</th>
<td>
</td>
</tr>
<tr>
<th>Reporter</th>
<td>
Explorer09
</td>
</tr>
</table>
<pre>
When an expression contains modulo and division, if the modulo happens first but the divisor is a multiple of the divisor later on, the expression can be optimized by swapping and division and modulo, especially when this can reduce code size (`-Os` option).
(Sometimes it is desirable to swap the operators the other way around, if the compiler can tell if the divisor has been loaded already by the surrounding code.)
Below are the examples: `func1a`, `func1b` and `func1c` are equivalent; likewise for `func2a`, `func2b` and `func2c`.
(Can be tested in Compiler Explorer. x86-64 clang 19.1.0 with `-Os` option)
```c
unsigned long long func1a(unsigned long long x) {
return (x / 60) % 60;
}
unsigned long long func1b(unsigned long long x) {
return (x % 3600) / 60;
}
unsigned long long func1c(unsigned long long x) {
return (x % (60 * 60)) / 60;
}
unsigned long long func2a(unsigned long long x) {
return (x / 60) % 24;
}
unsigned long long func2b(unsigned long long x) {
return (x % 1440) / 60;
}
unsigned long long func2c(unsigned long long x) {
return (x % (24 * 60)) / 60;
}
```
Note: I also reported this bug in gcc (https://gcc.gnu.org/bugzilla/show_bug.cgi?id=118397)
</pre>
<img width="1" height="1" alt="" src="http://email.email.llvm.org/o/eJycVU9vpDYU_zSey1MQPP4NBw7JpEg9tD300GNl7Dfg1tjUNpmZfPrKMGiz6VabjYRmsJ_5_cPPcO_VYIhaVj6x8vnAlzBa1_50nbV15NLm0Ft5a_8YyQA3QNfZkffKGhDWBK6Mh8nKRVvgRoJULyoWGZ5AnSGMtFdHPs9kPJyV8wH6JazFdb11oDxwmBYd1KwJ7PmrouaBHGygcf6tBm6gJ7BzUJN6JQn9DfyFz7Myw1eC1sEmJcKQn0korvUN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