help-gplusplus
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: Protect a block of code from optimization?


From: John Victor
Subject: Re: Protect a block of code from optimization?
Date: Fri, 3 Aug 2007 03:48:11 -0400

> Is there some kind of preprocessor line or something to instruct the
> optimizer to not optimize a certain section of code, but still be able
> to optimize the rest?

It isn't clear here what you mean by not optimizing. But assuming that the order of the instructions is what bothers you, and also assuming a GNU compiler collection (since you're posting on this mailing list), then you can use a memory barrier or optimization barrier. Optimization barrier can be done as follows:
volatile asm("":::"memory");
This tells the compiler to insert the assembly instruction (i.e. an empty instruction). The "memory" part tells the compiler that this artificial assembly instruction can alter the memory in some indirect way and the volatile keyword is necessary so that the optimization doesn't remove the empty instruction. The result will be that the compiler will make sure not to mix the code before the asm directive with those that comes after it. Notice that this doesn't prevent the processor from doing it's own optimization, i.e. reordering instrcutions, but this seldom become a problem for the program since the processor retirement unit will make sure to produce the expected results. Usually instruction reordering on the microprocessor scale is of interest to kernel developers only, and this is where memory barriers becomes handy. If the previous assumption didn't match what you had in mind, then feel free to reply with details of the architecture and meaning of "not to optimize"

Cheers,

---------------------------
John V. Shahid
<jvshahid@gmail.com>

reply via email to

[Prev in Thread] Current Thread [Next in Thread]