www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.bugs - -O is evil

here it comes again... an optimizer bug i've reported back in dmd 
0.92... it's still present in dmd 0.100 and i've stumbled upon it again.
Here are two completely different code samples. Both produce different 
results when -O is enabled and disabled. They both use floats and arrays 
(the first works the same if structs are used).

<code1>
import std.stdio;

void len(float x, float y, float z)
{
	writefln("x: ", x, ", y: ", y, ", z: ", z, ",  lenSq: ", x*x+y*y+z*z);
}

void main()
{
	float[3] a;
	a[0] = a[1] = a[2] = 0.f;

	for (int y = 0; y < 7; ++y)
	{
		len(a[0], a[1], a[2]);

		float justOne() { return 1.f; }

		float dot = justOne();
		if (dot < 0.f) dot = 0.f;
	}
	
	getchar();
}
</code1>

try to modify anything in code1 and there's a large chance it will work 
in the optimized mode. e.g. the justOne function was stripped down from 
a larger one, yet simple assignment works just fine, only setting dot 
from the function gives problems. also, if you remove that float dot = 
... line, everything will be fine.

<code2>
import std.stdio;

ubyte[4] arr;

void foo()
{
  *cast(float*)(&arr[0]) = 3.14;
}

uint bar()
{
  uint result = *cast(uint*)&arr[0];
  return result;
}

float baz()
{
  assert (float.sizeof == uint.sizeof);
  uint result = bar();
  //result &= 0xffffffff;
  return *cast(float*)&result;
}

void main()
{
  foo();
  float x = baz();

  writefln("value: %f", x);
  getchar();
}
</code2>

both of these were boiled down from much longer programs so don't look 
at their functionality, cuz it isn't the point. If I've stumbled upon 
this problem for the second time, I believe other ppl will as well. 
Unless ofcuz optimizations are disabled :/

my system: dmd .100, winxp


Tom S.
Aug 22 2004