flee@shire.cs.psu.edu (Felix Lee) (02/22/89)
Machine Type: Sun 4/260S
O/S Version: SunOS 4.0
Organization: Computer Science Department, The Pennsylvania State University
333 Whitmore Laboratory, University Park, PA 16802
Description:
Compile the following code with -O2 optimization:
main()
{
int k, total, x, y;
total = 0;
for (k = 3; k > 0; --k) {
x = total;
total += 7;
x = total - x;
y = x << 2;
printf("%d\n", y);
}
}
Instead of printing 28, 28, 28 as you would expect, it produces
0, 28, 56.
Looking at the assembly code, the compiler is doing strength
reduction in the outer loop, incorrectly:
%i4 = 0;
for (k = 3; k > 0; --k) {
printf("%d\n", %i4);
%i4 += 28;
}
%i4 is a register that tracks the value (total*4).
Despite being wrong, the strength reduction is of dubious value...
--
Felix Lee