https://gcc.gnu.org/bugzilla/show_bug.cgi?id=109053
Bug ID: 109053 Summary: [missed optimization] value-range tracking fails in simple case with __builtin_unreachable Product: gcc Version: 13.0 Status: UNCONFIRMED Severity: normal Priority: P3 Component: tree-optimization Assignee: unassigned at gcc dot gnu.org Reporter: avi at scylladb dot com Target Milestone: --- I'm trying to use __builtin_unreachable() to inject assumptions about values of variables into this code. In this case, the fact that a reference count must be one or greater. Consider the code: struct refcounted { int* p; refcounted() : p(new int(1)) {} ~refcounted() { assume_stuff(); if (!--*p) { delete p; } } refcounted(const refcounted& x) : p(x.p) { assume_stuff(); ++*p; assume_stuff(); } refcounted& operator=(const refcounted& x) { assume_stuff(); x.assume_stuff(); if (this != &x) { ++*x.p; if (!--*p) { delete p; } p = x.p; } assume_stuff(); x.assume_stuff(); return *this; } void assume_stuff() const { if (*p <= 0) { __builtin_unreachable(); } } }; refcounted assign(refcounted& a, refcounted& b) { auto x = a; a = b; return x; } In the assign() function, although we assign to `a`, we also return it (as `x`), so there's never a reason to call operator delete. Yet the code does. assign(refcounted&, refcounted&): mov %rdi,%rax mov (%rsi),%rdi mov %rdi,(%rax) addl $0x1,(%rdi) ; gcc now knows that (%rdi) is 2 or greater cmp %rdx,%rsi je 68 <assign(refcounted&, refcounted&)+0x68> push %rbp mov %rdx,%rbp push %rbx mov %rsi,%rbx sub $0x18,%rsp mov (%rdx),%rcx addl $0x1,(%rcx) mov (%rdi),%edx sub $0x1,%edx ; gcc now knows that (%rdi) is 1 or greater je 40 <assign(refcounted&, refcounted&)+0x40> ; so how can it be zero? ; if gcc tracked the ranges correctly, it would have eliminated the branch and made assign() a leaf function mov %edx,(%rdi) mov %rcx,(%rbx) add $0x18,%rsp pop %rbx pop %rbp ret cs nopw 0x0(%rax,%rax,1) mov $0x4,%esi mov %rax,0x8(%rsp) call 4f <assign(refcounted&, refcounted&)+0x4f> R_X86_64_PLT32 operator delete(void*, unsigned long)-0x4 mov 0x0(%rbp),%rcx mov 0x8(%rsp),%rax mov %rcx,(%rbx) add $0x18,%rsp pop %rbx pop %rbp ret nopw 0x0(%rax,%rax,1) ret Also on: https://godbolt.org/z/Tnehj86hc