When the compiler (gcc, or intel c++) optimizes a for loop with an index that is a member of a struct, can the compiler break the struct into individual variables/register?
For example, when one member of the struct a is actually always equal to another variable b, it would be safe to replace all a to b in the actual program.
When the struct has a and other things as member, can compilers still perform this optimization?
How about other optimization such as removing unnecessary indirection (referencing and dereferencing)?
I tried to test, but the test is not complete.
Code: (compiled with g++ -O3 -std=c++14)
int main()
{
int i, j // version 1
// version 2
/*
struct Index{
int ii;
int jj;
}C;
int &i = C.ii;
int &j = C.jj;
*/
int a = 0;
constexpr int N = 65536;
int x[N];
for (int k = 0; k < N; ++k) x[k] = 1;
for (i = 0; i < N; ++i) {
a += x[i];
}
for (j = 0; j < N; ++j) {
a += x[j];
}
std::cout << a << "\n";
}
gcc godbolt:
Version 1 and 2 have identical assembly.
Update:
Things I found online:
From GCC's structure reorganization optimization development plan (gcc.gnu.org):
- GCC can split a struct with four fields into four structs when two fields are extensively accessed by function
f()while the other two fields are extensively accessed by functiong(). (Table 2. test1.c)
Why doesn't GCC optimize structs?
- GCC doesn't reorder attributes of a struct because C standard doesn't allow that.
The new intraprocedural scalar replacement of aggregates (gcc.gnu.org, suggested by Mysticial)
- So gcc can replace a member of a struct by register.