如何prevent GCC优化一些C语句? [英] How to prevent gcc optimizing some statements in C?

查看:131
本文介绍了如何prevent GCC优化一些C语句?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为了使一个脏页(在页表项的脏位开关),我接触到页面的第一个字节是这样的:

In order to make a page dirty (switching on the dirty bit in the page table entry), I touch the first bytes of the page like this:

pageptr[0] = pageptr[0];

但在实践中gcc会忽略死存储清除的声明。为了prevent GCC的优化,我重新写的声明如下:

But in practice gcc will ignore the statement by dead store elimination. In order to prevent gcc optimizing it, I re-write the statement as follows:

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

看来招的作品,但有些难看。我想知道有没有具有相同效果的任何指示或语法?而且我不希望使用 -O0 标志,因为它会带来很大的性能损失也是如此。

It seems the trick works, but somewhat ugly. I would like to know is there any directives or syntax which has the same effect? And I don't want to use a -O0 flag, since it will bring great performance penalty as well.

推荐答案

关闭优化解决了这个问题,但它是不必要的。一个更安全的替代方案是让违法的编译器使用挥发性键入预选赛。

Turning off optimization fixes the problem, but it is unnecessary. A safer alternative is to make it illegal for the compiler to optimize out the store by using the volatile type qualifier.

// Assuming pageptr is unsigned char * already...
unsigned char *pageptr = ...;
((unsigned char volatile *)pageptr)[0] = pageptr[0];

挥发性类型修饰符指示编译器要严格有关内存存储和负载。的目的之一挥发性是让编译器知道,内存访问有副作用,因此必须preserved。在这种情况下,店里有导致页面错误的副作用,并且希望编译器preserve页面错误。

The volatile type qualifier instructs the compiler to be strict about memory stores and loads. One purpose of volatile is to let the compiler know that the memory access has side effects, and therefore must be preserved. In this case, the store has the side effect of causing a page fault, and you want the compiler to preserve the page fault.

这样一来,周围code仍然可以优化,你的code是移植到不知道其他的编译器GCC的的#pragma __ __属性语法。

This way, the surrounding code can still be optimized, and your code is portable to other compilers which don't understand GCC's #pragma or __attribute__ syntax.

这篇关于如何prevent GCC优化一些C语句?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