public inbox for gcc@gcc.gnu.org
 help / color / mirror / Atom feed
* Nested restrict pointers: missed optimization & client with UB?
@ 2024-02-13 13:00 Ties Klappe
  2024-02-13 14:15 ` Richard Biener
  2024-02-13 14:29 ` Joseph Myers
  0 siblings, 2 replies; 6+ messages in thread
From: Ties Klappe @ 2024-02-13 13:00 UTC (permalink / raw)
  To: gcc

[-- Attachment #1: Type: text/plain, Size: 1741 bytes --]

Hi,

I have two questions related to nested restrict pointers.
GCC 13.02 with optimization level 3 optimizes the function *foo1* to simply
return 10.

int foo1(int *restrict *restrict p, int *restrict *restrict q)
{
    **p = 10;
    **q = 11;
    return **p;
}

I am curious why the function *foo2* is not optimized in the same way (see
https://godbolt.org/z/E4cx1c1GP): the first pointer dereference of p and q
result in the restrict qualified pointer lvalues, which are used to write
to a disjoint (as promised by the restrict qualifier) location storing an
integer object. So this should give enough information to perform the
optimization, i.e. a write via **q cannot change the object **p designates
if the program has defined behavior.

int foo2(int *restrict *p, int *restrict *q)
{
    **p = 10;
    **q = 11;
    return **p;
}

Secondly, if we would have a client *main* invoking *foo1* (see below), the
optimization would be incorrect if the client does not contain undefined
behavior. So I am curious how the standard section 6.7.3.1 actually applies
here: if the program is defined, I would assume both lvalues *p and *q are
said to be based on xp (xp = *p = *q; = object `*P` *where the standard
refers to), but is it actually the case that both the *p and *q expressions
are based on the same object P?

int main() {
    int x = 0;
    int* xp = &x;

    int res = foo1(&xp, &xp);

    return 0;
}

So to wrap up, I have two questions:

1. Should *foo2* be optimized in the same way as *foo1* and is it simply a
missed optimization candidate, or is there another reason GCC does not
optimize it?
2. Does the client *main* contain undefined behavior according to GCC, and
if so, why?

Thank you in advance.

Kind regards,
Ties

^ permalink raw reply	[flat|nested] 6+ messages in thread

end of thread, other threads:[~2024-02-13 16:06 UTC | newest]

Thread overview: 6+ messages (download: mbox.gz / follow: Atom feed)
-- links below jump to the message on this page --
2024-02-13 13:00 Nested restrict pointers: missed optimization & client with UB? Ties Klappe
2024-02-13 14:15 ` Richard Biener
2024-02-13 14:29 ` Joseph Myers
2024-02-13 15:25   ` Ties Klappe
2024-02-13 15:33     ` Joseph Myers
2024-02-13 16:06     ` Richard Biener

This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox;
as well as URLs for read-only IMAP folder(s) and NNTP newsgroup(s).