18 October 2014

什么是as-if规则?

cppreference中对有如下定义

Allows any and all code transformations that do not change the observable behavior of the program.

与之相关的解释有:

  1. At every sequence point, the values of all volatile objects are stable (previous evaluations are complete, new evaluations not started) (until C++11)
  2. Accesses (reads and writes) to volatile objects occur strictly according to the semantics of the expressions in which they occur. In particular, they are not reordered. (since C++11)
  3. At program termination, data written to files is exactly as if the program was executed as written.
  4. Prompting text which is sent to an interactive devices will be shown before the program waits for input.
  5. If #pragma STDC FENV_ACCESS is set to ON, the changes to the floating-point environment (floating-point exceptions and rounding modes) are guaranteed to be observed by the floating-point arithmetic operators and function calls as if executed as written, except that intermediate results of any expression may be calculated as if to infinite range and precision (unless #pragma STDC FP_CONTRACT is OFF)

C++11中1.9节对此的定义如下:

The semantic descriptions in this International Standard define a parameterized nondeterministic abstract machine. This International Standard places no requirement on the structure of conforming implementations.In particular, they need not copy or emulate the structure of the abstract machine. Rather, conformingimplementations are required to emulate (only) the observable behavior of the abstract machine as explained below.

在其脚注中有如下说明:

This provision is sometimes called the “as-if” rule, because an implementation is free to disregard any requirement of this International Standard as long as the result is as if the requirement had been obeyed, as far as can be determined from the observable behavior of the program. For instance, an actual implementation need not evaluate part of an expression if it can deduce that its value is not used and that no side effects affecting the observable behavior of the program are produced.

observable behavior包括:

  • Access 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 one of the possible results that execution of the program according to the abstract semantics would have produced.
  • The input and output dynamics of interactive devices shall take place in such a fashion that prompting output is actually delivered before a program waits for input. What constitutes an interactive device is implementation-defined.

也就是说,只要不改变程序的 可观察行为(observable behavior),就可以任意改变程序代码。在as-if规则下,编译器可以对代码做最大限度的优化,尽可能提升应用程序的执行效率。

Resources