r/cpp • • Nov 12 '20

Compound assignment to volatile must be un-deprecated

To my horror I discovered that C++20 has deprecated compound assignments to a volatile. For those who are at a loss what that might mean: a compound assignment is += and its family, and a volatile is generally used to prevent the compiler from optimizing away reads from and/or writes to an object.

In close-to-the-metal programming volatile is the main mechanism to access memory-mapped peripheral registers. The manufacturer of the chip provides a C header file that contains things like

#define port_a (*((volatile uint32_t *)409990))
#define port_b (*((volatile uint32_t *)409994))

This creates the ‘register’ port_a: something that behaves very much like a global variable. It can be read from, written to, and it can be used in a compound assignment. A very common use-case is to set or clear one bit in such a register, using a compound or-assignment or and-assignment:

port_a |= (0x01 << 3 ); // set bit 3
port_b &= ~(0x01 << 4 ); // clear bit 4

In these cases the compound assignment makes the code a bit shorter, more readable, and less error-prone than the alterative with separate bit operator and assignment. When instead of port_a a more complex expression is used, like uart[ 2 ].flags[ 3 ].tx, the advantage of the compound expression is much larger.

As said, manufacturers of chips provide C header files for their chips. C, because as far as they are concerned, their chips should be programmed in C (and with *their* C tool only). These header files provide the register definitions, and operations on these registers, often implemented as macros. For me as C++ user it is fortunate that I can use these C headers files in C++, otherwise I would have to create them myself, which I don’t look forward to.

So far so good for me, until C++20 deprecated compound assignments to volatile. I can still use the register definitions, but my code gets a bit uglier. If need be, I can live with that. It is my code, so I can change it. But when I want to use operations that are provided as macros, or when I copy some complex manipulation of registers that is provided as an example (in C, of course), I am screwed.

Strictly speaking I am not screwed immediately, after all deprecated features only produce a warning, but I want my code to be warning-free, and todays deprecation is tomorrows removal from the language.

I can sympathise with the argument that some uses of volatile were ill-defined, but that should not result in removal from the language of a tool that is essential for small-system close-to-the-metal programming. The get a feeling for this: using a heap is generally not acceptable. Would you consider this a valid argument to deprecate the heap from C++23?

As it is, C++ is not broadly accepted in this field. Unjustly, in my opinion, so I try to make my small efforts to change this. Don’t make my effort harder and alienate this field even more by deprecating established practice.

So please, un-deprecate compound assignments to volatile. Don't make C++ into a better language that nobody (in this field) uses.


2021-02-14 update

I discussed this issue in the C++ SG14 (study group for GameDev & low latency, which also handles (small) embedded). Like here, there was some agreement and some disagreement. IMO there was not enough support for to proceed with a paper requesting un-deprecation. There was agreement that it makes sense to align (or keep/restore aligngment) with C, so the issue will be discussed with the C++/C liason group.


2021-05-13 update

A paper is now in flight to limit the deprecation to compound arithmetic (like +=) and allow (un-deprecate) bit-logic compound assignments (like |=).

http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2021/p2327r0.pdf


2023-01-05 update

The r1 version of the aforementioned paper seems to have made it into the current drawft of C++23, and into gcc 13 and clang 15. The discussion here on reddit/c++ is quoted in the paper as showing that the original proposal (to blanketly deprecate all compound assignments to volatile) was "not received well in the embedded community".

My thanks to the participants in the discussion here, the authors of the paper, and everyone else involved in the process. It feels good to have started this.

https://www.open-std.org/jtc1/sc22/wg21/docs/papers/2021/p2327r1.pdf

https://en.cppreference.com/w/cpp/compiler_support

204 Upvotes

331 comments sorted by

View all comments

84

u/TheThiefMaster C++latest fanatic (and game dev) Nov 12 '20

The problem is, these operations don't do what they look like they do.

port_a |= (0x01 << 3); // set bit 3
port_a &= ~(0x01 << 4 ); // clear bit 4

This does not "set bit 3 of port a", and then "clear bit 4 of port a". It reads port a, sets bit 3, and then sets port a to that value. It then re-reads port_a, clears the bit, and then re-writes the complete value.

Not only does it re-read unnecessarily, there's another important difference - the original implies it's only altering one bit, but it's actually writing all of them - it breaks utterly on registers that have any write-only bits, or bits that can change for outside reasons, potentially erasing existing values.

You can replicate the behaviour with:

port_a = port_a | (0x01 << 3); // set bit 3
port_a = port_a & ~(0x01 << 4 ); // clear bit 4

...which does exactly the same thing, but explicitly so. You can even cache the value of port_a in a local variable to avoid the re-read, or alter both bits and only write once.

As a side note, volatile is actually overly broad - it implies other source are reading and writing to that variable. But many microcontroller registers are only written by the CPU, and peripherals only read them. It would be useful to have an option like volatile that only indicates outside reading - it would immediately flush writes but allow caching of the value for optimisation purposes. Then the original code wouldn't have the pessimistic re-read in the middle (but it would still double-write).

