by mnw21cam · 4y ago · 0 comments
C needs a mechanism to declare in a source file that certain behaviour must be defined, where that behaviour is undefined in the C standard but the target architecture behaves the defined way. Then, when the source is compiled on the target architecture it works as expected, but when compiled on something else it refuses to compile.
For example, unsigned ints. It'd be great to be able to declare "I define int to be 32 bits and to overflow like a sensible 32-bit int - treat this as defined behaviour, and refuse to compile on a system where this isn't true." The number of platforms where this would fail to compile would be extremely small, and at least they would give a sensible compile error on systems that are weird.
(I'm the post's author.)
As far as I can tell there is no reason LLVM couldn't compile a document like "On x86 division by zero throws a #DE exception. On ARM division by zero returns zero. On x86 shifting by more than 32 bits shifts by (cnt mod 32) bits. On ARM shifting by more than 32 bits clears all bits. [...]" that specifies all undefined behavior. The current "nasal demons" behavior is preferred in the name of performance on some SPEC benchmarks that nobody was asking for, screwing OS writers and anyone who expected sane language semantics.
`-fwrapv` is an attempt toward doing such a thing for signed integer overflow specifically. I bet it's a pain to maintain because it significantly increases the surface area of the compiler that needs to be tested.
I don't believe doing this for more cases is feasible at the level of the compiler. Things like CHERI where the hardware and OS help are much more viable, in my book: https://www.cl.cam.ac.uk/research/security/ctsrd/cheri/
The purpose of C is to be easy to implement on new systems. You're never going to get a lot of traction adding anything to C proper.
It is ok, the accelerometer readings won't go outside the range of an int.
What's nice about Ada is you have choices, and the ecosystem facilitates creating and using such tooling.
As for your example, unsigned overflow is already defined in C and C++ and you can force the compiler error for non-32-bits using a static_assert.