c++: treat NON_DEPENDENT_EXPR as not potentially constant [PR104507]
authorPatrick Palka <ppalka@redhat.com>
Wed, 16 Feb 2022 17:41:35 +0000 (12:41 -0500)
committerPatrick Palka <ppalka@redhat.com>
Wed, 16 Feb 2022 17:41:35 +0000 (12:41 -0500)
commitc19f317a78c0e4c1b51d0e5a8e4c0a3b985b7a8e
tree28c4b2f885959305bf8383c03e90ab6d23a1728e
parentf9c4917f01692a10f122f5ad56e559ba27751ace
c++: treat NON_DEPENDENT_EXPR as not potentially constant [PR104507]

Here we're crashing from potential_constant_expression because it tries
to perform trial evaluation of the first operand '(bool)__r' of the
conjunction (which is overall wrapped in a NON_DEPENDENT_EXPR), but
cxx_eval_constant_expression ICEs on unsupported trees (of which CAST_EXPR
is one).  The sequence of events is:

  1. build_non_dependent_expr for the array subscript yields
     NON_DEPENDENT_EXPR<<<(bool)__r && __s>>> ? 1 : 2
  2. cp_build_array_ref calls fold_non_dependent_expr on this subscript
     (after this point, processing_template_decl is cleared)
  3. during which, the COND_EXPR case of tsubst_copy_and_build calls
     fold_non_dependent_expr on the first operand
  4. during which, we crash from p_c_e_1 because it attempts trial
     evaluation of the CAST_EXPR '(bool)__r'.

Note that even if this crash didn't happen, fold_non_dependent_expr
from cp_build_array_ref would still ultimately be one big no-op here
since neither constexpr evaluation nor tsubst handle NON_DEPENDENT_EXPR.

In light of this and of the observation that we should never see
NON_DEPENDENT_EXPR in a context where a constant expression is needed
(it's used primarily in the build_x_* family of functions), it seems
futile for p_c_e_1 to ever return true for NON_DEPENDENT_EXPR.  And the
otherwise inconsistent handling of NON_DEPENDENT_EXPR between p_c_e_1,
cxx_evaluate_constexpr_expression and tsubst apparently leads to weird
bugs such as this one.

PR c++/104507

gcc/cp/ChangeLog:

* constexpr.cc (potential_constant_expression_1)
<case NON_DEPENDENT_EXPR>: Return false instead of recursing.
Assert tf_error isn't set.

gcc/testsuite/ChangeLog:

* g++.dg/template/non-dependent21.C: New test.
gcc/cp/constexpr.cc
gcc/testsuite/g++.dg/template/non-dependent21.C [new file with mode: 0644]