https://gcc.gnu.org/bugzilla/show_bug.cgi?id=108767

            Bug ID: 108767
           Summary: O2 optimization has side effects on static analysis.
           Product: gcc
           Version: 13.0
            Status: UNCONFIRMED
          Severity: normal
          Priority: P3
         Component: analyzer
          Assignee: dmalcolm at gcc dot gnu.org
          Reporter: geoffreydgr at icloud dot com
  Target Milestone: ---

Hi, David. I found a problem through the following case that the optimization
`-O2` has side effects on static analysis. GCC static analzyer falsely gives a
NPD warning under the optimization `-O2`.

Input:
```c
#include "stdio.h"
extern void __analyzer_describe ();
extern void __analyzer_eval ();
extern void __analyzer_dump ();

int main()
{
    int b = 1;
    int e = 2;
    int f = 3;
    int *g[] = {&e, &e};
    int *h = &b;
    int *j = &f;

    for (int d = 0; d <= 1; d++)
    {
        *j = (*h && (h = g[d]));
        // __analyzer_dump ();
        __analyzer_eval(h==0);
        // __analyzer_describe(0,h);
    }
    printf("NPD_FLAG %d\n", *j);

}
```

options: -O2 -fanalyzer
Output:
```
<source>: In function 'main':
<source>:19:9: warning: FALSE
   19 |         __analyzer_eval(h==0);
      |         ^~~~~~~~~~~~~~~~~~~~~
<source>:19:9: warning: UNKNOWN
<source>:19:9: warning: TRUE
<source>:19:9: warning: TRUE
<source>:19:9: warning: UNKNOWN
<source>:19:9: warning: TRUE
<source>:19:9: warning: TRUE
<source>:19:9: warning: UNKNOWN
<source>:17:15: warning: dereference of NULL 'h' [CWE-476]
[-Wanalyzer-null-dereference]
   17 |         *j = (*h && (h = g[d]));
      |               ^~
  'main': events 1-9
    |
    |   15 |     for (int d = 0; d <= 1; d++)
    |      |                     ~~^~~~
    |      |                       |
    |      |                       (1) following 'true' branch (when 'd !=
2')...
    |      |                       (5) following 'true' branch (when 'd !=
2')...
    |      |                       (7) following 'true' branch (when 'd !=
2')...
    |   16 |     {
    |   17 |         *j = (*h && (h = g[d]));
    |      |         ~~~~~~~~~~~~~~~~~~~~~~~
    |      |         |  |  |  |
    |      |         |  |  |  (3) following 'true' branch...
    |      |         |  |  (9) dereference of NULL 'h'
    |      |         |  (4) ...to here
    |      |         (2) ...to here
    |      |         (6) ...to here
    |      |         (8) ...to here
    |
Compiler returned: 0
```

options : -O1 -fanalyzer
Output:
```
<source>: In function 'main':
<source>:19:9: warning: FALSE
   19 |         __analyzer_eval(h==0);
      |         ^~~~~~~~~~~~~~~~~~~~~
<source>:19:9: warning: UNKNOWN
Compiler returned: 0
```
-O2: https://godbolt.org/z/GeTaeGMaf
-O1: https://godbolt.org/z/adnY8aa3K

Reply via email to