Is there a way to declare a variable is non-aliased in clang
to allow for more optimizations where the variable is used?
I understand restrict
can be used to declare pointers as non-aliasing.
However, I'm also wondering about variables which can be pointer into. I guess (perhaps wrongfully) that the compiler has to be careful about assuming things which can allow it to cache a variable's value instead of re-fetching it each time.
Example:
class Data
{
public:
void updateVal() {
// Updates m_val with some value each time it's called (value may differ across different calls)
...
}
int complicatedCalculation() const {
return 3 * m_val + 2;
}
int m_val;
};
class User
{
User(Data& data) : m_data{data} {}
void f()
{
m_data.updateVal();
for (int i=0; i<1000; ++i)
g();
}
void g()
{
// Will the optimizer be able to cache calc's value for use in all the calls to g() from f()?
int calc = m_data.complicatedCalculation();
// Do more work
...
}
Data& m_data;
};
Even if the answer to the question in the sample code is "yes", might it not change to "no" if the code were more complicated (e.g. work being under // Do more work
), due to a possibility of a pointer contents being modified where the pointer might have pointed into m_data.m_val
? Or is this something the compiler assumes never happens, unless it sees the address of m_val
being taken somewhere in the code?
If it doesn't assume that, or even it does but the address of m_val
does get taken somewhere (but we know its contents won't be modified), then it would be nice to be able to mark m_val
as "safe" from aliasing concerns, so its value can be assumed to not be changed by pointer access.