https://gcc.gnu.org/bugzilla/show_bug.cgi?id=93742
Bug ID: 93742 Summary: Optimization request: pattern-match typical addition overflow checks Product: gcc Version: 10.0 Status: UNCONFIRMED Severity: normal Priority: P3 Component: middle-end Assignee: unassigned at gcc dot gnu.org Reporter: tavianator at gmail dot com Target Milestone: --- It would be nice if GCC could pattern-match the typical pattern for overflow-safe addition and optimize it to just branch on the overflow flag. Right now, this: _Bool add_overflow(int a, int b, int *res) { if ((a > 0 && b > INT_MAX - a) || (a < 0 && b < INT_MIN - a)) { return 1; } else { *res = a + b; return 0; } } compiles to this: testl %edi, %edi jle .L2 movl $2147483647, %ecx movl $1, %eax subl %edi, %ecx cmpl %esi, %ecx jl .L12 .L4: addl %esi, %edi xorl %eax, %eax movl %edi, (%rdx) ret .L12: ret .L2: je .L4 movl $-2147483648, %ecx movl $1, %eax subl %edi, %ecx cmpl %esi, %ecx jle .L4 ret #48580 is similar but about multiplication, for which the overflow-safe pattern is a lot more complicated. But the addition one above is a lot simpler and pretty widespread I think. For example, it's what CERT recommends: https://wiki.sei.cmu.edu/confluence/display/c/INT32-C.+Ensure+that+operations+on+signed+integers+do+not+result+in+overflow