https://gcc.gnu.org/bugzilla/show_bug.cgi?id=111405
Bug ID: 111405 Summary: Problem with incorrect optimizion for "constexpr" function with possible overflow Product: gcc Version: 13.2.0 Status: UNCONFIRMED Severity: normal Priority: P3 Component: c Assignee: unassigned at gcc dot gnu.org Reporter: 3180104919 at zju dot edu.cn Target Milestone: --- Created attachment 55891 --> https://gcc.gnu.org/bugzilla/attachment.cgi?id=55891&action=edit A demo file contains a funciton that will be wrongly optimized using -O2 I happened to find this problem when I did the CSAPP lab. int isTmax(int x) { // make it all of 1 // it's quite strange that the results of x + 1 + x and x + x + 1 are different int c = x + x + 1; // check if it's all of 1 int flag_all_ones = !(~c); // avoid -1 int flag_not_neg1 = !!(x + 1); return flag_all_ones & flag_not_neg1; } This function will be incorrectly optimized to return zero only with "-O2" compiler flag. But in fact isTmax(0x7fffffff) should return 1. Here's the disassembly code using coredump: 000012ac <isTmax>: // check if it's all of 1 int flag_all_ones = !(~c); // avoid -1 int flag_not_neg1 = !!(x + 1); return flag_all_ones & flag_not_neg1; } 12ac: b8 00 00 00 00 mov $0x0,%eax 12b1: c3 ret This function can be correctly compiled with no compiler optimization (-O0). And this behaviour always occurs using the latest 2 version gcc compiler (from 11.0 to 12.0). But using clang or msvc, everything works well. Thank you for your time.