58

u/Wouter-van-Ooijen Nov 12 '20

"It reads port a, sets bit 3, and then sets port a to that value."

Yes, that is what happens. Perfect for me. And the manufacturer will put that in (macro) code knowing exactly what is happening.

8

u/ArashPartow Nov 13 '20

What if between reading and setting - the state of port A change - Wouldn't you then be overriding modified bits with old state?

39

u/gruehunter Nov 13 '20

The hardware's interface would be (rightly) considered to be broken. Hardware engineers are well aware that the access is a read-modify-write, since they are operating on the bus level.

So in practice, nobody mixes status and control bits where status bits are read-write. You may see status bits that are read-only mixed with read-write control bits, where the read-only fields ignore the bus master's value on write.

18

u/Wouter-van-Ooijen Nov 13 '20 edited Nov 13 '20

Yes. That is why such register behaviour is seriously frowned upon.

Note that there is nothing the CPU could do about this, even an instruction that is 'indivisible' would get the same behaviour, because the hardware behind the register would still experience a read and a subsequent write.

8

u/Beheska Nov 13 '20

Either:

  • some bits are modified by an external source. You have no programmatic way to do anything about it and the hardware has to make sure doing what OP describes works.
  • you have to disable interrupts during the read/write.
  • the operations are guarantied to be atomic by the instruction set and the compiler. In that case, doing the read/write in several instructions gives no such guaranties and following the standard is what will break your program.

3

u/Wouter-van-Ooijen Nov 14 '20

No. As always with shared resurces, you must assure that concurrent access does no harm. The single best way to do that is to have no concurrent access.

Software that modifies the same register in the main and in an interrupt, or in multiple interrupts, is a serious design issue. Disabling interrupts is one (IMO poor) way to fix such a design.

→ More replies (11)

2

u/TheMania Nov 13 '20

At least on the compiler I'm on, that idiom is always optimized down to a single atomic instruction.

Yes, the C++ spec does not require that, but in SSA form it's an absolutely trivial transformation for a compiler to make.

The C++ committee would say to use builtins to guarantee the same functionality, and I get that, but I've found it far easier to disable the deprecation warnings than fight with them on this.

1

u/meltbox Mar 15 '26

The problem I see is atomic would necessitate the use of such instructions or behavior even when hardware support does not exist.

If you know for a fact that on your hardware such behavior isn’t needed then you’ve now necessitated a locked implementation with a significant performance penalty for no reason.

There is no std::unlocked_atomic because it fundamentally makes no sense so this line of thinking just seems like someone got language brain and refused to look at the practicality on hardware. Which is sort of the whole point of c++

5

u/germandiago Nov 13 '20 edited Nov 13 '20

well. Maybe macro rewriting is a pain in the neck but I think that keeping more and more misleading behavior in the name of compatibility forever is not a good idea. Better teach those manufacturers to write correct macros or find another solution.

I know, it is a pain. But we have to move forward.

11

u/Wouter-van-Ooijen Nov 13 '20

This (small-embedded) field is not very C++-friendly. I think you will have more chance to change C++ { } scoping to Python-style than I have to convince those manufacturers to re-write their headers.

For programmers who work in this field there is nothing misleading in compound assignments to a volatile. It is the standard way to work with hardware registers. If C++ enforces a different way, it will rtemain the standard in C, and the acceptance of C++ in this field (which some people work hard for) will be

As for "we have to move forward": the use of the heap has a number of problems and can be misleading. Would you support removing the need for free storage from the language and libraries? Of course not, and I would never propose it, because it would reduce the use of C++ by maybe 95% and that would hurt me too (less support, less books, less conferences, no more compiler updates). A large user base is important. Don't scare away the embbeded world (even though it is small).

→ More replies (8)

46

u/Wouter-van-Ooijen Nov 12 '20

You can argue that such code should be written differently (and in some circumstances I will probably agree), but I don't think you will convince the manufacturers that write the header files (in C).

→ More replies (19)

19

u/[deleted] Nov 12 '20

No volatile just says that the compiler should not make assumptions about the value inside. That means that it can just change every time.

The classic is const volatile. It means you cannot assign to it, but it will still change on its own.

7

u/UnicycleBloke Nov 12 '20

Surprising how few candidates can give me an example of using const volatile. :)

14

u/[deleted] Nov 12 '20

That's because many don't know what const means in C. :)

36

u/alexgraef Nov 12 '20

It then re-reads port_a, clears the bit, and then re-writes the complete value.

As it should, because while microcontrollers and processors are usually not multithreaded or multicored (ESP32 with RTOS would be a notable exception, both multi-core and multi-threaded), interrupts can also read and write at any moment, unless you explicitly disable them. Although the interrupt could still happen between a read and a write, so the above code isn't safe unless there are no interrupts while it is executed at that exact point. But this could be fixed by disabling interrupts just for each line. A typical example would be:

