https://gcc.gnu.org/bugzilla/show_bug.cgi?id=71177
Bug ID: 71177 Summary: [6 Regression] Spurious -Waggressive-loop-optimizations warning Product: gcc Version: 6.1.1 Status: UNCONFIRMED Severity: normal Priority: P3 Component: middle-end Assignee: unassigned at gcc dot gnu.org Reporter: tavianator at gmail dot com Target Milestone: --- Created attachment 38516 --> https://gcc.gnu.org/bugzilla/attachment.cgi?id=38516&action=edit Reduced testcase The following use of boost::container::string gives a warning since GCC 6: $ cat stringbug.cpp #include <boost/container/string.hpp> using boost::container::string; string normalize(string token) { if (token.length() >= 2) { token.resize(token.length() - 2); } return token; } $ g++ -Wall -O3 -c stringbug.cpp In function ‘boost::container::string normalize(boost::container::string)’: cc1plus: warning: iteration 9223372036854775807 invokes undefined behavior [-Waggressive-loop-optimizations] In file included from stringbug.cpp:1:0: /usr/include/boost/container/string.hpp:2608:10: note: within this loop for (; first != last; ++dest, ++first, ++constructed){ ^~~ cc1plus: warning: iteration 9223372036854775807 invokes undefined behavior [-Waggressive-loop-optimizations] /usr/include/boost/container/string.hpp:2626:7: note: within this loop for ( ; first != last; ++first, ++result) ^~~ What's happening is that resize() is implemented like this: void resize(size_type n, CharT c) { if (n <= this->size()) this->erase(this->begin() + n, this->end()); else this->append(n - this->size(), c); } After inlining/constant propagation, the else block contains undefined behaviour for resize(length - 2). But the else block is also unreachable due to the if (length >= 2) check. Reduced testcase attached.