Don't warn when alignment of global common data exceeds maximum alignment.
[official-gcc.git] / gcc / cp / constexpr.c
blobb9c006217be867d376f442f5aa36c5fdb0cbcfe8
1 /* Perform -*- C++ -*- constant expression evaluation, including calls to
2 constexpr functions. These routines are used both during actual parsing
3 and during the instantiation of template functions.
5 Copyright (C) 1998-2021 Free Software Foundation, Inc.
7 This file is part of GCC.
9 GCC is free software; you can redistribute it and/or modify it
10 under the terms of the GNU General Public License as published by
11 the Free Software Foundation; either version 3, or (at your option)
12 any later version.
14 GCC is distributed in the hope that it will be useful, but
15 WITHOUT ANY WARRANTY; without even the implied warranty of
16 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
17 General Public License for more details.
19 You should have received a copy of the GNU General Public License
20 along with GCC; see the file COPYING3. If not see
21 <http://www.gnu.org/licenses/>. */
23 #include "config.h"
24 #include "system.h"
25 #include "coretypes.h"
26 #include "cp-tree.h"
27 #include "varasm.h"
28 #include "c-family/c-objc.h"
29 #include "tree-iterator.h"
30 #include "gimplify.h"
31 #include "builtins.h"
32 #include "tree-inline.h"
33 #include "ubsan.h"
34 #include "gimple-fold.h"
35 #include "timevar.h"
36 #include "fold-const-call.h"
37 #include "stor-layout.h"
38 #include "cgraph.h"
40 static bool verify_constant (tree, bool, bool *, bool *);
41 #define VERIFY_CONSTANT(X) \
42 do { \
43 if (verify_constant ((X), ctx->quiet, non_constant_p, overflow_p)) \
44 return t; \
45 } while (0)
47 static HOST_WIDE_INT find_array_ctor_elt (tree ary, tree dindex,
48 bool insert = false);
49 static int array_index_cmp (tree key, tree index);
51 /* Returns true iff FUN is an instantiation of a constexpr function
52 template or a defaulted constexpr function. */
54 bool
55 is_instantiation_of_constexpr (tree fun)
57 return ((DECL_TEMPLOID_INSTANTIATION (fun)
58 && DECL_DECLARED_CONSTEXPR_P (DECL_TI_TEMPLATE (fun)))
59 || (DECL_DEFAULTED_FN (fun)
60 && DECL_DECLARED_CONSTEXPR_P (fun)));
63 /* Return true if T is a literal type. */
65 bool
66 literal_type_p (tree t)
68 if (SCALAR_TYPE_P (t)
69 || VECTOR_TYPE_P (t)
70 || TYPE_REF_P (t)
71 || (VOID_TYPE_P (t) && cxx_dialect >= cxx14))
72 return true;
73 if (CLASS_TYPE_P (t))
75 t = complete_type (t);
76 gcc_assert (COMPLETE_TYPE_P (t) || errorcount);
77 return CLASSTYPE_LITERAL_P (t);
79 if (TREE_CODE (t) == ARRAY_TYPE)
80 return literal_type_p (strip_array_types (t));
81 return false;
84 /* If DECL is a variable declared `constexpr', require its type
85 be literal. Return error_mark_node if we give an error, the
86 DECL otherwise. */
88 tree
89 ensure_literal_type_for_constexpr_object (tree decl)
91 tree type = TREE_TYPE (decl);
92 if (VAR_P (decl)
93 && (DECL_DECLARED_CONSTEXPR_P (decl)
94 || var_in_constexpr_fn (decl))
95 && !processing_template_decl)
97 tree stype = strip_array_types (type);
98 if (CLASS_TYPE_P (stype) && !COMPLETE_TYPE_P (complete_type (stype)))
99 /* Don't complain here, we'll complain about incompleteness
100 when we try to initialize the variable. */;
101 else if (!literal_type_p (type))
103 if (DECL_DECLARED_CONSTEXPR_P (decl))
105 auto_diagnostic_group d;
106 error_at (DECL_SOURCE_LOCATION (decl),
107 "the type %qT of %<constexpr%> variable %qD "
108 "is not literal", type, decl);
109 explain_non_literal_class (type);
110 decl = error_mark_node;
112 else
114 if (!is_instantiation_of_constexpr (current_function_decl))
116 auto_diagnostic_group d;
117 error_at (DECL_SOURCE_LOCATION (decl),
118 "variable %qD of non-literal type %qT in "
119 "%<constexpr%> function", decl, type);
120 explain_non_literal_class (type);
121 decl = error_mark_node;
123 cp_function_chain->invalid_constexpr = true;
126 else if (DECL_DECLARED_CONSTEXPR_P (decl)
127 && variably_modified_type_p (type, NULL_TREE))
129 error_at (DECL_SOURCE_LOCATION (decl),
130 "%<constexpr%> variable %qD has variably-modified "
131 "type %qT", decl, type);
132 decl = error_mark_node;
135 return decl;
138 struct constexpr_fundef_hasher : ggc_ptr_hash<constexpr_fundef>
140 static hashval_t hash (const constexpr_fundef *);
141 static bool equal (const constexpr_fundef *, const constexpr_fundef *);
144 /* This table holds all constexpr function definitions seen in
145 the current translation unit. */
147 static GTY (()) hash_table<constexpr_fundef_hasher> *constexpr_fundef_table;
149 /* Utility function used for managing the constexpr function table.
150 Return true if the entries pointed to by P and Q are for the
151 same constexpr function. */
153 inline bool
154 constexpr_fundef_hasher::equal (const constexpr_fundef *lhs,
155 const constexpr_fundef *rhs)
157 return lhs->decl == rhs->decl;
160 /* Utility function used for managing the constexpr function table.
161 Return a hash value for the entry pointed to by Q. */
163 inline hashval_t
164 constexpr_fundef_hasher::hash (const constexpr_fundef *fundef)
166 return DECL_UID (fundef->decl);
169 /* Return a previously saved definition of function FUN. */
171 constexpr_fundef *
172 retrieve_constexpr_fundef (tree fun)
174 if (constexpr_fundef_table == NULL)
175 return NULL;
177 constexpr_fundef fundef = { fun, NULL_TREE, NULL_TREE, NULL_TREE };
178 return constexpr_fundef_table->find (&fundef);
181 /* Check whether the parameter and return types of FUN are valid for a
182 constexpr function, and complain if COMPLAIN. */
184 bool
185 is_valid_constexpr_fn (tree fun, bool complain)
187 bool ret = true;
189 if (DECL_INHERITED_CTOR (fun)
190 && TREE_CODE (fun) == TEMPLATE_DECL)
192 ret = false;
193 if (complain)
194 error ("inherited constructor %qD is not %<constexpr%>",
195 DECL_INHERITED_CTOR (fun));
197 else
199 for (tree parm = FUNCTION_FIRST_USER_PARM (fun);
200 parm != NULL_TREE; parm = TREE_CHAIN (parm))
201 if (!literal_type_p (TREE_TYPE (parm)))
203 ret = false;
204 if (complain)
206 auto_diagnostic_group d;
207 error ("invalid type for parameter %d of %<constexpr%> "
208 "function %q+#D", DECL_PARM_INDEX (parm), fun);
209 explain_non_literal_class (TREE_TYPE (parm));
214 if (LAMBDA_TYPE_P (CP_DECL_CONTEXT (fun)) && cxx_dialect < cxx17)
216 ret = false;
217 if (complain)
218 inform (DECL_SOURCE_LOCATION (fun),
219 "lambdas are implicitly %<constexpr%> only in C++17 and later");
221 else if (!DECL_CONSTRUCTOR_P (fun))
223 tree rettype = TREE_TYPE (TREE_TYPE (fun));
224 if (!literal_type_p (rettype))
226 ret = false;
227 if (complain)
229 auto_diagnostic_group d;
230 error ("invalid return type %qT of %<constexpr%> function %q+D",
231 rettype, fun);
232 explain_non_literal_class (rettype);
236 /* C++14 DR 1684 removed this restriction. */
237 if (cxx_dialect < cxx14
238 && DECL_NONSTATIC_MEMBER_FUNCTION_P (fun)
239 && !CLASSTYPE_LITERAL_P (DECL_CONTEXT (fun)))
241 ret = false;
242 if (complain)
244 auto_diagnostic_group d;
245 if (pedwarn (DECL_SOURCE_LOCATION (fun), OPT_Wpedantic,
246 "enclosing class of %<constexpr%> non-static"
247 " member function %q+#D is not a literal type",
248 fun))
249 explain_non_literal_class (DECL_CONTEXT (fun));
253 else if (CLASSTYPE_VBASECLASSES (DECL_CONTEXT (fun)))
255 ret = false;
256 if (complain)
257 error ("%q#T has virtual base classes", DECL_CONTEXT (fun));
260 return ret;
263 /* Subroutine of build_data_member_initialization. MEMBER is a COMPONENT_REF
264 for a member of an anonymous aggregate, INIT is the initializer for that
265 member, and VEC_OUTER is the vector of constructor elements for the class
266 whose constructor we are processing. Add the initializer to the vector
267 and return true to indicate success. */
269 static bool
270 build_anon_member_initialization (tree member, tree init,
271 vec<constructor_elt, va_gc> **vec_outer)
273 /* MEMBER presents the relevant fields from the inside out, but we need
274 to build up the initializer from the outside in so that we can reuse
275 previously built CONSTRUCTORs if this is, say, the second field in an
276 anonymous struct. So we use a vec as a stack. */
277 auto_vec<tree, 2> fields;
280 fields.safe_push (TREE_OPERAND (member, 1));
281 member = TREE_OPERAND (member, 0);
283 while (ANON_AGGR_TYPE_P (TREE_TYPE (member))
284 && TREE_CODE (member) == COMPONENT_REF);
286 /* VEC has the constructor elements vector for the context of FIELD.
287 If FIELD is an anonymous aggregate, we will push inside it. */
288 vec<constructor_elt, va_gc> **vec = vec_outer;
289 tree field;
290 while (field = fields.pop(),
291 ANON_AGGR_TYPE_P (TREE_TYPE (field)))
293 tree ctor;
294 /* If there is already an outer constructor entry for the anonymous
295 aggregate FIELD, use it; otherwise, insert one. */
296 if (vec_safe_is_empty (*vec)
297 || (*vec)->last().index != field)
299 ctor = build_constructor (TREE_TYPE (field), NULL);
300 CONSTRUCTOR_APPEND_ELT (*vec, field, ctor);
302 else
303 ctor = (*vec)->last().value;
304 vec = &CONSTRUCTOR_ELTS (ctor);
307 /* Now we're at the innermost field, the one that isn't an anonymous
308 aggregate. Add its initializer to the CONSTRUCTOR and we're done. */
309 gcc_assert (fields.is_empty());
310 CONSTRUCTOR_APPEND_ELT (*vec, field, init);
312 return true;
315 /* Subroutine of build_constexpr_constructor_member_initializers.
316 The expression tree T represents a data member initialization
317 in a (constexpr) constructor definition. Build a pairing of
318 the data member with its initializer, and prepend that pair
319 to the existing initialization pair INITS. */
321 static bool
322 build_data_member_initialization (tree t, vec<constructor_elt, va_gc> **vec)
324 tree member, init;
325 if (TREE_CODE (t) == CLEANUP_POINT_EXPR)
326 t = TREE_OPERAND (t, 0);
327 if (TREE_CODE (t) == EXPR_STMT)
328 t = TREE_OPERAND (t, 0);
329 if (t == error_mark_node)
330 return false;
331 if (TREE_CODE (t) == STATEMENT_LIST)
333 for (tree stmt : tsi_range (t))
334 if (! build_data_member_initialization (stmt, vec))
335 return false;
336 return true;
338 if (TREE_CODE (t) == CLEANUP_STMT)
340 /* We can't see a CLEANUP_STMT in a constructor for a literal class,
341 but we can in a constexpr constructor for a non-literal class. Just
342 ignore it; either all the initialization will be constant, in which
343 case the cleanup can't run, or it can't be constexpr.
344 Still recurse into CLEANUP_BODY. */
345 return build_data_member_initialization (CLEANUP_BODY (t), vec);
347 if (TREE_CODE (t) == CONVERT_EXPR)
348 t = TREE_OPERAND (t, 0);
349 if (TREE_CODE (t) == INIT_EXPR
350 /* vptr initialization shows up as a MODIFY_EXPR. In C++14 we only
351 use what this function builds for cx_check_missing_mem_inits, and
352 assignment in the ctor body doesn't count. */
353 || (cxx_dialect < cxx14 && TREE_CODE (t) == MODIFY_EXPR))
355 member = TREE_OPERAND (t, 0);
356 init = break_out_target_exprs (TREE_OPERAND (t, 1));
358 else if (TREE_CODE (t) == CALL_EXPR)
360 tree fn = get_callee_fndecl (t);
361 if (!fn || !DECL_CONSTRUCTOR_P (fn))
362 /* We're only interested in calls to subobject constructors. */
363 return true;
364 member = CALL_EXPR_ARG (t, 0);
365 /* We don't use build_cplus_new here because it complains about
366 abstract bases. Leaving the call unwrapped means that it has the
367 wrong type, but cxx_eval_constant_expression doesn't care. */
368 init = break_out_target_exprs (t);
370 else if (TREE_CODE (t) == BIND_EXPR)
371 return build_data_member_initialization (BIND_EXPR_BODY (t), vec);
372 else
373 /* Don't add anything else to the CONSTRUCTOR. */
374 return true;
375 if (INDIRECT_REF_P (member))
376 member = TREE_OPERAND (member, 0);
377 if (TREE_CODE (member) == NOP_EXPR)
379 tree op = member;
380 STRIP_NOPS (op);
381 if (TREE_CODE (op) == ADDR_EXPR)
383 gcc_assert (same_type_ignoring_top_level_qualifiers_p
384 (TREE_TYPE (TREE_TYPE (op)),
385 TREE_TYPE (TREE_TYPE (member))));
386 /* Initializing a cv-qualified member; we need to look through
387 the const_cast. */
388 member = op;
390 else if (op == current_class_ptr
391 && (same_type_ignoring_top_level_qualifiers_p
392 (TREE_TYPE (TREE_TYPE (member)),
393 current_class_type)))
394 /* Delegating constructor. */
395 member = op;
396 else
398 /* This is an initializer for an empty base; keep it for now so
399 we can check it in cxx_eval_bare_aggregate. */
400 gcc_assert (is_empty_class (TREE_TYPE (TREE_TYPE (member))));
403 if (TREE_CODE (member) == ADDR_EXPR)
404 member = TREE_OPERAND (member, 0);
405 if (TREE_CODE (member) == COMPONENT_REF)
407 tree aggr = TREE_OPERAND (member, 0);
408 if (TREE_CODE (aggr) == VAR_DECL)
409 /* Initializing a local variable, don't add anything. */
410 return true;
411 if (TREE_CODE (aggr) != COMPONENT_REF)
412 /* Normal member initialization. */
413 member = TREE_OPERAND (member, 1);
414 else if (ANON_AGGR_TYPE_P (TREE_TYPE (aggr)))
415 /* Initializing a member of an anonymous union. */
416 return build_anon_member_initialization (member, init, vec);
417 else
418 /* We're initializing a vtable pointer in a base. Leave it as
419 COMPONENT_REF so we remember the path to get to the vfield. */
420 gcc_assert (TREE_TYPE (member) == vtbl_ptr_type_node);
423 /* Value-initialization can produce multiple initializers for the
424 same field; use the last one. */
425 if (!vec_safe_is_empty (*vec) && (*vec)->last().index == member)
426 (*vec)->last().value = init;
427 else
428 CONSTRUCTOR_APPEND_ELT (*vec, member, init);
429 return true;
432 /* Subroutine of check_constexpr_ctor_body_1 and constexpr_fn_retval.
433 In C++11 mode checks that the TYPE_DECLs in the BIND_EXPR_VARS of a
434 BIND_EXPR conform to 7.1.5/3/4 on typedef and alias declarations. */
436 static bool
437 check_constexpr_bind_expr_vars (tree t)
439 gcc_assert (TREE_CODE (t) == BIND_EXPR);
441 for (tree var = BIND_EXPR_VARS (t); var; var = DECL_CHAIN (var))
442 if (TREE_CODE (var) == TYPE_DECL
443 && DECL_IMPLICIT_TYPEDEF_P (var)
444 && !LAMBDA_TYPE_P (TREE_TYPE (var)))
445 return false;
446 return true;
449 /* Subroutine of check_constexpr_ctor_body. */
451 static bool
452 check_constexpr_ctor_body_1 (tree last, tree list)
454 switch (TREE_CODE (list))
456 case DECL_EXPR:
457 if (TREE_CODE (DECL_EXPR_DECL (list)) == USING_DECL
458 || TREE_CODE (DECL_EXPR_DECL (list)) == TYPE_DECL)
459 return true;
460 return false;
462 case CLEANUP_POINT_EXPR:
463 return check_constexpr_ctor_body (last, TREE_OPERAND (list, 0),
464 /*complain=*/false);
466 case BIND_EXPR:
467 if (!check_constexpr_bind_expr_vars (list)
468 || !check_constexpr_ctor_body (last, BIND_EXPR_BODY (list),
469 /*complain=*/false))
470 return false;
471 return true;
473 case USING_STMT:
474 case STATIC_ASSERT:
475 case DEBUG_BEGIN_STMT:
476 return true;
478 default:
479 return false;
483 /* Make sure that there are no statements after LAST in the constructor
484 body represented by LIST. */
486 bool
487 check_constexpr_ctor_body (tree last, tree list, bool complain)
489 /* C++14 doesn't require a constexpr ctor to have an empty body. */
490 if (cxx_dialect >= cxx14)
491 return true;
493 bool ok = true;
494 if (TREE_CODE (list) == STATEMENT_LIST)
496 tree_stmt_iterator i = tsi_last (list);
497 for (; !tsi_end_p (i); tsi_prev (&i))
499 tree t = tsi_stmt (i);
500 if (t == last)
501 break;
502 if (!check_constexpr_ctor_body_1 (last, t))
504 ok = false;
505 break;
509 else if (list != last
510 && !check_constexpr_ctor_body_1 (last, list))
511 ok = false;
512 if (!ok)
514 if (complain)
515 error ("%<constexpr%> constructor does not have empty body");
516 DECL_DECLARED_CONSTEXPR_P (current_function_decl) = false;
518 return ok;
521 /* V is a vector of constructor elements built up for the base and member
522 initializers of a constructor for TYPE. They need to be in increasing
523 offset order, which they might not be yet if TYPE has a primary base
524 which is not first in the base-clause or a vptr and at least one base
525 all of which are non-primary. */
527 static vec<constructor_elt, va_gc> *
528 sort_constexpr_mem_initializers (tree type, vec<constructor_elt, va_gc> *v)
530 tree pri = CLASSTYPE_PRIMARY_BINFO (type);
531 tree field_type;
532 unsigned i;
533 constructor_elt *ce;
535 if (pri)
536 field_type = BINFO_TYPE (pri);
537 else if (TYPE_CONTAINS_VPTR_P (type))
538 field_type = vtbl_ptr_type_node;
539 else
540 return v;
542 /* Find the element for the primary base or vptr and move it to the
543 beginning of the vec. */
544 for (i = 0; vec_safe_iterate (v, i, &ce); ++i)
545 if (TREE_TYPE (ce->index) == field_type)
546 break;
548 if (i > 0 && i < vec_safe_length (v))
550 vec<constructor_elt, va_gc> &vref = *v;
551 constructor_elt elt = vref[i];
552 for (; i > 0; --i)
553 vref[i] = vref[i-1];
554 vref[0] = elt;
557 return v;
560 /* Build compile-time evalable representations of member-initializer list
561 for a constexpr constructor. */
563 static tree
564 build_constexpr_constructor_member_initializers (tree type, tree body)
566 vec<constructor_elt, va_gc> *vec = NULL;
567 bool ok = true;
568 while (true)
569 switch (TREE_CODE (body))
571 case MUST_NOT_THROW_EXPR:
572 case EH_SPEC_BLOCK:
573 body = TREE_OPERAND (body, 0);
574 break;
576 case STATEMENT_LIST:
577 for (tree stmt : tsi_range (body))
579 body = stmt;
580 if (TREE_CODE (body) == BIND_EXPR)
581 break;
583 break;
585 case BIND_EXPR:
586 body = BIND_EXPR_BODY (body);
587 goto found;
589 default:
590 gcc_unreachable ();
592 found:
593 if (TREE_CODE (body) == TRY_BLOCK)
595 body = TREE_OPERAND (body, 0);
596 if (TREE_CODE (body) == BIND_EXPR)
597 body = BIND_EXPR_BODY (body);
599 if (TREE_CODE (body) == CLEANUP_POINT_EXPR)
601 body = TREE_OPERAND (body, 0);
602 if (TREE_CODE (body) == EXPR_STMT)
603 body = TREE_OPERAND (body, 0);
604 if (TREE_CODE (body) == INIT_EXPR
605 && (same_type_ignoring_top_level_qualifiers_p
606 (TREE_TYPE (TREE_OPERAND (body, 0)),
607 current_class_type)))
609 /* Trivial copy. */
610 return TREE_OPERAND (body, 1);
612 ok = build_data_member_initialization (body, &vec);
614 else if (TREE_CODE (body) == STATEMENT_LIST)
616 for (tree stmt : tsi_range (body))
618 ok = build_data_member_initialization (stmt, &vec);
619 if (!ok)
620 break;
623 else if (EXPR_P (body))
624 ok = build_data_member_initialization (body, &vec);
625 else
626 gcc_assert (errorcount > 0);
627 if (ok)
629 if (vec_safe_length (vec) > 0)
631 /* In a delegating constructor, return the target. */
632 constructor_elt *ce = &(*vec)[0];
633 if (ce->index == current_class_ptr)
635 body = ce->value;
636 vec_free (vec);
637 return body;
640 vec = sort_constexpr_mem_initializers (type, vec);
641 return build_constructor (type, vec);
643 else
644 return error_mark_node;
647 /* We have an expression tree T that represents a call, either CALL_EXPR
648 or AGGR_INIT_EXPR. If the call is lexically to a named function,
649 retrun the _DECL for that function. */
651 static tree
652 get_function_named_in_call (tree t)
654 tree fun = cp_get_callee (t);
655 if (fun && TREE_CODE (fun) == ADDR_EXPR
656 && TREE_CODE (TREE_OPERAND (fun, 0)) == FUNCTION_DECL)
657 fun = TREE_OPERAND (fun, 0);
658 return fun;
661 /* Subroutine of check_constexpr_fundef. BODY is the body of a function
662 declared to be constexpr, or a sub-statement thereof. Returns the
663 return value if suitable, error_mark_node for a statement not allowed in
664 a constexpr function, or NULL_TREE if no return value was found. */
666 tree
667 constexpr_fn_retval (tree body)
669 switch (TREE_CODE (body))
671 case STATEMENT_LIST:
673 tree expr = NULL_TREE;
674 for (tree stmt : tsi_range (body))
676 tree s = constexpr_fn_retval (stmt);
677 if (s == error_mark_node)
678 return error_mark_node;
679 else if (s == NULL_TREE)
680 /* Keep iterating. */;
681 else if (expr)
682 /* Multiple return statements. */
683 return error_mark_node;
684 else
685 expr = s;
687 return expr;
690 case RETURN_EXPR:
691 return break_out_target_exprs (TREE_OPERAND (body, 0));
693 case DECL_EXPR:
695 tree decl = DECL_EXPR_DECL (body);
696 if (TREE_CODE (decl) == USING_DECL
697 /* Accept __func__, __FUNCTION__, and __PRETTY_FUNCTION__. */
698 || DECL_ARTIFICIAL (decl))
699 return NULL_TREE;
700 return error_mark_node;
703 case CLEANUP_POINT_EXPR:
704 return constexpr_fn_retval (TREE_OPERAND (body, 0));
706 case BIND_EXPR:
707 if (!check_constexpr_bind_expr_vars (body))
708 return error_mark_node;
709 return constexpr_fn_retval (BIND_EXPR_BODY (body));
711 case USING_STMT:
712 case DEBUG_BEGIN_STMT:
713 return NULL_TREE;
715 case CALL_EXPR:
717 tree fun = get_function_named_in_call (body);
718 if (fun != NULL_TREE
719 && fndecl_built_in_p (fun, BUILT_IN_UNREACHABLE))
720 return NULL_TREE;
722 /* Fallthru. */
724 default:
725 return error_mark_node;
729 /* Subroutine of check_constexpr_fundef. BODY is the DECL_SAVED_TREE of
730 FUN; do the necessary transformations to turn it into a single expression
731 that we can store in the hash table. */
733 static tree
734 massage_constexpr_body (tree fun, tree body)
736 if (DECL_CONSTRUCTOR_P (fun))
737 body = build_constexpr_constructor_member_initializers
738 (DECL_CONTEXT (fun), body);
739 else if (cxx_dialect < cxx14)
741 if (TREE_CODE (body) == EH_SPEC_BLOCK)
742 body = EH_SPEC_STMTS (body);
743 if (TREE_CODE (body) == MUST_NOT_THROW_EXPR)
744 body = TREE_OPERAND (body, 0);
745 body = constexpr_fn_retval (body);
747 return body;
750 /* CTYPE is a type constructed from BODY. Return true if some
751 bases/fields are uninitialized, and complain if COMPLAIN. */
753 static bool
754 cx_check_missing_mem_inits (tree ctype, tree body, bool complain)
756 /* We allow uninitialized bases/fields in C++20. */
757 if (cxx_dialect >= cxx20)
758 return false;
760 unsigned nelts = 0;
762 if (body)
764 if (TREE_CODE (body) != CONSTRUCTOR)
765 return false;
766 nelts = CONSTRUCTOR_NELTS (body);
768 tree field = TYPE_FIELDS (ctype);
770 if (TREE_CODE (ctype) == UNION_TYPE)
772 if (nelts == 0 && next_initializable_field (field))
774 if (complain)
775 error ("%<constexpr%> constructor for union %qT must "
776 "initialize exactly one non-static data member", ctype);
777 return true;
779 return false;
782 /* Iterate over the CONSTRUCTOR, checking any missing fields don't
783 need an explicit initialization. */
784 bool bad = false;
785 for (unsigned i = 0; i <= nelts; ++i)
787 tree index = NULL_TREE;
788 if (i < nelts)
790 index = CONSTRUCTOR_ELT (body, i)->index;
791 /* Skip base and vtable inits. */
792 if (TREE_CODE (index) != FIELD_DECL
793 || DECL_ARTIFICIAL (index))
794 continue;
797 for (; field != index; field = DECL_CHAIN (field))
799 tree ftype;
800 if (TREE_CODE (field) != FIELD_DECL)
801 continue;
802 if (DECL_UNNAMED_BIT_FIELD (field))
803 continue;
804 if (DECL_ARTIFICIAL (field))
805 continue;
806 if (ANON_AGGR_TYPE_P (TREE_TYPE (field)))
808 /* Recurse to check the anonymous aggregate member. */
809 bad |= cx_check_missing_mem_inits
810 (TREE_TYPE (field), NULL_TREE, complain);
811 if (bad && !complain)
812 return true;
813 continue;
815 ftype = TREE_TYPE (field);
816 if (!ftype || !TYPE_P (ftype) || !COMPLETE_TYPE_P (ftype))
817 /* A flexible array can't be intialized here, so don't complain
818 that it isn't. */
819 continue;
820 if (is_empty_field (field))
821 /* An empty field doesn't need an initializer. */
822 continue;
823 ftype = strip_array_types (ftype);
824 if (type_has_constexpr_default_constructor (ftype))
826 /* It's OK to skip a member with a trivial constexpr ctor.
827 A constexpr ctor that isn't trivial should have been
828 added in by now. */
829 gcc_checking_assert (!TYPE_HAS_COMPLEX_DFLT (ftype)
830 || errorcount != 0);
831 continue;
833 if (!complain)
834 return true;
835 auto_diagnostic_group d;
836 error ("member %qD must be initialized by mem-initializer "
837 "in %<constexpr%> constructor", field);
838 inform (DECL_SOURCE_LOCATION (field), "declared here");
839 bad = true;
841 if (field == NULL_TREE)
842 break;
844 if (ANON_AGGR_TYPE_P (TREE_TYPE (index)))
846 /* Check the anonymous aggregate initializer is valid. */
847 bad |= cx_check_missing_mem_inits
848 (TREE_TYPE (index), CONSTRUCTOR_ELT (body, i)->value, complain);
849 if (bad && !complain)
850 return true;
852 field = DECL_CHAIN (field);
855 return bad;
858 /* We are processing the definition of the constexpr function FUN.
859 Check that its body fulfills the apropriate requirements and
860 enter it in the constexpr function definition table. */
862 void
863 maybe_save_constexpr_fundef (tree fun)
865 if (processing_template_decl
866 || !DECL_DECLARED_CONSTEXPR_P (fun)
867 || cp_function_chain->invalid_constexpr
868 || DECL_CLONED_FUNCTION_P (fun))
869 return;
871 if (!is_valid_constexpr_fn (fun, !DECL_GENERATED_P (fun)))
872 return;
874 tree massaged = massage_constexpr_body (fun, DECL_SAVED_TREE (fun));
875 if (massaged == NULL_TREE || massaged == error_mark_node)
877 if (!DECL_CONSTRUCTOR_P (fun))
878 error ("body of %<constexpr%> function %qD not a return-statement",
879 fun);
880 return;
883 bool potential = potential_rvalue_constant_expression (massaged);
884 if (!potential && !DECL_GENERATED_P (fun))
885 require_potential_rvalue_constant_expression (massaged);
887 if (DECL_CONSTRUCTOR_P (fun)
888 && cx_check_missing_mem_inits (DECL_CONTEXT (fun),
889 massaged, !DECL_GENERATED_P (fun)))
890 potential = false;
892 if (!potential && !DECL_GENERATED_P (fun))
893 return;
895 constexpr_fundef entry = {fun, NULL_TREE, NULL_TREE, NULL_TREE};
896 bool clear_ctx = false;
897 if (DECL_RESULT (fun) && DECL_CONTEXT (DECL_RESULT (fun)) == NULL_TREE)
899 clear_ctx = true;
900 DECL_CONTEXT (DECL_RESULT (fun)) = fun;
902 tree saved_fn = current_function_decl;
903 current_function_decl = fun;
904 entry.body = copy_fn (entry.decl, entry.parms, entry.result);
905 current_function_decl = saved_fn;
906 if (clear_ctx)
907 DECL_CONTEXT (DECL_RESULT (entry.decl)) = NULL_TREE;
908 if (!potential)
909 /* For a template instantiation, we want to remember the pre-generic body
910 for explain_invalid_constexpr_fn, but do tell cxx_eval_call_expression
911 that it doesn't need to bother trying to expand the function. */
912 entry.result = error_mark_node;
914 register_constexpr_fundef (entry);
917 /* BODY is a validated and massaged definition of a constexpr
918 function. Register it in the hash table. */
920 void
921 register_constexpr_fundef (const constexpr_fundef &value)
923 /* Create the constexpr function table if necessary. */
924 if (constexpr_fundef_table == NULL)
925 constexpr_fundef_table
926 = hash_table<constexpr_fundef_hasher>::create_ggc (101);
928 constexpr_fundef **slot = constexpr_fundef_table->find_slot
929 (const_cast<constexpr_fundef *> (&value), INSERT);
931 gcc_assert (*slot == NULL);
932 *slot = ggc_alloc<constexpr_fundef> ();
933 **slot = value;
936 /* FUN is a non-constexpr function called in a context that requires a
937 constant expression. If it comes from a constexpr template, explain why
938 the instantiation isn't constexpr. */
940 void
941 explain_invalid_constexpr_fn (tree fun)
943 static hash_set<tree> *diagnosed;
944 tree body;
945 location_t save_loc;
946 /* Only diagnose defaulted functions, lambdas, or instantiations. */
947 if (!DECL_DEFAULTED_FN (fun)
948 && !LAMBDA_TYPE_P (CP_DECL_CONTEXT (fun))
949 && !is_instantiation_of_constexpr (fun))
951 inform (DECL_SOURCE_LOCATION (fun), "%qD declared here", fun);
952 return;
954 if (diagnosed == NULL)
955 diagnosed = new hash_set<tree>;
956 if (diagnosed->add (fun))
957 /* Already explained. */
958 return;
960 save_loc = input_location;
961 if (!lambda_static_thunk_p (fun))
963 /* Diagnostics should completely ignore the static thunk, so leave
964 input_location set to our caller's location. */
965 input_location = DECL_SOURCE_LOCATION (fun);
966 inform (input_location,
967 "%qD is not usable as a %<constexpr%> function because:", fun);
969 /* First check the declaration. */
970 if (is_valid_constexpr_fn (fun, true))
972 /* Then if it's OK, the body. */
973 if (!DECL_DECLARED_CONSTEXPR_P (fun)
974 && DECL_DEFAULTED_FN (fun))
975 explain_implicit_non_constexpr (fun);
976 else
978 if (constexpr_fundef *fd = retrieve_constexpr_fundef (fun))
979 body = fd->body;
980 else
981 body = DECL_SAVED_TREE (fun);
982 body = massage_constexpr_body (fun, body);
983 require_potential_rvalue_constant_expression (body);
984 if (DECL_CONSTRUCTOR_P (fun))
985 cx_check_missing_mem_inits (DECL_CONTEXT (fun), body, true);
988 input_location = save_loc;
991 /* Objects of this type represent calls to constexpr functions
992 along with the bindings of parameters to their arguments, for
993 the purpose of compile time evaluation. */
995 struct GTY((for_user)) constexpr_call {
996 /* Description of the constexpr function definition. */
997 constexpr_fundef *fundef;
998 /* Parameter bindings environment. A TREE_VEC of arguments. */
999 tree bindings;
1000 /* Result of the call.
1001 NULL means the call is being evaluated.
1002 error_mark_node means that the evaluation was erroneous;
1003 otherwise, the actuall value of the call. */
1004 tree result;
1005 /* The hash of this call; we remember it here to avoid having to
1006 recalculate it when expanding the hash table. */
1007 hashval_t hash;
1008 /* Whether __builtin_is_constant_evaluated() should evaluate to true. */
1009 bool manifestly_const_eval;
1012 struct constexpr_call_hasher : ggc_ptr_hash<constexpr_call>
1014 static hashval_t hash (constexpr_call *);
1015 static bool equal (constexpr_call *, constexpr_call *);
1018 enum constexpr_switch_state {
1019 /* Used when processing a switch for the first time by cxx_eval_switch_expr
1020 and default: label for that switch has not been seen yet. */
1021 css_default_not_seen,
1022 /* Used when processing a switch for the first time by cxx_eval_switch_expr
1023 and default: label for that switch has been seen already. */
1024 css_default_seen,
1025 /* Used when processing a switch for the second time by
1026 cxx_eval_switch_expr, where default: label should match. */
1027 css_default_processing
1030 /* The constexpr expansion context part which needs one instance per
1031 cxx_eval_outermost_constant_expr invocation. VALUES is a map of values of
1032 variables initialized within the expression. */
1034 struct constexpr_global_ctx {
1035 /* Values for any temporaries or local variables within the
1036 constant-expression. */
1037 hash_map<tree,tree> values;
1038 /* Number of cxx_eval_constant_expression calls (except skipped ones,
1039 on simple constants or location wrappers) encountered during current
1040 cxx_eval_outermost_constant_expr call. */
1041 HOST_WIDE_INT constexpr_ops_count;
1042 /* Heap VAR_DECLs created during the evaluation of the outermost constant
1043 expression. */
1044 auto_vec<tree, 16> heap_vars;
1045 /* Cleanups that need to be evaluated at the end of CLEANUP_POINT_EXPR. */
1046 vec<tree> *cleanups;
1047 /* Number of heap VAR_DECL deallocations. */
1048 unsigned heap_dealloc_count;
1049 /* Constructor. */
1050 constexpr_global_ctx ()
1051 : constexpr_ops_count (0), cleanups (NULL), heap_dealloc_count (0) {}
1054 /* The constexpr expansion context. CALL is the current function
1055 expansion, CTOR is the current aggregate initializer, OBJECT is the
1056 object being initialized by CTOR, either a VAR_DECL or a _REF. */
1058 struct constexpr_ctx {
1059 /* The part of the context that needs to be unique to the whole
1060 cxx_eval_outermost_constant_expr invocation. */
1061 constexpr_global_ctx *global;
1062 /* The innermost call we're evaluating. */
1063 constexpr_call *call;
1064 /* SAVE_EXPRs and TARGET_EXPR_SLOT vars of TARGET_EXPRs that we've seen
1065 within the current LOOP_EXPR. NULL if we aren't inside a loop. */
1066 vec<tree> *save_exprs;
1067 /* The CONSTRUCTOR we're currently building up for an aggregate
1068 initializer. */
1069 tree ctor;
1070 /* The object we're building the CONSTRUCTOR for. */
1071 tree object;
1072 /* If inside SWITCH_EXPR. */
1073 constexpr_switch_state *css_state;
1074 /* The aggregate initialization context inside which this one is nested. This
1075 is used by lookup_placeholder to resolve PLACEHOLDER_EXPRs. */
1076 const constexpr_ctx *parent;
1078 /* Whether we should error on a non-constant expression or fail quietly.
1079 This flag needs to be here, but some of the others could move to global
1080 if they get larger than a word. */
1081 bool quiet;
1082 /* Whether we are strictly conforming to constant expression rules or
1083 trying harder to get a constant value. */
1084 bool strict;
1085 /* Whether __builtin_is_constant_evaluated () should be true. */
1086 bool manifestly_const_eval;
1089 /* This internal flag controls whether we should avoid doing anything during
1090 constexpr evaluation that would cause extra DECL_UID generation, such as
1091 template instantiation and function body copying. */
1093 static bool uid_sensitive_constexpr_evaluation_value;
1095 /* An internal counter that keeps track of the number of times
1096 uid_sensitive_constexpr_evaluation_p returned true. */
1098 static unsigned uid_sensitive_constexpr_evaluation_true_counter;
1100 /* The accessor for uid_sensitive_constexpr_evaluation_value which also
1101 increments the corresponding counter. */
1103 static bool
1104 uid_sensitive_constexpr_evaluation_p ()
1106 if (uid_sensitive_constexpr_evaluation_value)
1108 ++uid_sensitive_constexpr_evaluation_true_counter;
1109 return true;
1111 else
1112 return false;
1115 /* The default constructor for uid_sensitive_constexpr_evaluation_sentinel
1116 enables the internal flag for uid_sensitive_constexpr_evaluation_p
1117 during the lifetime of the sentinel object. Upon its destruction, the
1118 previous value of uid_sensitive_constexpr_evaluation_p is restored. */
1120 uid_sensitive_constexpr_evaluation_sentinel
1121 ::uid_sensitive_constexpr_evaluation_sentinel ()
1122 : ovr (uid_sensitive_constexpr_evaluation_value, true)
1126 /* The default constructor for uid_sensitive_constexpr_evaluation_checker
1127 records the current number of times that uid_sensitive_constexpr_evaluation_p
1128 has been called and returned true. */
1130 uid_sensitive_constexpr_evaluation_checker
1131 ::uid_sensitive_constexpr_evaluation_checker ()
1132 : saved_counter (uid_sensitive_constexpr_evaluation_true_counter)
1136 /* Returns true iff uid_sensitive_constexpr_evaluation_p is true, and
1137 some constexpr evaluation was restricted due to u_s_c_e_p being called
1138 and returning true during the lifetime of this checker object. */
1140 bool
1141 uid_sensitive_constexpr_evaluation_checker::evaluation_restricted_p () const
1143 return (uid_sensitive_constexpr_evaluation_value
1144 && saved_counter != uid_sensitive_constexpr_evaluation_true_counter);
1148 /* A table of all constexpr calls that have been evaluated by the
1149 compiler in this translation unit. */
1151 static GTY (()) hash_table<constexpr_call_hasher> *constexpr_call_table;
1153 static tree cxx_eval_constant_expression (const constexpr_ctx *, tree,
1154 bool, bool *, bool *, tree * = NULL);
1156 /* Compute a hash value for a constexpr call representation. */
1158 inline hashval_t
1159 constexpr_call_hasher::hash (constexpr_call *info)
1161 return info->hash;
1164 /* Return true if the objects pointed to by P and Q represent calls
1165 to the same constexpr function with the same arguments.
1166 Otherwise, return false. */
1168 bool
1169 constexpr_call_hasher::equal (constexpr_call *lhs, constexpr_call *rhs)
1171 if (lhs == rhs)
1172 return true;
1173 if (lhs->hash != rhs->hash)
1174 return false;
1175 if (lhs->manifestly_const_eval != rhs->manifestly_const_eval)
1176 return false;
1177 if (!constexpr_fundef_hasher::equal (lhs->fundef, rhs->fundef))
1178 return false;
1179 return cp_tree_equal (lhs->bindings, rhs->bindings);
1182 /* Initialize the constexpr call table, if needed. */
1184 static void
1185 maybe_initialize_constexpr_call_table (void)
1187 if (constexpr_call_table == NULL)
1188 constexpr_call_table = hash_table<constexpr_call_hasher>::create_ggc (101);
1191 /* During constexpr CALL_EXPR evaluation, to avoid issues with sharing when
1192 a function happens to get called recursively, we unshare the callee
1193 function's body and evaluate this unshared copy instead of evaluating the
1194 original body.
1196 FUNDEF_COPIES_TABLE is a per-function freelist of these unshared function
1197 copies. The underlying data structure of FUNDEF_COPIES_TABLE is a hash_map
1198 that's keyed off of the original FUNCTION_DECL and whose value is a
1199 TREE_LIST of this function's unused copies awaiting reuse.
1201 This is not GC-deletable to avoid GC affecting UID generation. */
1203 static GTY(()) decl_tree_map *fundef_copies_table;
1205 /* Reuse a copy or create a new unshared copy of the function FUN.
1206 Return this copy. We use a TREE_LIST whose PURPOSE is body, VALUE
1207 is parms, TYPE is result. */
1209 static tree
1210 get_fundef_copy (constexpr_fundef *fundef)
1212 tree copy;
1213 bool existed;
1214 tree *slot = &(hash_map_safe_get_or_insert<hm_ggc>
1215 (fundef_copies_table, fundef->decl, &existed, 127));
1217 if (!existed)
1219 /* There is no cached function available, or in use. We can use
1220 the function directly. That the slot is now created records
1221 that this function is now in use. */
1222 copy = build_tree_list (fundef->body, fundef->parms);
1223 TREE_TYPE (copy) = fundef->result;
1225 else if (*slot == NULL_TREE)
1227 if (uid_sensitive_constexpr_evaluation_p ())
1228 return NULL_TREE;
1230 /* We've already used the function itself, so make a copy. */
1231 copy = build_tree_list (NULL, NULL);
1232 tree saved_body = DECL_SAVED_TREE (fundef->decl);
1233 tree saved_parms = DECL_ARGUMENTS (fundef->decl);
1234 tree saved_result = DECL_RESULT (fundef->decl);
1235 tree saved_fn = current_function_decl;
1236 DECL_SAVED_TREE (fundef->decl) = fundef->body;
1237 DECL_ARGUMENTS (fundef->decl) = fundef->parms;
1238 DECL_RESULT (fundef->decl) = fundef->result;
1239 current_function_decl = fundef->decl;
1240 TREE_PURPOSE (copy) = copy_fn (fundef->decl, TREE_VALUE (copy),
1241 TREE_TYPE (copy));
1242 current_function_decl = saved_fn;
1243 DECL_RESULT (fundef->decl) = saved_result;
1244 DECL_ARGUMENTS (fundef->decl) = saved_parms;
1245 DECL_SAVED_TREE (fundef->decl) = saved_body;
1247 else
1249 /* We have a cached function available. */
1250 copy = *slot;
1251 *slot = TREE_CHAIN (copy);
1254 return copy;
1257 /* Save the copy COPY of function FUN for later reuse by
1258 get_fundef_copy(). By construction, there will always be an entry
1259 to find. */
1261 static void
1262 save_fundef_copy (tree fun, tree copy)
1264 tree *slot = fundef_copies_table->get (fun);
1265 TREE_CHAIN (copy) = *slot;
1266 *slot = copy;
1269 /* We have an expression tree T that represents a call, either CALL_EXPR
1270 or AGGR_INIT_EXPR. Return the Nth argument. */
1272 static inline tree
1273 get_nth_callarg (tree t, int n)
1275 switch (TREE_CODE (t))
1277 case CALL_EXPR:
1278 return CALL_EXPR_ARG (t, n);
1280 case AGGR_INIT_EXPR:
1281 return AGGR_INIT_EXPR_ARG (t, n);
1283 default:
1284 gcc_unreachable ();
1285 return NULL;
1289 /* Attempt to evaluate T which represents a call to a builtin function.
1290 We assume here that all builtin functions evaluate to scalar types
1291 represented by _CST nodes. */
1293 static tree
1294 cxx_eval_builtin_function_call (const constexpr_ctx *ctx, tree t, tree fun,
1295 bool lval,
1296 bool *non_constant_p, bool *overflow_p)
1298 const int nargs = call_expr_nargs (t);
1299 tree *args = (tree *) alloca (nargs * sizeof (tree));
1300 tree new_call;
1301 int i;
1303 /* Don't fold __builtin_constant_p within a constexpr function. */
1304 bool bi_const_p = DECL_IS_BUILTIN_CONSTANT_P (fun);
1306 /* If we aren't requiring a constant expression, defer __builtin_constant_p
1307 in a constexpr function until we have values for the parameters. */
1308 if (bi_const_p
1309 && !ctx->manifestly_const_eval
1310 && current_function_decl
1311 && DECL_DECLARED_CONSTEXPR_P (current_function_decl))
1313 *non_constant_p = true;
1314 return t;
1317 /* For __builtin_is_constant_evaluated, defer it if not
1318 ctx->manifestly_const_eval (as sometimes we try to constant evaluate
1319 without manifestly_const_eval even expressions or parts thereof which
1320 will later be manifestly const_eval evaluated), otherwise fold it to
1321 true. */
1322 if (fndecl_built_in_p (fun, CP_BUILT_IN_IS_CONSTANT_EVALUATED,
1323 BUILT_IN_FRONTEND))
1325 if (!ctx->manifestly_const_eval)
1327 *non_constant_p = true;
1328 return t;
1330 return boolean_true_node;
1333 if (fndecl_built_in_p (fun, CP_BUILT_IN_SOURCE_LOCATION, BUILT_IN_FRONTEND))
1335 temp_override<tree> ovr (current_function_decl);
1336 if (ctx->call && ctx->call->fundef)
1337 current_function_decl = ctx->call->fundef->decl;
1338 return fold_builtin_source_location (EXPR_LOCATION (t));
1341 int strops = 0;
1342 int strret = 0;
1343 if (fndecl_built_in_p (fun, BUILT_IN_NORMAL))
1344 switch (DECL_FUNCTION_CODE (fun))
1346 case BUILT_IN_STRLEN:
1347 case BUILT_IN_STRNLEN:
1348 strops = 1;
1349 break;
1350 case BUILT_IN_MEMCHR:
1351 case BUILT_IN_STRCHR:
1352 case BUILT_IN_STRRCHR:
1353 strops = 1;
1354 strret = 1;
1355 break;
1356 case BUILT_IN_MEMCMP:
1357 case BUILT_IN_STRCMP:
1358 strops = 2;
1359 break;
1360 case BUILT_IN_STRSTR:
1361 strops = 2;
1362 strret = 1;
1363 break;
1364 case BUILT_IN_ASAN_POINTER_COMPARE:
1365 case BUILT_IN_ASAN_POINTER_SUBTRACT:
1366 /* These builtins shall be ignored during constant expression
1367 evaluation. */
1368 return void_node;
1369 default:
1370 break;
1373 /* Be permissive for arguments to built-ins; __builtin_constant_p should
1374 return constant false for a non-constant argument. */
1375 constexpr_ctx new_ctx = *ctx;
1376 new_ctx.quiet = true;
1377 for (i = 0; i < nargs; ++i)
1379 tree arg = CALL_EXPR_ARG (t, i);
1380 tree oarg = arg;
1382 /* To handle string built-ins we need to pass ADDR_EXPR<STRING_CST> since
1383 expand_builtin doesn't know how to look in the values table. */
1384 bool strop = i < strops;
1385 if (strop)
1387 STRIP_NOPS (arg);
1388 if (TREE_CODE (arg) == ADDR_EXPR)
1389 arg = TREE_OPERAND (arg, 0);
1390 else
1391 strop = false;
1394 /* If builtin_valid_in_constant_expr_p is true,
1395 potential_constant_expression_1 has not recursed into the arguments
1396 of the builtin, verify it here. */
1397 if (!builtin_valid_in_constant_expr_p (fun)
1398 || potential_constant_expression (arg))
1400 bool dummy1 = false, dummy2 = false;
1401 arg = cxx_eval_constant_expression (&new_ctx, arg, false,
1402 &dummy1, &dummy2);
1405 if (bi_const_p)
1406 /* For __builtin_constant_p, fold all expressions with constant values
1407 even if they aren't C++ constant-expressions. */
1408 arg = cp_fold_rvalue (arg);
1409 else if (strop)
1411 if (TREE_CODE (arg) == CONSTRUCTOR)
1412 arg = braced_lists_to_strings (TREE_TYPE (arg), arg);
1413 if (TREE_CODE (arg) == STRING_CST)
1414 arg = build_address (arg);
1415 else
1416 arg = oarg;
1419 args[i] = arg;
1422 bool save_ffbcp = force_folding_builtin_constant_p;
1423 force_folding_builtin_constant_p |= ctx->manifestly_const_eval;
1424 tree save_cur_fn = current_function_decl;
1425 /* Return name of ctx->call->fundef->decl for __builtin_FUNCTION (). */
1426 if (fndecl_built_in_p (fun, BUILT_IN_FUNCTION)
1427 && ctx->call
1428 && ctx->call->fundef)
1429 current_function_decl = ctx->call->fundef->decl;
1430 if (fndecl_built_in_p (fun,
1431 CP_BUILT_IN_IS_POINTER_INTERCONVERTIBLE_WITH_CLASS,
1432 BUILT_IN_FRONTEND))
1434 location_t loc = EXPR_LOCATION (t);
1435 if (nargs >= 1)
1436 VERIFY_CONSTANT (args[0]);
1437 new_call
1438 = fold_builtin_is_pointer_inverconvertible_with_class (loc, nargs,
1439 args);
1441 else if (fndecl_built_in_p (fun,
1442 CP_BUILT_IN_IS_CORRESPONDING_MEMBER,
1443 BUILT_IN_FRONTEND))
1445 location_t loc = EXPR_LOCATION (t);
1446 if (nargs >= 2)
1448 VERIFY_CONSTANT (args[0]);
1449 VERIFY_CONSTANT (args[1]);
1451 new_call = fold_builtin_is_corresponding_member (loc, nargs, args);
1453 else
1454 new_call = fold_builtin_call_array (EXPR_LOCATION (t), TREE_TYPE (t),
1455 CALL_EXPR_FN (t), nargs, args);
1456 current_function_decl = save_cur_fn;
1457 force_folding_builtin_constant_p = save_ffbcp;
1458 if (new_call == NULL)
1460 if (!*non_constant_p && !ctx->quiet)
1462 /* Do not allow__builtin_unreachable in constexpr function.
1463 The __builtin_unreachable call with BUILTINS_LOCATION
1464 comes from cp_maybe_instrument_return. */
1465 if (fndecl_built_in_p (fun, BUILT_IN_UNREACHABLE)
1466 && EXPR_LOCATION (t) == BUILTINS_LOCATION)
1467 error ("%<constexpr%> call flows off the end of the function");
1468 else
1470 new_call = build_call_array_loc (EXPR_LOCATION (t), TREE_TYPE (t),
1471 CALL_EXPR_FN (t), nargs, args);
1472 error ("%q+E is not a constant expression", new_call);
1475 *non_constant_p = true;
1476 return t;
1479 if (!potential_constant_expression (new_call))
1481 if (!*non_constant_p && !ctx->quiet)
1482 error ("%q+E is not a constant expression", new_call);
1483 *non_constant_p = true;
1484 return t;
1487 if (strret)
1489 /* memchr returns a pointer into the first argument, but we replaced the
1490 argument above with a STRING_CST; put it back it now. */
1491 tree op = CALL_EXPR_ARG (t, strret-1);
1492 STRIP_NOPS (new_call);
1493 if (TREE_CODE (new_call) == POINTER_PLUS_EXPR)
1494 TREE_OPERAND (new_call, 0) = op;
1495 else if (TREE_CODE (new_call) == ADDR_EXPR)
1496 new_call = op;
1499 return cxx_eval_constant_expression (&new_ctx, new_call, lval,
1500 non_constant_p, overflow_p);
1503 /* TEMP is the constant value of a temporary object of type TYPE. Adjust
1504 the type of the value to match. */
1506 static tree
1507 adjust_temp_type (tree type, tree temp)
1509 if (same_type_p (TREE_TYPE (temp), type))
1510 return temp;
1511 /* Avoid wrapping an aggregate value in a NOP_EXPR. */
1512 if (TREE_CODE (temp) == CONSTRUCTOR)
1514 /* build_constructor wouldn't retain various CONSTRUCTOR flags. */
1515 tree t = copy_node (temp);
1516 TREE_TYPE (t) = type;
1517 return t;
1519 if (TREE_CODE (temp) == EMPTY_CLASS_EXPR)
1520 return build0 (EMPTY_CLASS_EXPR, type);
1521 gcc_assert (scalarish_type_p (type));
1522 /* Now we know we're dealing with a scalar, and a prvalue of non-class
1523 type is cv-unqualified. */
1524 return cp_fold_convert (cv_unqualified (type), temp);
1527 /* If T is a CONSTRUCTOR, return an unshared copy of T and any
1528 sub-CONSTRUCTORs. Otherwise return T.
1530 We use this whenever we initialize an object as a whole, whether it's a
1531 parameter, a local variable, or a subobject, so that subsequent
1532 modifications don't affect other places where it was used. */
1534 tree
1535 unshare_constructor (tree t MEM_STAT_DECL)
1537 if (!t || TREE_CODE (t) != CONSTRUCTOR)
1538 return t;
1539 auto_vec <tree*, 4> ptrs;
1540 ptrs.safe_push (&t);
1541 while (!ptrs.is_empty ())
1543 tree *p = ptrs.pop ();
1544 tree n = copy_node (*p PASS_MEM_STAT);
1545 CONSTRUCTOR_ELTS (n) = vec_safe_copy (CONSTRUCTOR_ELTS (*p) PASS_MEM_STAT);
1546 *p = n;
1547 vec<constructor_elt, va_gc> *v = CONSTRUCTOR_ELTS (n);
1548 constructor_elt *ce;
1549 for (HOST_WIDE_INT i = 0; vec_safe_iterate (v, i, &ce); ++i)
1550 if (ce->value && TREE_CODE (ce->value) == CONSTRUCTOR)
1551 ptrs.safe_push (&ce->value);
1553 return t;
1556 /* If T is a CONSTRUCTOR, ggc_free T and any sub-CONSTRUCTORs. */
1558 static void
1559 free_constructor (tree t)
1561 if (!t || TREE_CODE (t) != CONSTRUCTOR)
1562 return;
1563 releasing_vec ctors;
1564 vec_safe_push (ctors, t);
1565 while (!ctors->is_empty ())
1567 tree c = ctors->pop ();
1568 if (vec<constructor_elt, va_gc> *elts = CONSTRUCTOR_ELTS (c))
1570 constructor_elt *ce;
1571 for (HOST_WIDE_INT i = 0; vec_safe_iterate (elts, i, &ce); ++i)
1572 if (TREE_CODE (ce->value) == CONSTRUCTOR)
1573 vec_safe_push (ctors, ce->value);
1574 ggc_free (elts);
1576 ggc_free (c);
1580 /* Helper function of cxx_bind_parameters_in_call. Return non-NULL
1581 if *TP is address of a static variable (or part of it) currently being
1582 constructed or of a heap artificial variable. */
1584 static tree
1585 addr_of_non_const_var (tree *tp, int *walk_subtrees, void *data)
1587 if (TREE_CODE (*tp) == ADDR_EXPR)
1588 if (tree var = get_base_address (TREE_OPERAND (*tp, 0)))
1589 if (VAR_P (var) && TREE_STATIC (var))
1591 if (DECL_NAME (var) == heap_uninit_identifier
1592 || DECL_NAME (var) == heap_identifier
1593 || DECL_NAME (var) == heap_vec_uninit_identifier
1594 || DECL_NAME (var) == heap_vec_identifier)
1595 return var;
1597 constexpr_global_ctx *global = (constexpr_global_ctx *) data;
1598 if (global->values.get (var))
1599 return var;
1601 if (TYPE_P (*tp))
1602 *walk_subtrees = false;
1603 return NULL_TREE;
1606 /* Subroutine of cxx_eval_call_expression.
1607 We are processing a call expression (either CALL_EXPR or
1608 AGGR_INIT_EXPR) in the context of CTX. Evaluate
1609 all arguments and bind their values to correspondings
1610 parameters, making up the NEW_CALL context. */
1612 static void
1613 cxx_bind_parameters_in_call (const constexpr_ctx *ctx, tree t,
1614 constexpr_call *new_call,
1615 bool *non_constant_p, bool *overflow_p,
1616 bool *non_constant_args)
1618 const int nargs = call_expr_nargs (t);
1619 tree fun = new_call->fundef->decl;
1620 tree parms = new_call->fundef->parms;
1621 int i;
1622 /* We don't record ellipsis args below. */
1623 int nparms = list_length (parms);
1624 int nbinds = nargs < nparms ? nargs : nparms;
1625 tree binds = new_call->bindings = make_tree_vec (nbinds);
1626 for (i = 0; i < nargs; ++i)
1628 tree x, arg;
1629 tree type = parms ? TREE_TYPE (parms) : void_type_node;
1630 x = get_nth_callarg (t, i);
1631 /* For member function, the first argument is a pointer to the implied
1632 object. For a constructor, it might still be a dummy object, in
1633 which case we get the real argument from ctx. */
1634 if (i == 0 && DECL_CONSTRUCTOR_P (fun)
1635 && is_dummy_object (x))
1637 x = ctx->object;
1638 x = build_address (x);
1640 if (TREE_ADDRESSABLE (type))
1641 /* Undo convert_for_arg_passing work here. */
1642 x = convert_from_reference (x);
1643 /* Normally we would strip a TARGET_EXPR in an initialization context
1644 such as this, but here we do the elision differently: we keep the
1645 TARGET_EXPR, and use its CONSTRUCTOR as the value of the parm. */
1646 arg = cxx_eval_constant_expression (ctx, x, /*lval=*/false,
1647 non_constant_p, overflow_p);
1648 /* Don't VERIFY_CONSTANT here. */
1649 if (*non_constant_p && ctx->quiet)
1650 return;
1651 /* Just discard ellipsis args after checking their constantitude. */
1652 if (!parms)
1653 continue;
1655 if (!*non_constant_p)
1657 /* Make sure the binding has the same type as the parm. But
1658 only for constant args. */
1659 if (!TYPE_REF_P (type))
1660 arg = adjust_temp_type (type, arg);
1661 if (!TREE_CONSTANT (arg))
1662 *non_constant_args = true;
1663 else if (TYPE_HAS_NONTRIVIAL_DESTRUCTOR (type))
1664 /* The destructor needs to see any modifications the callee makes
1665 to the argument. */
1666 *non_constant_args = true;
1667 /* If arg is or contains address of a heap artificial variable or
1668 of a static variable being constructed, avoid caching the
1669 function call, as those variables might be modified by the
1670 function, or might be modified by the callers in between
1671 the cached function and just read by the function. */
1672 else if (!*non_constant_args
1673 && cp_walk_tree (&arg, addr_of_non_const_var, ctx->global,
1674 NULL))
1675 *non_constant_args = true;
1677 /* For virtual calls, adjust the this argument, so that it is
1678 the object on which the method is called, rather than
1679 one of its bases. */
1680 if (i == 0 && DECL_VIRTUAL_P (fun))
1682 tree addr = arg;
1683 STRIP_NOPS (addr);
1684 if (TREE_CODE (addr) == ADDR_EXPR)
1686 tree obj = TREE_OPERAND (addr, 0);
1687 while (TREE_CODE (obj) == COMPONENT_REF
1688 && DECL_FIELD_IS_BASE (TREE_OPERAND (obj, 1))
1689 && !same_type_ignoring_top_level_qualifiers_p
1690 (TREE_TYPE (obj), DECL_CONTEXT (fun)))
1691 obj = TREE_OPERAND (obj, 0);
1692 if (obj != TREE_OPERAND (addr, 0))
1693 arg = build_fold_addr_expr_with_type (obj,
1694 TREE_TYPE (arg));
1697 TREE_VEC_ELT (binds, i) = arg;
1699 parms = TREE_CHAIN (parms);
1703 /* Variables and functions to manage constexpr call expansion context.
1704 These do not need to be marked for PCH or GC. */
1706 /* FIXME remember and print actual constant arguments. */
1707 static vec<tree> call_stack;
1708 static int call_stack_tick;
1709 static int last_cx_error_tick;
1711 static int
1712 push_cx_call_context (tree call)
1714 ++call_stack_tick;
1715 if (!EXPR_HAS_LOCATION (call))
1716 SET_EXPR_LOCATION (call, input_location);
1717 call_stack.safe_push (call);
1718 int len = call_stack.length ();
1719 if (len > max_constexpr_depth)
1720 return false;
1721 return len;
1724 static void
1725 pop_cx_call_context (void)
1727 ++call_stack_tick;
1728 call_stack.pop ();
1731 vec<tree>
1732 cx_error_context (void)
1734 vec<tree> r = vNULL;
1735 if (call_stack_tick != last_cx_error_tick
1736 && !call_stack.is_empty ())
1737 r = call_stack;
1738 last_cx_error_tick = call_stack_tick;
1739 return r;
1742 /* Evaluate a call T to a GCC internal function when possible and return
1743 the evaluated result or, under the control of CTX, give an error, set
1744 NON_CONSTANT_P, and return the unevaluated call T otherwise. */
1746 static tree
1747 cxx_eval_internal_function (const constexpr_ctx *ctx, tree t,
1748 bool lval,
1749 bool *non_constant_p, bool *overflow_p)
1751 enum tree_code opcode = ERROR_MARK;
1753 switch (CALL_EXPR_IFN (t))
1755 case IFN_UBSAN_NULL:
1756 case IFN_UBSAN_BOUNDS:
1757 case IFN_UBSAN_VPTR:
1758 case IFN_FALLTHROUGH:
1759 return void_node;
1761 case IFN_ADD_OVERFLOW:
1762 opcode = PLUS_EXPR;
1763 break;
1764 case IFN_SUB_OVERFLOW:
1765 opcode = MINUS_EXPR;
1766 break;
1767 case IFN_MUL_OVERFLOW:
1768 opcode = MULT_EXPR;
1769 break;
1771 case IFN_LAUNDER:
1772 return cxx_eval_constant_expression (ctx, CALL_EXPR_ARG (t, 0),
1773 false, non_constant_p, overflow_p);
1775 case IFN_VEC_CONVERT:
1777 tree arg = cxx_eval_constant_expression (ctx, CALL_EXPR_ARG (t, 0),
1778 false, non_constant_p,
1779 overflow_p);
1780 if (TREE_CODE (arg) == VECTOR_CST)
1781 return fold_const_call (CFN_VEC_CONVERT, TREE_TYPE (t), arg);
1782 else
1784 *non_constant_p = true;
1785 return t;
1789 default:
1790 if (!ctx->quiet)
1791 error_at (cp_expr_loc_or_input_loc (t),
1792 "call to internal function %qE", t);
1793 *non_constant_p = true;
1794 return t;
1797 /* Evaluate constant arguments using OPCODE and return a complex
1798 number containing the result and the overflow bit. */
1799 tree arg0 = cxx_eval_constant_expression (ctx, CALL_EXPR_ARG (t, 0), lval,
1800 non_constant_p, overflow_p);
1801 tree arg1 = cxx_eval_constant_expression (ctx, CALL_EXPR_ARG (t, 1), lval,
1802 non_constant_p, overflow_p);
1804 if (TREE_CODE (arg0) == INTEGER_CST && TREE_CODE (arg1) == INTEGER_CST)
1806 location_t loc = cp_expr_loc_or_input_loc (t);
1807 tree type = TREE_TYPE (TREE_TYPE (t));
1808 tree result = fold_binary_loc (loc, opcode, type,
1809 fold_convert_loc (loc, type, arg0),
1810 fold_convert_loc (loc, type, arg1));
1811 tree ovf
1812 = build_int_cst (type, arith_overflowed_p (opcode, type, arg0, arg1));
1813 /* Reset TREE_OVERFLOW to avoid warnings for the overflow. */
1814 if (TREE_OVERFLOW (result))
1815 TREE_OVERFLOW (result) = 0;
1817 return build_complex (TREE_TYPE (t), result, ovf);
1820 *non_constant_p = true;
1821 return t;
1824 /* Clean CONSTRUCTOR_NO_CLEARING from CTOR and its sub-aggregates. */
1826 static void
1827 clear_no_implicit_zero (tree ctor)
1829 if (CONSTRUCTOR_NO_CLEARING (ctor))
1831 CONSTRUCTOR_NO_CLEARING (ctor) = false;
1832 tree elt; unsigned HOST_WIDE_INT idx;
1833 FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (ctor), idx, elt)
1834 if (TREE_CODE (elt) == CONSTRUCTOR)
1835 clear_no_implicit_zero (elt);
1839 /* Complain about a const object OBJ being modified in a constant expression.
1840 EXPR is the MODIFY_EXPR expression performing the modification. */
1842 static void
1843 modifying_const_object_error (tree expr, tree obj)
1845 location_t loc = cp_expr_loc_or_input_loc (expr);
1846 auto_diagnostic_group d;
1847 error_at (loc, "modifying a const object %qE is not allowed in "
1848 "a constant expression", TREE_OPERAND (expr, 0));
1849 inform (location_of (obj), "originally declared %<const%> here");
1852 /* Return true if FNDECL is a replaceable global allocation function that
1853 should be useable during constant expression evaluation. */
1855 static inline bool
1856 cxx_replaceable_global_alloc_fn (tree fndecl)
1858 return (cxx_dialect >= cxx20
1859 && IDENTIFIER_NEWDEL_OP_P (DECL_NAME (fndecl))
1860 && CP_DECL_CONTEXT (fndecl) == global_namespace
1861 && (DECL_IS_REPLACEABLE_OPERATOR_NEW_P (fndecl)
1862 || DECL_IS_OPERATOR_DELETE_P (fndecl)));
1865 /* Return true if FNDECL is a placement new function that should be
1866 useable during constant expression evaluation of std::construct_at. */
1868 static inline bool
1869 cxx_placement_new_fn (tree fndecl)
1871 if (cxx_dialect >= cxx20
1872 && IDENTIFIER_NEW_OP_P (DECL_NAME (fndecl))
1873 && CP_DECL_CONTEXT (fndecl) == global_namespace
1874 && !DECL_IS_REPLACEABLE_OPERATOR_NEW_P (fndecl)
1875 && TREE_CODE (TREE_TYPE (fndecl)) == FUNCTION_TYPE)
1877 tree first_arg = TREE_CHAIN (TYPE_ARG_TYPES (TREE_TYPE (fndecl)));
1878 if (TREE_VALUE (first_arg) == ptr_type_node
1879 && TREE_CHAIN (first_arg) == void_list_node)
1880 return true;
1882 return false;
1885 /* Return true if FNDECL is std::construct_at. */
1887 static inline bool
1888 is_std_construct_at (tree fndecl)
1890 if (!decl_in_std_namespace_p (fndecl))
1891 return false;
1893 tree name = DECL_NAME (fndecl);
1894 return name && id_equal (name, "construct_at");
1897 /* Overload for the above taking constexpr_call*. */
1899 static inline bool
1900 is_std_construct_at (const constexpr_call *call)
1902 return (call
1903 && call->fundef
1904 && is_std_construct_at (call->fundef->decl));
1907 /* Return true if FNDECL is std::allocator<T>::{,de}allocate. */
1909 static inline bool
1910 is_std_allocator_allocate (tree fndecl)
1912 tree name = DECL_NAME (fndecl);
1913 if (name == NULL_TREE
1914 || !(id_equal (name, "allocate") || id_equal (name, "deallocate")))
1915 return false;
1917 tree ctx = DECL_CONTEXT (fndecl);
1918 if (ctx == NULL_TREE || !CLASS_TYPE_P (ctx) || !TYPE_MAIN_DECL (ctx))
1919 return false;
1921 tree decl = TYPE_MAIN_DECL (ctx);
1922 name = DECL_NAME (decl);
1923 if (name == NULL_TREE || !id_equal (name, "allocator"))
1924 return false;
1926 return decl_in_std_namespace_p (decl);
1929 /* Overload for the above taking constexpr_call*. */
1931 static inline bool
1932 is_std_allocator_allocate (const constexpr_call *call)
1934 return (call
1935 && call->fundef
1936 && is_std_allocator_allocate (call->fundef->decl));
1939 /* Return true if FNDECL is __dynamic_cast. */
1941 static inline bool
1942 cxx_dynamic_cast_fn_p (tree fndecl)
1944 return (cxx_dialect >= cxx20
1945 && id_equal (DECL_NAME (fndecl), "__dynamic_cast")
1946 && CP_DECL_CONTEXT (fndecl) == global_namespace);
1949 /* Often, we have an expression in the form of address + offset, e.g.
1950 "&_ZTV1A + 16". Extract the object from it, i.e. "_ZTV1A". */
1952 static tree
1953 extract_obj_from_addr_offset (tree expr)
1955 if (TREE_CODE (expr) == POINTER_PLUS_EXPR)
1956 expr = TREE_OPERAND (expr, 0);
1957 STRIP_NOPS (expr);
1958 if (TREE_CODE (expr) == ADDR_EXPR)
1959 expr = TREE_OPERAND (expr, 0);
1960 return expr;
1963 /* Given a PATH like
1965 g.D.2181.D.2154.D.2102.D.2093
1967 find a component with type TYPE. Return NULL_TREE if not found, and
1968 error_mark_node if the component is not accessible. If STOP is non-null,
1969 this function will return NULL_TREE if STOP is found before TYPE. */
1971 static tree
1972 get_component_with_type (tree path, tree type, tree stop)
1974 while (true)
1976 if (same_type_ignoring_top_level_qualifiers_p (TREE_TYPE (path), type))
1977 /* Found it. */
1978 return path;
1979 else if (stop
1980 && (same_type_ignoring_top_level_qualifiers_p (TREE_TYPE (path),
1981 stop)))
1982 return NULL_TREE;
1983 else if (TREE_CODE (path) == COMPONENT_REF
1984 && DECL_FIELD_IS_BASE (TREE_OPERAND (path, 1)))
1986 /* We need to check that the component we're accessing is in fact
1987 accessible. */
1988 if (TREE_PRIVATE (TREE_OPERAND (path, 1))
1989 || TREE_PROTECTED (TREE_OPERAND (path, 1)))
1990 return error_mark_node;
1991 path = TREE_OPERAND (path, 0);
1993 else
1994 return NULL_TREE;
1998 /* Evaluate a call to __dynamic_cast (permitted by P1327R1).
2000 The declaration of __dynamic_cast is:
2002 void* __dynamic_cast (const void* __src_ptr,
2003 const __class_type_info* __src_type,
2004 const __class_type_info* __dst_type,
2005 ptrdiff_t __src2dst);
2007 where src2dst has the following possible values
2009 >-1: src_type is a unique public non-virtual base of dst_type
2010 dst_ptr + src2dst == src_ptr
2011 -1: unspecified relationship
2012 -2: src_type is not a public base of dst_type
2013 -3: src_type is a multiple public non-virtual base of dst_type
2015 Since literal types can't have virtual bases, we only expect hint >=0,
2016 -2, or -3. */
2018 static tree
2019 cxx_eval_dynamic_cast_fn (const constexpr_ctx *ctx, tree call,
2020 bool *non_constant_p, bool *overflow_p)
2022 /* T will be something like
2023 __dynamic_cast ((B*) b, &_ZTI1B, &_ZTI1D, 8)
2024 dismantle it. */
2025 gcc_assert (call_expr_nargs (call) == 4);
2026 tsubst_flags_t complain = ctx->quiet ? tf_none : tf_warning_or_error;
2027 tree obj = CALL_EXPR_ARG (call, 0);
2028 tree type = CALL_EXPR_ARG (call, 2);
2029 HOST_WIDE_INT hint = int_cst_value (CALL_EXPR_ARG (call, 3));
2030 location_t loc = cp_expr_loc_or_input_loc (call);
2032 /* Get the target type of the dynamic_cast. */
2033 gcc_assert (TREE_CODE (type) == ADDR_EXPR);
2034 type = TREE_OPERAND (type, 0);
2035 type = TREE_TYPE (DECL_NAME (type));
2037 /* TYPE can only be either T* or T&. We can't know which of these it
2038 is by looking at TYPE, but OBJ will be "(T*) x" in the first case,
2039 and something like "(T*)(T&)(T*) x" in the second case. */
2040 bool reference_p = false;
2041 while (CONVERT_EXPR_P (obj) || TREE_CODE (obj) == SAVE_EXPR)
2043 reference_p |= TYPE_REF_P (TREE_TYPE (obj));
2044 obj = TREE_OPERAND (obj, 0);
2047 /* Evaluate the object so that we know its dynamic type. */
2048 obj = cxx_eval_constant_expression (ctx, obj, /*lval*/false, non_constant_p,
2049 overflow_p);
2050 if (*non_constant_p)
2051 return call;
2053 /* We expect OBJ to be in form of &d.D.2102 when HINT == 0,
2054 but when HINT is > 0, it can also be something like
2055 &d.D.2102 + 18446744073709551608, which includes the BINFO_OFFSET. */
2056 obj = extract_obj_from_addr_offset (obj);
2057 const tree objtype = TREE_TYPE (obj);
2058 /* If OBJ doesn't refer to a base field, we're done. */
2059 if (tree t = (TREE_CODE (obj) == COMPONENT_REF
2060 ? TREE_OPERAND (obj, 1) : obj))
2061 if (TREE_CODE (t) != FIELD_DECL || !DECL_FIELD_IS_BASE (t))
2063 if (reference_p)
2065 if (!ctx->quiet)
2067 error_at (loc, "reference %<dynamic_cast%> failed");
2068 inform (loc, "dynamic type %qT of its operand does "
2069 "not have a base class of type %qT",
2070 objtype, type);
2072 *non_constant_p = true;
2074 return integer_zero_node;
2077 /* [class.cdtor] When a dynamic_cast is used in a constructor ...
2078 or in a destructor ... if the operand of the dynamic_cast refers
2079 to the object under construction or destruction, this object is
2080 considered to be a most derived object that has the type of the
2081 constructor or destructor's class. */
2082 tree vtable = build_vfield_ref (obj, objtype);
2083 vtable = cxx_eval_constant_expression (ctx, vtable, /*lval*/false,
2084 non_constant_p, overflow_p);
2085 if (*non_constant_p)
2086 return call;
2087 /* With -fsanitize=vptr, we initialize all vtable pointers to null,
2088 so it's possible that we got a null pointer now. */
2089 if (integer_zerop (vtable))
2091 if (!ctx->quiet)
2092 error_at (loc, "virtual table pointer is used uninitialized");
2093 *non_constant_p = true;
2094 return integer_zero_node;
2096 /* VTABLE will be &_ZTV1A + 16 or similar, get _ZTV1A. */
2097 vtable = extract_obj_from_addr_offset (vtable);
2098 const tree mdtype = DECL_CONTEXT (vtable);
2100 /* Given dynamic_cast<T>(v),
2102 [expr.dynamic.cast] If C is the class type to which T points or refers,
2103 the runtime check logically executes as follows:
2105 If, in the most derived object pointed (referred) to by v, v points
2106 (refers) to a public base class subobject of a C object, and if only
2107 one object of type C is derived from the subobject pointed (referred)
2108 to by v the result points (refers) to that C object.
2110 In this case, HINT >= 0 or -3. */
2111 if (hint >= 0 || hint == -3)
2113 /* Look for a component with type TYPE. */
2114 tree t = get_component_with_type (obj, type, mdtype);
2115 /* If not accessible, give an error. */
2116 if (t == error_mark_node)
2118 if (reference_p)
2120 if (!ctx->quiet)
2122 error_at (loc, "reference %<dynamic_cast%> failed");
2123 inform (loc, "static type %qT of its operand is a "
2124 "non-public base class of dynamic type %qT",
2125 objtype, type);
2128 *non_constant_p = true;
2130 return integer_zero_node;
2132 else if (t)
2133 /* The result points to the TYPE object. */
2134 return cp_build_addr_expr (t, complain);
2135 /* Else, TYPE was not found, because the HINT turned out to be wrong.
2136 Fall through to the normal processing. */
2139 /* Otherwise, if v points (refers) to a public base class subobject of the
2140 most derived object, and the type of the most derived object has a base
2141 class, of type C, that is unambiguous and public, the result points
2142 (refers) to the C subobject of the most derived object.
2144 But it can also be an invalid case. */
2146 /* Get the most derived object. */
2147 obj = get_component_with_type (obj, mdtype, NULL_TREE);
2148 if (obj == error_mark_node)
2150 if (reference_p)
2152 if (!ctx->quiet)
2154 error_at (loc, "reference %<dynamic_cast%> failed");
2155 inform (loc, "static type %qT of its operand is a non-public"
2156 " base class of dynamic type %qT", objtype, mdtype);
2158 *non_constant_p = true;
2160 return integer_zero_node;
2162 else
2163 gcc_assert (obj);
2165 /* Check that the type of the most derived object has a base class
2166 of type TYPE that is unambiguous and public. */
2167 base_kind b_kind;
2168 tree binfo = lookup_base (mdtype, type, ba_check, &b_kind, tf_none);
2169 if (!binfo || binfo == error_mark_node)
2171 if (reference_p)
2173 if (!ctx->quiet)
2175 error_at (loc, "reference %<dynamic_cast%> failed");
2176 if (b_kind == bk_ambig)
2177 inform (loc, "%qT is an ambiguous base class of dynamic "
2178 "type %qT of its operand", type, mdtype);
2179 else
2180 inform (loc, "dynamic type %qT of its operand does not "
2181 "have an unambiguous public base class %qT",
2182 mdtype, type);
2184 *non_constant_p = true;
2186 return integer_zero_node;
2188 /* If so, return the TYPE subobject of the most derived object. */
2189 obj = convert_to_base_statically (obj, binfo);
2190 return cp_build_addr_expr (obj, complain);
2193 /* Data structure used by replace_result_decl and replace_result_decl_r. */
2195 struct replace_result_decl_data
2197 /* The RESULT_DECL we want to replace. */
2198 tree decl;
2199 /* The replacement for DECL. */
2200 tree replacement;
2201 /* Whether we've performed any replacements. */
2202 bool changed;
2205 /* Helper function for replace_result_decl, called through cp_walk_tree. */
2207 static tree
2208 replace_result_decl_r (tree *tp, int *walk_subtrees, void *data)
2210 replace_result_decl_data *d = (replace_result_decl_data *) data;
2212 if (*tp == d->decl)
2214 *tp = unshare_expr (d->replacement);
2215 d->changed = true;
2216 *walk_subtrees = 0;
2218 else if (TYPE_P (*tp))
2219 *walk_subtrees = 0;
2221 return NULL_TREE;
2224 /* Replace every occurrence of DECL, a RESULT_DECL, with (an unshared copy of)
2225 REPLACEMENT within the reduced constant expression *TP. Returns true iff a
2226 replacement was performed. */
2228 static bool
2229 replace_result_decl (tree *tp, tree decl, tree replacement)
2231 gcc_checking_assert (TREE_CODE (decl) == RESULT_DECL
2232 && (same_type_ignoring_top_level_qualifiers_p
2233 (TREE_TYPE (decl), TREE_TYPE (replacement))));
2234 replace_result_decl_data data = { decl, replacement, false };
2235 cp_walk_tree_without_duplicates (tp, replace_result_decl_r, &data);
2236 return data.changed;
2239 /* Evaluate the call T to virtual function thunk THUNK_FNDECL. */
2241 static tree
2242 cxx_eval_thunk_call (const constexpr_ctx *ctx, tree t, tree thunk_fndecl,
2243 bool lval,
2244 bool *non_constant_p, bool *overflow_p)
2246 tree function = THUNK_TARGET (thunk_fndecl);
2248 /* virtual_offset is only set in the presence of virtual bases, which make
2249 the class non-literal, so we don't need to handle it here. */
2250 if (THUNK_VIRTUAL_OFFSET (thunk_fndecl))
2252 gcc_assert (!DECL_DECLARED_CONSTEXPR_P (function));
2253 if (!ctx->quiet)
2255 error ("call to non-%<constexpr%> function %qD", function);
2256 explain_invalid_constexpr_fn (function);
2258 *non_constant_p = true;
2259 return t;
2262 tree new_call = copy_node (t);
2263 CALL_EXPR_FN (new_call) = function;
2264 TREE_TYPE (new_call) = TREE_TYPE (TREE_TYPE (function));
2266 tree offset = size_int (THUNK_FIXED_OFFSET (thunk_fndecl));
2268 if (DECL_THIS_THUNK_P (thunk_fndecl))
2270 /* 'this'-adjusting thunk. */
2271 tree this_arg = CALL_EXPR_ARG (t, 0);
2272 this_arg = build2 (POINTER_PLUS_EXPR, TREE_TYPE (this_arg),
2273 this_arg, offset);
2274 CALL_EXPR_ARG (new_call, 0) = this_arg;
2276 else
2277 /* Return-adjusting thunk. */
2278 new_call = build2 (POINTER_PLUS_EXPR, TREE_TYPE (new_call),
2279 new_call, offset);
2281 return cxx_eval_constant_expression (ctx, new_call, lval,
2282 non_constant_p, overflow_p);
2285 /* If OBJECT is of const class type, evaluate it to a CONSTRUCTOR and set
2286 its TREE_READONLY flag according to READONLY_P. Used for constexpr
2287 'tors to detect modifying const objects in a constexpr context. */
2289 static void
2290 cxx_set_object_constness (const constexpr_ctx *ctx, tree object,
2291 bool readonly_p, bool *non_constant_p,
2292 bool *overflow_p)
2294 if (CLASS_TYPE_P (TREE_TYPE (object))
2295 && CP_TYPE_CONST_P (TREE_TYPE (object)))
2297 /* Subobjects might not be stored in ctx->global->values but we
2298 can get its CONSTRUCTOR by evaluating *this. */
2299 tree e = cxx_eval_constant_expression (ctx, object, /*lval*/false,
2300 non_constant_p, overflow_p);
2301 if (TREE_CODE (e) == CONSTRUCTOR && !*non_constant_p)
2302 TREE_READONLY (e) = readonly_p;
2306 /* Subroutine of cxx_eval_constant_expression.
2307 Evaluate the call expression tree T in the context of OLD_CALL expression
2308 evaluation. */
2310 static tree
2311 cxx_eval_call_expression (const constexpr_ctx *ctx, tree t,
2312 bool lval,
2313 bool *non_constant_p, bool *overflow_p)
2315 /* Handle concept checks separately. */
2316 if (concept_check_p (t))
2317 return evaluate_concept_check (t);
2319 location_t loc = cp_expr_loc_or_input_loc (t);
2320 tree fun = get_function_named_in_call (t);
2321 constexpr_call new_call
2322 = { NULL, NULL, NULL, 0, ctx->manifestly_const_eval };
2323 int depth_ok;
2325 if (fun == NULL_TREE)
2326 return cxx_eval_internal_function (ctx, t, lval,
2327 non_constant_p, overflow_p);
2329 if (TREE_CODE (fun) != FUNCTION_DECL)
2331 /* Might be a constexpr function pointer. */
2332 fun = cxx_eval_constant_expression (ctx, fun,
2333 /*lval*/false, non_constant_p,
2334 overflow_p);
2335 STRIP_NOPS (fun);
2336 if (TREE_CODE (fun) == ADDR_EXPR)
2337 fun = TREE_OPERAND (fun, 0);
2338 /* For TARGET_VTABLE_USES_DESCRIPTORS targets, there is no
2339 indirection, the called expression is a pointer into the
2340 virtual table which should contain FDESC_EXPR. Extract the
2341 FUNCTION_DECL from there. */
2342 else if (TARGET_VTABLE_USES_DESCRIPTORS
2343 && TREE_CODE (fun) == POINTER_PLUS_EXPR
2344 && TREE_CODE (TREE_OPERAND (fun, 0)) == ADDR_EXPR
2345 && TREE_CODE (TREE_OPERAND (fun, 1)) == INTEGER_CST)
2347 tree d = TREE_OPERAND (TREE_OPERAND (fun, 0), 0);
2348 if (VAR_P (d)
2349 && DECL_VTABLE_OR_VTT_P (d)
2350 && TREE_CODE (TREE_TYPE (d)) == ARRAY_TYPE
2351 && TREE_TYPE (TREE_TYPE (d)) == vtable_entry_type
2352 && DECL_INITIAL (d)
2353 && TREE_CODE (DECL_INITIAL (d)) == CONSTRUCTOR)
2355 tree i = int_const_binop (TRUNC_DIV_EXPR, TREE_OPERAND (fun, 1),
2356 TYPE_SIZE_UNIT (vtable_entry_type));
2357 HOST_WIDE_INT idx = find_array_ctor_elt (DECL_INITIAL (d), i);
2358 if (idx >= 0)
2360 tree fdesc
2361 = (*CONSTRUCTOR_ELTS (DECL_INITIAL (d)))[idx].value;
2362 if (TREE_CODE (fdesc) == FDESC_EXPR
2363 && integer_zerop (TREE_OPERAND (fdesc, 1)))
2364 fun = TREE_OPERAND (fdesc, 0);
2369 if (TREE_CODE (fun) != FUNCTION_DECL)
2371 if (!ctx->quiet && !*non_constant_p)
2372 error_at (loc, "expression %qE does not designate a %<constexpr%> "
2373 "function", fun);
2374 *non_constant_p = true;
2375 return t;
2377 if (DECL_CLONED_FUNCTION_P (fun))
2378 fun = DECL_CLONED_FUNCTION (fun);
2380 if (is_ubsan_builtin_p (fun))
2381 return void_node;
2383 if (fndecl_built_in_p (fun))
2384 return cxx_eval_builtin_function_call (ctx, t, fun,
2385 lval, non_constant_p, overflow_p);
2386 if (DECL_THUNK_P (fun))
2387 return cxx_eval_thunk_call (ctx, t, fun, lval, non_constant_p, overflow_p);
2388 if (!DECL_DECLARED_CONSTEXPR_P (fun))
2390 if (TREE_CODE (t) == CALL_EXPR
2391 && cxx_replaceable_global_alloc_fn (fun)
2392 && (CALL_FROM_NEW_OR_DELETE_P (t)
2393 || is_std_allocator_allocate (ctx->call)))
2395 const int nargs = call_expr_nargs (t);
2396 tree arg0 = NULL_TREE;
2397 for (int i = 0; i < nargs; ++i)
2399 tree arg = CALL_EXPR_ARG (t, i);
2400 arg = cxx_eval_constant_expression (ctx, arg, false,
2401 non_constant_p, overflow_p);
2402 VERIFY_CONSTANT (arg);
2403 if (i == 0)
2404 arg0 = arg;
2406 gcc_assert (arg0);
2407 if (IDENTIFIER_NEW_OP_P (DECL_NAME (fun)))
2409 tree type = build_array_type_nelts (char_type_node,
2410 tree_to_uhwi (arg0));
2411 tree var = build_decl (loc, VAR_DECL,
2412 (IDENTIFIER_OVL_OP_FLAGS (DECL_NAME (fun))
2413 & OVL_OP_FLAG_VEC)
2414 ? heap_vec_uninit_identifier
2415 : heap_uninit_identifier,
2416 type);
2417 DECL_ARTIFICIAL (var) = 1;
2418 TREE_STATIC (var) = 1;
2419 // Temporarily register the artificial var in varpool,
2420 // so that comparisons of its address against NULL are folded
2421 // through nonzero_address even with
2422 // -fno-delete-null-pointer-checks or that comparison of
2423 // addresses of different heap artificial vars is folded too.
2424 // See PR98988 and PR99031.
2425 varpool_node::finalize_decl (var);
2426 ctx->global->heap_vars.safe_push (var);
2427 ctx->global->values.put (var, NULL_TREE);
2428 return fold_convert (ptr_type_node, build_address (var));
2430 else
2432 STRIP_NOPS (arg0);
2433 if (TREE_CODE (arg0) == ADDR_EXPR
2434 && VAR_P (TREE_OPERAND (arg0, 0)))
2436 tree var = TREE_OPERAND (arg0, 0);
2437 if (DECL_NAME (var) == heap_uninit_identifier
2438 || DECL_NAME (var) == heap_identifier)
2440 if (IDENTIFIER_OVL_OP_FLAGS (DECL_NAME (fun))
2441 & OVL_OP_FLAG_VEC)
2443 if (!ctx->quiet)
2445 error_at (loc, "array deallocation of object "
2446 "allocated with non-array "
2447 "allocation");
2448 inform (DECL_SOURCE_LOCATION (var),
2449 "allocation performed here");
2451 *non_constant_p = true;
2452 return t;
2454 DECL_NAME (var) = heap_deleted_identifier;
2455 ctx->global->values.remove (var);
2456 ctx->global->heap_dealloc_count++;
2457 return void_node;
2459 else if (DECL_NAME (var) == heap_vec_uninit_identifier
2460 || DECL_NAME (var) == heap_vec_identifier)
2462 if ((IDENTIFIER_OVL_OP_FLAGS (DECL_NAME (fun))
2463 & OVL_OP_FLAG_VEC) == 0)
2465 if (!ctx->quiet)
2467 error_at (loc, "non-array deallocation of "
2468 "object allocated with array "
2469 "allocation");
2470 inform (DECL_SOURCE_LOCATION (var),
2471 "allocation performed here");
2473 *non_constant_p = true;
2474 return t;
2476 DECL_NAME (var) = heap_deleted_identifier;
2477 ctx->global->values.remove (var);
2478 ctx->global->heap_dealloc_count++;
2479 return void_node;
2481 else if (DECL_NAME (var) == heap_deleted_identifier)
2483 if (!ctx->quiet)
2484 error_at (loc, "deallocation of already deallocated "
2485 "storage");
2486 *non_constant_p = true;
2487 return t;
2490 if (!ctx->quiet)
2491 error_at (loc, "deallocation of storage that was "
2492 "not previously allocated");
2493 *non_constant_p = true;
2494 return t;
2497 /* Allow placement new in std::construct_at, just return the second
2498 argument. */
2499 if (TREE_CODE (t) == CALL_EXPR
2500 && cxx_placement_new_fn (fun)
2501 && is_std_construct_at (ctx->call))
2503 const int nargs = call_expr_nargs (t);
2504 tree arg1 = NULL_TREE;
2505 for (int i = 0; i < nargs; ++i)
2507 tree arg = CALL_EXPR_ARG (t, i);
2508 arg = cxx_eval_constant_expression (ctx, arg, false,
2509 non_constant_p, overflow_p);
2510 if (i == 1)
2511 arg1 = arg;
2512 else
2513 VERIFY_CONSTANT (arg);
2515 gcc_assert (arg1);
2516 return arg1;
2518 else if (cxx_dynamic_cast_fn_p (fun))
2519 return cxx_eval_dynamic_cast_fn (ctx, t, non_constant_p, overflow_p);
2521 if (!ctx->quiet)
2523 if (!lambda_static_thunk_p (fun))
2524 error_at (loc, "call to non-%<constexpr%> function %qD", fun);
2525 explain_invalid_constexpr_fn (fun);
2527 *non_constant_p = true;
2528 return t;
2531 constexpr_ctx new_ctx = *ctx;
2532 if (DECL_CONSTRUCTOR_P (fun) && !ctx->object
2533 && TREE_CODE (t) == AGGR_INIT_EXPR)
2535 /* We want to have an initialization target for an AGGR_INIT_EXPR.
2536 If we don't already have one in CTX, use the AGGR_INIT_EXPR_SLOT. */
2537 new_ctx.object = AGGR_INIT_EXPR_SLOT (t);
2538 tree ctor = new_ctx.ctor = build_constructor (DECL_CONTEXT (fun), NULL);
2539 CONSTRUCTOR_NO_CLEARING (ctor) = true;
2540 ctx->global->values.put (new_ctx.object, ctor);
2541 ctx = &new_ctx;
2544 /* Shortcut trivial constructor/op=. */
2545 if (trivial_fn_p (fun))
2547 tree init = NULL_TREE;
2548 if (call_expr_nargs (t) == 2)
2549 init = convert_from_reference (get_nth_callarg (t, 1));
2550 else if (TREE_CODE (t) == AGGR_INIT_EXPR
2551 && AGGR_INIT_ZERO_FIRST (t))
2552 init = build_zero_init (DECL_CONTEXT (fun), NULL_TREE, false);
2553 if (init)
2555 tree op = get_nth_callarg (t, 0);
2556 if (is_dummy_object (op))
2557 op = ctx->object;
2558 else
2559 op = build1 (INDIRECT_REF, TREE_TYPE (TREE_TYPE (op)), op);
2560 tree set = build2 (MODIFY_EXPR, TREE_TYPE (op), op, init);
2561 new_ctx.call = &new_call;
2562 return cxx_eval_constant_expression (&new_ctx, set, lval,
2563 non_constant_p, overflow_p);
2567 /* We can't defer instantiating the function any longer. */
2568 if (!DECL_INITIAL (fun)
2569 && DECL_TEMPLOID_INSTANTIATION (fun)
2570 && !uid_sensitive_constexpr_evaluation_p ())
2572 location_t save_loc = input_location;
2573 input_location = loc;
2574 ++function_depth;
2575 instantiate_decl (fun, /*defer_ok*/false, /*expl_inst*/false);
2576 --function_depth;
2577 input_location = save_loc;
2580 /* If in direct recursive call, optimize definition search. */
2581 if (ctx && ctx->call && ctx->call->fundef && ctx->call->fundef->decl == fun)
2582 new_call.fundef = ctx->call->fundef;
2583 else
2585 new_call.fundef = retrieve_constexpr_fundef (fun);
2586 if (new_call.fundef == NULL || new_call.fundef->body == NULL
2587 || new_call.fundef->result == error_mark_node
2588 || fun == current_function_decl)
2590 if (!ctx->quiet)
2592 /* We need to check for current_function_decl here in case we're
2593 being called during cp_fold_function, because at that point
2594 DECL_INITIAL is set properly and we have a fundef but we
2595 haven't lowered invisirefs yet (c++/70344). */
2596 if (DECL_INITIAL (fun) == error_mark_node
2597 || fun == current_function_decl)
2598 error_at (loc, "%qD called in a constant expression before its "
2599 "definition is complete", fun);
2600 else if (DECL_INITIAL (fun))
2602 /* The definition of fun was somehow unsuitable. But pretend
2603 that lambda static thunks don't exist. */
2604 if (!lambda_static_thunk_p (fun))
2605 error_at (loc, "%qD called in a constant expression", fun);
2606 explain_invalid_constexpr_fn (fun);
2608 else
2609 error_at (loc, "%qD used before its definition", fun);
2611 *non_constant_p = true;
2612 return t;
2616 bool non_constant_args = false;
2617 cxx_bind_parameters_in_call (ctx, t, &new_call,
2618 non_constant_p, overflow_p, &non_constant_args);
2620 /* We build up the bindings list before we know whether we already have this
2621 call cached. If we don't end up saving these bindings, ggc_free them when
2622 this function exits. */
2623 class free_bindings
2625 tree *bindings;
2626 public:
2627 free_bindings (tree &b): bindings (&b) { }
2628 ~free_bindings () { if (bindings) ggc_free (*bindings); }
2629 void preserve () { bindings = NULL; }
2630 } fb (new_call.bindings);
2632 if (*non_constant_p)
2633 return t;
2635 depth_ok = push_cx_call_context (t);
2637 /* Remember the object we are constructing or destructing. */
2638 tree new_obj = NULL_TREE;
2639 if (DECL_CONSTRUCTOR_P (fun) || DECL_DESTRUCTOR_P (fun))
2641 /* In a cdtor, it should be the first `this' argument.
2642 At this point it has already been evaluated in the call
2643 to cxx_bind_parameters_in_call. */
2644 new_obj = TREE_VEC_ELT (new_call.bindings, 0);
2645 STRIP_NOPS (new_obj);
2646 if (TREE_CODE (new_obj) == ADDR_EXPR)
2647 new_obj = TREE_OPERAND (new_obj, 0);
2649 if (ctx->call && ctx->call->fundef
2650 && DECL_CONSTRUCTOR_P (ctx->call->fundef->decl))
2652 tree cur_obj = TREE_VEC_ELT (ctx->call->bindings, 0);
2653 STRIP_NOPS (cur_obj);
2654 if (TREE_CODE (cur_obj) == ADDR_EXPR)
2655 cur_obj = TREE_OPERAND (cur_obj, 0);
2656 if (new_obj == cur_obj)
2657 /* We're calling the target constructor of a delegating
2658 constructor, or accessing a base subobject through a
2659 NOP_EXPR as part of a call to a base constructor, so
2660 there is no new (sub)object. */
2661 new_obj = NULL_TREE;
2665 tree result = NULL_TREE;
2667 constexpr_call *entry = NULL;
2668 if (depth_ok && !non_constant_args && ctx->strict)
2670 new_call.hash = constexpr_fundef_hasher::hash (new_call.fundef);
2671 new_call.hash
2672 = iterative_hash_template_arg (new_call.bindings, new_call.hash);
2673 new_call.hash
2674 = iterative_hash_object (ctx->manifestly_const_eval, new_call.hash);
2676 /* If we have seen this call before, we are done. */
2677 maybe_initialize_constexpr_call_table ();
2678 constexpr_call **slot
2679 = constexpr_call_table->find_slot (&new_call, INSERT);
2680 entry = *slot;
2681 if (entry == NULL)
2683 /* Only cache up to constexpr_cache_depth to limit memory use. */
2684 if (depth_ok < constexpr_cache_depth)
2686 /* We need to keep a pointer to the entry, not just the slot, as
2687 the slot can move during evaluation of the body. */
2688 *slot = entry = ggc_alloc<constexpr_call> ();
2689 *entry = new_call;
2690 fb.preserve ();
2693 /* Calls that are in progress have their result set to NULL, so that we
2694 can detect circular dependencies. Now that we only cache up to
2695 constexpr_cache_depth this won't catch circular dependencies that
2696 start deeper, but they'll hit the recursion or ops limit. */
2697 else if (entry->result == NULL)
2699 if (!ctx->quiet)
2700 error ("call has circular dependency");
2701 *non_constant_p = true;
2702 entry->result = result = error_mark_node;
2704 else
2705 result = entry->result;
2708 if (!depth_ok)
2710 if (!ctx->quiet)
2711 error ("%<constexpr%> evaluation depth exceeds maximum of %d (use "
2712 "%<-fconstexpr-depth=%> to increase the maximum)",
2713 max_constexpr_depth);
2714 *non_constant_p = true;
2715 result = error_mark_node;
2717 else
2719 bool cacheable = true;
2720 if (result && result != error_mark_node)
2721 /* OK */;
2722 else if (!DECL_SAVED_TREE (fun))
2724 /* When at_eof >= 2, cgraph has started throwing away
2725 DECL_SAVED_TREE, so fail quietly. FIXME we get here because of
2726 late code generation for VEC_INIT_EXPR, which needs to be
2727 completely reconsidered. */
2728 gcc_assert (at_eof >= 2 && ctx->quiet);
2729 *non_constant_p = true;
2731 else if (tree copy = get_fundef_copy (new_call.fundef))
2733 tree body, parms, res;
2734 releasing_vec ctors;
2736 /* Reuse or create a new unshared copy of this function's body. */
2737 body = TREE_PURPOSE (copy);
2738 parms = TREE_VALUE (copy);
2739 res = TREE_TYPE (copy);
2741 /* Associate the bindings with the remapped parms. */
2742 tree bound = new_call.bindings;
2743 tree remapped = parms;
2744 for (int i = 0; i < TREE_VEC_LENGTH (bound); ++i)
2746 tree arg = TREE_VEC_ELT (bound, i);
2747 if (entry)
2749 /* Unshare args going into the hash table to separate them
2750 from the caller's context, for better GC and to avoid
2751 problems with verify_gimple. */
2752 arg = unshare_expr_without_location (arg);
2753 TREE_VEC_ELT (bound, i) = arg;
2755 /* And then unshare again so the callee doesn't change the
2756 argument values in the hash table. XXX Could we unshare
2757 lazily in cxx_eval_store_expression? */
2758 arg = unshare_constructor (arg);
2759 if (TREE_CODE (arg) == CONSTRUCTOR)
2760 vec_safe_push (ctors, arg);
2762 ctx->global->values.put (remapped, arg);
2763 remapped = DECL_CHAIN (remapped);
2765 /* Add the RESULT_DECL to the values map, too. */
2766 gcc_assert (!DECL_BY_REFERENCE (res));
2767 ctx->global->values.put (res, NULL_TREE);
2769 /* Track the callee's evaluated SAVE_EXPRs and TARGET_EXPRs so that
2770 we can forget their values after the call. */
2771 constexpr_ctx ctx_with_save_exprs = *ctx;
2772 auto_vec<tree, 10> save_exprs;
2773 ctx_with_save_exprs.save_exprs = &save_exprs;
2774 ctx_with_save_exprs.call = &new_call;
2775 unsigned save_heap_alloc_count = ctx->global->heap_vars.length ();
2776 unsigned save_heap_dealloc_count = ctx->global->heap_dealloc_count;
2778 /* If this is a constexpr destructor, the object's const and volatile
2779 semantics are no longer in effect; see [class.dtor]p5. */
2780 if (new_obj && DECL_DESTRUCTOR_P (fun))
2781 cxx_set_object_constness (ctx, new_obj, /*readonly_p=*/false,
2782 non_constant_p, overflow_p);
2784 tree jump_target = NULL_TREE;
2785 cxx_eval_constant_expression (&ctx_with_save_exprs, body,
2786 lval, non_constant_p, overflow_p,
2787 &jump_target);
2789 if (DECL_CONSTRUCTOR_P (fun))
2790 /* This can be null for a subobject constructor call, in
2791 which case what we care about is the initialization
2792 side-effects rather than the value. We could get at the
2793 value by evaluating *this, but we don't bother; there's
2794 no need to put such a call in the hash table. */
2795 result = lval ? ctx->object : ctx->ctor;
2796 else if (VOID_TYPE_P (TREE_TYPE (res)))
2797 result = void_node;
2798 else
2800 result = *ctx->global->values.get (res);
2801 if (result == NULL_TREE && !*non_constant_p)
2803 if (!ctx->quiet)
2804 error ("%<constexpr%> call flows off the end "
2805 "of the function");
2806 *non_constant_p = true;
2810 /* At this point, the object's constructor will have run, so
2811 the object is no longer under construction, and its possible
2812 'const' semantics now apply. Make a note of this fact by
2813 marking the CONSTRUCTOR TREE_READONLY. */
2814 if (new_obj && DECL_CONSTRUCTOR_P (fun))
2815 cxx_set_object_constness (ctx, new_obj, /*readonly_p=*/true,
2816 non_constant_p, overflow_p);
2818 /* Forget the saved values of the callee's SAVE_EXPRs and
2819 TARGET_EXPRs. */
2820 for (tree save_expr : save_exprs)
2821 ctx->global->values.remove (save_expr);
2823 /* Remove the parms/result from the values map. Is it worth
2824 bothering to do this when the map itself is only live for
2825 one constexpr evaluation? If so, maybe also clear out
2826 other vars from call, maybe in BIND_EXPR handling? */
2827 ctx->global->values.remove (res);
2828 for (tree parm = parms; parm; parm = TREE_CHAIN (parm))
2829 ctx->global->values.remove (parm);
2831 /* Free any parameter CONSTRUCTORs we aren't returning directly. */
2832 while (!ctors->is_empty ())
2834 tree c = ctors->pop ();
2835 if (c != result)
2836 free_constructor (c);
2839 /* Make the unshared function copy we used available for re-use. */
2840 save_fundef_copy (fun, copy);
2842 /* If the call allocated some heap object that hasn't been
2843 deallocated during the call, or if it deallocated some heap
2844 object it has not allocated, the call isn't really stateless
2845 for the constexpr evaluation and should not be cached.
2846 It is fine if the call allocates something and deallocates it
2847 too. */
2848 if (entry
2849 && (save_heap_alloc_count != ctx->global->heap_vars.length ()
2850 || (save_heap_dealloc_count
2851 != ctx->global->heap_dealloc_count)))
2853 tree heap_var;
2854 unsigned int i;
2855 if ((ctx->global->heap_vars.length ()
2856 - ctx->global->heap_dealloc_count)
2857 != save_heap_alloc_count - save_heap_dealloc_count)
2858 cacheable = false;
2859 else
2860 FOR_EACH_VEC_ELT_FROM (ctx->global->heap_vars, i, heap_var,
2861 save_heap_alloc_count)
2862 if (DECL_NAME (heap_var) != heap_deleted_identifier)
2864 cacheable = false;
2865 break;
2869 /* Rewrite all occurrences of the function's RESULT_DECL with the
2870 current object under construction. */
2871 if (!*non_constant_p && ctx->object
2872 && CLASS_TYPE_P (TREE_TYPE (res))
2873 && !is_empty_class (TREE_TYPE (res)))
2874 if (replace_result_decl (&result, res, ctx->object))
2875 cacheable = false;
2877 else
2878 /* Couldn't get a function copy to evaluate. */
2879 *non_constant_p = true;
2881 if (result == error_mark_node)
2882 *non_constant_p = true;
2883 if (*non_constant_p || *overflow_p)
2884 result = error_mark_node;
2885 else if (!result)
2886 result = void_node;
2887 if (entry)
2888 entry->result = cacheable ? result : error_mark_node;
2891 /* The result of a constexpr function must be completely initialized.
2893 However, in C++20, a constexpr constructor doesn't necessarily have
2894 to initialize all the fields, so we don't clear CONSTRUCTOR_NO_CLEARING
2895 in order to detect reading an unitialized object in constexpr instead
2896 of value-initializing it. (reduced_constant_expression_p is expected to
2897 take care of clearing the flag.) */
2898 if (TREE_CODE (result) == CONSTRUCTOR
2899 && (cxx_dialect < cxx20
2900 || !DECL_CONSTRUCTOR_P (fun)))
2901 clear_no_implicit_zero (result);
2903 pop_cx_call_context ();
2904 return result;
2907 /* Return true if T is a valid constant initializer. If a CONSTRUCTOR
2908 initializes all the members, the CONSTRUCTOR_NO_CLEARING flag will be
2909 cleared.
2910 FIXME speed this up, it's taking 16% of compile time on sieve testcase. */
2912 bool
2913 reduced_constant_expression_p (tree t)
2915 if (t == NULL_TREE)
2916 return false;
2918 switch (TREE_CODE (t))
2920 case PTRMEM_CST:
2921 /* Even if we can't lower this yet, it's constant. */
2922 return true;
2924 case CONSTRUCTOR:
2925 /* And we need to handle PTRMEM_CST wrapped in a CONSTRUCTOR. */
2926 tree idx, val, field; unsigned HOST_WIDE_INT i;
2927 if (CONSTRUCTOR_NO_CLEARING (t))
2929 if (TREE_CODE (TREE_TYPE (t)) == VECTOR_TYPE)
2930 /* An initialized vector would have a VECTOR_CST. */
2931 return false;
2932 else if (cxx_dialect >= cxx20
2933 && TREE_CODE (TREE_TYPE (t)) == ARRAY_TYPE)
2935 /* There must be a valid constant initializer at every array
2936 index. */
2937 tree min = TYPE_MIN_VALUE (TYPE_DOMAIN (TREE_TYPE (t)));
2938 tree max = TYPE_MAX_VALUE (TYPE_DOMAIN (TREE_TYPE (t)));
2939 tree cursor = min;
2940 FOR_EACH_CONSTRUCTOR_ELT (CONSTRUCTOR_ELTS (t), i, idx, val)
2942 if (!reduced_constant_expression_p (val))
2943 return false;
2944 if (array_index_cmp (cursor, idx) != 0)
2945 return false;
2946 if (TREE_CODE (idx) == RANGE_EXPR)
2947 cursor = TREE_OPERAND (idx, 1);
2948 cursor = int_const_binop (PLUS_EXPR, cursor, size_one_node);
2950 if (find_array_ctor_elt (t, max) == -1)
2951 return false;
2952 goto ok;
2954 else if (cxx_dialect >= cxx20
2955 && TREE_CODE (TREE_TYPE (t)) == UNION_TYPE)
2957 if (CONSTRUCTOR_NELTS (t) == 0)
2958 /* An initialized union has a constructor element. */
2959 return false;
2960 /* And it only initializes one member. */
2961 field = NULL_TREE;
2963 else
2964 field = next_initializable_field (TYPE_FIELDS (TREE_TYPE (t)));
2966 else
2967 field = NULL_TREE;
2968 FOR_EACH_CONSTRUCTOR_ELT (CONSTRUCTOR_ELTS (t), i, idx, val)
2970 /* If VAL is null, we're in the middle of initializing this
2971 element. */
2972 if (!reduced_constant_expression_p (val))
2973 return false;
2974 /* Empty class field may or may not have an initializer. */
2975 for (; field && idx != field;
2976 field = next_initializable_field (DECL_CHAIN (field)))
2977 if (!is_really_empty_class (TREE_TYPE (field),
2978 /*ignore_vptr*/false))
2979 return false;
2980 if (field)
2981 field = next_initializable_field (DECL_CHAIN (field));
2983 /* There could be a non-empty field at the end. */
2984 for (; field; field = next_initializable_field (DECL_CHAIN (field)))
2985 if (!is_really_empty_class (TREE_TYPE (field), /*ignore_vptr*/false))
2986 return false;
2988 if (CONSTRUCTOR_NO_CLEARING (t))
2989 /* All the fields are initialized. */
2990 CONSTRUCTOR_NO_CLEARING (t) = false;
2991 return true;
2993 default:
2994 /* FIXME are we calling this too much? */
2995 return initializer_constant_valid_p (t, TREE_TYPE (t)) != NULL_TREE;
2999 /* Some expressions may have constant operands but are not constant
3000 themselves, such as 1/0. Call this function to check for that
3001 condition.
3003 We only call this in places that require an arithmetic constant, not in
3004 places where we might have a non-constant expression that can be a
3005 component of a constant expression, such as the address of a constexpr
3006 variable that might be dereferenced later. */
3008 static bool
3009 verify_constant (tree t, bool allow_non_constant, bool *non_constant_p,
3010 bool *overflow_p)
3012 if (!*non_constant_p && !reduced_constant_expression_p (t)
3013 && t != void_node)
3015 if (!allow_non_constant)
3016 error ("%q+E is not a constant expression", t);
3017 *non_constant_p = true;
3019 if (TREE_OVERFLOW_P (t))
3021 if (!allow_non_constant)
3023 permerror (input_location, "overflow in constant expression");
3024 /* If we're being permissive (and are in an enforcing
3025 context), ignore the overflow. */
3026 if (flag_permissive)
3027 return *non_constant_p;
3029 *overflow_p = true;
3031 return *non_constant_p;
3034 /* Check whether the shift operation with code CODE and type TYPE on LHS
3035 and RHS is undefined. If it is, give an error with an explanation,
3036 and return true; return false otherwise. */
3038 static bool
3039 cxx_eval_check_shift_p (location_t loc, const constexpr_ctx *ctx,
3040 enum tree_code code, tree type, tree lhs, tree rhs)
3042 if ((code != LSHIFT_EXPR && code != RSHIFT_EXPR)
3043 || TREE_CODE (lhs) != INTEGER_CST
3044 || TREE_CODE (rhs) != INTEGER_CST)
3045 return false;
3047 tree lhstype = TREE_TYPE (lhs);
3048 unsigned HOST_WIDE_INT uprec = TYPE_PRECISION (TREE_TYPE (lhs));
3050 /* [expr.shift] The behavior is undefined if the right operand
3051 is negative, or greater than or equal to the length in bits
3052 of the promoted left operand. */
3053 if (tree_int_cst_sgn (rhs) == -1)
3055 if (!ctx->quiet)
3056 permerror (loc, "right operand of shift expression %q+E is negative",
3057 build2_loc (loc, code, type, lhs, rhs));
3058 return (!flag_permissive || ctx->quiet);
3060 if (compare_tree_int (rhs, uprec) >= 0)
3062 if (!ctx->quiet)
3063 permerror (loc, "right operand of shift expression %q+E is greater "
3064 "than or equal to the precision %wu of the left operand",
3065 build2_loc (loc, code, type, lhs, rhs), uprec);
3066 return (!flag_permissive || ctx->quiet);
3069 /* The value of E1 << E2 is E1 left-shifted E2 bit positions; [...]
3070 if E1 has a signed type and non-negative value, and E1x2^E2 is
3071 representable in the corresponding unsigned type of the result type,
3072 then that value, converted to the result type, is the resulting value;
3073 otherwise, the behavior is undefined.
3074 For C++20:
3075 The value of E1 << E2 is the unique value congruent to E1 x 2^E2 modulo
3076 2^N, where N is the range exponent of the type of the result. */
3077 if (code == LSHIFT_EXPR
3078 && !TYPE_UNSIGNED (lhstype)
3079 && cxx_dialect >= cxx11
3080 && cxx_dialect < cxx20)
3082 if (tree_int_cst_sgn (lhs) == -1)
3084 if (!ctx->quiet)
3085 permerror (loc,
3086 "left operand of shift expression %q+E is negative",
3087 build2_loc (loc, code, type, lhs, rhs));
3088 return (!flag_permissive || ctx->quiet);
3090 /* For signed x << y the following:
3091 (unsigned) x >> ((prec (lhs) - 1) - y)
3092 if > 1, is undefined. The right-hand side of this formula
3093 is the highest bit of the LHS that can be set (starting from 0),
3094 so that the shift doesn't overflow. We then right-shift the LHS
3095 to see whether any other bit is set making the original shift
3096 undefined -- the result is not representable in the corresponding
3097 unsigned type. */
3098 tree t = build_int_cst (unsigned_type_node, uprec - 1);
3099 t = fold_build2 (MINUS_EXPR, unsigned_type_node, t, rhs);
3100 tree ulhs = fold_convert (unsigned_type_for (lhstype), lhs);
3101 t = fold_build2 (RSHIFT_EXPR, TREE_TYPE (ulhs), ulhs, t);
3102 if (tree_int_cst_lt (integer_one_node, t))
3104 if (!ctx->quiet)
3105 permerror (loc, "shift expression %q+E overflows",
3106 build2_loc (loc, code, type, lhs, rhs));
3107 return (!flag_permissive || ctx->quiet);
3110 return false;
3113 /* Subroutine of cxx_eval_constant_expression.
3114 Attempt to reduce the unary expression tree T to a compile time value.
3115 If successful, return the value. Otherwise issue a diagnostic
3116 and return error_mark_node. */
3118 static tree
3119 cxx_eval_unary_expression (const constexpr_ctx *ctx, tree t,
3120 bool /*lval*/,
3121 bool *non_constant_p, bool *overflow_p)
3123 tree r;
3124 tree orig_arg = TREE_OPERAND (t, 0);
3125 tree arg = cxx_eval_constant_expression (ctx, orig_arg, /*lval*/false,
3126 non_constant_p, overflow_p);
3127 VERIFY_CONSTANT (arg);
3128 location_t loc = EXPR_LOCATION (t);
3129 enum tree_code code = TREE_CODE (t);
3130 tree type = TREE_TYPE (t);
3131 r = fold_unary_loc (loc, code, type, arg);
3132 if (r == NULL_TREE)
3134 if (arg == orig_arg)
3135 r = t;
3136 else
3137 r = build1_loc (loc, code, type, arg);
3139 VERIFY_CONSTANT (r);
3140 return r;
3143 /* Helper function for cxx_eval_binary_expression. Try to optimize
3144 original POINTER_PLUS_EXPR T, LHS p+ RHS, return NULL_TREE if the
3145 generic folding should be used. */
3147 static tree
3148 cxx_fold_pointer_plus_expression (const constexpr_ctx *ctx, tree t,
3149 tree lhs, tree rhs, bool *non_constant_p,
3150 bool *overflow_p)
3152 STRIP_NOPS (lhs);
3153 if (TREE_CODE (lhs) != ADDR_EXPR)
3154 return NULL_TREE;
3156 lhs = TREE_OPERAND (lhs, 0);
3158 /* &A[i] p+ j => &A[i + j] */
3159 if (TREE_CODE (lhs) == ARRAY_REF
3160 && TREE_CODE (TREE_OPERAND (lhs, 1)) == INTEGER_CST
3161 && TREE_CODE (rhs) == INTEGER_CST
3162 && TYPE_SIZE_UNIT (TREE_TYPE (lhs))
3163 && TREE_CODE (TYPE_SIZE_UNIT (TREE_TYPE (lhs))) == INTEGER_CST)
3165 tree orig_type = TREE_TYPE (t);
3166 location_t loc = EXPR_LOCATION (t);
3167 tree type = TREE_TYPE (lhs);
3169 t = fold_convert_loc (loc, ssizetype, TREE_OPERAND (lhs, 1));
3170 tree nelts = array_type_nelts_top (TREE_TYPE (TREE_OPERAND (lhs, 0)));
3171 nelts = cxx_eval_constant_expression (ctx, nelts, false, non_constant_p,
3172 overflow_p);
3173 if (*non_constant_p)
3174 return NULL_TREE;
3175 /* Don't fold an out-of-bound access. */
3176 if (!tree_int_cst_le (t, nelts))
3177 return NULL_TREE;
3178 rhs = cp_fold_convert (ssizetype, rhs);
3179 /* Don't fold if rhs can't be divided exactly by TYPE_SIZE_UNIT.
3180 constexpr int A[1]; ... (char *)&A[0] + 1 */
3181 if (!integer_zerop (fold_build2_loc (loc, TRUNC_MOD_EXPR, sizetype,
3182 rhs, TYPE_SIZE_UNIT (type))))
3183 return NULL_TREE;
3184 /* Make sure to treat the second operand of POINTER_PLUS_EXPR
3185 as signed. */
3186 rhs = fold_build2_loc (loc, EXACT_DIV_EXPR, ssizetype, rhs,
3187 TYPE_SIZE_UNIT (type));
3188 t = size_binop_loc (loc, PLUS_EXPR, rhs, t);
3189 t = build4_loc (loc, ARRAY_REF, type, TREE_OPERAND (lhs, 0),
3190 t, NULL_TREE, NULL_TREE);
3191 t = cp_build_addr_expr (t, tf_warning_or_error);
3192 t = cp_fold_convert (orig_type, t);
3193 return cxx_eval_constant_expression (ctx, t, /*lval*/false,
3194 non_constant_p, overflow_p);
3197 return NULL_TREE;
3200 /* Subroutine of cxx_eval_constant_expression.
3201 Like cxx_eval_unary_expression, except for binary expressions. */
3203 static tree
3204 cxx_eval_binary_expression (const constexpr_ctx *ctx, tree t,
3205 bool lval,
3206 bool *non_constant_p, bool *overflow_p)
3208 tree r = NULL_TREE;
3209 tree orig_lhs = TREE_OPERAND (t, 0);
3210 tree orig_rhs = TREE_OPERAND (t, 1);
3211 tree lhs, rhs;
3212 lhs = cxx_eval_constant_expression (ctx, orig_lhs, /*lval*/false,
3213 non_constant_p, overflow_p);
3214 /* Don't VERIFY_CONSTANT here, it's unnecessary and will break pointer
3215 subtraction. */
3216 if (*non_constant_p)
3217 return t;
3218 rhs = cxx_eval_constant_expression (ctx, orig_rhs, /*lval*/false,
3219 non_constant_p, overflow_p);
3220 if (*non_constant_p)
3221 return t;
3223 location_t loc = EXPR_LOCATION (t);
3224 enum tree_code code = TREE_CODE (t);
3225 tree type = TREE_TYPE (t);
3227 if (code == EQ_EXPR || code == NE_EXPR)
3229 bool is_code_eq = (code == EQ_EXPR);
3231 if (TREE_CODE (lhs) == PTRMEM_CST
3232 && TREE_CODE (rhs) == PTRMEM_CST)
3234 tree lmem = PTRMEM_CST_MEMBER (lhs);
3235 tree rmem = PTRMEM_CST_MEMBER (rhs);
3236 bool eq;
3237 if (TREE_CODE (lmem) == TREE_CODE (rmem)
3238 && TREE_CODE (lmem) == FIELD_DECL
3239 && TREE_CODE (DECL_CONTEXT (lmem)) == UNION_TYPE
3240 && same_type_p (DECL_CONTEXT (lmem),
3241 DECL_CONTEXT (rmem)))
3242 /* If both refer to (possibly different) members of the same union
3243 (12.3), they compare equal. */
3244 eq = true;
3245 else
3246 eq = cp_tree_equal (lhs, rhs);
3247 r = constant_boolean_node (eq == is_code_eq, type);
3249 else if ((TREE_CODE (lhs) == PTRMEM_CST
3250 || TREE_CODE (rhs) == PTRMEM_CST)
3251 && (null_member_pointer_value_p (lhs)
3252 || null_member_pointer_value_p (rhs)))
3253 r = constant_boolean_node (!is_code_eq, type);
3254 else if (TREE_CODE (lhs) == PTRMEM_CST)
3255 lhs = cplus_expand_constant (lhs);
3256 else if (TREE_CODE (rhs) == PTRMEM_CST)
3257 rhs = cplus_expand_constant (rhs);
3259 if (code == POINTER_PLUS_EXPR && !*non_constant_p
3260 && integer_zerop (lhs) && !integer_zerop (rhs))
3262 if (!ctx->quiet)
3263 error ("arithmetic involving a null pointer in %qE", lhs);
3264 *non_constant_p = true;
3265 return t;
3267 else if (code == POINTER_PLUS_EXPR)
3268 r = cxx_fold_pointer_plus_expression (ctx, t, lhs, rhs, non_constant_p,
3269 overflow_p);
3270 else if (code == SPACESHIP_EXPR)
3272 r = genericize_spaceship (loc, type, lhs, rhs);
3273 return cxx_eval_constant_expression (ctx, r, lval, non_constant_p,
3274 overflow_p);
3277 if (r == NULL_TREE)
3278 r = fold_binary_loc (loc, code, type, lhs, rhs);
3280 if (r == NULL_TREE
3281 && (code == LSHIFT_EXPR || code == RSHIFT_EXPR)
3282 && TREE_CODE (lhs) == INTEGER_CST
3283 && TREE_CODE (rhs) == INTEGER_CST
3284 && wi::neg_p (wi::to_wide (rhs)))
3286 /* For diagnostics and -fpermissive emulate previous behavior of
3287 handling shifts by negative amount. */
3288 tree nrhs = const_unop (NEGATE_EXPR, TREE_TYPE (rhs), rhs);
3289 if (nrhs)
3290 r = fold_binary_loc (loc,
3291 code == LSHIFT_EXPR ? RSHIFT_EXPR : LSHIFT_EXPR,
3292 type, lhs, nrhs);
3295 if (r == NULL_TREE)
3297 if (lhs == orig_lhs && rhs == orig_rhs)
3298 r = t;
3299 else
3300 r = build2_loc (loc, code, type, lhs, rhs);
3302 else if (cxx_eval_check_shift_p (loc, ctx, code, type, lhs, rhs))
3303 *non_constant_p = true;
3304 /* Don't VERIFY_CONSTANT if this might be dealing with a pointer to
3305 a local array in a constexpr function. */
3306 bool ptr = INDIRECT_TYPE_P (TREE_TYPE (lhs));
3307 if (!ptr)
3308 VERIFY_CONSTANT (r);
3309 return r;
3312 /* Subroutine of cxx_eval_constant_expression.
3313 Attempt to evaluate condition expressions. Dead branches are not
3314 looked into. */
3316 static tree
3317 cxx_eval_conditional_expression (const constexpr_ctx *ctx, tree t,
3318 bool lval,
3319 bool *non_constant_p, bool *overflow_p,
3320 tree *jump_target)
3322 tree val = cxx_eval_constant_expression (ctx, TREE_OPERAND (t, 0),
3323 /*lval*/false,
3324 non_constant_p, overflow_p);
3325 VERIFY_CONSTANT (val);
3326 if (TREE_CODE (t) == IF_STMT && IF_STMT_CONSTEVAL_P (t))
3328 /* Evaluate the condition as if it was
3329 if (__builtin_is_constant_evaluated ()), i.e. defer it if not
3330 ctx->manifestly_const_eval (as sometimes we try to constant evaluate
3331 without manifestly_const_eval even expressions or parts thereof which
3332 will later be manifestly const_eval evaluated), otherwise fold it to
3333 true. */
3334 if (ctx->manifestly_const_eval)
3335 val = boolean_true_node;
3336 else
3338 *non_constant_p = true;
3339 return t;
3342 /* Don't VERIFY_CONSTANT the other operands. */
3343 if (integer_zerop (val))
3344 val = TREE_OPERAND (t, 2);
3345 else
3346 val = TREE_OPERAND (t, 1);
3347 if (TREE_CODE (t) == IF_STMT && !val)
3348 val = void_node;
3349 return cxx_eval_constant_expression (ctx, val, lval, non_constant_p,
3350 overflow_p, jump_target);
3353 /* Subroutine of cxx_eval_constant_expression.
3354 Attempt to evaluate vector condition expressions. Unlike
3355 cxx_eval_conditional_expression, VEC_COND_EXPR acts like a normal
3356 ternary arithmetics operation, where all 3 arguments have to be
3357 evaluated as constants and then folding computes the result from
3358 them. */
3360 static tree
3361 cxx_eval_vector_conditional_expression (const constexpr_ctx *ctx, tree t,
3362 bool *non_constant_p, bool *overflow_p)
3364 tree arg1 = cxx_eval_constant_expression (ctx, TREE_OPERAND (t, 0),
3365 /*lval*/false,
3366 non_constant_p, overflow_p);
3367 VERIFY_CONSTANT (arg1);
3368 tree arg2 = cxx_eval_constant_expression (ctx, TREE_OPERAND (t, 1),
3369 /*lval*/false,
3370 non_constant_p, overflow_p);
3371 VERIFY_CONSTANT (arg2);
3372 tree arg3 = cxx_eval_constant_expression (ctx, TREE_OPERAND (t, 2),
3373 /*lval*/false,
3374 non_constant_p, overflow_p);
3375 VERIFY_CONSTANT (arg3);
3376 location_t loc = EXPR_LOCATION (t);
3377 tree type = TREE_TYPE (t);
3378 tree r = fold_ternary_loc (loc, VEC_COND_EXPR, type, arg1, arg2, arg3);
3379 if (r == NULL_TREE)
3381 if (arg1 == TREE_OPERAND (t, 0)
3382 && arg2 == TREE_OPERAND (t, 1)
3383 && arg3 == TREE_OPERAND (t, 2))
3384 r = t;
3385 else
3386 r = build3_loc (loc, VEC_COND_EXPR, type, arg1, arg2, arg3);
3388 VERIFY_CONSTANT (r);
3389 return r;
3392 /* Returns less than, equal to, or greater than zero if KEY is found to be
3393 less than, to match, or to be greater than the constructor_elt's INDEX. */
3395 static int
3396 array_index_cmp (tree key, tree index)
3398 gcc_assert (TREE_CODE (key) == INTEGER_CST);
3400 switch (TREE_CODE (index))
3402 case INTEGER_CST:
3403 return tree_int_cst_compare (key, index);
3404 case RANGE_EXPR:
3406 tree lo = TREE_OPERAND (index, 0);
3407 tree hi = TREE_OPERAND (index, 1);
3408 if (tree_int_cst_lt (key, lo))
3409 return -1;
3410 else if (tree_int_cst_lt (hi, key))
3411 return 1;
3412 else
3413 return 0;
3415 default:
3416 gcc_unreachable ();
3420 /* Returns the index of the constructor_elt of ARY which matches DINDEX, or -1
3421 if none. If INSERT is true, insert a matching element rather than fail. */
3423 static HOST_WIDE_INT
3424 find_array_ctor_elt (tree ary, tree dindex, bool insert)
3426 if (tree_int_cst_sgn (dindex) < 0)
3427 return -1;
3429 unsigned HOST_WIDE_INT i = tree_to_uhwi (dindex);
3430 vec<constructor_elt, va_gc> *elts = CONSTRUCTOR_ELTS (ary);
3431 unsigned HOST_WIDE_INT len = vec_safe_length (elts);
3433 unsigned HOST_WIDE_INT end = len;
3434 unsigned HOST_WIDE_INT begin = 0;
3436 /* If the last element of the CONSTRUCTOR has its own index, we can assume
3437 that the same is true of the other elements and index directly. */
3438 if (end > 0)
3440 tree cindex = (*elts)[end - 1].index;
3441 if (cindex == NULL_TREE)
3443 /* Verify that if the last index is missing, all indexes
3444 are missing. */
3445 if (flag_checking)
3446 for (unsigned int j = 0; j < len - 1; ++j)
3447 gcc_assert ((*elts)[j].index == NULL_TREE);
3448 if (i < end)
3449 return i;
3450 else
3452 begin = end;
3453 if (i == end)
3454 /* If the element is to be added right at the end,
3455 make sure it is added with cleared index too. */
3456 dindex = NULL_TREE;
3457 else if (insert)
3458 /* Otherwise, in order not to break the assumption
3459 that CONSTRUCTOR either has all indexes or none,
3460 we need to add indexes to all elements. */
3461 for (unsigned int j = 0; j < len; ++j)
3462 (*elts)[j].index = build_int_cst (TREE_TYPE (dindex), j);
3465 else if (TREE_CODE (cindex) == INTEGER_CST
3466 && compare_tree_int (cindex, end - 1) == 0)
3468 if (i < end)
3469 return i;
3470 else
3471 begin = end;
3475 /* Otherwise, find a matching index by means of a binary search. */
3476 while (begin != end)
3478 unsigned HOST_WIDE_INT middle = (begin + end) / 2;
3479 constructor_elt &elt = (*elts)[middle];
3480 tree idx = elt.index;
3482 int cmp = array_index_cmp (dindex, idx);
3483 if (cmp < 0)
3484 end = middle;
3485 else if (cmp > 0)
3486 begin = middle + 1;
3487 else
3489 if (insert && TREE_CODE (idx) == RANGE_EXPR)
3491 /* We need to split the range. */
3492 constructor_elt e;
3493 tree lo = TREE_OPERAND (idx, 0);
3494 tree hi = TREE_OPERAND (idx, 1);
3495 tree value = elt.value;
3496 dindex = fold_convert (sizetype, dindex);
3497 if (tree_int_cst_lt (lo, dindex))
3499 /* There are still some lower elts; shorten the range. */
3500 tree new_hi = int_const_binop (MINUS_EXPR, dindex,
3501 size_one_node);
3502 if (tree_int_cst_equal (lo, new_hi))
3503 /* Only one element left, no longer a range. */
3504 elt.index = lo;
3505 else
3506 TREE_OPERAND (idx, 1) = new_hi;
3507 /* Append the element we want to insert. */
3508 ++middle;
3509 e.index = dindex;
3510 e.value = unshare_constructor (value);
3511 vec_safe_insert (CONSTRUCTOR_ELTS (ary), middle, e);
3513 else
3514 /* No lower elts, the range elt is now ours. */
3515 elt.index = dindex;
3517 if (tree_int_cst_lt (dindex, hi))
3519 /* There are still some higher elts; append a range. */
3520 tree new_lo = int_const_binop (PLUS_EXPR, dindex,
3521 size_one_node);
3522 if (tree_int_cst_equal (new_lo, hi))
3523 e.index = hi;
3524 else
3525 e.index = build2 (RANGE_EXPR, sizetype, new_lo, hi);
3526 e.value = unshare_constructor (value);
3527 vec_safe_insert (CONSTRUCTOR_ELTS (ary), middle + 1, e);
3530 return middle;
3534 if (insert)
3536 constructor_elt e = { dindex, NULL_TREE };
3537 vec_safe_insert (CONSTRUCTOR_ELTS (ary), end, e);
3538 return end;
3541 return -1;
3544 /* Return a pointer to the constructor_elt of CTOR which matches INDEX. If no
3545 matching constructor_elt exists, then add one to CTOR.
3547 As an optimization, if POS_HINT is non-negative then it is used as a guess
3548 for the (integer) index of the matching constructor_elt within CTOR. */
3550 static constructor_elt *
3551 get_or_insert_ctor_field (tree ctor, tree index, int pos_hint = -1)
3553 /* Check the hint first. */
3554 if (pos_hint >= 0 && (unsigned)pos_hint < CONSTRUCTOR_NELTS (ctor)
3555 && CONSTRUCTOR_ELT (ctor, pos_hint)->index == index)
3556 return CONSTRUCTOR_ELT (ctor, pos_hint);
3558 tree type = TREE_TYPE (ctor);
3559 if (TREE_CODE (type) == VECTOR_TYPE && index == NULL_TREE)
3561 CONSTRUCTOR_APPEND_ELT (CONSTRUCTOR_ELTS (ctor), index, NULL_TREE);
3562 return &CONSTRUCTOR_ELTS (ctor)->last();
3564 else if (TREE_CODE (type) == ARRAY_TYPE || TREE_CODE (type) == VECTOR_TYPE)
3566 if (TREE_CODE (index) == RANGE_EXPR)
3568 /* Support for RANGE_EXPR index lookups is currently limited to
3569 accessing an existing element via POS_HINT, or appending a new
3570 element to the end of CTOR. ??? Support for other access
3571 patterns may also be needed. */
3572 vec<constructor_elt, va_gc> *elts = CONSTRUCTOR_ELTS (ctor);
3573 if (vec_safe_length (elts))
3575 tree lo = TREE_OPERAND (index, 0);
3576 gcc_assert (array_index_cmp (elts->last().index, lo) < 0);
3578 CONSTRUCTOR_APPEND_ELT (elts, index, NULL_TREE);
3579 return &elts->last();
3582 HOST_WIDE_INT i = find_array_ctor_elt (ctor, index, /*insert*/true);
3583 gcc_assert (i >= 0);
3584 constructor_elt *cep = CONSTRUCTOR_ELT (ctor, i);
3585 gcc_assert (cep->index == NULL_TREE
3586 || TREE_CODE (cep->index) != RANGE_EXPR);
3587 return cep;
3589 else
3591 gcc_assert (TREE_CODE (index) == FIELD_DECL
3592 && (same_type_ignoring_top_level_qualifiers_p
3593 (DECL_CONTEXT (index), TREE_TYPE (ctor))));
3595 /* We must keep the CONSTRUCTOR's ELTS in FIELD order.
3596 Usually we meet initializers in that order, but it is
3597 possible for base types to be placed not in program
3598 order. */
3599 tree fields = TYPE_FIELDS (DECL_CONTEXT (index));
3600 unsigned HOST_WIDE_INT idx = 0;
3601 constructor_elt *cep = NULL;
3603 /* Check if we're changing the active member of a union. */
3604 if (TREE_CODE (type) == UNION_TYPE && CONSTRUCTOR_NELTS (ctor)
3605 && CONSTRUCTOR_ELT (ctor, 0)->index != index)
3606 vec_safe_truncate (CONSTRUCTOR_ELTS (ctor), 0);
3607 /* If the bit offset of INDEX is larger than that of the last
3608 constructor_elt, then we can just immediately append a new
3609 constructor_elt to the end of CTOR. */
3610 else if (CONSTRUCTOR_NELTS (ctor)
3611 && tree_int_cst_compare (bit_position (index),
3612 bit_position (CONSTRUCTOR_ELTS (ctor)
3613 ->last().index)) > 0)
3615 idx = CONSTRUCTOR_NELTS (ctor);
3616 goto insert;
3619 /* Otherwise, we need to iterate over CTOR to find or insert INDEX
3620 appropriately. */
3622 for (; vec_safe_iterate (CONSTRUCTOR_ELTS (ctor), idx, &cep);
3623 idx++, fields = DECL_CHAIN (fields))
3625 if (index == cep->index)
3626 goto found;
3628 /* The field we're initializing must be on the field
3629 list. Look to see if it is present before the
3630 field the current ELT initializes. */
3631 for (; fields != cep->index; fields = DECL_CHAIN (fields))
3632 if (index == fields)
3633 goto insert;
3635 /* We fell off the end of the CONSTRUCTOR, so insert a new
3636 entry at the end. */
3638 insert:
3640 constructor_elt ce = { index, NULL_TREE };
3642 vec_safe_insert (CONSTRUCTOR_ELTS (ctor), idx, ce);
3643 cep = CONSTRUCTOR_ELT (ctor, idx);
3645 found:;
3647 return cep;
3651 /* Under the control of CTX, issue a detailed diagnostic for
3652 an out-of-bounds subscript INDEX into the expression ARRAY. */
3654 static void
3655 diag_array_subscript (location_t loc, const constexpr_ctx *ctx, tree array, tree index)
3657 if (!ctx->quiet)
3659 tree arraytype = TREE_TYPE (array);
3661 /* Convert the unsigned array subscript to a signed integer to avoid
3662 printing huge numbers for small negative values. */
3663 tree sidx = fold_convert (ssizetype, index);
3664 STRIP_ANY_LOCATION_WRAPPER (array);
3665 if (DECL_P (array))
3667 if (TYPE_DOMAIN (arraytype))
3668 error_at (loc, "array subscript value %qE is outside the bounds "
3669 "of array %qD of type %qT", sidx, array, arraytype);
3670 else
3671 error_at (loc, "nonzero array subscript %qE is used with array %qD of "
3672 "type %qT with unknown bounds", sidx, array, arraytype);
3673 inform (DECL_SOURCE_LOCATION (array), "declared here");
3675 else if (TYPE_DOMAIN (arraytype))
3676 error_at (loc, "array subscript value %qE is outside the bounds "
3677 "of array type %qT", sidx, arraytype);
3678 else
3679 error_at (loc, "nonzero array subscript %qE is used with array of type %qT "
3680 "with unknown bounds", sidx, arraytype);
3684 /* Return the number of elements for TYPE (which is an ARRAY_TYPE or
3685 a VECTOR_TYPE). */
3687 static tree
3688 get_array_or_vector_nelts (const constexpr_ctx *ctx, tree type,
3689 bool *non_constant_p, bool *overflow_p)
3691 tree nelts;
3692 if (TREE_CODE (type) == ARRAY_TYPE)
3694 if (TYPE_DOMAIN (type))
3695 nelts = array_type_nelts_top (type);
3696 else
3697 nelts = size_zero_node;
3699 else if (VECTOR_TYPE_P (type))
3700 nelts = size_int (TYPE_VECTOR_SUBPARTS (type));
3701 else
3702 gcc_unreachable ();
3704 /* For VLAs, the number of elements won't be an integer constant. */
3705 nelts = cxx_eval_constant_expression (ctx, nelts, false,
3706 non_constant_p, overflow_p);
3707 return nelts;
3710 /* Extract element INDEX consisting of CHARS_PER_ELT chars from
3711 STRING_CST STRING. */
3713 static tree
3714 extract_string_elt (tree string, unsigned chars_per_elt, unsigned index)
3716 tree type = cv_unqualified (TREE_TYPE (TREE_TYPE (string)));
3717 tree r;
3719 if (chars_per_elt == 1)
3720 r = build_int_cst (type, TREE_STRING_POINTER (string)[index]);
3721 else
3723 const unsigned char *ptr
3724 = ((const unsigned char *)TREE_STRING_POINTER (string)
3725 + index * chars_per_elt);
3726 r = native_interpret_expr (type, ptr, chars_per_elt);
3728 return r;
3731 /* Subroutine of cxx_eval_array_reference. T is an ARRAY_REF; evaluate the
3732 subscript, diagnose any problems with it, and return the result. */
3734 static tree
3735 eval_and_check_array_index (const constexpr_ctx *ctx,
3736 tree t, bool allow_one_past,
3737 bool *non_constant_p, bool *overflow_p)
3739 location_t loc = cp_expr_loc_or_input_loc (t);
3740 tree ary = TREE_OPERAND (t, 0);
3741 t = TREE_OPERAND (t, 1);
3742 tree index = cxx_eval_constant_expression (ctx, t, false,
3743 non_constant_p, overflow_p);
3744 VERIFY_CONSTANT (index);
3746 if (!tree_fits_shwi_p (index)
3747 || tree_int_cst_sgn (index) < 0)
3749 diag_array_subscript (loc, ctx, ary, index);
3750 *non_constant_p = true;
3751 return t;
3754 tree nelts = get_array_or_vector_nelts (ctx, TREE_TYPE (ary), non_constant_p,
3755 overflow_p);
3756 VERIFY_CONSTANT (nelts);
3757 if (allow_one_past
3758 ? !tree_int_cst_le (index, nelts)
3759 : !tree_int_cst_lt (index, nelts))
3761 diag_array_subscript (loc, ctx, ary, index);
3762 *non_constant_p = true;
3763 return t;
3766 return index;
3769 /* Subroutine of cxx_eval_constant_expression.
3770 Attempt to reduce a reference to an array slot. */
3772 static tree
3773 cxx_eval_array_reference (const constexpr_ctx *ctx, tree t,
3774 bool lval,
3775 bool *non_constant_p, bool *overflow_p)
3777 tree oldary = TREE_OPERAND (t, 0);
3778 tree ary = cxx_eval_constant_expression (ctx, oldary,
3779 lval,
3780 non_constant_p, overflow_p);
3781 if (*non_constant_p)
3782 return t;
3783 if (!lval
3784 && TREE_CODE (ary) == VIEW_CONVERT_EXPR
3785 && VECTOR_TYPE_P (TREE_TYPE (TREE_OPERAND (ary, 0)))
3786 && TREE_TYPE (t) == TREE_TYPE (TREE_TYPE (TREE_OPERAND (ary, 0))))
3787 ary = TREE_OPERAND (ary, 0);
3789 tree oldidx = TREE_OPERAND (t, 1);
3790 tree index = eval_and_check_array_index (ctx, t, lval,
3791 non_constant_p, overflow_p);
3792 if (*non_constant_p)
3793 return t;
3795 if (lval && ary == oldary && index == oldidx)
3796 return t;
3797 else if (lval)
3798 return build4 (ARRAY_REF, TREE_TYPE (t), ary, index, NULL, NULL);
3800 unsigned len = 0, elem_nchars = 1;
3801 tree elem_type = TREE_TYPE (TREE_TYPE (ary));
3802 if (TREE_CODE (ary) == CONSTRUCTOR)
3803 len = CONSTRUCTOR_NELTS (ary);
3804 else if (TREE_CODE (ary) == STRING_CST)
3806 elem_nchars = (TYPE_PRECISION (elem_type)
3807 / TYPE_PRECISION (char_type_node));
3808 len = (unsigned) TREE_STRING_LENGTH (ary) / elem_nchars;
3810 else if (TREE_CODE (ary) == VECTOR_CST)
3811 /* We don't create variable-length VECTOR_CSTs. */
3812 len = VECTOR_CST_NELTS (ary).to_constant ();
3813 else
3815 /* We can't do anything with other tree codes, so use
3816 VERIFY_CONSTANT to complain and fail. */
3817 VERIFY_CONSTANT (ary);
3818 gcc_unreachable ();
3821 bool found;
3822 HOST_WIDE_INT i = 0;
3823 if (TREE_CODE (ary) == CONSTRUCTOR)
3825 HOST_WIDE_INT ix = find_array_ctor_elt (ary, index);
3826 found = (ix >= 0);
3827 if (found)
3828 i = ix;
3830 else
3832 i = tree_to_shwi (index);
3833 found = (i < len);
3836 if (found)
3838 tree r;
3839 if (TREE_CODE (ary) == CONSTRUCTOR)
3840 r = (*CONSTRUCTOR_ELTS (ary))[i].value;
3841 else if (TREE_CODE (ary) == VECTOR_CST)
3842 r = VECTOR_CST_ELT (ary, i);
3843 else
3844 r = extract_string_elt (ary, elem_nchars, i);
3846 if (r)
3847 /* Don't VERIFY_CONSTANT here. */
3848 return r;
3850 /* Otherwise the element doesn't have a value yet. */
3853 /* Not found. */
3855 if (TREE_CODE (ary) == CONSTRUCTOR
3856 && CONSTRUCTOR_NO_CLEARING (ary))
3858 /* 'ary' is part of the aggregate initializer we're currently
3859 building; if there's no initializer for this element yet,
3860 that's an error. */
3861 if (!ctx->quiet)
3862 error ("accessing uninitialized array element");
3863 *non_constant_p = true;
3864 return t;
3867 /* If it's within the array bounds but doesn't have an explicit
3868 initializer, it's initialized from {}. But use build_value_init
3869 directly for non-aggregates to avoid creating a garbage CONSTRUCTOR. */
3870 tree val;
3871 constexpr_ctx new_ctx;
3872 if (is_really_empty_class (elem_type, /*ignore_vptr*/false))
3873 return build_constructor (elem_type, NULL);
3874 else if (CP_AGGREGATE_TYPE_P (elem_type))
3876 tree empty_ctor = build_constructor (init_list_type_node, NULL);
3877 val = digest_init (elem_type, empty_ctor, tf_warning_or_error);
3879 else
3880 val = build_value_init (elem_type, tf_warning_or_error);
3882 if (!SCALAR_TYPE_P (elem_type))
3884 new_ctx = *ctx;
3885 if (ctx->object)
3886 /* If there was no object, don't add one: it could confuse us
3887 into thinking we're modifying a const object. */
3888 new_ctx.object = t;
3889 new_ctx.ctor = build_constructor (elem_type, NULL);
3890 ctx = &new_ctx;
3892 t = cxx_eval_constant_expression (ctx, val, lval, non_constant_p,
3893 overflow_p);
3894 if (!SCALAR_TYPE_P (elem_type) && t != ctx->ctor)
3895 free_constructor (ctx->ctor);
3896 return t;
3899 /* Subroutine of cxx_eval_constant_expression.
3900 Attempt to reduce a field access of a value of class type. */
3902 static tree
3903 cxx_eval_component_reference (const constexpr_ctx *ctx, tree t,
3904 bool lval,
3905 bool *non_constant_p, bool *overflow_p)
3907 unsigned HOST_WIDE_INT i;
3908 tree field;
3909 tree value;
3910 tree part = TREE_OPERAND (t, 1);
3911 tree orig_whole = TREE_OPERAND (t, 0);
3912 tree whole = cxx_eval_constant_expression (ctx, orig_whole,
3913 lval,
3914 non_constant_p, overflow_p);
3915 if (INDIRECT_REF_P (whole)
3916 && integer_zerop (TREE_OPERAND (whole, 0)))
3918 if (!ctx->quiet)
3919 error ("dereferencing a null pointer in %qE", orig_whole);
3920 *non_constant_p = true;
3921 return t;
3924 if (TREE_CODE (whole) == PTRMEM_CST)
3925 whole = cplus_expand_constant (whole);
3926 if (whole == orig_whole)
3927 return t;
3928 if (lval)
3929 return fold_build3 (COMPONENT_REF, TREE_TYPE (t),
3930 whole, part, NULL_TREE);
3931 /* Don't VERIFY_CONSTANT here; we only want to check that we got a
3932 CONSTRUCTOR. */
3933 if (!*non_constant_p && TREE_CODE (whole) != CONSTRUCTOR)
3935 if (!ctx->quiet)
3936 error ("%qE is not a constant expression", orig_whole);
3937 *non_constant_p = true;
3939 if (DECL_MUTABLE_P (part))
3941 if (!ctx->quiet)
3942 error ("mutable %qD is not usable in a constant expression", part);
3943 *non_constant_p = true;
3945 if (*non_constant_p)
3946 return t;
3947 bool pmf = TYPE_PTRMEMFUNC_P (TREE_TYPE (whole));
3948 FOR_EACH_CONSTRUCTOR_ELT (CONSTRUCTOR_ELTS (whole), i, field, value)
3950 /* Use name match for PMF fields, as a variant will have a
3951 different FIELD_DECL with a different type. */
3952 if (pmf ? DECL_NAME (field) == DECL_NAME (part)
3953 : field == part)
3955 if (value)
3957 STRIP_ANY_LOCATION_WRAPPER (value);
3958 return value;
3960 else
3961 /* We're in the middle of initializing it. */
3962 break;
3965 if (TREE_CODE (TREE_TYPE (whole)) == UNION_TYPE
3966 && CONSTRUCTOR_NELTS (whole) > 0)
3968 /* DR 1188 says we don't have to deal with this. */
3969 if (!ctx->quiet)
3971 constructor_elt *cep = CONSTRUCTOR_ELT (whole, 0);
3972 if (cep->value == NULL_TREE)
3973 error ("accessing uninitialized member %qD", part);
3974 else
3975 error ("accessing %qD member instead of initialized %qD member in "
3976 "constant expression", part, cep->index);
3978 *non_constant_p = true;
3979 return t;
3982 /* We only create a CONSTRUCTOR for a subobject when we modify it, so empty
3983 classes never get represented; throw together a value now. */
3984 if (is_really_empty_class (TREE_TYPE (t), /*ignore_vptr*/false))
3985 return build_constructor (TREE_TYPE (t), NULL);
3987 gcc_assert (DECL_CONTEXT (part) == TYPE_MAIN_VARIANT (TREE_TYPE (whole)));
3989 if (CONSTRUCTOR_NO_CLEARING (whole))
3991 /* 'whole' is part of the aggregate initializer we're currently
3992 building; if there's no initializer for this member yet, that's an
3993 error. */
3994 if (!ctx->quiet)
3995 error ("accessing uninitialized member %qD", part);
3996 *non_constant_p = true;
3997 return t;
4000 /* If there's no explicit init for this field, it's value-initialized. */
4001 value = build_value_init (TREE_TYPE (t), tf_warning_or_error);
4002 return cxx_eval_constant_expression (ctx, value,
4003 lval,
4004 non_constant_p, overflow_p);
4007 /* Subroutine of cxx_eval_constant_expression.
4008 Attempt to reduce a field access of a value of class type that is
4009 expressed as a BIT_FIELD_REF. */
4011 static tree
4012 cxx_eval_bit_field_ref (const constexpr_ctx *ctx, tree t,
4013 bool lval,
4014 bool *non_constant_p, bool *overflow_p)
4016 tree orig_whole = TREE_OPERAND (t, 0);
4017 tree retval, fldval, utype, mask;
4018 bool fld_seen = false;
4019 HOST_WIDE_INT istart, isize;
4020 tree whole = cxx_eval_constant_expression (ctx, orig_whole,
4021 lval,
4022 non_constant_p, overflow_p);
4023 tree start, field, value;
4024 unsigned HOST_WIDE_INT i;
4026 if (whole == orig_whole)
4027 return t;
4028 /* Don't VERIFY_CONSTANT here; we only want to check that we got a
4029 CONSTRUCTOR. */
4030 if (!*non_constant_p
4031 && TREE_CODE (whole) != VECTOR_CST
4032 && TREE_CODE (whole) != CONSTRUCTOR)
4034 if (!ctx->quiet)
4035 error ("%qE is not a constant expression", orig_whole);
4036 *non_constant_p = true;
4038 if (*non_constant_p)
4039 return t;
4041 if (TREE_CODE (whole) == VECTOR_CST)
4042 return fold_ternary (BIT_FIELD_REF, TREE_TYPE (t), whole,
4043 TREE_OPERAND (t, 1), TREE_OPERAND (t, 2));
4045 start = TREE_OPERAND (t, 2);
4046 istart = tree_to_shwi (start);
4047 isize = tree_to_shwi (TREE_OPERAND (t, 1));
4048 utype = TREE_TYPE (t);
4049 if (!TYPE_UNSIGNED (utype))
4050 utype = build_nonstandard_integer_type (TYPE_PRECISION (utype), 1);
4051 retval = build_int_cst (utype, 0);
4052 FOR_EACH_CONSTRUCTOR_ELT (CONSTRUCTOR_ELTS (whole), i, field, value)
4054 tree bitpos = bit_position (field);
4055 STRIP_ANY_LOCATION_WRAPPER (value);
4056 if (bitpos == start && DECL_SIZE (field) == TREE_OPERAND (t, 1))
4057 return value;
4058 if (TREE_CODE (TREE_TYPE (field)) == INTEGER_TYPE
4059 && TREE_CODE (value) == INTEGER_CST
4060 && tree_fits_shwi_p (bitpos)
4061 && tree_fits_shwi_p (DECL_SIZE (field)))
4063 HOST_WIDE_INT bit = tree_to_shwi (bitpos);
4064 HOST_WIDE_INT sz = tree_to_shwi (DECL_SIZE (field));
4065 HOST_WIDE_INT shift;
4066 if (bit >= istart && bit + sz <= istart + isize)
4068 fldval = fold_convert (utype, value);
4069 mask = build_int_cst_type (utype, -1);
4070 mask = fold_build2 (LSHIFT_EXPR, utype, mask,
4071 size_int (TYPE_PRECISION (utype) - sz));
4072 mask = fold_build2 (RSHIFT_EXPR, utype, mask,
4073 size_int (TYPE_PRECISION (utype) - sz));
4074 fldval = fold_build2 (BIT_AND_EXPR, utype, fldval, mask);
4075 shift = bit - istart;
4076 if (BYTES_BIG_ENDIAN)
4077 shift = TYPE_PRECISION (utype) - shift - sz;
4078 fldval = fold_build2 (LSHIFT_EXPR, utype, fldval,
4079 size_int (shift));
4080 retval = fold_build2 (BIT_IOR_EXPR, utype, retval, fldval);
4081 fld_seen = true;
4085 if (fld_seen)
4086 return fold_convert (TREE_TYPE (t), retval);
4087 gcc_unreachable ();
4088 return error_mark_node;
4091 /* Helper for cxx_eval_bit_cast.
4092 Check [bit.cast]/3 rules, bit_cast is constexpr only if the To and From
4093 types and types of all subobjects have is_union_v<T>, is_pointer_v<T>,
4094 is_member_pointer_v<T>, is_volatile_v<T> false and has no non-static
4095 data members of reference type. */
4097 static bool
4098 check_bit_cast_type (const constexpr_ctx *ctx, location_t loc, tree type,
4099 tree orig_type)
4101 if (TREE_CODE (type) == UNION_TYPE)
4103 if (!ctx->quiet)
4105 if (type == orig_type)
4106 error_at (loc, "%qs is not a constant expression because %qT is "
4107 "a union type", "__builtin_bit_cast", type);
4108 else
4109 error_at (loc, "%qs is not a constant expression because %qT "
4110 "contains a union type", "__builtin_bit_cast",
4111 orig_type);
4113 return true;
4115 if (TREE_CODE (type) == POINTER_TYPE)
4117 if (!ctx->quiet)
4119 if (type == orig_type)
4120 error_at (loc, "%qs is not a constant expression because %qT is "
4121 "a pointer type", "__builtin_bit_cast", type);
4122 else
4123 error_at (loc, "%qs is not a constant expression because %qT "
4124 "contains a pointer type", "__builtin_bit_cast",
4125 orig_type);
4127 return true;
4129 if (TREE_CODE (type) == REFERENCE_TYPE)
4131 if (!ctx->quiet)
4133 if (type == orig_type)
4134 error_at (loc, "%qs is not a constant expression because %qT is "
4135 "a reference type", "__builtin_bit_cast", type);
4136 else
4137 error_at (loc, "%qs is not a constant expression because %qT "
4138 "contains a reference type", "__builtin_bit_cast",
4139 orig_type);
4141 return true;
4143 if (TYPE_PTRMEM_P (type))
4145 if (!ctx->quiet)
4147 if (type == orig_type)
4148 error_at (loc, "%qs is not a constant expression because %qT is "
4149 "a pointer to member type", "__builtin_bit_cast",
4150 type);
4151 else
4152 error_at (loc, "%qs is not a constant expression because %qT "
4153 "contains a pointer to member type",
4154 "__builtin_bit_cast", orig_type);
4156 return true;
4158 if (TYPE_VOLATILE (type))
4160 if (!ctx->quiet)
4162 if (type == orig_type)
4163 error_at (loc, "%qs is not a constant expression because %qT is "
4164 "volatile", "__builtin_bit_cast", type);
4165 else
4166 error_at (loc, "%qs is not a constant expression because %qT "
4167 "contains a volatile subobject",
4168 "__builtin_bit_cast", orig_type);
4170 return true;
4172 if (TREE_CODE (type) == RECORD_TYPE)
4173 for (tree field = TYPE_FIELDS (type); field; field = DECL_CHAIN (field))
4174 if (TREE_CODE (field) == FIELD_DECL
4175 && check_bit_cast_type (ctx, loc, TREE_TYPE (field), orig_type))
4176 return true;
4177 return false;
4180 /* Subroutine of cxx_eval_constant_expression.
4181 Attempt to evaluate a BIT_CAST_EXPR. */
4183 static tree
4184 cxx_eval_bit_cast (const constexpr_ctx *ctx, tree t, bool *non_constant_p,
4185 bool *overflow_p)
4187 if (check_bit_cast_type (ctx, EXPR_LOCATION (t), TREE_TYPE (t),
4188 TREE_TYPE (t))
4189 || check_bit_cast_type (ctx, cp_expr_loc_or_loc (TREE_OPERAND (t, 0),
4190 EXPR_LOCATION (t)),
4191 TREE_TYPE (TREE_OPERAND (t, 0)),
4192 TREE_TYPE (TREE_OPERAND (t, 0))))
4194 *non_constant_p = true;
4195 return t;
4198 tree op = cxx_eval_constant_expression (ctx, TREE_OPERAND (t, 0), false,
4199 non_constant_p, overflow_p);
4200 if (*non_constant_p)
4201 return t;
4203 location_t loc = EXPR_LOCATION (t);
4204 if (BITS_PER_UNIT != 8 || CHAR_BIT != 8)
4206 if (!ctx->quiet)
4207 sorry_at (loc, "%qs cannot be constant evaluated on the target",
4208 "__builtin_bit_cast");
4209 *non_constant_p = true;
4210 return t;
4213 if (!tree_fits_shwi_p (TYPE_SIZE_UNIT (TREE_TYPE (t))))
4215 if (!ctx->quiet)
4216 sorry_at (loc, "%qs cannot be constant evaluated because the "
4217 "type is too large", "__builtin_bit_cast");
4218 *non_constant_p = true;
4219 return t;
4222 HOST_WIDE_INT len = tree_to_shwi (TYPE_SIZE_UNIT (TREE_TYPE (t)));
4223 if (len < 0 || (int) len != len)
4225 if (!ctx->quiet)
4226 sorry_at (loc, "%qs cannot be constant evaluated because the "
4227 "type is too large", "__builtin_bit_cast");
4228 *non_constant_p = true;
4229 return t;
4232 unsigned char buf[64];
4233 unsigned char *ptr, *mask;
4234 size_t alen = (size_t) len * 2;
4235 if (alen <= sizeof (buf))
4236 ptr = buf;
4237 else
4238 ptr = XNEWVEC (unsigned char, alen);
4239 mask = ptr + (size_t) len;
4240 /* At the beginning consider everything indeterminate. */
4241 memset (mask, ~0, (size_t) len);
4243 if (native_encode_initializer (op, ptr, len, 0, mask) != len)
4245 if (!ctx->quiet)
4246 sorry_at (loc, "%qs cannot be constant evaluated because the "
4247 "argument cannot be encoded", "__builtin_bit_cast");
4248 *non_constant_p = true;
4249 if (ptr != buf)
4250 XDELETE (ptr);
4251 return t;
4254 tree r = NULL_TREE;
4255 if (can_native_interpret_type_p (TREE_TYPE (t)))
4256 r = native_interpret_expr (TREE_TYPE (t), ptr, len);
4257 else if (TREE_CODE (TREE_TYPE (t)) == RECORD_TYPE)
4259 r = native_interpret_aggregate (TREE_TYPE (t), ptr, 0, len);
4260 if (r != NULL_TREE)
4261 clear_type_padding_in_mask (TREE_TYPE (t), mask);
4264 if (r != NULL_TREE)
4266 for (int i = 0; i < len; i++)
4267 if (mask[i])
4269 if (!ctx->quiet)
4270 error_at (loc, "%qs accessing uninitialized byte at offset %d",
4271 "__builtin_bit_cast", i);
4272 *non_constant_p = true;
4273 r = t;
4274 break;
4276 if (ptr != buf)
4277 XDELETE (ptr);
4278 return r;
4281 if (!ctx->quiet)
4282 sorry_at (loc, "%qs cannot be constant evaluated because the "
4283 "argument cannot be interpreted", "__builtin_bit_cast");
4284 *non_constant_p = true;
4285 if (ptr != buf)
4286 XDELETE (ptr);
4287 return t;
4290 /* Subroutine of cxx_eval_constant_expression.
4291 Evaluate a short-circuited logical expression T in the context
4292 of a given constexpr CALL. BAILOUT_VALUE is the value for
4293 early return. CONTINUE_VALUE is used here purely for
4294 sanity check purposes. */
4296 static tree
4297 cxx_eval_logical_expression (const constexpr_ctx *ctx, tree t,
4298 tree bailout_value, tree continue_value,
4299 bool lval,
4300 bool *non_constant_p, bool *overflow_p)
4302 tree r;
4303 tree lhs = cxx_eval_constant_expression (ctx, TREE_OPERAND (t, 0),
4304 lval,
4305 non_constant_p, overflow_p);
4306 VERIFY_CONSTANT (lhs);
4307 if (tree_int_cst_equal (lhs, bailout_value))
4308 return lhs;
4309 gcc_assert (tree_int_cst_equal (lhs, continue_value));
4310 r = cxx_eval_constant_expression (ctx, TREE_OPERAND (t, 1),
4311 lval, non_constant_p,
4312 overflow_p);
4313 VERIFY_CONSTANT (r);
4314 return r;
4317 /* REF is a COMPONENT_REF designating a particular field. V is a vector of
4318 CONSTRUCTOR elements to initialize (part of) an object containing that
4319 field. Return a pointer to the constructor_elt corresponding to the
4320 initialization of the field. */
4322 static constructor_elt *
4323 base_field_constructor_elt (vec<constructor_elt, va_gc> *v, tree ref)
4325 tree aggr = TREE_OPERAND (ref, 0);
4326 tree field = TREE_OPERAND (ref, 1);
4327 HOST_WIDE_INT i;
4328 constructor_elt *ce;
4330 gcc_assert (TREE_CODE (ref) == COMPONENT_REF);
4332 if (TREE_CODE (aggr) == COMPONENT_REF)
4334 constructor_elt *base_ce
4335 = base_field_constructor_elt (v, aggr);
4336 v = CONSTRUCTOR_ELTS (base_ce->value);
4339 for (i = 0; vec_safe_iterate (v, i, &ce); ++i)
4340 if (ce->index == field)
4341 return ce;
4343 gcc_unreachable ();
4344 return NULL;
4347 /* Some of the expressions fed to the constexpr mechanism are calls to
4348 constructors, which have type void. In that case, return the type being
4349 initialized by the constructor. */
4351 static tree
4352 initialized_type (tree t)
4354 if (TYPE_P (t))
4355 return t;
4356 tree type = TREE_TYPE (t);
4357 if (TREE_CODE (t) == CALL_EXPR)
4359 /* A constructor call has void type, so we need to look deeper. */
4360 tree fn = get_function_named_in_call (t);
4361 if (fn && TREE_CODE (fn) == FUNCTION_DECL
4362 && DECL_CXX_CONSTRUCTOR_P (fn))
4363 type = DECL_CONTEXT (fn);
4365 else if (TREE_CODE (t) == COMPOUND_EXPR)
4366 return initialized_type (TREE_OPERAND (t, 1));
4367 else if (TREE_CODE (t) == AGGR_INIT_EXPR)
4368 type = TREE_TYPE (AGGR_INIT_EXPR_SLOT (t));
4369 return cv_unqualified (type);
4372 /* We're about to initialize element INDEX of an array or class from VALUE.
4373 Set up NEW_CTX appropriately by adjusting .object to refer to the
4374 subobject and creating a new CONSTRUCTOR if the element is itself
4375 a class or array. */
4377 static void
4378 init_subob_ctx (const constexpr_ctx *ctx, constexpr_ctx &new_ctx,
4379 tree index, tree &value)
4381 new_ctx = *ctx;
4383 if (index && TREE_CODE (index) != INTEGER_CST
4384 && TREE_CODE (index) != FIELD_DECL
4385 && TREE_CODE (index) != RANGE_EXPR)
4386 /* This won't have an element in the new CONSTRUCTOR. */
4387 return;
4389 tree type = initialized_type (value);
4390 if (!AGGREGATE_TYPE_P (type) && !VECTOR_TYPE_P (type))
4391 /* A non-aggregate member doesn't get its own CONSTRUCTOR. */
4392 return;
4394 /* The sub-aggregate initializer might contain a placeholder;
4395 update object to refer to the subobject and ctor to refer to
4396 the (newly created) sub-initializer. */
4397 if (ctx->object)
4399 if (index == NULL_TREE || TREE_CODE (index) == RANGE_EXPR)
4400 /* There's no well-defined subobject for this index. */
4401 new_ctx.object = NULL_TREE;
4402 else
4403 new_ctx.object = build_ctor_subob_ref (index, type, ctx->object);
4405 tree elt = build_constructor (type, NULL);
4406 CONSTRUCTOR_NO_CLEARING (elt) = true;
4407 new_ctx.ctor = elt;
4409 if (TREE_CODE (value) == TARGET_EXPR)
4410 /* Avoid creating another CONSTRUCTOR when we expand the TARGET_EXPR. */
4411 value = TARGET_EXPR_INITIAL (value);
4414 /* We're about to process an initializer for a class or array TYPE. Make
4415 sure that CTX is set up appropriately. */
4417 static void
4418 verify_ctor_sanity (const constexpr_ctx *ctx, tree type)
4420 /* We don't bother building a ctor for an empty base subobject. */
4421 if (is_empty_class (type))
4422 return;
4424 /* We're in the middle of an initializer that might involve placeholders;
4425 our caller should have created a CONSTRUCTOR for us to put the
4426 initializer into. We will either return that constructor or T. */
4427 gcc_assert (ctx->ctor);
4428 gcc_assert (same_type_ignoring_top_level_qualifiers_p
4429 (type, TREE_TYPE (ctx->ctor)));
4430 /* We used to check that ctx->ctor was empty, but that isn't the case when
4431 the object is zero-initialized before calling the constructor. */
4432 if (ctx->object)
4434 tree otype = TREE_TYPE (ctx->object);
4435 gcc_assert (same_type_ignoring_top_level_qualifiers_p (type, otype)
4436 /* Handle flexible array members. */
4437 || (TREE_CODE (otype) == ARRAY_TYPE
4438 && TYPE_DOMAIN (otype) == NULL_TREE
4439 && TREE_CODE (type) == ARRAY_TYPE
4440 && (same_type_ignoring_top_level_qualifiers_p
4441 (TREE_TYPE (type), TREE_TYPE (otype)))));
4443 gcc_assert (!ctx->object || !DECL_P (ctx->object)
4444 || *(ctx->global->values.get (ctx->object)) == ctx->ctor);
4447 /* Subroutine of cxx_eval_constant_expression.
4448 The expression tree T denotes a C-style array or a C-style
4449 aggregate. Reduce it to a constant expression. */
4451 static tree
4452 cxx_eval_bare_aggregate (const constexpr_ctx *ctx, tree t,
4453 bool lval,
4454 bool *non_constant_p, bool *overflow_p)
4456 vec<constructor_elt, va_gc> *v = CONSTRUCTOR_ELTS (t);
4457 bool changed = false;
4458 gcc_assert (!BRACE_ENCLOSED_INITIALIZER_P (t));
4459 tree type = TREE_TYPE (t);
4461 constexpr_ctx new_ctx;
4462 if (TYPE_PTRMEMFUNC_P (type) || VECTOR_TYPE_P (type))
4464 /* We don't really need the ctx->ctor business for a PMF or
4465 vector, but it's simpler to use the same code. */
4466 new_ctx = *ctx;
4467 new_ctx.ctor = build_constructor (type, NULL);
4468 new_ctx.object = NULL_TREE;
4469 ctx = &new_ctx;
4471 verify_ctor_sanity (ctx, type);
4472 vec<constructor_elt, va_gc> **p = &CONSTRUCTOR_ELTS (ctx->ctor);
4473 vec_alloc (*p, vec_safe_length (v));
4475 if (CONSTRUCTOR_PLACEHOLDER_BOUNDARY (t))
4476 CONSTRUCTOR_PLACEHOLDER_BOUNDARY (ctx->ctor) = 1;
4478 unsigned i;
4479 tree index, value;
4480 bool constant_p = true;
4481 bool side_effects_p = false;
4482 FOR_EACH_CONSTRUCTOR_ELT (v, i, index, value)
4484 tree orig_value = value;
4485 /* Like in cxx_eval_store_expression, omit entries for empty fields. */
4486 bool no_slot = TREE_CODE (type) == RECORD_TYPE && is_empty_field (index);
4487 if (no_slot)
4488 new_ctx = *ctx;
4489 else
4490 init_subob_ctx (ctx, new_ctx, index, value);
4491 int pos_hint = -1;
4492 if (new_ctx.ctor != ctx->ctor)
4494 /* If we built a new CONSTRUCTOR, attach it now so that other
4495 initializers can refer to it. */
4496 constructor_elt *cep = get_or_insert_ctor_field (ctx->ctor, index);
4497 cep->value = new_ctx.ctor;
4498 pos_hint = cep - (*p)->begin();
4500 else if (TREE_CODE (type) == UNION_TYPE)
4501 /* Otherwise if we're constructing a non-aggregate union member, set
4502 the active union member now so that we can later detect and diagnose
4503 if its initializer attempts to activate another member. */
4504 get_or_insert_ctor_field (ctx->ctor, index);
4505 tree elt = cxx_eval_constant_expression (&new_ctx, value,
4506 lval,
4507 non_constant_p, overflow_p);
4508 /* Don't VERIFY_CONSTANT here. */
4509 if (ctx->quiet && *non_constant_p)
4510 break;
4511 if (elt != orig_value)
4512 changed = true;
4514 if (!TREE_CONSTANT (elt))
4515 constant_p = false;
4516 if (TREE_SIDE_EFFECTS (elt))
4517 side_effects_p = true;
4518 if (index && TREE_CODE (index) == COMPONENT_REF)
4520 /* This is an initialization of a vfield inside a base
4521 subaggregate that we already initialized; push this
4522 initialization into the previous initialization. */
4523 constructor_elt *inner = base_field_constructor_elt (*p, index);
4524 inner->value = elt;
4525 changed = true;
4527 else if (index
4528 && (TREE_CODE (index) == NOP_EXPR
4529 || TREE_CODE (index) == POINTER_PLUS_EXPR))
4531 /* This is an initializer for an empty base; now that we've
4532 checked that it's constant, we can ignore it. */
4533 gcc_assert (is_empty_class (TREE_TYPE (TREE_TYPE (index))));
4534 changed = true;
4536 else if (no_slot)
4537 changed = true;
4538 else
4540 if (TREE_CODE (type) == UNION_TYPE
4541 && (*p)->last().index != index)
4542 /* The initializer erroneously changed the active union member that
4543 we're initializing. */
4544 gcc_assert (*non_constant_p);
4545 else
4547 /* The initializer might have mutated the underlying CONSTRUCTOR,
4548 so recompute the location of the target constructer_elt. */
4549 constructor_elt *cep
4550 = get_or_insert_ctor_field (ctx->ctor, index, pos_hint);
4551 cep->value = elt;
4554 /* Adding or replacing an element might change the ctor's flags. */
4555 TREE_CONSTANT (ctx->ctor) = constant_p;
4556 TREE_SIDE_EFFECTS (ctx->ctor) = side_effects_p;
4559 if (*non_constant_p || !changed)
4560 return t;
4561 t = ctx->ctor;
4562 /* We're done building this CONSTRUCTOR, so now we can interpret an
4563 element without an explicit initializer as value-initialized. */
4564 CONSTRUCTOR_NO_CLEARING (t) = false;
4565 TREE_CONSTANT (t) = constant_p;
4566 TREE_SIDE_EFFECTS (t) = side_effects_p;
4567 if (VECTOR_TYPE_P (type))
4568 t = fold (t);
4569 return t;
4572 /* Subroutine of cxx_eval_constant_expression.
4573 The expression tree T is a VEC_INIT_EXPR which denotes the desired
4574 initialization of a non-static data member of array type. Reduce it to a
4575 CONSTRUCTOR.
4577 Note that apart from value-initialization (when VALUE_INIT is true),
4578 this is only intended to support value-initialization and the
4579 initializations done by defaulted constructors for classes with
4580 non-static data members of array type. In this case, VEC_INIT_EXPR_INIT
4581 will either be NULL_TREE for the default constructor, or a COMPONENT_REF
4582 for the copy/move constructor. */
4584 static tree
4585 cxx_eval_vec_init_1 (const constexpr_ctx *ctx, tree atype, tree init,
4586 bool value_init, bool lval,
4587 bool *non_constant_p, bool *overflow_p)
4589 tree elttype = TREE_TYPE (atype);
4590 verify_ctor_sanity (ctx, atype);
4591 vec<constructor_elt, va_gc> **p = &CONSTRUCTOR_ELTS (ctx->ctor);
4592 bool pre_init = false;
4593 unsigned HOST_WIDE_INT i;
4594 tsubst_flags_t complain = ctx->quiet ? tf_none : tf_warning_or_error;
4596 if (init && TREE_CODE (init) == CONSTRUCTOR)
4597 return cxx_eval_bare_aggregate (ctx, init, lval,
4598 non_constant_p, overflow_p);
4600 /* For the default constructor, build up a call to the default
4601 constructor of the element type. We only need to handle class types
4602 here, as for a constructor to be constexpr, all members must be
4603 initialized, which for a defaulted default constructor means they must
4604 be of a class type with a constexpr default constructor. */
4605 if (TREE_CODE (elttype) == ARRAY_TYPE)
4606 /* We only do this at the lowest level. */;
4607 else if (value_init)
4609 init = build_value_init (elttype, complain);
4610 pre_init = true;
4612 else if (!init)
4614 releasing_vec argvec;
4615 init = build_special_member_call (NULL_TREE, complete_ctor_identifier,
4616 &argvec, elttype, LOOKUP_NORMAL,
4617 complain);
4618 init = build_aggr_init_expr (elttype, init);
4619 pre_init = true;
4622 bool zeroed_out = false;
4623 if (!CONSTRUCTOR_NO_CLEARING (ctx->ctor))
4625 /* We're initializing an array object that had been zero-initialized
4626 earlier. Truncate ctx->ctor, and propagate its zeroed state by
4627 clearing CONSTRUCTOR_NO_CLEARING on each of the aggregate element
4628 initializers we append to it. */
4629 gcc_checking_assert (initializer_zerop (ctx->ctor));
4630 zeroed_out = true;
4631 vec_safe_truncate (*p, 0);
4634 tree nelts = get_array_or_vector_nelts (ctx, atype, non_constant_p,
4635 overflow_p);
4636 unsigned HOST_WIDE_INT max = tree_to_uhwi (nelts);
4637 for (i = 0; i < max; ++i)
4639 tree idx = build_int_cst (size_type_node, i);
4640 tree eltinit;
4641 bool reuse = false;
4642 constexpr_ctx new_ctx;
4643 init_subob_ctx (ctx, new_ctx, idx, pre_init ? init : elttype);
4644 if (new_ctx.ctor != ctx->ctor)
4646 if (zeroed_out)
4647 CONSTRUCTOR_NO_CLEARING (new_ctx.ctor) = false;
4648 CONSTRUCTOR_APPEND_ELT (*p, idx, new_ctx.ctor);
4650 if (TREE_CODE (elttype) == ARRAY_TYPE)
4652 /* A multidimensional array; recurse. */
4653 if (value_init || init == NULL_TREE)
4655 eltinit = NULL_TREE;
4656 reuse = i == 0;
4658 else
4659 eltinit = cp_build_array_ref (input_location, init, idx, complain);
4660 eltinit = cxx_eval_vec_init_1 (&new_ctx, elttype, eltinit, value_init,
4661 lval,
4662 non_constant_p, overflow_p);
4664 else if (pre_init)
4666 /* Initializing an element using value or default initialization
4667 we just pre-built above. */
4668 if (init == void_node)
4669 /* Trivial default-init, don't do anything to the CONSTRUCTOR. */
4670 return ctx->ctor;
4671 eltinit = cxx_eval_constant_expression (&new_ctx, init, lval,
4672 non_constant_p, overflow_p);
4673 reuse = i == 0;
4675 else
4677 /* Copying an element. */
4678 gcc_assert (same_type_ignoring_top_level_qualifiers_p
4679 (atype, TREE_TYPE (init)));
4680 eltinit = cp_build_array_ref (input_location, init, idx, complain);
4681 if (!lvalue_p (init))
4682 eltinit = move (eltinit);
4683 eltinit = force_rvalue (eltinit, complain);
4684 eltinit = cxx_eval_constant_expression (&new_ctx, eltinit, lval,
4685 non_constant_p, overflow_p);
4687 if (*non_constant_p)
4688 break;
4689 if (new_ctx.ctor != ctx->ctor)
4691 /* We appended this element above; update the value. */
4692 gcc_assert ((*p)->last().index == idx);
4693 (*p)->last().value = eltinit;
4695 else
4696 CONSTRUCTOR_APPEND_ELT (*p, idx, eltinit);
4697 /* Reuse the result of cxx_eval_constant_expression call
4698 from the first iteration to all others if it is a constant
4699 initializer that doesn't require relocations. */
4700 if (reuse
4701 && max > 1
4702 && (eltinit == NULL_TREE
4703 || (initializer_constant_valid_p (eltinit, TREE_TYPE (eltinit))
4704 == null_pointer_node)))
4706 if (new_ctx.ctor != ctx->ctor)
4707 eltinit = new_ctx.ctor;
4708 tree range = build2 (RANGE_EXPR, size_type_node,
4709 build_int_cst (size_type_node, 1),
4710 build_int_cst (size_type_node, max - 1));
4711 CONSTRUCTOR_APPEND_ELT (*p, range, unshare_constructor (eltinit));
4712 break;
4714 else if (i == 0)
4715 vec_safe_reserve (*p, max);
4718 if (!*non_constant_p)
4720 init = ctx->ctor;
4721 CONSTRUCTOR_NO_CLEARING (init) = false;
4723 return init;
4726 static tree
4727 cxx_eval_vec_init (const constexpr_ctx *ctx, tree t,
4728 bool lval,
4729 bool *non_constant_p, bool *overflow_p)
4731 tree atype = TREE_TYPE (t);
4732 tree init = VEC_INIT_EXPR_INIT (t);
4733 tree r = cxx_eval_vec_init_1 (ctx, atype, init,
4734 VEC_INIT_EXPR_VALUE_INIT (t),
4735 lval, non_constant_p, overflow_p);
4736 if (*non_constant_p)
4737 return t;
4738 else
4739 return r;
4742 /* Like same_type_ignoring_top_level_qualifiers_p, but also handle the case
4743 where the desired type is an array of unknown bounds because the variable
4744 has had its bounds deduced since the wrapping expression was created. */
4746 static bool
4747 same_type_ignoring_tlq_and_bounds_p (tree type1, tree type2)
4749 while (TREE_CODE (type1) == ARRAY_TYPE
4750 && TREE_CODE (type2) == ARRAY_TYPE
4751 && (!TYPE_DOMAIN (type1) || !TYPE_DOMAIN (type2)))
4753 type1 = TREE_TYPE (type1);
4754 type2 = TREE_TYPE (type2);
4756 return same_type_ignoring_top_level_qualifiers_p (type1, type2);
4759 /* Try to determine the currently active union member for an expression
4760 with UNION_TYPE. If it can be determined, return the FIELD_DECL,
4761 otherwise return NULL_TREE. */
4763 static tree
4764 cxx_union_active_member (const constexpr_ctx *ctx, tree t)
4766 constexpr_ctx new_ctx = *ctx;
4767 new_ctx.quiet = true;
4768 bool non_constant_p = false, overflow_p = false;
4769 tree ctor = cxx_eval_constant_expression (&new_ctx, t, false,
4770 &non_constant_p,
4771 &overflow_p);
4772 if (TREE_CODE (ctor) == CONSTRUCTOR
4773 && CONSTRUCTOR_NELTS (ctor) == 1
4774 && CONSTRUCTOR_ELT (ctor, 0)->index
4775 && TREE_CODE (CONSTRUCTOR_ELT (ctor, 0)->index) == FIELD_DECL)
4776 return CONSTRUCTOR_ELT (ctor, 0)->index;
4777 return NULL_TREE;
4780 /* Helper function for cxx_fold_indirect_ref_1, called recursively. */
4782 static tree
4783 cxx_fold_indirect_ref_1 (const constexpr_ctx *ctx, location_t loc, tree type,
4784 tree op, unsigned HOST_WIDE_INT off, bool *empty_base)
4786 tree optype = TREE_TYPE (op);
4787 unsigned HOST_WIDE_INT const_nunits;
4788 if (off == 0 && similar_type_p (optype, type))
4789 return op;
4790 else if (TREE_CODE (optype) == COMPLEX_TYPE
4791 && similar_type_p (type, TREE_TYPE (optype)))
4793 /* *(foo *)&complexfoo => __real__ complexfoo */
4794 if (off == 0)
4795 return build1_loc (loc, REALPART_EXPR, type, op);
4796 /* ((foo*)&complexfoo)[1] => __imag__ complexfoo */
4797 else if (tree_to_uhwi (TYPE_SIZE_UNIT (type)) == off)
4798 return build1_loc (loc, IMAGPART_EXPR, type, op);
4800 /* ((foo*)&vectorfoo)[x] => BIT_FIELD_REF<vectorfoo,...> */
4801 else if (VECTOR_TYPE_P (optype)
4802 && similar_type_p (type, TREE_TYPE (optype))
4803 && TYPE_VECTOR_SUBPARTS (optype).is_constant (&const_nunits))
4805 unsigned HOST_WIDE_INT part_width = tree_to_uhwi (TYPE_SIZE_UNIT (type));
4806 unsigned HOST_WIDE_INT max_offset = part_width * const_nunits;
4807 if (off < max_offset && off % part_width == 0)
4809 tree index = bitsize_int (off * BITS_PER_UNIT);
4810 return build3_loc (loc, BIT_FIELD_REF, type, op,
4811 TYPE_SIZE (type), index);
4814 /* ((foo *)&fooarray)[x] => fooarray[x] */
4815 else if (TREE_CODE (optype) == ARRAY_TYPE
4816 && tree_fits_uhwi_p (TYPE_SIZE_UNIT (TREE_TYPE (optype)))
4817 && !integer_zerop (TYPE_SIZE_UNIT (TREE_TYPE (optype))))
4819 tree type_domain = TYPE_DOMAIN (optype);
4820 tree min_val = size_zero_node;
4821 if (type_domain && TYPE_MIN_VALUE (type_domain))
4822 min_val = TYPE_MIN_VALUE (type_domain);
4823 unsigned HOST_WIDE_INT el_sz
4824 = tree_to_uhwi (TYPE_SIZE_UNIT (TREE_TYPE (optype)));
4825 unsigned HOST_WIDE_INT idx = off / el_sz;
4826 unsigned HOST_WIDE_INT rem = off % el_sz;
4827 if (tree_fits_uhwi_p (min_val))
4829 tree index = size_int (idx + tree_to_uhwi (min_val));
4830 op = build4_loc (loc, ARRAY_REF, TREE_TYPE (optype), op, index,
4831 NULL_TREE, NULL_TREE);
4832 return cxx_fold_indirect_ref_1 (ctx, loc, type, op, rem,
4833 empty_base);
4836 /* ((foo *)&struct_with_foo_field)[x] => COMPONENT_REF */
4837 else if (TREE_CODE (optype) == RECORD_TYPE
4838 || TREE_CODE (optype) == UNION_TYPE)
4840 if (TREE_CODE (optype) == UNION_TYPE)
4841 /* For unions prefer the currently active member. */
4842 if (tree field = cxx_union_active_member (ctx, op))
4844 unsigned HOST_WIDE_INT el_sz
4845 = tree_to_uhwi (TYPE_SIZE_UNIT (TREE_TYPE (field)));
4846 if (off < el_sz)
4848 tree cop = build3 (COMPONENT_REF, TREE_TYPE (field),
4849 op, field, NULL_TREE);
4850 if (tree ret = cxx_fold_indirect_ref_1 (ctx, loc, type, cop,
4851 off, empty_base))
4852 return ret;
4855 for (tree field = TYPE_FIELDS (optype);
4856 field; field = DECL_CHAIN (field))
4857 if (TREE_CODE (field) == FIELD_DECL
4858 && TREE_TYPE (field) != error_mark_node
4859 && tree_fits_uhwi_p (TYPE_SIZE_UNIT (TREE_TYPE (field))))
4861 tree pos = byte_position (field);
4862 if (!tree_fits_uhwi_p (pos))
4863 continue;
4864 unsigned HOST_WIDE_INT upos = tree_to_uhwi (pos);
4865 unsigned HOST_WIDE_INT el_sz
4866 = tree_to_uhwi (TYPE_SIZE_UNIT (TREE_TYPE (field)));
4867 if (upos <= off && off < upos + el_sz)
4869 tree cop = build3 (COMPONENT_REF, TREE_TYPE (field),
4870 op, field, NULL_TREE);
4871 if (tree ret = cxx_fold_indirect_ref_1 (ctx, loc, type, cop,
4872 off - upos,
4873 empty_base))
4874 return ret;
4877 /* Also handle conversion to an empty base class, which
4878 is represented with a NOP_EXPR. */
4879 if (is_empty_class (type)
4880 && CLASS_TYPE_P (optype)
4881 && DERIVED_FROM_P (type, optype))
4883 *empty_base = true;
4884 return op;
4888 return NULL_TREE;
4891 /* A less strict version of fold_indirect_ref_1, which requires cv-quals to
4892 match. We want to be less strict for simple *& folding; if we have a
4893 non-const temporary that we access through a const pointer, that should
4894 work. We handle this here rather than change fold_indirect_ref_1
4895 because we're dealing with things like ADDR_EXPR of INTEGER_CST which
4896 don't really make sense outside of constant expression evaluation. Also
4897 we want to allow folding to COMPONENT_REF, which could cause trouble
4898 with TBAA in fold_indirect_ref_1. */
4900 static tree
4901 cxx_fold_indirect_ref (const constexpr_ctx *ctx, location_t loc, tree type,
4902 tree op0, bool *empty_base)
4904 tree sub = op0;
4905 tree subtype;
4906 poly_uint64 const_op01;
4908 /* STRIP_NOPS, but stop if REINTERPRET_CAST_P. */
4909 while (CONVERT_EXPR_P (sub) || TREE_CODE (sub) == NON_LVALUE_EXPR
4910 || TREE_CODE (sub) == VIEW_CONVERT_EXPR)
4912 if (TREE_CODE (sub) == NOP_EXPR
4913 && REINTERPRET_CAST_P (sub))
4914 return NULL_TREE;
4915 sub = TREE_OPERAND (sub, 0);
4918 subtype = TREE_TYPE (sub);
4919 if (!INDIRECT_TYPE_P (subtype))
4920 return NULL_TREE;
4922 if (TREE_CODE (sub) == ADDR_EXPR)
4924 tree op = TREE_OPERAND (sub, 0);
4925 tree optype = TREE_TYPE (op);
4927 /* *&CONST_DECL -> to the value of the const decl. */
4928 if (TREE_CODE (op) == CONST_DECL)
4929 return DECL_INITIAL (op);
4930 /* *&p => p; make sure to handle *&"str"[cst] here. */
4931 if (similar_type_p (optype, type))
4933 tree fop = fold_read_from_constant_string (op);
4934 if (fop)
4935 return fop;
4936 else
4937 return op;
4939 else
4940 return cxx_fold_indirect_ref_1 (ctx, loc, type, op, 0, empty_base);
4942 else if (TREE_CODE (sub) == POINTER_PLUS_EXPR
4943 && tree_fits_uhwi_p (TREE_OPERAND (sub, 1)))
4945 tree op00 = TREE_OPERAND (sub, 0);
4946 tree off = TREE_OPERAND (sub, 1);
4948 STRIP_NOPS (op00);
4949 if (TREE_CODE (op00) == ADDR_EXPR)
4951 tree obj = TREE_OPERAND (op00, 0);
4952 while (TREE_CODE (obj) == COMPONENT_REF
4953 && tree_int_cst_sign_bit (off))
4955 /* Canonicalize this object/offset pair by iteratively absorbing
4956 the innermost component into the offset until the offset is
4957 nonnegative, so that cxx_fold_indirect_ref_1 can identify
4958 more folding opportunities. */
4959 tree field = TREE_OPERAND (obj, 1);
4960 off = int_const_binop (PLUS_EXPR, off, byte_position (field));
4961 obj = TREE_OPERAND (obj, 0);
4963 return cxx_fold_indirect_ref_1 (ctx, loc, type, obj,
4964 tree_to_uhwi (off), empty_base);
4967 /* *(foo *)fooarrptr => (*fooarrptr)[0] */
4968 else if (TREE_CODE (TREE_TYPE (subtype)) == ARRAY_TYPE
4969 && similar_type_p (type, TREE_TYPE (TREE_TYPE (subtype))))
4971 tree type_domain;
4972 tree min_val = size_zero_node;
4973 tree newsub
4974 = cxx_fold_indirect_ref (ctx, loc, TREE_TYPE (subtype), sub, NULL);
4975 if (newsub)
4976 sub = newsub;
4977 else
4978 sub = build1_loc (loc, INDIRECT_REF, TREE_TYPE (subtype), sub);
4979 type_domain = TYPE_DOMAIN (TREE_TYPE (sub));
4980 if (type_domain && TYPE_MIN_VALUE (type_domain))
4981 min_val = TYPE_MIN_VALUE (type_domain);
4982 return build4_loc (loc, ARRAY_REF, type, sub, min_val, NULL_TREE,
4983 NULL_TREE);
4986 return NULL_TREE;
4989 static tree
4990 cxx_eval_indirect_ref (const constexpr_ctx *ctx, tree t,
4991 bool lval,
4992 bool *non_constant_p, bool *overflow_p)
4994 tree orig_op0 = TREE_OPERAND (t, 0);
4995 bool empty_base = false;
4997 /* We can handle a MEM_REF like an INDIRECT_REF, if MEM_REF's second
4998 operand is an integer-zero. Otherwise reject the MEM_REF for now. */
5000 if (TREE_CODE (t) == MEM_REF
5001 && (!TREE_OPERAND (t, 1) || !integer_zerop (TREE_OPERAND (t, 1))))
5003 gcc_assert (ctx->quiet);
5004 *non_constant_p = true;
5005 return t;
5008 /* First try to simplify it directly. */
5009 tree r = cxx_fold_indirect_ref (ctx, EXPR_LOCATION (t), TREE_TYPE (t),
5010 orig_op0, &empty_base);
5011 if (!r)
5013 /* If that didn't work, evaluate the operand first. */
5014 tree op0 = cxx_eval_constant_expression (ctx, orig_op0,
5015 /*lval*/false, non_constant_p,
5016 overflow_p);
5017 /* Don't VERIFY_CONSTANT here. */
5018 if (*non_constant_p)
5019 return t;
5021 if (!lval && integer_zerop (op0))
5023 if (!ctx->quiet)
5024 error ("dereferencing a null pointer");
5025 *non_constant_p = true;
5026 return t;
5029 r = cxx_fold_indirect_ref (ctx, EXPR_LOCATION (t), TREE_TYPE (t), op0,
5030 &empty_base);
5031 if (r == NULL_TREE)
5033 /* We couldn't fold to a constant value. Make sure it's not
5034 something we should have been able to fold. */
5035 tree sub = op0;
5036 STRIP_NOPS (sub);
5037 if (TREE_CODE (sub) == ADDR_EXPR)
5039 gcc_assert (!similar_type_p
5040 (TREE_TYPE (TREE_TYPE (sub)), TREE_TYPE (t)));
5041 /* DR 1188 says we don't have to deal with this. */
5042 if (!ctx->quiet)
5043 error_at (cp_expr_loc_or_input_loc (t),
5044 "accessing value of %qE through a %qT glvalue in a "
5045 "constant expression", build_fold_indirect_ref (sub),
5046 TREE_TYPE (t));
5047 *non_constant_p = true;
5048 return t;
5051 if (lval && op0 != orig_op0)
5052 return build1 (INDIRECT_REF, TREE_TYPE (t), op0);
5053 if (!lval)
5054 VERIFY_CONSTANT (t);
5055 return t;
5059 r = cxx_eval_constant_expression (ctx, r,
5060 lval, non_constant_p, overflow_p);
5061 if (*non_constant_p)
5062 return t;
5064 /* If we're pulling out the value of an empty base, just return an empty
5065 CONSTRUCTOR. */
5066 if (empty_base && !lval)
5068 r = build_constructor (TREE_TYPE (t), NULL);
5069 TREE_CONSTANT (r) = true;
5072 return r;
5075 /* Complain about R, a VAR_DECL, not being usable in a constant expression.
5076 Shared between potential_constant_expression and
5077 cxx_eval_constant_expression. */
5079 static void
5080 non_const_var_error (location_t loc, tree r)
5082 auto_diagnostic_group d;
5083 tree type = TREE_TYPE (r);
5084 if (DECL_NAME (r) == heap_uninit_identifier
5085 || DECL_NAME (r) == heap_identifier
5086 || DECL_NAME (r) == heap_vec_uninit_identifier
5087 || DECL_NAME (r) == heap_vec_identifier)
5089 error_at (loc, "the content of uninitialized storage is not usable "
5090 "in a constant expression");
5091 inform (DECL_SOURCE_LOCATION (r), "allocated here");
5092 return;
5094 if (DECL_NAME (r) == heap_deleted_identifier)
5096 error_at (loc, "use of allocated storage after deallocation in a "
5097 "constant expression");
5098 inform (DECL_SOURCE_LOCATION (r), "allocated here");
5099 return;
5101 error_at (loc, "the value of %qD is not usable in a constant "
5102 "expression", r);
5103 /* Avoid error cascade. */
5104 if (DECL_INITIAL (r) == error_mark_node)
5105 return;
5106 if (DECL_DECLARED_CONSTEXPR_P (r))
5107 inform (DECL_SOURCE_LOCATION (r),
5108 "%qD used in its own initializer", r);
5109 else if (INTEGRAL_OR_ENUMERATION_TYPE_P (type))
5111 if (!CP_TYPE_CONST_P (type))
5112 inform (DECL_SOURCE_LOCATION (r),
5113 "%q#D is not const", r);
5114 else if (CP_TYPE_VOLATILE_P (type))
5115 inform (DECL_SOURCE_LOCATION (r),
5116 "%q#D is volatile", r);
5117 else if (!DECL_INITIAL (r)
5118 || !TREE_CONSTANT (DECL_INITIAL (r))
5119 || !DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (r))
5120 inform (DECL_SOURCE_LOCATION (r),
5121 "%qD was not initialized with a constant "
5122 "expression", r);
5123 else
5124 gcc_unreachable ();
5126 else if (TYPE_REF_P (type))
5127 inform (DECL_SOURCE_LOCATION (r),
5128 "%qD was not initialized with a constant "
5129 "expression", r);
5130 else
5132 if (cxx_dialect >= cxx11 && !DECL_DECLARED_CONSTEXPR_P (r))
5133 inform (DECL_SOURCE_LOCATION (r),
5134 "%qD was not declared %<constexpr%>", r);
5135 else
5136 inform (DECL_SOURCE_LOCATION (r),
5137 "%qD does not have integral or enumeration type",
5142 /* Subroutine of cxx_eval_constant_expression.
5143 Like cxx_eval_unary_expression, except for trinary expressions. */
5145 static tree
5146 cxx_eval_trinary_expression (const constexpr_ctx *ctx, tree t,
5147 bool lval,
5148 bool *non_constant_p, bool *overflow_p)
5150 int i;
5151 tree args[3];
5152 tree val;
5154 for (i = 0; i < 3; i++)
5156 args[i] = cxx_eval_constant_expression (ctx, TREE_OPERAND (t, i),
5157 lval,
5158 non_constant_p, overflow_p);
5159 VERIFY_CONSTANT (args[i]);
5162 val = fold_ternary_loc (EXPR_LOCATION (t), TREE_CODE (t), TREE_TYPE (t),
5163 args[0], args[1], args[2]);
5164 if (val == NULL_TREE)
5165 return t;
5166 VERIFY_CONSTANT (val);
5167 return val;
5170 /* True if T was declared in a function declared to be constexpr, and
5171 therefore potentially constant in C++14. */
5173 bool
5174 var_in_constexpr_fn (tree t)
5176 tree ctx = DECL_CONTEXT (t);
5177 return (ctx && TREE_CODE (ctx) == FUNCTION_DECL
5178 && DECL_DECLARED_CONSTEXPR_P (ctx));
5181 /* True if a function might be constexpr: either a function that was
5182 declared constexpr, or a C++17 lambda op(). */
5184 bool
5185 maybe_constexpr_fn (tree t)
5187 return (DECL_DECLARED_CONSTEXPR_P (t)
5188 || (cxx_dialect >= cxx17 && LAMBDA_FUNCTION_P (t)));
5191 /* True if T was declared in a function that might be constexpr: either a
5192 function that was declared constexpr, or a C++17 lambda op(). */
5194 bool
5195 var_in_maybe_constexpr_fn (tree t)
5197 if (cxx_dialect >= cxx17
5198 && DECL_FUNCTION_SCOPE_P (t)
5199 && LAMBDA_FUNCTION_P (DECL_CONTEXT (t)))
5200 return true;
5201 return var_in_constexpr_fn (t);
5204 /* We're assigning INIT to TARGET. In do_build_copy_constructor and
5205 build_over_call we implement trivial copy of a class with tail padding using
5206 assignment of character arrays, which is valid in normal code, but not in
5207 constexpr evaluation. We don't need to worry about clobbering tail padding
5208 in constexpr evaluation, so strip the type punning. */
5210 static void
5211 maybe_simplify_trivial_copy (tree &target, tree &init)
5213 if (TREE_CODE (target) == MEM_REF
5214 && TREE_CODE (init) == MEM_REF
5215 && TREE_TYPE (target) == TREE_TYPE (init)
5216 && TREE_CODE (TREE_TYPE (target)) == ARRAY_TYPE
5217 && TREE_TYPE (TREE_TYPE (target)) == unsigned_char_type_node)
5219 target = build_fold_indirect_ref (TREE_OPERAND (target, 0));
5220 init = build_fold_indirect_ref (TREE_OPERAND (init, 0));
5224 /* Returns true if REF, which is a COMPONENT_REF, has any fields
5225 of constant type. This does not check for 'mutable', so the
5226 caller is expected to be mindful of that. */
5228 static bool
5229 cref_has_const_field (tree ref)
5231 while (TREE_CODE (ref) == COMPONENT_REF)
5233 if (CP_TYPE_CONST_P (TREE_TYPE (TREE_OPERAND (ref, 1))))
5234 return true;
5235 ref = TREE_OPERAND (ref, 0);
5237 return false;
5240 /* Return true if we are modifying something that is const during constant
5241 expression evaluation. CODE is the code of the statement, OBJ is the
5242 object in question, MUTABLE_P is true if one of the subobjects were
5243 declared mutable. */
5245 static bool
5246 modifying_const_object_p (tree_code code, tree obj, bool mutable_p)
5248 /* If this is initialization, there's no problem. */
5249 if (code != MODIFY_EXPR)
5250 return false;
5252 /* [basic.type.qualifier] "A const object is an object of type
5253 const T or a non-mutable subobject of a const object." */
5254 if (mutable_p)
5255 return false;
5257 if (TREE_READONLY (obj))
5258 return true;
5260 if (CP_TYPE_CONST_P (TREE_TYPE (obj)))
5262 /* Although a COMPONENT_REF may have a const type, we should
5263 only consider it modifying a const object when any of the
5264 field components is const. This can happen when using
5265 constructs such as const_cast<const T &>(m), making something
5266 const even though it wasn't declared const. */
5267 if (TREE_CODE (obj) == COMPONENT_REF)
5268 return cref_has_const_field (obj);
5269 else
5270 return true;
5273 return false;
5276 /* Evaluate an INIT_EXPR or MODIFY_EXPR. */
5278 static tree
5279 cxx_eval_store_expression (const constexpr_ctx *ctx, tree t,
5280 bool lval,
5281 bool *non_constant_p, bool *overflow_p)
5283 constexpr_ctx new_ctx = *ctx;
5285 tree init = TREE_OPERAND (t, 1);
5286 if (TREE_CLOBBER_P (init))
5287 /* Just ignore clobbers. */
5288 return void_node;
5290 /* First we figure out where we're storing to. */
5291 tree target = TREE_OPERAND (t, 0);
5293 maybe_simplify_trivial_copy (target, init);
5295 tree type = TREE_TYPE (target);
5296 bool preeval = SCALAR_TYPE_P (type) || TREE_CODE (t) == MODIFY_EXPR;
5297 if (preeval)
5299 /* Evaluate the value to be stored without knowing what object it will be
5300 stored in, so that any side-effects happen first. */
5301 if (!SCALAR_TYPE_P (type))
5302 new_ctx.ctor = new_ctx.object = NULL_TREE;
5303 init = cxx_eval_constant_expression (&new_ctx, init, false,
5304 non_constant_p, overflow_p);
5305 if (*non_constant_p)
5306 return t;
5309 bool evaluated = false;
5310 if (lval)
5312 /* If we want to return a reference to the target, we need to evaluate it
5313 as a whole; otherwise, only evaluate the innermost piece to avoid
5314 building up unnecessary *_REFs. */
5315 target = cxx_eval_constant_expression (ctx, target, true,
5316 non_constant_p, overflow_p);
5317 evaluated = true;
5318 if (*non_constant_p)
5319 return t;
5322 /* Find the underlying variable. */
5323 releasing_vec refs;
5324 tree object = NULL_TREE;
5325 /* If we're modifying a const object, save it. */
5326 tree const_object_being_modified = NULL_TREE;
5327 bool mutable_p = false;
5328 for (tree probe = target; object == NULL_TREE; )
5330 switch (TREE_CODE (probe))
5332 case BIT_FIELD_REF:
5333 case COMPONENT_REF:
5334 case ARRAY_REF:
5336 tree ob = TREE_OPERAND (probe, 0);
5337 tree elt = TREE_OPERAND (probe, 1);
5338 if (TREE_CODE (elt) == FIELD_DECL && DECL_MUTABLE_P (elt))
5339 mutable_p = true;
5340 if (TREE_CODE (probe) == ARRAY_REF)
5342 elt = eval_and_check_array_index (ctx, probe, false,
5343 non_constant_p, overflow_p);
5344 if (*non_constant_p)
5345 return t;
5347 /* We don't check modifying_const_object_p for ARRAY_REFs. Given
5348 "int a[10]", an ARRAY_REF "a[2]" can be "const int", even though
5349 the array isn't const. Instead, check "a" in the next iteration;
5350 that will detect modifying "const int a[10]". */
5351 else if (evaluated
5352 && modifying_const_object_p (TREE_CODE (t), probe,
5353 mutable_p)
5354 && const_object_being_modified == NULL_TREE)
5355 const_object_being_modified = probe;
5356 vec_safe_push (refs, elt);
5357 vec_safe_push (refs, TREE_TYPE (probe));
5358 probe = ob;
5360 break;
5362 default:
5363 if (evaluated)
5364 object = probe;
5365 else
5367 probe = cxx_eval_constant_expression (ctx, probe, true,
5368 non_constant_p, overflow_p);
5369 evaluated = true;
5370 if (*non_constant_p)
5371 return t;
5373 break;
5377 if (modifying_const_object_p (TREE_CODE (t), object, mutable_p)
5378 && const_object_being_modified == NULL_TREE)
5379 const_object_being_modified = object;
5381 /* And then find/build up our initializer for the path to the subobject
5382 we're initializing. */
5383 tree *valp;
5384 if (DECL_P (object))
5385 valp = ctx->global->values.get (object);
5386 else
5387 valp = NULL;
5388 if (!valp)
5390 /* A constant-expression cannot modify objects from outside the
5391 constant-expression. */
5392 if (!ctx->quiet)
5393 error ("modification of %qE is not a constant expression", object);
5394 *non_constant_p = true;
5395 return t;
5397 type = TREE_TYPE (object);
5398 bool no_zero_init = true;
5400 releasing_vec ctors, indexes;
5401 auto_vec<int> index_pos_hints;
5402 bool activated_union_member_p = false;
5403 while (!refs->is_empty ())
5405 if (*valp == NULL_TREE)
5407 *valp = build_constructor (type, NULL);
5408 CONSTRUCTOR_NO_CLEARING (*valp) = no_zero_init;
5410 else if (TREE_CODE (*valp) == STRING_CST)
5412 /* An array was initialized with a string constant, and now
5413 we're writing into one of its elements. Explode the
5414 single initialization into a set of element
5415 initializations. */
5416 gcc_assert (TREE_CODE (type) == ARRAY_TYPE);
5418 tree string = *valp;
5419 tree elt_type = TREE_TYPE (type);
5420 unsigned chars_per_elt = (TYPE_PRECISION (elt_type)
5421 / TYPE_PRECISION (char_type_node));
5422 unsigned num_elts = TREE_STRING_LENGTH (string) / chars_per_elt;
5423 tree ary_ctor = build_constructor (type, NULL);
5425 vec_safe_reserve (CONSTRUCTOR_ELTS (ary_ctor), num_elts);
5426 for (unsigned ix = 0; ix != num_elts; ix++)
5428 constructor_elt elt =
5430 build_int_cst (size_type_node, ix),
5431 extract_string_elt (string, chars_per_elt, ix)
5433 CONSTRUCTOR_ELTS (ary_ctor)->quick_push (elt);
5436 *valp = ary_ctor;
5439 /* If the value of object is already zero-initialized, any new ctors for
5440 subobjects will also be zero-initialized. */
5441 no_zero_init = CONSTRUCTOR_NO_CLEARING (*valp);
5443 enum tree_code code = TREE_CODE (type);
5444 type = refs->pop();
5445 tree index = refs->pop();
5447 if (code == RECORD_TYPE && is_empty_field (index))
5448 /* Don't build a sub-CONSTRUCTOR for an empty base or field, as they
5449 have no data and might have an offset lower than previously declared
5450 fields, which confuses the middle-end. The code below will notice
5451 that we don't have a CONSTRUCTOR for our inner target and just
5452 return init. */
5453 break;
5455 if (code == UNION_TYPE && CONSTRUCTOR_NELTS (*valp)
5456 && CONSTRUCTOR_ELT (*valp, 0)->index != index)
5458 if (cxx_dialect < cxx20)
5460 if (!ctx->quiet)
5461 error_at (cp_expr_loc_or_input_loc (t),
5462 "change of the active member of a union "
5463 "from %qD to %qD",
5464 CONSTRUCTOR_ELT (*valp, 0)->index,
5465 index);
5466 *non_constant_p = true;
5468 else if (TREE_CODE (t) == MODIFY_EXPR
5469 && CONSTRUCTOR_NO_CLEARING (*valp))
5471 /* Diagnose changing the active union member while the union
5472 is in the process of being initialized. */
5473 if (!ctx->quiet)
5474 error_at (cp_expr_loc_or_input_loc (t),
5475 "change of the active member of a union "
5476 "from %qD to %qD during initialization",
5477 CONSTRUCTOR_ELT (*valp, 0)->index,
5478 index);
5479 *non_constant_p = true;
5481 no_zero_init = true;
5484 vec_safe_push (ctors, *valp);
5485 vec_safe_push (indexes, index);
5487 constructor_elt *cep
5488 = get_or_insert_ctor_field (*valp, index);
5489 index_pos_hints.safe_push (cep - CONSTRUCTOR_ELTS (*valp)->begin());
5491 if (code == UNION_TYPE)
5492 activated_union_member_p = true;
5494 valp = &cep->value;
5497 /* Detect modifying a constant object in constexpr evaluation.
5498 We have found a const object that is being modified. Figure out
5499 if we need to issue an error. Consider
5501 struct A {
5502 int n;
5503 constexpr A() : n(1) { n = 2; } // #1
5505 struct B {
5506 const A a;
5507 constexpr B() { a.n = 3; } // #2
5509 constexpr B b{};
5511 #1 is OK, since we're modifying an object under construction, but
5512 #2 is wrong, since "a" is const and has been fully constructed.
5513 To track it, we use the TREE_READONLY bit in the object's CONSTRUCTOR
5514 which means that the object is read-only. For the example above, the
5515 *ctors stack at the point of #2 will look like:
5517 ctors[0] = {.a={.n=2}} TREE_READONLY = 0
5518 ctors[1] = {.n=2} TREE_READONLY = 1
5520 and we're modifying "b.a", so we search the stack and see if the
5521 constructor for "b.a" has already run. */
5522 if (const_object_being_modified)
5524 bool fail = false;
5525 tree const_objtype
5526 = strip_array_types (TREE_TYPE (const_object_being_modified));
5527 if (!CLASS_TYPE_P (const_objtype))
5528 fail = true;
5529 else
5531 /* [class.ctor]p5 "A constructor can be invoked for a const,
5532 volatile, or const volatile object. const and volatile
5533 semantics are not applied on an object under construction.
5534 They come into effect when the constructor for the most
5535 derived object ends." */
5536 for (tree elt : *ctors)
5537 if (same_type_ignoring_top_level_qualifiers_p
5538 (TREE_TYPE (const_object_being_modified), TREE_TYPE (elt)))
5540 fail = TREE_READONLY (elt);
5541 break;
5544 if (fail)
5546 if (!ctx->quiet)
5547 modifying_const_object_error (t, const_object_being_modified);
5548 *non_constant_p = true;
5549 return t;
5553 if (!preeval)
5555 /* We're handling an INIT_EXPR of class type, so the value of the
5556 initializer can depend on the object it's initializing. */
5558 /* Create a new CONSTRUCTOR in case evaluation of the initializer
5559 wants to modify it. */
5560 if (*valp == NULL_TREE)
5562 *valp = build_constructor (type, NULL);
5563 CONSTRUCTOR_NO_CLEARING (*valp) = no_zero_init;
5565 new_ctx.ctor = *valp;
5566 new_ctx.object = target;
5567 /* Avoid temporary materialization when initializing from a TARGET_EXPR.
5568 We don't need to mess with AGGR_EXPR_SLOT/VEC_INIT_EXPR_SLOT because
5569 expansion of those trees uses ctx instead. */
5570 if (TREE_CODE (init) == TARGET_EXPR)
5571 if (tree tinit = TARGET_EXPR_INITIAL (init))
5572 init = tinit;
5573 init = cxx_eval_constant_expression (&new_ctx, init, false,
5574 non_constant_p, overflow_p);
5575 /* The hash table might have moved since the get earlier, and the
5576 initializer might have mutated the underlying CONSTRUCTORs, so we must
5577 recompute VALP. */
5578 valp = ctx->global->values.get (object);
5579 for (unsigned i = 0; i < vec_safe_length (indexes); i++)
5581 constructor_elt *cep
5582 = get_or_insert_ctor_field (*valp, indexes[i], index_pos_hints[i]);
5583 valp = &cep->value;
5587 /* Don't share a CONSTRUCTOR that might be changed later. */
5588 init = unshare_constructor (init);
5590 if (*valp && TREE_CODE (*valp) == CONSTRUCTOR
5591 && TREE_CODE (init) == CONSTRUCTOR)
5593 /* An outer ctx->ctor might be pointing to *valp, so replace
5594 its contents. */
5595 if (!same_type_ignoring_top_level_qualifiers_p (TREE_TYPE (init),
5596 TREE_TYPE (*valp)))
5598 /* For initialization of an empty base, the original target will be
5599 *(base*)this, evaluation of which resolves to the object
5600 argument, which has the derived type rather than the base type. In
5601 this situation, just evaluate the initializer and return, since
5602 there's no actual data to store. */
5603 gcc_assert (is_empty_class (TREE_TYPE (init)));
5604 return lval ? target : init;
5606 CONSTRUCTOR_ELTS (*valp) = CONSTRUCTOR_ELTS (init);
5607 TREE_CONSTANT (*valp) = TREE_CONSTANT (init);
5608 TREE_SIDE_EFFECTS (*valp) = TREE_SIDE_EFFECTS (init);
5609 CONSTRUCTOR_NO_CLEARING (*valp)
5610 = CONSTRUCTOR_NO_CLEARING (init);
5612 else if (TREE_CODE (init) == CONSTRUCTOR
5613 && !same_type_ignoring_top_level_qualifiers_p (TREE_TYPE (init),
5614 type))
5616 /* See above on initialization of empty bases. */
5617 gcc_assert (is_empty_class (TREE_TYPE (init)) && !lval);
5618 return init;
5620 else
5621 *valp = init;
5623 /* After initialization, 'const' semantics apply to the value of the
5624 object. Make a note of this fact by marking the CONSTRUCTOR
5625 TREE_READONLY. */
5626 if (TREE_CODE (t) == INIT_EXPR
5627 && TREE_CODE (*valp) == CONSTRUCTOR
5628 && TYPE_READONLY (type))
5630 if (INDIRECT_REF_P (target)
5631 && (is_this_parameter
5632 (tree_strip_nop_conversions (TREE_OPERAND (target, 0)))))
5633 /* We've just initialized '*this' (perhaps via the target
5634 constructor of a delegating constructor). Leave it up to the
5635 caller that set 'this' to set TREE_READONLY appropriately. */
5636 gcc_checking_assert (same_type_ignoring_top_level_qualifiers_p
5637 (TREE_TYPE (target), type));
5638 else
5639 TREE_READONLY (*valp) = true;
5642 /* Update TREE_CONSTANT and TREE_SIDE_EFFECTS on enclosing
5643 CONSTRUCTORs, if any. */
5644 bool c = TREE_CONSTANT (init);
5645 bool s = TREE_SIDE_EFFECTS (init);
5646 if (!c || s || activated_union_member_p)
5647 for (tree elt : *ctors)
5649 if (!c)
5650 TREE_CONSTANT (elt) = false;
5651 if (s)
5652 TREE_SIDE_EFFECTS (elt) = true;
5653 /* Clear CONSTRUCTOR_NO_CLEARING since we've activated a member of
5654 this union. */
5655 if (TREE_CODE (TREE_TYPE (elt)) == UNION_TYPE)
5656 CONSTRUCTOR_NO_CLEARING (elt) = false;
5659 if (*non_constant_p)
5660 return t;
5661 else if (lval)
5662 return target;
5663 else
5664 return init;
5667 /* Evaluate a ++ or -- expression. */
5669 static tree
5670 cxx_eval_increment_expression (const constexpr_ctx *ctx, tree t,
5671 bool lval,
5672 bool *non_constant_p, bool *overflow_p)
5674 enum tree_code code = TREE_CODE (t);
5675 tree type = TREE_TYPE (t);
5676 tree op = TREE_OPERAND (t, 0);
5677 tree offset = TREE_OPERAND (t, 1);
5678 gcc_assert (TREE_CONSTANT (offset));
5680 /* OFFSET is constant, but perhaps not constant enough. We need to
5681 e.g. bash FLOAT_EXPRs to REAL_CSTs. */
5682 offset = fold_simple (offset);
5684 /* The operand as an lvalue. */
5685 op = cxx_eval_constant_expression (ctx, op, true,
5686 non_constant_p, overflow_p);
5688 /* The operand as an rvalue. */
5689 tree val
5690 = cxx_eval_constant_expression (ctx, op, false,
5691 non_constant_p, overflow_p);
5692 /* Don't VERIFY_CONSTANT if this might be dealing with a pointer to
5693 a local array in a constexpr function. */
5694 bool ptr = INDIRECT_TYPE_P (TREE_TYPE (val));
5695 if (!ptr)
5696 VERIFY_CONSTANT (val);
5698 /* The modified value. */
5699 bool inc = (code == PREINCREMENT_EXPR || code == POSTINCREMENT_EXPR);
5700 tree mod;
5701 if (INDIRECT_TYPE_P (type))
5703 /* The middle end requires pointers to use POINTER_PLUS_EXPR. */
5704 offset = convert_to_ptrofftype (offset);
5705 if (!inc)
5706 offset = fold_build1 (NEGATE_EXPR, TREE_TYPE (offset), offset);
5707 mod = fold_build2 (POINTER_PLUS_EXPR, type, val, offset);
5709 else
5710 mod = fold_build2 (inc ? PLUS_EXPR : MINUS_EXPR, type, val, offset);
5711 if (!ptr)
5712 VERIFY_CONSTANT (mod);
5714 /* Storing the modified value. */
5715 tree store = build2_loc (cp_expr_loc_or_loc (t, input_location),
5716 MODIFY_EXPR, type, op, mod);
5717 mod = cxx_eval_constant_expression (ctx, store, lval,
5718 non_constant_p, overflow_p);
5719 ggc_free (store);
5720 if (*non_constant_p)
5721 return t;
5723 /* And the value of the expression. */
5724 if (code == PREINCREMENT_EXPR || code == PREDECREMENT_EXPR)
5725 /* Prefix ops are lvalues, but the caller might want an rvalue;
5726 lval has already been taken into account in the store above. */
5727 return mod;
5728 else
5729 /* Postfix ops are rvalues. */
5730 return val;
5733 /* Predicates for the meaning of *jump_target. */
5735 static bool
5736 returns (tree *jump_target)
5738 return *jump_target
5739 && (TREE_CODE (*jump_target) == RETURN_EXPR
5740 || (TREE_CODE (*jump_target) == LABEL_DECL
5741 && LABEL_DECL_CDTOR (*jump_target)));
5744 static bool
5745 breaks (tree *jump_target)
5747 return *jump_target
5748 && ((TREE_CODE (*jump_target) == LABEL_DECL
5749 && LABEL_DECL_BREAK (*jump_target))
5750 || TREE_CODE (*jump_target) == BREAK_STMT
5751 || TREE_CODE (*jump_target) == EXIT_EXPR);
5754 static bool
5755 continues (tree *jump_target)
5757 return *jump_target
5758 && ((TREE_CODE (*jump_target) == LABEL_DECL
5759 && LABEL_DECL_CONTINUE (*jump_target))
5760 || TREE_CODE (*jump_target) == CONTINUE_STMT);
5764 static bool
5765 switches (tree *jump_target)
5767 return *jump_target
5768 && TREE_CODE (*jump_target) == INTEGER_CST;
5771 /* Subroutine of cxx_eval_statement_list. Determine whether the statement
5772 STMT matches *jump_target. If we're looking for a case label and we see
5773 the default label, note it in ctx->css_state. */
5775 static bool
5776 label_matches (const constexpr_ctx *ctx, tree *jump_target, tree stmt)
5778 switch (TREE_CODE (*jump_target))
5780 case LABEL_DECL:
5781 if (TREE_CODE (stmt) == LABEL_EXPR
5782 && LABEL_EXPR_LABEL (stmt) == *jump_target)
5783 return true;
5784 break;
5786 case INTEGER_CST:
5787 if (TREE_CODE (stmt) == CASE_LABEL_EXPR)
5789 gcc_assert (ctx->css_state != NULL);
5790 if (!CASE_LOW (stmt))
5792 /* default: should appear just once in a SWITCH_EXPR
5793 body (excluding nested SWITCH_EXPR). */
5794 gcc_assert (*ctx->css_state != css_default_seen);
5795 /* When evaluating SWITCH_EXPR body for the second time,
5796 return true for the default: label. */
5797 if (*ctx->css_state == css_default_processing)
5798 return true;
5799 *ctx->css_state = css_default_seen;
5801 else if (CASE_HIGH (stmt))
5803 if (tree_int_cst_le (CASE_LOW (stmt), *jump_target)
5804 && tree_int_cst_le (*jump_target, CASE_HIGH (stmt)))
5805 return true;
5807 else if (tree_int_cst_equal (*jump_target, CASE_LOW (stmt)))
5808 return true;
5810 break;
5812 case BREAK_STMT:
5813 case CONTINUE_STMT:
5814 /* These two are handled directly in cxx_eval_loop_expr by testing
5815 breaks (jump_target) or continues (jump_target). */
5816 break;
5818 default:
5819 gcc_unreachable ();
5821 return false;
5824 /* Evaluate a STATEMENT_LIST for side-effects. Handles various jump
5825 semantics, for switch, break, continue, and return. */
5827 static tree
5828 cxx_eval_statement_list (const constexpr_ctx *ctx, tree t,
5829 bool *non_constant_p, bool *overflow_p,
5830 tree *jump_target)
5832 tree local_target;
5833 /* In a statement-expression we want to return the last value.
5834 For empty statement expression return void_node. */
5835 tree r = void_node;
5836 if (!jump_target)
5838 local_target = NULL_TREE;
5839 jump_target = &local_target;
5841 for (tree stmt : tsi_range (t))
5843 /* We've found a continue, so skip everything until we reach
5844 the label its jumping to. */
5845 if (continues (jump_target))
5847 if (label_matches (ctx, jump_target, stmt))
5848 /* Found it. */
5849 *jump_target = NULL_TREE;
5850 else
5851 continue;
5853 if (TREE_CODE (stmt) == DEBUG_BEGIN_STMT)
5854 continue;
5855 r = cxx_eval_constant_expression (ctx, stmt, false,
5856 non_constant_p, overflow_p,
5857 jump_target);
5858 if (*non_constant_p)
5859 break;
5860 if (returns (jump_target) || breaks (jump_target))
5861 break;
5863 if (*jump_target && jump_target == &local_target)
5865 /* We aren't communicating the jump to our caller, so give up. We don't
5866 need to support evaluation of jumps out of statement-exprs. */
5867 if (!ctx->quiet)
5868 error_at (cp_expr_loc_or_input_loc (r),
5869 "statement is not a constant expression");
5870 *non_constant_p = true;
5872 return r;
5875 /* Evaluate a LOOP_EXPR for side-effects. Handles break and return
5876 semantics; continue semantics are covered by cxx_eval_statement_list. */
5878 static tree
5879 cxx_eval_loop_expr (const constexpr_ctx *ctx, tree t,
5880 bool *non_constant_p, bool *overflow_p,
5881 tree *jump_target)
5883 constexpr_ctx new_ctx = *ctx;
5884 tree local_target;
5885 if (!jump_target)
5887 local_target = NULL_TREE;
5888 jump_target = &local_target;
5891 tree body, cond = NULL_TREE, expr = NULL_TREE;
5892 int count = 0;
5893 switch (TREE_CODE (t))
5895 case LOOP_EXPR:
5896 body = LOOP_EXPR_BODY (t);
5897 break;
5898 case DO_STMT:
5899 body = DO_BODY (t);
5900 cond = DO_COND (t);
5901 break;
5902 case WHILE_STMT:
5903 body = WHILE_BODY (t);
5904 cond = WHILE_COND (t);
5905 count = -1;
5906 break;
5907 case FOR_STMT:
5908 if (FOR_INIT_STMT (t))
5909 cxx_eval_constant_expression (ctx, FOR_INIT_STMT (t), /*lval*/false,
5910 non_constant_p, overflow_p, jump_target);
5911 if (*non_constant_p)
5912 return NULL_TREE;
5913 body = FOR_BODY (t);
5914 cond = FOR_COND (t);
5915 expr = FOR_EXPR (t);
5916 count = -1;
5917 break;
5918 default:
5919 gcc_unreachable ();
5921 auto_vec<tree, 10> save_exprs;
5922 new_ctx.save_exprs = &save_exprs;
5925 if (count != -1)
5927 if (body)
5928 cxx_eval_constant_expression (&new_ctx, body, /*lval*/false,
5929 non_constant_p, overflow_p,
5930 jump_target);
5931 if (breaks (jump_target))
5933 *jump_target = NULL_TREE;
5934 break;
5937 if (TREE_CODE (t) != LOOP_EXPR && continues (jump_target))
5938 *jump_target = NULL_TREE;
5940 if (expr)
5941 cxx_eval_constant_expression (&new_ctx, expr, /*lval*/false,
5942 non_constant_p, overflow_p,
5943 jump_target);
5946 if (cond)
5948 tree res
5949 = cxx_eval_constant_expression (&new_ctx, cond, /*lval*/false,
5950 non_constant_p, overflow_p,
5951 jump_target);
5952 if (res)
5954 if (verify_constant (res, ctx->quiet, non_constant_p,
5955 overflow_p))
5956 break;
5957 if (integer_zerop (res))
5958 break;
5960 else
5961 gcc_assert (*jump_target);
5964 /* Forget saved values of SAVE_EXPRs and TARGET_EXPRs. */
5965 for (tree save_expr : save_exprs)
5966 ctx->global->values.remove (save_expr);
5967 save_exprs.truncate (0);
5969 if (++count >= constexpr_loop_limit)
5971 if (!ctx->quiet)
5972 error_at (cp_expr_loc_or_input_loc (t),
5973 "%<constexpr%> loop iteration count exceeds limit of %d "
5974 "(use %<-fconstexpr-loop-limit=%> to increase the limit)",
5975 constexpr_loop_limit);
5976 *non_constant_p = true;
5977 break;
5980 while (!returns (jump_target)
5981 && !breaks (jump_target)
5982 && !continues (jump_target)
5983 && (!switches (jump_target) || count == 0)
5984 && !*non_constant_p);
5986 /* Forget saved values of SAVE_EXPRs and TARGET_EXPRs. */
5987 for (tree save_expr : save_exprs)
5988 ctx->global->values.remove (save_expr);
5990 return NULL_TREE;
5993 /* Evaluate a SWITCH_EXPR for side-effects. Handles switch and break jump
5994 semantics. */
5996 static tree
5997 cxx_eval_switch_expr (const constexpr_ctx *ctx, tree t,
5998 bool *non_constant_p, bool *overflow_p,
5999 tree *jump_target)
6001 tree cond
6002 = TREE_CODE (t) == SWITCH_STMT ? SWITCH_STMT_COND (t) : SWITCH_COND (t);
6003 cond = cxx_eval_constant_expression (ctx, cond, false,
6004 non_constant_p, overflow_p);
6005 VERIFY_CONSTANT (cond);
6006 *jump_target = cond;
6008 tree body
6009 = TREE_CODE (t) == SWITCH_STMT ? SWITCH_STMT_BODY (t) : SWITCH_BODY (t);
6010 constexpr_ctx new_ctx = *ctx;
6011 constexpr_switch_state css = css_default_not_seen;
6012 new_ctx.css_state = &css;
6013 cxx_eval_constant_expression (&new_ctx, body, false,
6014 non_constant_p, overflow_p, jump_target);
6015 if (switches (jump_target) && css == css_default_seen)
6017 /* If the SWITCH_EXPR body has default: label, process it once again,
6018 this time instructing label_matches to return true for default:
6019 label on switches (jump_target). */
6020 css = css_default_processing;
6021 cxx_eval_constant_expression (&new_ctx, body, false,
6022 non_constant_p, overflow_p, jump_target);
6024 if (breaks (jump_target) || switches (jump_target))
6025 *jump_target = NULL_TREE;
6026 return NULL_TREE;
6029 /* Find the object of TYPE under initialization in CTX. */
6031 static tree
6032 lookup_placeholder (const constexpr_ctx *ctx, bool lval, tree type)
6034 if (!ctx)
6035 return NULL_TREE;
6037 /* Prefer the outermost matching object, but don't cross
6038 CONSTRUCTOR_PLACEHOLDER_BOUNDARY constructors. */
6039 if (ctx->ctor && !CONSTRUCTOR_PLACEHOLDER_BOUNDARY (ctx->ctor))
6040 if (tree outer_ob = lookup_placeholder (ctx->parent, lval, type))
6041 return outer_ob;
6043 /* We could use ctx->object unconditionally, but using ctx->ctor when we
6044 can is a minor optimization. */
6045 if (!lval && ctx->ctor && same_type_p (TREE_TYPE (ctx->ctor), type))
6046 return ctx->ctor;
6048 if (!ctx->object)
6049 return NULL_TREE;
6051 /* Since an object cannot have a field of its own type, we can search outward
6052 from ctx->object to find the unique containing object of TYPE. */
6053 tree ob = ctx->object;
6054 while (ob)
6056 if (same_type_ignoring_top_level_qualifiers_p (TREE_TYPE (ob), type))
6057 break;
6058 if (handled_component_p (ob))
6059 ob = TREE_OPERAND (ob, 0);
6060 else
6061 ob = NULL_TREE;
6064 return ob;
6067 /* Complain about an attempt to evaluate inline assembly. */
6069 static void
6070 inline_asm_in_constexpr_error (location_t loc)
6072 auto_diagnostic_group d;
6073 error_at (loc, "inline assembly is not a constant expression");
6074 inform (loc, "only unevaluated inline assembly is allowed in a "
6075 "%<constexpr%> function in C++20");
6078 /* Attempt to reduce the expression T to a constant value.
6079 On failure, issue diagnostic and return error_mark_node. */
6080 /* FIXME unify with c_fully_fold */
6081 /* FIXME overflow_p is too global */
6083 static tree
6084 cxx_eval_constant_expression (const constexpr_ctx *ctx, tree t,
6085 bool lval,
6086 bool *non_constant_p, bool *overflow_p,
6087 tree *jump_target /* = NULL */)
6089 if (jump_target && *jump_target)
6091 /* If we are jumping, ignore all statements/expressions except those
6092 that could have LABEL_EXPR or CASE_LABEL_EXPR in their bodies. */
6093 switch (TREE_CODE (t))
6095 case BIND_EXPR:
6096 case STATEMENT_LIST:
6097 case LOOP_EXPR:
6098 case COND_EXPR:
6099 case IF_STMT:
6100 case DO_STMT:
6101 case WHILE_STMT:
6102 case FOR_STMT:
6103 break;
6104 case LABEL_EXPR:
6105 case CASE_LABEL_EXPR:
6106 if (label_matches (ctx, jump_target, t))
6107 /* Found it. */
6108 *jump_target = NULL_TREE;
6109 return NULL_TREE;
6110 default:
6111 return NULL_TREE;
6114 if (error_operand_p (t))
6116 *non_constant_p = true;
6117 return t;
6120 location_t loc = cp_expr_loc_or_input_loc (t);
6122 STRIP_ANY_LOCATION_WRAPPER (t);
6124 if (CONSTANT_CLASS_P (t))
6126 if (TREE_OVERFLOW (t))
6128 if (!ctx->quiet)
6129 permerror (input_location, "overflow in constant expression");
6130 if (!flag_permissive || ctx->quiet)
6131 *overflow_p = true;
6134 if (TREE_CODE (t) == INTEGER_CST
6135 && TYPE_PTR_P (TREE_TYPE (t))
6136 && !integer_zerop (t))
6138 if (!ctx->quiet)
6139 error ("value %qE of type %qT is not a constant expression",
6140 t, TREE_TYPE (t));
6141 *non_constant_p = true;
6144 return t;
6147 /* Avoid excessively long constexpr evaluations. */
6148 if (++ctx->global->constexpr_ops_count >= constexpr_ops_limit)
6150 if (!ctx->quiet)
6151 error_at (loc,
6152 "%<constexpr%> evaluation operation count exceeds limit of "
6153 "%wd (use %<-fconstexpr-ops-limit=%> to increase the limit)",
6154 constexpr_ops_limit);
6155 ctx->global->constexpr_ops_count = INTTYPE_MINIMUM (HOST_WIDE_INT);
6156 *non_constant_p = true;
6157 return t;
6160 constexpr_ctx new_ctx;
6161 tree r = t;
6163 tree_code tcode = TREE_CODE (t);
6164 switch (tcode)
6166 case RESULT_DECL:
6167 if (lval)
6168 return t;
6169 /* We ask for an rvalue for the RESULT_DECL when indirecting
6170 through an invisible reference, or in named return value
6171 optimization. */
6172 if (tree *p = ctx->global->values.get (t))
6173 return *p;
6174 else
6176 if (!ctx->quiet)
6177 error ("%qE is not a constant expression", t);
6178 *non_constant_p = true;
6180 break;
6182 case VAR_DECL:
6183 if (DECL_HAS_VALUE_EXPR_P (t))
6185 if (is_normal_capture_proxy (t)
6186 && current_function_decl == DECL_CONTEXT (t))
6188 /* Function parms aren't constexpr within the function
6189 definition, so don't try to look at the closure. But if the
6190 captured variable is constant, try to evaluate it directly. */
6191 r = DECL_CAPTURED_VARIABLE (t);
6192 tree type = TREE_TYPE (t);
6193 if (TYPE_REF_P (type) != TYPE_REF_P (TREE_TYPE (r)))
6195 /* Adjust r to match the reference-ness of t. */
6196 if (TYPE_REF_P (type))
6197 r = build_address (r);
6198 else
6199 r = convert_from_reference (r);
6202 else
6203 r = DECL_VALUE_EXPR (t);
6204 return cxx_eval_constant_expression (ctx, r, lval, non_constant_p,
6205 overflow_p);
6207 /* fall through */
6208 case CONST_DECL:
6209 /* We used to not check lval for CONST_DECL, but darwin.c uses
6210 CONST_DECL for aggregate constants. */
6211 if (lval)
6212 return t;
6213 else if (t == ctx->object)
6214 return ctx->ctor;
6215 if (VAR_P (t))
6216 if (tree *p = ctx->global->values.get (t))
6217 if (*p != NULL_TREE)
6219 r = *p;
6220 break;
6222 if (COMPLETE_TYPE_P (TREE_TYPE (t))
6223 && is_really_empty_class (TREE_TYPE (t), /*ignore_vptr*/false))
6225 /* If the class is empty, we aren't actually loading anything. */
6226 r = build_constructor (TREE_TYPE (t), NULL);
6227 TREE_CONSTANT (r) = true;
6229 else if (ctx->strict)
6230 r = decl_really_constant_value (t, /*unshare_p=*/false);
6231 else
6232 r = decl_constant_value (t, /*unshare_p=*/false);
6233 if (TREE_CODE (r) == TARGET_EXPR
6234 && TREE_CODE (TARGET_EXPR_INITIAL (r)) == CONSTRUCTOR)
6235 r = TARGET_EXPR_INITIAL (r);
6236 if (DECL_P (r))
6238 if (!ctx->quiet)
6239 non_const_var_error (loc, r);
6240 *non_constant_p = true;
6242 break;
6244 case DEBUG_BEGIN_STMT:
6245 /* ??? It might be nice to retain this information somehow, so
6246 as to be able to step into a constexpr function call. */
6247 /* Fall through. */
6249 case FUNCTION_DECL:
6250 case TEMPLATE_DECL:
6251 case LABEL_DECL:
6252 case LABEL_EXPR:
6253 case CASE_LABEL_EXPR:
6254 case PREDICT_EXPR:
6255 return t;
6257 case PARM_DECL:
6258 if (lval && !TYPE_REF_P (TREE_TYPE (t)))
6259 /* glvalue use. */;
6260 else if (tree *p = ctx->global->values.get (r))
6261 r = *p;
6262 else if (lval)
6263 /* Defer in case this is only used for its type. */;
6264 else if (COMPLETE_TYPE_P (TREE_TYPE (t))
6265 && is_really_empty_class (TREE_TYPE (t), /*ignore_vptr*/false))
6267 /* If the class is empty, we aren't actually loading anything. */
6268 r = build_constructor (TREE_TYPE (t), NULL);
6269 TREE_CONSTANT (r) = true;
6271 else
6273 if (!ctx->quiet)
6274 error ("%qE is not a constant expression", t);
6275 *non_constant_p = true;
6277 break;
6279 case CALL_EXPR:
6280 case AGGR_INIT_EXPR:
6281 r = cxx_eval_call_expression (ctx, t, lval,
6282 non_constant_p, overflow_p);
6283 break;
6285 case DECL_EXPR:
6287 r = DECL_EXPR_DECL (t);
6288 if (TREE_CODE (r) == USING_DECL)
6290 r = void_node;
6291 break;
6293 if (AGGREGATE_TYPE_P (TREE_TYPE (r))
6294 || VECTOR_TYPE_P (TREE_TYPE (r)))
6296 new_ctx = *ctx;
6297 new_ctx.object = r;
6298 new_ctx.ctor = build_constructor (TREE_TYPE (r), NULL);
6299 CONSTRUCTOR_NO_CLEARING (new_ctx.ctor) = true;
6300 ctx->global->values.put (r, new_ctx.ctor);
6301 ctx = &new_ctx;
6304 if (tree init = DECL_INITIAL (r))
6306 init = cxx_eval_constant_expression (ctx, init,
6307 false,
6308 non_constant_p, overflow_p);
6309 /* Don't share a CONSTRUCTOR that might be changed. */
6310 init = unshare_constructor (init);
6311 /* Remember that a constant object's constructor has already
6312 run. */
6313 if (CLASS_TYPE_P (TREE_TYPE (r))
6314 && CP_TYPE_CONST_P (TREE_TYPE (r)))
6315 TREE_READONLY (init) = true;
6316 ctx->global->values.put (r, init);
6318 else if (ctx == &new_ctx)
6319 /* We gave it a CONSTRUCTOR above. */;
6320 else
6321 ctx->global->values.put (r, NULL_TREE);
6323 break;
6325 case TARGET_EXPR:
6327 tree type = TREE_TYPE (t);
6329 if (!literal_type_p (type))
6331 if (!ctx->quiet)
6333 auto_diagnostic_group d;
6334 error ("temporary of non-literal type %qT in a "
6335 "constant expression", type);
6336 explain_non_literal_class (type);
6338 *non_constant_p = true;
6339 break;
6341 gcc_checking_assert (!TARGET_EXPR_DIRECT_INIT_P (t));
6342 /* Avoid evaluating a TARGET_EXPR more than once. */
6343 tree slot = TARGET_EXPR_SLOT (t);
6344 if (tree *p = ctx->global->values.get (slot))
6346 if (lval)
6347 return slot;
6348 r = *p;
6349 break;
6351 if ((AGGREGATE_TYPE_P (type) || VECTOR_TYPE_P (type)))
6353 /* We're being expanded without an explicit target, so start
6354 initializing a new object; expansion with an explicit target
6355 strips the TARGET_EXPR before we get here. */
6356 new_ctx = *ctx;
6357 /* Link CTX to NEW_CTX so that lookup_placeholder can resolve
6358 any PLACEHOLDER_EXPR within the initializer that refers to the
6359 former object under construction. */
6360 new_ctx.parent = ctx;
6361 new_ctx.ctor = build_constructor (type, NULL);
6362 CONSTRUCTOR_NO_CLEARING (new_ctx.ctor) = true;
6363 new_ctx.object = slot;
6364 ctx->global->values.put (new_ctx.object, new_ctx.ctor);
6365 ctx = &new_ctx;
6367 /* Pass false for 'lval' because this indicates
6368 initialization of a temporary. */
6369 r = cxx_eval_constant_expression (ctx, TREE_OPERAND (t, 1),
6370 false,
6371 non_constant_p, overflow_p);
6372 if (*non_constant_p)
6373 break;
6374 /* Adjust the type of the result to the type of the temporary. */
6375 r = adjust_temp_type (type, r);
6376 if (TARGET_EXPR_CLEANUP (t) && !CLEANUP_EH_ONLY (t))
6377 ctx->global->cleanups->safe_push (TARGET_EXPR_CLEANUP (t));
6378 r = unshare_constructor (r);
6379 ctx->global->values.put (slot, r);
6380 if (ctx->save_exprs)
6381 ctx->save_exprs->safe_push (slot);
6382 if (lval)
6383 return slot;
6385 break;
6387 case INIT_EXPR:
6388 case MODIFY_EXPR:
6389 gcc_assert (jump_target == NULL || *jump_target == NULL_TREE);
6390 r = cxx_eval_store_expression (ctx, t, lval,
6391 non_constant_p, overflow_p);
6392 break;
6394 case SCOPE_REF:
6395 r = cxx_eval_constant_expression (ctx, TREE_OPERAND (t, 1),
6396 lval,
6397 non_constant_p, overflow_p);
6398 break;
6400 case RETURN_EXPR:
6401 if (TREE_OPERAND (t, 0) != NULL_TREE)
6402 r = cxx_eval_constant_expression (ctx, TREE_OPERAND (t, 0),
6403 lval,
6404 non_constant_p, overflow_p);
6405 /* FALLTHRU */
6406 case BREAK_STMT:
6407 case CONTINUE_STMT:
6408 if (jump_target)
6409 *jump_target = t;
6410 else
6412 /* Can happen with ({ return true; }) && false; passed to
6413 maybe_constant_value. There is nothing to jump over in this
6414 case, and the bug will be diagnosed later. */
6415 gcc_assert (ctx->quiet);
6416 *non_constant_p = true;
6418 break;
6420 case SAVE_EXPR:
6421 /* Avoid evaluating a SAVE_EXPR more than once. */
6422 if (tree *p = ctx->global->values.get (t))
6423 r = *p;
6424 else
6426 r = cxx_eval_constant_expression (ctx, TREE_OPERAND (t, 0), false,
6427 non_constant_p, overflow_p);
6428 if (*non_constant_p)
6429 break;
6430 ctx->global->values.put (t, r);
6431 if (ctx->save_exprs)
6432 ctx->save_exprs->safe_push (t);
6434 break;
6436 case TRY_CATCH_EXPR:
6437 if (TREE_OPERAND (t, 0) == NULL_TREE)
6439 r = void_node;
6440 break;
6442 /* FALLTHRU */
6443 case NON_LVALUE_EXPR:
6444 case TRY_BLOCK:
6445 case MUST_NOT_THROW_EXPR:
6446 case EXPR_STMT:
6447 case EH_SPEC_BLOCK:
6448 r = cxx_eval_constant_expression (ctx, TREE_OPERAND (t, 0),
6449 lval,
6450 non_constant_p, overflow_p,
6451 jump_target);
6452 break;
6454 case CLEANUP_POINT_EXPR:
6456 auto_vec<tree, 2> cleanups;
6457 vec<tree> *prev_cleanups = ctx->global->cleanups;
6458 ctx->global->cleanups = &cleanups;
6459 r = cxx_eval_constant_expression (ctx, TREE_OPERAND (t, 0),
6460 lval,
6461 non_constant_p, overflow_p,
6462 jump_target);
6463 ctx->global->cleanups = prev_cleanups;
6464 unsigned int i;
6465 tree cleanup;
6466 /* Evaluate the cleanups. */
6467 FOR_EACH_VEC_ELT_REVERSE (cleanups, i, cleanup)
6468 cxx_eval_constant_expression (ctx, cleanup, false,
6469 non_constant_p, overflow_p);
6471 break;
6473 case TRY_FINALLY_EXPR:
6474 r = cxx_eval_constant_expression (ctx, TREE_OPERAND (t, 0), lval,
6475 non_constant_p, overflow_p,
6476 jump_target);
6477 if (!*non_constant_p)
6478 /* Also evaluate the cleanup. */
6479 cxx_eval_constant_expression (ctx, TREE_OPERAND (t, 1), true,
6480 non_constant_p, overflow_p);
6481 break;
6483 case CLEANUP_STMT:
6484 r = cxx_eval_constant_expression (ctx, CLEANUP_BODY (t), lval,
6485 non_constant_p, overflow_p,
6486 jump_target);
6487 if (!CLEANUP_EH_ONLY (t) && !*non_constant_p)
6489 iloc_sentinel ils (loc);
6490 /* Also evaluate the cleanup. */
6491 cxx_eval_constant_expression (ctx, CLEANUP_EXPR (t), true,
6492 non_constant_p, overflow_p);
6494 break;
6496 /* These differ from cxx_eval_unary_expression in that this doesn't
6497 check for a constant operand or result; an address can be
6498 constant without its operand being, and vice versa. */
6499 case MEM_REF:
6500 case INDIRECT_REF:
6501 r = cxx_eval_indirect_ref (ctx, t, lval,
6502 non_constant_p, overflow_p);
6503 break;
6505 case ADDR_EXPR:
6507 tree oldop = TREE_OPERAND (t, 0);
6508 tree op = cxx_eval_constant_expression (ctx, oldop,
6509 /*lval*/true,
6510 non_constant_p, overflow_p);
6511 /* Don't VERIFY_CONSTANT here. */
6512 if (*non_constant_p)
6513 return t;
6514 gcc_checking_assert (TREE_CODE (op) != CONSTRUCTOR);
6515 /* This function does more aggressive folding than fold itself. */
6516 r = build_fold_addr_expr_with_type (op, TREE_TYPE (t));
6517 if (TREE_CODE (r) == ADDR_EXPR && TREE_OPERAND (r, 0) == oldop)
6519 ggc_free (r);
6520 return t;
6522 break;
6525 case REALPART_EXPR:
6526 case IMAGPART_EXPR:
6527 if (lval)
6529 r = cxx_eval_constant_expression (ctx, TREE_OPERAND (t, 0), lval,
6530 non_constant_p, overflow_p);
6531 if (r == error_mark_node)
6533 else if (r == TREE_OPERAND (t, 0))
6534 r = t;
6535 else
6536 r = fold_build1 (TREE_CODE (t), TREE_TYPE (t), r);
6537 break;
6539 /* FALLTHRU */
6540 case CONJ_EXPR:
6541 case FIX_TRUNC_EXPR:
6542 case FLOAT_EXPR:
6543 case NEGATE_EXPR:
6544 case ABS_EXPR:
6545 case ABSU_EXPR:
6546 case BIT_NOT_EXPR:
6547 case TRUTH_NOT_EXPR:
6548 case FIXED_CONVERT_EXPR:
6549 r = cxx_eval_unary_expression (ctx, t, lval,
6550 non_constant_p, overflow_p);
6551 break;
6553 case SIZEOF_EXPR:
6554 r = fold_sizeof_expr (t);
6555 /* In a template, fold_sizeof_expr may merely create a new SIZEOF_EXPR,
6556 which could lead to an infinite recursion. */
6557 if (TREE_CODE (r) != SIZEOF_EXPR)
6558 r = cxx_eval_constant_expression (ctx, r, lval,
6559 non_constant_p, overflow_p,
6560 jump_target);
6561 else
6563 *non_constant_p = true;
6564 gcc_assert (ctx->quiet);
6567 break;
6569 case COMPOUND_EXPR:
6571 /* check_return_expr sometimes wraps a TARGET_EXPR in a
6572 COMPOUND_EXPR; don't get confused. Also handle EMPTY_CLASS_EXPR
6573 introduced by build_call_a. */
6574 tree op0 = TREE_OPERAND (t, 0);
6575 tree op1 = TREE_OPERAND (t, 1);
6576 STRIP_NOPS (op1);
6577 if ((TREE_CODE (op0) == TARGET_EXPR && op1 == TARGET_EXPR_SLOT (op0))
6578 || TREE_CODE (op1) == EMPTY_CLASS_EXPR)
6579 r = cxx_eval_constant_expression (ctx, op0,
6580 lval, non_constant_p, overflow_p,
6581 jump_target);
6582 else
6584 /* Check that the LHS is constant and then discard it. */
6585 cxx_eval_constant_expression (ctx, op0,
6586 true, non_constant_p, overflow_p,
6587 jump_target);
6588 if (*non_constant_p)
6589 return t;
6590 op1 = TREE_OPERAND (t, 1);
6591 r = cxx_eval_constant_expression (ctx, op1,
6592 lval, non_constant_p, overflow_p,
6593 jump_target);
6596 break;
6598 case POINTER_PLUS_EXPR:
6599 case POINTER_DIFF_EXPR:
6600 case PLUS_EXPR:
6601 case MINUS_EXPR:
6602 case MULT_EXPR:
6603 case TRUNC_DIV_EXPR:
6604 case CEIL_DIV_EXPR:
6605 case FLOOR_DIV_EXPR:
6606 case ROUND_DIV_EXPR:
6607 case TRUNC_MOD_EXPR:
6608 case CEIL_MOD_EXPR:
6609 case ROUND_MOD_EXPR:
6610 case RDIV_EXPR:
6611 case EXACT_DIV_EXPR:
6612 case MIN_EXPR:
6613 case MAX_EXPR:
6614 case LSHIFT_EXPR:
6615 case RSHIFT_EXPR:
6616 case LROTATE_EXPR:
6617 case RROTATE_EXPR:
6618 case BIT_IOR_EXPR:
6619 case BIT_XOR_EXPR:
6620 case BIT_AND_EXPR:
6621 case TRUTH_XOR_EXPR:
6622 case LT_EXPR:
6623 case LE_EXPR:
6624 case GT_EXPR:
6625 case GE_EXPR:
6626 case EQ_EXPR:
6627 case NE_EXPR:
6628 case SPACESHIP_EXPR:
6629 case UNORDERED_EXPR:
6630 case ORDERED_EXPR:
6631 case UNLT_EXPR:
6632 case UNLE_EXPR:
6633 case UNGT_EXPR:
6634 case UNGE_EXPR:
6635 case UNEQ_EXPR:
6636 case LTGT_EXPR:
6637 case RANGE_EXPR:
6638 case COMPLEX_EXPR:
6639 r = cxx_eval_binary_expression (ctx, t, lval,
6640 non_constant_p, overflow_p);
6641 break;
6643 /* fold can introduce non-IF versions of these; still treat them as
6644 short-circuiting. */
6645 case TRUTH_AND_EXPR:
6646 case TRUTH_ANDIF_EXPR:
6647 r = cxx_eval_logical_expression (ctx, t, boolean_false_node,
6648 boolean_true_node,
6649 lval,
6650 non_constant_p, overflow_p);
6651 break;
6653 case TRUTH_OR_EXPR:
6654 case TRUTH_ORIF_EXPR:
6655 r = cxx_eval_logical_expression (ctx, t, boolean_true_node,
6656 boolean_false_node,
6657 lval,
6658 non_constant_p, overflow_p);
6659 break;
6661 case ARRAY_REF:
6662 r = cxx_eval_array_reference (ctx, t, lval,
6663 non_constant_p, overflow_p);
6664 break;
6666 case COMPONENT_REF:
6667 if (is_overloaded_fn (t))
6669 /* We can only get here in checking mode via
6670 build_non_dependent_expr, because any expression that
6671 calls or takes the address of the function will have
6672 pulled a FUNCTION_DECL out of the COMPONENT_REF. */
6673 gcc_checking_assert (ctx->quiet || errorcount);
6674 *non_constant_p = true;
6675 return t;
6677 r = cxx_eval_component_reference (ctx, t, lval,
6678 non_constant_p, overflow_p);
6679 break;
6681 case BIT_FIELD_REF:
6682 r = cxx_eval_bit_field_ref (ctx, t, lval,
6683 non_constant_p, overflow_p);
6684 break;
6686 case COND_EXPR:
6687 case IF_STMT:
6688 if (jump_target && *jump_target)
6690 tree orig_jump = *jump_target;
6691 tree arg = ((TREE_CODE (t) != IF_STMT || TREE_OPERAND (t, 1))
6692 ? TREE_OPERAND (t, 1) : void_node);
6693 /* When jumping to a label, the label might be either in the
6694 then or else blocks, so process then block first in skipping
6695 mode first, and if we are still in the skipping mode at its end,
6696 process the else block too. */
6697 r = cxx_eval_constant_expression (ctx, arg, lval, non_constant_p,
6698 overflow_p, jump_target);
6699 /* It's possible that we found the label in the then block. But
6700 it could have been followed by another jumping statement, e.g.
6701 say we're looking for case 1:
6702 if (cond)
6704 // skipped statements
6705 case 1:; // clears up *jump_target
6706 return 1; // and sets it to a RETURN_EXPR
6708 else { ... }
6709 in which case we need not go looking to the else block.
6710 (goto is not allowed in a constexpr function.) */
6711 if (*jump_target == orig_jump)
6713 arg = ((TREE_CODE (t) != IF_STMT || TREE_OPERAND (t, 2))
6714 ? TREE_OPERAND (t, 2) : void_node);
6715 r = cxx_eval_constant_expression (ctx, arg, lval, non_constant_p,
6716 overflow_p, jump_target);
6718 break;
6720 r = cxx_eval_conditional_expression (ctx, t, lval,
6721 non_constant_p, overflow_p,
6722 jump_target);
6723 break;
6724 case VEC_COND_EXPR:
6725 r = cxx_eval_vector_conditional_expression (ctx, t, non_constant_p,
6726 overflow_p);
6727 break;
6729 case CONSTRUCTOR:
6730 if (TREE_CONSTANT (t) && reduced_constant_expression_p (t))
6732 /* Don't re-process a constant CONSTRUCTOR, but do fold it to
6733 VECTOR_CST if applicable. */
6734 verify_constructor_flags (t);
6735 if (TREE_CONSTANT (t))
6736 return fold (t);
6738 r = cxx_eval_bare_aggregate (ctx, t, lval,
6739 non_constant_p, overflow_p);
6740 break;
6742 case VEC_INIT_EXPR:
6743 /* We can get this in a defaulted constructor for a class with a
6744 non-static data member of array type. Either the initializer will
6745 be NULL, meaning default-initialization, or it will be an lvalue
6746 or xvalue of the same type, meaning direct-initialization from the
6747 corresponding member. */
6748 r = cxx_eval_vec_init (ctx, t, lval,
6749 non_constant_p, overflow_p);
6750 break;
6752 case VEC_PERM_EXPR:
6753 r = cxx_eval_trinary_expression (ctx, t, lval,
6754 non_constant_p, overflow_p);
6755 break;
6757 case NOP_EXPR:
6758 if (REINTERPRET_CAST_P (t))
6760 if (!ctx->quiet)
6761 error_at (loc,
6762 "%<reinterpret_cast%> is not a constant expression");
6763 *non_constant_p = true;
6764 return t;
6766 /* FALLTHROUGH. */
6767 case CONVERT_EXPR:
6768 case VIEW_CONVERT_EXPR:
6769 case UNARY_PLUS_EXPR:
6771 tree oldop = TREE_OPERAND (t, 0);
6773 tree op = cxx_eval_constant_expression (ctx, oldop,
6774 lval,
6775 non_constant_p, overflow_p);
6776 if (*non_constant_p)
6777 return t;
6778 tree type = TREE_TYPE (t);
6780 if (VOID_TYPE_P (type))
6781 return void_node;
6783 if (TREE_CODE (t) == CONVERT_EXPR
6784 && ARITHMETIC_TYPE_P (type)
6785 && INDIRECT_TYPE_P (TREE_TYPE (op))
6786 && ctx->manifestly_const_eval)
6788 if (!ctx->quiet)
6789 error_at (loc,
6790 "conversion from pointer type %qT to arithmetic type "
6791 "%qT in a constant expression", TREE_TYPE (op), type);
6792 *non_constant_p = true;
6793 return t;
6796 /* [expr.const]: a conversion from type cv void* to a pointer-to-object
6797 type cannot be part of a core constant expression as a resolution to
6798 DR 1312. */
6799 if (TYPE_PTROB_P (type)
6800 && TYPE_PTR_P (TREE_TYPE (op))
6801 && VOID_TYPE_P (TREE_TYPE (TREE_TYPE (op)))
6802 /* Inside a call to std::construct_at or to
6803 std::allocator<T>::{,de}allocate, we permit casting from void*
6804 because that is compiler-generated code. */
6805 && !is_std_construct_at (ctx->call)
6806 && !is_std_allocator_allocate (ctx->call))
6808 /* Likewise, don't error when casting from void* when OP is
6809 &heap uninit and similar. */
6810 tree sop = tree_strip_nop_conversions (op);
6811 if (TREE_CODE (sop) == ADDR_EXPR
6812 && VAR_P (TREE_OPERAND (sop, 0))
6813 && DECL_ARTIFICIAL (TREE_OPERAND (sop, 0)))
6814 /* OK */;
6815 else
6817 if (!ctx->quiet)
6818 error_at (loc, "cast from %qT is not allowed",
6819 TREE_TYPE (op));
6820 *non_constant_p = true;
6821 return t;
6825 if (TREE_CODE (op) == PTRMEM_CST && !TYPE_PTRMEM_P (type))
6826 op = cplus_expand_constant (op);
6828 if (TREE_CODE (op) == PTRMEM_CST && tcode == NOP_EXPR)
6830 if (!same_type_ignoring_top_level_qualifiers_p (type, TREE_TYPE (op))
6831 && !can_convert_qual (type, op))
6832 op = cplus_expand_constant (op);
6833 return cp_fold_convert (type, op);
6836 if (INDIRECT_TYPE_P (type) && TREE_CODE (op) == INTEGER_CST)
6838 if (integer_zerop (op))
6840 if (TYPE_REF_P (type))
6842 if (!ctx->quiet)
6843 error_at (loc, "dereferencing a null pointer");
6844 *non_constant_p = true;
6845 return t;
6848 else
6850 /* This detects for example:
6851 reinterpret_cast<void*>(sizeof 0)
6853 if (!ctx->quiet)
6854 error_at (loc, "%<reinterpret_cast<%T>(%E)%> is not "
6855 "a constant expression",
6856 type, op);
6857 *non_constant_p = true;
6858 return t;
6862 if (INDIRECT_TYPE_P (type)
6863 && TREE_CODE (op) == NOP_EXPR
6864 && TREE_TYPE (op) == ptr_type_node
6865 && TREE_CODE (TREE_OPERAND (op, 0)) == ADDR_EXPR
6866 && VAR_P (TREE_OPERAND (TREE_OPERAND (op, 0), 0))
6867 && (DECL_NAME (TREE_OPERAND (TREE_OPERAND (op, 0),
6868 0)) == heap_uninit_identifier
6869 || DECL_NAME (TREE_OPERAND (TREE_OPERAND (op, 0),
6870 0)) == heap_vec_uninit_identifier))
6872 tree var = TREE_OPERAND (TREE_OPERAND (op, 0), 0);
6873 tree var_size = TYPE_SIZE_UNIT (TREE_TYPE (var));
6874 tree elt_type = TREE_TYPE (type);
6875 tree cookie_size = NULL_TREE;
6876 if (TREE_CODE (elt_type) == RECORD_TYPE
6877 && TYPE_NAME (elt_type) == heap_identifier)
6879 tree fld1 = TYPE_FIELDS (elt_type);
6880 tree fld2 = DECL_CHAIN (fld1);
6881 elt_type = TREE_TYPE (TREE_TYPE (fld2));
6882 cookie_size = TYPE_SIZE_UNIT (TREE_TYPE (fld1));
6884 DECL_NAME (var)
6885 = (DECL_NAME (var) == heap_uninit_identifier
6886 ? heap_identifier : heap_vec_identifier);
6887 TREE_TYPE (var)
6888 = build_new_constexpr_heap_type (elt_type, cookie_size,
6889 var_size);
6890 TREE_TYPE (TREE_OPERAND (op, 0))
6891 = build_pointer_type (TREE_TYPE (var));
6894 if (op == oldop && tcode != UNARY_PLUS_EXPR)
6895 /* We didn't fold at the top so we could check for ptr-int
6896 conversion. */
6897 return fold (t);
6899 tree sop;
6901 /* Handle an array's bounds having been deduced after we built
6902 the wrapping expression. */
6903 if (same_type_ignoring_tlq_and_bounds_p (type, TREE_TYPE (op)))
6904 r = op;
6905 else if (sop = tree_strip_nop_conversions (op),
6906 sop != op && (same_type_ignoring_tlq_and_bounds_p
6907 (type, TREE_TYPE (sop))))
6908 r = sop;
6909 else if (tcode == UNARY_PLUS_EXPR)
6910 r = fold_convert (TREE_TYPE (t), op);
6911 else
6912 r = fold_build1 (tcode, type, op);
6914 /* Conversion of an out-of-range value has implementation-defined
6915 behavior; the language considers it different from arithmetic
6916 overflow, which is undefined. */
6917 if (TREE_OVERFLOW_P (r) && !TREE_OVERFLOW_P (op))
6918 TREE_OVERFLOW (r) = false;
6920 break;
6922 case EMPTY_CLASS_EXPR:
6923 /* Handle EMPTY_CLASS_EXPR produced by build_call_a by lowering
6924 it to an appropriate CONSTRUCTOR. */
6925 return build_constructor (TREE_TYPE (t), NULL);
6927 case STATEMENT_LIST:
6928 new_ctx = *ctx;
6929 new_ctx.ctor = new_ctx.object = NULL_TREE;
6930 return cxx_eval_statement_list (&new_ctx, t,
6931 non_constant_p, overflow_p, jump_target);
6933 case BIND_EXPR:
6934 return cxx_eval_constant_expression (ctx, BIND_EXPR_BODY (t),
6935 lval,
6936 non_constant_p, overflow_p,
6937 jump_target);
6939 case PREINCREMENT_EXPR:
6940 case POSTINCREMENT_EXPR:
6941 case PREDECREMENT_EXPR:
6942 case POSTDECREMENT_EXPR:
6943 return cxx_eval_increment_expression (ctx, t,
6944 lval, non_constant_p, overflow_p);
6946 case LAMBDA_EXPR:
6947 case NEW_EXPR:
6948 case VEC_NEW_EXPR:
6949 case DELETE_EXPR:
6950 case VEC_DELETE_EXPR:
6951 case THROW_EXPR:
6952 case MODOP_EXPR:
6953 /* GCC internal stuff. */
6954 case VA_ARG_EXPR:
6955 case NON_DEPENDENT_EXPR:
6956 case BASELINK:
6957 case OFFSET_REF:
6958 if (!ctx->quiet)
6959 error_at (loc, "expression %qE is not a constant expression", t);
6960 *non_constant_p = true;
6961 break;
6963 case OBJ_TYPE_REF:
6964 /* Virtual function lookup. We don't need to do anything fancy. */
6965 return cxx_eval_constant_expression (ctx, OBJ_TYPE_REF_EXPR (t),
6966 lval, non_constant_p, overflow_p);
6968 case PLACEHOLDER_EXPR:
6969 /* Use of the value or address of the current object. */
6970 if (tree ctor = lookup_placeholder (ctx, lval, TREE_TYPE (t)))
6972 if (TREE_CODE (ctor) == CONSTRUCTOR)
6973 return ctor;
6974 else
6975 return cxx_eval_constant_expression (ctx, ctor, lval,
6976 non_constant_p, overflow_p);
6978 /* A placeholder without a referent. We can get here when
6979 checking whether NSDMIs are noexcept, or in massage_init_elt;
6980 just say it's non-constant for now. */
6981 gcc_assert (ctx->quiet);
6982 *non_constant_p = true;
6983 break;
6985 case EXIT_EXPR:
6987 tree cond = TREE_OPERAND (t, 0);
6988 cond = cxx_eval_constant_expression (ctx, cond, /*lval*/false,
6989 non_constant_p, overflow_p);
6990 VERIFY_CONSTANT (cond);
6991 if (integer_nonzerop (cond))
6992 *jump_target = t;
6994 break;
6996 case GOTO_EXPR:
6997 *jump_target = TREE_OPERAND (t, 0);
6998 gcc_assert (breaks (jump_target) || continues (jump_target)
6999 /* Allow for jumping to a cdtor_label. */
7000 || returns (jump_target));
7001 break;
7003 case LOOP_EXPR:
7004 case DO_STMT:
7005 case WHILE_STMT:
7006 case FOR_STMT:
7007 cxx_eval_loop_expr (ctx, t,
7008 non_constant_p, overflow_p, jump_target);
7009 break;
7011 case SWITCH_EXPR:
7012 case SWITCH_STMT:
7013 cxx_eval_switch_expr (ctx, t,
7014 non_constant_p, overflow_p, jump_target);
7015 break;
7017 case REQUIRES_EXPR:
7018 /* It's possible to get a requires-expression in a constant
7019 expression. For example:
7021 template<typename T> concept bool C() {
7022 return requires (T t) { t; };
7025 template<typename T> requires !C<T>() void f(T);
7027 Normalization leaves f with the associated constraint
7028 '!requires (T t) { ... }' which is not transformed into
7029 a constraint. */
7030 if (!processing_template_decl)
7031 return evaluate_requires_expr (t);
7032 else
7033 *non_constant_p = true;
7034 return t;
7036 case ANNOTATE_EXPR:
7037 r = cxx_eval_constant_expression (ctx, TREE_OPERAND (t, 0),
7038 lval,
7039 non_constant_p, overflow_p,
7040 jump_target);
7041 break;
7043 case USING_STMT:
7044 r = void_node;
7045 break;
7047 case TEMPLATE_ID_EXPR:
7049 /* We can evaluate template-id that refers to a concept only if
7050 the template arguments are non-dependent. */
7051 tree id = unpack_concept_check (t);
7052 tree tmpl = TREE_OPERAND (id, 0);
7053 if (!concept_definition_p (tmpl))
7054 internal_error ("unexpected template-id %qE", t);
7056 if (function_concept_p (tmpl))
7058 if (!ctx->quiet)
7059 error_at (cp_expr_loc_or_input_loc (t),
7060 "function concept must be called");
7061 r = error_mark_node;
7062 break;
7065 if (!processing_template_decl
7066 && !uid_sensitive_constexpr_evaluation_p ())
7067 r = evaluate_concept_check (t);
7068 else
7069 *non_constant_p = true;
7071 break;
7074 case ASM_EXPR:
7075 if (!ctx->quiet)
7076 inline_asm_in_constexpr_error (loc);
7077 *non_constant_p = true;
7078 return t;
7080 case BIT_CAST_EXPR:
7081 if (lval)
7083 if (!ctx->quiet)
7084 error_at (EXPR_LOCATION (t),
7085 "address of a call to %qs is not a constant expression",
7086 "__builtin_bit_cast");
7087 *non_constant_p = true;
7088 return t;
7090 r = cxx_eval_bit_cast (ctx, t, non_constant_p, overflow_p);
7091 break;
7093 default:
7094 if (STATEMENT_CODE_P (TREE_CODE (t)))
7096 /* This function doesn't know how to deal with pre-genericize
7097 statements; this can only happen with statement-expressions,
7098 so for now just fail. */
7099 if (!ctx->quiet)
7100 error_at (EXPR_LOCATION (t),
7101 "statement is not a constant expression");
7103 else
7104 internal_error ("unexpected expression %qE of kind %s", t,
7105 get_tree_code_name (TREE_CODE (t)));
7106 *non_constant_p = true;
7107 break;
7110 if (r == error_mark_node)
7111 *non_constant_p = true;
7113 if (*non_constant_p)
7114 return t;
7115 else
7116 return r;
7119 /* P0859: A function is needed for constant evaluation if it is a constexpr
7120 function that is named by an expression ([basic.def.odr]) that is
7121 potentially constant evaluated.
7123 So we need to instantiate any constexpr functions mentioned by the
7124 expression even if the definition isn't needed for evaluating the
7125 expression. */
7127 static tree
7128 instantiate_cx_fn_r (tree *tp, int *walk_subtrees, void */*data*/)
7130 if (TREE_CODE (*tp) == FUNCTION_DECL
7131 && DECL_DECLARED_CONSTEXPR_P (*tp)
7132 && !DECL_INITIAL (*tp)
7133 && !trivial_fn_p (*tp)
7134 && DECL_TEMPLOID_INSTANTIATION (*tp)
7135 && !uid_sensitive_constexpr_evaluation_p ())
7137 ++function_depth;
7138 instantiate_decl (*tp, /*defer_ok*/false, /*expl_inst*/false);
7139 --function_depth;
7141 else if (TREE_CODE (*tp) == CALL_EXPR
7142 || TREE_CODE (*tp) == AGGR_INIT_EXPR)
7144 if (EXPR_HAS_LOCATION (*tp))
7145 input_location = EXPR_LOCATION (*tp);
7148 if (!EXPR_P (*tp))
7149 *walk_subtrees = 0;
7151 return NULL_TREE;
7154 static void
7155 instantiate_constexpr_fns (tree t)
7157 location_t loc = input_location;
7158 cp_walk_tree_without_duplicates (&t, instantiate_cx_fn_r, NULL);
7159 input_location = loc;
7162 /* Look for heap variables in the expression *TP. */
7164 static tree
7165 find_heap_var_refs (tree *tp, int *walk_subtrees, void */*data*/)
7167 if (VAR_P (*tp)
7168 && (DECL_NAME (*tp) == heap_uninit_identifier
7169 || DECL_NAME (*tp) == heap_identifier
7170 || DECL_NAME (*tp) == heap_vec_uninit_identifier
7171 || DECL_NAME (*tp) == heap_vec_identifier
7172 || DECL_NAME (*tp) == heap_deleted_identifier))
7173 return *tp;
7175 if (TYPE_P (*tp))
7176 *walk_subtrees = 0;
7177 return NULL_TREE;
7180 /* Find immediate function decls in *TP if any. */
7182 static tree
7183 find_immediate_fndecl (tree *tp, int */*walk_subtrees*/, void */*data*/)
7185 if (TREE_CODE (*tp) == FUNCTION_DECL && DECL_IMMEDIATE_FUNCTION_P (*tp))
7186 return *tp;
7187 return NULL_TREE;
7190 /* ALLOW_NON_CONSTANT is false if T is required to be a constant expression.
7191 STRICT has the same sense as for constant_value_1: true if we only allow
7192 conforming C++ constant expressions, or false if we want a constant value
7193 even if it doesn't conform.
7194 MANIFESTLY_CONST_EVAL is true if T is manifestly const-evaluated as
7195 per P0595 even when ALLOW_NON_CONSTANT is true.
7196 CONSTEXPR_DTOR is true when evaluating the dtor of a constexpr variable.
7197 OBJECT must be non-NULL in that case. */
7199 static tree
7200 cxx_eval_outermost_constant_expr (tree t, bool allow_non_constant,
7201 bool strict = true,
7202 bool manifestly_const_eval = false,
7203 bool constexpr_dtor = false,
7204 tree object = NULL_TREE)
7206 auto_timevar time (TV_CONSTEXPR);
7208 bool non_constant_p = false;
7209 bool overflow_p = false;
7211 if (BRACE_ENCLOSED_INITIALIZER_P (t))
7213 gcc_checking_assert (allow_non_constant);
7214 return t;
7217 constexpr_global_ctx global_ctx;
7218 constexpr_ctx ctx = { &global_ctx, NULL, NULL, NULL, NULL, NULL, NULL,
7219 allow_non_constant, strict,
7220 manifestly_const_eval || !allow_non_constant };
7222 /* Turn off -frounding-math for manifestly constant evaluation. */
7223 warning_sentinel rm (flag_rounding_math, ctx.manifestly_const_eval);
7224 tree type = initialized_type (t);
7225 tree r = t;
7226 bool is_consteval = false;
7227 if (VOID_TYPE_P (type))
7229 if (constexpr_dtor)
7230 /* Used for destructors of array elements. */
7231 type = TREE_TYPE (object);
7232 else
7234 if (cxx_dialect < cxx20)
7235 return t;
7236 if (TREE_CODE (t) != CALL_EXPR && TREE_CODE (t) != AGGR_INIT_EXPR)
7237 return t;
7238 /* Calls to immediate functions returning void need to be
7239 evaluated. */
7240 tree fndecl = cp_get_callee_fndecl_nofold (t);
7241 if (fndecl == NULL_TREE || !DECL_IMMEDIATE_FUNCTION_P (fndecl))
7242 return t;
7243 else
7244 is_consteval = true;
7247 else if (cxx_dialect >= cxx20
7248 && (TREE_CODE (t) == CALL_EXPR
7249 || TREE_CODE (t) == AGGR_INIT_EXPR
7250 || TREE_CODE (t) == TARGET_EXPR))
7252 /* For non-concept checks, determine if it is consteval. */
7253 if (!concept_check_p (t))
7255 tree x = t;
7256 if (TREE_CODE (x) == TARGET_EXPR)
7257 x = TARGET_EXPR_INITIAL (x);
7258 tree fndecl = cp_get_callee_fndecl_nofold (x);
7259 if (fndecl && DECL_IMMEDIATE_FUNCTION_P (fndecl))
7260 is_consteval = true;
7263 if (AGGREGATE_TYPE_P (type) || VECTOR_TYPE_P (type))
7265 /* In C++14 an NSDMI can participate in aggregate initialization,
7266 and can refer to the address of the object being initialized, so
7267 we need to pass in the relevant VAR_DECL if we want to do the
7268 evaluation in a single pass. The evaluation will dynamically
7269 update ctx.values for the VAR_DECL. We use the same strategy
7270 for C++11 constexpr constructors that refer to the object being
7271 initialized. */
7272 if (constexpr_dtor)
7274 gcc_assert (object && VAR_P (object));
7275 gcc_assert (DECL_DECLARED_CONSTEXPR_P (object));
7276 gcc_assert (DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (object));
7277 if (error_operand_p (DECL_INITIAL (object)))
7278 return t;
7279 ctx.ctor = unshare_expr (DECL_INITIAL (object));
7280 TREE_READONLY (ctx.ctor) = false;
7281 /* Temporarily force decl_really_constant_value to return false
7282 for it, we want to use ctx.ctor for the current value instead. */
7283 DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (object) = false;
7285 else
7287 ctx.ctor = build_constructor (type, NULL);
7288 CONSTRUCTOR_NO_CLEARING (ctx.ctor) = true;
7290 if (!object)
7292 if (TREE_CODE (t) == TARGET_EXPR)
7293 object = TARGET_EXPR_SLOT (t);
7294 else if (TREE_CODE (t) == AGGR_INIT_EXPR)
7295 object = AGGR_INIT_EXPR_SLOT (t);
7297 ctx.object = object;
7298 if (object)
7299 gcc_assert (same_type_ignoring_top_level_qualifiers_p
7300 (type, TREE_TYPE (object)));
7301 if (object && DECL_P (object))
7302 global_ctx.values.put (object, ctx.ctor);
7303 if (TREE_CODE (r) == TARGET_EXPR)
7304 /* Avoid creating another CONSTRUCTOR when we expand the
7305 TARGET_EXPR. */
7306 r = TARGET_EXPR_INITIAL (r);
7309 auto_vec<tree, 16> cleanups;
7310 global_ctx.cleanups = &cleanups;
7312 instantiate_constexpr_fns (r);
7313 r = cxx_eval_constant_expression (&ctx, r,
7314 false, &non_constant_p, &overflow_p);
7316 if (!constexpr_dtor)
7317 verify_constant (r, allow_non_constant, &non_constant_p, &overflow_p);
7318 else
7319 DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (object) = true;
7321 unsigned int i;
7322 tree cleanup;
7323 /* Evaluate the cleanups. */
7324 FOR_EACH_VEC_ELT_REVERSE (cleanups, i, cleanup)
7325 cxx_eval_constant_expression (&ctx, cleanup, false,
7326 &non_constant_p, &overflow_p);
7328 /* Mutable logic is a bit tricky: we want to allow initialization of
7329 constexpr variables with mutable members, but we can't copy those
7330 members to another constexpr variable. */
7331 if (TREE_CODE (r) == CONSTRUCTOR && CONSTRUCTOR_MUTABLE_POISON (r))
7333 if (!allow_non_constant)
7334 error ("%qE is not a constant expression because it refers to "
7335 "mutable subobjects of %qT", t, type);
7336 non_constant_p = true;
7339 if (TREE_CODE (r) == CONSTRUCTOR && CONSTRUCTOR_NO_CLEARING (r))
7341 if (!allow_non_constant)
7342 error ("%qE is not a constant expression because it refers to "
7343 "an incompletely initialized variable", t);
7344 TREE_CONSTANT (r) = false;
7345 non_constant_p = true;
7348 if (!global_ctx.heap_vars.is_empty ())
7350 tree heap_var = cp_walk_tree_without_duplicates (&r, find_heap_var_refs,
7351 NULL);
7352 unsigned int i;
7353 if (heap_var)
7355 if (!allow_non_constant && !non_constant_p)
7356 error_at (DECL_SOURCE_LOCATION (heap_var),
7357 "%qE is not a constant expression because it refers to "
7358 "a result of %<operator new%>", t);
7359 r = t;
7360 non_constant_p = true;
7362 FOR_EACH_VEC_ELT (global_ctx.heap_vars, i, heap_var)
7364 if (DECL_NAME (heap_var) != heap_deleted_identifier)
7366 if (!allow_non_constant && !non_constant_p)
7367 error_at (DECL_SOURCE_LOCATION (heap_var),
7368 "%qE is not a constant expression because allocated "
7369 "storage has not been deallocated", t);
7370 r = t;
7371 non_constant_p = true;
7373 varpool_node::get (heap_var)->remove ();
7377 /* Check that immediate invocation does not return an expression referencing
7378 any immediate function decls. They need to be allowed while parsing
7379 immediate functions, but can't leak outside of them. */
7380 if (is_consteval
7381 && t != r
7382 && (current_function_decl == NULL_TREE
7383 || !DECL_IMMEDIATE_FUNCTION_P (current_function_decl)))
7384 if (tree immediate_fndecl
7385 = cp_walk_tree_without_duplicates (&r, find_immediate_fndecl,
7386 NULL))
7388 if (!allow_non_constant && !non_constant_p)
7389 error_at (cp_expr_loc_or_input_loc (t),
7390 "immediate evaluation returns address of immediate "
7391 "function %qD", immediate_fndecl);
7392 r = t;
7393 non_constant_p = true;
7396 if (non_constant_p)
7397 /* If we saw something bad, go back to our argument. The wrapping below is
7398 only for the cases of TREE_CONSTANT argument or overflow. */
7399 r = t;
7401 if (!non_constant_p && overflow_p)
7402 non_constant_p = true;
7404 /* Unshare the result. */
7405 bool should_unshare = true;
7406 if (r == t || (TREE_CODE (t) == TARGET_EXPR
7407 && TARGET_EXPR_INITIAL (t) == r))
7408 should_unshare = false;
7410 if (non_constant_p && !allow_non_constant)
7411 return error_mark_node;
7412 else if (constexpr_dtor)
7413 return r;
7414 else if (non_constant_p && TREE_CONSTANT (r))
7416 /* This isn't actually constant, so unset TREE_CONSTANT.
7417 Don't clear TREE_CONSTANT on ADDR_EXPR, as the middle-end requires
7418 it to be set if it is invariant address, even when it is not
7419 a valid C++ constant expression. Wrap it with a NOP_EXPR
7420 instead. */
7421 if (EXPR_P (r) && TREE_CODE (r) != ADDR_EXPR)
7422 r = copy_node (r);
7423 else if (TREE_CODE (r) == CONSTRUCTOR)
7424 r = build1 (VIEW_CONVERT_EXPR, TREE_TYPE (r), r);
7425 else
7426 r = build_nop (TREE_TYPE (r), r);
7427 TREE_CONSTANT (r) = false;
7429 else if (non_constant_p)
7430 return t;
7432 if (should_unshare)
7433 r = unshare_expr (r);
7435 if (TREE_CODE (r) == CONSTRUCTOR && CLASS_TYPE_P (TREE_TYPE (r)))
7437 r = adjust_temp_type (type, r);
7438 if (TREE_CODE (t) == TARGET_EXPR
7439 && TARGET_EXPR_INITIAL (t) == r)
7440 return t;
7441 else if (TREE_CODE (t) != CONSTRUCTOR)
7443 r = get_target_expr_sfinae (r, tf_warning_or_error | tf_no_cleanup);
7444 TREE_CONSTANT (r) = true;
7448 return r;
7451 /* If T represents a constant expression returns its reduced value.
7452 Otherwise return error_mark_node. If T is dependent, then
7453 return NULL. */
7455 tree
7456 cxx_constant_value (tree t, tree decl)
7458 return cxx_eval_outermost_constant_expr (t, false, true, true, false, decl);
7461 /* Like cxx_constant_value, but used for evaluation of constexpr destructors
7462 of constexpr variables. The actual initializer of DECL is not modified. */
7464 void
7465 cxx_constant_dtor (tree t, tree decl)
7467 cxx_eval_outermost_constant_expr (t, false, true, true, true, decl);
7470 /* Helper routine for fold_simple function. Either return simplified
7471 expression T, otherwise NULL_TREE.
7472 In contrast to cp_fully_fold, and to maybe_constant_value, we try to fold
7473 even if we are within template-declaration. So be careful on call, as in
7474 such case types can be undefined. */
7476 static tree
7477 fold_simple_1 (tree t)
7479 tree op1;
7480 enum tree_code code = TREE_CODE (t);
7482 switch (code)
7484 case INTEGER_CST:
7485 case REAL_CST:
7486 case VECTOR_CST:
7487 case FIXED_CST:
7488 case COMPLEX_CST:
7489 return t;
7491 case SIZEOF_EXPR:
7492 return fold_sizeof_expr (t);
7494 case ABS_EXPR:
7495 case ABSU_EXPR:
7496 case CONJ_EXPR:
7497 case REALPART_EXPR:
7498 case IMAGPART_EXPR:
7499 case NEGATE_EXPR:
7500 case BIT_NOT_EXPR:
7501 case TRUTH_NOT_EXPR:
7502 case NOP_EXPR:
7503 case VIEW_CONVERT_EXPR:
7504 case CONVERT_EXPR:
7505 case FLOAT_EXPR:
7506 case FIX_TRUNC_EXPR:
7507 case FIXED_CONVERT_EXPR:
7508 case ADDR_SPACE_CONVERT_EXPR:
7510 op1 = TREE_OPERAND (t, 0);
7512 t = const_unop (code, TREE_TYPE (t), op1);
7513 if (!t)
7514 return NULL_TREE;
7516 if (CONVERT_EXPR_CODE_P (code)
7517 && TREE_OVERFLOW_P (t) && !TREE_OVERFLOW_P (op1))
7518 TREE_OVERFLOW (t) = false;
7519 return t;
7521 default:
7522 return NULL_TREE;
7526 /* If T is a simple constant expression, returns its simplified value.
7527 Otherwise returns T. In contrast to maybe_constant_value we
7528 simplify only few operations on constant-expressions, and we don't
7529 try to simplify constexpressions. */
7531 tree
7532 fold_simple (tree t)
7534 if (processing_template_decl)
7535 return t;
7537 tree r = fold_simple_1 (t);
7538 if (r)
7539 return r;
7541 return t;
7544 /* If T is a constant expression, returns its reduced value.
7545 Otherwise, if T does not have TREE_CONSTANT set, returns T.
7546 Otherwise, returns a version of T without TREE_CONSTANT.
7547 MANIFESTLY_CONST_EVAL is true if T is manifestly const-evaluated
7548 as per P0595. */
7550 static GTY((deletable)) hash_map<tree, tree> *cv_cache;
7552 tree
7553 maybe_constant_value (tree t, tree decl, bool manifestly_const_eval)
7555 tree r;
7557 if (!is_nondependent_constant_expression (t))
7559 if (TREE_OVERFLOW_P (t))
7561 t = build_nop (TREE_TYPE (t), t);
7562 TREE_CONSTANT (t) = false;
7564 return t;
7566 else if (CONSTANT_CLASS_P (t))
7567 /* No caching or evaluation needed. */
7568 return t;
7570 if (manifestly_const_eval)
7571 return cxx_eval_outermost_constant_expr (t, true, true, true, false, decl);
7573 if (cv_cache == NULL)
7574 cv_cache = hash_map<tree, tree>::create_ggc (101);
7575 if (tree *cached = cv_cache->get (t))
7577 r = *cached;
7578 if (r != t)
7580 r = break_out_target_exprs (r, /*clear_loc*/true);
7581 protected_set_expr_location (r, EXPR_LOCATION (t));
7583 return r;
7586 uid_sensitive_constexpr_evaluation_checker c;
7587 r = cxx_eval_outermost_constant_expr (t, true, true, false, false, decl);
7588 gcc_checking_assert (r == t
7589 || CONVERT_EXPR_P (t)
7590 || TREE_CODE (t) == VIEW_CONVERT_EXPR
7591 || (TREE_CONSTANT (t) && !TREE_CONSTANT (r))
7592 || !cp_tree_equal (r, t));
7593 if (!c.evaluation_restricted_p ())
7594 cv_cache->put (t, r);
7595 return r;
7598 /* Dispose of the whole CV_CACHE. */
7600 static void
7601 clear_cv_cache (void)
7603 if (cv_cache != NULL)
7604 cv_cache->empty ();
7607 /* Dispose of the whole CV_CACHE and FOLD_CACHE. */
7609 void
7610 clear_cv_and_fold_caches ()
7612 clear_cv_cache ();
7613 clear_fold_cache ();
7616 /* Internal function handling expressions in templates for
7617 fold_non_dependent_expr and fold_non_dependent_init.
7619 If we're in a template, but T isn't value dependent, simplify
7620 it. We're supposed to treat:
7622 template <typename T> void f(T[1 + 1]);
7623 template <typename T> void f(T[2]);
7625 as two declarations of the same function, for example. */
7627 static tree
7628 fold_non_dependent_expr_template (tree t, tsubst_flags_t complain,
7629 bool manifestly_const_eval,
7630 tree object)
7632 gcc_assert (processing_template_decl);
7634 if (is_nondependent_constant_expression (t))
7636 processing_template_decl_sentinel s;
7637 t = instantiate_non_dependent_expr_internal (t, complain);
7639 if (type_unknown_p (t) || BRACE_ENCLOSED_INITIALIZER_P (t))
7641 if (TREE_OVERFLOW_P (t))
7643 t = build_nop (TREE_TYPE (t), t);
7644 TREE_CONSTANT (t) = false;
7646 return t;
7649 tree r = cxx_eval_outermost_constant_expr (t, true, true,
7650 manifestly_const_eval,
7651 false, object);
7652 /* cp_tree_equal looks through NOPs, so allow them. */
7653 gcc_checking_assert (r == t
7654 || CONVERT_EXPR_P (t)
7655 || TREE_CODE (t) == VIEW_CONVERT_EXPR
7656 || (TREE_CONSTANT (t) && !TREE_CONSTANT (r))
7657 || !cp_tree_equal (r, t));
7658 return r;
7660 else if (TREE_OVERFLOW_P (t))
7662 t = build_nop (TREE_TYPE (t), t);
7663 TREE_CONSTANT (t) = false;
7666 return t;
7669 /* Like maybe_constant_value but first fully instantiate the argument.
7671 Note: this is equivalent to instantiate_non_dependent_expr_sfinae
7672 (t, complain) followed by maybe_constant_value but is more efficient,
7673 because it calls instantiation_dependent_expression_p and
7674 potential_constant_expression at most once.
7675 The manifestly_const_eval argument is passed to maybe_constant_value.
7677 Callers should generally pass their active complain, or if they are in a
7678 non-template, diagnosing context, they can use the default of
7679 tf_warning_or_error. Callers that might be within a template context, don't
7680 have a complain parameter, and aren't going to remember the result for long
7681 (e.g. null_ptr_cst_p), can pass tf_none and deal with error_mark_node
7682 appropriately. */
7684 tree
7685 fold_non_dependent_expr (tree t,
7686 tsubst_flags_t complain /* = tf_warning_or_error */,
7687 bool manifestly_const_eval /* = false */,
7688 tree object /* = NULL_TREE */)
7690 if (t == NULL_TREE)
7691 return NULL_TREE;
7693 if (processing_template_decl)
7694 return fold_non_dependent_expr_template (t, complain,
7695 manifestly_const_eval, object);
7697 return maybe_constant_value (t, object, manifestly_const_eval);
7700 /* Like fold_non_dependent_expr, but if EXPR couldn't be folded to a constant,
7701 return the original expression. */
7703 tree
7704 maybe_fold_non_dependent_expr (tree expr,
7705 tsubst_flags_t complain/*=tf_warning_or_error*/)
7707 tree t = fold_non_dependent_expr (expr, complain);
7708 if (t && TREE_CONSTANT (t))
7709 return t;
7711 return expr;
7714 /* Like maybe_constant_init but first fully instantiate the argument. */
7716 tree
7717 fold_non_dependent_init (tree t,
7718 tsubst_flags_t complain /*=tf_warning_or_error*/,
7719 bool manifestly_const_eval /*=false*/,
7720 tree object /* = NULL_TREE */)
7722 if (t == NULL_TREE)
7723 return NULL_TREE;
7725 if (processing_template_decl)
7727 t = fold_non_dependent_expr_template (t, complain,
7728 manifestly_const_eval, object);
7729 /* maybe_constant_init does this stripping, so do it here too. */
7730 if (TREE_CODE (t) == TARGET_EXPR)
7732 tree init = TARGET_EXPR_INITIAL (t);
7733 if (TREE_CODE (init) == CONSTRUCTOR)
7734 t = init;
7736 return t;
7739 return maybe_constant_init (t, object, manifestly_const_eval);
7742 /* Like maybe_constant_value, but returns a CONSTRUCTOR directly, rather
7743 than wrapped in a TARGET_EXPR.
7744 ALLOW_NON_CONSTANT is false if T is required to be a constant expression.
7745 MANIFESTLY_CONST_EVAL is true if T is manifestly const-evaluated as
7746 per P0595 even when ALLOW_NON_CONSTANT is true. */
7748 static tree
7749 maybe_constant_init_1 (tree t, tree decl, bool allow_non_constant,
7750 bool manifestly_const_eval)
7752 if (!t)
7753 return t;
7754 if (TREE_CODE (t) == EXPR_STMT)
7755 t = TREE_OPERAND (t, 0);
7756 if (TREE_CODE (t) == CONVERT_EXPR
7757 && VOID_TYPE_P (TREE_TYPE (t)))
7758 t = TREE_OPERAND (t, 0);
7759 if (TREE_CODE (t) == INIT_EXPR)
7760 t = TREE_OPERAND (t, 1);
7761 if (TREE_CODE (t) == TARGET_EXPR)
7762 t = TARGET_EXPR_INITIAL (t);
7763 if (!is_nondependent_static_init_expression (t))
7764 /* Don't try to evaluate it. */;
7765 else if (CONSTANT_CLASS_P (t) && allow_non_constant)
7766 /* No evaluation needed. */;
7767 else
7768 t = cxx_eval_outermost_constant_expr (t, allow_non_constant,
7769 /*strict*/false,
7770 manifestly_const_eval, false, decl);
7771 if (TREE_CODE (t) == TARGET_EXPR)
7773 tree init = TARGET_EXPR_INITIAL (t);
7774 if (TREE_CODE (init) == CONSTRUCTOR)
7775 t = init;
7777 return t;
7780 /* Wrapper for maybe_constant_init_1 which permits non constants. */
7782 tree
7783 maybe_constant_init (tree t, tree decl, bool manifestly_const_eval)
7785 return maybe_constant_init_1 (t, decl, true, manifestly_const_eval);
7788 /* Wrapper for maybe_constant_init_1 which does not permit non constants. */
7790 tree
7791 cxx_constant_init (tree t, tree decl)
7793 return maybe_constant_init_1 (t, decl, false, true);
7796 #if 0
7797 /* FIXME see ADDR_EXPR section in potential_constant_expression_1. */
7798 /* Return true if the object referred to by REF has automatic or thread
7799 local storage. */
7801 enum { ck_ok, ck_bad, ck_unknown };
7802 static int
7803 check_automatic_or_tls (tree ref)
7805 machine_mode mode;
7806 poly_int64 bitsize, bitpos;
7807 tree offset;
7808 int volatilep = 0, unsignedp = 0;
7809 tree decl = get_inner_reference (ref, &bitsize, &bitpos, &offset,
7810 &mode, &unsignedp, &volatilep, false);
7811 duration_kind dk;
7813 /* If there isn't a decl in the middle, we don't know the linkage here,
7814 and this isn't a constant expression anyway. */
7815 if (!DECL_P (decl))
7816 return ck_unknown;
7817 dk = decl_storage_duration (decl);
7818 return (dk == dk_auto || dk == dk_thread) ? ck_bad : ck_ok;
7820 #endif
7822 /* Data structure for passing data from potential_constant_expression_1
7823 to check_for_return_continue via cp_walk_tree. */
7824 struct check_for_return_continue_data {
7825 hash_set<tree> *pset;
7826 tree continue_stmt;
7827 tree break_stmt;
7830 /* Helper function for potential_constant_expression_1 SWITCH_STMT handling,
7831 called through cp_walk_tree. Return the first RETURN_EXPR found, or note
7832 the first CONTINUE_STMT and/or BREAK_STMT if RETURN_EXPR is not found. */
7833 static tree
7834 check_for_return_continue (tree *tp, int *walk_subtrees, void *data)
7836 tree t = *tp, s, b;
7837 check_for_return_continue_data *d = (check_for_return_continue_data *) data;
7838 switch (TREE_CODE (t))
7840 case RETURN_EXPR:
7841 return t;
7843 case CONTINUE_STMT:
7844 if (d->continue_stmt == NULL_TREE)
7845 d->continue_stmt = t;
7846 break;
7848 case BREAK_STMT:
7849 if (d->break_stmt == NULL_TREE)
7850 d->break_stmt = t;
7851 break;
7853 #define RECUR(x) \
7854 if (tree r = cp_walk_tree (&x, check_for_return_continue, data, \
7855 d->pset)) \
7856 return r
7858 /* For loops, walk subtrees manually, so that continue stmts found
7859 inside of the bodies of the loops are ignored. */
7860 case DO_STMT:
7861 *walk_subtrees = 0;
7862 RECUR (DO_COND (t));
7863 s = d->continue_stmt;
7864 b = d->break_stmt;
7865 RECUR (DO_BODY (t));
7866 d->continue_stmt = s;
7867 d->break_stmt = b;
7868 break;
7870 case WHILE_STMT:
7871 *walk_subtrees = 0;
7872 RECUR (WHILE_COND (t));
7873 s = d->continue_stmt;
7874 b = d->break_stmt;
7875 RECUR (WHILE_BODY (t));
7876 d->continue_stmt = s;
7877 d->break_stmt = b;
7878 break;
7880 case FOR_STMT:
7881 *walk_subtrees = 0;
7882 RECUR (FOR_INIT_STMT (t));
7883 RECUR (FOR_COND (t));
7884 RECUR (FOR_EXPR (t));
7885 s = d->continue_stmt;
7886 b = d->break_stmt;
7887 RECUR (FOR_BODY (t));
7888 d->continue_stmt = s;
7889 d->break_stmt = b;
7890 break;
7892 case RANGE_FOR_STMT:
7893 *walk_subtrees = 0;
7894 RECUR (RANGE_FOR_EXPR (t));
7895 s = d->continue_stmt;
7896 b = d->break_stmt;
7897 RECUR (RANGE_FOR_BODY (t));
7898 d->continue_stmt = s;
7899 d->break_stmt = b;
7900 break;
7902 case SWITCH_STMT:
7903 *walk_subtrees = 0;
7904 RECUR (SWITCH_STMT_COND (t));
7905 b = d->break_stmt;
7906 RECUR (SWITCH_STMT_BODY (t));
7907 d->break_stmt = b;
7908 break;
7909 #undef RECUR
7911 case STATEMENT_LIST:
7912 case CONSTRUCTOR:
7913 break;
7915 default:
7916 if (!EXPR_P (t))
7917 *walk_subtrees = 0;
7918 break;
7921 return NULL_TREE;
7924 /* Return true if T denotes a potentially constant expression. Issue
7925 diagnostic as appropriate under control of FLAGS. If WANT_RVAL is true,
7926 an lvalue-rvalue conversion is implied. If NOW is true, we want to
7927 consider the expression in the current context, independent of constexpr
7928 substitution.
7930 C++0x [expr.const] used to say
7932 6 An expression is a potential constant expression if it is
7933 a constant expression where all occurrences of function
7934 parameters are replaced by arbitrary constant expressions
7935 of the appropriate type.
7937 2 A conditional expression is a constant expression unless it
7938 involves one of the following as a potentially evaluated
7939 subexpression (3.2), but subexpressions of logical AND (5.14),
7940 logical OR (5.15), and conditional (5.16) operations that are
7941 not evaluated are not considered. */
7943 static bool
7944 potential_constant_expression_1 (tree t, bool want_rval, bool strict, bool now,
7945 tsubst_flags_t flags, tree *jump_target)
7947 #define RECUR(T,RV) \
7948 potential_constant_expression_1 ((T), (RV), strict, now, flags, jump_target)
7950 enum { any = false, rval = true };
7951 int i;
7952 tree tmp;
7954 if (t == error_mark_node)
7955 return false;
7956 if (t == NULL_TREE)
7957 return true;
7958 location_t loc = cp_expr_loc_or_input_loc (t);
7960 if (*jump_target)
7961 /* If we are jumping, ignore everything. This is simpler than the
7962 cxx_eval_constant_expression handling because we only need to be
7963 conservatively correct, and we don't necessarily have a constant value
7964 available, so we don't bother with switch tracking. */
7965 return true;
7967 if (TREE_THIS_VOLATILE (t) && want_rval)
7969 if (flags & tf_error)
7970 error_at (loc, "lvalue-to-rvalue conversion of a volatile lvalue "
7971 "%qE with type %qT", t, TREE_TYPE (t));
7972 return false;
7974 if (CONSTANT_CLASS_P (t))
7975 return true;
7976 if (CODE_CONTAINS_STRUCT (TREE_CODE (t), TS_TYPED)
7977 && TREE_TYPE (t) == error_mark_node)
7978 return false;
7980 switch (TREE_CODE (t))
7982 case FUNCTION_DECL:
7983 case BASELINK:
7984 case TEMPLATE_DECL:
7985 case OVERLOAD:
7986 case TEMPLATE_ID_EXPR:
7987 case LABEL_DECL:
7988 case CASE_LABEL_EXPR:
7989 case PREDICT_EXPR:
7990 case CONST_DECL:
7991 case SIZEOF_EXPR:
7992 case ALIGNOF_EXPR:
7993 case OFFSETOF_EXPR:
7994 case NOEXCEPT_EXPR:
7995 case TEMPLATE_PARM_INDEX:
7996 case TRAIT_EXPR:
7997 case IDENTIFIER_NODE:
7998 case USERDEF_LITERAL:
7999 /* We can see a FIELD_DECL in a pointer-to-member expression. */
8000 case FIELD_DECL:
8001 case RESULT_DECL:
8002 case USING_DECL:
8003 case USING_STMT:
8004 case PLACEHOLDER_EXPR:
8005 case REQUIRES_EXPR:
8006 case STATIC_ASSERT:
8007 case DEBUG_BEGIN_STMT:
8008 return true;
8010 case RETURN_EXPR:
8011 if (!RECUR (TREE_OPERAND (t, 0), any))
8012 return false;
8013 /* FALLTHROUGH */
8015 case BREAK_STMT:
8016 case CONTINUE_STMT:
8017 *jump_target = t;
8018 return true;
8020 case PARM_DECL:
8021 if (now && want_rval)
8023 tree type = TREE_TYPE (t);
8024 if ((processing_template_decl && !COMPLETE_TYPE_P (type))
8025 || dependent_type_p (type)
8026 || is_really_empty_class (type, /*ignore_vptr*/false))
8027 /* An empty class has no data to read. */
8028 return true;
8029 if (flags & tf_error)
8030 error ("%qE is not a constant expression", t);
8031 return false;
8033 return true;
8035 case AGGR_INIT_EXPR:
8036 case CALL_EXPR:
8037 /* -- an invocation of a function other than a constexpr function
8038 or a constexpr constructor. */
8040 tree fun = get_function_named_in_call (t);
8041 const int nargs = call_expr_nargs (t);
8042 i = 0;
8044 if (fun == NULL_TREE)
8046 /* Reset to allow the function to continue past the end
8047 of the block below. Otherwise return early. */
8048 bool bail = true;
8050 if (TREE_CODE (t) == CALL_EXPR
8051 && CALL_EXPR_FN (t) == NULL_TREE)
8052 switch (CALL_EXPR_IFN (t))
8054 /* These should be ignored, they are optimized away from
8055 constexpr functions. */
8056 case IFN_UBSAN_NULL:
8057 case IFN_UBSAN_BOUNDS:
8058 case IFN_UBSAN_VPTR:
8059 case IFN_FALLTHROUGH:
8060 return true;
8062 case IFN_ADD_OVERFLOW:
8063 case IFN_SUB_OVERFLOW:
8064 case IFN_MUL_OVERFLOW:
8065 case IFN_LAUNDER:
8066 case IFN_VEC_CONVERT:
8067 bail = false;
8068 break;
8070 default:
8071 break;
8074 if (bail)
8076 /* fold_call_expr can't do anything with IFN calls. */
8077 if (flags & tf_error)
8078 error_at (loc, "call to internal function %qE", t);
8079 return false;
8083 if (fun && is_overloaded_fn (fun))
8085 if (TREE_CODE (fun) == FUNCTION_DECL)
8087 if (builtin_valid_in_constant_expr_p (fun))
8088 return true;
8089 if (!DECL_DECLARED_CONSTEXPR_P (fun)
8090 /* Allow any built-in function; if the expansion
8091 isn't constant, we'll deal with that then. */
8092 && !fndecl_built_in_p (fun)
8093 /* In C++20, replaceable global allocation functions
8094 are constant expressions. */
8095 && (!cxx_replaceable_global_alloc_fn (fun)
8096 || TREE_CODE (t) != CALL_EXPR
8097 || (!CALL_FROM_NEW_OR_DELETE_P (t)
8098 && (current_function_decl == NULL_TREE
8099 || !is_std_allocator_allocate
8100 (current_function_decl))))
8101 /* Allow placement new in std::construct_at. */
8102 && (!cxx_placement_new_fn (fun)
8103 || TREE_CODE (t) != CALL_EXPR
8104 || current_function_decl == NULL_TREE
8105 || !is_std_construct_at (current_function_decl))
8106 && !cxx_dynamic_cast_fn_p (fun))
8108 if (flags & tf_error)
8110 error_at (loc, "call to non-%<constexpr%> function %qD",
8111 fun);
8112 explain_invalid_constexpr_fn (fun);
8114 return false;
8116 /* A call to a non-static member function takes the address
8117 of the object as the first argument. But in a constant
8118 expression the address will be folded away, so look
8119 through it now. */
8120 if (DECL_NONSTATIC_MEMBER_FUNCTION_P (fun)
8121 && !DECL_CONSTRUCTOR_P (fun))
8123 tree x = get_nth_callarg (t, 0);
8124 if (is_this_parameter (x))
8125 return true;
8126 /* Don't require an immediately constant value, as
8127 constexpr substitution might not use the value. */
8128 bool sub_now = false;
8129 if (!potential_constant_expression_1 (x, rval, strict,
8130 sub_now, flags,
8131 jump_target))
8132 return false;
8133 i = 1;
8136 else
8138 if (!RECUR (fun, true))
8139 return false;
8140 fun = get_first_fn (fun);
8142 /* Skip initial arguments to base constructors. */
8143 if (DECL_BASE_CONSTRUCTOR_P (fun))
8144 i = num_artificial_parms_for (fun);
8145 fun = DECL_ORIGIN (fun);
8147 else if (fun)
8149 if (RECUR (fun, rval))
8150 /* Might end up being a constant function pointer. */;
8151 else
8152 return false;
8154 for (; i < nargs; ++i)
8156 tree x = get_nth_callarg (t, i);
8157 /* In a template, reference arguments haven't been converted to
8158 REFERENCE_TYPE and we might not even know if the parameter
8159 is a reference, so accept lvalue constants too. */
8160 bool rv = processing_template_decl ? any : rval;
8161 /* Don't require an immediately constant value, as constexpr
8162 substitution might not use the value of the argument. */
8163 bool sub_now = false;
8164 if (!potential_constant_expression_1 (x, rv, strict,
8165 sub_now, flags, jump_target))
8166 return false;
8168 return true;
8171 case NON_LVALUE_EXPR:
8172 /* -- an lvalue-to-rvalue conversion (4.1) unless it is applied to
8173 -- an lvalue of integral type that refers to a non-volatile
8174 const variable or static data member initialized with
8175 constant expressions, or
8177 -- an lvalue of literal type that refers to non-volatile
8178 object defined with constexpr, or that refers to a
8179 sub-object of such an object; */
8180 return RECUR (TREE_OPERAND (t, 0), rval);
8182 case VAR_DECL:
8183 if (DECL_HAS_VALUE_EXPR_P (t))
8185 if (now && is_normal_capture_proxy (t))
8187 /* -- in a lambda-expression, a reference to this or to a
8188 variable with automatic storage duration defined outside that
8189 lambda-expression, where the reference would be an
8190 odr-use. */
8192 if (want_rval)
8193 /* Since we're doing an lvalue-rvalue conversion, this might
8194 not be an odr-use, so evaluate the variable directly. */
8195 return RECUR (DECL_CAPTURED_VARIABLE (t), rval);
8197 if (flags & tf_error)
8199 tree cap = DECL_CAPTURED_VARIABLE (t);
8200 error ("lambda capture of %qE is not a constant expression",
8201 cap);
8202 if (decl_constant_var_p (cap))
8203 inform (input_location, "because it is used as a glvalue");
8205 return false;
8207 /* Treat __PRETTY_FUNCTION__ inside a template function as
8208 potentially-constant. */
8209 else if (DECL_PRETTY_FUNCTION_P (t)
8210 && DECL_VALUE_EXPR (t) == error_mark_node)
8211 return true;
8212 return RECUR (DECL_VALUE_EXPR (t), rval);
8214 if (want_rval
8215 && !var_in_maybe_constexpr_fn (t)
8216 && !type_dependent_expression_p (t)
8217 && !decl_maybe_constant_var_p (t)
8218 && (strict
8219 || !CP_TYPE_CONST_NON_VOLATILE_P (TREE_TYPE (t))
8220 || (DECL_INITIAL (t)
8221 && !DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (t)))
8222 && COMPLETE_TYPE_P (TREE_TYPE (t))
8223 && !is_really_empty_class (TREE_TYPE (t), /*ignore_vptr*/false))
8225 if (flags & tf_error)
8226 non_const_var_error (loc, t);
8227 return false;
8229 return true;
8231 case NOP_EXPR:
8232 if (REINTERPRET_CAST_P (t))
8234 if (flags & tf_error)
8235 error_at (loc, "%<reinterpret_cast%> is not a constant expression");
8236 return false;
8238 /* FALLTHRU */
8239 case CONVERT_EXPR:
8240 case VIEW_CONVERT_EXPR:
8241 /* -- a reinterpret_cast. FIXME not implemented, and this rule
8242 may change to something more specific to type-punning (DR 1312). */
8244 tree from = TREE_OPERAND (t, 0);
8245 if (location_wrapper_p (t))
8246 return (RECUR (from, want_rval));
8247 if (INDIRECT_TYPE_P (TREE_TYPE (t)))
8249 STRIP_ANY_LOCATION_WRAPPER (from);
8250 if (TREE_CODE (from) == INTEGER_CST
8251 && !integer_zerop (from))
8253 if (flags & tf_error)
8254 error_at (loc,
8255 "%<reinterpret_cast%> from integer to pointer");
8256 return false;
8259 return (RECUR (from, TREE_CODE (t) != VIEW_CONVERT_EXPR));
8262 case ADDRESSOF_EXPR:
8263 /* This is like ADDR_EXPR, except it won't form pointer-to-member. */
8264 t = TREE_OPERAND (t, 0);
8265 goto handle_addr_expr;
8267 case ADDR_EXPR:
8268 /* -- a unary operator & that is applied to an lvalue that
8269 designates an object with thread or automatic storage
8270 duration; */
8271 t = TREE_OPERAND (t, 0);
8273 if (TREE_CODE (t) == OFFSET_REF && PTRMEM_OK_P (t))
8274 /* A pointer-to-member constant. */
8275 return true;
8277 handle_addr_expr:
8278 #if 0
8279 /* FIXME adjust when issue 1197 is fully resolved. For now don't do
8280 any checking here, as we might dereference the pointer later. If
8281 we remove this code, also remove check_automatic_or_tls. */
8282 i = check_automatic_or_tls (t);
8283 if (i == ck_ok)
8284 return true;
8285 if (i == ck_bad)
8287 if (flags & tf_error)
8288 error ("address-of an object %qE with thread local or "
8289 "automatic storage is not a constant expression", t);
8290 return false;
8292 #endif
8293 return RECUR (t, any);
8295 case COMPONENT_REF:
8296 case ARROW_EXPR:
8297 case OFFSET_REF:
8298 /* -- a class member access unless its postfix-expression is
8299 of literal type or of pointer to literal type. */
8300 /* This test would be redundant, as it follows from the
8301 postfix-expression being a potential constant expression. */
8302 if (type_unknown_p (t))
8303 return true;
8304 if (is_overloaded_fn (t))
8305 /* In a template, a COMPONENT_REF of a function expresses ob.fn(),
8306 which uses ob as an lvalue. */
8307 want_rval = false;
8308 gcc_fallthrough ();
8310 case REALPART_EXPR:
8311 case IMAGPART_EXPR:
8312 case BIT_FIELD_REF:
8313 return RECUR (TREE_OPERAND (t, 0), want_rval);
8315 case EXPR_PACK_EXPANSION:
8316 return RECUR (PACK_EXPANSION_PATTERN (t), want_rval);
8318 case INDIRECT_REF:
8320 tree x = TREE_OPERAND (t, 0);
8321 STRIP_NOPS (x);
8322 if (is_this_parameter (x) && !is_capture_proxy (x))
8324 if (!var_in_maybe_constexpr_fn (x))
8326 if (flags & tf_error)
8327 error_at (loc, "use of %<this%> in a constant expression");
8328 return false;
8330 return true;
8332 return RECUR (x, rval);
8335 case STATEMENT_LIST:
8336 for (tree stmt : tsi_range (t))
8337 if (!RECUR (stmt, any))
8338 return false;
8339 return true;
8341 case MODIFY_EXPR:
8342 if (cxx_dialect < cxx14)
8343 goto fail;
8344 if (!RECUR (TREE_OPERAND (t, 0), any))
8345 return false;
8346 /* Just ignore clobbers. */
8347 if (TREE_CLOBBER_P (TREE_OPERAND (t, 1)))
8348 return true;
8349 if (!RECUR (TREE_OPERAND (t, 1), rval))
8350 return false;
8351 return true;
8353 case MODOP_EXPR:
8354 if (cxx_dialect < cxx14)
8355 goto fail;
8356 if (!RECUR (TREE_OPERAND (t, 0), rval))
8357 return false;
8358 if (!RECUR (TREE_OPERAND (t, 2), rval))
8359 return false;
8360 return true;
8362 case DO_STMT:
8363 if (!RECUR (DO_COND (t), rval))
8364 return false;
8365 if (!RECUR (DO_BODY (t), any))
8366 return false;
8367 if (breaks (jump_target) || continues (jump_target))
8368 *jump_target = NULL_TREE;
8369 return true;
8371 case FOR_STMT:
8372 if (!RECUR (FOR_INIT_STMT (t), any))
8373 return false;
8374 tmp = FOR_COND (t);
8375 if (!RECUR (tmp, rval))
8376 return false;
8377 if (tmp)
8379 if (!processing_template_decl)
8380 tmp = cxx_eval_outermost_constant_expr (tmp, true);
8381 /* If we couldn't evaluate the condition, it might not ever be
8382 true. */
8383 if (!integer_onep (tmp))
8385 /* Before returning true, check if the for body can contain
8386 a return. */
8387 hash_set<tree> pset;
8388 check_for_return_continue_data data = { &pset, NULL_TREE,
8389 NULL_TREE };
8390 if (tree ret_expr
8391 = cp_walk_tree (&FOR_BODY (t), check_for_return_continue,
8392 &data, &pset))
8393 *jump_target = ret_expr;
8394 return true;
8397 if (!RECUR (FOR_EXPR (t), any))
8398 return false;
8399 if (!RECUR (FOR_BODY (t), any))
8400 return false;
8401 if (breaks (jump_target) || continues (jump_target))
8402 *jump_target = NULL_TREE;
8403 return true;
8405 case RANGE_FOR_STMT:
8406 if (!RECUR (RANGE_FOR_INIT_STMT (t), any))
8407 return false;
8408 if (!RECUR (RANGE_FOR_EXPR (t), any))
8409 return false;
8410 if (!RECUR (RANGE_FOR_BODY (t), any))
8411 return false;
8412 if (breaks (jump_target) || continues (jump_target))
8413 *jump_target = NULL_TREE;
8414 return true;
8416 case WHILE_STMT:
8417 tmp = WHILE_COND (t);
8418 if (!RECUR (tmp, rval))
8419 return false;
8420 if (!processing_template_decl)
8421 tmp = cxx_eval_outermost_constant_expr (tmp, true);
8422 /* If we couldn't evaluate the condition, it might not ever be true. */
8423 if (!integer_onep (tmp))
8425 /* Before returning true, check if the while body can contain
8426 a return. */
8427 hash_set<tree> pset;
8428 check_for_return_continue_data data = { &pset, NULL_TREE,
8429 NULL_TREE };
8430 if (tree ret_expr
8431 = cp_walk_tree (&WHILE_BODY (t), check_for_return_continue,
8432 &data, &pset))
8433 *jump_target = ret_expr;
8434 return true;
8436 if (!RECUR (WHILE_BODY (t), any))
8437 return false;
8438 if (breaks (jump_target) || continues (jump_target))
8439 *jump_target = NULL_TREE;
8440 return true;
8442 case SWITCH_STMT:
8443 if (!RECUR (SWITCH_STMT_COND (t), rval))
8444 return false;
8445 /* FIXME we don't check SWITCH_STMT_BODY currently, because even
8446 unreachable labels would be checked and it is enough if there is
8447 a single switch cond value for which it is a valid constant
8448 expression. We need to check if there are any RETURN_EXPRs
8449 or CONTINUE_STMTs inside of the body though, as in that case
8450 we need to set *jump_target. */
8451 else
8453 hash_set<tree> pset;
8454 check_for_return_continue_data data = { &pset, NULL_TREE,
8455 NULL_TREE };
8456 if (tree ret_expr
8457 = cp_walk_tree (&SWITCH_STMT_BODY (t), check_for_return_continue,
8458 &data, &pset))
8459 /* The switch might return. */
8460 *jump_target = ret_expr;
8461 else if (data.continue_stmt)
8462 /* The switch can't return, but might continue. */
8463 *jump_target = data.continue_stmt;
8465 return true;
8467 case STMT_EXPR:
8468 return RECUR (STMT_EXPR_STMT (t), rval);
8470 case LAMBDA_EXPR:
8471 if (cxx_dialect >= cxx17)
8472 /* In C++17 lambdas can be constexpr, don't give up yet. */
8473 return true;
8474 else if (flags & tf_error)
8475 error_at (loc, "lambda-expression is not a constant expression "
8476 "before C++17");
8477 return false;
8479 case DYNAMIC_CAST_EXPR:
8480 case PSEUDO_DTOR_EXPR:
8481 case NEW_EXPR:
8482 case VEC_NEW_EXPR:
8483 case DELETE_EXPR:
8484 case VEC_DELETE_EXPR:
8485 case THROW_EXPR:
8486 case OMP_PARALLEL:
8487 case OMP_TASK:
8488 case OMP_FOR:
8489 case OMP_SIMD:
8490 case OMP_DISTRIBUTE:
8491 case OMP_TASKLOOP:
8492 case OMP_LOOP:
8493 case OMP_TEAMS:
8494 case OMP_TARGET_DATA:
8495 case OMP_TARGET:
8496 case OMP_SECTIONS:
8497 case OMP_ORDERED:
8498 case OMP_CRITICAL:
8499 case OMP_SINGLE:
8500 case OMP_SECTION:
8501 case OMP_MASTER:
8502 case OMP_TASKGROUP:
8503 case OMP_TARGET_UPDATE:
8504 case OMP_TARGET_ENTER_DATA:
8505 case OMP_TARGET_EXIT_DATA:
8506 case OMP_ATOMIC:
8507 case OMP_ATOMIC_READ:
8508 case OMP_ATOMIC_CAPTURE_OLD:
8509 case OMP_ATOMIC_CAPTURE_NEW:
8510 case OMP_DEPOBJ:
8511 case OACC_PARALLEL:
8512 case OACC_KERNELS:
8513 case OACC_SERIAL:
8514 case OACC_DATA:
8515 case OACC_HOST_DATA:
8516 case OACC_LOOP:
8517 case OACC_CACHE:
8518 case OACC_DECLARE:
8519 case OACC_ENTER_DATA:
8520 case OACC_EXIT_DATA:
8521 case OACC_UPDATE:
8522 /* GCC internal stuff. */
8523 case VA_ARG_EXPR:
8524 case TRANSACTION_EXPR:
8525 case AT_ENCODE_EXPR:
8526 fail:
8527 if (flags & tf_error)
8528 error_at (loc, "expression %qE is not a constant expression", t);
8529 return false;
8531 case ASM_EXPR:
8532 if (flags & tf_error)
8533 inline_asm_in_constexpr_error (loc);
8534 return false;
8536 case OBJ_TYPE_REF:
8537 if (cxx_dialect >= cxx20)
8538 /* In C++20 virtual calls can be constexpr, don't give up yet. */
8539 return true;
8540 else if (flags & tf_error)
8541 error_at (loc,
8542 "virtual functions cannot be %<constexpr%> before C++20");
8543 return false;
8545 case TYPEID_EXPR:
8546 /* In C++20, a typeid expression whose operand is of polymorphic
8547 class type can be constexpr. */
8549 tree e = TREE_OPERAND (t, 0);
8550 if (cxx_dialect < cxx20
8551 && strict
8552 && !TYPE_P (e)
8553 && !type_dependent_expression_p (e)
8554 && TYPE_POLYMORPHIC_P (TREE_TYPE (e)))
8556 if (flags & tf_error)
8557 error_at (loc, "%<typeid%> is not a constant expression "
8558 "because %qE is of polymorphic type", e);
8559 return false;
8561 return true;
8564 case POINTER_DIFF_EXPR:
8565 case MINUS_EXPR:
8566 want_rval = true;
8567 goto binary;
8569 case LT_EXPR:
8570 case LE_EXPR:
8571 case GT_EXPR:
8572 case GE_EXPR:
8573 case EQ_EXPR:
8574 case NE_EXPR:
8575 case SPACESHIP_EXPR:
8576 want_rval = true;
8577 goto binary;
8579 case PREINCREMENT_EXPR:
8580 case POSTINCREMENT_EXPR:
8581 case PREDECREMENT_EXPR:
8582 case POSTDECREMENT_EXPR:
8583 if (cxx_dialect < cxx14)
8584 goto fail;
8585 goto unary;
8587 case BIT_NOT_EXPR:
8588 /* A destructor. */
8589 if (TYPE_P (TREE_OPERAND (t, 0)))
8590 return true;
8591 /* fall through. */
8593 case CONJ_EXPR:
8594 case SAVE_EXPR:
8595 case FIX_TRUNC_EXPR:
8596 case FLOAT_EXPR:
8597 case NEGATE_EXPR:
8598 case ABS_EXPR:
8599 case ABSU_EXPR:
8600 case TRUTH_NOT_EXPR:
8601 case FIXED_CONVERT_EXPR:
8602 case UNARY_PLUS_EXPR:
8603 case UNARY_LEFT_FOLD_EXPR:
8604 case UNARY_RIGHT_FOLD_EXPR:
8605 unary:
8606 return RECUR (TREE_OPERAND (t, 0), rval);
8608 case CAST_EXPR:
8609 case CONST_CAST_EXPR:
8610 case STATIC_CAST_EXPR:
8611 case REINTERPRET_CAST_EXPR:
8612 case IMPLICIT_CONV_EXPR:
8613 if (cxx_dialect < cxx11
8614 && !dependent_type_p (TREE_TYPE (t))
8615 && !INTEGRAL_OR_ENUMERATION_TYPE_P (TREE_TYPE (t)))
8616 /* In C++98, a conversion to non-integral type can't be part of a
8617 constant expression. */
8619 if (flags & tf_error)
8620 error_at (loc,
8621 "cast to non-integral type %qT in a constant expression",
8622 TREE_TYPE (t));
8623 return false;
8625 /* This might be a conversion from a class to a (potentially) literal
8626 type. Let's consider it potentially constant since the conversion
8627 might be a constexpr user-defined conversion. */
8628 else if (cxx_dialect >= cxx11
8629 && (dependent_type_p (TREE_TYPE (t))
8630 || !COMPLETE_TYPE_P (TREE_TYPE (t))
8631 || literal_type_p (TREE_TYPE (t)))
8632 && TREE_OPERAND (t, 0))
8634 tree type = TREE_TYPE (TREE_OPERAND (t, 0));
8635 /* If this is a dependent type, it could end up being a class
8636 with conversions. */
8637 if (type == NULL_TREE || WILDCARD_TYPE_P (type))
8638 return true;
8639 /* Or a non-dependent class which has conversions. */
8640 else if (CLASS_TYPE_P (type)
8641 && (TYPE_HAS_CONVERSION (type) || dependent_scope_p (type)))
8642 return true;
8645 return (RECUR (TREE_OPERAND (t, 0),
8646 !TYPE_REF_P (TREE_TYPE (t))));
8648 case BIND_EXPR:
8649 return RECUR (BIND_EXPR_BODY (t), want_rval);
8651 case CLEANUP_POINT_EXPR:
8652 case MUST_NOT_THROW_EXPR:
8653 case TRY_CATCH_EXPR:
8654 case TRY_BLOCK:
8655 case EH_SPEC_BLOCK:
8656 case EXPR_STMT:
8657 case PAREN_EXPR:
8658 case NON_DEPENDENT_EXPR:
8659 /* For convenience. */
8660 case LOOP_EXPR:
8661 case EXIT_EXPR:
8662 return RECUR (TREE_OPERAND (t, 0), want_rval);
8664 case DECL_EXPR:
8665 tmp = DECL_EXPR_DECL (t);
8666 if (VAR_P (tmp) && !DECL_ARTIFICIAL (tmp))
8668 if (TREE_STATIC (tmp))
8670 if (flags & tf_error)
8671 error_at (DECL_SOURCE_LOCATION (tmp), "%qD declared "
8672 "%<static%> in %<constexpr%> context", tmp);
8673 return false;
8675 else if (CP_DECL_THREAD_LOCAL_P (tmp))
8677 if (flags & tf_error)
8678 error_at (DECL_SOURCE_LOCATION (tmp), "%qD declared "
8679 "%<thread_local%> in %<constexpr%> context", tmp);
8680 return false;
8682 else if (!check_for_uninitialized_const_var
8683 (tmp, /*constexpr_context_p=*/true, flags))
8684 return false;
8686 return RECUR (tmp, want_rval);
8688 case TRY_FINALLY_EXPR:
8689 return (RECUR (TREE_OPERAND (t, 0), want_rval)
8690 && RECUR (TREE_OPERAND (t, 1), any));
8692 case SCOPE_REF:
8693 return RECUR (TREE_OPERAND (t, 1), want_rval);
8695 case TARGET_EXPR:
8696 if (!TARGET_EXPR_DIRECT_INIT_P (t)
8697 && !literal_type_p (TREE_TYPE (t)))
8699 if (flags & tf_error)
8701 auto_diagnostic_group d;
8702 error_at (loc, "temporary of non-literal type %qT in a "
8703 "constant expression", TREE_TYPE (t));
8704 explain_non_literal_class (TREE_TYPE (t));
8706 return false;
8708 /* FALLTHRU */
8709 case INIT_EXPR:
8710 return RECUR (TREE_OPERAND (t, 1), rval);
8712 case CONSTRUCTOR:
8714 vec<constructor_elt, va_gc> *v = CONSTRUCTOR_ELTS (t);
8715 constructor_elt *ce;
8716 for (i = 0; vec_safe_iterate (v, i, &ce); ++i)
8717 if (!RECUR (ce->value, want_rval))
8718 return false;
8719 return true;
8722 case TREE_LIST:
8724 gcc_assert (TREE_PURPOSE (t) == NULL_TREE
8725 || DECL_P (TREE_PURPOSE (t)));
8726 if (!RECUR (TREE_VALUE (t), want_rval))
8727 return false;
8728 if (TREE_CHAIN (t) == NULL_TREE)
8729 return true;
8730 return RECUR (TREE_CHAIN (t), want_rval);
8733 case TRUNC_DIV_EXPR:
8734 case CEIL_DIV_EXPR:
8735 case FLOOR_DIV_EXPR:
8736 case ROUND_DIV_EXPR:
8737 case TRUNC_MOD_EXPR:
8738 case CEIL_MOD_EXPR:
8739 case ROUND_MOD_EXPR:
8741 tree denom = TREE_OPERAND (t, 1);
8742 if (!RECUR (denom, rval))
8743 return false;
8744 /* We can't call cxx_eval_outermost_constant_expr on an expression
8745 that hasn't been through instantiate_non_dependent_expr yet. */
8746 if (!processing_template_decl)
8747 denom = cxx_eval_outermost_constant_expr (denom, true);
8748 if (integer_zerop (denom))
8750 if (flags & tf_error)
8751 error ("division by zero is not a constant expression");
8752 return false;
8754 else
8756 want_rval = true;
8757 return RECUR (TREE_OPERAND (t, 0), want_rval);
8761 case COMPOUND_EXPR:
8763 /* check_return_expr sometimes wraps a TARGET_EXPR in a
8764 COMPOUND_EXPR; don't get confused. */
8765 tree op0 = TREE_OPERAND (t, 0);
8766 tree op1 = TREE_OPERAND (t, 1);
8767 STRIP_NOPS (op1);
8768 if (TREE_CODE (op0) == TARGET_EXPR && op1 == TARGET_EXPR_SLOT (op0))
8769 return RECUR (op0, want_rval);
8770 else
8771 goto binary;
8774 /* If the first operand is the non-short-circuit constant, look at
8775 the second operand; otherwise we only care about the first one for
8776 potentiality. */
8777 case TRUTH_AND_EXPR:
8778 case TRUTH_ANDIF_EXPR:
8779 tmp = boolean_true_node;
8780 goto truth;
8781 case TRUTH_OR_EXPR:
8782 case TRUTH_ORIF_EXPR:
8783 tmp = boolean_false_node;
8784 truth:
8786 tree op = TREE_OPERAND (t, 0);
8787 if (!RECUR (op, rval))
8788 return false;
8789 if (!processing_template_decl)
8790 op = cxx_eval_outermost_constant_expr (op, true);
8791 if (tree_int_cst_equal (op, tmp))
8792 return RECUR (TREE_OPERAND (t, 1), rval);
8793 else
8794 return true;
8797 case PLUS_EXPR:
8798 case MULT_EXPR:
8799 case POINTER_PLUS_EXPR:
8800 case RDIV_EXPR:
8801 case EXACT_DIV_EXPR:
8802 case MIN_EXPR:
8803 case MAX_EXPR:
8804 case LSHIFT_EXPR:
8805 case RSHIFT_EXPR:
8806 case LROTATE_EXPR:
8807 case RROTATE_EXPR:
8808 case BIT_IOR_EXPR:
8809 case BIT_XOR_EXPR:
8810 case BIT_AND_EXPR:
8811 case TRUTH_XOR_EXPR:
8812 case UNORDERED_EXPR:
8813 case ORDERED_EXPR:
8814 case UNLT_EXPR:
8815 case UNLE_EXPR:
8816 case UNGT_EXPR:
8817 case UNGE_EXPR:
8818 case UNEQ_EXPR:
8819 case LTGT_EXPR:
8820 case RANGE_EXPR:
8821 case COMPLEX_EXPR:
8822 want_rval = true;
8823 /* Fall through. */
8824 case ARRAY_REF:
8825 case ARRAY_RANGE_REF:
8826 case MEMBER_REF:
8827 case DOTSTAR_EXPR:
8828 case MEM_REF:
8829 case BINARY_LEFT_FOLD_EXPR:
8830 case BINARY_RIGHT_FOLD_EXPR:
8831 binary:
8832 for (i = 0; i < 2; ++i)
8833 if (!RECUR (TREE_OPERAND (t, i), want_rval))
8834 return false;
8835 return true;
8837 case VEC_PERM_EXPR:
8838 for (i = 0; i < 3; ++i)
8839 if (!RECUR (TREE_OPERAND (t, i), true))
8840 return false;
8841 return true;
8843 case COND_EXPR:
8844 if (COND_EXPR_IS_VEC_DELETE (t) && cxx_dialect < cxx20)
8846 if (flags & tf_error)
8847 error_at (loc, "%<delete[]%> is not a constant expression");
8848 return false;
8850 /* Fall through. */
8851 case IF_STMT:
8852 case VEC_COND_EXPR:
8853 /* If the condition is a known constant, we know which of the legs we
8854 care about; otherwise we only require that the condition and
8855 either of the legs be potentially constant. */
8856 tmp = TREE_OPERAND (t, 0);
8857 if (!RECUR (tmp, rval))
8858 return false;
8859 if (!processing_template_decl)
8860 tmp = cxx_eval_outermost_constant_expr (tmp, true);
8861 /* potential_constant_expression* isn't told if it is called for
8862 manifestly_const_eval or not, so for consteval if always
8863 process both branches as if the condition is not a known
8864 constant. */
8865 if (TREE_CODE (t) != IF_STMT || !IF_STMT_CONSTEVAL_P (t))
8867 if (integer_zerop (tmp))
8868 return RECUR (TREE_OPERAND (t, 2), want_rval);
8869 else if (TREE_CODE (tmp) == INTEGER_CST)
8870 return RECUR (TREE_OPERAND (t, 1), want_rval);
8872 tmp = *jump_target;
8873 for (i = 1; i < 3; ++i)
8875 tree this_jump_target = tmp;
8876 if (potential_constant_expression_1 (TREE_OPERAND (t, i),
8877 want_rval, strict, now,
8878 tf_none, &this_jump_target))
8880 if (returns (&this_jump_target))
8881 *jump_target = this_jump_target;
8882 else if (!returns (jump_target))
8884 if (breaks (&this_jump_target)
8885 || continues (&this_jump_target))
8886 *jump_target = this_jump_target;
8887 if (i == 1)
8889 /* If the then branch is potentially constant, but
8890 does not return, check if the else branch
8891 couldn't return, break or continue. */
8892 hash_set<tree> pset;
8893 check_for_return_continue_data data = { &pset, NULL_TREE,
8894 NULL_TREE };
8895 if (tree ret_expr
8896 = cp_walk_tree (&TREE_OPERAND (t, 2),
8897 check_for_return_continue, &data,
8898 &pset))
8899 *jump_target = ret_expr;
8900 else if (*jump_target == NULL_TREE)
8902 if (data.continue_stmt)
8903 *jump_target = data.continue_stmt;
8904 else if (data.break_stmt)
8905 *jump_target = data.break_stmt;
8909 return true;
8912 if (flags & tf_error)
8913 error_at (loc, "expression %qE is not a constant expression", t);
8914 return false;
8916 case VEC_INIT_EXPR:
8917 if (VEC_INIT_EXPR_IS_CONSTEXPR (t))
8918 return true;
8919 if (flags & tf_error)
8921 error_at (loc, "non-constant array initialization");
8922 diagnose_non_constexpr_vec_init (t);
8924 return false;
8926 case TYPE_DECL:
8927 case TAG_DEFN:
8928 /* We can see these in statement-expressions. */
8929 return true;
8931 case CLEANUP_STMT:
8932 if (!RECUR (CLEANUP_BODY (t), any))
8933 return false;
8934 if (!CLEANUP_EH_ONLY (t) && !RECUR (CLEANUP_EXPR (t), any))
8935 return false;
8936 return true;
8938 case EMPTY_CLASS_EXPR:
8939 return true;
8941 case GOTO_EXPR:
8943 tree *target = &TREE_OPERAND (t, 0);
8944 /* Gotos representing break and continue are OK. */
8945 if (breaks (target) || continues (target))
8947 *jump_target = *target;
8948 return true;
8950 if (flags & tf_error)
8951 error_at (loc, "%<goto%> is not a constant expression");
8952 return false;
8955 case LABEL_EXPR:
8956 t = LABEL_EXPR_LABEL (t);
8957 if (DECL_ARTIFICIAL (t))
8958 return true;
8959 else if (flags & tf_error)
8960 error_at (loc, "label definition is not a constant expression");
8961 return false;
8963 case ANNOTATE_EXPR:
8964 return RECUR (TREE_OPERAND (t, 0), rval);
8966 case BIT_CAST_EXPR:
8967 return RECUR (TREE_OPERAND (t, 0), rval);
8969 /* Coroutine await, yield and return expressions are not. */
8970 case CO_AWAIT_EXPR:
8971 case CO_YIELD_EXPR:
8972 case CO_RETURN_EXPR:
8973 return false;
8975 default:
8976 if (objc_non_constant_expr_p (t))
8977 return false;
8979 sorry ("unexpected AST of kind %s", get_tree_code_name (TREE_CODE (t)));
8980 gcc_unreachable ();
8981 return false;
8983 #undef RECUR
8986 bool
8987 potential_constant_expression_1 (tree t, bool want_rval, bool strict, bool now,
8988 tsubst_flags_t flags)
8990 tree target = NULL_TREE;
8991 return potential_constant_expression_1 (t, want_rval, strict, now,
8992 flags, &target);
8995 /* The main entry point to the above. */
8997 bool
8998 potential_constant_expression (tree t)
9000 return potential_constant_expression_1 (t, false, true, false, tf_none);
9003 /* As above, but require a constant rvalue. */
9005 bool
9006 potential_rvalue_constant_expression (tree t)
9008 return potential_constant_expression_1 (t, true, true, false, tf_none);
9011 /* Like above, but complain about non-constant expressions. */
9013 bool
9014 require_potential_constant_expression (tree t)
9016 return potential_constant_expression_1 (t, false, true, false,
9017 tf_warning_or_error);
9020 /* Cross product of the above. */
9022 bool
9023 require_potential_rvalue_constant_expression (tree t)
9025 return potential_constant_expression_1 (t, true, true, false,
9026 tf_warning_or_error);
9029 /* Like above, but don't consider PARM_DECL a potential_constant_expression. */
9031 bool
9032 require_rvalue_constant_expression (tree t)
9034 return potential_constant_expression_1 (t, true, true, true,
9035 tf_warning_or_error);
9038 /* Like potential_constant_expression, but don't consider possible constexpr
9039 substitution of the current function. That is, PARM_DECL qualifies under
9040 potential_constant_expression, but not here.
9042 This is basically what you can check when any actual constant values might
9043 be value-dependent. */
9045 bool
9046 is_constant_expression (tree t)
9048 return potential_constant_expression_1 (t, false, true, true, tf_none);
9051 /* As above, but expect an rvalue. */
9053 bool
9054 is_rvalue_constant_expression (tree t)
9056 return potential_constant_expression_1 (t, true, true, true, tf_none);
9059 /* Like above, but complain about non-constant expressions. */
9061 bool
9062 require_constant_expression (tree t)
9064 return potential_constant_expression_1 (t, false, true, true,
9065 tf_warning_or_error);
9068 /* Like is_constant_expression, but allow const variables that are not allowed
9069 under constexpr rules. */
9071 bool
9072 is_static_init_expression (tree t)
9074 return potential_constant_expression_1 (t, false, false, true, tf_none);
9077 /* Returns true if T is a potential constant expression that is not
9078 instantiation-dependent, and therefore a candidate for constant folding even
9079 in a template. */
9081 bool
9082 is_nondependent_constant_expression (tree t)
9084 return (!type_unknown_p (t)
9085 && is_constant_expression (t)
9086 && !instantiation_dependent_expression_p (t));
9089 /* Returns true if T is a potential static initializer expression that is not
9090 instantiation-dependent. */
9092 bool
9093 is_nondependent_static_init_expression (tree t)
9095 return (!type_unknown_p (t)
9096 && is_static_init_expression (t)
9097 && !instantiation_dependent_expression_p (t));
9100 /* Finalize constexpr processing after parsing. */
9102 void
9103 fini_constexpr (void)
9105 /* The contexpr call and fundef copies tables are no longer needed. */
9106 constexpr_call_table = NULL;
9107 fundef_copies_table = NULL;
9110 #include "gt-cp-constexpr.h"