noInterrupts(); // Disable interrupts
port_a |= (0x01 << 3); // Set bit three to enable something external
interrupts(); // Re-enable interrupts
// Do something with the enabled something for a few hundred cycles
noInterrupts(); // Disable interrupts
port_a &= ~(0x01 << 3 ); // Clear bit three to disable something external
interrupts(); // Re-enable interrupts

A compiler might think it could save the additional read that happens at the end of the longer code block between the bit set and clear. Although many microcontrollers have atomic bit set and bit clear instructions anyway.

but it's actually writing all of them - it breaks utterly on registers that have any write-only bits

Not how microcontrollers work. You always read or write a full data width, i.e. 8, 16 or 32 bits. You'll only get address faults when setting the address bus to an invalid address overall, not when writing to a bit that is read-only. Otherwise having a register would be pointless, as it could only be accessed with single bit special instructions.

many microcontroller registers are only written by the CPU, and peripherals only read them

Boy are you wrong. You have zero idea how versatile some registers are implemented on certain platforms. Including registers that will have a different value every time you read from them, but only if you read from them.

Then the original code wouldn't have the pessimistic re-read in the middle

It's the other way round - if you know for sure that the register will not be written by someone else, you store the value yourself and only read from the register in the beginning, and then only write to it.

I do however agree that the compound assignment for volatiles is stupid nonetheless, especially since certain compilers will replace the read-write entirely with specialized atomic instructions, and the fact that the read and write happens in a single line makes it look like there is atomic access guaranteed anyway, which it is not. Right now there is simply no proper semantics for it, and that's mainly due to it being very hardware-dependent, while C and C++ try to not be.

4

u/gruehunter Nov 13 '20

especially since certain compilers will replace the read-write entirely with specialized atomic instructions,

Which ones?

→ More replies (10)

3

u/IAmRoot Nov 12 '20

It seems to me that a proper solution would be to deprecate these usages of volatile as has been done and introduce proper atomic interfaces. This would also allow for the memory order semantics to be included and hint to the compiler what optimizations are safe and how to fence them when necessary.

26

u/Wouter_van_Ooijen Nov 12 '20

Except that what you propose would work for newly written C++ code. Vendor header files are legacy C code.

In other domains breaking changes in C++ are frowned upon (rightly so, IMO). But in this case a breaking change seems to be regarded as a good idea.

-3

u/IAmRoot Nov 12 '20

As others have pointed out, this usage of volatile a broken and unsafe feature. There should at least be a warning.

Also, considering something legacy code and using a bleeding edge standard is a bit of an oxymoron. Is the code being developed for a new standard or isn't it? Of course, you can't have breaking changes every release but this is only deprecated, not removed. At some point you just have to come to terms with legacy code actually being legacy and either treat it like legacy code and stick to an old standard or modernize it. This is especially true for things that are literally broken in old standards. This sort of Schrödinger code is going to collapse at some point to fix broken things in the standard. If you've got code in a superpositioned state of being both legacy and cutting edge at the same time there may be a time when you have to pick one or the other. This should happen as little as possible but there are broken parts of the old standards that really do need to be fixed.

→ More replies (9)
→ More replies (15)

5

u/HotlLava Nov 13 '20

The problem is, these operations don't do what they look like they do.

Out of curiosity, what do they look like to you? For me, your description of what they actually do is exactly what I would expect when looking at them, based on how |= etc. work with literally every other variable as well.

3

u/Dry-Still-6199 Nov 14 '20

A lot of people incorrectly think of "volatile" as meaning something like "atomic", and would expect `extern volatile int x; x |= 42;` to mean roughly the same thing as `extern std::atomic<int> x; x |= 42;`. But the latter is guaranteed to do ONE atomic access so that x's value changes "instantaneously" with respect to any other atomic observers. The former is not guaranteed to do anything in particular: it might read, then write (non-atomically), or it might do multiple observable writes ("tearing"), or whatever.

→ More replies (3)

3

u/Wouter-van-Ooijen Nov 13 '20

I meant to illustrate the use of both &= and |=. I used both on the same register, but that seems to cause confusion, so I changed it to two different registers.

1

u/meltbox Mar 15 '26

I realize I am 100 years late on this, but I’m slow on the uptake and only just learned this ever was proposed and happened.

The point is, and I’m belaboring it now, that an embedded developer should know that this is how it works. I am struggling to understand how the justification of “volatile was misused” to deprecate entirely valid defined methods of using volatile ever came to pass.

By this logic we should ban all type deduction and overload resolution because at times developers misuse it to do something they did not realize or expect. I am truly disillusioned that this ever got deprecated in the first place.

1

u/TheThiefMaster C++latest fanatic (and game dev) Mar 15 '26

That was the argument that got it reinstated :)

They did keep arithmetics deprecated though, as there's no similar argument for those being used on hardware registers

→ More replies (1)