[OT] The Usual Arithmetic Confusions
Siarhei Siamashka
siarhei.siamashka at gmail.com
Sat Feb 5 21:16:54 UTC 2022
On Saturday, 5 February 2022 at 08:59:22 UTC, Walter Bright wrote:
> On 2/4/2022 6:35 PM, Siarhei Siamashka wrote:
>> My suggestion:
>>
>> 1. Implement `wrapping_add`, `wrapping_sub`, `wrapping_mul`
>> intrinsics similar to Rust, this is easy and costs nothing.
>> 2. Implement an experimental `-ftrapv` option in one of the
>> D compilers (most likely GDC or LDC) to catch both signed and
>> unsigned overflows at runtime. Or maybe add function
>> attributes to enable/disable this functionality with a more
>> fine grained control. Yes, I know that this violates the
>> current D language spec, which requires two's complement
>> wraparound for everything, but it doesn't matter for a fancy
>> experimental option.
>> 3. Run some tests with `-ftrapv` and check how many
>> arithmetic overflows are actually triggered in Phobos. Replace
>> the affected arithmetic operators with intrinsics if the
>> wrapping behavior is actually intended.
>> 4. In the long run consider updating the language spec.
>>
>> Benefits: even if `-ftrapv` turns out to have a high overhead,
>> this would still become a useful tool for testing arithmetic
>> overflows safety in applications. Having something is better
>> than having nothing.
>
> I recommend creating a DIP for it.
Thanks for not outright rejecting it. This really means a lot!
I'll look into the DIP submission process.
Accidentally or not, turns out that GDC already supports
`-ftrapv` option. Which works with C/C++ semantics (traps for
signed overflows, wraparound for unsigned overflows, types
smaller than `int` are flying under the radar due to integral
promotion). Now I need to experiment with it a little bit to
check how it interacts with Phobos and the other D code in
practice. Patching up GCC sources to test if unsigned overflows
can be also trapped is going to be interesting too.
But in general, this looks like a very promising feature. It can
provide some protection against arithmetic overflow bugs for
32-bit and 64-bit calculations. And the practical implications of
troubleshooting such arithmetic overflows in large and
complicated software was one of my primary concerns about D
language.
More information about the Digitalmars-d
mailing list