tags:

views:

375

answers:

3

In order to make a page dirty, I touch the first bytes of the page like this:

pageptr[0] = pageptr[0];

But it seems gcc will eliminate the statement when optimizing. In order to prevent gcc optimizing it, I write the statement like this:

volatile int tmp;
tmp = pageptr[0];
pageptr[0] = tmp;

It seems the trick works, I'd like to know is there any directives or syntax which has the same effect?

=========

Summary

Dietrich Epp's solution:

((unsigned char volatile *)pageptr)[0] = pageptr[0];

Plow's solution: using function specific option pragmas introduced since gcc 4.4

#pragma GCC push_options
#pragma GCC optimize ("O0")

your code

#pragma GCC pop_options
+10  A: 

Use the volatile type qualifier. Example:

((unsigned char volatile *)pageptr)[0] = pageptr[0];

The volatile type qualifier instructs the compiler to be strict about memory stores and loads. It doesn't turn off optimization per se, but it does what you want.

Edit: I had put volatile on the wrong side of the *. Whoops, fixed.

Dietrich Epp
I would say this is preferable to turning off optimizations. You can still benefit from other optimizations using this method.
Ben S
Do you really need to do a load from the page, though? Surely just the store would do: `*(volatile int *)pageptr = 0;`
caf
You need to modify the program which will make it humanly unreadable.
Phong
@caf - your version could cause the contents of the page to change. The OP implies that the page contents should not change.
R Samuel Klatchko
True, I read something into it that wasn't there (of course, the given solution here also would change the page, if the type of `pageptr[0]` is wider than `char`).
caf
@caf - missed the int/char issue. @DietrichEpp - it looks like your fix should be `*(unsigned char volatile *)pageptr = *(unsigned char *)pageptr;`
R Samuel Klatchko
A: 

With the gcc option "-O0", it should work. (which mean no optimization)

Phong
But it will hurts performance greatly.
ZelluX
+3  A: 

You can use

#pragma GCC push_options
#pragma GCC optimize ("O0")

your code

#pragma GCC pop_options

to disable optimizations since GCC 4.4.

See the GCC documentation if you need more details.

Plow