可以优化这种不稳定的访问吗?

Can this volatile access be optimized out?

来自ISO/IEC9899:201x部分5.1.2.3程序执行:

2 Accessing a volatile object, modifying an object, modifying a file, or calling a function that does any of those operations are all side effects, which are changes in the state of the execution environment. Evaluation of an expression in general includes both value computations and initiation of side effects. Value computation for an lvalue expression includes determining the identity of the designated object.

因此,访问 (read\write) volatile 称为副作用。 让我们继续:

4 In the abstract machine, all expressions are evaluated as specified by the semantics. An actual implementation need not evaluate part of an expression if it can deduce that its value is not used and that no needed side effects are produced (including any caused by calling a function or accessing a volatile object).

因此,如果我读取了一个 volatile(这是一个副作用)但对我读取的获取值不做任何操作,则实际上不需要此访问并且可以进行优化。

好的,还有:

6 The least requirements on a conforming implementation are:

  • Accesses to volatile objects are evaluated strictly according to the rules of the abstract machine.

  • At program termination, all data written into files shall be identical to the result that execution of the program according to the abstract semantics would have produced.

  • The input and output dynamics of interactive devices shall take place as specified in 7.21.3. The intent of these requirements is that unbuffered or line-buffered output appear as soon as possible, to ensure that prompting messages actually appear prior to a program waiting for input. This is the observable behavior of the program.

所以,据我理解,4节是抽象机的规则,6节说volatiles需要严格按照抽象机规则进行评估(4 是哪一节)。因此可以优化读取访问(无需进一步使用获取的值)。

所以,看看这段代码:

volatile int *timer_reg = REGISTER_ADDRESS_CONST;
while (*timer_reg  == 0) {/*empty loop*/}

这段代码会阻塞执行,直到 HW 在 timer_reg 指向的地址处提高一位。该寄存器充当一种定时器,它被配置为在经过一定时间后提高一位。当计时器结束时,忙碌等待结束并继续执行。

现在,这个while循环可以优化掉吗?我已经在许多具有不同优化级别的在线编译器上进行了尝试,但似乎没有。 我在这里缺少什么吗?据我了解,标准明确表示可以对其进行优化。

编辑:我的观点是,由于 while 循环是空的,编译器可能会认为获取的 volatile 值是不需要的。

So if I read a volatile (which is a side effect) without using the value I read, this access is actually not needed and can be optimized out.

没有。文字说 "its value is not used and that no needed side effects are produced"。它没有说“”。无论您是否使用该值,都会产生副作用 - 访问 volatile 变量。

So the read access (without further using the fetched value) can be optimized out.

没有

Now, can this while loop be optimized out?

没有。指向的数据是 volatile 限定的。在循环的每一圈,它必须直接从内存中读取 *timer_reg。它可能不会优化读取。它可能不会重新订购它。它可能不会缓存 it/pre-fetch 它。