Hi! fold_read_from_constant_string and expand_expr_real_1 have code to optimize constant reads from string (tree vs. rtl). If the STRING_CST array type has zero low bound, index is fold converted to sizetype and so the compare_tree_int works fine, but if it has some other low bound, it calls size_diffop_loc and that function from 2 sizetype operands creates a ssizetype difference. expand_expr_real_1 then uses tree_fits_uhwi_p + compare_tree_int and so works fine, but fold-const.c only checked if index is INTEGER_CST and calls compare_tree_int, which means for negative index it will succeed and result in UB in the compiler.
This patch just follows what expand_expr_real_1 is doing. Bootstrapped/regtested on x86_64-linux and i686-linux, ok for trunk? 2021-02-22 Jakub Jelinek <ja...@redhat.com> PR tree-optimization/99204 * fold-const.c (fold_read_from_constant_string): Check that tree_fits_uhwi_p (index) rather than just that index is INTEGER_CST. * gfortran.dg/pr99204.f90: New test. --- gcc/fold-const.c.jj 2021-01-04 10:25:39.031231582 +0100 +++ gcc/fold-const.c 2021-02-22 19:46:57.167342075 +0100 @@ -15433,7 +15433,7 @@ fold_read_from_constant_string (tree exp if (string && TYPE_MODE (TREE_TYPE (exp)) == TYPE_MODE (TREE_TYPE (TREE_TYPE (string))) && TREE_CODE (string) == STRING_CST - && TREE_CODE (index) == INTEGER_CST + && tree_fits_uhwi_p (index) && compare_tree_int (index, TREE_STRING_LENGTH (string)) < 0 && is_int_mode (TYPE_MODE (TREE_TYPE (TREE_TYPE (string))), &char_mode) --- gcc/testsuite/gfortran.dg/pr99204.f90.jj 2021-02-22 19:52:55.749431186 +0100 +++ gcc/testsuite/gfortran.dg/pr99204.f90 2021-02-22 19:51:07.410612678 +0100 @@ -0,0 +1,10 @@ +! PR tree-optimization/99204 +! { dg-do compile } +! { dg-options "-O2 -w" } + +program pr99204 + character :: c + integer :: i = -12345678 + c = 'abc'(i:i) + print *, c +end Jakub