https://gcc.gnu.org/bugzilla/show_bug.cgi?id=121720
Bug ID: 121720 Summary: [13.4 / 14.3 / 15 / 16 Regression] std::min_element is not optimized at -O2 Product: gcc Version: 14.3.0 Status: UNCONFIRMED Severity: normal Priority: P3 Component: c++ Assignee: unassigned at gcc dot gnu.org Reporter: moncef.mechri at gmail dot com Target Milestone: --- Consider the following code: #include <algorithm> #include <cstdint> #include <vector> size_t min1(const std::vector<uint64_t>& v) { return *std::min_element(v.begin(), v.end()); } size_t min2(const std::vector<uint64_t>& v) { auto min = v[0]; for (size_t i = 1; i < v.size(); ++i) if (v[i] < min) min = v[i]; return min; } On Linux x86_64, with g++ 13.3 or 14.2 at -O2, the codegen for the main loop is identical between the two versions: mov rcx, QWORD PTR [rdx] cmp rax, rcx cmova rax, rcx mov rcx, QWORD PTR [rdx+8] cmp rax, rcx cmova rax, rcx add rdx, 16 cmp rsi, rdx jne .L4 Indicating that the iterator in min1() has been optimized away successfully. However, starting with GCC 13.4 and 14.3 (as well as 15 and 16 trunk), the iterator isn't optimized away anymore at -O2: .L4: mov rsi, QWORD PTR [rdx] cmp QWORD PTR [rax], rsi cmovb rdx, rax add rax, 8 cmp rcx, rax jne .L4 With the impacted compiler versions, the iterator does get optimized away at -O3. Demo: https://godbolt.org/z/85rdj4s36 Note: There are existing issues related to missed optimizations of std::min_element (for example [1] and [2]), but I felt like this one warranted its own issue since it's a regression introduced in versions released just a few months ago. [1] https://gcc.gnu.org/bugzilla/show_bug.cgi?id=89121 [2] https://gcc.gnu.org/bugzilla/show_bug.cgi?id=102684