Adding checked arithmetic low-level functions
After a chat with Ben on IRC, I'd like to suggest adding new low-level functions to GHC.
Prior reading:
- https://gustedt.wordpress.com/2022/12/18/checked-integer-arithmetic-in-the-prospect-of-c23/
- https://gcc.gnu.org/onlinedocs/gcc/Integer-Overflow-Builtins.html
- https://clang.llvm.org/docs/LanguageExtensions.html#checked-arithmetic-builtins
GCC and Clang have beautiful builtins that are being included in the C23 standard: checked arithmetic operations:
For fixed-size integer, these functions take a pointer to store the result of the operation, and will return a boolean indicating if there has been an overflow. In such a case, the pointer then stores the overflowed result.
Considering the volatile nature of C regarding type-safety, and UBs, I wish to bring only a subset of these operations to the GHC primops at first without generalising to every possible type of argument like GCC and Clang so kindly do. Only the specialisations on the following types would be brought:
- int
- long int
- long long int
- unsigned int
- unsigned long int
- unsigned long long int
The operations are addition, subtraction and multiplication.
My personal argument in favour is that they would be helpful in promoting user-level correctness when handling fixed-size integers. One particular use-case is reading port numbers (Word16) from external configuration. Silent overflowing does not inspire much trust. And it would certainly help with domain modelling in Haskell if we can bring tools to the user to help them represent their domain with the most precise types.
EDIT: After considering the argument of emulation, I believe it could be more flexible to emulate these builtins with the primops we have today.