[comp.lang.c] Re^2: C optimizer

richard@torch.UUCP (Richard Nuttall) (02/23/89)

thor@stout.ucar.edu (Rich Neitzel) writes:

>In addition, should one let the compiler do optimization? This may not
>be important in most cases, but for others it can destroy the
>functioning of the code. For example, many external devices have
>control/status registers that are cleared only when read. An optimizer
>might see code:

>	junk = *csr;

>and since junk is never used again, remove that line.

Thats what the keyword VOLATILE is for. It is an important part of
many languages (I have used it in VAX PASCAL and have seen it in several
versions of C).

volatile int *csr;

means (to the compiler) "don't make any assumptions about the value of this
variable, as it may be changed at any time by outside forces.

>Optimizing is an uncertain tool unless one knows what the optimizer is
>doing. Since RISC cpus use heavily optimizing compilers and have
>assemblers that are nearly impossible to follow, how does one make
>certain that the optimizer hasn't shafted you? (On my 68020 I can peek
>at the assembler output.) Even on CISC machines, perhaps compiler
>vendors should supply a OPT_ON and OPT_OFF set of directives.

How about the -O option to C compilers. I have never used a compiler which
did'nt allow you to switch off all or parts of optimisation.


On another note, my favourite optimisations done by some compilers
(e.g. APOLLO CC) is lifetime analysis. In the example below,

x = func(y);     /* statement 1 */
z = 4 * x;       /* statement 2 */
.....            /* other statements not using x*/
x = func(q);     /* statement 3 */
y = 10 * x;      /* statement 4 */
.....            /* other statements not using x*/

a compiler doing lifetime analysis will realise that after (1..2) the value
of "x" is set before it is used again. Therefore, x is effectively two
different variables. The compiler will therefore recode (3..4) as

temp = func(q);     /* statement 3 */
y = 10 * temp;      /* statement 4 */

This will allow other optimisations; e.g. if x was assigned a register,
the register can now be reused.

The manuals for compilers that do this and other complex optimisations are
full of warnings that if you are doing something sneeky behind its back,
you must tell the compiler (by switching off optimisation) or it may optimise
out your piece of sneeky code.

-- 
Richard Nuttall               |    ukc!stc!datlog!torch!richard
Torch Technology Ltd.         |    
Cambridge England             |    0223 841000 X 309