Optimizer removing pointer lines

I'm having a problem where the optimizer seems to really delete lines of code. Some prerequisites: I have a program that interacts with the PCIe driver. I have an integer pointer UINT32 *bar_reg; which points to the user space address in the BAR register with which I am communicating. To write to the register, I simply cancel the link to the pointer. *(bar_reg + OFFSET) = value;

Without optimizations, this works great. However, as soon as I turn on any level of optimization, all lines that delete the link to the pointer are deleted. As I finally discovered this, I switched to Visual Studio. However, this happens regardless of the platform. So far I have managed to turn off the optimizer, but someone using my library code on Linux now wants to turn on the optimization. Therefore, I am curious why this problem arises and what is the most reasonable solution / workaround.

+5
source share
2 answers

Use the volatile keyword to prevent this variable from being optimized.

For instance:

 volatile UINT32 *bar_reg; 

The problem is that the compiler assumes that since memory does not gain access to the program, this means that the memory will remain unchanged and, therefore, it may try to optimize some entries in this memory.

+6
source

The problem you are facing includes an as-if rule , which allows the optimizer to somehow convert your code if this does not affect the observed behavior of the program.

So, if you only write to a variable, but never use it in your program, the optimizer considers that there is no observable behavior, and assumes that it can effectively optimize the work on the record.

In your case, the data is observed outside of your program, and the way to tell this to the compiler and optimizer is through volatile ., Cppreference tells us (emphasis is my going forwrd):

an object whose type is unstable, or a subobject, a mutable object, or a mutable subobject of an object with a stable change. Each access (read or write operation, call of a member function, etc.) to a volatile object is considered as a visible side effect for the purpose of optimization [...]

For reference, the as-if rule is discussed in the draft C ++ standard in section 1.9 , which states:

[...] Rather, appropriate implementations are needed to emulate the (only) observed behavior of an abstract machine, as described below.

and with regard to the as-if volatile rule is also discussed in section 1.9 , and he says:

Access to unstable objects is evaluated strictly in accordance with the rules of an abstract machine.

+2
source

Source: https://habr.com/ru/post/1207453/


All Articles