C99 __restrict and compiler optimization

typedef struct { void * field1; } s1; void func1(void) { s1 my_s1; s1 * __restrict my_s1_ptr = &my_s1; *((int*)((char*)my_s1_ptr->field1 + 4)) = 0; *((int*)((char*)my_s1_ptr->field1 + 8)) = 1; *((int*)((char*)my_s1_ptr->field1 + 12)) = 2; *((int*)((char*)my_s1_ptr->field1 + 16)) = 3; } 

It seems that for Intel compiler version 11.1 and gcc version 4.6, the compiler reloads my_s1_ptr-> field1 for each of the last 4 statements. My understanding of __restrict tells me that the last 3 loads should be redundant and can be eliminated. Yes, I know that the code is strange, but there is a reason why it is structured this way. I would just like to get a compiler to eliminate the overload. Any idea how to convince him of this?

+6
source share
1 answer

s1 * __restrict means that this is the only pointer to a specific s1 , so there are no aliases for this type. This does not mean that there will be no aliases for other types of pointers, such as void* , int* or char* .

Using char* especially difficult for the compiler, because char* specifically allowed to use other types of bytes. ( char also means byte and can be used to access other types of main memory).

If the compiler cannot prove that your task will never, ever change what is indicated, it will have to reload the pointer each time. For example, how can he say that void* field1 not pointing to itself?


And wouldn’t it be something like this work without all the casts?

 int* p = my_s1.field1; p[1] = 0; p[2] = 1; p[3] = 2; p[4] = 3; 

Assuming int has 4 bytes and that field1 actually points to an array of them.

+3
source

Source: https://habr.com/ru/post/917575/


All Articles