https://gcc.gnu.org/bugzilla/show_bug.cgi?id=129126
Bug ID: 129126
Summary: [15/16/17 Regression] False-positive -Warray-bounds in
zero-trip loop over std::vector constructed with size
and value
Product: gcc
Version: 16.2.0
Status: UNCONFIRMED
Severity: normal
Priority: P3
Component: tree-optimization
Assignee: unassigned at gcc dot gnu.org
Reporter: Bil.Kleb at NASA dot gov
Target Milestone: ---
Created attachment 66320
--> https://gcc.gnu.org/bugzilla/attachment.cgi?id=66320&action=edit
Minimal C++ reproducer for false-positive -Warray-bounds in a zero-iteration
loop
The following valid program produces two -Warray-bounds warnings with
-O2 -Wall or -O3 -Wall. The diagnosed accesses are in a loop that executes
zero iterations.
Reproducer (pr.cpp):
#include <vector>
int f() {
std::vector<double> t(1);
std::vector<int> r(t.size(), 1);
int id = 0;
for (int i = 1; i < int(r.size()); i++)
if (t[i] - r[i] > 0) id = i;
return id;
}
Command:
g++ -std=c++17 -O2 -Wall -c pr.cpp
Diagnostic excerpts:
pr.cpp:7:18: warning: array subscript 1 is outside array bounds of 'double [1]'
[-Warray-bounds=]
pr.cpp:7:18: warning: array subscript 1 is outside array bounds of 'int [1]'
[-Warray-bounds=]
Expected result: no warning. Both vectors have size 1; the loop starts at
i == 1, so its condition is false before any access occurs.
Compiler Explorer:
https://godbolt.org/z/jPWWbMsc8
Version comparison using Compiler Explorer's x86-64 GCC compilers:
- No warning with GCC 9.5, 10.5, 11.5, 12.5, 13.4, or 14.4.
- Warns with GCC 15.1, 15.2, 15.3, 16.1, 16.2, and the available trunk
snapshot, at both -O2 and -O3.
Also reproduced locally with:
gcc version 16.2.0 (Homebrew GCC 16.2.0)
Target: aarch64-apple-darwin25
Changes that remove the warning locally:
- Adding -fno-tree-vrp.
- Replacing r(t.size(), 1) with r(t.size()).
- Replacing r(t.size(), 1) with r(1, 1).
- Using an unsigned loop index and comparing directly against r.size(),
without the int cast.
With -O2 -fdump-tree-all, the final optimized body of f is simply:
int f ()
{
<bb 2>:
return 0;
}
Thus GCC ultimately eliminates the loop, but diagnoses its accesses
before that elimination.
In the vrp1 dump, the vector fill operation still contains a one-trip
loop, and r's end pointer comes from that loop's PHI result. This appears
to prevent the subsequent bounds analysis from establishing r.size() == 1.
Possibly related reports: PR 128679, PR 126733, and PR 126737.
I have not established whether this is a duplicate. In particular, I
have not verified whether Compiler Explorer's trunk snapshot includes
r17-6233, the fix discussed in PR 128679.