<table border="1" cellspacing="0" cellpadding="8">
<tr>
<th>Issue</th>
<td>
<a href=https://github.com/llvm/llvm-project/issues/55718>55718</a>
</td>
</tr>
<tr>
<th>Summary</th>
<td>
Rewrite divisions of small constants to lookup tables
</td>
</tr>
<tr>
<th>Labels</th>
<td>
llvm:optimizations,
missed-optimization
</td>
</tr>
<tr>
<th>Assignees</th>
<td>
</td>
</tr>
<tr>
<th>Reporter</th>
<td>
Kmeakin
</td>
</tr>
</table>
<pre>
Division, `x / y` where `x` is a constant can be rewritten to a switch-statement/lookup table. The size of the lookup table is directly proportional to `x`, so will need some sensible upper bound to prevent code bloat, or some smarter switch-statement translation that groups together divisors that give the same result into a single table entry.
# Examples
Unsigned division ([godbolt](https://godbolt.org/z/sbdvzscnj), [alive](https://alive2.llvm.org/ce/z/uHi3j-))
```c
#define CASE(y) case y: return x / y;
static uint8_t x = 10;
uint8_t src(uint8_t y) { return x / y; }
uint8_t tgt(uint8_t y) {
switch (y) {
CASE(1)
CASE(2)
CASE(3)
CASE(4)
CASE(5)
CASE(6)
CASE(7)
CASE(8)
CASE(9)
CASE(10)
default:
return 0;
}
}
```
Signed division ([godbolt](https://godbolt.org/z/8T43z9a73), [alive](https://alive2.llvm.org/ce/z/rW2Gic))
```c
#define CASE(y) case y: return x / y;
static int8_t x = 10;
int8_t src(int8_t y) { return x / y; }
int8_t tgt(int8_t y) {
switch (y) {
CASE(-10)
CASE(-9)
CASE(-8)
CASE(-7)
CASE(-6)
CASE(-5)
CASE(-4)
CASE(-3)
CASE(-2)
CASE(-1)
CASE(1)
CASE(2)
CASE(3)
CASE(4)
CASE(5)
CASE(6)
CASE(7)
CASE(8)
CASE(9)
CASE(10)
default:
return 0;
}
}
```
</pre>
<img width="1px" height="1px" alt="" src="http://email.email.llvm.org/o/eJztVkuP2jAQ_jXhYgUFm_A45ADLbiv11m3VY-UkQ_CuY0e2Awu_vuMQWKC4UrXqrRGP2J9nPI9v7Ml1uc9WYius0CqiDySaJG8kok9kj29ktw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