llvm-project icon indicating copy to clipboard operation
llvm-project copied to clipboard

-O2/-O3 breaks reverse iterators

Open llvmbot opened this issue 13 years ago • 2 comments

Bugzilla Link 16421
Resolution FIXED
Resolved on Oct 29, 2019 01:24
Version trunk
OS Linux
Reporter LLVM Bugzilla Contributor
CC @atrick,@ekatz,@zygoloid

Extended Description

#include #include #include #include int main() { std::vector wd(5); std::iota(wd.rbegin(), wd.rend(), 1.0); for (std::size_t i = 0; i < wd.size(); ++i) std::cout << wd[i] << ", "; for (std::ptrdiff_t i = wd.size() - 1; i >= 0; --i) std::cout << wd[i] << ", "; }

This code yields the expected result when compiled with -O1: 5, 4, 3, 2, 1, 1, 2, 3, 4, 5, When compiling with -O2 or -O3, it breaks, however: 0, 4, 3, 2, 1, 1, 2, 3, 4, 5,

That's a pretty heavy bug if you ask me. It has affected me in a real application. Interestingly, if the two loops are interchanged, the bug disappears. The sample is compiled correctly when using gcc 4.6, 4.7, 4.8 as well as Intel C++ 13.1. It is also broken in Clang 3.2

Possible duplicate is http://llvm.org/bugs/show_bug.cgi?id=12531

llvmbot avatar Jun 22 '13 21:06 llvmbot

Confirmed on clang 3.4.1. Fixed in clang 3.5.

ekatz avatar Oct 29 '19 08:10 ekatz

Confirmed, reduced to:

#include <stdio.h> struct reverse_iterator { mutable double *t; double *current; attribute((always_inline)) reverse_iterator(double x) : t(x), current(x) {} double &operator() const { t = current; return *--t; } reverse_iterator operator++(int) { reverse_iterator tmp(*this); --current; return tmp; } }; template void f(T a, T b) { double x = 1.0; while (a.current != b.current) { *a++ = x++; } } int main() { double *wd = new double[5]; f(reverse_iterator(wd + 5), reverse_iterator(wd)); for (unsigned i = 0; i < 5; ++i) printf("%f, ", wd[i]); for (int i = 4; i >= 0; --i) printf("%f, ", wd[i]); }

Looks like a GVN bug?