I noticed this bug a while ago on ppc64 and now I reproduced it even on x86_64 with -m32. The problem was that we were using add_optab even when dealing with MINUS_EXPR; we should use sub_optab instead.
Regtested on x86_64-linux (with both -m32/-m64), ok for trunk? 2013-12-14 Marek Polacek <pola...@redhat.com> PR sanitizer/59503 * internal-fn.c (ubsan_expand_si_overflow_addsub_check): Call expand_binop with correct optab depending on code. testsuite/ * c-c++-common/ubsan/pr59503.c: New test. --- gcc/internal-fn.c.mp 2013-12-14 00:43:47.621016850 +0100 +++ gcc/internal-fn.c 2013-12-14 01:25:37.274728223 +0100 @@ -214,14 +214,14 @@ ubsan_expand_si_overflow_addsub_check (t /* Compute the operation. On RTL level, the addition is always unsigned. */ - res = expand_binop (mode, add_optab, op0, op1, - NULL_RTX, false, OPTAB_LIB_WIDEN); + res = expand_binop (mode, code == PLUS_EXPR ? add_optab : sub_optab, + op0, op1, NULL_RTX, false, OPTAB_LIB_WIDEN); /* If the op1 is negative, we have to use a different check. */ emit_cmp_and_jump_insns (op1, const0_rtx, LT, NULL_RTX, mode, false, sub_check, PROB_EVEN); - /* Compare the result of the addition with one of the operands. */ + /* Compare the result of the operation with one of the operands. */ emit_cmp_and_jump_insns (res, op0, code == PLUS_EXPR ? GE : LE, NULL_RTX, mode, false, done_label, PROB_VERY_LIKELY); --- gcc/testsuite/c-c++-common/ubsan/pr59503.c.mp 2013-12-14 02:04:14.209620616 +0100 +++ gcc/testsuite/c-c++-common/ubsan/pr59503.c 2013-12-14 02:18:32.681699158 +0100 @@ -0,0 +1,14 @@ +/* { dg-do run } */ +/* { dg-options "-fsanitize=signed-integer-overflow" } */ +/* { dg-skip-if "" { *-*-* } { "-flto" } { "" } } */ + +int +main (void) +{ + long long int a = 14; + long int b = 9; + asm volatile ("" : "+r" (a), "+r" (b)); + if ((a - b) != 5) + __builtin_abort (); + return 0; +} Marek