https://gcc.gnu.org/g:71655554ecf0de0abfa7b419317d55ab6bb94fa2
commit 71655554ecf0de0abfa7b419317d55ab6bb94fa2 Author: Alexandre Oliva <ol...@gnu.org> Date: Fri Jan 17 16:47:25 2025 -0300 [ifcombine] out-of-bounds bitfield refs can trap [PR118514] Diff: --- gcc/gimple-fold.cc | 2 ++ gcc/testsuite/gcc.dg/field-merge-23.c | 19 +++++++++++++++++++ gcc/tree-eh.cc | 28 +++++++++++++++++++++++++++- 3 files changed, 48 insertions(+), 1 deletion(-) diff --git a/gcc/gimple-fold.cc b/gcc/gimple-fold.cc index 3c971a29ef04..5f1d69c19fe4 100644 --- a/gcc/gimple-fold.cc +++ b/gcc/gimple-fold.cc @@ -7834,6 +7834,8 @@ make_bit_field_load (location_t loc, tree inner, tree orig_inner, tree type, if (!point) return ref; + gcc_checking_assert (gimple_could_trap_p (point) == tree_could_trap_p (ref)); + /* If we're remaking the same load, reuse the SSA NAME it is already loaded into. */ if (gimple_assign_load_p (point) diff --git a/gcc/testsuite/gcc.dg/field-merge-23.c b/gcc/testsuite/gcc.dg/field-merge-23.c new file mode 100644 index 000000000000..d60f76206ebe --- /dev/null +++ b/gcc/testsuite/gcc.dg/field-merge-23.c @@ -0,0 +1,19 @@ +/* { dg-do run } */ +/* { dg-options "-O" } */ + +/* PR tree-optimization/118514 */ + +/* Check that we don't pull optimized references that could trap out of + loops. */ + +int a, c = 1; +unsigned char b[1], d; +int main() { + while (a || !c) { + signed char e = b[1000000000]; + d = e < 0 || b[1000000000] > 1; + if (d) + __builtin_abort (); + } + return 0; +} diff --git a/gcc/tree-eh.cc b/gcc/tree-eh.cc index 1033b124e4df..57b14a606c12 100644 --- a/gcc/tree-eh.cc +++ b/gcc/tree-eh.cc @@ -2646,6 +2646,28 @@ range_in_array_bounds_p (tree ref) return true; } +/* Return true iff EXPR, a BIT_FIELD_REF, accesses a bit range that is known to + be in bounds for the referred operand type. */ + +static bool +bit_field_ref_in_bounds_p (tree expr) +{ + tree size_tree; + poly_uint64 size_max, min, wid, max; + + size_tree = TYPE_SIZE (TREE_TYPE (TREE_OPERAND (expr, 0))); + if (!size_tree || !poly_int_tree_p (size_tree, &size_max) + || !poly_int_tree_p (TREE_OPERAND (expr, 2), &min) + || !poly_int_tree_p (TREE_OPERAND (expr, 1), &wid)) + return false; + + max = min + wid; + if (known_lt (max, min) || maybe_le (size_max, max)) + return false; + + return true; +} + /* Return true if EXPR can trap, as in dereferencing an invalid pointer location or floating point arithmetic. C.f. the rtl version, may_trap_p. This routine expects only GIMPLE lhs or rhs input. */ @@ -2688,10 +2710,14 @@ tree_could_trap_p (tree expr) restart: switch (code) { + case BIT_FIELD_REF: + if (!bit_field_ref_in_bounds_p (expr)) + return true; + /* Fall through. */ + case COMPONENT_REF: case REALPART_EXPR: case IMAGPART_EXPR: - case BIT_FIELD_REF: case VIEW_CONVERT_EXPR: case WITH_SIZE_EXPR: expr = TREE_OPERAND (expr, 0);