-->

Opposite keyword of “restrict” in C?

2019-04-28 17:25发布

问题:

Since strict aliasing may help compiler optimize better, C99 introduced the restrict keyword which can be used as a qualifier of a variable if programmers guarantee that it won't be accessed through a pointer to a different type. However, typecasting between different types is inevitable for several reasons and this will make compiler assume that one pointer is not an alias of the other. Therefore, the workaround method is to disable the global strict aliasing optimization by passing -fno-strict-aliasing (a GCC flag). This makes totally no sense because there may only have two pointers that should not be fully optimized. Hence, why not introduce an opposite keyword of restrict which tells compiler that do not assume that those two pointers point to different addresses. This is somewhat similar to what volatile does, and that tells compiler this variable is changed vastly, so treat them in a special way. Is it possible to create such keyword?

EDIT: There is a way to solve this problem. Please see yano's comment below.

回答1:

Given the code:

int foo(int * restrict p)
{
  *p = 3;
  someOutsideFunction();
  return *p;
}

a compiler is entitled to assume that as long as p is in scope, no object which is written using *p will be accessed via any means other than via pointer which is copied or otherwise "derived" from p. Other pointers to the object may exist elsewhere in the universe, but until foo returns none of them will be usable to access *p. Consequently, a compiler could replace the above with

int foo(int * restrict p)
{
  someOutsideFunction();
  *p = 3;
  return 3;
}

since it can see that no pointer copied or derived from p is ever exposed in a way that someOutsideFunction could see it, and thus no legitimate way for someOutsideFunction to access the object *p.

If someOutsideFunction could--unbeknownst to the compiler processing foo--include a keyword that behaved as the opposite of restrict, and could allow it to access the object identified by p [receiving a pointer to that object from a global variable or other such means], that would make it impossible for the compiler processing foo to know whether someOutsideFunction might access *p, and thus impossible for it to know whether it could safely apply the indicated optimization.