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

            Bug ID: 113301
           Summary: [12/13/14 Regression] Missed optimization: (1/(x+1))/2
                    => 0 since gcc-12
           Product: gcc
           Version: 14.0
            Status: UNCONFIRMED
          Severity: normal
          Priority: P3
         Component: tree-optimization
          Assignee: unassigned at gcc dot gnu.org
          Reporter: 652023330028 at smail dot nju.edu.cn
  Target Milestone: ---

Hello, we noticed that GCC seems to have missed optimizations as stated in the
title, and it works as expected on gcc-11.4.

After analysis, we found that they (gcc-trunk and gcc-11.4) are different in
evrp(tree), and further, the difference is in the calculation of the value
range.

reduced code:
https://godbolt.org/z/Y7v1jsTKf

int c;
void func(int x){
    c=(1/(x+1))/2;
}

gcc(trunk) -O3 -fwrapv:
func(int):
        lea     edx, [rdi+1]
        add     edi, 2
        xor     eax, eax
        cmp     edi, 2
        cmova   edx, eax
        mov     eax, edx
        shr     eax, 31
        add     eax, edx
        sar     eax
        mov     DWORD PTR c[rip], eax
        ret

evrp (tree):
Folding statement: _7 = _6 <= 2;
Not folded
Folding statement: _2 = _7 ? _1 : 0;
Possible COND_EXPR adjustment. Range op1 : [irange] int VARYING and Range op2:
[irange] int [0, 0] NONZERO 0x0
Not folded
Folding statement: _3 = _2 / 2;
Global Exported: _3 = [irange] int [-1073741824, 1073741823]
Not folded
Folding statement: c = _3;
Not folded
Folding statement: return;
Not folded


Expected code:
gcc(11.4) -O3 -fwrapv:
func(int):
        mov     DWORD PTR c[rip], 0
        ret

evrp (tree):
=========== BB 2 ============
    <bb 2> :
    # DEBUG BEGIN_STMT
    _1 = x_4(D) + 1;
    _2 = 1 / _1;
    c = 0;
    return;

_2 : int [-1, 1]
Non-varying global ranges:
=========================:
_2  : int [-1, 1]


Also, the following code works as expected (gcc-trunk):
void func1(int x){
    c=(1/x)/2;
}

Thank you very much for your time and effort! We look forward to hearing from
you.

Reply via email to