<table border="1" cellspacing="0" cellpadding="8">
    <tr>
        <th>Issue</th>
        <td>
            <a href=https://github.com/llvm/llvm-project/issues/58400>58400</a>
        </td>
    </tr>

    <tr>
        <th>Summary</th>
        <td>
            Incorrect code generation when we use __builtin_constant_p built-in function
        </td>
    </tr>

    <tr>
      <th>Labels</th>
      <td>
            new issue
      </td>
    </tr>

    <tr>
      <th>Assignees</th>
      <td>
      </td>
    </tr>

    <tr>
      <th>Reporter</th>
      <td>
          alex-curiou
      </td>
    </tr>
</table>

<pre>
    Incorrect codegeneration from version 8.0.0:
 - with -O2 flag the return NOT CORRECT value 13 (https://godbolt.org/z/xs9EzP4Mo);
 - with -Og flag the return CORRECT value 60 (https://godbolt.org/z/v8E3xGvT6);

>From version 13.0.0 and till 15.0.0 INCORRECT code generation for both -Og and -O2,
the return value is 13, but the bar func code is generated to calculate 60:
 - with -O2 flag: https://godbolt.org/z/nzn5zT65e
 - with -Og flag: https://godbolt.org/z/4osxW8fnz


The minimized example of code:

~~~
#define test(val1) \
  __builtin_constant_p(val1) ? (val1 + 10) : (val1 * 20);


unsigned int bar(unsigned int value1) {
    return test(value1);
}

int main(void) {
    unsigned int a = bar(3);

    return a;
}
~~~

The __builtin_constant_p considers the val1 value to be NOT known to be constant at compile time. So the generated code is
val1 * 20

But optimizer considers that the value is WELL known and can WELL be calculated.
So, the return value of func bar is calculated at compile time and the call to the bar func is dropped away.

And the final return value is WRONG:
val1 + 10

As a result we have different return values with -O2 and -Og optimization flags, 13 and 60 accordingly.

For example, here is the compiler output for version 8.0.0:

-O2 will return 13
https://godbolt.org/z/xs9EzP4Mo

~~~
bar:                                    # @bar
        shl     edi, 2
        lea     eax, [rdi + 4*rdi]
        ret
main:                                   # @main
        mov     eax, 13
        ret
~~~

-Og will return 60
https://godbolt.org/z/v8E3xGvT6

~~~
bar:                                    # @bar
        shl     edi, 2
        lea     eax, [rdi + 4*rdi]
        ret
main:                                   # @main
        mov     edi, 3
        jmp     bar
~~~
</pre>
<img width="1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