In RISC-V, integer computational instructions do not cause hardware traps or exceptions on arithmetic overflow. When multiplying two 32-bit integers using the standard mul instruction from the "M" Standard Extension, the processor quietly ignores the overflow and simply returns the lower 32 bits of the mathematically true 64-bit product.
Because there are no condition codes or overflow flags in the base RISC-V architecture, you must manually check for overflow using software sequence branches.
Multiplying two 32-bit integers always yields a 64-bit result, which mathematically cannot overflow a 64-bit space. RISC-V handles this by providing separate instructions to capture either the lower or upper half of that 64-bit product:
To check if a 32-bit multiplication overflowed, you can use the mulh or mulhu instructions to examine whether the bits discarded by mul contain relevant data.
For unsigned multiplication, an overflow occurs if the upper 32 bits of the full 64-bit product are anything other than zero.
For signed multiplication, the upper 32 bits must be a valid sign extension of the lower 32 bits. This means if the result is positive, the upper bits must be all 0. If the result is negative, the upper bits must be all 1 (or -1 when viewed as a signed integer). Additionally, the sign of the upper bits must match the sign bit (bit 31) of the lower bits.
To detect a double-word (64-bit) integer multiplication overflow in RISC-V (RV64), you must use a widening multiplication approach by comparing the high-order bits (MULH/MULHU) with an arithmetic shift of the low-order result.
For signed 64-bit integers (a and b), multiplying them produces a 128-bit result split into low 64 bits (low) and high 64 bits (high). Overflow occurs if the high 64-bit word is not merely the sign-extension of the low 64-bit word.
For unsigned 64-bit integers, overflow occurs if any of the upper 64 bits in the 128-bit product are non-zero.