<table border="1" cellspacing="0" cellpadding="8">
<tr>
<th>Issue</th>
<td>
<a href=https://github.com/llvm/llvm-project/issues/61958>61958</a>
</td>
</tr>
<tr>
<th>Summary</th>
<td>
Missed optimization: Loop-invariant code motion
</td>
</tr>
<tr>
<th>Labels</th>
<td>
new issue
</td>
</tr>
<tr>
<th>Assignees</th>
<td>
</td>
</tr>
<tr>
<th>Reporter</th>
<td>
wheatman
</td>
</tr>
</table>
<pre>
```c
#include <cstdlib>
int sum(int const *const vec, int n) {
int total = 0;
for (int j = 0; j < n; j++) {
total += vec[j];
}
return total;
}
int sum2(int n) {
int *vec = (int *)malloc(n * sizeof(int));
// int vec[1000000];
int total = 0;
// int sum_total = sum(vec, n);
for (int i = 0; i < n; i++) {
total += sum(vec, n);
// total += sum_total;
}
return total;
}
int main(int argc, char *argv[]) {
int n = atoi(argv[1]);
return sum2(n);
}
```
The call to sum is not hoisted out of the loop.
I tried the following to help it;
Making sure `sum` took in a pointer to const data.
Making sure `sum`'s definition was available.
Making sure that the creation of `vec` was local so there couldn't be another thread modifying it somewhere else.
Placing `vec` on the stack to see if it was something about not knowing the origin of the data that malloc returns
If its relevant I original noticed this when looking at a simple normalize function, which shows where code of this form might arise.
```c
unsigned long sum(unsigned long const *const vec, unsigned long n) {
unsigned long total = 0;
for (unsigned long i = 0; i < n; i++) {
total += vec[i];
}
return total;
}
void normalize(unsigned long const *const in, double *out, unsigned long n) {
for(unsigned long i = 0; i < n; i++) {
out[i] = ((double)in[i]) / sum(in, n);
}
return;
}
```
</pre>
<img width="1px" height="1px" alt="" src="http://email.email.llvm.org/o/eJykVk1v4zgM_TXKhZjAkfPlQw5puwEG2AH2sPcBLdMxW1kMLDnB9NcvJDtfnW672BZGq4p85OOjRBu9570j2qjFg1o8TbAPjXSbU0MYWnSTUqpfG7XMhseo7EllW6Vzdsb2FYHKH40PleVS5X-M1vSbXQDft0qv48qI8wGU3g6LIxmlHyFanNIFqNXDgIK0FySgBZU_Qabyi6WWDsZwzxdj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