Skip to content

Clearer and more efficient MulMayOflo

Currently the (IMHO confusingly-named) MulMayOflo machop is used by Integer multiplication to determine whether the result of a small Integer multiplication will overflow the word size. However, in order to compute whether this overflow will occur it is often necessary to perform the multiplication.

Conceptually, it seems clearer to instead have an operation like:

mulMaybe :: Int -> Int -> Maybe Int

where

  • mulMaybe x y = Just (x*y) if x*y certainly fits in Int, or
  • mulMaybe x y = Nothing otherwise

As a machop this would be:

mulMaybe# :: r -> r -> (# Bool#, r #)

where, e.g., mulMaybe# @Int16# x y would be:

  • (# 1#, x*y #) if the x*y product is guaranteed not to overflow Int16#
  • (# 0#, _ #) otherwise

In general, a backend may always conservatively return (# 0#, _ #).

This would allow sharing of the (often rather expensive) multiplication result and make the intended semantics of the operation a bit clearer, IMHO.

Edited by Ben Gamari
To upload designs, you'll need to enable LFS and have an admin enable hashed storage. More information