[Bug c++/92298] The expression X / X is simplified to 1 even when the variable X is 0

disquisitiones at gmail dot com gcc-bugzilla@gcc.gnu.org
Thu Oct 31 12:59:00 GMT 2019


https://gcc.gnu.org/bugzilla/show_bug.cgi?id=92298

Luca Rocca <disquisitiones at gmail dot com> changed:

           What    |Removed                     |Added
----------------------------------------------------------------------------
             Status|RESOLVED                    |UNCONFIRMED
         Resolution|INVALID                     |---

--- Comment #2 from Luca Rocca <disquisitiones at gmail dot com> ---
Division by 0 is always undefined, regardless of the numerator.
So, X / X should not be simplified if we cannot exclude that X = 0.
Then if X = 0 we should expect an exception triggered at runtime,
as we have for example for 1 / 0.

Consider the relevant section of the file gcc-9.2.0/gcc/match.pd:

/* X / X is one.  */
 (simplify
  (div @0 @0)
  /* But not for 0 / 0 so that we can get the proper warnings and errors.
     And not for _Fract types where we can't build 1.  */
  (if (!integer_zerop (@0) && !ALL_FRACT_MODE_P (TYPE_MODE (type)))
   { build_one_cst (type); }))

It seems that the intention is in fact to perform the simplification
except for the case 0 / 0, but for some reason this is not implemented
correctly.

Consider also for comparison the approach of gcc up to gcc-6.4.0,
reading this comment from the corresponding file gcc-6.4.0/gcc/match.pd:

/* Make sure to preserve divisions by zero.  This is the reason why
   we don't simplify x / x to 1 or 0 / x to 0.  */

For the same code, GCC up to 6.4.0 does not perform the simplification and when
X = 0 we have an exception raised at runtime as expected


More information about the Gcc-bugs mailing list