As mentioned a few times -ftrapv is broken in many cases it would be better if it become something like -fsanitize=undefined -fsanitize-undefined-trap-on-error.
Confirmed. In particular this would free the compiler from caring about -ftrapv when generating expressions on its own. It was suggested that this transform can be done at gimplification time using the IFN_{ADD,SUB,MUL}_OVERFLOW machinery (notably negate and division are missing here but easy to test for).
Note, -fsanitize=undefined -fsanitize-undefined-trap-on-error actually doesn't use IFN_{ADD,SUB,MUL}_OVERFLOW, those are used for the __builtin_*_overflow* builtins, but its own IFN_UBSAN_CHECK_{ADD,SUB,MUL} ones. Those are for the IL simpler than IFN_{ADD,SUB,MUL}_OVERFLOW, they just return their value instead of _Complex containing both the value and overflow flag - the abort operation (whether __builtin_trap () or some libubsan API call) is implicit in it. I think best would be to introduce for -ftrapv another set of ifns, and treat those mostly as IFN_UBSAN_CHECK_{ADD,SUB,MUL}, except that the abort operation would be always __builtin_trap regardless of -f{,no-}sanitize-undefined-trap-on-error and perhaps the expansion could at least for -Os or for longer sequences try to use the existing libgcc APIs when they are available. Negate is for ubsan handled as IFN_UBSAN_CHECK_SUB (0, x), yes, division would need a new ifn.
*** Bug 94934 has been marked as a duplicate of this bug. ***
the request for a division overflow function is PR 78473.