https://gcc.gnu.org/bugzilla/show_bug.cgi?id=106921
Bug ID: 106921 Summary: [11/12.1] -O1 and -fipa-icf -fpartial-inlining causes wrong code Product: gcc Version: 11.3.0 Status: UNCONFIRMED Severity: normal Priority: P3 Component: c++ Assignee: unassigned at gcc dot gnu.org Reporter: lutztonineubert at gmail dot com Target Milestone: --- Short summary: The following code returns 1 if compiled with -O2 (which is wrong) and does return 0 if compiled without optimization. ``` #include <array> #include <cstddef> #include <exception> #define GCC_VERSION (__GNUC__ * 10000 \ + __GNUC_MINOR__ * 100 \ + __GNUC_PATCHLEVEL__) static_assert(GCC_VERSION == 110300); template <size_t Bits> class bitset { private: using word_t = size_t; static constexpr size_t bits_per_word = sizeof(word_t) * 8; static constexpr size_t number_of_words = (Bits / bits_per_word) + (((Bits % bits_per_word) == 0) ? 0 : 1); public: bool all_first(size_t n) const { { if (n > Bits) { #ifdef RETURN_INSTEAD_TERMINATE return false; #else std::terminate(); #endif } size_t i = 0; for (; n > bits_per_word; n -= bits_per_word, i++) { if (words_[i] != ~word_t{0}) { return false; } } word_t last_word = words_[i]; for (; n != 0; n--) { if ((last_word & 1) != 1) { return false; } last_word >>= 1; } return true; } } void fill() noexcept { for (auto& word : words_) { word = ~word_t{0}; } } private: std::array<word_t, number_of_words> words_{}; }; volatile int X = 0; int main() { if (X == 1) { bitset<123> bitset; static_cast<void>(bitset.all_first(123)); } else { bitset<256> bitset; bitset.fill(); if (!bitset.all_first(255)) { return 1; } } return 0; } ``` See: https://gcc.godbolt.org/z/bEexjrKP4 This issue does not exist in GCC 10 or GCC > 12.1. I couldn't test if it does work in GCC 11.3.1 (or the trunk of it). Additional: * I could also trigger the issue with -O1 -fipa-icf -fpartial-inlining * If we do a return false instead of a std::terminate, no wrong code is generated. I am sorry, but I couldn't reduced the code any further - this already took so much time to figure out it is a compiler bug.