On 19/03/2021 16:33, Ian Pilcher wrote:
> It took me years, but I've finally managed to grok aliasing and the
> purpose of the restrict qualifier.
>
> I believe that I know the basic aliasing rules, but I often find myself
> wondering if restrict is necessary in certain situations. For example:
"restrict" is never necessary for code functionality. It gives the
compiler extra information for optimisation (and, if you are lucky,
static error checking), but no program that is correct /with/ restrict
will change its behaviour if restrict is omitted.
>
> uint8_t ipmi_cmd(const uint8_t *const cmd, const size_t cmd_len,
> uint8_t *const response, const size_t resp_len)
>
Putting "const" on the parameters themselves doesn't do anything to the
code, or give the compiler any more information, as the parameters are
always copied by value. It simply means you promise not to change the
local copy in the function body. Many programmers like to avoid
changing parameters in the function body, except perhaps in a few simple
or idiomatic cases. Putting "const" on these means the compiler will
complain if you break that rule. But it also may make it harder to see
the only relevant "const" in that declaration - the first one on "cmd".
> Can the compiler infer from this that cmd and response do not alias one
> another (because cmd is a pointer to *const* uint8_t and response is a
> pointer to non-const uint8_t)?
No. The "const" in a pointer declaration (including a parameter) is
only your promise not to change the value via that pointer, and even
that is not a binding promise. Such "const" are useful for making the
code clear and helping the compiler spot (and warn about) some kinds of
errors, but it is not strong enough to give the kind of optimisation
benefits you are hoping for. So "restrict" will help here.
(If you are using gcc 10 or newer, and are happy to use extensions, you
can also use the "access" function attributes to give the compiler more
details about how data is accessed via pointers. This could be used for
better error checking and/or optimisation. Other compilers may have
corresponding features.)
>
> Are pointers to uint8_t treated as pointers to char for aliasing
> purposes?
Hypothetically, "uint8_t" may not necessarily be a "char" type. I have
not heard of any real compilers where it is not, however.
>
> Does anyone know of a resource anywhere that discusses these sorts of
> "corner cases?"
>
This newsgroup specialises in such "language lawyer" details, so this is
probably as good a place as any. Of course, the C language standards
are important references, and the <
https://en.cppreference.com/w/c>
website is a convenient place to look.