From mboxrd@z Thu Jan 1 00:00:00 1970 From: "Trenton D. Adams" To: "'Gary Thomas'" , Cc: Subject: RE: [ECOS] Optimizations and bad code Date: Mon, 23 Jul 2001 09:31:00 -0000 Message-id: <000101c11394$fc14be70$090110ac@TRENT> References: X-SW-Source: 2001-07/msg00697.html > > > On 23-Jul-2001 rob.wj.jansen@philips.com wrote: > > > > Compiler optimizations can be a real pain, especially if you have some > funny code. > > Look at the following example: > > > > { > > int i, y; > > > > i = 0; > > > > for(y=0; y<176; y++) > > { > > func(x, y, (a[i++] + (a[i++]<<1) + a[i++])>>2); > > } > > } > > > > This is real ugly code, extracted from a non working progam. > > It was meant to combine three values from an RGB buffer (containing a > 24 bit image) > > into one 8 bit gray scale value. This was no serious programming but > just a fast hack > > to get something on the LCD. > > > > According to the C standard, the arguments to the + operator may be > evaluated in any > > order, making it unpredictable to tell if the R, G or B value will get > the <<1. But I guess that > > the "i" should always be three more that it started of with after > going through the loop once. > > > > The amizing part however is that with the arm-elf-gcc compiler, it > depends if optimizations > > are on "-O2" or off "-O0". Without optimizations i is incremented with > 1 (!) after going through > > the loop once. All other variants (including different optimization > settings for the > > i686-pc-linux-gnu > > and native linux compiler) have i incremented by 3. > > > > Although I admit that one should never write code like this, the > results are amazing. > > It just shows that "working in my private enviroment" does not mean it > is correct code. > > This code is simply frightening!! > > Firstly, in the line > func(x, y, (a[i++] + (a[i++]<<1) + a[i++])>>2); > the order of the i++ is not guaranteed at all, so the results could vary > widely from platform/architecture to platform. > > Also, since the value of 'i' is not used after the for{} loop, or even > within it except > as an index, there is no reason at all for the compiler to ever keep it > around or make > the updated value available. > > The worst part of it all is that even "This was no serious programming > but just a fast hack", > writing this sort of code can become habitual. Once in that "mold", the > programmer will > write similar code for "serious" use and then wonder why it doesn't work > :-( Happy to say that I don't have anything remotely that NASTY in my code, nor will there ever be any! So, it's unlikely it's optimizations. Besides, I already disabled optimizations in the makefile for my PCMCIA driver, and that had no effect. Still can't read the piece of crap CIS though. Cirrus sucks for support.