strlen opt uses ao_ref_init_from_ptr_and_size to prepare alias queries to invalidate its knowledge about strings. It constrains the size using the number of known-nonzero chars and adds one for a terminating nul - without knowing whether such nul exists or even fits the object. The latter is now a problem since the oracle disambiguates an access of size two (as built so) against a store to a plain char variable (where a terminating nul does not fit). The fix is to instead increment max_size but leave size to the number of chars we know are accessed.
Bootstrap and regtest running on x86_64-unknown-linux-gnu. Richard. 2021-06-14 Richard Biener <rguent...@suse.de> PR tree-optimization/101031 * tree-ssa-strlen.c (maybe_invalidate): Increment max_size instead of size when accounting for a possibly string terminating nul. * gcc.dg/torture/pr101031.c: New testcase. --- gcc/testsuite/gcc.dg/torture/pr101031.c | 28 +++++++++++++++++++++++++ gcc/tree-ssa-strlen.c | 19 ++++++++++------- 2 files changed, 39 insertions(+), 8 deletions(-) create mode 100644 gcc/testsuite/gcc.dg/torture/pr101031.c diff --git a/gcc/testsuite/gcc.dg/torture/pr101031.c b/gcc/testsuite/gcc.dg/torture/pr101031.c new file mode 100644 index 00000000000..daf3bcf44eb --- /dev/null +++ b/gcc/testsuite/gcc.dg/torture/pr101031.c @@ -0,0 +1,28 @@ +/* { dg-do run } */ + +int a; +char b, e; +static char *c = &b; +static long d; +void f(void); +void __attribute__((noipa)) h() { + int g = 0; + for (; g < 2; ++g) { + d = *c; + *c = 1; + b = 0; + } + f(); +} +void __attribute__((noipa)) f() { + if (d++) + c = &e; + for (; a;) + ; +} +int main() { + h(); + if (b != 0) + __builtin_abort (); + return 0; +} diff --git a/gcc/tree-ssa-strlen.c b/gcc/tree-ssa-strlen.c index 423075b2bd1..6add8c99032 100644 --- a/gcc/tree-ssa-strlen.c +++ b/gcc/tree-ssa-strlen.c @@ -1284,16 +1284,19 @@ maybe_invalidate (gimple *stmt, bool zero_write = false) continue; ao_ref r; - tree size = NULL_TREE; - if (si->nonzero_chars) + tree size = si->nonzero_chars; + ao_ref_init_from_ptr_and_size (&r, si->ptr, size); + /* Include the terminating nul in the size of the string + to consider when determining possible clobber. But do not + add it to 'size' since we don't know whether it would + actually fit the allocated area. */ + if (known_size_p (r.size)) { - /* Include the terminating nul in the size of the string - to consider when determining possible clobber. */ - tree type = TREE_TYPE (si->nonzero_chars); - size = fold_build2 (PLUS_EXPR, type, si->nonzero_chars, - build_int_cst (type, 1)); + if (known_le (r.size, HOST_WIDE_INT_MAX - BITS_PER_UNIT)) + r.max_size += BITS_PER_UNIT; + else + r.max_size = -1; } - ao_ref_init_from_ptr_and_size (&r, si->ptr, size); if (stmt_may_clobber_ref_p_1 (stmt, &r)) { if (dump_file && (dump_flags & TDF_DETAILS)) -- 2.26.2