[OT] The Usual Arithmetic Confusions

Siarhei Siamashka siarhei.siamashka at gmail.com
Sat Feb 5 02:35:27 UTC 2022


On Friday, 4 February 2022 at 23:45:31 UTC, Walter Bright wrote:
> On 2/4/2022 2:18 PM, Siarhei Siamashka wrote:
>> If we want D language to be SIMD friendly, then discouraging 
>> the use of `short` and `byte` types for local variables isn't 
>> the best idea.
>
> SIMD is its own world, and why D has vector types as a core 
> language feature. I never had much faith in autovectorization.

I don't have much faith in autovectorization quality either, but 
this feature is provided by free by GCC and LLVM backends. And 
right now excessively paranoid errors about byte/short variables 
coerce the users into one of these two unattractive alternatives:

  * litter the code with ugly casts
  * change types of temporary variables to ints and waste some 
vectorization opportunities

When the signal/noise ratio is bad, then it's natural that the 
users start ignoring error messages. Beginners are effectively 
trained to apply casts without thinking just to shut up the 
annoying compiler and it leads to situations like this: 
https://forum.dlang.org/thread/uqeobimtzhuyhvjpvkvz@forum.dlang.org

Is see VRP as just a band-aid, which helps very little, but 
causes a lot of inconveniences.

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.


More information about the Digitalmars-d mailing list