void cpv(float x)
{}
void main(){
int cnt;
for(int i=0; i<30; i++)
{
cnt++;
cpv(i*60 - 100); // comment this out and it makes 30 loops
}
writefln("%s",cnt); // compile with -O and it prints 1
}
tested with dmd2.050 using -O for optimization.
Comment #1 by bearophile_hugs — 2010-12-01T12:47:01Z
Reduced a little:
import core.stdc.stdio: printf;
void foo(int) {}
void main() {
int count;
for (int i = 0; i < 2; i++) {
count++;
foo(i * 5 - 6); // comment this out and it makes 2 loops
}
printf("%d\n", count); // compile with -O and it prints 1
}
Comment #2 by clugdbug — 2010-12-01T16:26:06Z
Applies to all D1 and D2, even prehistoric versions (tested as far back as DMD0.140).
Very weird. In bearophile's test case, written as
for (int i = 0; i < A; i++) {
count++;
foo(i * 5 - B); // comment this out and it makes 2 loops
}
it fails for B = (5+1)..(5*A) inclusive (eg, 6, 7, 8, 9, 10 all fail for A==2).
And if it is foo(i*6 - B), it fails for B= 7..6*A.
(In reply to comment #5)
> Automatic fuzzy testing like this
kidding me ? I wish it would have been found by any test, it appeared in an actual project. while i converted some C code to D i wondered a lot until i finally reduced it to this testcase.
Comment #7 by clugdbug — 2010-12-06T11:53:27Z
Bearophile -- That's an interesting link. Currently, DMD back-end bugs are being found at the rate of about 3 per year. So yes, fuzzy testing of DMC could probably flush out some backend bugs a bit faster.
-------------------
Here's what's happening. First, in this code:
for (int i = 0; i < 10; i++) {
foo(i * 5 - 6);
}
it sees that i and 10 are always >=0, so the signed comparison "i < 10" is replaced with an unsigned one. (This happens in the backend in constprop() ).
Then, while dealing with loop invariants, it rewrites the loop into:
for (int _i2 = -6; _i2 < 10*5 - 6; _i2 += 5)
{
foo(_i2);
}
Fine. Except that it had changed the comparison into an unsigned one!
Particularly interesting is the case where the call is foo(i*5-50);
Then, the loop becomes:
for (int _i2 = -50; _i2 < 0; _i2 += 5)
Since an unsigned value is NEVER less than zero, it just drops the loop completely!
Nasty.
Comment #8 by bugzilla — 2010-12-06T22:41:10Z
For optimizer spelunkers, if you compile dmd with debug on, and compile with:
-O --c
you'll get reports of the various optimizations done.