I have a question regarding optimizations the compiler can potentially do.
The below code will speak for itself (this is an example):
typedef struct test
{
short i;
} s_test;
int function1(char *bin)
{
s_test foo;
lock(gmutex);
foo.i = *(int*)bin * 8;
unlock(gmutex);
sleep(5);
//
// Here anything can happen to *bin in another thread
// an inline example here could be: *(volatile int *)bin = 42;
//
int b = foo.i + sizeof(char*);
return (b > 1000);
}
Could the compiler ever replace the last lines with
return ((*(int*)bin * 8 + sizeof(char*)) > 1000);
It did not seem to be the case using -O2 or -O3 with gcc 4.4 but could it be the case with other compilers and with other compilation flags?
I don't think compiler will do such kind of optimization.
this is function, the compiler can't assume that value pointed by bin will be changed in unlock function or not.
for example, maybe bin comes from a globe. So optimization for bin can't cross the function call.