What Does the 'Restrict' Keyword in C Mean?
The restrict keyword in C (a pre-C 14 syntax only valid as a GCC extension) specifies that two or more pointers passed to a function do not point to overlapping memory regions.
C99 Standard
In C99, restrict is intended to optimize code by allowing compilers to assume that pointers will not alias each other. This can result in significant performance improvements by enabling optimizations such as loop unrolling and vectorization, as shown in the following example:
void f(int *a, int *b, int *x) { *a += *x; *b += *x; } void fr(int *__restrict__ a, int *__restrict__ b, int *__restrict__ x) { *a += *x; *b += *x; }
Without restrict, two assembly instructions are required to load the value of 'x' for both 'a' and 'b', but with restrict, the value of 'x' is loaded only once.
GCC Optimization
GCC can leverage restrict to optimize code, as demonstrated by the following assembly code:
f: mov (%rdx),%eax add %eax,(%rdi) mov (%rdx),%eax add %eax,(%rsi) fr: mov (%rdx),%eax add %eax,(%rdi) add %eax,(%rsi)
In this example, the 'fr' function optimized with restrict has one less assembly instruction than the unoptimized 'f' function.
Arrays
Restrict can be especially useful when dealing with pointer arguments that reference arrays, allowing compilers to optimize operations such as memset and memcpy, potentially enhancing performance.
Array Example
void f(char *restrict p1, char *restrict p2, size_t size) { for (size_t i = 0; i < size; i++) { p1[i] = 4; p2[i] = 9; } }
With restrict, this code can be optimized to use memset for greater efficiency. Removing restrict would disable this optimization, leading to incorrect behavior if the arrays overlap.
Strict Aliasing Rule
Restrict only applies to pointers of compatible types, due to the strict aliasing rule. Casting an incompatible type to a valid type will break the restrict contract, potentially leading to undefined behavior.
GCC Extensions
GCC also allows restrict to be used with references and member functions, extending the scope of its optimization capabilities.
The above is the detailed content of What Does the C `restrict` Keyword Do and How Does It Optimize Code?. For more information, please follow other related articles on the PHP Chinese website!