This is the mail archive of the
mailing list for the GCC project.
Division by INT64_MIN
- From: Matthew Fernandez <matthew dot fernandez at gmail dot com>
- To: gcc at gcc dot gnu dot org
- Date: Mon, 5 Oct 2015 13:10:57 +1100
- Subject: Division by INT64_MIN
- Authentication-results: sourceware.org; auth=none
Apologies in advance if this question is naÃve or misdirected.
tl;dr: Is dividing by INT64_MIN in C undefined behaviour?
In more detail... AIUI when the current target does not have native instructions for a given division or modulo
operation, GCC emits calls to software emulation provided by libgcc. For example, a signed 64-bit division on x86 is
emitted as a call to __divdi3. If the numerator or denominator are negative, __divdi3 negates them. If either of these
values is INT64_MIN, I believe this negation is undefined. Is this correct? If this is the case, then it seems code like
"INT64_MIN / INT64_MIN" which should be perfectly legal accidentally causes undefined behaviour via libgcc. In practice,
everything seems to work as expected, but it seems to me that the C code of __divdi3 should not be relying on these
negations working consistently.
This only occurred to me after being in a situation where I had to implement __divdi3 myself. Afterwards I looked at
libgcc's out of curiosity and was surprised to find it was much simpler than my attempt. Any clarification would be