Skip to content

Missed optimization with redundant overflow checks #40191

Closed
@alex

Description

@alex
Bugzilla Link 40845
Version trunk
OS All
CC @alex,@nelhage

Extended Description

Godbolt link: https://godbolt.org/z/h2lkGE

The subtraction can be known not to overflow because it's derived from an overflow checked addition. This was reduced/converted to C from this rust bug: rust-lang/rust#58692

One commenter suggested they thought the issue was in how GVN handled overflow checked operations.

Code:

#include <stdlib.h>

extern void panic1();
extern void panic2();
extern void panic3();

size_t f(size_t a, size_t b) {
    size_t x;
    if (!__builtin_add_overflow(a, b, &x)) {
        panic1();
        __builtin_unreachable();
    }

    size_t r;
    if (!__builtin_sub_overflow(x, a, &r)) {
        panic2();
        __builtin_unreachable();
    }
    
    if (r < 0) {
        panic3();
        __builtin_unreachable();
    }

    return x;
}

Assembly:

f(unsigned long, unsigned long):                                 # @f(unsigned long, unsigned long)
        push    rax
        mov     rax, rsi
        add     rax, rdi
        jae     .LBB0_3
        cmp     rax, rdi
        jae     .LBB0_4
        pop     rcx
        ret
.LBB0_3:
        call    panic1()
.LBB0_4:
        call    panic2()

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions