How to tell a C or a C++ compiler that pointers are not aliased
-
27-10-2019 - |
سؤال
I have function that receives an array of pointers like so:
void foo(int *ptrs[], int num, int size)
{
/* The body is an example only */
for (int i = 0; i < size; ++i) {
for (int j = 0; j < num-1; ++j)
ptrs[num-1][i] += ptrs[j][i];
}
}
What I want to convey to the compiler is that the pointers ptrs[i]
are not aliases of each other and that the arrays ptrs[i]
do not overlap. How shall I do this ? My ulterior motive is to encourage automatic vectorization.
Also, is there a way to get the same effect as __restrict__
on an iterator of a std::vector
?
المحلول
restrict
, unlike the more common const
, is a property of the pointer rather than the data pointed to. It therefore belongs on the right side of the '*
' declarator-modifier. []
in a parameter declaration is another way to write *
. Putting these things together, you should be able to get the effect you want with this function prototype:
void foo(int *restrict *restrict ptrs, int num, int size)
{
/* body */
}
and no need for new names. (Not tested. Your mileage may vary. restrict
is a pure optimization hint and may not actually do anything constructive with your compiler.)
نصائح أخرى
Something like:
void foo(int *ptrs[], int num, int size)
{
/* The body is an example only */
for (int i = 0; i < size; ++i) {
for (int j = 0; j < num-1; ++j) {
int * restrict a = ptrs[num-1];
int * restrict b = ptrs[j];
a[i] += b[i];
}
}
... should do it, I think, in C99. I don't think there's any way in C++, but many C++ compilers also support restrict.
In C++, pointer arguments are assumed not to alias if they point to fundamentally different types ("strict aliasing" rules).
In C99, the "restrict" keyword specifies that a pointer argument does not alias any other pointer argument.