c++: look for empty base at specific offset [PR109678]
[official-gcc.git] / gcc / cp / constexpr.cc
blob70dd6cf4d904f346b0006fea70d122ba239c121a
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-2023 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 "timevar.h"
35 #include "fold-const-call.h"
36 #include "stor-layout.h"
37 #include "cgraph.h"
38 #include "opts.h"
39 #include "stringpool.h"
40 #include "attribs.h"
41 #include "fold-const.h"
42 #include "intl.h"
43 #include "toplev.h"
45 static bool verify_constant (tree, bool, bool *, bool *);
46 #define VERIFY_CONSTANT(X) \
47 do { \
48 if (verify_constant ((X), ctx->quiet, non_constant_p, overflow_p)) \
49 return t; \
50 } while (0)
52 static HOST_WIDE_INT find_array_ctor_elt (tree ary, tree dindex,
53 bool insert = false);
54 static int array_index_cmp (tree key, tree index);
56 /* Returns true iff FUN is an instantiation of a constexpr function
57 template or a defaulted constexpr function. */
59 bool
60 is_instantiation_of_constexpr (tree fun)
62 return ((DECL_TEMPLOID_INSTANTIATION (fun)
63 && DECL_DECLARED_CONSTEXPR_P (DECL_TI_TEMPLATE (fun)))
64 || (DECL_DEFAULTED_FN (fun)
65 && DECL_DECLARED_CONSTEXPR_P (fun)));
68 /* Return true if T is a literal type. */
70 bool
71 literal_type_p (tree t)
73 if (SCALAR_TYPE_P (t)
74 || VECTOR_TYPE_P (t)
75 || TYPE_REF_P (t)
76 || (VOID_TYPE_P (t) && cxx_dialect >= cxx14))
77 return true;
78 if (CLASS_TYPE_P (t))
80 t = complete_type (t);
81 gcc_assert (COMPLETE_TYPE_P (t) || errorcount);
82 return CLASSTYPE_LITERAL_P (t);
84 if (TREE_CODE (t) == ARRAY_TYPE)
85 return literal_type_p (strip_array_types (t));
86 return false;
89 /* If DECL is a variable declared `constexpr', require its type
90 be literal. Return error_mark_node if we give an error, the
91 DECL otherwise. */
93 tree
94 ensure_literal_type_for_constexpr_object (tree decl)
96 tree type = TREE_TYPE (decl);
97 if (VAR_P (decl)
98 && (DECL_DECLARED_CONSTEXPR_P (decl)
99 || var_in_constexpr_fn (decl))
100 && !processing_template_decl)
102 tree stype = strip_array_types (type);
103 if (CLASS_TYPE_P (stype) && !COMPLETE_TYPE_P (complete_type (stype)))
104 /* Don't complain here, we'll complain about incompleteness
105 when we try to initialize the variable. */;
106 else if (!literal_type_p (type))
108 if (DECL_DECLARED_CONSTEXPR_P (decl))
110 auto_diagnostic_group d;
111 error_at (DECL_SOURCE_LOCATION (decl),
112 "the type %qT of %<constexpr%> variable %qD "
113 "is not literal", type, decl);
114 explain_non_literal_class (type);
115 decl = error_mark_node;
117 else if (cxx_dialect < cxx23)
119 if (!is_instantiation_of_constexpr (current_function_decl))
121 auto_diagnostic_group d;
122 error_at (DECL_SOURCE_LOCATION (decl),
123 "variable %qD of non-literal type %qT in "
124 "%<constexpr%> function only available with "
125 "%<-std=c++2b%> or %<-std=gnu++2b%>", decl, type);
126 explain_non_literal_class (type);
127 decl = error_mark_node;
129 cp_function_chain->invalid_constexpr = true;
132 else if (DECL_DECLARED_CONSTEXPR_P (decl)
133 && variably_modified_type_p (type, NULL_TREE))
135 error_at (DECL_SOURCE_LOCATION (decl),
136 "%<constexpr%> variable %qD has variably-modified "
137 "type %qT", decl, type);
138 decl = error_mark_node;
141 return decl;
144 /* Issue a diagnostic with text GMSGID for constructs that are invalid in
145 constexpr functions. CONSTEXPR_FUNDEF_P is true if we're checking
146 a constexpr function body; if so, don't report hard errors and issue
147 a pedwarn pre-C++23, or a warning in C++23, if requested by
148 -Winvalid-constexpr. Otherwise, we're not in the context where we are
149 checking if a function can be marked 'constexpr', so give a hard error. */
151 ATTRIBUTE_GCC_DIAG(3,4)
152 static bool
153 constexpr_error (location_t location, bool constexpr_fundef_p,
154 const char *gmsgid, ...)
156 diagnostic_info diagnostic;
157 va_list ap;
158 rich_location richloc (line_table, location);
159 va_start (ap, gmsgid);
160 bool ret;
161 if (!constexpr_fundef_p)
163 /* Report an error that cannot be suppressed. */
164 diagnostic_set_info (&diagnostic, gmsgid, &ap, &richloc, DK_ERROR);
165 ret = diagnostic_report_diagnostic (global_dc, &diagnostic);
167 else if (warn_invalid_constexpr)
169 diagnostic_set_info (&diagnostic, gmsgid, &ap, &richloc,
170 cxx_dialect < cxx23 ? DK_PEDWARN : DK_WARNING);
171 diagnostic.option_index = OPT_Winvalid_constexpr;
172 ret = diagnostic_report_diagnostic (global_dc, &diagnostic);
174 else
175 ret = false;
176 va_end (ap);
177 return ret;
180 struct constexpr_fundef_hasher : ggc_ptr_hash<constexpr_fundef>
182 static hashval_t hash (const constexpr_fundef *);
183 static bool equal (const constexpr_fundef *, const constexpr_fundef *);
186 /* This table holds all constexpr function definitions seen in
187 the current translation unit. */
189 static GTY (()) hash_table<constexpr_fundef_hasher> *constexpr_fundef_table;
191 /* Utility function used for managing the constexpr function table.
192 Return true if the entries pointed to by P and Q are for the
193 same constexpr function. */
195 inline bool
196 constexpr_fundef_hasher::equal (const constexpr_fundef *lhs,
197 const constexpr_fundef *rhs)
199 return lhs->decl == rhs->decl;
202 /* Utility function used for managing the constexpr function table.
203 Return a hash value for the entry pointed to by Q. */
205 inline hashval_t
206 constexpr_fundef_hasher::hash (const constexpr_fundef *fundef)
208 return DECL_UID (fundef->decl);
211 /* Return a previously saved definition of function FUN. */
213 constexpr_fundef *
214 retrieve_constexpr_fundef (tree fun)
216 if (constexpr_fundef_table == NULL)
217 return NULL;
219 constexpr_fundef fundef = { fun, NULL_TREE, NULL_TREE, NULL_TREE };
220 return constexpr_fundef_table->find (&fundef);
223 /* Check whether the parameter and return types of FUN are valid for a
224 constexpr function, and complain if COMPLAIN. */
226 bool
227 is_valid_constexpr_fn (tree fun, bool complain)
229 bool ret = true;
231 if (DECL_INHERITED_CTOR (fun)
232 && TREE_CODE (fun) == TEMPLATE_DECL)
234 ret = false;
235 if (complain)
236 error ("inherited constructor %qD is not %<constexpr%>",
237 DECL_INHERITED_CTOR (fun));
239 else
241 for (tree parm = FUNCTION_FIRST_USER_PARM (fun);
242 parm != NULL_TREE; parm = TREE_CHAIN (parm))
243 if (!literal_type_p (TREE_TYPE (parm)))
245 ret = false;
246 if (complain)
248 auto_diagnostic_group d;
249 if (constexpr_error (input_location, /*constexpr_fundef_p*/true,
250 "invalid type for parameter %d of "
251 "%<constexpr%> function %q+#D",
252 DECL_PARM_INDEX (parm), fun))
253 explain_non_literal_class (TREE_TYPE (parm));
258 if (LAMBDA_TYPE_P (CP_DECL_CONTEXT (fun)) && cxx_dialect < cxx17)
260 ret = false;
261 if (complain)
262 inform (DECL_SOURCE_LOCATION (fun),
263 "lambdas are implicitly %<constexpr%> only in C++17 and later");
265 else if (DECL_DESTRUCTOR_P (fun))
267 if (cxx_dialect < cxx20)
269 ret = false;
270 if (complain)
271 error_at (DECL_SOURCE_LOCATION (fun),
272 "%<constexpr%> destructors only available"
273 " with %<-std=c++20%> or %<-std=gnu++20%>");
276 else if (!DECL_CONSTRUCTOR_P (fun))
278 tree rettype = TREE_TYPE (TREE_TYPE (fun));
279 if (!literal_type_p (rettype))
281 ret = false;
282 if (complain)
284 auto_diagnostic_group d;
285 if (constexpr_error (input_location, /*constexpr_fundef_p*/true,
286 "invalid return type %qT of %<constexpr%> "
287 "function %q+D", rettype, fun))
288 explain_non_literal_class (rettype);
292 /* C++14 DR 1684 removed this restriction. */
293 if (cxx_dialect < cxx14
294 && DECL_NONSTATIC_MEMBER_FUNCTION_P (fun)
295 && !CLASSTYPE_LITERAL_P (DECL_CONTEXT (fun)))
297 ret = false;
298 if (complain)
300 auto_diagnostic_group d;
301 if (pedwarn (DECL_SOURCE_LOCATION (fun), OPT_Wpedantic,
302 "enclosing class of %<constexpr%> non-static"
303 " member function %q+#D is not a literal type",
304 fun))
305 explain_non_literal_class (DECL_CONTEXT (fun));
309 else if (CLASSTYPE_VBASECLASSES (DECL_CONTEXT (fun)))
311 ret = false;
312 if (complain)
313 error ("%q#T has virtual base classes", DECL_CONTEXT (fun));
316 return ret;
319 /* Subroutine of build_data_member_initialization. MEMBER is a COMPONENT_REF
320 for a member of an anonymous aggregate, INIT is the initializer for that
321 member, and VEC_OUTER is the vector of constructor elements for the class
322 whose constructor we are processing. Add the initializer to the vector
323 and return true to indicate success. */
325 static bool
326 build_anon_member_initialization (tree member, tree init,
327 vec<constructor_elt, va_gc> **vec_outer)
329 /* MEMBER presents the relevant fields from the inside out, but we need
330 to build up the initializer from the outside in so that we can reuse
331 previously built CONSTRUCTORs if this is, say, the second field in an
332 anonymous struct. So we use a vec as a stack. */
333 auto_vec<tree, 2> fields;
336 fields.safe_push (TREE_OPERAND (member, 1));
337 member = TREE_OPERAND (member, 0);
339 while (ANON_AGGR_TYPE_P (TREE_TYPE (member))
340 && TREE_CODE (member) == COMPONENT_REF);
342 /* VEC has the constructor elements vector for the context of FIELD.
343 If FIELD is an anonymous aggregate, we will push inside it. */
344 vec<constructor_elt, va_gc> **vec = vec_outer;
345 tree field;
346 while (field = fields.pop(),
347 ANON_AGGR_TYPE_P (TREE_TYPE (field)))
349 tree ctor;
350 /* If there is already an outer constructor entry for the anonymous
351 aggregate FIELD, use it; otherwise, insert one. */
352 if (vec_safe_is_empty (*vec)
353 || (*vec)->last().index != field)
355 ctor = build_constructor (TREE_TYPE (field), NULL);
356 CONSTRUCTOR_APPEND_ELT (*vec, field, ctor);
358 else
359 ctor = (*vec)->last().value;
360 vec = &CONSTRUCTOR_ELTS (ctor);
363 /* Now we're at the innermost field, the one that isn't an anonymous
364 aggregate. Add its initializer to the CONSTRUCTOR and we're done. */
365 gcc_assert (fields.is_empty());
366 CONSTRUCTOR_APPEND_ELT (*vec, field, init);
368 return true;
371 /* Subroutine of build_constexpr_constructor_member_initializers.
372 The expression tree T represents a data member initialization
373 in a (constexpr) constructor definition. Build a pairing of
374 the data member with its initializer, and prepend that pair
375 to the existing initialization pair INITS. */
377 static bool
378 build_data_member_initialization (tree t, vec<constructor_elt, va_gc> **vec)
380 tree member, init;
381 if (TREE_CODE (t) == CLEANUP_POINT_EXPR)
382 t = TREE_OPERAND (t, 0);
383 if (TREE_CODE (t) == EXPR_STMT)
384 t = TREE_OPERAND (t, 0);
385 if (t == error_mark_node)
386 return false;
387 if (TREE_CODE (t) == STATEMENT_LIST)
389 for (tree stmt : tsi_range (t))
390 if (! build_data_member_initialization (stmt, vec))
391 return false;
392 return true;
394 if (TREE_CODE (t) == CLEANUP_STMT)
396 /* We can't see a CLEANUP_STMT in a constructor for a literal class,
397 but we can in a constexpr constructor for a non-literal class. Just
398 ignore it; either all the initialization will be constant, in which
399 case the cleanup can't run, or it can't be constexpr.
400 Still recurse into CLEANUP_BODY. */
401 return build_data_member_initialization (CLEANUP_BODY (t), vec);
403 if (TREE_CODE (t) == CONVERT_EXPR)
404 t = TREE_OPERAND (t, 0);
405 if (TREE_CODE (t) == INIT_EXPR
406 /* vptr initialization shows up as a MODIFY_EXPR. In C++14 we only
407 use what this function builds for cx_check_missing_mem_inits, and
408 assignment in the ctor body doesn't count. */
409 || (cxx_dialect < cxx14 && TREE_CODE (t) == MODIFY_EXPR))
411 member = TREE_OPERAND (t, 0);
412 init = break_out_target_exprs (TREE_OPERAND (t, 1));
414 else if (TREE_CODE (t) == CALL_EXPR)
416 tree fn = get_callee_fndecl (t);
417 if (!fn || !DECL_CONSTRUCTOR_P (fn))
418 /* We're only interested in calls to subobject constructors. */
419 return true;
420 member = CALL_EXPR_ARG (t, 0);
421 /* We don't use build_cplus_new here because it complains about
422 abstract bases. Leaving the call unwrapped means that it has the
423 wrong type, but cxx_eval_constant_expression doesn't care. */
424 init = break_out_target_exprs (t);
426 else if (TREE_CODE (t) == BIND_EXPR)
427 return build_data_member_initialization (BIND_EXPR_BODY (t), vec);
428 else
429 /* Don't add anything else to the CONSTRUCTOR. */
430 return true;
431 if (INDIRECT_REF_P (member))
432 member = TREE_OPERAND (member, 0);
433 if (TREE_CODE (member) == NOP_EXPR)
435 tree op = member;
436 STRIP_NOPS (op);
437 if (TREE_CODE (op) == ADDR_EXPR)
439 gcc_assert (same_type_ignoring_top_level_qualifiers_p
440 (TREE_TYPE (TREE_TYPE (op)),
441 TREE_TYPE (TREE_TYPE (member))));
442 /* Initializing a cv-qualified member; we need to look through
443 the const_cast. */
444 member = op;
446 else if (op == current_class_ptr
447 && (same_type_ignoring_top_level_qualifiers_p
448 (TREE_TYPE (TREE_TYPE (member)),
449 current_class_type)))
450 /* Delegating constructor. */
451 member = op;
452 else
454 /* This is an initializer for an empty base; keep it for now so
455 we can check it in cxx_eval_bare_aggregate. */
456 gcc_assert (is_empty_class (TREE_TYPE (TREE_TYPE (member))));
459 if (TREE_CODE (member) == ADDR_EXPR)
460 member = TREE_OPERAND (member, 0);
461 if (TREE_CODE (member) == COMPONENT_REF)
463 tree aggr = TREE_OPERAND (member, 0);
464 if (TREE_CODE (aggr) == VAR_DECL)
465 /* Initializing a local variable, don't add anything. */
466 return true;
467 if (TREE_CODE (aggr) != COMPONENT_REF)
468 /* Normal member initialization. */
469 member = TREE_OPERAND (member, 1);
470 else if (ANON_AGGR_TYPE_P (TREE_TYPE (aggr)))
471 /* Initializing a member of an anonymous union. */
472 return build_anon_member_initialization (member, init, vec);
473 else
474 /* We're initializing a vtable pointer in a base. Leave it as
475 COMPONENT_REF so we remember the path to get to the vfield. */
476 gcc_assert (TREE_TYPE (member) == vtbl_ptr_type_node);
479 /* Value-initialization can produce multiple initializers for the
480 same field; use the last one. */
481 if (!vec_safe_is_empty (*vec) && (*vec)->last().index == member)
482 (*vec)->last().value = init;
483 else
484 CONSTRUCTOR_APPEND_ELT (*vec, member, init);
485 return true;
488 /* Subroutine of check_constexpr_ctor_body_1 and constexpr_fn_retval.
489 In C++11 mode checks that the TYPE_DECLs in the BIND_EXPR_VARS of a
490 BIND_EXPR conform to 7.1.5/3/4 on typedef and alias declarations. */
492 static bool
493 check_constexpr_bind_expr_vars (tree t)
495 gcc_assert (TREE_CODE (t) == BIND_EXPR);
497 for (tree var = BIND_EXPR_VARS (t); var; var = DECL_CHAIN (var))
498 if (TREE_CODE (var) == TYPE_DECL
499 && DECL_IMPLICIT_TYPEDEF_P (var)
500 && !LAMBDA_TYPE_P (TREE_TYPE (var)))
501 return false;
502 return true;
505 /* Subroutine of check_constexpr_ctor_body. */
507 static bool
508 check_constexpr_ctor_body_1 (tree last, tree list)
510 switch (TREE_CODE (list))
512 case DECL_EXPR:
513 if (TREE_CODE (DECL_EXPR_DECL (list)) == USING_DECL
514 || TREE_CODE (DECL_EXPR_DECL (list)) == TYPE_DECL)
515 return true;
516 return false;
518 case CLEANUP_POINT_EXPR:
519 return check_constexpr_ctor_body (last, TREE_OPERAND (list, 0),
520 /*complain=*/false);
522 case BIND_EXPR:
523 if (!check_constexpr_bind_expr_vars (list)
524 || !check_constexpr_ctor_body (last, BIND_EXPR_BODY (list),
525 /*complain=*/false))
526 return false;
527 return true;
529 case USING_STMT:
530 case STATIC_ASSERT:
531 case DEBUG_BEGIN_STMT:
532 return true;
534 default:
535 return false;
539 /* Make sure that there are no statements after LAST in the constructor
540 body represented by LIST. */
542 bool
543 check_constexpr_ctor_body (tree last, tree list, bool complain)
545 /* C++14 doesn't require a constexpr ctor to have an empty body. */
546 if (cxx_dialect >= cxx14)
547 return true;
549 bool ok = true;
550 if (TREE_CODE (list) == STATEMENT_LIST)
552 tree_stmt_iterator i = tsi_last (list);
553 for (; !tsi_end_p (i); tsi_prev (&i))
555 tree t = tsi_stmt (i);
556 if (t == last)
557 break;
558 if (!check_constexpr_ctor_body_1 (last, t))
560 ok = false;
561 break;
565 else if (list != last
566 && !check_constexpr_ctor_body_1 (last, list))
567 ok = false;
568 if (!ok)
570 if (complain)
571 error ("%<constexpr%> constructor does not have empty body");
572 DECL_DECLARED_CONSTEXPR_P (current_function_decl) = false;
574 return ok;
577 /* V is a vector of constructor elements built up for the base and member
578 initializers of a constructor for TYPE. They need to be in increasing
579 offset order, which they might not be yet if TYPE has a primary base
580 which is not first in the base-clause or a vptr and at least one base
581 all of which are non-primary. */
583 static vec<constructor_elt, va_gc> *
584 sort_constexpr_mem_initializers (tree type, vec<constructor_elt, va_gc> *v)
586 tree pri = CLASSTYPE_PRIMARY_BINFO (type);
587 tree field_type;
588 unsigned i;
589 constructor_elt *ce;
591 if (pri)
592 field_type = BINFO_TYPE (pri);
593 else if (TYPE_CONTAINS_VPTR_P (type))
594 field_type = vtbl_ptr_type_node;
595 else
596 return v;
598 /* Find the element for the primary base or vptr and move it to the
599 beginning of the vec. */
600 for (i = 0; vec_safe_iterate (v, i, &ce); ++i)
601 if (TREE_TYPE (ce->index) == field_type)
602 break;
604 if (i > 0 && i < vec_safe_length (v))
606 vec<constructor_elt, va_gc> &vref = *v;
607 constructor_elt elt = vref[i];
608 for (; i > 0; --i)
609 vref[i] = vref[i-1];
610 vref[0] = elt;
613 return v;
616 /* Build compile-time evalable representations of member-initializer list
617 for a constexpr constructor. */
619 static tree
620 build_constexpr_constructor_member_initializers (tree type, tree body)
622 vec<constructor_elt, va_gc> *vec = NULL;
623 bool ok = true;
624 while (true)
625 switch (TREE_CODE (body))
627 case MUST_NOT_THROW_EXPR:
628 case EH_SPEC_BLOCK:
629 body = TREE_OPERAND (body, 0);
630 break;
632 case STATEMENT_LIST:
633 for (tree stmt : tsi_range (body))
635 body = stmt;
636 if (TREE_CODE (body) == BIND_EXPR)
637 break;
639 break;
641 case BIND_EXPR:
642 body = BIND_EXPR_BODY (body);
643 goto found;
645 default:
646 gcc_unreachable ();
648 found:
649 if (TREE_CODE (body) == TRY_BLOCK)
651 body = TREE_OPERAND (body, 0);
652 if (TREE_CODE (body) == BIND_EXPR)
653 body = BIND_EXPR_BODY (body);
655 if (TREE_CODE (body) == CLEANUP_POINT_EXPR)
657 body = TREE_OPERAND (body, 0);
658 if (TREE_CODE (body) == EXPR_STMT)
659 body = TREE_OPERAND (body, 0);
660 if (TREE_CODE (body) == INIT_EXPR
661 && (same_type_ignoring_top_level_qualifiers_p
662 (TREE_TYPE (TREE_OPERAND (body, 0)),
663 current_class_type)))
665 /* Trivial copy. */
666 return TREE_OPERAND (body, 1);
668 ok = build_data_member_initialization (body, &vec);
670 else if (TREE_CODE (body) == STATEMENT_LIST)
672 for (tree stmt : tsi_range (body))
674 ok = build_data_member_initialization (stmt, &vec);
675 if (!ok)
676 break;
679 else if (EXPR_P (body))
680 ok = build_data_member_initialization (body, &vec);
681 else
682 gcc_assert (errorcount > 0);
683 if (ok)
685 if (vec_safe_length (vec) > 0)
687 /* In a delegating constructor, return the target. */
688 constructor_elt *ce = &(*vec)[0];
689 if (ce->index == current_class_ptr)
691 body = ce->value;
692 vec_free (vec);
693 return body;
696 vec = sort_constexpr_mem_initializers (type, vec);
697 return build_constructor (type, vec);
699 else
700 return error_mark_node;
703 /* We have an expression tree T that represents a call, either CALL_EXPR
704 or AGGR_INIT_EXPR. If the call is lexically to a named function,
705 retrun the _DECL for that function. */
707 static tree
708 get_function_named_in_call (tree t)
710 tree fun = cp_get_callee (t);
711 if (fun && TREE_CODE (fun) == ADDR_EXPR
712 && TREE_CODE (TREE_OPERAND (fun, 0)) == FUNCTION_DECL)
713 fun = TREE_OPERAND (fun, 0);
714 return fun;
717 /* Subroutine of check_constexpr_fundef. BODY is the body of a function
718 declared to be constexpr, or a sub-statement thereof. Returns the
719 return value if suitable, error_mark_node for a statement not allowed in
720 a constexpr function, or NULL_TREE if no return value was found. */
722 tree
723 constexpr_fn_retval (tree body)
725 switch (TREE_CODE (body))
727 case STATEMENT_LIST:
729 tree expr = NULL_TREE;
730 for (tree stmt : tsi_range (body))
732 tree s = constexpr_fn_retval (stmt);
733 if (s == error_mark_node)
734 return error_mark_node;
735 else if (s == NULL_TREE)
736 /* Keep iterating. */;
737 else if (expr)
738 /* Multiple return statements. */
739 return error_mark_node;
740 else
741 expr = s;
743 return expr;
746 case RETURN_EXPR:
747 return break_out_target_exprs (TREE_OPERAND (body, 0));
749 case DECL_EXPR:
751 tree decl = DECL_EXPR_DECL (body);
752 if (TREE_CODE (decl) == USING_DECL
753 /* Accept __func__, __FUNCTION__, and __PRETTY_FUNCTION__. */
754 || DECL_ARTIFICIAL (decl))
755 return NULL_TREE;
756 return error_mark_node;
759 case CLEANUP_POINT_EXPR:
760 return constexpr_fn_retval (TREE_OPERAND (body, 0));
762 case BIND_EXPR:
763 if (!check_constexpr_bind_expr_vars (body))
764 return error_mark_node;
765 return constexpr_fn_retval (BIND_EXPR_BODY (body));
767 case USING_STMT:
768 case DEBUG_BEGIN_STMT:
769 return NULL_TREE;
771 case CALL_EXPR:
773 tree fun = get_function_named_in_call (body);
774 if (fun != NULL_TREE
775 && fndecl_built_in_p (fun, BUILT_IN_UNREACHABLE))
776 return NULL_TREE;
778 /* Fallthru. */
780 default:
781 return error_mark_node;
785 /* Subroutine of check_constexpr_fundef. BODY is the DECL_SAVED_TREE of
786 FUN; do the necessary transformations to turn it into a single expression
787 that we can store in the hash table. */
789 static tree
790 massage_constexpr_body (tree fun, tree body)
792 if (DECL_CONSTRUCTOR_P (fun))
793 body = build_constexpr_constructor_member_initializers
794 (DECL_CONTEXT (fun), body);
795 else if (cxx_dialect < cxx14)
797 if (TREE_CODE (body) == EH_SPEC_BLOCK)
798 body = EH_SPEC_STMTS (body);
799 if (TREE_CODE (body) == MUST_NOT_THROW_EXPR)
800 body = TREE_OPERAND (body, 0);
801 body = constexpr_fn_retval (body);
803 return body;
806 /* CTYPE is a type constructed from BODY. Return true if some
807 bases/fields are uninitialized, and complain if COMPLAIN. */
809 static bool
810 cx_check_missing_mem_inits (tree ctype, tree body, bool complain)
812 /* We allow uninitialized bases/fields in C++20. */
813 if (cxx_dialect >= cxx20)
814 return false;
816 unsigned nelts = 0;
818 if (body)
820 if (TREE_CODE (body) != CONSTRUCTOR)
821 return false;
822 nelts = CONSTRUCTOR_NELTS (body);
824 tree field = TYPE_FIELDS (ctype);
826 if (TREE_CODE (ctype) == UNION_TYPE)
828 if (nelts == 0 && next_aggregate_field (field))
830 if (complain)
831 error ("%<constexpr%> constructor for union %qT must "
832 "initialize exactly one non-static data member", ctype);
833 return true;
835 return false;
838 /* Iterate over the CONSTRUCTOR, checking any missing fields don't
839 need an explicit initialization. */
840 bool bad = false;
841 for (unsigned i = 0; i <= nelts; ++i)
843 tree index = NULL_TREE;
844 if (i < nelts)
846 index = CONSTRUCTOR_ELT (body, i)->index;
847 /* Skip base and vtable inits. */
848 if (TREE_CODE (index) != FIELD_DECL
849 || DECL_ARTIFICIAL (index))
850 continue;
853 for (; field != index; field = DECL_CHAIN (field))
855 tree ftype;
856 if (TREE_CODE (field) != FIELD_DECL)
857 continue;
858 if (DECL_UNNAMED_BIT_FIELD (field))
859 continue;
860 if (DECL_ARTIFICIAL (field))
861 continue;
862 if (ANON_AGGR_TYPE_P (TREE_TYPE (field)))
864 /* Recurse to check the anonymous aggregate member. */
865 bad |= cx_check_missing_mem_inits
866 (TREE_TYPE (field), NULL_TREE, complain);
867 if (bad && !complain)
868 return true;
869 continue;
871 ftype = TREE_TYPE (field);
872 if (!ftype || !TYPE_P (ftype) || !COMPLETE_TYPE_P (ftype))
873 /* A flexible array can't be intialized here, so don't complain
874 that it isn't. */
875 continue;
876 if (is_empty_field (field))
877 /* An empty field doesn't need an initializer. */
878 continue;
879 ftype = strip_array_types (ftype);
880 if (type_has_constexpr_default_constructor (ftype))
882 /* It's OK to skip a member with a trivial constexpr ctor.
883 A constexpr ctor that isn't trivial should have been
884 added in by now. */
885 gcc_checking_assert (!TYPE_HAS_COMPLEX_DFLT (ftype)
886 || errorcount != 0);
887 continue;
889 if (!complain)
890 return true;
891 auto_diagnostic_group d;
892 error ("member %qD must be initialized by mem-initializer "
893 "in %<constexpr%> constructor", field);
894 inform (DECL_SOURCE_LOCATION (field), "declared here");
895 bad = true;
897 if (field == NULL_TREE)
898 break;
900 if (ANON_AGGR_TYPE_P (TREE_TYPE (index)))
902 /* Check the anonymous aggregate initializer is valid. */
903 bad |= cx_check_missing_mem_inits
904 (TREE_TYPE (index), CONSTRUCTOR_ELT (body, i)->value, complain);
905 if (bad && !complain)
906 return true;
908 field = DECL_CHAIN (field);
911 return bad;
914 /* We are processing the definition of the constexpr function FUN.
915 Check that its body fulfills the apropriate requirements and
916 enter it in the constexpr function definition table. */
918 void
919 maybe_save_constexpr_fundef (tree fun)
921 if (processing_template_decl
922 || cp_function_chain->invalid_constexpr
923 || (DECL_CLONED_FUNCTION_P (fun) && !DECL_DELETING_DESTRUCTOR_P (fun)))
924 return;
926 /* With -fimplicit-constexpr, try to make inlines constexpr. We'll
927 actually set DECL_DECLARED_CONSTEXPR_P below if the checks pass. */
928 bool implicit = false;
929 if (flag_implicit_constexpr)
931 if (DECL_DELETING_DESTRUCTOR_P (fun)
932 && decl_implicit_constexpr_p (DECL_CLONED_FUNCTION (fun)))
933 /* Don't inherit implicit constexpr from the non-deleting
934 destructor. */
935 DECL_DECLARED_CONSTEXPR_P (fun) = false;
937 if (!DECL_DECLARED_CONSTEXPR_P (fun)
938 && DECL_DECLARED_INLINE_P (fun)
939 && !lookup_attribute ("noinline", DECL_ATTRIBUTES (fun)))
940 implicit = true;
943 if (!DECL_DECLARED_CONSTEXPR_P (fun) && !implicit)
944 return;
946 bool complain = !DECL_GENERATED_P (fun) && !implicit;
948 if (!is_valid_constexpr_fn (fun, complain))
949 return;
951 tree massaged = massage_constexpr_body (fun, DECL_SAVED_TREE (fun));
952 if (massaged == NULL_TREE || massaged == error_mark_node)
954 if (!DECL_CONSTRUCTOR_P (fun) && complain)
955 error ("body of %<constexpr%> function %qD not a return-statement",
956 fun);
957 return;
960 bool potential = potential_rvalue_constant_expression (massaged);
961 if (!potential && complain)
962 require_potential_rvalue_constant_expression_fncheck (massaged);
964 if (DECL_CONSTRUCTOR_P (fun) && potential
965 && !DECL_DEFAULTED_FN (fun))
967 if (cx_check_missing_mem_inits (DECL_CONTEXT (fun),
968 massaged, complain))
969 potential = false;
970 else if (cxx_dialect > cxx11)
972 /* What we got from massage_constexpr_body is pretty much just the
973 ctor-initializer, also check the body. */
974 massaged = DECL_SAVED_TREE (fun);
975 potential = potential_rvalue_constant_expression (massaged);
976 if (!potential && complain)
977 require_potential_rvalue_constant_expression_fncheck (massaged);
981 if (!potential && complain
982 /* If -Wno-invalid-constexpr was specified, we haven't complained
983 about non-constant expressions yet. Register the function and
984 complain in explain_invalid_constexpr_fn if the function is
985 called. */
986 && warn_invalid_constexpr != 0)
987 return;
989 if (implicit)
991 if (potential)
993 DECL_DECLARED_CONSTEXPR_P (fun) = true;
994 DECL_LANG_SPECIFIC (fun)->u.fn.implicit_constexpr = true;
995 if (DECL_CONSTRUCTOR_P (fun))
996 TYPE_HAS_CONSTEXPR_CTOR (DECL_CONTEXT (fun)) = true;
998 else
999 /* Don't bother keeping the pre-generic body of unsuitable functions
1000 not explicitly declared constexpr. */
1001 return;
1004 constexpr_fundef entry = {fun, NULL_TREE, NULL_TREE, NULL_TREE};
1005 bool clear_ctx = false;
1006 if (DECL_RESULT (fun) && DECL_CONTEXT (DECL_RESULT (fun)) == NULL_TREE)
1008 clear_ctx = true;
1009 DECL_CONTEXT (DECL_RESULT (fun)) = fun;
1011 tree saved_fn = current_function_decl;
1012 current_function_decl = fun;
1013 entry.body = copy_fn (entry.decl, entry.parms, entry.result);
1014 current_function_decl = saved_fn;
1015 if (clear_ctx)
1016 DECL_CONTEXT (DECL_RESULT (entry.decl)) = NULL_TREE;
1017 if (!potential)
1018 /* For a template instantiation, we want to remember the pre-generic body
1019 for explain_invalid_constexpr_fn, but do tell cxx_eval_call_expression
1020 that it doesn't need to bother trying to expand the function. */
1021 entry.result = error_mark_node;
1023 register_constexpr_fundef (entry);
1026 /* BODY is a validated and massaged definition of a constexpr
1027 function. Register it in the hash table. */
1029 void
1030 register_constexpr_fundef (const constexpr_fundef &value)
1032 /* Create the constexpr function table if necessary. */
1033 if (constexpr_fundef_table == NULL)
1034 constexpr_fundef_table
1035 = hash_table<constexpr_fundef_hasher>::create_ggc (101);
1037 constexpr_fundef **slot = constexpr_fundef_table->find_slot
1038 (const_cast<constexpr_fundef *> (&value), INSERT);
1040 gcc_assert (*slot == NULL);
1041 *slot = ggc_alloc<constexpr_fundef> ();
1042 **slot = value;
1045 /* FUN is a non-constexpr (or, with -Wno-invalid-constexpr, a constexpr
1046 function called in a context that requires a constant expression).
1047 If it comes from a constexpr template, explain why the instantiation
1048 isn't constexpr. Otherwise, explain why the function cannot be used
1049 in a constexpr context. */
1051 void
1052 explain_invalid_constexpr_fn (tree fun)
1054 static hash_set<tree> *diagnosed;
1055 tree body;
1056 /* In C++23, a function marked 'constexpr' may not actually be a constant
1057 expression. We haven't diagnosed the problem yet: -Winvalid-constexpr
1058 wasn't enabled. The function was called, so diagnose why it cannot be
1059 used in a constant expression. */
1060 if (warn_invalid_constexpr == 0 && DECL_DECLARED_CONSTEXPR_P (fun))
1061 /* Go on. */;
1062 /* Only diagnose defaulted functions, lambdas, or instantiations. */
1063 else if (!DECL_DEFAULTED_FN (fun)
1064 && !LAMBDA_TYPE_P (CP_DECL_CONTEXT (fun))
1065 && !is_instantiation_of_constexpr (fun))
1067 inform (DECL_SOURCE_LOCATION (fun), "%qD declared here", fun);
1068 return;
1070 if (diagnosed == NULL)
1071 diagnosed = new hash_set<tree>;
1072 if (diagnosed->add (fun))
1073 /* Already explained. */
1074 return;
1076 iloc_sentinel ils = input_location;
1077 if (!lambda_static_thunk_p (fun))
1079 /* Diagnostics should completely ignore the static thunk, so leave
1080 input_location set to our caller's location. */
1081 input_location = DECL_SOURCE_LOCATION (fun);
1082 inform (input_location,
1083 "%qD is not usable as a %<constexpr%> function because:", fun);
1085 /* First check the declaration. */
1086 if (is_valid_constexpr_fn (fun, true))
1088 /* Then if it's OK, the body. */
1089 if (!DECL_DECLARED_CONSTEXPR_P (fun)
1090 && DECL_DEFAULTED_FN (fun))
1091 explain_implicit_non_constexpr (fun);
1092 else
1094 if (constexpr_fundef *fd = retrieve_constexpr_fundef (fun))
1095 body = fd->body;
1096 else
1097 body = DECL_SAVED_TREE (fun);
1098 body = massage_constexpr_body (fun, body);
1099 require_potential_rvalue_constant_expression (body);
1100 if (DECL_CONSTRUCTOR_P (fun))
1101 cx_check_missing_mem_inits (DECL_CONTEXT (fun), body, true);
1106 /* Objects of this type represent calls to constexpr functions
1107 along with the bindings of parameters to their arguments, for
1108 the purpose of compile time evaluation. */
1110 struct GTY((for_user)) constexpr_call {
1111 /* Description of the constexpr function definition. */
1112 constexpr_fundef *fundef;
1113 /* Parameter bindings environment. A TREE_VEC of arguments. */
1114 tree bindings;
1115 /* Result of the call.
1116 NULL means the call is being evaluated.
1117 error_mark_node means that the evaluation was erroneous;
1118 otherwise, the actuall value of the call. */
1119 tree result;
1120 /* The hash of this call; we remember it here to avoid having to
1121 recalculate it when expanding the hash table. */
1122 hashval_t hash;
1123 /* The value of constexpr_ctx::manifestly_const_eval. */
1124 enum mce_value manifestly_const_eval;
1127 struct constexpr_call_hasher : ggc_ptr_hash<constexpr_call>
1129 static hashval_t hash (constexpr_call *);
1130 static bool equal (constexpr_call *, constexpr_call *);
1133 enum constexpr_switch_state {
1134 /* Used when processing a switch for the first time by cxx_eval_switch_expr
1135 and default: label for that switch has not been seen yet. */
1136 css_default_not_seen,
1137 /* Used when processing a switch for the first time by cxx_eval_switch_expr
1138 and default: label for that switch has been seen already. */
1139 css_default_seen,
1140 /* Used when processing a switch for the second time by
1141 cxx_eval_switch_expr, where default: label should match. */
1142 css_default_processing
1145 /* The constexpr expansion context part which needs one instance per
1146 cxx_eval_outermost_constant_expr invocation. VALUES is a map of values of
1147 variables initialized within the expression. */
1149 class constexpr_global_ctx {
1150 /* Values for any temporaries or local variables within the
1151 constant-expression. */
1152 hash_map<tree,tree> values;
1153 public:
1154 /* Number of cxx_eval_constant_expression calls (except skipped ones,
1155 on simple constants or location wrappers) encountered during current
1156 cxx_eval_outermost_constant_expr call. */
1157 HOST_WIDE_INT constexpr_ops_count;
1158 /* Heap VAR_DECLs created during the evaluation of the outermost constant
1159 expression. */
1160 auto_vec<tree, 16> heap_vars;
1161 /* Cleanups that need to be evaluated at the end of CLEANUP_POINT_EXPR. */
1162 vec<tree> *cleanups;
1163 /* If non-null, only allow modification of existing values of the variables
1164 in this set. Set by modifiable_tracker, below. */
1165 hash_set<tree> *modifiable;
1166 /* Number of heap VAR_DECL deallocations. */
1167 unsigned heap_dealloc_count;
1168 /* Constructor. */
1169 constexpr_global_ctx ()
1170 : constexpr_ops_count (0), cleanups (NULL), modifiable (nullptr),
1171 heap_dealloc_count (0) {}
1173 tree get_value (tree t)
1175 if (tree *p = values.get (t))
1176 return *p;
1177 return NULL_TREE;
1179 tree *get_value_ptr (tree t)
1181 if (modifiable && !modifiable->contains (t))
1182 return nullptr;
1183 return values.get (t);
1185 void put_value (tree t, tree v)
1187 bool already_in_map = values.put (t, v);
1188 if (!already_in_map && modifiable)
1189 modifiable->add (t);
1191 void remove_value (tree t) { values.remove (t); }
1194 /* Helper class for constexpr_global_ctx. In some cases we want to avoid
1195 side-effects from evaluation of a particular subexpression of a
1196 constant-expression. In such cases we use modifiable_tracker to prevent
1197 modification of variables created outside of that subexpression.
1199 ??? We could change the hash_set to a hash_map, allow and track external
1200 modifications, and roll them back in the destructor. It's not clear to me
1201 that this would be worthwhile. */
1203 class modifiable_tracker
1205 hash_set<tree> set;
1206 constexpr_global_ctx *global;
1207 public:
1208 modifiable_tracker (constexpr_global_ctx *g): global(g)
1210 global->modifiable = &set;
1212 ~modifiable_tracker ()
1214 for (tree t: set)
1215 global->remove_value (t);
1216 global->modifiable = nullptr;
1220 /* The constexpr expansion context. CALL is the current function
1221 expansion, CTOR is the current aggregate initializer, OBJECT is the
1222 object being initialized by CTOR, either a VAR_DECL or a _REF. */
1224 struct constexpr_ctx {
1225 /* The part of the context that needs to be unique to the whole
1226 cxx_eval_outermost_constant_expr invocation. */
1227 constexpr_global_ctx *global;
1228 /* The innermost call we're evaluating. */
1229 constexpr_call *call;
1230 /* SAVE_EXPRs and TARGET_EXPR_SLOT vars of TARGET_EXPRs that we've seen
1231 within the current LOOP_EXPR. NULL if we aren't inside a loop. */
1232 vec<tree> *save_exprs;
1233 /* The CONSTRUCTOR we're currently building up for an aggregate
1234 initializer. */
1235 tree ctor;
1236 /* The object we're building the CONSTRUCTOR for. */
1237 tree object;
1238 /* If inside SWITCH_EXPR. */
1239 constexpr_switch_state *css_state;
1240 /* The aggregate initialization context inside which this one is nested. This
1241 is used by lookup_placeholder to resolve PLACEHOLDER_EXPRs. */
1242 const constexpr_ctx *parent;
1244 /* Whether we should error on a non-constant expression or fail quietly.
1245 This flag needs to be here, but some of the others could move to global
1246 if they get larger than a word. */
1247 bool quiet;
1248 /* Whether we are strictly conforming to constant expression rules or
1249 trying harder to get a constant value. */
1250 bool strict;
1251 /* Whether __builtin_is_constant_evaluated () should be true. */
1252 mce_value manifestly_const_eval;
1255 /* This internal flag controls whether we should avoid doing anything during
1256 constexpr evaluation that would cause extra DECL_UID generation, such as
1257 template instantiation and function body copying. */
1259 static bool uid_sensitive_constexpr_evaluation_value;
1261 /* An internal counter that keeps track of the number of times
1262 uid_sensitive_constexpr_evaluation_p returned true. */
1264 static unsigned uid_sensitive_constexpr_evaluation_true_counter;
1266 /* The accessor for uid_sensitive_constexpr_evaluation_value which also
1267 increments the corresponding counter. */
1269 static bool
1270 uid_sensitive_constexpr_evaluation_p ()
1272 if (uid_sensitive_constexpr_evaluation_value)
1274 ++uid_sensitive_constexpr_evaluation_true_counter;
1275 return true;
1277 else
1278 return false;
1281 /* The default constructor for uid_sensitive_constexpr_evaluation_sentinel
1282 enables the internal flag for uid_sensitive_constexpr_evaluation_p
1283 during the lifetime of the sentinel object. Upon its destruction, the
1284 previous value of uid_sensitive_constexpr_evaluation_p is restored. */
1286 uid_sensitive_constexpr_evaluation_sentinel
1287 ::uid_sensitive_constexpr_evaluation_sentinel ()
1288 : ovr (uid_sensitive_constexpr_evaluation_value, true)
1292 /* The default constructor for uid_sensitive_constexpr_evaluation_checker
1293 records the current number of times that uid_sensitive_constexpr_evaluation_p
1294 has been called and returned true. */
1296 uid_sensitive_constexpr_evaluation_checker
1297 ::uid_sensitive_constexpr_evaluation_checker ()
1298 : saved_counter (uid_sensitive_constexpr_evaluation_true_counter)
1302 /* Returns true iff uid_sensitive_constexpr_evaluation_p is true, and
1303 some constexpr evaluation was restricted due to u_s_c_e_p being called
1304 and returning true during the lifetime of this checker object. */
1306 bool
1307 uid_sensitive_constexpr_evaluation_checker::evaluation_restricted_p () const
1309 return (uid_sensitive_constexpr_evaluation_value
1310 && saved_counter != uid_sensitive_constexpr_evaluation_true_counter);
1314 /* A table of all constexpr calls that have been evaluated by the
1315 compiler in this translation unit. */
1317 static GTY (()) hash_table<constexpr_call_hasher> *constexpr_call_table;
1319 /* Compute a hash value for a constexpr call representation. */
1321 inline hashval_t
1322 constexpr_call_hasher::hash (constexpr_call *info)
1324 return info->hash;
1327 /* Return true if the objects pointed to by P and Q represent calls
1328 to the same constexpr function with the same arguments.
1329 Otherwise, return false. */
1331 bool
1332 constexpr_call_hasher::equal (constexpr_call *lhs, constexpr_call *rhs)
1334 if (lhs == rhs)
1335 return true;
1336 if (lhs->hash != rhs->hash)
1337 return false;
1338 if (lhs->manifestly_const_eval != rhs->manifestly_const_eval)
1339 return false;
1340 if (!constexpr_fundef_hasher::equal (lhs->fundef, rhs->fundef))
1341 return false;
1342 return cp_tree_equal (lhs->bindings, rhs->bindings);
1345 /* Initialize the constexpr call table, if needed. */
1347 static void
1348 maybe_initialize_constexpr_call_table (void)
1350 if (constexpr_call_table == NULL)
1351 constexpr_call_table = hash_table<constexpr_call_hasher>::create_ggc (101);
1354 /* During constexpr CALL_EXPR evaluation, to avoid issues with sharing when
1355 a function happens to get called recursively, we unshare the callee
1356 function's body and evaluate this unshared copy instead of evaluating the
1357 original body.
1359 FUNDEF_COPIES_TABLE is a per-function freelist of these unshared function
1360 copies. The underlying data structure of FUNDEF_COPIES_TABLE is a hash_map
1361 that's keyed off of the original FUNCTION_DECL and whose value is a
1362 TREE_LIST of this function's unused copies awaiting reuse.
1364 This is not GC-deletable to avoid GC affecting UID generation. */
1366 static GTY(()) decl_tree_map *fundef_copies_table;
1368 /* Reuse a copy or create a new unshared copy of the function FUN.
1369 Return this copy. We use a TREE_LIST whose PURPOSE is body, VALUE
1370 is parms, TYPE is result. */
1372 static tree
1373 get_fundef_copy (constexpr_fundef *fundef)
1375 tree copy;
1376 bool existed;
1377 tree *slot = &(hash_map_safe_get_or_insert<hm_ggc>
1378 (fundef_copies_table, fundef->decl, &existed, 127));
1380 if (!existed)
1382 /* There is no cached function available, or in use. We can use
1383 the function directly. That the slot is now created records
1384 that this function is now in use. */
1385 copy = build_tree_list (fundef->body, fundef->parms);
1386 TREE_TYPE (copy) = fundef->result;
1388 else if (*slot == NULL_TREE)
1390 if (uid_sensitive_constexpr_evaluation_p ())
1391 return NULL_TREE;
1393 /* We've already used the function itself, so make a copy. */
1394 copy = build_tree_list (NULL, NULL);
1395 tree saved_body = DECL_SAVED_TREE (fundef->decl);
1396 tree saved_parms = DECL_ARGUMENTS (fundef->decl);
1397 tree saved_result = DECL_RESULT (fundef->decl);
1398 tree saved_fn = current_function_decl;
1399 DECL_SAVED_TREE (fundef->decl) = fundef->body;
1400 DECL_ARGUMENTS (fundef->decl) = fundef->parms;
1401 DECL_RESULT (fundef->decl) = fundef->result;
1402 current_function_decl = fundef->decl;
1403 TREE_PURPOSE (copy) = copy_fn (fundef->decl, TREE_VALUE (copy),
1404 TREE_TYPE (copy));
1405 current_function_decl = saved_fn;
1406 DECL_RESULT (fundef->decl) = saved_result;
1407 DECL_ARGUMENTS (fundef->decl) = saved_parms;
1408 DECL_SAVED_TREE (fundef->decl) = saved_body;
1410 else
1412 /* We have a cached function available. */
1413 copy = *slot;
1414 *slot = TREE_CHAIN (copy);
1417 return copy;
1420 /* Save the copy COPY of function FUN for later reuse by
1421 get_fundef_copy(). By construction, there will always be an entry
1422 to find. */
1424 static void
1425 save_fundef_copy (tree fun, tree copy)
1427 tree *slot = fundef_copies_table->get (fun);
1428 TREE_CHAIN (copy) = *slot;
1429 *slot = copy;
1432 /* Whether our evaluation wants a prvalue (e.g. CONSTRUCTOR or _CST),
1433 a glvalue (e.g. VAR_DECL or _REF), or nothing. */
1435 enum value_cat {
1436 vc_prvalue = 0,
1437 vc_glvalue = 1,
1438 vc_discard = 2
1441 static tree cxx_eval_constant_expression (const constexpr_ctx *, tree,
1442 value_cat, bool *, bool *, tree * = NULL);
1443 static tree cxx_fold_indirect_ref (const constexpr_ctx *, location_t, tree, tree,
1444 bool * = NULL);
1445 static tree find_heap_var_refs (tree *, int *, void *);
1447 /* Attempt to evaluate T which represents a call to a builtin function.
1448 We assume here that all builtin functions evaluate to scalar types
1449 represented by _CST nodes. */
1451 static tree
1452 cxx_eval_builtin_function_call (const constexpr_ctx *ctx, tree t, tree fun,
1453 value_cat lval,
1454 bool *non_constant_p, bool *overflow_p)
1456 const int nargs = call_expr_nargs (t);
1457 tree *args = (tree *) alloca (nargs * sizeof (tree));
1458 tree new_call;
1459 int i;
1461 /* Don't fold __builtin_constant_p within a constexpr function. */
1462 bool bi_const_p = DECL_IS_BUILTIN_CONSTANT_P (fun);
1464 /* If we aren't requiring a constant expression, defer __builtin_constant_p
1465 in a constexpr function until we have values for the parameters. */
1466 if (bi_const_p
1467 && ctx->manifestly_const_eval != mce_true
1468 && current_function_decl
1469 && DECL_DECLARED_CONSTEXPR_P (current_function_decl))
1471 *non_constant_p = true;
1472 return t;
1475 /* For __builtin_is_constant_evaluated, defer it if not
1476 ctx->manifestly_const_eval (as sometimes we try to constant evaluate
1477 without manifestly_const_eval even expressions or parts thereof which
1478 will later be manifestly const_eval evaluated), otherwise fold it to
1479 true. */
1480 if (fndecl_built_in_p (fun, CP_BUILT_IN_IS_CONSTANT_EVALUATED,
1481 BUILT_IN_FRONTEND))
1483 if (ctx->manifestly_const_eval == mce_unknown)
1485 *non_constant_p = true;
1486 return t;
1488 return constant_boolean_node (ctx->manifestly_const_eval == mce_true,
1489 boolean_type_node);
1492 if (fndecl_built_in_p (fun, CP_BUILT_IN_SOURCE_LOCATION, BUILT_IN_FRONTEND))
1494 temp_override<tree> ovr (current_function_decl);
1495 if (ctx->call && ctx->call->fundef)
1496 current_function_decl = ctx->call->fundef->decl;
1497 return fold_builtin_source_location (t);
1500 int strops = 0;
1501 int strret = 0;
1502 if (fndecl_built_in_p (fun, BUILT_IN_NORMAL))
1503 switch (DECL_FUNCTION_CODE (fun))
1505 case BUILT_IN_STRLEN:
1506 case BUILT_IN_STRNLEN:
1507 strops = 1;
1508 break;
1509 case BUILT_IN_MEMCHR:
1510 case BUILT_IN_STRCHR:
1511 case BUILT_IN_STRRCHR:
1512 strops = 1;
1513 strret = 1;
1514 break;
1515 case BUILT_IN_MEMCMP:
1516 case BUILT_IN_STRCMP:
1517 strops = 2;
1518 break;
1519 case BUILT_IN_STRSTR:
1520 strops = 2;
1521 strret = 1;
1522 break;
1523 case BUILT_IN_ASAN_POINTER_COMPARE:
1524 case BUILT_IN_ASAN_POINTER_SUBTRACT:
1525 /* These builtins shall be ignored during constant expression
1526 evaluation. */
1527 return void_node;
1528 case BUILT_IN_UNREACHABLE:
1529 case BUILT_IN_TRAP:
1530 if (!*non_constant_p && !ctx->quiet)
1532 /* Do not allow__builtin_unreachable in constexpr function.
1533 The __builtin_unreachable call with BUILTINS_LOCATION
1534 comes from cp_maybe_instrument_return. */
1535 if (EXPR_LOCATION (t) == BUILTINS_LOCATION)
1536 error ("%<constexpr%> call flows off the end of the function");
1537 else
1538 error ("%q+E is not a constant expression", t);
1540 *non_constant_p = true;
1541 return t;
1542 default:
1543 break;
1546 /* Be permissive for arguments to built-ins; __builtin_constant_p should
1547 return constant false for a non-constant argument. */
1548 constexpr_ctx new_ctx = *ctx;
1549 new_ctx.quiet = true;
1550 for (i = 0; i < nargs; ++i)
1552 tree arg = CALL_EXPR_ARG (t, i);
1553 tree oarg = arg;
1555 /* To handle string built-ins we need to pass ADDR_EXPR<STRING_CST> since
1556 expand_builtin doesn't know how to look in the values table. */
1557 bool strop = i < strops;
1558 if (strop)
1560 STRIP_NOPS (arg);
1561 if (TREE_CODE (arg) == ADDR_EXPR)
1562 arg = TREE_OPERAND (arg, 0);
1563 else
1564 strop = false;
1567 /* If builtin_valid_in_constant_expr_p is true,
1568 potential_constant_expression_1 has not recursed into the arguments
1569 of the builtin, verify it here. */
1570 if (!builtin_valid_in_constant_expr_p (fun)
1571 || potential_constant_expression (arg))
1573 bool dummy1 = false, dummy2 = false;
1574 arg = cxx_eval_constant_expression (&new_ctx, arg, vc_prvalue,
1575 &dummy1, &dummy2);
1578 if (bi_const_p)
1579 /* For __builtin_constant_p, fold all expressions with constant values
1580 even if they aren't C++ constant-expressions. */
1581 arg = cp_fold_rvalue (arg);
1582 else if (strop)
1584 if (TREE_CODE (arg) == CONSTRUCTOR)
1585 arg = braced_lists_to_strings (TREE_TYPE (arg), arg);
1586 if (TREE_CODE (arg) == STRING_CST)
1587 arg = build_address (arg);
1588 else
1589 arg = oarg;
1592 args[i] = arg;
1595 bool save_ffbcp = force_folding_builtin_constant_p;
1596 force_folding_builtin_constant_p |= ctx->manifestly_const_eval == mce_true;
1597 tree save_cur_fn = current_function_decl;
1598 /* Return name of ctx->call->fundef->decl for __builtin_FUNCTION (). */
1599 if (fndecl_built_in_p (fun, BUILT_IN_FUNCTION)
1600 && ctx->call
1601 && ctx->call->fundef)
1602 current_function_decl = ctx->call->fundef->decl;
1603 if (fndecl_built_in_p (fun,
1604 CP_BUILT_IN_IS_POINTER_INTERCONVERTIBLE_WITH_CLASS,
1605 BUILT_IN_FRONTEND))
1607 location_t loc = EXPR_LOCATION (t);
1608 if (nargs >= 1)
1609 VERIFY_CONSTANT (args[0]);
1610 new_call
1611 = fold_builtin_is_pointer_inverconvertible_with_class (loc, nargs,
1612 args);
1614 else if (fndecl_built_in_p (fun,
1615 CP_BUILT_IN_IS_CORRESPONDING_MEMBER,
1616 BUILT_IN_FRONTEND))
1618 location_t loc = EXPR_LOCATION (t);
1619 if (nargs >= 2)
1621 VERIFY_CONSTANT (args[0]);
1622 VERIFY_CONSTANT (args[1]);
1624 new_call = fold_builtin_is_corresponding_member (loc, nargs, args);
1626 else
1627 new_call = fold_builtin_call_array (EXPR_LOCATION (t), TREE_TYPE (t),
1628 CALL_EXPR_FN (t), nargs, args);
1629 current_function_decl = save_cur_fn;
1630 force_folding_builtin_constant_p = save_ffbcp;
1631 if (new_call == NULL)
1633 if (!*non_constant_p && !ctx->quiet)
1635 new_call = build_call_array_loc (EXPR_LOCATION (t), TREE_TYPE (t),
1636 CALL_EXPR_FN (t), nargs, args);
1637 error ("%q+E is not a constant expression", new_call);
1639 *non_constant_p = true;
1640 return t;
1643 if (!potential_constant_expression (new_call))
1645 if (!*non_constant_p && !ctx->quiet)
1646 error ("%q+E is not a constant expression", new_call);
1647 *non_constant_p = true;
1648 return t;
1651 if (strret)
1653 /* memchr returns a pointer into the first argument, but we replaced the
1654 argument above with a STRING_CST; put it back it now. */
1655 tree op = CALL_EXPR_ARG (t, strret-1);
1656 STRIP_NOPS (new_call);
1657 if (TREE_CODE (new_call) == POINTER_PLUS_EXPR)
1658 TREE_OPERAND (new_call, 0) = op;
1659 else if (TREE_CODE (new_call) == ADDR_EXPR)
1660 new_call = op;
1663 return cxx_eval_constant_expression (&new_ctx, new_call, lval,
1664 non_constant_p, overflow_p);
1667 /* TEMP is the constant value of a temporary object of type TYPE. Adjust
1668 the type of the value to match. */
1670 static tree
1671 adjust_temp_type (tree type, tree temp)
1673 if (same_type_p (TREE_TYPE (temp), type))
1674 return temp;
1675 /* Avoid wrapping an aggregate value in a NOP_EXPR. */
1676 if (TREE_CODE (temp) == CONSTRUCTOR)
1678 /* build_constructor wouldn't retain various CONSTRUCTOR flags. */
1679 tree t = copy_node (temp);
1680 TREE_TYPE (t) = type;
1681 return t;
1683 if (TREE_CODE (temp) == EMPTY_CLASS_EXPR)
1684 return build0 (EMPTY_CLASS_EXPR, type);
1685 gcc_assert (scalarish_type_p (type));
1686 /* Now we know we're dealing with a scalar, and a prvalue of non-class
1687 type is cv-unqualified. */
1688 return cp_fold_convert (cv_unqualified (type), temp);
1691 /* If T is a CONSTRUCTOR, return an unshared copy of T and any
1692 sub-CONSTRUCTORs. Otherwise return T.
1694 We use this whenever we initialize an object as a whole, whether it's a
1695 parameter, a local variable, or a subobject, so that subsequent
1696 modifications don't affect other places where it was used. */
1698 tree
1699 unshare_constructor (tree t MEM_STAT_DECL)
1701 if (!t || TREE_CODE (t) != CONSTRUCTOR)
1702 return t;
1703 auto_vec <tree*, 4> ptrs;
1704 ptrs.safe_push (&t);
1705 while (!ptrs.is_empty ())
1707 tree *p = ptrs.pop ();
1708 tree n = copy_node (*p PASS_MEM_STAT);
1709 CONSTRUCTOR_ELTS (n) = vec_safe_copy (CONSTRUCTOR_ELTS (*p) PASS_MEM_STAT);
1710 *p = n;
1711 vec<constructor_elt, va_gc> *v = CONSTRUCTOR_ELTS (n);
1712 constructor_elt *ce;
1713 for (HOST_WIDE_INT i = 0; vec_safe_iterate (v, i, &ce); ++i)
1714 if (ce->value && TREE_CODE (ce->value) == CONSTRUCTOR)
1715 ptrs.safe_push (&ce->value);
1717 return t;
1720 /* If T is a CONSTRUCTOR, ggc_free T and any sub-CONSTRUCTORs. */
1722 static void
1723 free_constructor (tree t)
1725 if (!t || TREE_CODE (t) != CONSTRUCTOR)
1726 return;
1727 releasing_vec ctors;
1728 vec_safe_push (ctors, t);
1729 while (!ctors->is_empty ())
1731 tree c = ctors->pop ();
1732 if (vec<constructor_elt, va_gc> *elts = CONSTRUCTOR_ELTS (c))
1734 constructor_elt *ce;
1735 for (HOST_WIDE_INT i = 0; vec_safe_iterate (elts, i, &ce); ++i)
1736 if (TREE_CODE (ce->value) == CONSTRUCTOR)
1737 vec_safe_push (ctors, ce->value);
1738 ggc_free (elts);
1740 ggc_free (c);
1744 /* Helper function of cxx_bind_parameters_in_call. Return non-NULL
1745 if *TP is address of a static variable (or part of it) currently being
1746 constructed or of a heap artificial variable. */
1748 static tree
1749 addr_of_non_const_var (tree *tp, int *walk_subtrees, void *data)
1751 if (TREE_CODE (*tp) == ADDR_EXPR)
1752 if (tree var = get_base_address (TREE_OPERAND (*tp, 0)))
1753 if (VAR_P (var) && TREE_STATIC (var))
1755 if (DECL_NAME (var) == heap_uninit_identifier
1756 || DECL_NAME (var) == heap_identifier
1757 || DECL_NAME (var) == heap_vec_uninit_identifier
1758 || DECL_NAME (var) == heap_vec_identifier)
1759 return var;
1761 constexpr_global_ctx *global = (constexpr_global_ctx *) data;
1762 if (global->get_value (var))
1763 return var;
1765 if (TYPE_P (*tp))
1766 *walk_subtrees = false;
1767 return NULL_TREE;
1770 /* Subroutine of cxx_eval_call_expression.
1771 We are processing a call expression (either CALL_EXPR or
1772 AGGR_INIT_EXPR) in the context of CTX. Evaluate
1773 all arguments and bind their values to correspondings
1774 parameters, making up the NEW_CALL context. */
1776 static tree
1777 cxx_bind_parameters_in_call (const constexpr_ctx *ctx, tree t, tree fun,
1778 bool *non_constant_p, bool *overflow_p,
1779 bool *non_constant_args)
1781 const int nargs = call_expr_nargs (t);
1782 tree parms = DECL_ARGUMENTS (fun);
1783 int i;
1784 /* We don't record ellipsis args below. */
1785 int nparms = list_length (parms);
1786 int nbinds = nargs < nparms ? nargs : nparms;
1787 tree binds = make_tree_vec (nbinds);
1788 for (i = 0; i < nargs; ++i)
1790 tree x, arg;
1791 tree type = parms ? TREE_TYPE (parms) : void_type_node;
1792 if (parms && DECL_BY_REFERENCE (parms))
1793 type = TREE_TYPE (type);
1794 x = get_nth_callarg (t, i);
1795 /* For member function, the first argument is a pointer to the implied
1796 object. For a constructor, it might still be a dummy object, in
1797 which case we get the real argument from ctx. */
1798 if (i == 0 && DECL_CONSTRUCTOR_P (fun)
1799 && is_dummy_object (x))
1801 x = ctx->object;
1802 x = build_address (x);
1804 if (TREE_ADDRESSABLE (type))
1805 /* Undo convert_for_arg_passing work here. */
1806 x = convert_from_reference (x);
1807 /* Normally we would strip a TARGET_EXPR in an initialization context
1808 such as this, but here we do the elision differently: we keep the
1809 TARGET_EXPR, and use its CONSTRUCTOR as the value of the parm. */
1810 arg = cxx_eval_constant_expression (ctx, x, vc_prvalue,
1811 non_constant_p, overflow_p);
1812 /* Don't VERIFY_CONSTANT here. */
1813 if (*non_constant_p && ctx->quiet)
1814 break;
1815 /* Just discard ellipsis args after checking their constantitude. */
1816 if (!parms)
1817 continue;
1819 if (!*non_constant_p)
1821 /* Make sure the binding has the same type as the parm. But
1822 only for constant args. */
1823 if (!TYPE_REF_P (type))
1824 arg = adjust_temp_type (type, arg);
1825 if (!TREE_CONSTANT (arg))
1826 *non_constant_args = true;
1827 else if (TYPE_HAS_NONTRIVIAL_DESTRUCTOR (type))
1828 /* The destructor needs to see any modifications the callee makes
1829 to the argument. */
1830 *non_constant_args = true;
1831 /* If arg is or contains address of a heap artificial variable or
1832 of a static variable being constructed, avoid caching the
1833 function call, as those variables might be modified by the
1834 function, or might be modified by the callers in between
1835 the cached function and just read by the function. */
1836 else if (!*non_constant_args
1837 && cp_walk_tree (&arg, addr_of_non_const_var, ctx->global,
1838 NULL))
1839 *non_constant_args = true;
1841 /* For virtual calls, adjust the this argument, so that it is
1842 the object on which the method is called, rather than
1843 one of its bases. */
1844 if (i == 0 && DECL_VIRTUAL_P (fun))
1846 tree addr = arg;
1847 STRIP_NOPS (addr);
1848 if (TREE_CODE (addr) == ADDR_EXPR)
1850 tree obj = TREE_OPERAND (addr, 0);
1851 while (TREE_CODE (obj) == COMPONENT_REF
1852 && DECL_FIELD_IS_BASE (TREE_OPERAND (obj, 1))
1853 && !same_type_ignoring_top_level_qualifiers_p
1854 (TREE_TYPE (obj), DECL_CONTEXT (fun)))
1855 obj = TREE_OPERAND (obj, 0);
1856 if (obj != TREE_OPERAND (addr, 0))
1857 arg = build_fold_addr_expr_with_type (obj,
1858 TREE_TYPE (arg));
1861 TREE_VEC_ELT (binds, i) = arg;
1863 parms = TREE_CHAIN (parms);
1866 return binds;
1869 /* Variables and functions to manage constexpr call expansion context.
1870 These do not need to be marked for PCH or GC. */
1872 /* FIXME remember and print actual constant arguments. */
1873 static vec<tree> call_stack;
1874 static int call_stack_tick;
1875 static int last_cx_error_tick;
1877 static int
1878 push_cx_call_context (tree call)
1880 ++call_stack_tick;
1881 if (!EXPR_HAS_LOCATION (call))
1882 SET_EXPR_LOCATION (call, input_location);
1883 call_stack.safe_push (call);
1884 int len = call_stack.length ();
1885 if (len > max_constexpr_depth)
1886 return false;
1887 return len;
1890 static void
1891 pop_cx_call_context (void)
1893 ++call_stack_tick;
1894 call_stack.pop ();
1897 vec<tree>
1898 cx_error_context (void)
1900 vec<tree> r = vNULL;
1901 if (call_stack_tick != last_cx_error_tick
1902 && !call_stack.is_empty ())
1903 r = call_stack;
1904 last_cx_error_tick = call_stack_tick;
1905 return r;
1908 /* E is an operand of a failed assertion, fold it either with or without
1909 constexpr context. */
1911 static tree
1912 fold_operand (tree e, const constexpr_ctx *ctx)
1914 if (ctx)
1916 bool new_non_constant_p = false, new_overflow_p = false;
1917 e = cxx_eval_constant_expression (ctx, e, vc_prvalue,
1918 &new_non_constant_p,
1919 &new_overflow_p);
1921 else
1922 e = fold_non_dependent_expr (e, tf_none, /*manifestly_const_eval=*/true);
1923 return e;
1926 /* If we have a condition in conjunctive normal form (CNF), find the first
1927 failing clause. In other words, given an expression like
1929 true && true && false && true && false
1931 return the first 'false'. EXPR is the expression. */
1933 static tree
1934 find_failing_clause_r (const constexpr_ctx *ctx, tree expr)
1936 if (TREE_CODE (expr) == TRUTH_ANDIF_EXPR)
1938 /* First check the left side... */
1939 tree e = find_failing_clause_r (ctx, TREE_OPERAND (expr, 0));
1940 if (e == NULL_TREE)
1941 /* ...if we didn't find a false clause, check the right side. */
1942 e = find_failing_clause_r (ctx, TREE_OPERAND (expr, 1));
1943 return e;
1945 tree e = contextual_conv_bool (expr, tf_none);
1946 e = fold_operand (e, ctx);
1947 if (integer_zerop (e))
1948 /* This is the failing clause. */
1949 return expr;
1950 return NULL_TREE;
1953 /* Wrapper for find_failing_clause_r. */
1955 tree
1956 find_failing_clause (const constexpr_ctx *ctx, tree expr)
1958 if (TREE_CODE (expr) == TRUTH_ANDIF_EXPR)
1959 if (tree e = find_failing_clause_r (ctx, expr))
1960 expr = e;
1961 return expr;
1964 /* Emit additional diagnostics for failing condition BAD.
1965 Used by finish_static_assert and IFN_ASSUME constexpr diagnostics.
1966 If SHOW_EXPR_P is true, print the condition (because it was
1967 instantiation-dependent). */
1969 void
1970 diagnose_failing_condition (tree bad, location_t cloc, bool show_expr_p,
1971 const constexpr_ctx *ctx /* = nullptr */)
1973 /* Nobody wants to see the artificial (bool) cast. */
1974 bad = tree_strip_nop_conversions (bad);
1975 if (TREE_CODE (bad) == CLEANUP_POINT_EXPR)
1976 bad = TREE_OPERAND (bad, 0);
1978 /* Actually explain the failure if this is a concept check or a
1979 requires-expression. */
1980 if (concept_check_p (bad) || TREE_CODE (bad) == REQUIRES_EXPR)
1981 diagnose_constraints (cloc, bad, NULL_TREE);
1982 else if (COMPARISON_CLASS_P (bad)
1983 && ARITHMETIC_TYPE_P (TREE_TYPE (TREE_OPERAND (bad, 0))))
1985 tree op0 = fold_operand (TREE_OPERAND (bad, 0), ctx);
1986 tree op1 = fold_operand (TREE_OPERAND (bad, 1), ctx);
1987 tree cond = build2 (TREE_CODE (bad), boolean_type_node, op0, op1);
1988 inform (cloc, "the comparison reduces to %qE", cond);
1990 else if (show_expr_p)
1991 inform (cloc, "%qE evaluates to false", bad);
1994 /* Process an assert/assume of ORIG_ARG. If it's not supposed to be evaluated,
1995 do it without changing the current evaluation state. If it evaluates to
1996 false, complain and return false; otherwise, return true. */
1998 static bool
1999 cxx_eval_assert (const constexpr_ctx *ctx, tree arg, const char *msg,
2000 location_t loc, bool evaluated,
2001 bool *non_constant_p, bool *overflow_p)
2003 if (*non_constant_p)
2004 return true;
2006 tree eval;
2007 if (!evaluated)
2009 if (!potential_rvalue_constant_expression (arg))
2010 return true;
2012 constexpr_ctx new_ctx = *ctx;
2013 new_ctx.quiet = true;
2014 bool new_non_constant_p = false, new_overflow_p = false;
2015 /* Avoid modification of existing values. */
2016 modifiable_tracker ms (new_ctx.global);
2017 eval = cxx_eval_constant_expression (&new_ctx, arg, vc_prvalue,
2018 &new_non_constant_p,
2019 &new_overflow_p);
2021 else
2022 eval = cxx_eval_constant_expression (ctx, arg, vc_prvalue,
2023 non_constant_p,
2024 overflow_p);
2025 if (!*non_constant_p && integer_zerop (eval))
2027 if (!ctx->quiet)
2029 /* See if we can find which clause was failing
2030 (for logical AND). */
2031 tree bad = find_failing_clause (ctx, arg);
2032 /* If not, or its location is unusable, fall back to the
2033 previous location. */
2034 location_t cloc = cp_expr_loc_or_loc (bad, loc);
2036 /* Report the error. */
2037 auto_diagnostic_group d;
2038 error_at (cloc, msg);
2039 diagnose_failing_condition (bad, cloc, true, ctx);
2040 return bad;
2042 *non_constant_p = true;
2043 return false;
2046 return true;
2049 /* Evaluate a call T to a GCC internal function when possible and return
2050 the evaluated result or, under the control of CTX, give an error, set
2051 NON_CONSTANT_P, and return the unevaluated call T otherwise. */
2053 static tree
2054 cxx_eval_internal_function (const constexpr_ctx *ctx, tree t,
2055 value_cat lval,
2056 bool *non_constant_p, bool *overflow_p)
2058 enum tree_code opcode = ERROR_MARK;
2060 switch (CALL_EXPR_IFN (t))
2062 case IFN_UBSAN_NULL:
2063 case IFN_UBSAN_BOUNDS:
2064 case IFN_UBSAN_VPTR:
2065 case IFN_FALLTHROUGH:
2066 return void_node;
2068 case IFN_ASSUME:
2069 if (!cxx_eval_assert (ctx, CALL_EXPR_ARG (t, 0),
2070 G_("failed %<assume%> attribute assumption"),
2071 EXPR_LOCATION (t), /*eval*/false,
2072 non_constant_p, overflow_p))
2073 return t;
2074 return void_node;
2076 case IFN_ADD_OVERFLOW:
2077 opcode = PLUS_EXPR;
2078 break;
2079 case IFN_SUB_OVERFLOW:
2080 opcode = MINUS_EXPR;
2081 break;
2082 case IFN_MUL_OVERFLOW:
2083 opcode = MULT_EXPR;
2084 break;
2086 case IFN_LAUNDER:
2087 return cxx_eval_constant_expression (ctx, CALL_EXPR_ARG (t, 0),
2088 vc_prvalue, non_constant_p,
2089 overflow_p);
2091 case IFN_VEC_CONVERT:
2093 tree arg = cxx_eval_constant_expression (ctx, CALL_EXPR_ARG (t, 0),
2094 vc_prvalue, non_constant_p,
2095 overflow_p);
2096 if (TREE_CODE (arg) == VECTOR_CST)
2097 if (tree r = fold_const_call (CFN_VEC_CONVERT, TREE_TYPE (t), arg))
2098 return r;
2100 /* FALLTHRU */
2102 default:
2103 if (!ctx->quiet)
2104 error_at (cp_expr_loc_or_input_loc (t),
2105 "call to internal function %qE", t);
2106 *non_constant_p = true;
2107 return t;
2110 /* Evaluate constant arguments using OPCODE and return a complex
2111 number containing the result and the overflow bit. */
2112 tree arg0 = cxx_eval_constant_expression (ctx, CALL_EXPR_ARG (t, 0), lval,
2113 non_constant_p, overflow_p);
2114 tree arg1 = cxx_eval_constant_expression (ctx, CALL_EXPR_ARG (t, 1), lval,
2115 non_constant_p, overflow_p);
2117 if (TREE_CODE (arg0) == INTEGER_CST && TREE_CODE (arg1) == INTEGER_CST)
2119 location_t loc = cp_expr_loc_or_input_loc (t);
2120 tree type = TREE_TYPE (TREE_TYPE (t));
2121 tree result = fold_binary_loc (loc, opcode, type,
2122 fold_convert_loc (loc, type, arg0),
2123 fold_convert_loc (loc, type, arg1));
2124 tree ovf
2125 = build_int_cst (type, arith_overflowed_p (opcode, type, arg0, arg1));
2126 /* Reset TREE_OVERFLOW to avoid warnings for the overflow. */
2127 if (TREE_OVERFLOW (result))
2128 TREE_OVERFLOW (result) = 0;
2130 return build_complex (TREE_TYPE (t), result, ovf);
2133 *non_constant_p = true;
2134 return t;
2137 /* Clean CONSTRUCTOR_NO_CLEARING from CTOR and its sub-aggregates. */
2139 static void
2140 clear_no_implicit_zero (tree ctor)
2142 if (CONSTRUCTOR_NO_CLEARING (ctor))
2144 CONSTRUCTOR_NO_CLEARING (ctor) = false;
2145 for (auto &e: CONSTRUCTOR_ELTS (ctor))
2146 if (TREE_CODE (e.value) == CONSTRUCTOR)
2147 clear_no_implicit_zero (e.value);
2151 /* Complain about a const object OBJ being modified in a constant expression.
2152 EXPR is the MODIFY_EXPR expression performing the modification. */
2154 static void
2155 modifying_const_object_error (tree expr, tree obj)
2157 location_t loc = cp_expr_loc_or_input_loc (expr);
2158 auto_diagnostic_group d;
2159 error_at (loc, "modifying a const object %qE is not allowed in "
2160 "a constant expression", TREE_OPERAND (expr, 0));
2161 inform (location_of (obj), "originally declared %<const%> here");
2164 /* Return true if FNDECL is a replaceable global allocation function that
2165 should be useable during constant expression evaluation. */
2167 static inline bool
2168 cxx_replaceable_global_alloc_fn (tree fndecl)
2170 return (cxx_dialect >= cxx20
2171 && IDENTIFIER_NEWDEL_OP_P (DECL_NAME (fndecl))
2172 && CP_DECL_CONTEXT (fndecl) == global_namespace
2173 && (DECL_IS_REPLACEABLE_OPERATOR_NEW_P (fndecl)
2174 || DECL_IS_OPERATOR_DELETE_P (fndecl)));
2177 /* Return true if FNDECL is a placement new function that should be
2178 useable during constant expression evaluation of std::construct_at. */
2180 static inline bool
2181 cxx_placement_new_fn (tree fndecl)
2183 if (cxx_dialect >= cxx20
2184 && IDENTIFIER_NEW_OP_P (DECL_NAME (fndecl))
2185 && CP_DECL_CONTEXT (fndecl) == global_namespace
2186 && !DECL_IS_REPLACEABLE_OPERATOR_NEW_P (fndecl)
2187 && TREE_CODE (TREE_TYPE (fndecl)) == FUNCTION_TYPE)
2189 tree first_arg = TREE_CHAIN (TYPE_ARG_TYPES (TREE_TYPE (fndecl)));
2190 if (TREE_VALUE (first_arg) == ptr_type_node
2191 && TREE_CHAIN (first_arg) == void_list_node)
2192 return true;
2194 return false;
2197 /* Return true if FNDECL is std::construct_at. */
2199 static inline bool
2200 is_std_construct_at (tree fndecl)
2202 if (!decl_in_std_namespace_p (fndecl))
2203 return false;
2205 tree name = DECL_NAME (fndecl);
2206 return name && id_equal (name, "construct_at");
2209 /* Overload for the above taking constexpr_call*. */
2211 static inline bool
2212 is_std_construct_at (const constexpr_call *call)
2214 return (call
2215 && call->fundef
2216 && is_std_construct_at (call->fundef->decl));
2219 /* True if CTX is an instance of std::allocator. */
2221 bool
2222 is_std_allocator (tree ctx)
2224 if (ctx == NULL_TREE || !CLASS_TYPE_P (ctx) || !TYPE_MAIN_DECL (ctx))
2225 return false;
2227 tree decl = TYPE_MAIN_DECL (ctx);
2228 tree name = DECL_NAME (decl);
2229 if (name == NULL_TREE || !id_equal (name, "allocator"))
2230 return false;
2232 return decl_in_std_namespace_p (decl);
2235 /* Return true if FNDECL is std::allocator<T>::{,de}allocate. */
2237 static inline bool
2238 is_std_allocator_allocate (tree fndecl)
2240 tree name = DECL_NAME (fndecl);
2241 if (name == NULL_TREE
2242 || !(id_equal (name, "allocate") || id_equal (name, "deallocate")))
2243 return false;
2245 return is_std_allocator (DECL_CONTEXT (fndecl));
2248 /* Overload for the above taking constexpr_call*. */
2250 static inline bool
2251 is_std_allocator_allocate (const constexpr_call *call)
2253 return (call
2254 && call->fundef
2255 && is_std_allocator_allocate (call->fundef->decl));
2258 /* Return true if FNDECL is __dynamic_cast. */
2260 static inline bool
2261 cxx_dynamic_cast_fn_p (tree fndecl)
2263 return (cxx_dialect >= cxx20
2264 && id_equal (DECL_NAME (fndecl), "__dynamic_cast")
2265 && CP_DECL_CONTEXT (fndecl) == abi_node);
2268 /* Often, we have an expression in the form of address + offset, e.g.
2269 "&_ZTV1A + 16". Extract the object from it, i.e. "_ZTV1A". */
2271 static tree
2272 extract_obj_from_addr_offset (tree expr)
2274 if (TREE_CODE (expr) == POINTER_PLUS_EXPR)
2275 expr = TREE_OPERAND (expr, 0);
2276 STRIP_NOPS (expr);
2277 if (TREE_CODE (expr) == ADDR_EXPR)
2278 expr = TREE_OPERAND (expr, 0);
2279 return expr;
2282 /* Given a PATH like
2284 g.D.2181.D.2154.D.2102.D.2093
2286 find a component with type TYPE. Return NULL_TREE if not found, and
2287 error_mark_node if the component is not accessible. If STOP is non-null,
2288 this function will return NULL_TREE if STOP is found before TYPE. */
2290 static tree
2291 get_component_with_type (tree path, tree type, tree stop)
2293 while (true)
2295 if (same_type_ignoring_top_level_qualifiers_p (TREE_TYPE (path), type))
2296 /* Found it. */
2297 return path;
2298 else if (stop
2299 && (same_type_ignoring_top_level_qualifiers_p (TREE_TYPE (path),
2300 stop)))
2301 return NULL_TREE;
2302 else if (TREE_CODE (path) == COMPONENT_REF
2303 && DECL_FIELD_IS_BASE (TREE_OPERAND (path, 1)))
2305 /* We need to check that the component we're accessing is in fact
2306 accessible. */
2307 if (TREE_PRIVATE (TREE_OPERAND (path, 1))
2308 || TREE_PROTECTED (TREE_OPERAND (path, 1)))
2309 return error_mark_node;
2310 path = TREE_OPERAND (path, 0);
2312 else
2313 return NULL_TREE;
2317 /* Evaluate a call to __dynamic_cast (permitted by P1327R1).
2319 The declaration of __dynamic_cast is:
2321 void* __dynamic_cast (const void* __src_ptr,
2322 const __class_type_info* __src_type,
2323 const __class_type_info* __dst_type,
2324 ptrdiff_t __src2dst);
2326 where src2dst has the following possible values
2328 >-1: src_type is a unique public non-virtual base of dst_type
2329 dst_ptr + src2dst == src_ptr
2330 -1: unspecified relationship
2331 -2: src_type is not a public base of dst_type
2332 -3: src_type is a multiple public non-virtual base of dst_type
2334 Since literal types can't have virtual bases, we only expect hint >=0,
2335 -2, or -3. */
2337 static tree
2338 cxx_eval_dynamic_cast_fn (const constexpr_ctx *ctx, tree call,
2339 bool *non_constant_p, bool *overflow_p)
2341 /* T will be something like
2342 __dynamic_cast ((B*) b, &_ZTI1B, &_ZTI1D, 8)
2343 dismantle it. */
2344 gcc_assert (call_expr_nargs (call) == 4);
2345 tsubst_flags_t complain = ctx->quiet ? tf_none : tf_warning_or_error;
2346 tree obj = CALL_EXPR_ARG (call, 0);
2347 tree type = CALL_EXPR_ARG (call, 2);
2348 HOST_WIDE_INT hint = int_cst_value (CALL_EXPR_ARG (call, 3));
2349 location_t loc = cp_expr_loc_or_input_loc (call);
2351 /* Get the target type of the dynamic_cast. */
2352 gcc_assert (TREE_CODE (type) == ADDR_EXPR);
2353 type = TREE_OPERAND (type, 0);
2354 type = TREE_TYPE (DECL_NAME (type));
2356 /* TYPE can only be either T* or T&. We can't know which of these it
2357 is by looking at TYPE, but OBJ will be "(T*) x" in the first case,
2358 and something like "(T*)(T&)(T*) x" in the second case. */
2359 bool reference_p = false;
2360 while (CONVERT_EXPR_P (obj) || TREE_CODE (obj) == SAVE_EXPR)
2362 reference_p |= TYPE_REF_P (TREE_TYPE (obj));
2363 obj = TREE_OPERAND (obj, 0);
2366 /* Evaluate the object so that we know its dynamic type. */
2367 obj = cxx_eval_constant_expression (ctx, obj, vc_prvalue, non_constant_p,
2368 overflow_p);
2369 if (*non_constant_p)
2370 return call;
2372 /* We expect OBJ to be in form of &d.D.2102 when HINT == 0,
2373 but when HINT is > 0, it can also be something like
2374 &d.D.2102 + 18446744073709551608, which includes the BINFO_OFFSET. */
2375 obj = extract_obj_from_addr_offset (obj);
2376 const tree objtype = TREE_TYPE (obj);
2377 /* If OBJ doesn't refer to a base field, we're done. */
2378 if (tree t = (TREE_CODE (obj) == COMPONENT_REF
2379 ? TREE_OPERAND (obj, 1) : obj))
2380 if (TREE_CODE (t) != FIELD_DECL || !DECL_FIELD_IS_BASE (t))
2382 if (reference_p)
2384 if (!ctx->quiet)
2386 error_at (loc, "reference %<dynamic_cast%> failed");
2387 inform (loc, "dynamic type %qT of its operand does "
2388 "not have a base class of type %qT",
2389 objtype, type);
2391 *non_constant_p = true;
2393 return integer_zero_node;
2396 /* [class.cdtor] When a dynamic_cast is used in a constructor ...
2397 or in a destructor ... if the operand of the dynamic_cast refers
2398 to the object under construction or destruction, this object is
2399 considered to be a most derived object that has the type of the
2400 constructor or destructor's class. */
2401 tree vtable = build_vfield_ref (obj, objtype);
2402 vtable = cxx_eval_constant_expression (ctx, vtable, vc_prvalue,
2403 non_constant_p, overflow_p);
2404 if (*non_constant_p)
2405 return call;
2406 /* With -fsanitize=vptr, we initialize all vtable pointers to null,
2407 so it's possible that we got a null pointer now. */
2408 if (integer_zerop (vtable))
2410 if (!ctx->quiet)
2411 error_at (loc, "virtual table pointer is used uninitialized");
2412 *non_constant_p = true;
2413 return integer_zero_node;
2415 /* VTABLE will be &_ZTV1A + 16 or similar, get _ZTV1A. */
2416 vtable = extract_obj_from_addr_offset (vtable);
2417 const tree mdtype = DECL_CONTEXT (vtable);
2419 /* Given dynamic_cast<T>(v),
2421 [expr.dynamic.cast] If C is the class type to which T points or refers,
2422 the runtime check logically executes as follows:
2424 If, in the most derived object pointed (referred) to by v, v points
2425 (refers) to a public base class subobject of a C object, and if only
2426 one object of type C is derived from the subobject pointed (referred)
2427 to by v the result points (refers) to that C object.
2429 In this case, HINT >= 0 or -3. */
2430 if (hint >= 0 || hint == -3)
2432 /* Look for a component with type TYPE. */
2433 tree t = get_component_with_type (obj, type, mdtype);
2434 /* If not accessible, give an error. */
2435 if (t == error_mark_node)
2437 if (reference_p)
2439 if (!ctx->quiet)
2441 error_at (loc, "reference %<dynamic_cast%> failed");
2442 inform (loc, "static type %qT of its operand is a "
2443 "non-public base class of dynamic type %qT",
2444 objtype, type);
2447 *non_constant_p = true;
2449 return integer_zero_node;
2451 else if (t)
2452 /* The result points to the TYPE object. */
2453 return cp_build_addr_expr (t, complain);
2454 /* Else, TYPE was not found, because the HINT turned out to be wrong.
2455 Fall through to the normal processing. */
2458 /* Otherwise, if v points (refers) to a public base class subobject of the
2459 most derived object, and the type of the most derived object has a base
2460 class, of type C, that is unambiguous and public, the result points
2461 (refers) to the C subobject of the most derived object.
2463 But it can also be an invalid case. */
2465 /* Get the most derived object. */
2466 obj = get_component_with_type (obj, mdtype, NULL_TREE);
2467 if (obj == error_mark_node)
2469 if (reference_p)
2471 if (!ctx->quiet)
2473 error_at (loc, "reference %<dynamic_cast%> failed");
2474 inform (loc, "static type %qT of its operand is a non-public"
2475 " base class of dynamic type %qT", objtype, mdtype);
2477 *non_constant_p = true;
2479 return integer_zero_node;
2481 else
2482 gcc_assert (obj);
2484 /* Check that the type of the most derived object has a base class
2485 of type TYPE that is unambiguous and public. */
2486 base_kind b_kind;
2487 tree binfo = lookup_base (mdtype, type, ba_check, &b_kind, tf_none);
2488 if (!binfo || binfo == error_mark_node)
2490 if (reference_p)
2492 if (!ctx->quiet)
2494 error_at (loc, "reference %<dynamic_cast%> failed");
2495 if (b_kind == bk_ambig)
2496 inform (loc, "%qT is an ambiguous base class of dynamic "
2497 "type %qT of its operand", type, mdtype);
2498 else
2499 inform (loc, "dynamic type %qT of its operand does not "
2500 "have an unambiguous public base class %qT",
2501 mdtype, type);
2503 *non_constant_p = true;
2505 return integer_zero_node;
2507 /* If so, return the TYPE subobject of the most derived object. */
2508 obj = convert_to_base_statically (obj, binfo);
2509 return cp_build_addr_expr (obj, complain);
2512 /* Data structure used by replace_decl and replace_decl_r. */
2514 struct replace_decl_data
2516 /* The _DECL we want to replace. */
2517 tree decl;
2518 /* The replacement for DECL. */
2519 tree replacement;
2520 /* Trees we've visited. */
2521 hash_set<tree> *pset;
2522 /* Whether we've performed any replacements. */
2523 bool changed;
2526 /* Helper function for replace_decl, called through cp_walk_tree. */
2528 static tree
2529 replace_decl_r (tree *tp, int *walk_subtrees, void *data)
2531 replace_decl_data *d = (replace_decl_data *) data;
2533 if (*tp == d->decl)
2535 *tp = unshare_expr (d->replacement);
2536 d->changed = true;
2537 *walk_subtrees = 0;
2539 else if (TYPE_P (*tp)
2540 || d->pset->add (*tp))
2541 *walk_subtrees = 0;
2543 return NULL_TREE;
2546 /* Replace every occurrence of DECL with (an unshared copy of)
2547 REPLACEMENT within the expression *TP. Returns true iff a
2548 replacement was performed. */
2550 bool
2551 replace_decl (tree *tp, tree decl, tree replacement)
2553 gcc_checking_assert (same_type_ignoring_top_level_qualifiers_p
2554 (TREE_TYPE (decl), TREE_TYPE (replacement)));
2555 hash_set<tree> pset;
2556 replace_decl_data data = { decl, replacement, &pset, false };
2557 cp_walk_tree (tp, replace_decl_r, &data, NULL);
2558 return data.changed;
2561 /* Evaluate the call T to virtual function thunk THUNK_FNDECL. */
2563 static tree
2564 cxx_eval_thunk_call (const constexpr_ctx *ctx, tree t, tree thunk_fndecl,
2565 value_cat lval,
2566 bool *non_constant_p, bool *overflow_p)
2568 tree function = THUNK_TARGET (thunk_fndecl);
2570 if (THUNK_VIRTUAL_OFFSET (thunk_fndecl))
2572 if (!ctx->quiet)
2574 if (!DECL_DECLARED_CONSTEXPR_P (function))
2576 error ("call to non-%<constexpr%> function %qD", function);
2577 explain_invalid_constexpr_fn (function);
2579 else
2580 /* virtual_offset is only set for virtual bases, which make the
2581 class non-literal, so we don't need to handle it here. */
2582 error ("calling constexpr member function %qD through virtual "
2583 "base subobject", function);
2585 *non_constant_p = true;
2586 return t;
2589 tree new_call = copy_node (t);
2590 CALL_EXPR_FN (new_call) = function;
2591 TREE_TYPE (new_call) = TREE_TYPE (TREE_TYPE (function));
2593 tree offset = size_int (THUNK_FIXED_OFFSET (thunk_fndecl));
2595 if (DECL_THIS_THUNK_P (thunk_fndecl))
2597 /* 'this'-adjusting thunk. */
2598 tree this_arg = CALL_EXPR_ARG (t, 0);
2599 this_arg = build2 (POINTER_PLUS_EXPR, TREE_TYPE (this_arg),
2600 this_arg, offset);
2601 CALL_EXPR_ARG (new_call, 0) = this_arg;
2603 else
2604 /* Return-adjusting thunk. */
2605 new_call = build2 (POINTER_PLUS_EXPR, TREE_TYPE (new_call),
2606 new_call, offset);
2608 return cxx_eval_constant_expression (ctx, new_call, lval,
2609 non_constant_p, overflow_p);
2612 /* If OBJECT is of const class type, evaluate it to a CONSTRUCTOR and set
2613 its TREE_READONLY flag according to READONLY_P. Used for constexpr
2614 'tors to detect modifying const objects in a constexpr context. */
2616 static void
2617 cxx_set_object_constness (const constexpr_ctx *ctx, tree object,
2618 bool readonly_p, bool *non_constant_p,
2619 bool *overflow_p)
2621 if (CLASS_TYPE_P (TREE_TYPE (object))
2622 && CP_TYPE_CONST_P (TREE_TYPE (object)))
2624 /* Subobjects might not be stored in ctx->global->values but we
2625 can get its CONSTRUCTOR by evaluating *this. */
2626 tree e = cxx_eval_constant_expression (ctx, object, vc_prvalue,
2627 non_constant_p, overflow_p);
2628 if (TREE_CODE (e) == CONSTRUCTOR && !*non_constant_p)
2629 TREE_READONLY (e) = readonly_p;
2633 /* Subroutine of cxx_eval_constant_expression.
2634 Evaluate the call expression tree T in the context of OLD_CALL expression
2635 evaluation. */
2637 static tree
2638 cxx_eval_call_expression (const constexpr_ctx *ctx, tree t,
2639 value_cat lval,
2640 bool *non_constant_p, bool *overflow_p)
2642 /* Handle concept checks separately. */
2643 if (concept_check_p (t))
2644 return evaluate_concept_check (t);
2646 location_t loc = cp_expr_loc_or_input_loc (t);
2647 tree fun = get_function_named_in_call (t);
2648 constexpr_call new_call
2649 = { NULL, NULL, NULL, 0, ctx->manifestly_const_eval };
2650 int depth_ok;
2652 if (fun == NULL_TREE)
2653 return cxx_eval_internal_function (ctx, t, lval,
2654 non_constant_p, overflow_p);
2656 if (TREE_CODE (fun) != FUNCTION_DECL)
2658 /* Might be a constexpr function pointer. */
2659 fun = cxx_eval_constant_expression (ctx, fun, vc_prvalue,
2660 non_constant_p, overflow_p);
2661 STRIP_NOPS (fun);
2662 if (TREE_CODE (fun) == ADDR_EXPR)
2663 fun = TREE_OPERAND (fun, 0);
2664 /* For TARGET_VTABLE_USES_DESCRIPTORS targets, there is no
2665 indirection, the called expression is a pointer into the
2666 virtual table which should contain FDESC_EXPR. Extract the
2667 FUNCTION_DECL from there. */
2668 else if (TARGET_VTABLE_USES_DESCRIPTORS
2669 && TREE_CODE (fun) == POINTER_PLUS_EXPR
2670 && TREE_CODE (TREE_OPERAND (fun, 0)) == ADDR_EXPR
2671 && TREE_CODE (TREE_OPERAND (fun, 1)) == INTEGER_CST)
2673 tree d = TREE_OPERAND (TREE_OPERAND (fun, 0), 0);
2674 if (VAR_P (d)
2675 && DECL_VTABLE_OR_VTT_P (d)
2676 && TREE_CODE (TREE_TYPE (d)) == ARRAY_TYPE
2677 && TREE_TYPE (TREE_TYPE (d)) == vtable_entry_type
2678 && DECL_INITIAL (d)
2679 && TREE_CODE (DECL_INITIAL (d)) == CONSTRUCTOR)
2681 tree i = int_const_binop (TRUNC_DIV_EXPR, TREE_OPERAND (fun, 1),
2682 TYPE_SIZE_UNIT (vtable_entry_type));
2683 HOST_WIDE_INT idx = find_array_ctor_elt (DECL_INITIAL (d), i);
2684 if (idx >= 0)
2686 tree fdesc
2687 = (*CONSTRUCTOR_ELTS (DECL_INITIAL (d)))[idx].value;
2688 if (TREE_CODE (fdesc) == FDESC_EXPR
2689 && integer_zerop (TREE_OPERAND (fdesc, 1)))
2690 fun = TREE_OPERAND (fdesc, 0);
2695 if (TREE_CODE (fun) != FUNCTION_DECL)
2697 if (!ctx->quiet && !*non_constant_p)
2698 error_at (loc, "expression %qE does not designate a %<constexpr%> "
2699 "function", fun);
2700 *non_constant_p = true;
2701 return t;
2703 if (DECL_CLONED_FUNCTION_P (fun) && !DECL_DELETING_DESTRUCTOR_P (fun))
2704 fun = DECL_CLONED_FUNCTION (fun);
2706 if (is_ubsan_builtin_p (fun))
2707 return void_node;
2709 if (fndecl_built_in_p (fun))
2710 return cxx_eval_builtin_function_call (ctx, t, fun,
2711 lval, non_constant_p, overflow_p);
2712 if (DECL_THUNK_P (fun))
2713 return cxx_eval_thunk_call (ctx, t, fun, lval, non_constant_p, overflow_p);
2714 if (!maybe_constexpr_fn (fun))
2716 if (TREE_CODE (t) == CALL_EXPR
2717 && cxx_replaceable_global_alloc_fn (fun)
2718 && (CALL_FROM_NEW_OR_DELETE_P (t)
2719 || is_std_allocator_allocate (ctx->call)))
2721 const int nargs = call_expr_nargs (t);
2722 tree arg0 = NULL_TREE;
2723 for (int i = 0; i < nargs; ++i)
2725 tree arg = CALL_EXPR_ARG (t, i);
2726 arg = cxx_eval_constant_expression (ctx, arg, vc_prvalue,
2727 non_constant_p, overflow_p);
2728 VERIFY_CONSTANT (arg);
2729 if (i == 0)
2730 arg0 = arg;
2732 gcc_assert (arg0);
2733 if (IDENTIFIER_NEW_OP_P (DECL_NAME (fun)))
2735 tree type = build_array_type_nelts (char_type_node,
2736 tree_to_uhwi (arg0));
2737 tree var = build_decl (loc, VAR_DECL,
2738 (IDENTIFIER_OVL_OP_FLAGS (DECL_NAME (fun))
2739 & OVL_OP_FLAG_VEC)
2740 ? heap_vec_uninit_identifier
2741 : heap_uninit_identifier,
2742 type);
2743 DECL_ARTIFICIAL (var) = 1;
2744 TREE_STATIC (var) = 1;
2745 // Temporarily register the artificial var in varpool,
2746 // so that comparisons of its address against NULL are folded
2747 // through nonzero_address even with
2748 // -fno-delete-null-pointer-checks or that comparison of
2749 // addresses of different heap artificial vars is folded too.
2750 // See PR98988 and PR99031.
2751 varpool_node::finalize_decl (var);
2752 ctx->global->heap_vars.safe_push (var);
2753 ctx->global->put_value (var, NULL_TREE);
2754 return fold_convert (ptr_type_node, build_address (var));
2756 else
2758 STRIP_NOPS (arg0);
2759 if (TREE_CODE (arg0) == ADDR_EXPR
2760 && VAR_P (TREE_OPERAND (arg0, 0)))
2762 tree var = TREE_OPERAND (arg0, 0);
2763 if (DECL_NAME (var) == heap_uninit_identifier
2764 || DECL_NAME (var) == heap_identifier)
2766 if (IDENTIFIER_OVL_OP_FLAGS (DECL_NAME (fun))
2767 & OVL_OP_FLAG_VEC)
2769 if (!ctx->quiet)
2771 error_at (loc, "array deallocation of object "
2772 "allocated with non-array "
2773 "allocation");
2774 inform (DECL_SOURCE_LOCATION (var),
2775 "allocation performed here");
2777 *non_constant_p = true;
2778 return t;
2780 DECL_NAME (var) = heap_deleted_identifier;
2781 ctx->global->remove_value (var);
2782 ctx->global->heap_dealloc_count++;
2783 return void_node;
2785 else if (DECL_NAME (var) == heap_vec_uninit_identifier
2786 || DECL_NAME (var) == heap_vec_identifier)
2788 if ((IDENTIFIER_OVL_OP_FLAGS (DECL_NAME (fun))
2789 & OVL_OP_FLAG_VEC) == 0)
2791 if (!ctx->quiet)
2793 error_at (loc, "non-array deallocation of "
2794 "object allocated with array "
2795 "allocation");
2796 inform (DECL_SOURCE_LOCATION (var),
2797 "allocation performed here");
2799 *non_constant_p = true;
2800 return t;
2802 DECL_NAME (var) = heap_deleted_identifier;
2803 ctx->global->remove_value (var);
2804 ctx->global->heap_dealloc_count++;
2805 return void_node;
2807 else if (DECL_NAME (var) == heap_deleted_identifier)
2809 if (!ctx->quiet)
2810 error_at (loc, "deallocation of already deallocated "
2811 "storage");
2812 *non_constant_p = true;
2813 return t;
2816 if (!ctx->quiet)
2817 error_at (loc, "deallocation of storage that was "
2818 "not previously allocated");
2819 *non_constant_p = true;
2820 return t;
2823 /* Allow placement new in std::construct_at, just return the second
2824 argument. */
2825 if (TREE_CODE (t) == CALL_EXPR
2826 && cxx_placement_new_fn (fun)
2827 && is_std_construct_at (ctx->call))
2829 const int nargs = call_expr_nargs (t);
2830 tree arg1 = NULL_TREE;
2831 for (int i = 0; i < nargs; ++i)
2833 tree arg = CALL_EXPR_ARG (t, i);
2834 arg = cxx_eval_constant_expression (ctx, arg, vc_prvalue,
2835 non_constant_p, overflow_p);
2836 if (i == 1)
2837 arg1 = arg;
2838 else
2839 VERIFY_CONSTANT (arg);
2841 gcc_assert (arg1);
2842 return arg1;
2844 else if (cxx_dynamic_cast_fn_p (fun))
2845 return cxx_eval_dynamic_cast_fn (ctx, t, non_constant_p, overflow_p);
2847 if (!ctx->quiet)
2849 if (!lambda_static_thunk_p (fun))
2850 error_at (loc, "call to non-%<constexpr%> function %qD", fun);
2851 explain_invalid_constexpr_fn (fun);
2853 *non_constant_p = true;
2854 return t;
2857 constexpr_ctx new_ctx = *ctx;
2858 if (DECL_CONSTRUCTOR_P (fun) && !ctx->object
2859 && TREE_CODE (t) == AGGR_INIT_EXPR)
2861 /* We want to have an initialization target for an AGGR_INIT_EXPR.
2862 If we don't already have one in CTX, use the AGGR_INIT_EXPR_SLOT. */
2863 new_ctx.object = AGGR_INIT_EXPR_SLOT (t);
2864 tree ctor = new_ctx.ctor = build_constructor (DECL_CONTEXT (fun), NULL);
2865 CONSTRUCTOR_NO_CLEARING (ctor) = true;
2866 ctx->global->put_value (new_ctx.object, ctor);
2867 ctx = &new_ctx;
2870 /* We used to shortcut trivial constructor/op= here, but nowadays
2871 we can only get a trivial function here with -fno-elide-constructors. */
2872 gcc_checking_assert (!trivial_fn_p (fun)
2873 || !flag_elide_constructors
2874 /* We don't elide constructors when processing
2875 a noexcept-expression. */
2876 || cp_noexcept_operand);
2878 bool non_constant_args = false;
2879 new_call.bindings
2880 = cxx_bind_parameters_in_call (ctx, t, fun, non_constant_p,
2881 overflow_p, &non_constant_args);
2883 /* We build up the bindings list before we know whether we already have this
2884 call cached. If we don't end up saving these bindings, ggc_free them when
2885 this function exits. */
2886 class free_bindings
2888 tree *bindings;
2889 public:
2890 free_bindings (tree &b): bindings (&b) { }
2891 ~free_bindings () { if (bindings) ggc_free (*bindings); }
2892 void preserve () { bindings = NULL; }
2893 } fb (new_call.bindings);
2895 if (*non_constant_p)
2896 return t;
2898 /* We can't defer instantiating the function any longer. */
2899 if (!DECL_INITIAL (fun)
2900 && DECL_TEMPLOID_INSTANTIATION (fun)
2901 && !uid_sensitive_constexpr_evaluation_p ())
2903 location_t save_loc = input_location;
2904 input_location = loc;
2905 ++function_depth;
2906 if (ctx->manifestly_const_eval == mce_true)
2907 FNDECL_MANIFESTLY_CONST_EVALUATED (fun) = true;
2908 instantiate_decl (fun, /*defer_ok*/false, /*expl_inst*/false);
2909 --function_depth;
2910 input_location = save_loc;
2913 /* If in direct recursive call, optimize definition search. */
2914 if (ctx && ctx->call && ctx->call->fundef && ctx->call->fundef->decl == fun)
2915 new_call.fundef = ctx->call->fundef;
2916 else
2918 new_call.fundef = retrieve_constexpr_fundef (fun);
2919 if (new_call.fundef == NULL || new_call.fundef->body == NULL
2920 || new_call.fundef->result == error_mark_node
2921 || fun == current_function_decl)
2923 if (!ctx->quiet)
2925 /* We need to check for current_function_decl here in case we're
2926 being called during cp_fold_function, because at that point
2927 DECL_INITIAL is set properly and we have a fundef but we
2928 haven't lowered invisirefs yet (c++/70344). */
2929 if (DECL_INITIAL (fun) == error_mark_node
2930 || fun == current_function_decl)
2931 error_at (loc, "%qD called in a constant expression before its "
2932 "definition is complete", fun);
2933 else if (DECL_INITIAL (fun))
2935 /* The definition of fun was somehow unsuitable. But pretend
2936 that lambda static thunks don't exist. */
2937 if (!lambda_static_thunk_p (fun))
2938 error_at (loc, "%qD called in a constant expression", fun);
2939 explain_invalid_constexpr_fn (fun);
2941 else
2942 error_at (loc, "%qD used before its definition", fun);
2944 *non_constant_p = true;
2945 return t;
2949 depth_ok = push_cx_call_context (t);
2951 /* Remember the object we are constructing or destructing. */
2952 tree new_obj = NULL_TREE;
2953 if (DECL_CONSTRUCTOR_P (fun) || DECL_DESTRUCTOR_P (fun))
2955 /* In a cdtor, it should be the first `this' argument.
2956 At this point it has already been evaluated in the call
2957 to cxx_bind_parameters_in_call. */
2958 new_obj = TREE_VEC_ELT (new_call.bindings, 0);
2959 new_obj = cxx_fold_indirect_ref (ctx, loc, DECL_CONTEXT (fun), new_obj);
2961 if (ctx->call && ctx->call->fundef
2962 && DECL_CONSTRUCTOR_P (ctx->call->fundef->decl))
2964 tree cur_obj = TREE_VEC_ELT (ctx->call->bindings, 0);
2965 STRIP_NOPS (cur_obj);
2966 if (TREE_CODE (cur_obj) == ADDR_EXPR)
2967 cur_obj = TREE_OPERAND (cur_obj, 0);
2968 if (new_obj == cur_obj)
2969 /* We're calling the target constructor of a delegating
2970 constructor, or accessing a base subobject through a
2971 NOP_EXPR as part of a call to a base constructor, so
2972 there is no new (sub)object. */
2973 new_obj = NULL_TREE;
2977 tree result = NULL_TREE;
2979 constexpr_call *entry = NULL;
2980 if (depth_ok && !non_constant_args && ctx->strict)
2982 new_call.hash = constexpr_fundef_hasher::hash (new_call.fundef);
2983 new_call.hash
2984 = iterative_hash_template_arg (new_call.bindings, new_call.hash);
2985 new_call.hash
2986 = iterative_hash_object (ctx->manifestly_const_eval, new_call.hash);
2988 /* If we have seen this call before, we are done. */
2989 maybe_initialize_constexpr_call_table ();
2990 bool insert = depth_ok < constexpr_cache_depth;
2991 constexpr_call **slot
2992 = constexpr_call_table->find_slot (&new_call,
2993 insert ? INSERT : NO_INSERT);
2994 entry = slot ? *slot : NULL;
2995 if (entry == NULL)
2997 /* Only cache up to constexpr_cache_depth to limit memory use. */
2998 if (insert)
3000 /* We need to keep a pointer to the entry, not just the slot, as
3001 the slot can move during evaluation of the body. */
3002 *slot = entry = ggc_alloc<constexpr_call> ();
3003 *entry = new_call;
3004 fb.preserve ();
3007 /* Calls that are in progress have their result set to NULL, so that we
3008 can detect circular dependencies. Now that we only cache up to
3009 constexpr_cache_depth this won't catch circular dependencies that
3010 start deeper, but they'll hit the recursion or ops limit. */
3011 else if (entry->result == NULL)
3013 if (!ctx->quiet)
3014 error ("call has circular dependency");
3015 *non_constant_p = true;
3016 entry->result = result = error_mark_node;
3018 else
3019 result = entry->result;
3022 if (!depth_ok)
3024 if (!ctx->quiet)
3025 error ("%<constexpr%> evaluation depth exceeds maximum of %d (use "
3026 "%<-fconstexpr-depth=%> to increase the maximum)",
3027 max_constexpr_depth);
3028 *non_constant_p = true;
3029 result = error_mark_node;
3031 else
3033 bool cacheable = true;
3034 if (result && result != error_mark_node)
3035 /* OK */;
3036 else if (!DECL_SAVED_TREE (fun))
3038 /* When at_eof >= 2, cgraph has started throwing away
3039 DECL_SAVED_TREE, so fail quietly. FIXME we get here because of
3040 late code generation for VEC_INIT_EXPR, which needs to be
3041 completely reconsidered. */
3042 gcc_assert (at_eof >= 2 && ctx->quiet);
3043 *non_constant_p = true;
3045 else if (tree copy = get_fundef_copy (new_call.fundef))
3047 tree body, parms, res;
3048 releasing_vec ctors;
3050 /* Reuse or create a new unshared copy of this function's body. */
3051 body = TREE_PURPOSE (copy);
3052 parms = TREE_VALUE (copy);
3053 res = TREE_TYPE (copy);
3055 /* Associate the bindings with the remapped parms. */
3056 tree bound = new_call.bindings;
3057 tree remapped = parms;
3058 for (int i = 0; i < TREE_VEC_LENGTH (bound); ++i)
3060 tree arg = TREE_VEC_ELT (bound, i);
3061 if (entry)
3063 /* Unshare args going into the hash table to separate them
3064 from the caller's context, for better GC and to avoid
3065 problems with verify_gimple. */
3066 arg = unshare_expr_without_location (arg);
3067 TREE_VEC_ELT (bound, i) = arg;
3069 /* And then unshare again so the callee doesn't change the
3070 argument values in the hash table. XXX Could we unshare
3071 lazily in cxx_eval_store_expression? */
3072 arg = unshare_constructor (arg);
3073 if (TREE_CODE (arg) == CONSTRUCTOR)
3074 vec_safe_push (ctors, arg);
3076 ctx->global->put_value (remapped, arg);
3077 remapped = DECL_CHAIN (remapped);
3079 /* Add the RESULT_DECL to the values map, too. */
3080 gcc_assert (!DECL_BY_REFERENCE (res));
3081 ctx->global->put_value (res, NULL_TREE);
3083 /* Track the callee's evaluated SAVE_EXPRs and TARGET_EXPRs so that
3084 we can forget their values after the call. */
3085 constexpr_ctx ctx_with_save_exprs = *ctx;
3086 auto_vec<tree, 10> save_exprs;
3087 ctx_with_save_exprs.save_exprs = &save_exprs;
3088 ctx_with_save_exprs.call = &new_call;
3089 unsigned save_heap_alloc_count = ctx->global->heap_vars.length ();
3090 unsigned save_heap_dealloc_count = ctx->global->heap_dealloc_count;
3092 /* If this is a constexpr destructor, the object's const and volatile
3093 semantics are no longer in effect; see [class.dtor]p5. */
3094 if (new_obj && DECL_DESTRUCTOR_P (fun))
3095 cxx_set_object_constness (ctx, new_obj, /*readonly_p=*/false,
3096 non_constant_p, overflow_p);
3098 tree jump_target = NULL_TREE;
3099 cxx_eval_constant_expression (&ctx_with_save_exprs, body,
3100 vc_discard, non_constant_p, overflow_p,
3101 &jump_target);
3103 if (DECL_CONSTRUCTOR_P (fun))
3105 /* This can be null for a subobject constructor call, in
3106 which case what we care about is the initialization
3107 side-effects rather than the value. We could get at the
3108 value by evaluating *this, but we don't bother; there's
3109 no need to put such a call in the hash table. */
3110 result = lval ? ctx->object : ctx->ctor;
3112 /* If we've just evaluated a subobject constructor call for an
3113 empty union member, it might not have produced a side effect
3114 that actually activated the union member. So produce such a
3115 side effect now to ensure the union appears initialized. */
3116 if (!result && new_obj
3117 && TREE_CODE (new_obj) == COMPONENT_REF
3118 && TREE_CODE (TREE_TYPE
3119 (TREE_OPERAND (new_obj, 0))) == UNION_TYPE
3120 && is_really_empty_class (TREE_TYPE (new_obj),
3121 /*ignore_vptr*/false))
3123 tree activate = build2 (MODIFY_EXPR, TREE_TYPE (new_obj),
3124 new_obj,
3125 build_constructor (TREE_TYPE (new_obj),
3126 NULL));
3127 cxx_eval_constant_expression (ctx, activate, lval,
3128 non_constant_p, overflow_p);
3129 ggc_free (activate);
3132 else if (VOID_TYPE_P (TREE_TYPE (res)))
3133 result = void_node;
3134 else
3136 result = ctx->global->get_value (res);
3137 if (result == NULL_TREE && !*non_constant_p
3138 && !DECL_DESTRUCTOR_P (fun))
3140 if (!ctx->quiet)
3141 error ("%<constexpr%> call flows off the end "
3142 "of the function");
3143 *non_constant_p = true;
3147 /* At this point, the object's constructor will have run, so
3148 the object is no longer under construction, and its possible
3149 'const' semantics now apply. Make a note of this fact by
3150 marking the CONSTRUCTOR TREE_READONLY. */
3151 if (new_obj && DECL_CONSTRUCTOR_P (fun))
3152 cxx_set_object_constness (ctx, new_obj, /*readonly_p=*/true,
3153 non_constant_p, overflow_p);
3155 /* Forget the saved values of the callee's SAVE_EXPRs and
3156 TARGET_EXPRs. */
3157 for (tree save_expr : save_exprs)
3158 ctx->global->remove_value (save_expr);
3160 /* Remove the parms/result from the values map. Is it worth
3161 bothering to do this when the map itself is only live for
3162 one constexpr evaluation? If so, maybe also clear out
3163 other vars from call, maybe in BIND_EXPR handling? */
3164 ctx->global->remove_value (res);
3165 for (tree parm = parms; parm; parm = TREE_CHAIN (parm))
3166 ctx->global->remove_value (parm);
3168 /* Free any parameter CONSTRUCTORs we aren't returning directly. */
3169 while (!ctors->is_empty ())
3171 tree c = ctors->pop ();
3172 if (c != result)
3173 free_constructor (c);
3176 /* Make the unshared function copy we used available for re-use. */
3177 save_fundef_copy (fun, copy);
3179 /* If the call allocated some heap object that hasn't been
3180 deallocated during the call, or if it deallocated some heap
3181 object it has not allocated, the call isn't really stateless
3182 for the constexpr evaluation and should not be cached.
3183 It is fine if the call allocates something and deallocates it
3184 too. */
3185 if (entry
3186 && (save_heap_alloc_count != ctx->global->heap_vars.length ()
3187 || (save_heap_dealloc_count
3188 != ctx->global->heap_dealloc_count)))
3190 tree heap_var;
3191 unsigned int i;
3192 if ((ctx->global->heap_vars.length ()
3193 - ctx->global->heap_dealloc_count)
3194 != save_heap_alloc_count - save_heap_dealloc_count)
3195 cacheable = false;
3196 else
3197 FOR_EACH_VEC_ELT_FROM (ctx->global->heap_vars, i, heap_var,
3198 save_heap_alloc_count)
3199 if (DECL_NAME (heap_var) != heap_deleted_identifier)
3201 cacheable = false;
3202 break;
3204 /* Also don't cache a call that returns a deallocated pointer. */
3205 if (cacheable && (cp_walk_tree_without_duplicates
3206 (&result, find_heap_var_refs, NULL)))
3207 cacheable = false;
3210 /* Rewrite all occurrences of the function's RESULT_DECL with the
3211 current object under construction. */
3212 if (!*non_constant_p && ctx->object
3213 && CLASS_TYPE_P (TREE_TYPE (res))
3214 && !is_empty_class (TREE_TYPE (res)))
3215 if (replace_decl (&result, res, ctx->object))
3216 cacheable = false;
3218 else
3219 /* Couldn't get a function copy to evaluate. */
3220 *non_constant_p = true;
3222 if (result == error_mark_node)
3223 *non_constant_p = true;
3224 if (*non_constant_p || *overflow_p)
3225 result = error_mark_node;
3226 else if (!result)
3227 result = void_node;
3228 if (entry)
3229 entry->result = cacheable ? result : error_mark_node;
3232 /* The result of a constexpr function must be completely initialized.
3234 However, in C++20, a constexpr constructor doesn't necessarily have
3235 to initialize all the fields, so we don't clear CONSTRUCTOR_NO_CLEARING
3236 in order to detect reading an unitialized object in constexpr instead
3237 of value-initializing it. (reduced_constant_expression_p is expected to
3238 take care of clearing the flag.) */
3239 if (TREE_CODE (result) == CONSTRUCTOR
3240 && (cxx_dialect < cxx20
3241 || !DECL_CONSTRUCTOR_P (fun)))
3242 clear_no_implicit_zero (result);
3244 pop_cx_call_context ();
3245 return result;
3248 /* Return true if T is a valid constant initializer. If a CONSTRUCTOR
3249 initializes all the members, the CONSTRUCTOR_NO_CLEARING flag will be
3250 cleared.
3251 FIXME speed this up, it's taking 16% of compile time on sieve testcase. */
3253 bool
3254 reduced_constant_expression_p (tree t)
3256 if (t == NULL_TREE)
3257 return false;
3259 switch (TREE_CODE (t))
3261 case PTRMEM_CST:
3262 /* Even if we can't lower this yet, it's constant. */
3263 return true;
3265 case CONSTRUCTOR:
3266 /* And we need to handle PTRMEM_CST wrapped in a CONSTRUCTOR. */
3267 tree field;
3268 if (TREE_CODE (TREE_TYPE (t)) == VECTOR_TYPE)
3269 /* An initialized vector would have a VECTOR_CST. */
3270 return false;
3271 if (CONSTRUCTOR_NO_CLEARING (t))
3273 if (TREE_CODE (TREE_TYPE (t)) == ARRAY_TYPE)
3275 /* There must be a valid constant initializer at every array
3276 index. */
3277 tree min = TYPE_MIN_VALUE (TYPE_DOMAIN (TREE_TYPE (t)));
3278 tree max = TYPE_MAX_VALUE (TYPE_DOMAIN (TREE_TYPE (t)));
3279 tree cursor = min;
3280 for (auto &e: CONSTRUCTOR_ELTS (t))
3282 if (!reduced_constant_expression_p (e.value))
3283 return false;
3284 if (array_index_cmp (cursor, e.index) != 0)
3285 return false;
3286 if (TREE_CODE (e.index) == RANGE_EXPR)
3287 cursor = TREE_OPERAND (e.index, 1);
3288 cursor = int_const_binop (PLUS_EXPR, cursor, size_one_node);
3290 if (find_array_ctor_elt (t, max) == -1)
3291 return false;
3292 goto ok;
3294 else if (cxx_dialect >= cxx20
3295 && TREE_CODE (TREE_TYPE (t)) == UNION_TYPE)
3297 if (CONSTRUCTOR_NELTS (t) == 0)
3298 /* An initialized union has a constructor element. */
3299 return false;
3300 /* And it only initializes one member. */
3301 field = NULL_TREE;
3303 else
3304 field = next_subobject_field (TYPE_FIELDS (TREE_TYPE (t)));
3306 else
3307 field = NULL_TREE;
3308 for (auto &e: CONSTRUCTOR_ELTS (t))
3310 /* If VAL is null, we're in the middle of initializing this
3311 element. */
3312 if (!reduced_constant_expression_p (e.value))
3313 return false;
3314 /* We want to remove initializers for empty fields in a struct to
3315 avoid confusing output_constructor. */
3316 if (is_empty_field (e.index)
3317 && TREE_CODE (TREE_TYPE (t)) == RECORD_TYPE)
3318 return false;
3319 /* Check for non-empty fields between initialized fields when
3320 CONSTRUCTOR_NO_CLEARING. */
3321 for (; field && e.index != field;
3322 field = next_subobject_field (DECL_CHAIN (field)))
3323 if (!is_really_empty_class (TREE_TYPE (field),
3324 /*ignore_vptr*/false))
3325 return false;
3326 if (field)
3327 field = next_subobject_field (DECL_CHAIN (field));
3329 /* There could be a non-empty field at the end. */
3330 for (; field; field = next_subobject_field (DECL_CHAIN (field)))
3331 if (!is_really_empty_class (TREE_TYPE (field), /*ignore_vptr*/false))
3332 return false;
3334 if (CONSTRUCTOR_NO_CLEARING (t))
3335 /* All the fields are initialized. */
3336 CONSTRUCTOR_NO_CLEARING (t) = false;
3337 return true;
3339 default:
3340 /* FIXME are we calling this too much? */
3341 return initializer_constant_valid_p (t, TREE_TYPE (t)) != NULL_TREE;
3345 /* Some expressions may have constant operands but are not constant
3346 themselves, such as 1/0. Call this function to check for that
3347 condition.
3349 We only call this in places that require an arithmetic constant, not in
3350 places where we might have a non-constant expression that can be a
3351 component of a constant expression, such as the address of a constexpr
3352 variable that might be dereferenced later. */
3354 static bool
3355 verify_constant (tree t, bool allow_non_constant, bool *non_constant_p,
3356 bool *overflow_p)
3358 if (!*non_constant_p && !reduced_constant_expression_p (t)
3359 && t != void_node)
3361 if (!allow_non_constant)
3362 error ("%q+E is not a constant expression", t);
3363 *non_constant_p = true;
3365 if (TREE_OVERFLOW_P (t))
3367 if (!allow_non_constant)
3369 permerror (input_location, "overflow in constant expression");
3370 /* If we're being permissive (and are in an enforcing
3371 context), ignore the overflow. */
3372 if (flag_permissive)
3373 return *non_constant_p;
3375 *overflow_p = true;
3377 return *non_constant_p;
3380 /* Check whether the shift operation with code CODE and type TYPE on LHS
3381 and RHS is undefined. If it is, give an error with an explanation,
3382 and return true; return false otherwise. */
3384 static bool
3385 cxx_eval_check_shift_p (location_t loc, const constexpr_ctx *ctx,
3386 enum tree_code code, tree type, tree lhs, tree rhs)
3388 if ((code != LSHIFT_EXPR && code != RSHIFT_EXPR)
3389 || TREE_CODE (lhs) != INTEGER_CST
3390 || TREE_CODE (rhs) != INTEGER_CST)
3391 return false;
3393 tree lhstype = TREE_TYPE (lhs);
3394 unsigned HOST_WIDE_INT uprec = TYPE_PRECISION (TREE_TYPE (lhs));
3396 /* [expr.shift] The behavior is undefined if the right operand
3397 is negative, or greater than or equal to the length in bits
3398 of the promoted left operand. */
3399 if (tree_int_cst_sgn (rhs) == -1)
3401 if (!ctx->quiet)
3402 permerror (loc, "right operand of shift expression %q+E is negative",
3403 build2_loc (loc, code, type, lhs, rhs));
3404 return (!flag_permissive || ctx->quiet);
3406 if (compare_tree_int (rhs, uprec) >= 0)
3408 if (!ctx->quiet)
3409 permerror (loc, "right operand of shift expression %q+E is greater "
3410 "than or equal to the precision %wu of the left operand",
3411 build2_loc (loc, code, type, lhs, rhs), uprec);
3412 return (!flag_permissive || ctx->quiet);
3415 /* The value of E1 << E2 is E1 left-shifted E2 bit positions; [...]
3416 if E1 has a signed type and non-negative value, and E1x2^E2 is
3417 representable in the corresponding unsigned type of the result type,
3418 then that value, converted to the result type, is the resulting value;
3419 otherwise, the behavior is undefined.
3420 For C++20:
3421 The value of E1 << E2 is the unique value congruent to E1 x 2^E2 modulo
3422 2^N, where N is the range exponent of the type of the result. */
3423 if (code == LSHIFT_EXPR
3424 && !TYPE_OVERFLOW_WRAPS (lhstype)
3425 && cxx_dialect >= cxx11
3426 && cxx_dialect < cxx20)
3428 if (tree_int_cst_sgn (lhs) == -1)
3430 if (!ctx->quiet)
3431 permerror (loc,
3432 "left operand of shift expression %q+E is negative",
3433 build2_loc (loc, code, type, lhs, rhs));
3434 return (!flag_permissive || ctx->quiet);
3436 /* For signed x << y the following:
3437 (unsigned) x >> ((prec (lhs) - 1) - y)
3438 if > 1, is undefined. The right-hand side of this formula
3439 is the highest bit of the LHS that can be set (starting from 0),
3440 so that the shift doesn't overflow. We then right-shift the LHS
3441 to see whether any other bit is set making the original shift
3442 undefined -- the result is not representable in the corresponding
3443 unsigned type. */
3444 tree t = build_int_cst (unsigned_type_node, uprec - 1);
3445 t = fold_build2 (MINUS_EXPR, unsigned_type_node, t, rhs);
3446 tree ulhs = fold_convert (unsigned_type_for (lhstype), lhs);
3447 t = fold_build2 (RSHIFT_EXPR, TREE_TYPE (ulhs), ulhs, t);
3448 if (tree_int_cst_lt (integer_one_node, t))
3450 if (!ctx->quiet)
3451 permerror (loc, "shift expression %q+E overflows",
3452 build2_loc (loc, code, type, lhs, rhs));
3453 return (!flag_permissive || ctx->quiet);
3456 return false;
3459 /* Subroutine of cxx_eval_constant_expression.
3460 Attempt to reduce the unary expression tree T to a compile time value.
3461 If successful, return the value. Otherwise issue a diagnostic
3462 and return error_mark_node. */
3464 static tree
3465 cxx_eval_unary_expression (const constexpr_ctx *ctx, tree t,
3466 bool /*lval*/,
3467 bool *non_constant_p, bool *overflow_p)
3469 tree r;
3470 tree orig_arg = TREE_OPERAND (t, 0);
3471 tree arg = cxx_eval_constant_expression (ctx, orig_arg, vc_prvalue,
3472 non_constant_p, overflow_p);
3473 VERIFY_CONSTANT (arg);
3474 location_t loc = EXPR_LOCATION (t);
3475 enum tree_code code = TREE_CODE (t);
3476 tree type = TREE_TYPE (t);
3477 r = fold_unary_loc (loc, code, type, arg);
3478 if (r == NULL_TREE)
3480 if (arg == orig_arg)
3481 r = t;
3482 else
3483 r = build1_loc (loc, code, type, arg);
3485 VERIFY_CONSTANT (r);
3486 return r;
3489 /* Helper function for cxx_eval_binary_expression. Try to optimize
3490 original POINTER_PLUS_EXPR T, LHS p+ RHS, return NULL_TREE if the
3491 generic folding should be used. */
3493 static tree
3494 cxx_fold_pointer_plus_expression (const constexpr_ctx *ctx, tree t,
3495 tree lhs, tree rhs, bool *non_constant_p,
3496 bool *overflow_p)
3498 STRIP_NOPS (lhs);
3499 if (TREE_CODE (lhs) != ADDR_EXPR)
3500 return NULL_TREE;
3502 lhs = TREE_OPERAND (lhs, 0);
3504 /* &A[i] p+ j => &A[i + j] */
3505 if (TREE_CODE (lhs) == ARRAY_REF
3506 && TREE_CODE (TREE_OPERAND (lhs, 1)) == INTEGER_CST
3507 && TREE_CODE (rhs) == INTEGER_CST
3508 && TYPE_SIZE_UNIT (TREE_TYPE (lhs))
3509 && TREE_CODE (TYPE_SIZE_UNIT (TREE_TYPE (lhs))) == INTEGER_CST)
3511 tree orig_type = TREE_TYPE (t);
3512 location_t loc = EXPR_LOCATION (t);
3513 tree type = TREE_TYPE (lhs);
3515 t = fold_convert_loc (loc, ssizetype, TREE_OPERAND (lhs, 1));
3516 tree nelts = array_type_nelts_top (TREE_TYPE (TREE_OPERAND (lhs, 0)));
3517 nelts = cxx_eval_constant_expression (ctx, nelts, vc_prvalue,
3518 non_constant_p, overflow_p);
3519 if (*non_constant_p)
3520 return NULL_TREE;
3521 /* Don't fold an out-of-bound access. */
3522 if (!tree_int_cst_le (t, nelts))
3523 return NULL_TREE;
3524 rhs = cp_fold_convert (ssizetype, rhs);
3525 /* Don't fold if rhs can't be divided exactly by TYPE_SIZE_UNIT.
3526 constexpr int A[1]; ... (char *)&A[0] + 1 */
3527 if (!integer_zerop (fold_build2_loc (loc, TRUNC_MOD_EXPR, sizetype,
3528 rhs, TYPE_SIZE_UNIT (type))))
3529 return NULL_TREE;
3530 /* Make sure to treat the second operand of POINTER_PLUS_EXPR
3531 as signed. */
3532 rhs = fold_build2_loc (loc, EXACT_DIV_EXPR, ssizetype, rhs,
3533 TYPE_SIZE_UNIT (type));
3534 t = size_binop_loc (loc, PLUS_EXPR, rhs, t);
3535 t = build4_loc (loc, ARRAY_REF, type, TREE_OPERAND (lhs, 0),
3536 t, NULL_TREE, NULL_TREE);
3537 t = cp_build_addr_expr (t, tf_warning_or_error);
3538 t = cp_fold_convert (orig_type, t);
3539 return cxx_eval_constant_expression (ctx, t, vc_prvalue,
3540 non_constant_p, overflow_p);
3543 return NULL_TREE;
3546 /* Try to fold expressions like
3547 (struct S *) (&a[0].D.2378 + 12)
3548 into
3549 &MEM <struct T> [(void *)&a + 12B]
3550 This is something normally done by gimple_fold_stmt_to_constant_1
3551 on GIMPLE, but is undesirable on GENERIC if we are e.g. going to
3552 dereference the address because some details are lost.
3553 For pointer comparisons we want such folding though so that
3554 match.pd address_compare optimization works. */
3556 static tree
3557 cxx_maybe_fold_addr_pointer_plus (tree t)
3559 while (CONVERT_EXPR_P (t)
3560 && POINTER_TYPE_P (TREE_TYPE (TREE_OPERAND (t, 0))))
3561 t = TREE_OPERAND (t, 0);
3562 if (TREE_CODE (t) != POINTER_PLUS_EXPR)
3563 return NULL_TREE;
3564 tree op0 = TREE_OPERAND (t, 0);
3565 tree op1 = TREE_OPERAND (t, 1);
3566 if (TREE_CODE (op1) != INTEGER_CST)
3567 return NULL_TREE;
3568 while (CONVERT_EXPR_P (op0)
3569 && POINTER_TYPE_P (TREE_TYPE (TREE_OPERAND (op0, 0))))
3570 op0 = TREE_OPERAND (op0, 0);
3571 if (TREE_CODE (op0) != ADDR_EXPR)
3572 return NULL_TREE;
3573 op1 = fold_convert (ptr_type_node, op1);
3574 tree r = fold_build2 (MEM_REF, TREE_TYPE (TREE_TYPE (op0)), op0, op1);
3575 return build1_loc (EXPR_LOCATION (t), ADDR_EXPR, TREE_TYPE (op0), r);
3578 /* Subroutine of cxx_eval_constant_expression.
3579 Like cxx_eval_unary_expression, except for binary expressions. */
3581 static tree
3582 cxx_eval_binary_expression (const constexpr_ctx *ctx, tree t,
3583 value_cat lval,
3584 bool *non_constant_p, bool *overflow_p)
3586 tree r = NULL_TREE;
3587 tree orig_lhs = TREE_OPERAND (t, 0);
3588 tree orig_rhs = TREE_OPERAND (t, 1);
3589 tree lhs, rhs;
3590 lhs = cxx_eval_constant_expression (ctx, orig_lhs, vc_prvalue,
3591 non_constant_p, overflow_p);
3592 /* Don't VERIFY_CONSTANT here, it's unnecessary and will break pointer
3593 subtraction. */
3594 if (*non_constant_p)
3595 return t;
3596 rhs = cxx_eval_constant_expression (ctx, orig_rhs, vc_prvalue,
3597 non_constant_p, overflow_p);
3598 if (*non_constant_p)
3599 return t;
3601 location_t loc = EXPR_LOCATION (t);
3602 enum tree_code code = TREE_CODE (t);
3603 tree type = TREE_TYPE (t);
3605 if (code == EQ_EXPR || code == NE_EXPR)
3607 bool is_code_eq = (code == EQ_EXPR);
3609 if (TREE_CODE (lhs) == PTRMEM_CST
3610 && TREE_CODE (rhs) == PTRMEM_CST)
3612 tree lmem = PTRMEM_CST_MEMBER (lhs);
3613 tree rmem = PTRMEM_CST_MEMBER (rhs);
3614 bool eq;
3615 if (TREE_CODE (lmem) == TREE_CODE (rmem)
3616 && TREE_CODE (lmem) == FIELD_DECL
3617 && TREE_CODE (DECL_CONTEXT (lmem)) == UNION_TYPE
3618 && same_type_p (DECL_CONTEXT (lmem),
3619 DECL_CONTEXT (rmem)))
3620 /* If both refer to (possibly different) members of the same union
3621 (12.3), they compare equal. */
3622 eq = true;
3623 else
3624 eq = cp_tree_equal (lhs, rhs);
3625 r = constant_boolean_node (eq == is_code_eq, type);
3627 else if ((TREE_CODE (lhs) == PTRMEM_CST
3628 || TREE_CODE (rhs) == PTRMEM_CST)
3629 && (null_member_pointer_value_p (lhs)
3630 || null_member_pointer_value_p (rhs)))
3631 r = constant_boolean_node (!is_code_eq, type);
3632 else if (TREE_CODE (lhs) == PTRMEM_CST)
3633 lhs = cplus_expand_constant (lhs);
3634 else if (TREE_CODE (rhs) == PTRMEM_CST)
3635 rhs = cplus_expand_constant (rhs);
3637 if (r == NULL_TREE
3638 && TREE_CODE_CLASS (code) == tcc_comparison
3639 && POINTER_TYPE_P (TREE_TYPE (lhs)))
3641 if (tree lhso = cxx_maybe_fold_addr_pointer_plus (lhs))
3642 lhs = fold_convert (TREE_TYPE (lhs), lhso);
3643 if (tree rhso = cxx_maybe_fold_addr_pointer_plus (rhs))
3644 rhs = fold_convert (TREE_TYPE (rhs), rhso);
3646 if (code == POINTER_PLUS_EXPR && !*non_constant_p
3647 && integer_zerop (lhs) && !integer_zerop (rhs))
3649 if (!ctx->quiet)
3650 error ("arithmetic involving a null pointer in %qE", lhs);
3651 *non_constant_p = true;
3652 return t;
3654 else if (code == POINTER_PLUS_EXPR)
3655 r = cxx_fold_pointer_plus_expression (ctx, t, lhs, rhs, non_constant_p,
3656 overflow_p);
3657 else if (code == SPACESHIP_EXPR)
3659 r = genericize_spaceship (loc, type, lhs, rhs);
3660 return cxx_eval_constant_expression (ctx, r, lval, non_constant_p,
3661 overflow_p);
3664 if (r == NULL_TREE)
3666 if (ctx->manifestly_const_eval == mce_true
3667 && (flag_constexpr_fp_except
3668 || TREE_CODE (type) != REAL_TYPE))
3670 auto ofcc = make_temp_override (folding_cxx_constexpr, true);
3671 r = fold_binary_initializer_loc (loc, code, type, lhs, rhs);
3673 else
3674 r = fold_binary_loc (loc, code, type, lhs, rhs);
3677 if (r == NULL_TREE
3678 && (code == LSHIFT_EXPR || code == RSHIFT_EXPR)
3679 && TREE_CODE (lhs) == INTEGER_CST
3680 && TREE_CODE (rhs) == INTEGER_CST
3681 && wi::neg_p (wi::to_wide (rhs)))
3683 /* For diagnostics and -fpermissive emulate previous behavior of
3684 handling shifts by negative amount. */
3685 tree nrhs = const_unop (NEGATE_EXPR, TREE_TYPE (rhs), rhs);
3686 if (nrhs)
3687 r = fold_binary_loc (loc,
3688 code == LSHIFT_EXPR ? RSHIFT_EXPR : LSHIFT_EXPR,
3689 type, lhs, nrhs);
3692 if (r == NULL_TREE)
3694 if (lhs == orig_lhs && rhs == orig_rhs)
3695 r = t;
3696 else
3697 r = build2_loc (loc, code, type, lhs, rhs);
3699 else if (cxx_eval_check_shift_p (loc, ctx, code, type, lhs, rhs))
3700 *non_constant_p = true;
3701 /* Don't VERIFY_CONSTANT if this might be dealing with a pointer to
3702 a local array in a constexpr function. */
3703 bool ptr = INDIRECT_TYPE_P (TREE_TYPE (lhs));
3704 if (!ptr)
3705 VERIFY_CONSTANT (r);
3706 return r;
3709 /* Subroutine of cxx_eval_constant_expression.
3710 Attempt to evaluate condition expressions. Dead branches are not
3711 looked into. */
3713 static tree
3714 cxx_eval_conditional_expression (const constexpr_ctx *ctx, tree t,
3715 value_cat lval,
3716 bool *non_constant_p, bool *overflow_p,
3717 tree *jump_target)
3719 tree val = cxx_eval_constant_expression (ctx, TREE_OPERAND (t, 0),
3720 vc_prvalue,
3721 non_constant_p, overflow_p);
3722 VERIFY_CONSTANT (val);
3723 if (TREE_CODE (t) == IF_STMT && IF_STMT_CONSTEVAL_P (t))
3725 /* Evaluate the condition as if it was
3726 if (__builtin_is_constant_evaluated ()), i.e. defer it if not
3727 ctx->manifestly_const_eval (as sometimes we try to constant evaluate
3728 without manifestly_const_eval even expressions or parts thereof which
3729 will later be manifestly const_eval evaluated), otherwise fold it to
3730 true. */
3731 if (ctx->manifestly_const_eval == mce_unknown)
3733 *non_constant_p = true;
3734 return t;
3736 val = constant_boolean_node (ctx->manifestly_const_eval == mce_true,
3737 boolean_type_node);
3739 /* Don't VERIFY_CONSTANT the other operands. */
3740 if (integer_zerop (val))
3741 val = TREE_OPERAND (t, 2);
3742 else
3743 val = TREE_OPERAND (t, 1);
3744 if (TREE_CODE (t) == IF_STMT && !val)
3745 val = void_node;
3746 /* A TARGET_EXPR may be nested inside another TARGET_EXPR, but still
3747 serve as the initializer for the same object as the outer TARGET_EXPR,
3748 as in
3749 A a = true ? A{} : A{};
3750 so strip the inner TARGET_EXPR so we don't materialize a temporary. */
3751 if (TREE_CODE (val) == TARGET_EXPR)
3752 val = TARGET_EXPR_INITIAL (val);
3753 return cxx_eval_constant_expression (ctx, val, lval, non_constant_p,
3754 overflow_p, jump_target);
3757 /* Subroutine of cxx_eval_constant_expression.
3758 Attempt to evaluate vector condition expressions. Unlike
3759 cxx_eval_conditional_expression, VEC_COND_EXPR acts like a normal
3760 ternary arithmetics operation, where all 3 arguments have to be
3761 evaluated as constants and then folding computes the result from
3762 them. */
3764 static tree
3765 cxx_eval_vector_conditional_expression (const constexpr_ctx *ctx, tree t,
3766 bool *non_constant_p, bool *overflow_p)
3768 tree arg1 = cxx_eval_constant_expression (ctx, TREE_OPERAND (t, 0),
3769 vc_prvalue,
3770 non_constant_p, overflow_p);
3771 VERIFY_CONSTANT (arg1);
3772 tree arg2 = cxx_eval_constant_expression (ctx, TREE_OPERAND (t, 1),
3773 vc_prvalue,
3774 non_constant_p, overflow_p);
3775 VERIFY_CONSTANT (arg2);
3776 tree arg3 = cxx_eval_constant_expression (ctx, TREE_OPERAND (t, 2),
3777 vc_prvalue,
3778 non_constant_p, overflow_p);
3779 VERIFY_CONSTANT (arg3);
3780 location_t loc = EXPR_LOCATION (t);
3781 tree type = TREE_TYPE (t);
3782 tree r = fold_ternary_loc (loc, VEC_COND_EXPR, type, arg1, arg2, arg3);
3783 if (r == NULL_TREE)
3785 if (arg1 == TREE_OPERAND (t, 0)
3786 && arg2 == TREE_OPERAND (t, 1)
3787 && arg3 == TREE_OPERAND (t, 2))
3788 r = t;
3789 else
3790 r = build3_loc (loc, VEC_COND_EXPR, type, arg1, arg2, arg3);
3792 VERIFY_CONSTANT (r);
3793 return r;
3796 /* Returns less than, equal to, or greater than zero if KEY is found to be
3797 less than, to match, or to be greater than the constructor_elt's INDEX. */
3799 static int
3800 array_index_cmp (tree key, tree index)
3802 gcc_assert (TREE_CODE (key) == INTEGER_CST);
3804 switch (TREE_CODE (index))
3806 case INTEGER_CST:
3807 return tree_int_cst_compare (key, index);
3808 case RANGE_EXPR:
3810 tree lo = TREE_OPERAND (index, 0);
3811 tree hi = TREE_OPERAND (index, 1);
3812 if (tree_int_cst_lt (key, lo))
3813 return -1;
3814 else if (tree_int_cst_lt (hi, key))
3815 return 1;
3816 else
3817 return 0;
3819 default:
3820 gcc_unreachable ();
3824 /* Returns the index of the constructor_elt of ARY which matches DINDEX, or -1
3825 if none. If INSERT is true, insert a matching element rather than fail. */
3827 static HOST_WIDE_INT
3828 find_array_ctor_elt (tree ary, tree dindex, bool insert)
3830 if (tree_int_cst_sgn (dindex) < 0)
3831 return -1;
3833 unsigned HOST_WIDE_INT i = tree_to_uhwi (dindex);
3834 vec<constructor_elt, va_gc> *elts = CONSTRUCTOR_ELTS (ary);
3835 unsigned HOST_WIDE_INT len = vec_safe_length (elts);
3837 unsigned HOST_WIDE_INT end = len;
3838 unsigned HOST_WIDE_INT begin = 0;
3840 /* If the last element of the CONSTRUCTOR has its own index, we can assume
3841 that the same is true of the other elements and index directly. */
3842 if (end > 0)
3844 tree cindex = (*elts)[end - 1].index;
3845 if (cindex == NULL_TREE)
3847 /* Verify that if the last index is missing, all indexes
3848 are missing. */
3849 if (flag_checking)
3850 for (unsigned int j = 0; j < len - 1; ++j)
3851 gcc_assert ((*elts)[j].index == NULL_TREE);
3852 if (i < end)
3853 return i;
3854 else
3856 begin = end;
3857 if (i == end)
3858 /* If the element is to be added right at the end,
3859 make sure it is added with cleared index too. */
3860 dindex = NULL_TREE;
3861 else if (insert)
3862 /* Otherwise, in order not to break the assumption
3863 that CONSTRUCTOR either has all indexes or none,
3864 we need to add indexes to all elements. */
3865 for (unsigned int j = 0; j < len; ++j)
3866 (*elts)[j].index = build_int_cst (TREE_TYPE (dindex), j);
3869 else if (TREE_CODE (cindex) == INTEGER_CST
3870 && compare_tree_int (cindex, end - 1) == 0)
3872 if (i < end)
3873 return i;
3874 else
3875 begin = end;
3879 /* Otherwise, find a matching index by means of a binary search. */
3880 while (begin != end)
3882 unsigned HOST_WIDE_INT middle = (begin + end) / 2;
3883 constructor_elt &elt = (*elts)[middle];
3884 tree idx = elt.index;
3886 int cmp = array_index_cmp (dindex, idx);
3887 if (cmp < 0)
3888 end = middle;
3889 else if (cmp > 0)
3890 begin = middle + 1;
3891 else
3893 if (insert && TREE_CODE (idx) == RANGE_EXPR)
3895 /* We need to split the range. */
3896 constructor_elt e;
3897 tree lo = TREE_OPERAND (idx, 0);
3898 tree hi = TREE_OPERAND (idx, 1);
3899 tree value = elt.value;
3900 dindex = fold_convert (sizetype, dindex);
3901 if (tree_int_cst_lt (lo, dindex))
3903 /* There are still some lower elts; shorten the range. */
3904 tree new_hi = int_const_binop (MINUS_EXPR, dindex,
3905 size_one_node);
3906 if (tree_int_cst_equal (lo, new_hi))
3907 /* Only one element left, no longer a range. */
3908 elt.index = lo;
3909 else
3910 TREE_OPERAND (idx, 1) = new_hi;
3911 /* Append the element we want to insert. */
3912 ++middle;
3913 e.index = dindex;
3914 e.value = unshare_constructor (value);
3915 vec_safe_insert (CONSTRUCTOR_ELTS (ary), middle, e);
3917 else
3918 /* No lower elts, the range elt is now ours. */
3919 elt.index = dindex;
3921 if (tree_int_cst_lt (dindex, hi))
3923 /* There are still some higher elts; append a range. */
3924 tree new_lo = int_const_binop (PLUS_EXPR, dindex,
3925 size_one_node);
3926 if (tree_int_cst_equal (new_lo, hi))
3927 e.index = hi;
3928 else
3929 e.index = build2 (RANGE_EXPR, sizetype, new_lo, hi);
3930 e.value = unshare_constructor (value);
3931 vec_safe_insert (CONSTRUCTOR_ELTS (ary), middle + 1, e);
3934 return middle;
3938 if (insert)
3940 constructor_elt e = { dindex, NULL_TREE };
3941 vec_safe_insert (CONSTRUCTOR_ELTS (ary), end, e);
3942 return end;
3945 return -1;
3948 /* Return a pointer to the constructor_elt of CTOR which matches INDEX. If no
3949 matching constructor_elt exists, then add one to CTOR.
3951 As an optimization, if POS_HINT is non-negative then it is used as a guess
3952 for the (integer) index of the matching constructor_elt within CTOR. */
3954 static constructor_elt *
3955 get_or_insert_ctor_field (tree ctor, tree index, int pos_hint = -1)
3957 /* Check the hint first. */
3958 if (pos_hint >= 0 && (unsigned)pos_hint < CONSTRUCTOR_NELTS (ctor)
3959 && CONSTRUCTOR_ELT (ctor, pos_hint)->index == index)
3960 return CONSTRUCTOR_ELT (ctor, pos_hint);
3962 tree type = TREE_TYPE (ctor);
3963 if (TREE_CODE (type) == VECTOR_TYPE && index == NULL_TREE)
3965 CONSTRUCTOR_APPEND_ELT (CONSTRUCTOR_ELTS (ctor), index, NULL_TREE);
3966 return &CONSTRUCTOR_ELTS (ctor)->last();
3968 else if (TREE_CODE (type) == ARRAY_TYPE || TREE_CODE (type) == VECTOR_TYPE)
3970 if (TREE_CODE (index) == RANGE_EXPR)
3972 /* Support for RANGE_EXPR index lookups is currently limited to
3973 accessing an existing element via POS_HINT, or appending a new
3974 element to the end of CTOR. ??? Support for other access
3975 patterns may also be needed. */
3976 vec<constructor_elt, va_gc> *elts = CONSTRUCTOR_ELTS (ctor);
3977 if (vec_safe_length (elts))
3979 tree lo = TREE_OPERAND (index, 0);
3980 gcc_assert (array_index_cmp (elts->last().index, lo) < 0);
3982 CONSTRUCTOR_APPEND_ELT (elts, index, NULL_TREE);
3983 return &elts->last();
3986 HOST_WIDE_INT i = find_array_ctor_elt (ctor, index, /*insert*/true);
3987 gcc_assert (i >= 0);
3988 constructor_elt *cep = CONSTRUCTOR_ELT (ctor, i);
3989 gcc_assert (cep->index == NULL_TREE
3990 || TREE_CODE (cep->index) != RANGE_EXPR);
3991 return cep;
3993 else
3995 gcc_assert (TREE_CODE (index) == FIELD_DECL
3996 && (same_type_ignoring_top_level_qualifiers_p
3997 (DECL_CONTEXT (index), TREE_TYPE (ctor))));
3999 /* We must keep the CONSTRUCTOR's ELTS in FIELD order.
4000 Usually we meet initializers in that order, but it is
4001 possible for base types to be placed not in program
4002 order. */
4003 tree fields = TYPE_FIELDS (DECL_CONTEXT (index));
4004 unsigned HOST_WIDE_INT idx = 0;
4005 constructor_elt *cep = NULL;
4007 /* Check if we're changing the active member of a union. */
4008 if (TREE_CODE (type) == UNION_TYPE && CONSTRUCTOR_NELTS (ctor)
4009 && CONSTRUCTOR_ELT (ctor, 0)->index != index)
4010 vec_safe_truncate (CONSTRUCTOR_ELTS (ctor), 0);
4011 /* If the bit offset of INDEX is larger than that of the last
4012 constructor_elt, then we can just immediately append a new
4013 constructor_elt to the end of CTOR. */
4014 else if (CONSTRUCTOR_NELTS (ctor)
4015 && tree_int_cst_compare (bit_position (index),
4016 bit_position (CONSTRUCTOR_ELTS (ctor)
4017 ->last().index)) > 0)
4019 idx = CONSTRUCTOR_NELTS (ctor);
4020 goto insert;
4023 /* Otherwise, we need to iterate over CTOR to find or insert INDEX
4024 appropriately. */
4026 for (; vec_safe_iterate (CONSTRUCTOR_ELTS (ctor), idx, &cep);
4027 idx++, fields = DECL_CHAIN (fields))
4029 if (index == cep->index)
4030 goto found;
4032 /* The field we're initializing must be on the field
4033 list. Look to see if it is present before the
4034 field the current ELT initializes. */
4035 for (; fields != cep->index; fields = DECL_CHAIN (fields))
4036 if (index == fields)
4037 goto insert;
4039 /* We fell off the end of the CONSTRUCTOR, so insert a new
4040 entry at the end. */
4042 insert:
4044 constructor_elt ce = { index, NULL_TREE };
4046 vec_safe_insert (CONSTRUCTOR_ELTS (ctor), idx, ce);
4047 cep = CONSTRUCTOR_ELT (ctor, idx);
4049 found:;
4051 return cep;
4055 /* Under the control of CTX, issue a detailed diagnostic for
4056 an out-of-bounds subscript INDEX into the expression ARRAY. */
4058 static void
4059 diag_array_subscript (location_t loc, const constexpr_ctx *ctx, tree array, tree index)
4061 if (!ctx->quiet)
4063 tree arraytype = TREE_TYPE (array);
4065 /* Convert the unsigned array subscript to a signed integer to avoid
4066 printing huge numbers for small negative values. */
4067 tree sidx = fold_convert (ssizetype, index);
4068 STRIP_ANY_LOCATION_WRAPPER (array);
4069 if (DECL_P (array))
4071 if (TYPE_DOMAIN (arraytype))
4072 error_at (loc, "array subscript value %qE is outside the bounds "
4073 "of array %qD of type %qT", sidx, array, arraytype);
4074 else
4075 error_at (loc, "nonzero array subscript %qE is used with array %qD of "
4076 "type %qT with unknown bounds", sidx, array, arraytype);
4077 inform (DECL_SOURCE_LOCATION (array), "declared here");
4079 else if (TYPE_DOMAIN (arraytype))
4080 error_at (loc, "array subscript value %qE is outside the bounds "
4081 "of array type %qT", sidx, arraytype);
4082 else
4083 error_at (loc, "nonzero array subscript %qE is used with array of type %qT "
4084 "with unknown bounds", sidx, arraytype);
4088 /* Return the number of elements for TYPE (which is an ARRAY_TYPE or
4089 a VECTOR_TYPE). */
4091 static tree
4092 get_array_or_vector_nelts (const constexpr_ctx *ctx, tree type,
4093 bool *non_constant_p, bool *overflow_p)
4095 tree nelts;
4096 if (TREE_CODE (type) == ARRAY_TYPE)
4098 if (TYPE_DOMAIN (type))
4099 nelts = array_type_nelts_top (type);
4100 else
4101 nelts = size_zero_node;
4103 else if (VECTOR_TYPE_P (type))
4104 nelts = size_int (TYPE_VECTOR_SUBPARTS (type));
4105 else
4106 gcc_unreachable ();
4108 /* For VLAs, the number of elements won't be an integer constant. */
4109 nelts = cxx_eval_constant_expression (ctx, nelts, vc_prvalue,
4110 non_constant_p, overflow_p);
4111 return nelts;
4114 /* Extract element INDEX consisting of CHARS_PER_ELT chars from
4115 STRING_CST STRING. */
4117 static tree
4118 extract_string_elt (tree string, unsigned chars_per_elt, unsigned index)
4120 tree type = cv_unqualified (TREE_TYPE (TREE_TYPE (string)));
4121 tree r;
4123 if (chars_per_elt == 1)
4124 r = build_int_cst (type, TREE_STRING_POINTER (string)[index]);
4125 else
4127 const unsigned char *ptr
4128 = ((const unsigned char *)TREE_STRING_POINTER (string)
4129 + index * chars_per_elt);
4130 r = native_interpret_expr (type, ptr, chars_per_elt);
4132 return r;
4135 /* Subroutine of cxx_eval_array_reference. T is an ARRAY_REF; evaluate the
4136 subscript, diagnose any problems with it, and return the result. */
4138 static tree
4139 eval_and_check_array_index (const constexpr_ctx *ctx,
4140 tree t, bool allow_one_past,
4141 bool *non_constant_p, bool *overflow_p)
4143 location_t loc = cp_expr_loc_or_input_loc (t);
4144 tree ary = TREE_OPERAND (t, 0);
4145 t = TREE_OPERAND (t, 1);
4146 tree index = cxx_eval_constant_expression (ctx, t, vc_prvalue,
4147 non_constant_p, overflow_p);
4148 VERIFY_CONSTANT (index);
4150 if (!tree_fits_shwi_p (index)
4151 || tree_int_cst_sgn (index) < 0)
4153 diag_array_subscript (loc, ctx, ary, index);
4154 *non_constant_p = true;
4155 return t;
4158 tree nelts = get_array_or_vector_nelts (ctx, TREE_TYPE (ary), non_constant_p,
4159 overflow_p);
4160 VERIFY_CONSTANT (nelts);
4161 if (allow_one_past
4162 ? !tree_int_cst_le (index, nelts)
4163 : !tree_int_cst_lt (index, nelts))
4165 diag_array_subscript (loc, ctx, ary, index);
4166 *non_constant_p = true;
4167 return t;
4170 return index;
4173 /* Subroutine of cxx_eval_constant_expression.
4174 Attempt to reduce a reference to an array slot. */
4176 static tree
4177 cxx_eval_array_reference (const constexpr_ctx *ctx, tree t,
4178 value_cat lval,
4179 bool *non_constant_p, bool *overflow_p)
4181 tree oldary = TREE_OPERAND (t, 0);
4182 tree ary = cxx_eval_constant_expression (ctx, oldary,
4183 lval,
4184 non_constant_p, overflow_p);
4185 if (*non_constant_p)
4186 return t;
4187 if (!lval
4188 && TREE_CODE (ary) == VIEW_CONVERT_EXPR
4189 && VECTOR_TYPE_P (TREE_TYPE (TREE_OPERAND (ary, 0)))
4190 && TREE_TYPE (t) == TREE_TYPE (TREE_TYPE (TREE_OPERAND (ary, 0))))
4191 ary = TREE_OPERAND (ary, 0);
4193 tree oldidx = TREE_OPERAND (t, 1);
4194 tree index = eval_and_check_array_index (ctx, t, lval,
4195 non_constant_p, overflow_p);
4196 if (*non_constant_p)
4197 return t;
4199 if (lval && ary == oldary && index == oldidx)
4200 return t;
4201 else if (lval == vc_discard)
4202 return t;
4203 else if (lval)
4204 return build4 (ARRAY_REF, TREE_TYPE (t), ary, index, NULL, NULL);
4206 unsigned len = 0, elem_nchars = 1;
4207 tree elem_type = TREE_TYPE (TREE_TYPE (ary));
4208 if (TREE_CODE (ary) == CONSTRUCTOR)
4209 len = CONSTRUCTOR_NELTS (ary);
4210 else if (TREE_CODE (ary) == STRING_CST)
4212 elem_nchars = (TYPE_PRECISION (elem_type)
4213 / TYPE_PRECISION (char_type_node));
4214 len = (unsigned) TREE_STRING_LENGTH (ary) / elem_nchars;
4216 else if (TREE_CODE (ary) == VECTOR_CST)
4217 /* We don't create variable-length VECTOR_CSTs. */
4218 len = VECTOR_CST_NELTS (ary).to_constant ();
4219 else
4221 /* We can't do anything with other tree codes, so use
4222 VERIFY_CONSTANT to complain and fail. */
4223 VERIFY_CONSTANT (ary);
4224 gcc_unreachable ();
4227 bool found;
4228 HOST_WIDE_INT i = 0;
4229 if (TREE_CODE (ary) == CONSTRUCTOR)
4231 HOST_WIDE_INT ix = find_array_ctor_elt (ary, index);
4232 found = (ix >= 0);
4233 if (found)
4234 i = ix;
4236 else
4238 i = tree_to_shwi (index);
4239 found = (i < len);
4242 if (found)
4244 tree r;
4245 if (TREE_CODE (ary) == CONSTRUCTOR)
4246 r = (*CONSTRUCTOR_ELTS (ary))[i].value;
4247 else if (TREE_CODE (ary) == VECTOR_CST)
4248 r = VECTOR_CST_ELT (ary, i);
4249 else
4250 r = extract_string_elt (ary, elem_nchars, i);
4252 if (r)
4253 /* Don't VERIFY_CONSTANT here. */
4254 return r;
4256 /* Otherwise the element doesn't have a value yet. */
4259 /* Not found. */
4261 if (TREE_CODE (ary) == CONSTRUCTOR
4262 && CONSTRUCTOR_NO_CLEARING (ary))
4264 /* 'ary' is part of the aggregate initializer we're currently
4265 building; if there's no initializer for this element yet,
4266 that's an error. */
4267 if (!ctx->quiet)
4268 error ("accessing uninitialized array element");
4269 *non_constant_p = true;
4270 return t;
4273 /* If it's within the array bounds but doesn't have an explicit
4274 initializer, it's initialized from {}. But use build_value_init
4275 directly for non-aggregates to avoid creating a garbage CONSTRUCTOR. */
4276 tree val;
4277 constexpr_ctx new_ctx;
4278 if (is_really_empty_class (elem_type, /*ignore_vptr*/false))
4279 return build_constructor (elem_type, NULL);
4280 else if (CP_AGGREGATE_TYPE_P (elem_type))
4282 tree empty_ctor = build_constructor (init_list_type_node, NULL);
4283 val = digest_init (elem_type, empty_ctor, tf_warning_or_error);
4285 else
4286 val = build_value_init (elem_type, tf_warning_or_error);
4288 if (!SCALAR_TYPE_P (elem_type))
4290 new_ctx = *ctx;
4291 new_ctx.ctor = build_constructor (elem_type, NULL);
4292 ctx = &new_ctx;
4294 t = cxx_eval_constant_expression (ctx, val, lval, non_constant_p,
4295 overflow_p);
4296 if (!SCALAR_TYPE_P (elem_type) && t != ctx->ctor)
4297 free_constructor (ctx->ctor);
4298 return t;
4301 /* Subroutine of cxx_eval_constant_expression.
4302 Attempt to reduce a field access of a value of class type. */
4304 static tree
4305 cxx_eval_component_reference (const constexpr_ctx *ctx, tree t,
4306 value_cat lval,
4307 bool *non_constant_p, bool *overflow_p)
4309 unsigned HOST_WIDE_INT i;
4310 tree field;
4311 tree value;
4312 tree part = TREE_OPERAND (t, 1);
4313 tree orig_whole = TREE_OPERAND (t, 0);
4314 tree whole = cxx_eval_constant_expression (ctx, orig_whole,
4315 lval,
4316 non_constant_p, overflow_p);
4317 if (*non_constant_p)
4318 return t;
4319 if (INDIRECT_REF_P (whole)
4320 && integer_zerop (TREE_OPERAND (whole, 0)))
4322 if (!ctx->quiet)
4323 error ("dereferencing a null pointer in %qE", orig_whole);
4324 *non_constant_p = true;
4325 return t;
4328 if (TREE_CODE (whole) == PTRMEM_CST)
4329 whole = cplus_expand_constant (whole);
4330 if (whole == orig_whole)
4331 return t;
4332 if (lval == vc_discard)
4333 return t;
4334 if (lval)
4335 return fold_build3 (COMPONENT_REF, TREE_TYPE (t),
4336 whole, part, NULL_TREE);
4337 /* Don't VERIFY_CONSTANT here; we only want to check that we got a
4338 CONSTRUCTOR. */
4339 if (TREE_CODE (whole) != CONSTRUCTOR)
4341 if (!ctx->quiet)
4342 error ("%qE is not a constant expression", orig_whole);
4343 *non_constant_p = true;
4344 return t;
4346 if ((cxx_dialect < cxx14 || CONSTRUCTOR_MUTABLE_POISON (whole))
4347 && DECL_MUTABLE_P (part))
4349 if (!ctx->quiet)
4350 error ("mutable %qD is not usable in a constant expression", part);
4351 *non_constant_p = true;
4352 return t;
4354 bool pmf = TYPE_PTRMEMFUNC_P (TREE_TYPE (whole));
4355 FOR_EACH_CONSTRUCTOR_ELT (CONSTRUCTOR_ELTS (whole), i, field, value)
4357 /* Use name match for PMF fields, as a variant will have a
4358 different FIELD_DECL with a different type. */
4359 if (pmf ? DECL_NAME (field) == DECL_NAME (part)
4360 : field == part)
4362 if (value)
4364 STRIP_ANY_LOCATION_WRAPPER (value);
4365 return value;
4367 else
4368 /* We're in the middle of initializing it. */
4369 break;
4372 if (TREE_CODE (TREE_TYPE (whole)) == UNION_TYPE
4373 && CONSTRUCTOR_NELTS (whole) > 0)
4375 /* DR 1188 says we don't have to deal with this. */
4376 if (!ctx->quiet)
4378 constructor_elt *cep = CONSTRUCTOR_ELT (whole, 0);
4379 if (cep->value == NULL_TREE)
4380 error ("accessing uninitialized member %qD", part);
4381 else
4382 error ("accessing %qD member instead of initialized %qD member in "
4383 "constant expression", part, cep->index);
4385 *non_constant_p = true;
4386 return t;
4389 /* We only create a CONSTRUCTOR for a subobject when we modify it, so empty
4390 classes never get represented; throw together a value now. */
4391 if (is_really_empty_class (TREE_TYPE (t), /*ignore_vptr*/false))
4392 return build_constructor (TREE_TYPE (t), NULL);
4394 gcc_assert (DECL_CONTEXT (part) == TYPE_MAIN_VARIANT (TREE_TYPE (whole)));
4396 if (CONSTRUCTOR_NO_CLEARING (whole))
4398 /* 'whole' is part of the aggregate initializer we're currently
4399 building; if there's no initializer for this member yet, that's an
4400 error. */
4401 if (!ctx->quiet)
4402 error ("accessing uninitialized member %qD", part);
4403 *non_constant_p = true;
4404 return t;
4407 /* If there's no explicit init for this field, it's value-initialized. */
4408 value = build_value_init (TREE_TYPE (t), tf_warning_or_error);
4409 return cxx_eval_constant_expression (ctx, value,
4410 lval,
4411 non_constant_p, overflow_p);
4414 /* Subroutine of cxx_eval_constant_expression.
4415 Attempt to reduce a field access of a value of class type that is
4416 expressed as a BIT_FIELD_REF. */
4418 static tree
4419 cxx_eval_bit_field_ref (const constexpr_ctx *ctx, tree t,
4420 value_cat lval,
4421 bool *non_constant_p, bool *overflow_p)
4423 tree orig_whole = TREE_OPERAND (t, 0);
4424 tree retval, fldval, utype, mask;
4425 bool fld_seen = false;
4426 HOST_WIDE_INT istart, isize;
4427 tree whole = cxx_eval_constant_expression (ctx, orig_whole,
4428 lval,
4429 non_constant_p, overflow_p);
4430 tree start, field, value;
4431 unsigned HOST_WIDE_INT i;
4433 if (whole == orig_whole)
4434 return t;
4435 /* Don't VERIFY_CONSTANT here; we only want to check that we got a
4436 CONSTRUCTOR. */
4437 if (!*non_constant_p
4438 && TREE_CODE (whole) != VECTOR_CST
4439 && TREE_CODE (whole) != CONSTRUCTOR)
4441 if (!ctx->quiet)
4442 error ("%qE is not a constant expression", orig_whole);
4443 *non_constant_p = true;
4445 if (*non_constant_p)
4446 return t;
4448 if (TREE_CODE (whole) == VECTOR_CST || !INTEGRAL_TYPE_P (TREE_TYPE (t)))
4450 if (tree r = fold_ternary (BIT_FIELD_REF, TREE_TYPE (t), whole,
4451 TREE_OPERAND (t, 1), TREE_OPERAND (t, 2)))
4452 return r;
4453 if (!ctx->quiet)
4454 error ("%qE is not a constant expression", orig_whole);
4455 *non_constant_p = true;
4456 return t;
4459 start = TREE_OPERAND (t, 2);
4460 istart = tree_to_shwi (start);
4461 isize = tree_to_shwi (TREE_OPERAND (t, 1));
4462 utype = TREE_TYPE (t);
4463 if (!TYPE_UNSIGNED (utype))
4464 utype = build_nonstandard_integer_type (TYPE_PRECISION (utype), 1);
4465 retval = build_int_cst (utype, 0);
4466 FOR_EACH_CONSTRUCTOR_ELT (CONSTRUCTOR_ELTS (whole), i, field, value)
4468 tree bitpos = bit_position (field);
4469 STRIP_ANY_LOCATION_WRAPPER (value);
4470 if (bitpos == start && DECL_SIZE (field) == TREE_OPERAND (t, 1))
4471 return value;
4472 if (TREE_CODE (TREE_TYPE (field)) == INTEGER_TYPE
4473 && TREE_CODE (value) == INTEGER_CST
4474 && tree_fits_shwi_p (bitpos)
4475 && tree_fits_shwi_p (DECL_SIZE (field)))
4477 HOST_WIDE_INT bit = tree_to_shwi (bitpos);
4478 HOST_WIDE_INT sz = tree_to_shwi (DECL_SIZE (field));
4479 HOST_WIDE_INT shift;
4480 if (bit >= istart && bit + sz <= istart + isize)
4482 fldval = fold_convert (utype, value);
4483 mask = build_int_cst_type (utype, -1);
4484 mask = fold_build2 (LSHIFT_EXPR, utype, mask,
4485 size_int (TYPE_PRECISION (utype) - sz));
4486 mask = fold_build2 (RSHIFT_EXPR, utype, mask,
4487 size_int (TYPE_PRECISION (utype) - sz));
4488 fldval = fold_build2 (BIT_AND_EXPR, utype, fldval, mask);
4489 shift = bit - istart;
4490 if (BYTES_BIG_ENDIAN)
4491 shift = TYPE_PRECISION (utype) - shift - sz;
4492 fldval = fold_build2 (LSHIFT_EXPR, utype, fldval,
4493 size_int (shift));
4494 retval = fold_build2 (BIT_IOR_EXPR, utype, retval, fldval);
4495 fld_seen = true;
4499 if (fld_seen)
4500 return fold_convert (TREE_TYPE (t), retval);
4501 gcc_unreachable ();
4502 return error_mark_node;
4505 /* Helper for cxx_eval_bit_cast.
4506 Check [bit.cast]/3 rules, bit_cast is constexpr only if the To and From
4507 types and types of all subobjects have is_union_v<T>, is_pointer_v<T>,
4508 is_member_pointer_v<T>, is_volatile_v<T> false and has no non-static
4509 data members of reference type. */
4511 static bool
4512 check_bit_cast_type (const constexpr_ctx *ctx, location_t loc, tree type,
4513 tree orig_type)
4515 if (TREE_CODE (type) == UNION_TYPE)
4517 if (!ctx->quiet)
4519 if (type == orig_type)
4520 error_at (loc, "%qs is not a constant expression because %qT is "
4521 "a union type", "__builtin_bit_cast", type);
4522 else
4523 error_at (loc, "%qs is not a constant expression because %qT "
4524 "contains a union type", "__builtin_bit_cast",
4525 orig_type);
4527 return true;
4529 if (TREE_CODE (type) == POINTER_TYPE)
4531 if (!ctx->quiet)
4533 if (type == orig_type)
4534 error_at (loc, "%qs is not a constant expression because %qT is "
4535 "a pointer type", "__builtin_bit_cast", type);
4536 else
4537 error_at (loc, "%qs is not a constant expression because %qT "
4538 "contains a pointer type", "__builtin_bit_cast",
4539 orig_type);
4541 return true;
4543 if (TREE_CODE (type) == REFERENCE_TYPE)
4545 if (!ctx->quiet)
4547 if (type == orig_type)
4548 error_at (loc, "%qs is not a constant expression because %qT is "
4549 "a reference type", "__builtin_bit_cast", type);
4550 else
4551 error_at (loc, "%qs is not a constant expression because %qT "
4552 "contains a reference type", "__builtin_bit_cast",
4553 orig_type);
4555 return true;
4557 if (TYPE_PTRMEM_P (type))
4559 if (!ctx->quiet)
4561 if (type == orig_type)
4562 error_at (loc, "%qs is not a constant expression because %qT is "
4563 "a pointer to member type", "__builtin_bit_cast",
4564 type);
4565 else
4566 error_at (loc, "%qs is not a constant expression because %qT "
4567 "contains a pointer to member type",
4568 "__builtin_bit_cast", orig_type);
4570 return true;
4572 if (TYPE_VOLATILE (type))
4574 if (!ctx->quiet)
4576 if (type == orig_type)
4577 error_at (loc, "%qs is not a constant expression because %qT is "
4578 "volatile", "__builtin_bit_cast", type);
4579 else
4580 error_at (loc, "%qs is not a constant expression because %qT "
4581 "contains a volatile subobject",
4582 "__builtin_bit_cast", orig_type);
4584 return true;
4586 if (TREE_CODE (type) == RECORD_TYPE)
4587 for (tree field = TYPE_FIELDS (type); field; field = DECL_CHAIN (field))
4588 if (TREE_CODE (field) == FIELD_DECL
4589 && check_bit_cast_type (ctx, loc, TREE_TYPE (field), orig_type))
4590 return true;
4591 return false;
4594 /* Helper function for cxx_eval_bit_cast. For unsigned char or
4595 std::byte members of CONSTRUCTOR (recursively) if they contain
4596 some indeterminate bits (as set in MASK), remove the ctor elts,
4597 mark the CONSTRUCTOR as CONSTRUCTOR_NO_CLEARING and clear the
4598 bits in MASK. */
4600 static void
4601 clear_uchar_or_std_byte_in_mask (location_t loc, tree t, unsigned char *mask)
4603 if (TREE_CODE (t) != CONSTRUCTOR)
4604 return;
4606 unsigned i, j = 0;
4607 tree index, value;
4608 FOR_EACH_CONSTRUCTOR_ELT (CONSTRUCTOR_ELTS (t), i, index, value)
4610 tree type = TREE_TYPE (value);
4611 if (TREE_CODE (TREE_TYPE (t)) != ARRAY_TYPE
4612 && DECL_BIT_FIELD_TYPE (index) != NULL_TREE)
4614 if (is_byte_access_type_not_plain_char (DECL_BIT_FIELD_TYPE (index)))
4616 HOST_WIDE_INT fldsz = TYPE_PRECISION (TREE_TYPE (index));
4617 gcc_assert (fldsz != 0);
4618 HOST_WIDE_INT pos = int_byte_position (index);
4619 HOST_WIDE_INT bpos
4620 = tree_to_uhwi (DECL_FIELD_BIT_OFFSET (index));
4621 bpos %= BITS_PER_UNIT;
4622 HOST_WIDE_INT end
4623 = ROUND_UP (bpos + fldsz, BITS_PER_UNIT) / BITS_PER_UNIT;
4624 gcc_assert (end == 1 || end == 2);
4625 unsigned char *p = mask + pos;
4626 unsigned char mask_save[2];
4627 mask_save[0] = mask[pos];
4628 mask_save[1] = end == 2 ? mask[pos + 1] : 0;
4629 if (BYTES_BIG_ENDIAN != WORDS_BIG_ENDIAN)
4630 sorry_at (loc, "PDP11 bit-field handling unsupported"
4631 " in %qs", "__builtin_bit_cast");
4632 else if (BYTES_BIG_ENDIAN)
4634 /* Big endian. */
4635 if (bpos + fldsz <= BITS_PER_UNIT)
4636 *p &= ~(((1 << fldsz) - 1)
4637 << (BITS_PER_UNIT - bpos - fldsz));
4638 else
4640 gcc_assert (bpos);
4641 *p &= ~(((1U << BITS_PER_UNIT) - 1) >> bpos);
4642 p++;
4643 fldsz -= BITS_PER_UNIT - bpos;
4644 gcc_assert (fldsz && fldsz < BITS_PER_UNIT);
4645 *p &= ((1U << BITS_PER_UNIT) - 1) >> fldsz;
4648 else
4650 /* Little endian. */
4651 if (bpos + fldsz <= BITS_PER_UNIT)
4652 *p &= ~(((1 << fldsz) - 1) << bpos);
4653 else
4655 gcc_assert (bpos);
4656 *p &= ~(((1 << BITS_PER_UNIT) - 1) << bpos);
4657 p++;
4658 fldsz -= BITS_PER_UNIT - bpos;
4659 gcc_assert (fldsz && fldsz < BITS_PER_UNIT);
4660 *p &= ~((1 << fldsz) - 1);
4663 if (mask_save[0] != mask[pos]
4664 || (end == 2 && mask_save[1] != mask[pos + 1]))
4666 CONSTRUCTOR_NO_CLEARING (t) = 1;
4667 continue;
4671 else if (is_byte_access_type_not_plain_char (type))
4673 HOST_WIDE_INT pos;
4674 if (TREE_CODE (TREE_TYPE (t)) == ARRAY_TYPE)
4675 pos = tree_to_shwi (index);
4676 else
4677 pos = int_byte_position (index);
4678 if (mask[pos])
4680 CONSTRUCTOR_NO_CLEARING (t) = 1;
4681 mask[pos] = 0;
4682 continue;
4685 if (TREE_CODE (value) == CONSTRUCTOR)
4687 HOST_WIDE_INT pos;
4688 if (TREE_CODE (TREE_TYPE (t)) == ARRAY_TYPE)
4689 pos = tree_to_shwi (index)
4690 * tree_to_shwi (TYPE_SIZE_UNIT (TREE_TYPE (TREE_TYPE (t))));
4691 else
4692 pos = int_byte_position (index);
4693 clear_uchar_or_std_byte_in_mask (loc, value, mask + pos);
4695 if (i != j)
4697 CONSTRUCTOR_ELT (t, j)->index = index;
4698 CONSTRUCTOR_ELT (t, j)->value = value;
4700 ++j;
4702 if (CONSTRUCTOR_NELTS (t) != j)
4703 vec_safe_truncate (CONSTRUCTOR_ELTS (t), j);
4706 /* Subroutine of cxx_eval_constant_expression.
4707 Attempt to evaluate a BIT_CAST_EXPR. */
4709 static tree
4710 cxx_eval_bit_cast (const constexpr_ctx *ctx, tree t, bool *non_constant_p,
4711 bool *overflow_p)
4713 if (check_bit_cast_type (ctx, EXPR_LOCATION (t), TREE_TYPE (t),
4714 TREE_TYPE (t))
4715 || check_bit_cast_type (ctx, cp_expr_loc_or_loc (TREE_OPERAND (t, 0),
4716 EXPR_LOCATION (t)),
4717 TREE_TYPE (TREE_OPERAND (t, 0)),
4718 TREE_TYPE (TREE_OPERAND (t, 0))))
4720 *non_constant_p = true;
4721 return t;
4724 tree op = cxx_eval_constant_expression (ctx, TREE_OPERAND (t, 0), vc_prvalue,
4725 non_constant_p, overflow_p);
4726 if (*non_constant_p)
4727 return t;
4729 location_t loc = EXPR_LOCATION (t);
4730 if (BITS_PER_UNIT != 8 || CHAR_BIT != 8)
4732 if (!ctx->quiet)
4733 sorry_at (loc, "%qs cannot be constant evaluated on the target",
4734 "__builtin_bit_cast");
4735 *non_constant_p = true;
4736 return t;
4739 if (!tree_fits_shwi_p (TYPE_SIZE_UNIT (TREE_TYPE (t))))
4741 if (!ctx->quiet)
4742 sorry_at (loc, "%qs cannot be constant evaluated because the "
4743 "type is too large", "__builtin_bit_cast");
4744 *non_constant_p = true;
4745 return t;
4748 HOST_WIDE_INT len = tree_to_shwi (TYPE_SIZE_UNIT (TREE_TYPE (t)));
4749 if (len < 0 || (int) len != len)
4751 if (!ctx->quiet)
4752 sorry_at (loc, "%qs cannot be constant evaluated because the "
4753 "type is too large", "__builtin_bit_cast");
4754 *non_constant_p = true;
4755 return t;
4758 unsigned char buf[64];
4759 unsigned char *ptr, *mask;
4760 size_t alen = (size_t) len * 2;
4761 if (alen <= sizeof (buf))
4762 ptr = buf;
4763 else
4764 ptr = XNEWVEC (unsigned char, alen);
4765 mask = ptr + (size_t) len;
4766 /* At the beginning consider everything indeterminate. */
4767 memset (mask, ~0, (size_t) len);
4769 if (native_encode_initializer (op, ptr, len, 0, mask) != len)
4771 if (!ctx->quiet)
4772 sorry_at (loc, "%qs cannot be constant evaluated because the "
4773 "argument cannot be encoded", "__builtin_bit_cast");
4774 *non_constant_p = true;
4775 if (ptr != buf)
4776 XDELETE (ptr);
4777 return t;
4780 tree r = NULL_TREE;
4781 if (can_native_interpret_type_p (TREE_TYPE (t)))
4783 r = native_interpret_expr (TREE_TYPE (t), ptr, len);
4784 if (is_byte_access_type_not_plain_char (TREE_TYPE (t)))
4786 gcc_assert (len == 1);
4787 if (mask[0])
4789 memset (mask, 0, len);
4790 r = build_constructor (TREE_TYPE (r), NULL);
4791 CONSTRUCTOR_NO_CLEARING (r) = 1;
4795 else if (TREE_CODE (TREE_TYPE (t)) == RECORD_TYPE)
4797 r = native_interpret_aggregate (TREE_TYPE (t), ptr, 0, len);
4798 if (r != NULL_TREE)
4800 clear_type_padding_in_mask (TREE_TYPE (t), mask);
4801 clear_uchar_or_std_byte_in_mask (loc, r, mask);
4805 if (r != NULL_TREE)
4807 for (int i = 0; i < len; i++)
4808 if (mask[i])
4810 if (!ctx->quiet)
4811 error_at (loc, "%qs accessing uninitialized byte at offset %d",
4812 "__builtin_bit_cast", i);
4813 *non_constant_p = true;
4814 r = t;
4815 break;
4817 if (ptr != buf)
4818 XDELETE (ptr);
4819 return r;
4822 if (!ctx->quiet)
4823 sorry_at (loc, "%qs cannot be constant evaluated because the "
4824 "argument cannot be interpreted", "__builtin_bit_cast");
4825 *non_constant_p = true;
4826 if (ptr != buf)
4827 XDELETE (ptr);
4828 return t;
4831 /* Subroutine of cxx_eval_constant_expression.
4832 Evaluate a short-circuited logical expression T in the context
4833 of a given constexpr CALL. BAILOUT_VALUE is the value for
4834 early return. CONTINUE_VALUE is used here purely for
4835 sanity check purposes. */
4837 static tree
4838 cxx_eval_logical_expression (const constexpr_ctx *ctx, tree t,
4839 tree bailout_value, tree continue_value,
4840 bool *non_constant_p, bool *overflow_p)
4842 tree r;
4843 tree lhs = cxx_eval_constant_expression (ctx, TREE_OPERAND (t, 0),
4844 vc_prvalue, non_constant_p,
4845 overflow_p);
4846 VERIFY_CONSTANT (lhs);
4847 if (tree_int_cst_equal (lhs, bailout_value))
4848 return lhs;
4849 gcc_assert (tree_int_cst_equal (lhs, continue_value));
4850 r = cxx_eval_constant_expression (ctx, TREE_OPERAND (t, 1),
4851 vc_prvalue, non_constant_p,
4852 overflow_p);
4853 VERIFY_CONSTANT (r);
4854 return r;
4857 /* REF is a COMPONENT_REF designating a particular field. V is a vector of
4858 CONSTRUCTOR elements to initialize (part of) an object containing that
4859 field. Return a pointer to the constructor_elt corresponding to the
4860 initialization of the field. */
4862 static constructor_elt *
4863 base_field_constructor_elt (vec<constructor_elt, va_gc> *v, tree ref)
4865 tree aggr = TREE_OPERAND (ref, 0);
4866 tree field = TREE_OPERAND (ref, 1);
4867 HOST_WIDE_INT i;
4868 constructor_elt *ce;
4870 gcc_assert (TREE_CODE (ref) == COMPONENT_REF);
4872 if (TREE_CODE (aggr) == COMPONENT_REF)
4874 constructor_elt *base_ce
4875 = base_field_constructor_elt (v, aggr);
4876 v = CONSTRUCTOR_ELTS (base_ce->value);
4879 for (i = 0; vec_safe_iterate (v, i, &ce); ++i)
4880 if (ce->index == field)
4881 return ce;
4883 gcc_unreachable ();
4884 return NULL;
4887 /* Some of the expressions fed to the constexpr mechanism are calls to
4888 constructors, which have type void. In that case, return the type being
4889 initialized by the constructor. */
4891 static tree
4892 initialized_type (tree t)
4894 if (TYPE_P (t))
4895 return t;
4896 tree type = TREE_TYPE (t);
4897 if (TREE_CODE (t) == CALL_EXPR)
4899 /* A constructor call has void type, so we need to look deeper. */
4900 tree fn = get_function_named_in_call (t);
4901 if (fn && TREE_CODE (fn) == FUNCTION_DECL
4902 && DECL_CXX_CONSTRUCTOR_P (fn))
4903 type = DECL_CONTEXT (fn);
4905 else if (TREE_CODE (t) == COMPOUND_EXPR)
4906 return initialized_type (TREE_OPERAND (t, 1));
4907 else if (TREE_CODE (t) == AGGR_INIT_EXPR)
4908 type = TREE_TYPE (AGGR_INIT_EXPR_SLOT (t));
4909 return cv_unqualified (type);
4912 /* We're about to initialize element INDEX of an array or class from VALUE.
4913 Set up NEW_CTX appropriately by adjusting .object to refer to the
4914 subobject and creating a new CONSTRUCTOR if the element is itself
4915 a class or array. */
4917 static void
4918 init_subob_ctx (const constexpr_ctx *ctx, constexpr_ctx &new_ctx,
4919 tree index, tree &value)
4921 new_ctx = *ctx;
4923 if (index && TREE_CODE (index) != INTEGER_CST
4924 && TREE_CODE (index) != FIELD_DECL
4925 && TREE_CODE (index) != RANGE_EXPR)
4926 /* This won't have an element in the new CONSTRUCTOR. */
4927 return;
4929 tree type = initialized_type (value);
4930 if (!AGGREGATE_TYPE_P (type) && !VECTOR_TYPE_P (type))
4931 /* A non-aggregate member doesn't get its own CONSTRUCTOR. */
4932 return;
4933 if (VECTOR_TYPE_P (type)
4934 && VECTOR_TYPE_P (TREE_TYPE (ctx->ctor))
4935 && index == NULL_TREE)
4936 /* A vector inside of a vector CONSTRUCTOR, e.g. when a larger
4937 vector is constructed from smaller vectors, doesn't get its own
4938 CONSTRUCTOR either. */
4939 return;
4941 /* The sub-aggregate initializer might contain a placeholder;
4942 update object to refer to the subobject and ctor to refer to
4943 the (newly created) sub-initializer. */
4944 if (ctx->object)
4946 if (index == NULL_TREE || TREE_CODE (index) == RANGE_EXPR)
4947 /* There's no well-defined subobject for this index. */
4948 new_ctx.object = NULL_TREE;
4949 else
4950 new_ctx.object = build_ctor_subob_ref (index, type, ctx->object);
4953 if (is_empty_class (type))
4954 /* Leave ctor null for an empty subobject, they aren't represented in the
4955 result of evaluation. */
4956 new_ctx.ctor = NULL_TREE;
4957 else
4959 tree elt = build_constructor (type, NULL);
4960 CONSTRUCTOR_NO_CLEARING (elt) = true;
4961 new_ctx.ctor = elt;
4964 if (TREE_CODE (value) == TARGET_EXPR)
4965 /* Avoid creating another CONSTRUCTOR when we expand the TARGET_EXPR. */
4966 value = TARGET_EXPR_INITIAL (value);
4969 /* We're about to process an initializer for a class or array TYPE. Make
4970 sure that CTX is set up appropriately. */
4972 static void
4973 verify_ctor_sanity (const constexpr_ctx *ctx, tree type)
4975 /* We don't bother building a ctor for an empty base subobject. */
4976 if (is_empty_class (type))
4977 return;
4979 /* We're in the middle of an initializer that might involve placeholders;
4980 our caller should have created a CONSTRUCTOR for us to put the
4981 initializer into. We will either return that constructor or T. */
4982 gcc_assert (ctx->ctor);
4983 gcc_assert (same_type_ignoring_top_level_qualifiers_p
4984 (type, TREE_TYPE (ctx->ctor)));
4985 /* We used to check that ctx->ctor was empty, but that isn't the case when
4986 the object is zero-initialized before calling the constructor. */
4987 if (ctx->object)
4989 tree otype = TREE_TYPE (ctx->object);
4990 gcc_assert (same_type_ignoring_top_level_qualifiers_p (type, otype)
4991 /* Handle flexible array members. */
4992 || (TREE_CODE (otype) == ARRAY_TYPE
4993 && TYPE_DOMAIN (otype) == NULL_TREE
4994 && TREE_CODE (type) == ARRAY_TYPE
4995 && (same_type_ignoring_top_level_qualifiers_p
4996 (TREE_TYPE (type), TREE_TYPE (otype)))));
4998 gcc_assert (!ctx->object || !DECL_P (ctx->object)
4999 || ctx->global->get_value (ctx->object) == ctx->ctor);
5002 /* Subroutine of cxx_eval_constant_expression.
5003 The expression tree T denotes a C-style array or a C-style
5004 aggregate. Reduce it to a constant expression. */
5006 static tree
5007 cxx_eval_bare_aggregate (const constexpr_ctx *ctx, tree t,
5008 value_cat lval,
5009 bool *non_constant_p, bool *overflow_p)
5011 vec<constructor_elt, va_gc> *v = CONSTRUCTOR_ELTS (t);
5012 bool changed = false;
5013 gcc_assert (!BRACE_ENCLOSED_INITIALIZER_P (t));
5014 tree type = TREE_TYPE (t);
5016 constexpr_ctx new_ctx;
5017 if (TYPE_PTRMEMFUNC_P (type) || VECTOR_TYPE_P (type))
5019 /* We don't really need the ctx->ctor business for a PMF or
5020 vector, but it's simpler to use the same code. */
5021 new_ctx = *ctx;
5022 new_ctx.ctor = build_constructor (type, NULL);
5023 new_ctx.object = NULL_TREE;
5024 ctx = &new_ctx;
5026 verify_ctor_sanity (ctx, type);
5027 vec<constructor_elt, va_gc> **p = nullptr;
5028 if (ctx->ctor)
5030 p = &CONSTRUCTOR_ELTS (ctx->ctor);
5031 vec_alloc (*p, vec_safe_length (v));
5032 if (CONSTRUCTOR_PLACEHOLDER_BOUNDARY (t))
5033 CONSTRUCTOR_PLACEHOLDER_BOUNDARY (ctx->ctor) = 1;
5036 unsigned i;
5037 tree index, value;
5038 bool constant_p = true;
5039 bool side_effects_p = false;
5040 FOR_EACH_CONSTRUCTOR_ELT (v, i, index, value)
5042 tree orig_value = value;
5043 /* Like in cxx_eval_store_expression, omit entries for empty fields. */
5044 bool no_slot = TREE_CODE (type) == RECORD_TYPE && is_empty_field (index);
5045 init_subob_ctx (ctx, new_ctx, index, value);
5046 int pos_hint = -1;
5047 if (new_ctx.ctor != ctx->ctor && !no_slot)
5049 /* If we built a new CONSTRUCTOR, attach it now so that other
5050 initializers can refer to it. */
5051 constructor_elt *cep = get_or_insert_ctor_field (ctx->ctor, index);
5052 cep->value = new_ctx.ctor;
5053 pos_hint = cep - (*p)->begin();
5055 else if (TREE_CODE (type) == UNION_TYPE)
5056 /* Otherwise if we're constructing a non-aggregate union member, set
5057 the active union member now so that we can later detect and diagnose
5058 if its initializer attempts to activate another member. */
5059 get_or_insert_ctor_field (ctx->ctor, index);
5060 tree elt = cxx_eval_constant_expression (&new_ctx, value,
5061 lval,
5062 non_constant_p, overflow_p);
5063 /* Don't VERIFY_CONSTANT here. */
5064 if (ctx->quiet && *non_constant_p)
5065 break;
5066 if (elt != orig_value)
5067 changed = true;
5069 if (!TREE_CONSTANT (elt))
5070 constant_p = false;
5071 if (TREE_SIDE_EFFECTS (elt))
5072 side_effects_p = true;
5073 if (index && TREE_CODE (index) == COMPONENT_REF)
5075 /* This is an initialization of a vfield inside a base
5076 subaggregate that we already initialized; push this
5077 initialization into the previous initialization. */
5078 constructor_elt *inner = base_field_constructor_elt (*p, index);
5079 inner->value = elt;
5080 changed = true;
5082 else if (no_slot)
5083 /* This is an initializer for an empty field; now that we've
5084 checked that it's constant, we can ignore it. */
5085 changed = true;
5086 else if (index
5087 && (TREE_CODE (index) == NOP_EXPR
5088 || TREE_CODE (index) == POINTER_PLUS_EXPR))
5090 /* Old representation of empty bases. FIXME remove. */
5091 gcc_checking_assert (false);
5092 gcc_assert (is_empty_class (TREE_TYPE (TREE_TYPE (index))));
5093 changed = true;
5095 else
5097 if (TREE_CODE (type) == UNION_TYPE
5098 && (*p)->last().index != index)
5099 /* The initializer erroneously changed the active union member that
5100 we're initializing. */
5101 gcc_assert (*non_constant_p);
5102 else
5104 /* The initializer might have mutated the underlying CONSTRUCTOR,
5105 so recompute the location of the target constructer_elt. */
5106 constructor_elt *cep
5107 = get_or_insert_ctor_field (ctx->ctor, index, pos_hint);
5108 cep->value = elt;
5111 /* Adding or replacing an element might change the ctor's flags. */
5112 TREE_CONSTANT (ctx->ctor) = constant_p;
5113 TREE_SIDE_EFFECTS (ctx->ctor) = side_effects_p;
5116 if (*non_constant_p)
5117 return t;
5118 if (!changed)
5120 if (VECTOR_TYPE_P (type))
5121 t = fold (t);
5122 return t;
5124 t = ctx->ctor;
5125 if (!t)
5126 t = build_constructor (type, NULL);
5127 /* We're done building this CONSTRUCTOR, so now we can interpret an
5128 element without an explicit initializer as value-initialized. */
5129 CONSTRUCTOR_NO_CLEARING (t) = false;
5130 TREE_CONSTANT (t) = constant_p;
5131 TREE_SIDE_EFFECTS (t) = side_effects_p;
5132 if (VECTOR_TYPE_P (type))
5133 t = fold (t);
5134 return t;
5137 /* Subroutine of cxx_eval_constant_expression.
5138 The expression tree T is a VEC_INIT_EXPR which denotes the desired
5139 initialization of a non-static data member of array type. Reduce it to a
5140 CONSTRUCTOR.
5142 Note that apart from value-initialization (when VALUE_INIT is true),
5143 this is only intended to support value-initialization and the
5144 initializations done by defaulted constructors for classes with
5145 non-static data members of array type. In this case, VEC_INIT_EXPR_INIT
5146 will either be NULL_TREE for the default constructor, or a COMPONENT_REF
5147 for the copy/move constructor. */
5149 static tree
5150 cxx_eval_vec_init_1 (const constexpr_ctx *ctx, tree atype, tree init,
5151 bool value_init, value_cat lval,
5152 bool *non_constant_p, bool *overflow_p)
5154 tree elttype = TREE_TYPE (atype);
5155 verify_ctor_sanity (ctx, atype);
5156 vec<constructor_elt, va_gc> **p = &CONSTRUCTOR_ELTS (ctx->ctor);
5157 bool pre_init = false;
5158 unsigned HOST_WIDE_INT i;
5159 tsubst_flags_t complain = ctx->quiet ? tf_none : tf_warning_or_error;
5161 if (init && TREE_CODE (init) == CONSTRUCTOR)
5162 return cxx_eval_bare_aggregate (ctx, init, lval,
5163 non_constant_p, overflow_p);
5165 /* For the default constructor, build up a call to the default
5166 constructor of the element type. We only need to handle class types
5167 here, as for a constructor to be constexpr, all members must be
5168 initialized, which for a defaulted default constructor means they must
5169 be of a class type with a constexpr default constructor. */
5170 if (TREE_CODE (elttype) == ARRAY_TYPE)
5171 /* We only do this at the lowest level. */;
5172 else if (value_init)
5174 init = build_value_init (elttype, complain);
5175 pre_init = true;
5177 else if (!init)
5179 releasing_vec argvec;
5180 init = build_special_member_call (NULL_TREE, complete_ctor_identifier,
5181 &argvec, elttype, LOOKUP_NORMAL,
5182 complain);
5183 init = build_aggr_init_expr (elttype, init);
5184 pre_init = true;
5187 bool zeroed_out = false;
5188 if (!CONSTRUCTOR_NO_CLEARING (ctx->ctor))
5190 /* We're initializing an array object that had been zero-initialized
5191 earlier. Truncate ctx->ctor, and propagate its zeroed state by
5192 clearing CONSTRUCTOR_NO_CLEARING on each of the aggregate element
5193 initializers we append to it. */
5194 gcc_checking_assert (initializer_zerop (ctx->ctor));
5195 zeroed_out = true;
5196 vec_safe_truncate (*p, 0);
5199 tree nelts = get_array_or_vector_nelts (ctx, atype, non_constant_p,
5200 overflow_p);
5201 unsigned HOST_WIDE_INT max = tree_to_uhwi (nelts);
5202 for (i = 0; i < max; ++i)
5204 tree idx = build_int_cst (size_type_node, i);
5205 tree eltinit;
5206 bool reuse = false;
5207 constexpr_ctx new_ctx;
5208 init_subob_ctx (ctx, new_ctx, idx, pre_init ? init : elttype);
5209 if (new_ctx.ctor != ctx->ctor)
5211 if (zeroed_out)
5212 CONSTRUCTOR_NO_CLEARING (new_ctx.ctor) = false;
5213 CONSTRUCTOR_APPEND_ELT (*p, idx, new_ctx.ctor);
5215 if (TREE_CODE (elttype) == ARRAY_TYPE)
5217 /* A multidimensional array; recurse. */
5218 if (value_init || init == NULL_TREE)
5220 eltinit = NULL_TREE;
5221 reuse = i == 0;
5223 else
5224 eltinit = cp_build_array_ref (input_location, init, idx, complain);
5225 eltinit = cxx_eval_vec_init_1 (&new_ctx, elttype, eltinit, value_init,
5226 lval,
5227 non_constant_p, overflow_p);
5229 else if (pre_init)
5231 /* Initializing an element using value or default initialization
5232 we just pre-built above. */
5233 if (init == void_node)
5234 /* Trivial default-init, don't do anything to the CONSTRUCTOR. */
5235 return ctx->ctor;
5236 eltinit = cxx_eval_constant_expression (&new_ctx, init, lval,
5237 non_constant_p, overflow_p);
5238 reuse = i == 0;
5240 else
5242 /* Copying an element. */
5243 gcc_assert (same_type_ignoring_top_level_qualifiers_p
5244 (atype, TREE_TYPE (init)));
5245 eltinit = cp_build_array_ref (input_location, init, idx, complain);
5246 if (!lvalue_p (init))
5247 eltinit = move (eltinit);
5248 eltinit = force_rvalue (eltinit, complain);
5249 eltinit = cxx_eval_constant_expression (&new_ctx, eltinit, lval,
5250 non_constant_p, overflow_p);
5252 if (*non_constant_p)
5253 break;
5254 if (new_ctx.ctor != ctx->ctor)
5256 /* We appended this element above; update the value. */
5257 gcc_assert ((*p)->last().index == idx);
5258 (*p)->last().value = eltinit;
5260 else
5261 CONSTRUCTOR_APPEND_ELT (*p, idx, eltinit);
5262 /* Reuse the result of cxx_eval_constant_expression call
5263 from the first iteration to all others if it is a constant
5264 initializer that doesn't require relocations. */
5265 if (reuse
5266 && max > 1
5267 && (eltinit == NULL_TREE
5268 || (initializer_constant_valid_p (eltinit, TREE_TYPE (eltinit))
5269 == null_pointer_node)))
5271 if (new_ctx.ctor != ctx->ctor)
5272 eltinit = new_ctx.ctor;
5273 tree range = build2 (RANGE_EXPR, size_type_node,
5274 build_int_cst (size_type_node, 1),
5275 build_int_cst (size_type_node, max - 1));
5276 CONSTRUCTOR_APPEND_ELT (*p, range, unshare_constructor (eltinit));
5277 break;
5279 else if (i == 0)
5280 vec_safe_reserve (*p, max);
5283 if (!*non_constant_p)
5285 init = ctx->ctor;
5286 CONSTRUCTOR_NO_CLEARING (init) = false;
5288 return init;
5291 static tree
5292 cxx_eval_vec_init (const constexpr_ctx *ctx, tree t,
5293 value_cat lval,
5294 bool *non_constant_p, bool *overflow_p)
5296 tree atype = TREE_TYPE (t);
5297 tree init = VEC_INIT_EXPR_INIT (t);
5298 bool value_init = VEC_INIT_EXPR_VALUE_INIT (t);
5299 if (!init || !BRACE_ENCLOSED_INITIALIZER_P (init))
5301 else if (CONSTRUCTOR_NELTS (init) == 0
5302 && !CP_AGGREGATE_TYPE_P (strip_array_types (atype)))
5304 /* Handle {} as value-init. */
5305 init = NULL_TREE;
5306 value_init = true;
5308 else
5310 /* This is a more complicated case, like needing to loop over trailing
5311 elements; call build_vec_init and evaluate the result. */
5312 tsubst_flags_t complain = ctx->quiet ? tf_none : tf_warning_or_error;
5313 constexpr_ctx new_ctx = *ctx;
5314 if (!ctx->object)
5316 /* We want to have an initialization target for an VEC_INIT_EXPR.
5317 If we don't already have one in CTX, use the VEC_INIT_EXPR_SLOT. */
5318 new_ctx.object = VEC_INIT_EXPR_SLOT (t);
5319 tree ctor = new_ctx.ctor = build_constructor (atype, NULL);
5320 CONSTRUCTOR_NO_CLEARING (ctor) = true;
5321 ctx->global->put_value (new_ctx.object, ctor);
5322 ctx = &new_ctx;
5324 init = expand_vec_init_expr (ctx->object, t, complain);
5325 return cxx_eval_constant_expression (ctx, init, lval, non_constant_p,
5326 overflow_p);
5328 tree r = cxx_eval_vec_init_1 (ctx, atype, init, value_init,
5329 lval, non_constant_p, overflow_p);
5330 if (*non_constant_p)
5331 return t;
5332 else
5333 return r;
5336 /* Like same_type_ignoring_top_level_qualifiers_p, but also handle the case
5337 where the desired type is an array of unknown bounds because the variable
5338 has had its bounds deduced since the wrapping expression was created. */
5340 static bool
5341 same_type_ignoring_tlq_and_bounds_p (tree type1, tree type2)
5343 while (TREE_CODE (type1) == ARRAY_TYPE
5344 && TREE_CODE (type2) == ARRAY_TYPE
5345 && (!TYPE_DOMAIN (type1) || !TYPE_DOMAIN (type2)))
5347 type1 = TREE_TYPE (type1);
5348 type2 = TREE_TYPE (type2);
5350 return same_type_ignoring_top_level_qualifiers_p (type1, type2);
5353 /* Try to determine the currently active union member for an expression
5354 with UNION_TYPE. If it can be determined, return the FIELD_DECL,
5355 otherwise return NULL_TREE. */
5357 static tree
5358 cxx_union_active_member (const constexpr_ctx *ctx, tree t)
5360 constexpr_ctx new_ctx = *ctx;
5361 new_ctx.quiet = true;
5362 bool non_constant_p = false, overflow_p = false;
5363 tree ctor = cxx_eval_constant_expression (&new_ctx, t, vc_prvalue,
5364 &non_constant_p,
5365 &overflow_p);
5366 if (TREE_CODE (ctor) == CONSTRUCTOR
5367 && CONSTRUCTOR_NELTS (ctor) == 1
5368 && CONSTRUCTOR_ELT (ctor, 0)->index
5369 && TREE_CODE (CONSTRUCTOR_ELT (ctor, 0)->index) == FIELD_DECL)
5370 return CONSTRUCTOR_ELT (ctor, 0)->index;
5371 return NULL_TREE;
5374 /* Helper function for cxx_fold_indirect_ref_1, called recursively. */
5376 static tree
5377 cxx_fold_indirect_ref_1 (const constexpr_ctx *ctx, location_t loc, tree type,
5378 tree op, unsigned HOST_WIDE_INT off, bool *empty_base)
5380 tree optype = TREE_TYPE (op);
5381 unsigned HOST_WIDE_INT const_nunits;
5382 if (off == 0 && similar_type_p (optype, type))
5383 return op;
5384 else if (TREE_CODE (optype) == COMPLEX_TYPE
5385 && similar_type_p (type, TREE_TYPE (optype)))
5387 /* *(foo *)&complexfoo => __real__ complexfoo */
5388 if (off == 0)
5389 return build1_loc (loc, REALPART_EXPR, type, op);
5390 /* ((foo*)&complexfoo)[1] => __imag__ complexfoo */
5391 else if (tree_to_uhwi (TYPE_SIZE_UNIT (type)) == off)
5392 return build1_loc (loc, IMAGPART_EXPR, type, op);
5394 /* ((foo*)&vectorfoo)[x] => BIT_FIELD_REF<vectorfoo,...> */
5395 else if (VECTOR_TYPE_P (optype)
5396 && similar_type_p (type, TREE_TYPE (optype))
5397 && TYPE_VECTOR_SUBPARTS (optype).is_constant (&const_nunits))
5399 unsigned HOST_WIDE_INT part_width = tree_to_uhwi (TYPE_SIZE_UNIT (type));
5400 unsigned HOST_WIDE_INT max_offset = part_width * const_nunits;
5401 if (off < max_offset && off % part_width == 0)
5403 tree index = bitsize_int (off * BITS_PER_UNIT);
5404 return build3_loc (loc, BIT_FIELD_REF, type, op,
5405 TYPE_SIZE (type), index);
5408 /* ((foo *)&fooarray)[x] => fooarray[x] */
5409 else if (TREE_CODE (optype) == ARRAY_TYPE
5410 && tree_fits_uhwi_p (TYPE_SIZE_UNIT (TREE_TYPE (optype)))
5411 && !integer_zerop (TYPE_SIZE_UNIT (TREE_TYPE (optype))))
5413 tree type_domain = TYPE_DOMAIN (optype);
5414 tree min_val = size_zero_node;
5415 if (type_domain && TYPE_MIN_VALUE (type_domain))
5416 min_val = TYPE_MIN_VALUE (type_domain);
5417 unsigned HOST_WIDE_INT el_sz
5418 = tree_to_uhwi (TYPE_SIZE_UNIT (TREE_TYPE (optype)));
5419 unsigned HOST_WIDE_INT idx = off / el_sz;
5420 unsigned HOST_WIDE_INT rem = off % el_sz;
5421 if (tree_fits_uhwi_p (min_val))
5423 tree index = size_int (idx + tree_to_uhwi (min_val));
5424 op = build4_loc (loc, ARRAY_REF, TREE_TYPE (optype), op, index,
5425 NULL_TREE, NULL_TREE);
5426 return cxx_fold_indirect_ref_1 (ctx, loc, type, op, rem,
5427 empty_base);
5430 /* ((foo *)&struct_with_foo_field)[x] => COMPONENT_REF */
5431 else if (TREE_CODE (optype) == RECORD_TYPE
5432 || TREE_CODE (optype) == UNION_TYPE)
5434 if (TREE_CODE (optype) == UNION_TYPE)
5435 /* For unions prefer the currently active member. */
5436 if (tree field = cxx_union_active_member (ctx, op))
5438 unsigned HOST_WIDE_INT el_sz
5439 = tree_to_uhwi (TYPE_SIZE_UNIT (TREE_TYPE (field)));
5440 if (off < el_sz)
5442 tree cop = build3 (COMPONENT_REF, TREE_TYPE (field),
5443 op, field, NULL_TREE);
5444 if (tree ret = cxx_fold_indirect_ref_1 (ctx, loc, type, cop,
5445 off, empty_base))
5446 return ret;
5450 /* Handle conversion to an empty base class, which is represented with a
5451 NOP_EXPR. Do this before spelunking into the non-empty subobjects,
5452 which is likely to be a waste of time (109678). */
5453 if (is_empty_class (type)
5454 && CLASS_TYPE_P (optype)
5455 && lookup_base (optype, type, ba_any, NULL, tf_none, off))
5457 if (empty_base)
5458 *empty_base = true;
5459 return op;
5462 for (tree field = TYPE_FIELDS (optype);
5463 field; field = DECL_CHAIN (field))
5464 if (TREE_CODE (field) == FIELD_DECL
5465 && TREE_TYPE (field) != error_mark_node
5466 && tree_fits_uhwi_p (TYPE_SIZE_UNIT (TREE_TYPE (field))))
5468 tree pos = byte_position (field);
5469 if (!tree_fits_uhwi_p (pos))
5470 continue;
5471 unsigned HOST_WIDE_INT upos = tree_to_uhwi (pos);
5472 unsigned HOST_WIDE_INT el_sz
5473 = tree_to_uhwi (TYPE_SIZE_UNIT (TREE_TYPE (field)));
5474 if (upos <= off && off < upos + el_sz)
5476 tree cop = build3 (COMPONENT_REF, TREE_TYPE (field),
5477 op, field, NULL_TREE);
5478 if (tree ret = cxx_fold_indirect_ref_1 (ctx, loc, type, cop,
5479 off - upos,
5480 empty_base))
5481 return ret;
5486 return NULL_TREE;
5489 /* A less strict version of fold_indirect_ref_1, which requires cv-quals to
5490 match. We want to be less strict for simple *& folding; if we have a
5491 non-const temporary that we access through a const pointer, that should
5492 work. We handle this here rather than change fold_indirect_ref_1
5493 because we're dealing with things like ADDR_EXPR of INTEGER_CST which
5494 don't really make sense outside of constant expression evaluation. Also
5495 we want to allow folding to COMPONENT_REF, which could cause trouble
5496 with TBAA in fold_indirect_ref_1. */
5498 static tree
5499 cxx_fold_indirect_ref (const constexpr_ctx *ctx, location_t loc, tree type,
5500 tree op0, bool *empty_base /* = NULL*/)
5502 tree sub = op0;
5503 tree subtype;
5504 poly_uint64 const_op01;
5506 /* STRIP_NOPS, but stop if REINTERPRET_CAST_P. */
5507 while (CONVERT_EXPR_P (sub) || TREE_CODE (sub) == NON_LVALUE_EXPR
5508 || TREE_CODE (sub) == VIEW_CONVERT_EXPR)
5510 if (TREE_CODE (sub) == NOP_EXPR
5511 && REINTERPRET_CAST_P (sub))
5512 return NULL_TREE;
5513 sub = TREE_OPERAND (sub, 0);
5516 subtype = TREE_TYPE (sub);
5517 if (!INDIRECT_TYPE_P (subtype))
5518 return NULL_TREE;
5520 /* Canonicalizes the given OBJ/OFF pair by iteratively absorbing
5521 the innermost component into the offset until it would make the
5522 offset positive, so that cxx_fold_indirect_ref_1 can identify
5523 more folding opportunities. */
5524 auto canonicalize_obj_off = [] (tree& obj, tree& off) {
5525 while (TREE_CODE (obj) == COMPONENT_REF
5526 && (tree_int_cst_sign_bit (off) || integer_zerop (off)))
5528 tree field = TREE_OPERAND (obj, 1);
5529 tree pos = byte_position (field);
5530 if (integer_zerop (off) && integer_nonzerop (pos))
5531 /* If the offset is already 0, keep going as long as the
5532 component is at position 0. */
5533 break;
5534 off = int_const_binop (PLUS_EXPR, off, pos);
5535 obj = TREE_OPERAND (obj, 0);
5539 if (TREE_CODE (sub) == ADDR_EXPR)
5541 tree op = TREE_OPERAND (sub, 0);
5542 tree optype = TREE_TYPE (op);
5544 /* *&CONST_DECL -> to the value of the const decl. */
5545 if (TREE_CODE (op) == CONST_DECL)
5546 return DECL_INITIAL (op);
5547 /* *&p => p; make sure to handle *&"str"[cst] here. */
5548 if (similar_type_p (optype, type))
5550 tree fop = fold_read_from_constant_string (op);
5551 if (fop)
5552 return fop;
5553 else
5554 return op;
5556 else
5558 tree off = integer_zero_node;
5559 canonicalize_obj_off (op, off);
5560 gcc_assert (integer_zerop (off));
5561 return cxx_fold_indirect_ref_1 (ctx, loc, type, op, 0, empty_base);
5564 else if (TREE_CODE (sub) == POINTER_PLUS_EXPR
5565 && tree_fits_uhwi_p (TREE_OPERAND (sub, 1)))
5567 tree op00 = TREE_OPERAND (sub, 0);
5568 tree off = TREE_OPERAND (sub, 1);
5570 STRIP_NOPS (op00);
5571 if (TREE_CODE (op00) == ADDR_EXPR)
5573 tree obj = TREE_OPERAND (op00, 0);
5574 canonicalize_obj_off (obj, off);
5575 return cxx_fold_indirect_ref_1 (ctx, loc, type, obj,
5576 tree_to_uhwi (off), empty_base);
5579 /* *(foo *)fooarrptr => (*fooarrptr)[0] */
5580 else if (TREE_CODE (TREE_TYPE (subtype)) == ARRAY_TYPE
5581 && similar_type_p (type, TREE_TYPE (TREE_TYPE (subtype))))
5583 tree type_domain;
5584 tree min_val = size_zero_node;
5585 tree newsub
5586 = cxx_fold_indirect_ref (ctx, loc, TREE_TYPE (subtype), sub, NULL);
5587 if (newsub)
5588 sub = newsub;
5589 else
5590 sub = build1_loc (loc, INDIRECT_REF, TREE_TYPE (subtype), sub);
5591 type_domain = TYPE_DOMAIN (TREE_TYPE (sub));
5592 if (type_domain && TYPE_MIN_VALUE (type_domain))
5593 min_val = TYPE_MIN_VALUE (type_domain);
5594 return build4_loc (loc, ARRAY_REF, type, sub, min_val, NULL_TREE,
5595 NULL_TREE);
5598 return NULL_TREE;
5601 static tree
5602 cxx_eval_indirect_ref (const constexpr_ctx *ctx, tree t,
5603 value_cat lval,
5604 bool *non_constant_p, bool *overflow_p)
5606 tree orig_op0 = TREE_OPERAND (t, 0);
5607 bool empty_base = false;
5609 /* We can handle a MEM_REF like an INDIRECT_REF, if MEM_REF's second
5610 operand is an integer-zero. Otherwise reject the MEM_REF for now. */
5612 if (TREE_CODE (t) == MEM_REF
5613 && (!TREE_OPERAND (t, 1) || !integer_zerop (TREE_OPERAND (t, 1))))
5615 gcc_assert (ctx->quiet);
5616 *non_constant_p = true;
5617 return t;
5620 /* First try to simplify it directly. */
5621 tree r = cxx_fold_indirect_ref (ctx, EXPR_LOCATION (t), TREE_TYPE (t),
5622 orig_op0, &empty_base);
5623 if (!r)
5625 /* If that didn't work, evaluate the operand first. */
5626 tree op0 = cxx_eval_constant_expression (ctx, orig_op0,
5627 vc_prvalue, non_constant_p,
5628 overflow_p);
5629 /* Don't VERIFY_CONSTANT here. */
5630 if (*non_constant_p)
5631 return t;
5633 if (!lval && integer_zerop (op0))
5635 if (!ctx->quiet)
5636 error ("dereferencing a null pointer");
5637 *non_constant_p = true;
5638 return t;
5641 r = cxx_fold_indirect_ref (ctx, EXPR_LOCATION (t), TREE_TYPE (t), op0,
5642 &empty_base);
5643 if (r == NULL_TREE)
5645 /* We couldn't fold to a constant value. Make sure it's not
5646 something we should have been able to fold. */
5647 tree sub = op0;
5648 STRIP_NOPS (sub);
5649 if (TREE_CODE (sub) == ADDR_EXPR)
5651 gcc_assert (!similar_type_p
5652 (TREE_TYPE (TREE_TYPE (sub)), TREE_TYPE (t)));
5653 /* DR 1188 says we don't have to deal with this. */
5654 if (!ctx->quiet)
5655 error_at (cp_expr_loc_or_input_loc (t),
5656 "accessing value of %qE through a %qT glvalue in a "
5657 "constant expression", build_fold_indirect_ref (sub),
5658 TREE_TYPE (t));
5659 *non_constant_p = true;
5660 return t;
5663 if (lval == vc_glvalue && op0 != orig_op0)
5664 return build1 (INDIRECT_REF, TREE_TYPE (t), op0);
5665 if (!lval)
5666 VERIFY_CONSTANT (t);
5667 return t;
5671 r = cxx_eval_constant_expression (ctx, r,
5672 lval, non_constant_p, overflow_p);
5673 if (*non_constant_p)
5674 return t;
5676 /* If we're pulling out the value of an empty base, just return an empty
5677 CONSTRUCTOR. */
5678 if (empty_base && !lval)
5680 r = build_constructor (TREE_TYPE (t), NULL);
5681 TREE_CONSTANT (r) = true;
5684 return r;
5687 /* Complain about R, a VAR_DECL, not being usable in a constant expression.
5688 FUNDEF_P is true if we're checking a constexpr function body.
5689 Shared between potential_constant_expression and
5690 cxx_eval_constant_expression. */
5692 static void
5693 non_const_var_error (location_t loc, tree r, bool fundef_p)
5695 auto_diagnostic_group d;
5696 tree type = TREE_TYPE (r);
5697 if (DECL_NAME (r) == heap_uninit_identifier
5698 || DECL_NAME (r) == heap_identifier
5699 || DECL_NAME (r) == heap_vec_uninit_identifier
5700 || DECL_NAME (r) == heap_vec_identifier)
5702 if (constexpr_error (loc, fundef_p, "the content of uninitialized "
5703 "storage is not usable in a constant expression"))
5704 inform (DECL_SOURCE_LOCATION (r), "allocated here");
5705 return;
5707 if (DECL_NAME (r) == heap_deleted_identifier)
5709 if (constexpr_error (loc, fundef_p, "use of allocated storage after "
5710 "deallocation in a constant expression"))
5711 inform (DECL_SOURCE_LOCATION (r), "allocated here");
5712 return;
5714 if (!constexpr_error (loc, fundef_p, "the value of %qD is not usable in "
5715 "a constant expression", r))
5716 return;
5717 /* Avoid error cascade. */
5718 if (DECL_INITIAL (r) == error_mark_node)
5719 return;
5720 if (DECL_DECLARED_CONSTEXPR_P (r))
5721 inform (DECL_SOURCE_LOCATION (r),
5722 "%qD used in its own initializer", r);
5723 else if (INTEGRAL_OR_ENUMERATION_TYPE_P (type))
5725 if (!CP_TYPE_CONST_P (type))
5726 inform (DECL_SOURCE_LOCATION (r),
5727 "%q#D is not const", r);
5728 else if (CP_TYPE_VOLATILE_P (type))
5729 inform (DECL_SOURCE_LOCATION (r),
5730 "%q#D is volatile", r);
5731 else if (!DECL_INITIAL (r)
5732 || !TREE_CONSTANT (DECL_INITIAL (r))
5733 || !DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (r))
5734 inform (DECL_SOURCE_LOCATION (r),
5735 "%qD was not initialized with a constant "
5736 "expression", r);
5737 else
5738 gcc_unreachable ();
5740 else if (TYPE_REF_P (type))
5741 inform (DECL_SOURCE_LOCATION (r),
5742 "%qD was not initialized with a constant "
5743 "expression", r);
5744 else
5746 if (cxx_dialect >= cxx11 && !DECL_DECLARED_CONSTEXPR_P (r))
5747 inform (DECL_SOURCE_LOCATION (r),
5748 "%qD was not declared %<constexpr%>", r);
5749 else
5750 inform (DECL_SOURCE_LOCATION (r),
5751 "%qD does not have integral or enumeration type",
5756 /* Subroutine of cxx_eval_constant_expression.
5757 Like cxx_eval_unary_expression, except for trinary expressions. */
5759 static tree
5760 cxx_eval_trinary_expression (const constexpr_ctx *ctx, tree t,
5761 value_cat lval,
5762 bool *non_constant_p, bool *overflow_p)
5764 int i;
5765 tree args[3];
5766 tree val;
5768 for (i = 0; i < 3; i++)
5770 args[i] = cxx_eval_constant_expression (ctx, TREE_OPERAND (t, i),
5771 lval,
5772 non_constant_p, overflow_p);
5773 VERIFY_CONSTANT (args[i]);
5776 val = fold_ternary_loc (EXPR_LOCATION (t), TREE_CODE (t), TREE_TYPE (t),
5777 args[0], args[1], args[2]);
5778 if (val == NULL_TREE)
5779 return t;
5780 VERIFY_CONSTANT (val);
5781 return val;
5784 /* True if T was declared in a function declared to be constexpr, and
5785 therefore potentially constant in C++14. */
5787 bool
5788 var_in_constexpr_fn (tree t)
5790 tree ctx = DECL_CONTEXT (t);
5791 return (ctx && TREE_CODE (ctx) == FUNCTION_DECL
5792 && DECL_DECLARED_CONSTEXPR_P (ctx));
5795 /* True if a function might be constexpr: either a function that was
5796 declared constexpr, or a C++17 lambda op(). */
5798 bool
5799 maybe_constexpr_fn (tree t)
5801 return (DECL_DECLARED_CONSTEXPR_P (t)
5802 || (cxx_dialect >= cxx17 && LAMBDA_FUNCTION_P (t))
5803 || (flag_implicit_constexpr
5804 && DECL_DECLARED_INLINE_P (STRIP_TEMPLATE (t))));
5807 /* True if T was declared in a function that might be constexpr: either a
5808 function that was declared constexpr, or a C++17 lambda op(). */
5810 bool
5811 var_in_maybe_constexpr_fn (tree t)
5813 return (DECL_FUNCTION_SCOPE_P (t)
5814 && maybe_constexpr_fn (DECL_CONTEXT (t)));
5817 /* We're assigning INIT to TARGET. In do_build_copy_constructor and
5818 build_over_call we implement trivial copy of a class with tail padding using
5819 assignment of character arrays, which is valid in normal code, but not in
5820 constexpr evaluation. We don't need to worry about clobbering tail padding
5821 in constexpr evaluation, so strip the type punning. */
5823 static void
5824 maybe_simplify_trivial_copy (tree &target, tree &init)
5826 if (TREE_CODE (target) == MEM_REF
5827 && TREE_CODE (init) == MEM_REF
5828 && TREE_TYPE (target) == TREE_TYPE (init)
5829 && TREE_CODE (TREE_TYPE (target)) == ARRAY_TYPE
5830 && TREE_TYPE (TREE_TYPE (target)) == unsigned_char_type_node)
5832 target = build_fold_indirect_ref (TREE_OPERAND (target, 0));
5833 init = build_fold_indirect_ref (TREE_OPERAND (init, 0));
5837 /* Returns true if REF, which is a COMPONENT_REF, has any fields
5838 of constant type. This does not check for 'mutable', so the
5839 caller is expected to be mindful of that. */
5841 static bool
5842 cref_has_const_field (tree ref)
5844 while (TREE_CODE (ref) == COMPONENT_REF)
5846 if (CP_TYPE_CONST_P (TREE_TYPE (TREE_OPERAND (ref, 1))))
5847 return true;
5848 ref = TREE_OPERAND (ref, 0);
5850 return false;
5853 /* Return true if we are modifying something that is const during constant
5854 expression evaluation. CODE is the code of the statement, OBJ is the
5855 object in question, MUTABLE_P is true if one of the subobjects were
5856 declared mutable. */
5858 static bool
5859 modifying_const_object_p (tree_code code, tree obj, bool mutable_p)
5861 /* If this is initialization, there's no problem. */
5862 if (code != MODIFY_EXPR)
5863 return false;
5865 /* [basic.type.qualifier] "A const object is an object of type
5866 const T or a non-mutable subobject of a const object." */
5867 if (mutable_p)
5868 return false;
5870 if (TREE_READONLY (obj))
5871 return true;
5873 if (CP_TYPE_CONST_P (TREE_TYPE (obj)))
5875 /* Although a COMPONENT_REF may have a const type, we should
5876 only consider it modifying a const object when any of the
5877 field components is const. This can happen when using
5878 constructs such as const_cast<const T &>(m), making something
5879 const even though it wasn't declared const. */
5880 if (TREE_CODE (obj) == COMPONENT_REF)
5881 return cref_has_const_field (obj);
5882 else
5883 return true;
5886 return false;
5889 /* Evaluate an INIT_EXPR or MODIFY_EXPR. */
5891 static tree
5892 cxx_eval_store_expression (const constexpr_ctx *ctx, tree t,
5893 value_cat lval,
5894 bool *non_constant_p, bool *overflow_p)
5896 constexpr_ctx new_ctx = *ctx;
5898 tree init = TREE_OPERAND (t, 1);
5899 if (TREE_CLOBBER_P (init))
5900 /* Just ignore clobbers. */
5901 return void_node;
5903 /* First we figure out where we're storing to. */
5904 tree target = TREE_OPERAND (t, 0);
5906 maybe_simplify_trivial_copy (target, init);
5908 tree type = TREE_TYPE (target);
5909 bool preeval = SCALAR_TYPE_P (type) || TREE_CODE (t) == MODIFY_EXPR;
5910 if (preeval)
5912 /* Evaluate the value to be stored without knowing what object it will be
5913 stored in, so that any side-effects happen first. */
5914 if (!SCALAR_TYPE_P (type))
5915 new_ctx.ctor = new_ctx.object = NULL_TREE;
5916 init = cxx_eval_constant_expression (&new_ctx, init, vc_prvalue,
5917 non_constant_p, overflow_p);
5918 if (*non_constant_p)
5919 return t;
5922 bool evaluated = false;
5923 if (lval == vc_glvalue)
5925 /* If we want to return a reference to the target, we need to evaluate it
5926 as a whole; otherwise, only evaluate the innermost piece to avoid
5927 building up unnecessary *_REFs. */
5928 target = cxx_eval_constant_expression (ctx, target, lval,
5929 non_constant_p, overflow_p);
5930 evaluated = true;
5931 if (*non_constant_p)
5932 return t;
5935 /* Find the underlying variable. */
5936 releasing_vec refs;
5937 tree object = NULL_TREE;
5938 /* If we're modifying a const object, save it. */
5939 tree const_object_being_modified = NULL_TREE;
5940 bool mutable_p = false;
5941 for (tree probe = target; object == NULL_TREE; )
5943 switch (TREE_CODE (probe))
5945 case BIT_FIELD_REF:
5946 case COMPONENT_REF:
5947 case ARRAY_REF:
5949 tree ob = TREE_OPERAND (probe, 0);
5950 tree elt = TREE_OPERAND (probe, 1);
5951 if (TREE_CODE (elt) == FIELD_DECL && DECL_MUTABLE_P (elt))
5952 mutable_p = true;
5953 if (TREE_CODE (probe) == ARRAY_REF)
5955 elt = eval_and_check_array_index (ctx, probe, false,
5956 non_constant_p, overflow_p);
5957 if (*non_constant_p)
5958 return t;
5960 /* We don't check modifying_const_object_p for ARRAY_REFs. Given
5961 "int a[10]", an ARRAY_REF "a[2]" can be "const int", even though
5962 the array isn't const. Instead, check "a" in the next iteration;
5963 that will detect modifying "const int a[10]". */
5964 else if (evaluated
5965 && modifying_const_object_p (TREE_CODE (t), probe,
5966 mutable_p)
5967 && const_object_being_modified == NULL_TREE)
5968 const_object_being_modified = probe;
5969 vec_safe_push (refs, elt);
5970 vec_safe_push (refs, TREE_TYPE (probe));
5971 probe = ob;
5973 break;
5975 case REALPART_EXPR:
5976 gcc_assert (probe == target);
5977 vec_safe_push (refs, probe);
5978 vec_safe_push (refs, TREE_TYPE (probe));
5979 probe = TREE_OPERAND (probe, 0);
5980 break;
5982 case IMAGPART_EXPR:
5983 gcc_assert (probe == target);
5984 vec_safe_push (refs, probe);
5985 vec_safe_push (refs, TREE_TYPE (probe));
5986 probe = TREE_OPERAND (probe, 0);
5987 break;
5989 default:
5990 if (evaluated)
5991 object = probe;
5992 else
5994 probe = cxx_eval_constant_expression (ctx, probe, vc_glvalue,
5995 non_constant_p, overflow_p);
5996 evaluated = true;
5997 if (*non_constant_p)
5998 return t;
6000 break;
6004 if (modifying_const_object_p (TREE_CODE (t), object, mutable_p)
6005 && const_object_being_modified == NULL_TREE)
6006 const_object_being_modified = object;
6008 /* And then find/build up our initializer for the path to the subobject
6009 we're initializing. */
6010 tree *valp;
6011 if (DECL_P (object))
6012 valp = ctx->global->get_value_ptr (object);
6013 else
6014 valp = NULL;
6015 if (!valp)
6017 /* A constant-expression cannot modify objects from outside the
6018 constant-expression. */
6019 if (!ctx->quiet)
6020 error ("modification of %qE is not a constant expression", object);
6021 *non_constant_p = true;
6022 return t;
6024 type = TREE_TYPE (object);
6025 bool no_zero_init = true;
6027 auto_vec<tree *> ctors;
6028 releasing_vec indexes;
6029 auto_vec<int> index_pos_hints;
6030 bool activated_union_member_p = false;
6031 bool empty_base = false;
6032 while (!refs->is_empty ())
6034 if (*valp == NULL_TREE)
6036 *valp = build_constructor (type, NULL);
6037 CONSTRUCTOR_NO_CLEARING (*valp) = no_zero_init;
6039 else if (STRIP_ANY_LOCATION_WRAPPER (*valp),
6040 TREE_CODE (*valp) == STRING_CST)
6042 /* An array was initialized with a string constant, and now
6043 we're writing into one of its elements. Explode the
6044 single initialization into a set of element
6045 initializations. */
6046 gcc_assert (TREE_CODE (type) == ARRAY_TYPE);
6048 tree string = *valp;
6049 tree elt_type = TREE_TYPE (type);
6050 unsigned chars_per_elt = (TYPE_PRECISION (elt_type)
6051 / TYPE_PRECISION (char_type_node));
6052 unsigned num_elts = TREE_STRING_LENGTH (string) / chars_per_elt;
6053 tree ary_ctor = build_constructor (type, NULL);
6055 vec_safe_reserve (CONSTRUCTOR_ELTS (ary_ctor), num_elts);
6056 for (unsigned ix = 0; ix != num_elts; ix++)
6058 constructor_elt elt =
6060 build_int_cst (size_type_node, ix),
6061 extract_string_elt (string, chars_per_elt, ix)
6063 CONSTRUCTOR_ELTS (ary_ctor)->quick_push (elt);
6066 *valp = ary_ctor;
6069 enum tree_code code = TREE_CODE (type);
6070 tree reftype = refs->pop();
6071 tree index = refs->pop();
6073 if (code == COMPLEX_TYPE)
6075 if (TREE_CODE (*valp) == COMPLEX_CST)
6076 *valp = build2 (COMPLEX_EXPR, type, TREE_REALPART (*valp),
6077 TREE_IMAGPART (*valp));
6078 else if (TREE_CODE (*valp) == CONSTRUCTOR
6079 && CONSTRUCTOR_NELTS (*valp) == 0
6080 && CONSTRUCTOR_NO_CLEARING (*valp))
6082 tree r = build_constructor (reftype, NULL);
6083 CONSTRUCTOR_NO_CLEARING (r) = 1;
6084 *valp = build2 (COMPLEX_EXPR, type, r, r);
6086 gcc_assert (TREE_CODE (*valp) == COMPLEX_EXPR);
6087 ctors.safe_push (valp);
6088 vec_safe_push (indexes, index);
6089 valp = &TREE_OPERAND (*valp, TREE_CODE (index) == IMAGPART_EXPR);
6090 gcc_checking_assert (refs->is_empty ());
6091 type = reftype;
6092 break;
6095 /* If the value of object is already zero-initialized, any new ctors for
6096 subobjects will also be zero-initialized. */
6097 no_zero_init = CONSTRUCTOR_NO_CLEARING (*valp);
6099 if (code == RECORD_TYPE && is_empty_field (index))
6100 /* Don't build a sub-CONSTRUCTOR for an empty base or field, as they
6101 have no data and might have an offset lower than previously declared
6102 fields, which confuses the middle-end. The code below will notice
6103 that we don't have a CONSTRUCTOR for our inner target and just
6104 return init. */
6106 empty_base = true;
6107 break;
6110 type = reftype;
6112 if (code == UNION_TYPE && CONSTRUCTOR_NELTS (*valp)
6113 && CONSTRUCTOR_ELT (*valp, 0)->index != index)
6115 if (cxx_dialect < cxx20)
6117 if (!ctx->quiet)
6118 error_at (cp_expr_loc_or_input_loc (t),
6119 "change of the active member of a union "
6120 "from %qD to %qD",
6121 CONSTRUCTOR_ELT (*valp, 0)->index,
6122 index);
6123 *non_constant_p = true;
6125 else if (TREE_CODE (t) == MODIFY_EXPR
6126 && CONSTRUCTOR_NO_CLEARING (*valp))
6128 /* Diagnose changing the active union member while the union
6129 is in the process of being initialized. */
6130 if (!ctx->quiet)
6131 error_at (cp_expr_loc_or_input_loc (t),
6132 "change of the active member of a union "
6133 "from %qD to %qD during initialization",
6134 CONSTRUCTOR_ELT (*valp, 0)->index,
6135 index);
6136 *non_constant_p = true;
6138 no_zero_init = true;
6141 ctors.safe_push (valp);
6142 vec_safe_push (indexes, index);
6144 constructor_elt *cep
6145 = get_or_insert_ctor_field (*valp, index);
6146 index_pos_hints.safe_push (cep - CONSTRUCTOR_ELTS (*valp)->begin());
6148 if (code == UNION_TYPE)
6149 activated_union_member_p = true;
6151 valp = &cep->value;
6154 /* For initialization of an empty base, the original target will be
6155 *(base*)this, evaluation of which resolves to the object
6156 argument, which has the derived type rather than the base type. */
6157 if (!empty_base && !(same_type_ignoring_top_level_qualifiers_p
6158 (initialized_type (init), type)))
6160 gcc_assert (is_empty_class (TREE_TYPE (target)));
6161 empty_base = true;
6164 /* Detect modifying a constant object in constexpr evaluation.
6165 We have found a const object that is being modified. Figure out
6166 if we need to issue an error. Consider
6168 struct A {
6169 int n;
6170 constexpr A() : n(1) { n = 2; } // #1
6172 struct B {
6173 const A a;
6174 constexpr B() { a.n = 3; } // #2
6176 constexpr B b{};
6178 #1 is OK, since we're modifying an object under construction, but
6179 #2 is wrong, since "a" is const and has been fully constructed.
6180 To track it, we use the TREE_READONLY bit in the object's CONSTRUCTOR
6181 which means that the object is read-only. For the example above, the
6182 *ctors stack at the point of #2 will look like:
6184 ctors[0] = {.a={.n=2}} TREE_READONLY = 0
6185 ctors[1] = {.n=2} TREE_READONLY = 1
6187 and we're modifying "b.a", so we search the stack and see if the
6188 constructor for "b.a" has already run. */
6189 if (const_object_being_modified)
6191 bool fail = false;
6192 tree const_objtype
6193 = strip_array_types (TREE_TYPE (const_object_being_modified));
6194 if (!CLASS_TYPE_P (const_objtype))
6195 fail = true;
6196 else
6198 /* [class.ctor]p5 "A constructor can be invoked for a const,
6199 volatile, or const volatile object. const and volatile
6200 semantics are not applied on an object under construction.
6201 They come into effect when the constructor for the most
6202 derived object ends." */
6203 for (tree *elt : ctors)
6204 if (same_type_ignoring_top_level_qualifiers_p
6205 (TREE_TYPE (const_object_being_modified), TREE_TYPE (*elt)))
6207 fail = TREE_READONLY (*elt);
6208 break;
6211 if (fail)
6213 if (!ctx->quiet)
6214 modifying_const_object_error (t, const_object_being_modified);
6215 *non_constant_p = true;
6216 return t;
6220 if (!preeval)
6222 /* We're handling an INIT_EXPR of class type, so the value of the
6223 initializer can depend on the object it's initializing. */
6225 /* Create a new CONSTRUCTOR in case evaluation of the initializer
6226 wants to modify it. */
6227 if (*valp == NULL_TREE)
6229 *valp = build_constructor (type, NULL);
6230 CONSTRUCTOR_NO_CLEARING (*valp) = no_zero_init;
6232 new_ctx.ctor = empty_base ? NULL_TREE : *valp;
6233 new_ctx.object = target;
6234 /* Avoid temporary materialization when initializing from a TARGET_EXPR.
6235 We don't need to mess with AGGR_EXPR_SLOT/VEC_INIT_EXPR_SLOT because
6236 expansion of those trees uses ctx instead. */
6237 if (TREE_CODE (init) == TARGET_EXPR)
6238 if (tree tinit = TARGET_EXPR_INITIAL (init))
6239 init = tinit;
6240 init = cxx_eval_constant_expression (&new_ctx, init, vc_prvalue,
6241 non_constant_p, overflow_p);
6242 /* The hash table might have moved since the get earlier, and the
6243 initializer might have mutated the underlying CONSTRUCTORs, so we must
6244 recompute VALP. */
6245 valp = ctx->global->get_value_ptr (object);
6246 for (unsigned i = 0; i < vec_safe_length (indexes); i++)
6248 ctors[i] = valp;
6249 constructor_elt *cep
6250 = get_or_insert_ctor_field (*valp, indexes[i], index_pos_hints[i]);
6251 valp = &cep->value;
6255 if (*non_constant_p)
6256 return t;
6258 /* Don't share a CONSTRUCTOR that might be changed later. */
6259 init = unshare_constructor (init);
6261 gcc_checking_assert (!*valp || (same_type_ignoring_top_level_qualifiers_p
6262 (TREE_TYPE (*valp), type)));
6263 if (empty_base)
6265 /* Just evaluate the initializer and return, since there's no actual data
6266 to store, and we didn't build a CONSTRUCTOR. */
6267 if (!*valp)
6269 /* But do make sure we have something in *valp. */
6270 *valp = build_constructor (type, nullptr);
6271 CONSTRUCTOR_NO_CLEARING (*valp) = no_zero_init;
6274 else if (*valp && TREE_CODE (*valp) == CONSTRUCTOR
6275 && TREE_CODE (init) == CONSTRUCTOR)
6277 /* An outer ctx->ctor might be pointing to *valp, so replace
6278 its contents. */
6279 CONSTRUCTOR_ELTS (*valp) = CONSTRUCTOR_ELTS (init);
6280 TREE_CONSTANT (*valp) = TREE_CONSTANT (init);
6281 TREE_SIDE_EFFECTS (*valp) = TREE_SIDE_EFFECTS (init);
6282 CONSTRUCTOR_NO_CLEARING (*valp)
6283 = CONSTRUCTOR_NO_CLEARING (init);
6285 else
6286 *valp = init;
6288 /* After initialization, 'const' semantics apply to the value of the
6289 object. Make a note of this fact by marking the CONSTRUCTOR
6290 TREE_READONLY. */
6291 if (TREE_CODE (t) == INIT_EXPR
6292 && TREE_CODE (*valp) == CONSTRUCTOR
6293 && TYPE_READONLY (type))
6295 if (INDIRECT_REF_P (target)
6296 && (is_this_parameter
6297 (tree_strip_nop_conversions (TREE_OPERAND (target, 0)))))
6298 /* We've just initialized '*this' (perhaps via the target
6299 constructor of a delegating constructor). Leave it up to the
6300 caller that set 'this' to set TREE_READONLY appropriately. */
6301 gcc_checking_assert (same_type_ignoring_top_level_qualifiers_p
6302 (TREE_TYPE (target), type) || empty_base);
6303 else
6304 TREE_READONLY (*valp) = true;
6307 /* Update TREE_CONSTANT and TREE_SIDE_EFFECTS on enclosing
6308 CONSTRUCTORs, if any. */
6309 bool c = TREE_CONSTANT (init);
6310 bool s = TREE_SIDE_EFFECTS (init);
6311 if (!indexes->is_empty ())
6313 tree last = indexes->last ();
6314 if (TREE_CODE (last) == REALPART_EXPR
6315 || TREE_CODE (last) == IMAGPART_EXPR)
6317 /* And canonicalize COMPLEX_EXPR into COMPLEX_CST if
6318 possible. */
6319 tree *cexpr = ctors.last ();
6320 if (tree c = const_binop (COMPLEX_EXPR, TREE_TYPE (*cexpr),
6321 TREE_OPERAND (*cexpr, 0),
6322 TREE_OPERAND (*cexpr, 1)))
6323 *cexpr = c;
6324 else
6326 TREE_CONSTANT (*cexpr)
6327 = (TREE_CONSTANT (TREE_OPERAND (*cexpr, 0))
6328 & TREE_CONSTANT (TREE_OPERAND (*cexpr, 1)));
6329 TREE_SIDE_EFFECTS (*cexpr)
6330 = (TREE_SIDE_EFFECTS (TREE_OPERAND (*cexpr, 0))
6331 | TREE_SIDE_EFFECTS (TREE_OPERAND (*cexpr, 1)));
6333 c = TREE_CONSTANT (*cexpr);
6334 s = TREE_SIDE_EFFECTS (*cexpr);
6337 if (!c || s || activated_union_member_p)
6338 for (tree *elt : ctors)
6340 if (TREE_CODE (*elt) != CONSTRUCTOR)
6341 continue;
6342 if (!c)
6343 TREE_CONSTANT (*elt) = false;
6344 if (s)
6345 TREE_SIDE_EFFECTS (*elt) = true;
6346 /* Clear CONSTRUCTOR_NO_CLEARING since we've activated a member of
6347 this union. */
6348 if (TREE_CODE (TREE_TYPE (*elt)) == UNION_TYPE)
6349 CONSTRUCTOR_NO_CLEARING (*elt) = false;
6352 if (lval)
6353 return target;
6354 else
6355 return init;
6358 /* Evaluate a ++ or -- expression. */
6360 static tree
6361 cxx_eval_increment_expression (const constexpr_ctx *ctx, tree t,
6362 value_cat lval,
6363 bool *non_constant_p, bool *overflow_p)
6365 enum tree_code code = TREE_CODE (t);
6366 tree type = TREE_TYPE (t);
6367 tree op = TREE_OPERAND (t, 0);
6368 tree offset = TREE_OPERAND (t, 1);
6369 gcc_assert (TREE_CONSTANT (offset));
6371 /* OFFSET is constant, but perhaps not constant enough. We need to
6372 e.g. bash FLOAT_EXPRs to REAL_CSTs. */
6373 offset = fold_simple (offset);
6375 /* The operand as an lvalue. */
6376 op = cxx_eval_constant_expression (ctx, op, vc_glvalue,
6377 non_constant_p, overflow_p);
6379 /* The operand as an rvalue. */
6380 tree val
6381 = cxx_eval_constant_expression (ctx, op, vc_prvalue,
6382 non_constant_p, overflow_p);
6383 /* Don't VERIFY_CONSTANT if this might be dealing with a pointer to
6384 a local array in a constexpr function. */
6385 bool ptr = INDIRECT_TYPE_P (TREE_TYPE (val));
6386 if (!ptr)
6387 VERIFY_CONSTANT (val);
6389 /* The modified value. */
6390 bool inc = (code == PREINCREMENT_EXPR || code == POSTINCREMENT_EXPR);
6391 tree mod;
6392 if (INDIRECT_TYPE_P (type))
6394 /* The middle end requires pointers to use POINTER_PLUS_EXPR. */
6395 offset = convert_to_ptrofftype (offset);
6396 if (!inc)
6397 offset = fold_build1 (NEGATE_EXPR, TREE_TYPE (offset), offset);
6398 mod = fold_build2 (POINTER_PLUS_EXPR, type, val, offset);
6400 else if (c_promoting_integer_type_p (type)
6401 && !TYPE_UNSIGNED (type)
6402 && TYPE_PRECISION (type) < TYPE_PRECISION (integer_type_node))
6404 offset = fold_convert (integer_type_node, offset);
6405 mod = fold_convert (integer_type_node, val);
6406 tree t = fold_build2 (inc ? PLUS_EXPR : MINUS_EXPR, integer_type_node,
6407 mod, offset);
6408 mod = fold_convert (type, t);
6409 if (TREE_OVERFLOW_P (mod) && !TREE_OVERFLOW_P (t))
6410 TREE_OVERFLOW (mod) = false;
6412 else
6413 mod = fold_build2 (inc ? PLUS_EXPR : MINUS_EXPR, type, val, offset);
6414 if (!ptr)
6415 VERIFY_CONSTANT (mod);
6417 /* Storing the modified value. */
6418 tree store = build2_loc (cp_expr_loc_or_loc (t, input_location),
6419 MODIFY_EXPR, type, op, mod);
6420 mod = cxx_eval_constant_expression (ctx, store, lval,
6421 non_constant_p, overflow_p);
6422 ggc_free (store);
6423 if (*non_constant_p)
6424 return t;
6426 /* And the value of the expression. */
6427 if (code == PREINCREMENT_EXPR || code == PREDECREMENT_EXPR)
6428 /* Prefix ops are lvalues, but the caller might want an rvalue;
6429 lval has already been taken into account in the store above. */
6430 return mod;
6431 else
6432 /* Postfix ops are rvalues. */
6433 return val;
6436 /* Predicates for the meaning of *jump_target. */
6438 static bool
6439 returns (tree *jump_target)
6441 return *jump_target
6442 && TREE_CODE (*jump_target) == RETURN_EXPR;
6445 static bool
6446 breaks (tree *jump_target)
6448 return *jump_target
6449 && ((TREE_CODE (*jump_target) == LABEL_DECL
6450 && LABEL_DECL_BREAK (*jump_target))
6451 || TREE_CODE (*jump_target) == BREAK_STMT
6452 || TREE_CODE (*jump_target) == EXIT_EXPR);
6455 static bool
6456 continues (tree *jump_target)
6458 return *jump_target
6459 && ((TREE_CODE (*jump_target) == LABEL_DECL
6460 && LABEL_DECL_CONTINUE (*jump_target))
6461 || TREE_CODE (*jump_target) == CONTINUE_STMT);
6465 static bool
6466 switches (tree *jump_target)
6468 return *jump_target
6469 && TREE_CODE (*jump_target) == INTEGER_CST;
6472 /* Subroutine of cxx_eval_statement_list. Determine whether the statement
6473 STMT matches *jump_target. If we're looking for a case label and we see
6474 the default label, note it in ctx->css_state. */
6476 static bool
6477 label_matches (const constexpr_ctx *ctx, tree *jump_target, tree stmt)
6479 switch (TREE_CODE (*jump_target))
6481 case LABEL_DECL:
6482 if (TREE_CODE (stmt) == LABEL_EXPR
6483 && LABEL_EXPR_LABEL (stmt) == *jump_target)
6484 return true;
6485 break;
6487 case INTEGER_CST:
6488 if (TREE_CODE (stmt) == CASE_LABEL_EXPR)
6490 gcc_assert (ctx->css_state != NULL);
6491 if (!CASE_LOW (stmt))
6493 /* default: should appear just once in a SWITCH_EXPR
6494 body (excluding nested SWITCH_EXPR). */
6495 gcc_assert (*ctx->css_state != css_default_seen);
6496 /* When evaluating SWITCH_EXPR body for the second time,
6497 return true for the default: label. */
6498 if (*ctx->css_state == css_default_processing)
6499 return true;
6500 *ctx->css_state = css_default_seen;
6502 else if (CASE_HIGH (stmt))
6504 if (tree_int_cst_le (CASE_LOW (stmt), *jump_target)
6505 && tree_int_cst_le (*jump_target, CASE_HIGH (stmt)))
6506 return true;
6508 else if (tree_int_cst_equal (*jump_target, CASE_LOW (stmt)))
6509 return true;
6511 break;
6513 case BREAK_STMT:
6514 case CONTINUE_STMT:
6515 /* These two are handled directly in cxx_eval_loop_expr by testing
6516 breaks (jump_target) or continues (jump_target). */
6517 break;
6519 default:
6520 gcc_unreachable ();
6522 return false;
6525 /* Evaluate a STATEMENT_LIST for side-effects. Handles various jump
6526 semantics, for switch, break, continue, and return. */
6528 static tree
6529 cxx_eval_statement_list (const constexpr_ctx *ctx, tree t,
6530 bool *non_constant_p, bool *overflow_p,
6531 tree *jump_target)
6533 tree local_target;
6534 /* In a statement-expression we want to return the last value.
6535 For empty statement expression return void_node. */
6536 tree r = void_node;
6537 if (!jump_target)
6539 local_target = NULL_TREE;
6540 jump_target = &local_target;
6542 for (tree_stmt_iterator i = tsi_start (t); !tsi_end_p (i); ++i)
6544 tree stmt = *i;
6546 /* We've found a continue, so skip everything until we reach
6547 the label its jumping to. */
6548 if (continues (jump_target))
6550 if (label_matches (ctx, jump_target, stmt))
6551 /* Found it. */
6552 *jump_target = NULL_TREE;
6553 else
6554 continue;
6556 if (TREE_CODE (stmt) == DEBUG_BEGIN_STMT)
6557 continue;
6559 value_cat lval = vc_discard;
6560 /* The result of a statement-expression is not wrapped in EXPR_STMT. */
6561 if (tsi_one_before_end_p (i) && TREE_CODE (stmt) != EXPR_STMT)
6562 lval = vc_prvalue;
6564 r = cxx_eval_constant_expression (ctx, stmt, lval,
6565 non_constant_p, overflow_p,
6566 jump_target);
6567 if (*non_constant_p)
6568 break;
6569 if (returns (jump_target) || breaks (jump_target))
6570 break;
6572 if (*jump_target && jump_target == &local_target)
6574 /* We aren't communicating the jump to our caller, so give up. We don't
6575 need to support evaluation of jumps out of statement-exprs. */
6576 if (!ctx->quiet)
6577 error_at (cp_expr_loc_or_input_loc (r),
6578 "statement is not a constant expression");
6579 *non_constant_p = true;
6581 return r;
6584 /* Evaluate a LOOP_EXPR for side-effects. Handles break and return
6585 semantics; continue semantics are covered by cxx_eval_statement_list. */
6587 static tree
6588 cxx_eval_loop_expr (const constexpr_ctx *ctx, tree t,
6589 bool *non_constant_p, bool *overflow_p,
6590 tree *jump_target)
6592 constexpr_ctx new_ctx = *ctx;
6593 tree local_target;
6594 if (!jump_target)
6596 local_target = NULL_TREE;
6597 jump_target = &local_target;
6600 tree body, cond = NULL_TREE, expr = NULL_TREE;
6601 int count = 0;
6602 switch (TREE_CODE (t))
6604 case LOOP_EXPR:
6605 body = LOOP_EXPR_BODY (t);
6606 break;
6607 case DO_STMT:
6608 body = DO_BODY (t);
6609 cond = DO_COND (t);
6610 break;
6611 case WHILE_STMT:
6612 body = WHILE_BODY (t);
6613 cond = WHILE_COND (t);
6614 count = -1;
6615 break;
6616 case FOR_STMT:
6617 if (FOR_INIT_STMT (t))
6618 cxx_eval_constant_expression (ctx, FOR_INIT_STMT (t), vc_discard,
6619 non_constant_p, overflow_p, jump_target);
6620 if (*non_constant_p)
6621 return NULL_TREE;
6622 body = FOR_BODY (t);
6623 cond = FOR_COND (t);
6624 expr = FOR_EXPR (t);
6625 count = -1;
6626 break;
6627 default:
6628 gcc_unreachable ();
6630 auto_vec<tree, 10> save_exprs;
6631 new_ctx.save_exprs = &save_exprs;
6634 if (count != -1)
6636 if (body)
6637 cxx_eval_constant_expression (&new_ctx, body, vc_discard,
6638 non_constant_p, overflow_p,
6639 jump_target);
6640 if (breaks (jump_target))
6642 *jump_target = NULL_TREE;
6643 break;
6646 if (TREE_CODE (t) != LOOP_EXPR && continues (jump_target))
6647 *jump_target = NULL_TREE;
6649 if (expr)
6650 cxx_eval_constant_expression (&new_ctx, expr, vc_prvalue,
6651 non_constant_p, overflow_p,
6652 jump_target);
6655 if (cond)
6657 tree res
6658 = cxx_eval_constant_expression (&new_ctx, cond, vc_prvalue,
6659 non_constant_p, overflow_p,
6660 jump_target);
6661 if (res)
6663 if (verify_constant (res, ctx->quiet, non_constant_p,
6664 overflow_p))
6665 break;
6666 if (integer_zerop (res))
6667 break;
6669 else
6670 gcc_assert (*jump_target);
6673 /* Forget saved values of SAVE_EXPRs and TARGET_EXPRs. */
6674 for (tree save_expr : save_exprs)
6675 ctx->global->remove_value (save_expr);
6676 save_exprs.truncate (0);
6678 if (++count >= constexpr_loop_limit)
6680 if (!ctx->quiet)
6681 error_at (cp_expr_loc_or_input_loc (t),
6682 "%<constexpr%> loop iteration count exceeds limit of %d "
6683 "(use %<-fconstexpr-loop-limit=%> to increase the limit)",
6684 constexpr_loop_limit);
6685 *non_constant_p = true;
6686 break;
6689 while (!returns (jump_target)
6690 && !breaks (jump_target)
6691 && !continues (jump_target)
6692 && (!switches (jump_target) || count == 0)
6693 && !*non_constant_p);
6695 /* Forget saved values of SAVE_EXPRs and TARGET_EXPRs. */
6696 for (tree save_expr : save_exprs)
6697 ctx->global->remove_value (save_expr);
6699 return NULL_TREE;
6702 /* Evaluate a SWITCH_EXPR for side-effects. Handles switch and break jump
6703 semantics. */
6705 static tree
6706 cxx_eval_switch_expr (const constexpr_ctx *ctx, tree t,
6707 bool *non_constant_p, bool *overflow_p,
6708 tree *jump_target)
6710 tree cond
6711 = TREE_CODE (t) == SWITCH_STMT ? SWITCH_STMT_COND (t) : SWITCH_COND (t);
6712 cond = cxx_eval_constant_expression (ctx, cond, vc_prvalue,
6713 non_constant_p, overflow_p);
6714 VERIFY_CONSTANT (cond);
6715 *jump_target = cond;
6717 tree body
6718 = TREE_CODE (t) == SWITCH_STMT ? SWITCH_STMT_BODY (t) : SWITCH_BODY (t);
6719 constexpr_ctx new_ctx = *ctx;
6720 constexpr_switch_state css = css_default_not_seen;
6721 new_ctx.css_state = &css;
6722 cxx_eval_constant_expression (&new_ctx, body, vc_discard,
6723 non_constant_p, overflow_p, jump_target);
6724 if (switches (jump_target) && css == css_default_seen)
6726 /* If the SWITCH_EXPR body has default: label, process it once again,
6727 this time instructing label_matches to return true for default:
6728 label on switches (jump_target). */
6729 css = css_default_processing;
6730 cxx_eval_constant_expression (&new_ctx, body, vc_discard,
6731 non_constant_p, overflow_p, jump_target);
6733 if (breaks (jump_target) || switches (jump_target))
6734 *jump_target = NULL_TREE;
6735 return NULL_TREE;
6738 /* Find the object of TYPE under initialization in CTX. */
6740 static tree
6741 lookup_placeholder (const constexpr_ctx *ctx, value_cat lval, tree type)
6743 if (!ctx)
6744 return NULL_TREE;
6746 /* Prefer the outermost matching object, but don't cross
6747 CONSTRUCTOR_PLACEHOLDER_BOUNDARY constructors. */
6748 if (ctx->ctor && !CONSTRUCTOR_PLACEHOLDER_BOUNDARY (ctx->ctor))
6749 if (tree outer_ob = lookup_placeholder (ctx->parent, lval, type))
6750 return outer_ob;
6752 /* We could use ctx->object unconditionally, but using ctx->ctor when we
6753 can is a minor optimization. */
6754 if (!lval && ctx->ctor && same_type_p (TREE_TYPE (ctx->ctor), type))
6755 return ctx->ctor;
6757 if (!ctx->object)
6758 return NULL_TREE;
6760 /* Since an object cannot have a field of its own type, we can search outward
6761 from ctx->object to find the unique containing object of TYPE. */
6762 tree ob = ctx->object;
6763 while (ob)
6765 if (same_type_ignoring_top_level_qualifiers_p (TREE_TYPE (ob), type))
6766 break;
6767 if (handled_component_p (ob))
6768 ob = TREE_OPERAND (ob, 0);
6769 else
6770 ob = NULL_TREE;
6773 return ob;
6776 /* Complain about an attempt to evaluate inline assembly. If FUNDEF_P is
6777 true, we're checking a constexpr function body. */
6779 static void
6780 inline_asm_in_constexpr_error (location_t loc, bool fundef_p)
6782 auto_diagnostic_group d;
6783 if (constexpr_error (loc, fundef_p, "inline assembly is not a "
6784 "constant expression"))
6785 inform (loc, "only unevaluated inline assembly is allowed in a "
6786 "%<constexpr%> function in C++20");
6789 /* We're getting the constant value of DECL in a manifestly constant-evaluated
6790 context; maybe complain about that. */
6792 static void
6793 maybe_warn_about_constant_value (location_t loc, tree decl)
6795 static bool explained = false;
6796 if (cxx_dialect >= cxx17
6797 && warn_interference_size
6798 && !OPTION_SET_P (param_destruct_interfere_size)
6799 && DECL_CONTEXT (decl) == std_node
6800 && id_equal (DECL_NAME (decl), "hardware_destructive_interference_size")
6801 && (LOCATION_FILE (input_location) != main_input_filename
6802 || module_exporting_p ())
6803 && warning_at (loc, OPT_Winterference_size, "use of %qD", decl)
6804 && !explained)
6806 explained = true;
6807 inform (loc, "its value can vary between compiler versions or "
6808 "with different %<-mtune%> or %<-mcpu%> flags");
6809 inform (loc, "if this use is part of a public ABI, change it to "
6810 "instead use a constant variable you define");
6811 inform (loc, "the default value for the current CPU tuning "
6812 "is %d bytes", param_destruct_interfere_size);
6813 inform (loc, "you can stabilize this value with %<--param "
6814 "hardware_destructive_interference_size=%d%>, or disable "
6815 "this warning with %<-Wno-interference-size%>",
6816 param_destruct_interfere_size);
6820 /* For element type ELT_TYPE, return the appropriate type of the heap object
6821 containing such element(s). COOKIE_SIZE is NULL or the size of cookie
6822 in bytes. If COOKIE_SIZE is NULL, return array type
6823 ELT_TYPE[FULL_SIZE / sizeof(ELT_TYPE)], otherwise return
6824 struct { size_t[COOKIE_SIZE/sizeof(size_t)]; ELT_TYPE[N]; }
6825 where N is is computed such that the size of the struct fits into FULL_SIZE.
6826 If ARG_SIZE is non-NULL, it is the first argument to the new operator.
6827 It should be passed if ELT_TYPE is zero sized type in which case FULL_SIZE
6828 will be also 0 and so it is not possible to determine the actual array
6829 size. CTX, NON_CONSTANT_P and OVERFLOW_P are used during constant
6830 expression evaluation of subexpressions of ARG_SIZE. */
6832 static tree
6833 build_new_constexpr_heap_type (const constexpr_ctx *ctx, tree elt_type,
6834 tree cookie_size, tree full_size, tree arg_size,
6835 bool *non_constant_p, bool *overflow_p)
6837 gcc_assert (cookie_size == NULL_TREE || tree_fits_uhwi_p (cookie_size));
6838 gcc_assert (tree_fits_uhwi_p (full_size));
6839 unsigned HOST_WIDE_INT csz = cookie_size ? tree_to_uhwi (cookie_size) : 0;
6840 if (arg_size)
6842 STRIP_NOPS (arg_size);
6843 if (cookie_size)
6845 if (TREE_CODE (arg_size) != PLUS_EXPR)
6846 arg_size = NULL_TREE;
6847 else if (TREE_CODE (TREE_OPERAND (arg_size, 0)) == INTEGER_CST
6848 && tree_int_cst_equal (cookie_size,
6849 TREE_OPERAND (arg_size, 0)))
6851 arg_size = TREE_OPERAND (arg_size, 1);
6852 STRIP_NOPS (arg_size);
6854 else if (TREE_CODE (TREE_OPERAND (arg_size, 1)) == INTEGER_CST
6855 && tree_int_cst_equal (cookie_size,
6856 TREE_OPERAND (arg_size, 1)))
6858 arg_size = TREE_OPERAND (arg_size, 0);
6859 STRIP_NOPS (arg_size);
6861 else
6862 arg_size = NULL_TREE;
6864 if (arg_size && TREE_CODE (arg_size) == MULT_EXPR)
6866 tree op0 = TREE_OPERAND (arg_size, 0);
6867 tree op1 = TREE_OPERAND (arg_size, 1);
6868 if (integer_zerop (op0))
6869 arg_size
6870 = cxx_eval_constant_expression (ctx, op1, vc_prvalue,
6871 non_constant_p, overflow_p);
6872 else if (integer_zerop (op1))
6873 arg_size
6874 = cxx_eval_constant_expression (ctx, op0, vc_prvalue,
6875 non_constant_p, overflow_p);
6876 else
6877 arg_size = NULL_TREE;
6879 else
6880 arg_size = NULL_TREE;
6883 unsigned HOST_WIDE_INT fsz = tree_to_uhwi (arg_size ? arg_size : full_size);
6884 if (!arg_size)
6886 unsigned HOST_WIDE_INT esz = int_size_in_bytes (elt_type);
6887 gcc_assert (fsz >= csz);
6888 fsz -= csz;
6889 if (esz)
6890 fsz /= esz;
6892 tree itype2 = build_index_type (size_int (fsz - 1));
6893 if (!cookie_size)
6894 return build_cplus_array_type (elt_type, itype2);
6895 return build_new_constexpr_heap_type (elt_type, cookie_size, itype2);
6898 /* Attempt to reduce the expression T to a constant value.
6899 On failure, issue diagnostic and return error_mark_node. */
6900 /* FIXME unify with c_fully_fold */
6901 /* FIXME overflow_p is too global */
6903 static tree
6904 cxx_eval_constant_expression (const constexpr_ctx *ctx, tree t,
6905 value_cat lval,
6906 bool *non_constant_p, bool *overflow_p,
6907 tree *jump_target /* = NULL */)
6909 if (jump_target && *jump_target)
6911 /* If we are jumping, ignore all statements/expressions except those
6912 that could have LABEL_EXPR or CASE_LABEL_EXPR in their bodies. */
6913 switch (TREE_CODE (t))
6915 case BIND_EXPR:
6916 case STATEMENT_LIST:
6917 case LOOP_EXPR:
6918 case COND_EXPR:
6919 case IF_STMT:
6920 case DO_STMT:
6921 case WHILE_STMT:
6922 case FOR_STMT:
6923 break;
6924 case LABEL_EXPR:
6925 case CASE_LABEL_EXPR:
6926 if (label_matches (ctx, jump_target, t))
6927 /* Found it. */
6928 *jump_target = NULL_TREE;
6929 return NULL_TREE;
6930 default:
6931 return NULL_TREE;
6934 if (error_operand_p (t))
6936 *non_constant_p = true;
6937 return t;
6940 location_t loc = cp_expr_loc_or_input_loc (t);
6942 STRIP_ANY_LOCATION_WRAPPER (t);
6944 if (CONSTANT_CLASS_P (t))
6946 if (TREE_OVERFLOW (t))
6948 if (!ctx->quiet)
6949 permerror (input_location, "overflow in constant expression");
6950 if (!flag_permissive || ctx->quiet)
6951 *overflow_p = true;
6954 if (TREE_CODE (t) == INTEGER_CST
6955 && TYPE_PTR_P (TREE_TYPE (t))
6956 /* INTEGER_CST with pointer-to-method type is only used
6957 for a virtual method in a pointer to member function.
6958 Don't reject those. */
6959 && TREE_CODE (TREE_TYPE (TREE_TYPE (t))) != METHOD_TYPE
6960 && !integer_zerop (t))
6962 if (!ctx->quiet)
6963 error ("value %qE of type %qT is not a constant expression",
6964 t, TREE_TYPE (t));
6965 *non_constant_p = true;
6968 return t;
6971 /* Avoid excessively long constexpr evaluations. */
6972 if (++ctx->global->constexpr_ops_count >= constexpr_ops_limit)
6974 if (!ctx->quiet)
6975 error_at (loc,
6976 "%<constexpr%> evaluation operation count exceeds limit of "
6977 "%wd (use %<-fconstexpr-ops-limit=%> to increase the limit)",
6978 constexpr_ops_limit);
6979 ctx->global->constexpr_ops_count = INTTYPE_MINIMUM (HOST_WIDE_INT);
6980 *non_constant_p = true;
6981 return t;
6984 constexpr_ctx new_ctx;
6985 tree r = t;
6987 tree_code tcode = TREE_CODE (t);
6988 switch (tcode)
6990 case RESULT_DECL:
6991 if (lval)
6992 return t;
6993 /* We ask for an rvalue for the RESULT_DECL when indirecting
6994 through an invisible reference, or in named return value
6995 optimization. */
6996 if (tree v = ctx->global->get_value (t))
6997 return v;
6998 else
7000 if (!ctx->quiet)
7001 error ("%qE is not a constant expression", t);
7002 *non_constant_p = true;
7004 break;
7006 case VAR_DECL:
7007 if (DECL_HAS_VALUE_EXPR_P (t))
7009 if (is_normal_capture_proxy (t)
7010 && current_function_decl == DECL_CONTEXT (t))
7012 /* Function parms aren't constexpr within the function
7013 definition, so don't try to look at the closure. But if the
7014 captured variable is constant, try to evaluate it directly. */
7015 r = DECL_CAPTURED_VARIABLE (t);
7016 tree type = TREE_TYPE (t);
7017 if (TYPE_REF_P (type) != TYPE_REF_P (TREE_TYPE (r)))
7019 /* Adjust r to match the reference-ness of t. */
7020 if (TYPE_REF_P (type))
7021 r = build_address (r);
7022 else
7023 r = convert_from_reference (r);
7026 else
7027 r = DECL_VALUE_EXPR (t);
7028 return cxx_eval_constant_expression (ctx, r, lval, non_constant_p,
7029 overflow_p);
7031 /* fall through */
7032 case CONST_DECL:
7033 /* We used to not check lval for CONST_DECL, but darwin.cc uses
7034 CONST_DECL for aggregate constants. */
7035 if (lval)
7036 return t;
7037 else if (t == ctx->object)
7038 return ctx->ctor;
7039 if (VAR_P (t))
7040 if (tree v = ctx->global->get_value (t))
7042 r = v;
7043 break;
7045 if (ctx->manifestly_const_eval == mce_true)
7046 maybe_warn_about_constant_value (loc, t);
7047 if (COMPLETE_TYPE_P (TREE_TYPE (t))
7048 && is_really_empty_class (TREE_TYPE (t), /*ignore_vptr*/false))
7050 /* If the class is empty, we aren't actually loading anything. */
7051 r = build_constructor (TREE_TYPE (t), NULL);
7052 TREE_CONSTANT (r) = true;
7054 else if (ctx->strict)
7055 r = decl_really_constant_value (t, /*unshare_p=*/false);
7056 else
7057 r = decl_constant_value (t, /*unshare_p=*/false);
7058 if (TREE_CODE (r) == TARGET_EXPR
7059 && TREE_CODE (TARGET_EXPR_INITIAL (r)) == CONSTRUCTOR)
7060 r = TARGET_EXPR_INITIAL (r);
7061 if (DECL_P (r))
7063 if (!ctx->quiet)
7064 non_const_var_error (loc, r, /*fundef_p*/false);
7065 *non_constant_p = true;
7067 break;
7069 case DEBUG_BEGIN_STMT:
7070 /* ??? It might be nice to retain this information somehow, so
7071 as to be able to step into a constexpr function call. */
7072 /* Fall through. */
7074 case FUNCTION_DECL:
7075 case TEMPLATE_DECL:
7076 case LABEL_DECL:
7077 case LABEL_EXPR:
7078 case CASE_LABEL_EXPR:
7079 case PREDICT_EXPR:
7080 return t;
7082 case PARM_DECL:
7083 if (lval && !TYPE_REF_P (TREE_TYPE (t)))
7084 /* glvalue use. */;
7085 else if (tree v = ctx->global->get_value (r))
7086 r = v;
7087 else if (lval)
7088 /* Defer in case this is only used for its type. */;
7089 else if (COMPLETE_TYPE_P (TREE_TYPE (t))
7090 && is_really_empty_class (TREE_TYPE (t), /*ignore_vptr*/false))
7092 /* If the class is empty, we aren't actually loading anything. */
7093 r = build_constructor (TREE_TYPE (t), NULL);
7094 TREE_CONSTANT (r) = true;
7096 else
7098 if (!ctx->quiet)
7099 error ("%qE is not a constant expression", t);
7100 *non_constant_p = true;
7102 break;
7104 case CALL_EXPR:
7105 case AGGR_INIT_EXPR:
7106 r = cxx_eval_call_expression (ctx, t, lval,
7107 non_constant_p, overflow_p);
7108 break;
7110 case DECL_EXPR:
7112 r = DECL_EXPR_DECL (t);
7113 if (TREE_CODE (r) == USING_DECL)
7115 r = void_node;
7116 break;
7119 if (VAR_P (r)
7120 && (TREE_STATIC (r)
7121 || (CP_DECL_THREAD_LOCAL_P (r) && !DECL_REALLY_EXTERN (r)))
7122 /* Allow __FUNCTION__ etc. */
7123 && !DECL_ARTIFICIAL (r)
7124 && !decl_constant_var_p (r))
7126 if (!ctx->quiet)
7128 if (CP_DECL_THREAD_LOCAL_P (r))
7129 error_at (loc, "control passes through definition of %qD "
7130 "with thread storage duration", r);
7131 else
7132 error_at (loc, "control passes through definition of %qD "
7133 "with static storage duration", r);
7135 *non_constant_p = true;
7136 break;
7139 /* make_rtl_for_nonlocal_decl could have deferred emission of
7140 a local static var, but if it appears in a statement expression
7141 which is constant expression evaluated to e.g. just the address
7142 of the variable, its DECL_EXPR will never be seen during
7143 gimple lowering's record_vars_into as the statement expression
7144 will not be in the IL at all. */
7145 if (VAR_P (r)
7146 && TREE_STATIC (r)
7147 && !DECL_REALLY_EXTERN (r)
7148 && DECL_FUNCTION_SCOPE_P (r)
7149 && !var_in_maybe_constexpr_fn (r)
7150 && decl_constant_var_p (r))
7152 varpool_node *node = varpool_node::get (r);
7153 if (node == NULL || !node->definition)
7154 rest_of_decl_compilation (r, 0, at_eof);
7157 if (AGGREGATE_TYPE_P (TREE_TYPE (r))
7158 || VECTOR_TYPE_P (TREE_TYPE (r)))
7160 new_ctx = *ctx;
7161 new_ctx.object = r;
7162 new_ctx.ctor = build_constructor (TREE_TYPE (r), NULL);
7163 CONSTRUCTOR_NO_CLEARING (new_ctx.ctor) = true;
7164 ctx->global->put_value (r, new_ctx.ctor);
7165 ctx = &new_ctx;
7168 if (tree init = DECL_INITIAL (r))
7170 init = cxx_eval_constant_expression (ctx, init, vc_prvalue,
7171 non_constant_p, overflow_p);
7172 /* Don't share a CONSTRUCTOR that might be changed. */
7173 init = unshare_constructor (init);
7174 /* Remember that a constant object's constructor has already
7175 run. */
7176 if (CLASS_TYPE_P (TREE_TYPE (r))
7177 && CP_TYPE_CONST_P (TREE_TYPE (r)))
7178 TREE_READONLY (init) = true;
7179 ctx->global->put_value (r, init);
7181 else if (ctx == &new_ctx)
7182 /* We gave it a CONSTRUCTOR above. */;
7183 else
7184 ctx->global->put_value (r, NULL_TREE);
7186 break;
7188 case TARGET_EXPR:
7190 tree type = TREE_TYPE (t);
7192 if (!literal_type_p (type))
7194 if (!ctx->quiet)
7196 auto_diagnostic_group d;
7197 error ("temporary of non-literal type %qT in a "
7198 "constant expression", type);
7199 explain_non_literal_class (type);
7201 *non_constant_p = true;
7202 break;
7204 gcc_checking_assert (!TARGET_EXPR_DIRECT_INIT_P (t));
7205 /* Avoid evaluating a TARGET_EXPR more than once. */
7206 tree slot = TARGET_EXPR_SLOT (t);
7207 if (tree v = ctx->global->get_value (slot))
7209 if (lval)
7210 return slot;
7211 r = v;
7212 break;
7214 if ((AGGREGATE_TYPE_P (type) || VECTOR_TYPE_P (type)))
7216 /* We're being expanded without an explicit target, so start
7217 initializing a new object; expansion with an explicit target
7218 strips the TARGET_EXPR before we get here. */
7219 new_ctx = *ctx;
7220 /* Link CTX to NEW_CTX so that lookup_placeholder can resolve
7221 any PLACEHOLDER_EXPR within the initializer that refers to the
7222 former object under construction. */
7223 new_ctx.parent = ctx;
7224 new_ctx.ctor = build_constructor (type, NULL);
7225 CONSTRUCTOR_NO_CLEARING (new_ctx.ctor) = true;
7226 new_ctx.object = slot;
7227 ctx->global->put_value (new_ctx.object, new_ctx.ctor);
7228 ctx = &new_ctx;
7230 /* Pass vc_prvalue because this indicates
7231 initialization of a temporary. */
7232 r = cxx_eval_constant_expression (ctx, TREE_OPERAND (t, 1), vc_prvalue,
7233 non_constant_p, overflow_p);
7234 if (*non_constant_p)
7235 break;
7236 /* If the initializer is complex, evaluate it to initialize slot. */
7237 bool is_complex = target_expr_needs_replace (t);
7238 if (!is_complex)
7240 r = unshare_constructor (r);
7241 /* Adjust the type of the result to the type of the temporary. */
7242 r = adjust_temp_type (type, r);
7243 ctx->global->put_value (slot, r);
7245 if (TARGET_EXPR_CLEANUP (t) && !CLEANUP_EH_ONLY (t))
7246 ctx->global->cleanups->safe_push (TARGET_EXPR_CLEANUP (t));
7247 if (ctx->save_exprs)
7248 ctx->save_exprs->safe_push (slot);
7249 if (lval)
7250 return slot;
7251 if (is_complex)
7252 r = ctx->global->get_value (slot);
7254 break;
7256 case INIT_EXPR:
7257 case MODIFY_EXPR:
7258 gcc_assert (jump_target == NULL || *jump_target == NULL_TREE);
7259 r = cxx_eval_store_expression (ctx, t, lval,
7260 non_constant_p, overflow_p);
7261 break;
7263 case SCOPE_REF:
7264 r = cxx_eval_constant_expression (ctx, TREE_OPERAND (t, 1),
7265 lval,
7266 non_constant_p, overflow_p);
7267 break;
7269 case RETURN_EXPR:
7270 if (TREE_OPERAND (t, 0) != NULL_TREE)
7271 r = cxx_eval_constant_expression (ctx, TREE_OPERAND (t, 0),
7272 lval,
7273 non_constant_p, overflow_p);
7274 /* FALLTHRU */
7275 case BREAK_STMT:
7276 case CONTINUE_STMT:
7277 if (jump_target)
7278 *jump_target = t;
7279 else
7281 /* Can happen with ({ return true; }) && false; passed to
7282 maybe_constant_value. There is nothing to jump over in this
7283 case, and the bug will be diagnosed later. */
7284 gcc_assert (ctx->quiet);
7285 *non_constant_p = true;
7287 break;
7289 case SAVE_EXPR:
7290 /* Avoid evaluating a SAVE_EXPR more than once. */
7291 if (tree v = ctx->global->get_value (t))
7292 r = v;
7293 else
7295 r = cxx_eval_constant_expression (ctx, TREE_OPERAND (t, 0), vc_prvalue,
7296 non_constant_p, overflow_p);
7297 if (*non_constant_p)
7298 break;
7299 ctx->global->put_value (t, r);
7300 if (ctx->save_exprs)
7301 ctx->save_exprs->safe_push (t);
7303 break;
7305 case TRY_CATCH_EXPR:
7306 if (TREE_OPERAND (t, 0) == NULL_TREE)
7308 r = void_node;
7309 break;
7311 /* FALLTHRU */
7312 case NON_LVALUE_EXPR:
7313 case TRY_BLOCK:
7314 case MUST_NOT_THROW_EXPR:
7315 case EXPR_STMT:
7316 case EH_SPEC_BLOCK:
7317 r = cxx_eval_constant_expression (ctx, TREE_OPERAND (t, 0),
7318 lval,
7319 non_constant_p, overflow_p,
7320 jump_target);
7321 break;
7323 case CLEANUP_POINT_EXPR:
7325 auto_vec<tree, 2> cleanups;
7326 vec<tree> *prev_cleanups = ctx->global->cleanups;
7327 ctx->global->cleanups = &cleanups;
7328 r = cxx_eval_constant_expression (ctx, TREE_OPERAND (t, 0),
7329 lval,
7330 non_constant_p, overflow_p,
7331 jump_target);
7332 ctx->global->cleanups = prev_cleanups;
7333 unsigned int i;
7334 tree cleanup;
7335 /* Evaluate the cleanups. */
7336 FOR_EACH_VEC_ELT_REVERSE (cleanups, i, cleanup)
7337 cxx_eval_constant_expression (ctx, cleanup, vc_discard,
7338 non_constant_p, overflow_p);
7340 break;
7342 case TRY_FINALLY_EXPR:
7343 r = cxx_eval_constant_expression (ctx, TREE_OPERAND (t, 0), lval,
7344 non_constant_p, overflow_p,
7345 jump_target);
7346 if (!*non_constant_p)
7347 /* Also evaluate the cleanup. */
7348 cxx_eval_constant_expression (ctx, TREE_OPERAND (t, 1), vc_discard,
7349 non_constant_p, overflow_p);
7350 break;
7352 case CLEANUP_STMT:
7353 r = cxx_eval_constant_expression (ctx, CLEANUP_BODY (t), lval,
7354 non_constant_p, overflow_p,
7355 jump_target);
7356 if (!CLEANUP_EH_ONLY (t) && !*non_constant_p)
7358 iloc_sentinel ils (loc);
7359 /* Also evaluate the cleanup. */
7360 cxx_eval_constant_expression (ctx, CLEANUP_EXPR (t), vc_discard,
7361 non_constant_p, overflow_p);
7363 break;
7365 /* These differ from cxx_eval_unary_expression in that this doesn't
7366 check for a constant operand or result; an address can be
7367 constant without its operand being, and vice versa. */
7368 case MEM_REF:
7369 case INDIRECT_REF:
7370 r = cxx_eval_indirect_ref (ctx, t, lval,
7371 non_constant_p, overflow_p);
7372 break;
7374 case ADDR_EXPR:
7376 tree oldop = TREE_OPERAND (t, 0);
7377 tree op = cxx_eval_constant_expression (ctx, oldop, vc_glvalue,
7378 non_constant_p, overflow_p);
7379 /* Don't VERIFY_CONSTANT here. */
7380 if (*non_constant_p)
7381 return t;
7382 gcc_checking_assert (TREE_CODE (op) != CONSTRUCTOR);
7383 /* This function does more aggressive folding than fold itself. */
7384 r = build_fold_addr_expr_with_type (op, TREE_TYPE (t));
7385 if (TREE_CODE (r) == ADDR_EXPR && TREE_OPERAND (r, 0) == oldop)
7387 ggc_free (r);
7388 return t;
7390 break;
7393 case REALPART_EXPR:
7394 case IMAGPART_EXPR:
7395 if (lval)
7397 r = cxx_eval_constant_expression (ctx, TREE_OPERAND (t, 0), lval,
7398 non_constant_p, overflow_p);
7399 if (r == error_mark_node)
7401 else if (r == TREE_OPERAND (t, 0) || lval == vc_discard)
7402 r = t;
7403 else
7404 r = fold_build1 (TREE_CODE (t), TREE_TYPE (t), r);
7405 break;
7407 /* FALLTHRU */
7408 case CONJ_EXPR:
7409 case FIX_TRUNC_EXPR:
7410 case FLOAT_EXPR:
7411 case NEGATE_EXPR:
7412 case ABS_EXPR:
7413 case ABSU_EXPR:
7414 case BIT_NOT_EXPR:
7415 case TRUTH_NOT_EXPR:
7416 case FIXED_CONVERT_EXPR:
7417 r = cxx_eval_unary_expression (ctx, t, lval,
7418 non_constant_p, overflow_p);
7419 break;
7421 case SIZEOF_EXPR:
7422 r = fold_sizeof_expr (t);
7423 /* In a template, fold_sizeof_expr may merely create a new SIZEOF_EXPR,
7424 which could lead to an infinite recursion. */
7425 if (TREE_CODE (r) != SIZEOF_EXPR)
7426 r = cxx_eval_constant_expression (ctx, r, lval,
7427 non_constant_p, overflow_p,
7428 jump_target);
7429 else
7431 *non_constant_p = true;
7432 gcc_assert (ctx->quiet);
7435 break;
7437 case COMPOUND_EXPR:
7439 /* check_return_expr sometimes wraps a TARGET_EXPR in a
7440 COMPOUND_EXPR; don't get confused. Also handle EMPTY_CLASS_EXPR
7441 introduced by build_call_a. */
7442 tree op0 = TREE_OPERAND (t, 0);
7443 tree op1 = TREE_OPERAND (t, 1);
7444 STRIP_NOPS (op1);
7445 if ((TREE_CODE (op0) == TARGET_EXPR && op1 == TARGET_EXPR_SLOT (op0))
7446 || TREE_CODE (op1) == EMPTY_CLASS_EXPR)
7447 r = cxx_eval_constant_expression (ctx, op0,
7448 lval, non_constant_p, overflow_p,
7449 jump_target);
7450 else
7452 /* Check that the LHS is constant and then discard it. */
7453 cxx_eval_constant_expression (ctx, op0, vc_discard,
7454 non_constant_p, overflow_p,
7455 jump_target);
7456 if (*non_constant_p)
7457 return t;
7458 op1 = TREE_OPERAND (t, 1);
7459 r = cxx_eval_constant_expression (ctx, op1,
7460 lval, non_constant_p, overflow_p,
7461 jump_target);
7464 break;
7466 case POINTER_PLUS_EXPR:
7467 case POINTER_DIFF_EXPR:
7468 case PLUS_EXPR:
7469 case MINUS_EXPR:
7470 case MULT_EXPR:
7471 case TRUNC_DIV_EXPR:
7472 case CEIL_DIV_EXPR:
7473 case FLOOR_DIV_EXPR:
7474 case ROUND_DIV_EXPR:
7475 case TRUNC_MOD_EXPR:
7476 case CEIL_MOD_EXPR:
7477 case ROUND_MOD_EXPR:
7478 case RDIV_EXPR:
7479 case EXACT_DIV_EXPR:
7480 case MIN_EXPR:
7481 case MAX_EXPR:
7482 case LSHIFT_EXPR:
7483 case RSHIFT_EXPR:
7484 case LROTATE_EXPR:
7485 case RROTATE_EXPR:
7486 case BIT_IOR_EXPR:
7487 case BIT_XOR_EXPR:
7488 case BIT_AND_EXPR:
7489 case TRUTH_XOR_EXPR:
7490 case LT_EXPR:
7491 case LE_EXPR:
7492 case GT_EXPR:
7493 case GE_EXPR:
7494 case EQ_EXPR:
7495 case NE_EXPR:
7496 case SPACESHIP_EXPR:
7497 case UNORDERED_EXPR:
7498 case ORDERED_EXPR:
7499 case UNLT_EXPR:
7500 case UNLE_EXPR:
7501 case UNGT_EXPR:
7502 case UNGE_EXPR:
7503 case UNEQ_EXPR:
7504 case LTGT_EXPR:
7505 case RANGE_EXPR:
7506 case COMPLEX_EXPR:
7507 r = cxx_eval_binary_expression (ctx, t, lval,
7508 non_constant_p, overflow_p);
7509 break;
7511 /* fold can introduce non-IF versions of these; still treat them as
7512 short-circuiting. */
7513 case TRUTH_AND_EXPR:
7514 case TRUTH_ANDIF_EXPR:
7515 r = cxx_eval_logical_expression (ctx, t, boolean_false_node,
7516 boolean_true_node,
7517 non_constant_p, overflow_p);
7518 break;
7520 case TRUTH_OR_EXPR:
7521 case TRUTH_ORIF_EXPR:
7522 r = cxx_eval_logical_expression (ctx, t, boolean_true_node,
7523 boolean_false_node,
7524 non_constant_p, overflow_p);
7525 break;
7527 case ARRAY_REF:
7528 r = cxx_eval_array_reference (ctx, t, lval,
7529 non_constant_p, overflow_p);
7530 break;
7532 case COMPONENT_REF:
7533 if (is_overloaded_fn (t))
7535 /* We can only get here in checking mode via
7536 build_non_dependent_expr, because any expression that
7537 calls or takes the address of the function will have
7538 pulled a FUNCTION_DECL out of the COMPONENT_REF. */
7539 gcc_checking_assert (ctx->quiet || errorcount);
7540 *non_constant_p = true;
7541 return t;
7543 r = cxx_eval_component_reference (ctx, t, lval,
7544 non_constant_p, overflow_p);
7545 break;
7547 case BIT_FIELD_REF:
7548 r = cxx_eval_bit_field_ref (ctx, t, lval,
7549 non_constant_p, overflow_p);
7550 break;
7552 case COND_EXPR:
7553 case IF_STMT:
7554 if (jump_target && *jump_target)
7556 tree orig_jump = *jump_target;
7557 tree arg = ((TREE_CODE (t) != IF_STMT || TREE_OPERAND (t, 1))
7558 ? TREE_OPERAND (t, 1) : void_node);
7559 /* When jumping to a label, the label might be either in the
7560 then or else blocks, so process then block first in skipping
7561 mode first, and if we are still in the skipping mode at its end,
7562 process the else block too. */
7563 r = cxx_eval_constant_expression (ctx, arg, lval, non_constant_p,
7564 overflow_p, jump_target);
7565 /* It's possible that we found the label in the then block. But
7566 it could have been followed by another jumping statement, e.g.
7567 say we're looking for case 1:
7568 if (cond)
7570 // skipped statements
7571 case 1:; // clears up *jump_target
7572 return 1; // and sets it to a RETURN_EXPR
7574 else { ... }
7575 in which case we need not go looking to the else block.
7576 (goto is not allowed in a constexpr function.) */
7577 if (*jump_target == orig_jump)
7579 arg = ((TREE_CODE (t) != IF_STMT || TREE_OPERAND (t, 2))
7580 ? TREE_OPERAND (t, 2) : void_node);
7581 r = cxx_eval_constant_expression (ctx, arg, lval, non_constant_p,
7582 overflow_p, jump_target);
7584 break;
7586 r = cxx_eval_conditional_expression (ctx, t, lval,
7587 non_constant_p, overflow_p,
7588 jump_target);
7589 break;
7590 case VEC_COND_EXPR:
7591 r = cxx_eval_vector_conditional_expression (ctx, t, non_constant_p,
7592 overflow_p);
7593 break;
7595 case CONSTRUCTOR:
7596 if (TREE_CONSTANT (t) && reduced_constant_expression_p (t))
7598 /* Don't re-process a constant CONSTRUCTOR. */
7599 verify_constructor_flags (t);
7600 if (TREE_CONSTANT (t))
7601 return t;
7603 r = cxx_eval_bare_aggregate (ctx, t, lval,
7604 non_constant_p, overflow_p);
7605 break;
7607 case VEC_INIT_EXPR:
7608 /* We can get this in a defaulted constructor for a class with a
7609 non-static data member of array type. Either the initializer will
7610 be NULL, meaning default-initialization, or it will be an lvalue
7611 or xvalue of the same type, meaning direct-initialization from the
7612 corresponding member. */
7613 r = cxx_eval_vec_init (ctx, t, lval,
7614 non_constant_p, overflow_p);
7615 break;
7617 case VEC_PERM_EXPR:
7618 r = cxx_eval_trinary_expression (ctx, t, lval,
7619 non_constant_p, overflow_p);
7620 break;
7622 case PAREN_EXPR:
7623 gcc_assert (!REF_PARENTHESIZED_P (t));
7624 /* A PAREN_EXPR resulting from __builtin_assoc_barrier has no effect in
7625 constant expressions since it's unaffected by -fassociative-math. */
7626 r = cxx_eval_constant_expression (ctx, TREE_OPERAND (t, 0), lval,
7627 non_constant_p, overflow_p);
7628 break;
7630 case NOP_EXPR:
7631 if (REINTERPRET_CAST_P (t))
7633 if (!ctx->quiet)
7634 error_at (loc,
7635 "%<reinterpret_cast%> is not a constant expression");
7636 *non_constant_p = true;
7637 return t;
7639 /* FALLTHROUGH. */
7640 case CONVERT_EXPR:
7641 case VIEW_CONVERT_EXPR:
7642 case UNARY_PLUS_EXPR:
7644 tree oldop = TREE_OPERAND (t, 0);
7646 tree op = cxx_eval_constant_expression (ctx, oldop,
7647 lval,
7648 non_constant_p, overflow_p);
7649 if (*non_constant_p)
7650 return t;
7651 tree type = TREE_TYPE (t);
7653 if (VOID_TYPE_P (type))
7654 return void_node;
7656 if (TREE_CODE (t) == CONVERT_EXPR
7657 && ARITHMETIC_TYPE_P (type)
7658 && INDIRECT_TYPE_P (TREE_TYPE (op))
7659 && ctx->manifestly_const_eval == mce_true)
7661 if (!ctx->quiet)
7662 error_at (loc,
7663 "conversion from pointer type %qT to arithmetic type "
7664 "%qT in a constant expression", TREE_TYPE (op), type);
7665 *non_constant_p = true;
7666 return t;
7669 /* [expr.const]: a conversion from type cv void* to a pointer-to-object
7670 type cannot be part of a core constant expression as a resolution to
7671 DR 1312. */
7672 if (TYPE_PTROB_P (type)
7673 && TYPE_PTR_P (TREE_TYPE (op))
7674 && VOID_TYPE_P (TREE_TYPE (TREE_TYPE (op)))
7675 /* Inside a call to std::construct_at or to
7676 std::allocator<T>::{,de}allocate, we permit casting from void*
7677 because that is compiler-generated code. */
7678 && !is_std_construct_at (ctx->call)
7679 && !is_std_allocator_allocate (ctx->call))
7681 /* Likewise, don't error when casting from void* when OP is
7682 &heap uninit and similar. */
7683 tree sop = tree_strip_nop_conversions (op);
7684 if (TREE_CODE (sop) == ADDR_EXPR
7685 && VAR_P (TREE_OPERAND (sop, 0))
7686 && DECL_ARTIFICIAL (TREE_OPERAND (sop, 0)))
7687 /* OK */;
7688 else
7690 if (!ctx->quiet)
7691 error_at (loc, "cast from %qT is not allowed",
7692 TREE_TYPE (op));
7693 *non_constant_p = true;
7694 return t;
7698 if (TREE_CODE (op) == PTRMEM_CST && !TYPE_PTRMEM_P (type))
7700 op = cplus_expand_constant (op);
7701 if (TREE_CODE (op) == PTRMEM_CST)
7703 if (!ctx->quiet)
7704 error_at (loc, "%qE is not a constant expression when the "
7705 "class %qT is still incomplete", op,
7706 PTRMEM_CST_CLASS (op));
7707 *non_constant_p = true;
7708 return t;
7712 if (TREE_CODE (op) == PTRMEM_CST && tcode == NOP_EXPR)
7714 if (!same_type_ignoring_top_level_qualifiers_p (type, TREE_TYPE (op))
7715 && !can_convert_qual (type, op))
7716 op = cplus_expand_constant (op);
7717 return cp_fold_convert (type, op);
7720 if (INDIRECT_TYPE_P (type) && TREE_CODE (op) == INTEGER_CST)
7722 if (integer_zerop (op))
7724 if (TYPE_REF_P (type))
7726 if (!ctx->quiet)
7727 error_at (loc, "dereferencing a null pointer");
7728 *non_constant_p = true;
7729 return t;
7732 else
7734 /* This detects for example:
7735 reinterpret_cast<void*>(sizeof 0)
7737 if (!ctx->quiet)
7738 error_at (loc, "%<reinterpret_cast<%T>(%E)%> is not "
7739 "a constant expression",
7740 type, op);
7741 *non_constant_p = true;
7742 return t;
7746 if (INDIRECT_TYPE_P (type)
7747 && TREE_CODE (op) == NOP_EXPR
7748 && TREE_TYPE (op) == ptr_type_node
7749 && TREE_CODE (TREE_OPERAND (op, 0)) == ADDR_EXPR
7750 && VAR_P (TREE_OPERAND (TREE_OPERAND (op, 0), 0))
7751 && (DECL_NAME (TREE_OPERAND (TREE_OPERAND (op, 0),
7752 0)) == heap_uninit_identifier
7753 || DECL_NAME (TREE_OPERAND (TREE_OPERAND (op, 0),
7754 0)) == heap_vec_uninit_identifier))
7756 tree var = TREE_OPERAND (TREE_OPERAND (op, 0), 0);
7757 tree var_size = TYPE_SIZE_UNIT (TREE_TYPE (var));
7758 tree elt_type = TREE_TYPE (type);
7759 tree cookie_size = NULL_TREE;
7760 tree arg_size = NULL_TREE;
7761 if (TREE_CODE (elt_type) == RECORD_TYPE
7762 && TYPE_NAME (elt_type) == heap_identifier)
7764 tree fld1 = TYPE_FIELDS (elt_type);
7765 tree fld2 = DECL_CHAIN (fld1);
7766 elt_type = TREE_TYPE (TREE_TYPE (fld2));
7767 cookie_size = TYPE_SIZE_UNIT (TREE_TYPE (fld1));
7769 DECL_NAME (var)
7770 = (DECL_NAME (var) == heap_uninit_identifier
7771 ? heap_identifier : heap_vec_identifier);
7772 /* For zero sized elt_type, try to recover how many outer_nelts
7773 it should have. */
7774 if ((cookie_size ? tree_int_cst_equal (var_size, cookie_size)
7775 : integer_zerop (var_size))
7776 && !int_size_in_bytes (elt_type)
7777 && TREE_CODE (oldop) == CALL_EXPR
7778 && call_expr_nargs (oldop) >= 1)
7779 if (tree fun = get_function_named_in_call (oldop))
7780 if (cxx_replaceable_global_alloc_fn (fun)
7781 && IDENTIFIER_NEW_OP_P (DECL_NAME (fun)))
7782 arg_size = CALL_EXPR_ARG (oldop, 0);
7783 TREE_TYPE (var)
7784 = build_new_constexpr_heap_type (ctx, elt_type, cookie_size,
7785 var_size, arg_size,
7786 non_constant_p, overflow_p);
7787 TREE_TYPE (TREE_OPERAND (op, 0))
7788 = build_pointer_type (TREE_TYPE (var));
7791 if (op == oldop && tcode != UNARY_PLUS_EXPR)
7792 /* We didn't fold at the top so we could check for ptr-int
7793 conversion. */
7794 return fold (t);
7796 tree sop;
7798 /* Handle an array's bounds having been deduced after we built
7799 the wrapping expression. */
7800 if (same_type_ignoring_tlq_and_bounds_p (type, TREE_TYPE (op)))
7801 r = op;
7802 else if (sop = tree_strip_nop_conversions (op),
7803 sop != op && (same_type_ignoring_tlq_and_bounds_p
7804 (type, TREE_TYPE (sop))))
7805 r = sop;
7806 else if (tcode == UNARY_PLUS_EXPR)
7807 r = fold_convert (TREE_TYPE (t), op);
7808 else
7809 r = fold_build1 (tcode, type, op);
7811 /* Conversion of an out-of-range value has implementation-defined
7812 behavior; the language considers it different from arithmetic
7813 overflow, which is undefined. */
7814 if (TREE_OVERFLOW_P (r) && !TREE_OVERFLOW_P (op))
7815 TREE_OVERFLOW (r) = false;
7817 break;
7819 case EXCESS_PRECISION_EXPR:
7821 tree oldop = TREE_OPERAND (t, 0);
7823 tree op = cxx_eval_constant_expression (ctx, oldop,
7824 lval,
7825 non_constant_p, overflow_p);
7826 if (*non_constant_p)
7827 return t;
7828 r = fold_convert (TREE_TYPE (t), op);
7829 break;
7832 case EMPTY_CLASS_EXPR:
7833 /* Handle EMPTY_CLASS_EXPR produced by build_call_a by lowering
7834 it to an appropriate CONSTRUCTOR. */
7835 return build_constructor (TREE_TYPE (t), NULL);
7837 case STATEMENT_LIST:
7838 new_ctx = *ctx;
7839 new_ctx.ctor = new_ctx.object = NULL_TREE;
7840 return cxx_eval_statement_list (&new_ctx, t,
7841 non_constant_p, overflow_p, jump_target);
7843 case BIND_EXPR:
7844 return cxx_eval_constant_expression (ctx, BIND_EXPR_BODY (t),
7845 lval,
7846 non_constant_p, overflow_p,
7847 jump_target);
7849 case PREINCREMENT_EXPR:
7850 case POSTINCREMENT_EXPR:
7851 case PREDECREMENT_EXPR:
7852 case POSTDECREMENT_EXPR:
7853 return cxx_eval_increment_expression (ctx, t,
7854 lval, non_constant_p, overflow_p);
7856 case LAMBDA_EXPR:
7857 case NEW_EXPR:
7858 case VEC_NEW_EXPR:
7859 case DELETE_EXPR:
7860 case VEC_DELETE_EXPR:
7861 case THROW_EXPR:
7862 case MODOP_EXPR:
7863 /* GCC internal stuff. */
7864 case VA_ARG_EXPR:
7865 case NON_DEPENDENT_EXPR:
7866 case BASELINK:
7867 case OFFSET_REF:
7868 if (!ctx->quiet)
7869 error_at (loc, "expression %qE is not a constant expression", t);
7870 *non_constant_p = true;
7871 break;
7873 case OBJ_TYPE_REF:
7874 /* Virtual function lookup. We don't need to do anything fancy. */
7875 return cxx_eval_constant_expression (ctx, OBJ_TYPE_REF_EXPR (t),
7876 lval, non_constant_p, overflow_p);
7878 case PLACEHOLDER_EXPR:
7879 /* Use of the value or address of the current object. */
7880 if (tree ctor = lookup_placeholder (ctx, lval, TREE_TYPE (t)))
7882 if (TREE_CODE (ctor) == CONSTRUCTOR)
7883 return ctor;
7884 else
7885 return cxx_eval_constant_expression (ctx, ctor, lval,
7886 non_constant_p, overflow_p);
7888 /* A placeholder without a referent. We can get here when
7889 checking whether NSDMIs are noexcept, or in massage_init_elt;
7890 just say it's non-constant for now. */
7891 gcc_assert (ctx->quiet);
7892 *non_constant_p = true;
7893 break;
7895 case EXIT_EXPR:
7897 tree cond = TREE_OPERAND (t, 0);
7898 cond = cxx_eval_constant_expression (ctx, cond, vc_prvalue,
7899 non_constant_p, overflow_p);
7900 VERIFY_CONSTANT (cond);
7901 if (integer_nonzerop (cond))
7902 *jump_target = t;
7904 break;
7906 case GOTO_EXPR:
7907 if (breaks (&TREE_OPERAND (t, 0))
7908 || continues (&TREE_OPERAND (t, 0)))
7909 *jump_target = TREE_OPERAND (t, 0);
7910 else
7912 gcc_assert (cxx_dialect >= cxx23);
7913 if (!ctx->quiet)
7914 error_at (loc, "%<goto%> is not a constant expression");
7915 *non_constant_p = true;
7917 break;
7919 case LOOP_EXPR:
7920 case DO_STMT:
7921 case WHILE_STMT:
7922 case FOR_STMT:
7923 cxx_eval_loop_expr (ctx, t,
7924 non_constant_p, overflow_p, jump_target);
7925 break;
7927 case SWITCH_EXPR:
7928 case SWITCH_STMT:
7929 cxx_eval_switch_expr (ctx, t,
7930 non_constant_p, overflow_p, jump_target);
7931 break;
7933 case REQUIRES_EXPR:
7934 /* It's possible to get a requires-expression in a constant
7935 expression. For example:
7937 template<typename T> concept bool C() {
7938 return requires (T t) { t; };
7941 template<typename T> requires !C<T>() void f(T);
7943 Normalization leaves f with the associated constraint
7944 '!requires (T t) { ... }' which is not transformed into
7945 a constraint. */
7946 if (!processing_template_decl)
7947 return evaluate_requires_expr (t);
7948 else
7949 *non_constant_p = true;
7950 return t;
7952 case ANNOTATE_EXPR:
7953 r = cxx_eval_constant_expression (ctx, TREE_OPERAND (t, 0),
7954 lval,
7955 non_constant_p, overflow_p,
7956 jump_target);
7957 break;
7959 case USING_STMT:
7960 r = void_node;
7961 break;
7963 case ASSERTION_STMT:
7964 case PRECONDITION_STMT:
7965 case POSTCONDITION_STMT:
7967 contract_semantic semantic = get_contract_semantic (t);
7968 if (semantic == CCS_IGNORE)
7969 break;
7971 if (!cxx_eval_assert (ctx, CONTRACT_CONDITION (t),
7972 G_("contract predicate is false in "
7973 "constant expression"),
7974 EXPR_LOCATION (t), checked_contract_p (semantic),
7975 non_constant_p, overflow_p))
7976 *non_constant_p = true;
7977 r = void_node;
7979 break;
7981 case TEMPLATE_ID_EXPR:
7983 /* We can evaluate template-id that refers to a concept only if
7984 the template arguments are non-dependent. */
7985 tree id = unpack_concept_check (t);
7986 tree tmpl = TREE_OPERAND (id, 0);
7987 if (!concept_definition_p (tmpl))
7988 internal_error ("unexpected template-id %qE", t);
7990 if (function_concept_p (tmpl))
7992 if (!ctx->quiet)
7993 error_at (cp_expr_loc_or_input_loc (t),
7994 "function concept must be called");
7995 r = error_mark_node;
7996 break;
7999 if (!value_dependent_expression_p (t)
8000 && !uid_sensitive_constexpr_evaluation_p ())
8001 r = evaluate_concept_check (t);
8002 else
8003 *non_constant_p = true;
8005 break;
8008 case ASM_EXPR:
8009 if (!ctx->quiet)
8010 inline_asm_in_constexpr_error (loc, /*constexpr_fundef_p*/false);
8011 *non_constant_p = true;
8012 return t;
8014 case BIT_CAST_EXPR:
8015 if (lval)
8017 if (!ctx->quiet)
8018 error_at (EXPR_LOCATION (t),
8019 "address of a call to %qs is not a constant expression",
8020 "__builtin_bit_cast");
8021 *non_constant_p = true;
8022 return t;
8024 r = cxx_eval_bit_cast (ctx, t, non_constant_p, overflow_p);
8025 break;
8027 case OMP_PARALLEL:
8028 case OMP_TASK:
8029 case OMP_FOR:
8030 case OMP_SIMD:
8031 case OMP_DISTRIBUTE:
8032 case OMP_TASKLOOP:
8033 case OMP_LOOP:
8034 case OMP_TEAMS:
8035 case OMP_TARGET_DATA:
8036 case OMP_TARGET:
8037 case OMP_SECTIONS:
8038 case OMP_ORDERED:
8039 case OMP_CRITICAL:
8040 case OMP_SINGLE:
8041 case OMP_SCAN:
8042 case OMP_SCOPE:
8043 case OMP_SECTION:
8044 case OMP_MASTER:
8045 case OMP_MASKED:
8046 case OMP_TASKGROUP:
8047 case OMP_TARGET_UPDATE:
8048 case OMP_TARGET_ENTER_DATA:
8049 case OMP_TARGET_EXIT_DATA:
8050 case OMP_ATOMIC:
8051 case OMP_ATOMIC_READ:
8052 case OMP_ATOMIC_CAPTURE_OLD:
8053 case OMP_ATOMIC_CAPTURE_NEW:
8054 case OMP_DEPOBJ:
8055 case OACC_PARALLEL:
8056 case OACC_KERNELS:
8057 case OACC_SERIAL:
8058 case OACC_DATA:
8059 case OACC_HOST_DATA:
8060 case OACC_LOOP:
8061 case OACC_CACHE:
8062 case OACC_DECLARE:
8063 case OACC_ENTER_DATA:
8064 case OACC_EXIT_DATA:
8065 case OACC_UPDATE:
8066 if (!ctx->quiet)
8067 error_at (EXPR_LOCATION (t),
8068 "statement is not a constant expression");
8069 *non_constant_p = true;
8070 break;
8072 default:
8073 if (STATEMENT_CODE_P (TREE_CODE (t)))
8075 /* This function doesn't know how to deal with pre-genericize
8076 statements; this can only happen with statement-expressions,
8077 so for now just fail. */
8078 if (!ctx->quiet)
8079 error_at (EXPR_LOCATION (t),
8080 "statement is not a constant expression");
8082 else
8083 internal_error ("unexpected expression %qE of kind %s", t,
8084 get_tree_code_name (TREE_CODE (t)));
8085 *non_constant_p = true;
8086 break;
8089 if (r == error_mark_node)
8090 *non_constant_p = true;
8092 if (*non_constant_p)
8093 return t;
8094 else
8095 return r;
8098 /* P0859: A function is needed for constant evaluation if it is a constexpr
8099 function that is named by an expression ([basic.def.odr]) that is
8100 potentially constant evaluated.
8102 So we need to instantiate any constexpr functions mentioned by the
8103 expression even if the definition isn't needed for evaluating the
8104 expression. */
8106 static tree
8107 instantiate_cx_fn_r (tree *tp, int *walk_subtrees, void */*data*/)
8109 if (TREE_CODE (*tp) == FUNCTION_DECL
8110 && DECL_DECLARED_CONSTEXPR_P (*tp)
8111 && !DECL_INITIAL (*tp)
8112 && !trivial_fn_p (*tp)
8113 && DECL_TEMPLOID_INSTANTIATION (*tp)
8114 && !uid_sensitive_constexpr_evaluation_p ())
8116 ++function_depth;
8117 instantiate_decl (*tp, /*defer_ok*/false, /*expl_inst*/false);
8118 --function_depth;
8120 else if (TREE_CODE (*tp) == CALL_EXPR
8121 || TREE_CODE (*tp) == AGGR_INIT_EXPR)
8123 if (EXPR_HAS_LOCATION (*tp))
8124 input_location = EXPR_LOCATION (*tp);
8127 if (!EXPR_P (*tp))
8128 *walk_subtrees = 0;
8130 return NULL_TREE;
8133 static void
8134 instantiate_constexpr_fns (tree t)
8136 location_t loc = input_location;
8137 cp_walk_tree_without_duplicates (&t, instantiate_cx_fn_r, NULL);
8138 input_location = loc;
8141 /* Look for heap variables in the expression *TP. */
8143 static tree
8144 find_heap_var_refs (tree *tp, int *walk_subtrees, void */*data*/)
8146 if (VAR_P (*tp)
8147 && (DECL_NAME (*tp) == heap_uninit_identifier
8148 || DECL_NAME (*tp) == heap_identifier
8149 || DECL_NAME (*tp) == heap_vec_uninit_identifier
8150 || DECL_NAME (*tp) == heap_vec_identifier
8151 || DECL_NAME (*tp) == heap_deleted_identifier))
8152 return *tp;
8154 if (TYPE_P (*tp))
8155 *walk_subtrees = 0;
8156 return NULL_TREE;
8159 /* Find immediate function decls in *TP if any. */
8161 static tree
8162 find_immediate_fndecl (tree *tp, int */*walk_subtrees*/, void */*data*/)
8164 if (TREE_CODE (*tp) == FUNCTION_DECL && DECL_IMMEDIATE_FUNCTION_P (*tp))
8165 return *tp;
8166 if (TREE_CODE (*tp) == PTRMEM_CST
8167 && TREE_CODE (PTRMEM_CST_MEMBER (*tp)) == FUNCTION_DECL
8168 && DECL_IMMEDIATE_FUNCTION_P (PTRMEM_CST_MEMBER (*tp)))
8169 return PTRMEM_CST_MEMBER (*tp);
8170 return NULL_TREE;
8173 /* T has TREE_CONSTANT set but has been deemed not a valid C++ constant
8174 expression. Return a version of T that has TREE_CONSTANT cleared. */
8176 static tree
8177 mark_non_constant (tree t)
8179 gcc_checking_assert (TREE_CONSTANT (t));
8181 /* This isn't actually constant, so unset TREE_CONSTANT.
8182 Don't clear TREE_CONSTANT on ADDR_EXPR, as the middle-end requires
8183 it to be set if it is invariant address, even when it is not
8184 a valid C++ constant expression. Wrap it with a NOP_EXPR
8185 instead. */
8186 if (EXPR_P (t) && TREE_CODE (t) != ADDR_EXPR)
8187 t = copy_node (t);
8188 else if (TREE_CODE (t) == CONSTRUCTOR)
8189 t = build1 (VIEW_CONVERT_EXPR, TREE_TYPE (t), t);
8190 else
8191 t = build_nop (TREE_TYPE (t), t);
8192 TREE_CONSTANT (t) = false;
8193 return t;
8196 /* ALLOW_NON_CONSTANT is false if T is required to be a constant expression.
8197 STRICT has the same sense as for constant_value_1: true if we only allow
8198 conforming C++ constant expressions, or false if we want a constant value
8199 even if it doesn't conform.
8200 MANIFESTLY_CONST_EVAL is true if T is manifestly const-evaluated as
8201 per P0595 even when ALLOW_NON_CONSTANT is true.
8202 CONSTEXPR_DTOR is true when evaluating the dtor of a constexpr variable.
8203 OBJECT must be non-NULL in that case. */
8205 static tree
8206 cxx_eval_outermost_constant_expr (tree t, bool allow_non_constant,
8207 bool strict = true,
8208 mce_value manifestly_const_eval = mce_unknown,
8209 bool constexpr_dtor = false,
8210 tree object = NULL_TREE)
8212 auto_timevar time (TV_CONSTEXPR);
8214 bool non_constant_p = false;
8215 bool overflow_p = false;
8217 if (BRACE_ENCLOSED_INITIALIZER_P (t))
8219 gcc_checking_assert (allow_non_constant);
8220 return t;
8223 constexpr_global_ctx global_ctx;
8224 constexpr_ctx ctx = { &global_ctx, NULL, NULL, NULL, NULL, NULL, NULL,
8225 allow_non_constant, strict,
8226 !allow_non_constant ? mce_true : manifestly_const_eval };
8228 /* Turn off -frounding-math for manifestly constant evaluation. */
8229 warning_sentinel rm (flag_rounding_math,
8230 ctx.manifestly_const_eval == mce_true);
8231 tree type = initialized_type (t);
8232 tree r = t;
8233 bool is_consteval = false;
8234 if (VOID_TYPE_P (type))
8236 if (constexpr_dtor)
8237 /* Used for destructors of array elements. */
8238 type = TREE_TYPE (object);
8239 else
8241 if (cxx_dialect < cxx20)
8242 return t;
8243 if (TREE_CODE (t) != CALL_EXPR && TREE_CODE (t) != AGGR_INIT_EXPR)
8244 return t;
8245 /* Calls to immediate functions returning void need to be
8246 evaluated. */
8247 tree fndecl = cp_get_callee_fndecl_nofold (t);
8248 if (fndecl == NULL_TREE || !DECL_IMMEDIATE_FUNCTION_P (fndecl))
8249 return t;
8250 else
8251 is_consteval = true;
8254 else if (cxx_dialect >= cxx20
8255 && (TREE_CODE (t) == CALL_EXPR
8256 || TREE_CODE (t) == AGGR_INIT_EXPR
8257 || TREE_CODE (t) == TARGET_EXPR))
8259 /* For non-concept checks, determine if it is consteval. */
8260 if (!concept_check_p (t))
8262 tree x = t;
8263 if (TREE_CODE (x) == TARGET_EXPR)
8264 x = TARGET_EXPR_INITIAL (x);
8265 tree fndecl = cp_get_callee_fndecl_nofold (x);
8266 if (fndecl && DECL_IMMEDIATE_FUNCTION_P (fndecl))
8267 is_consteval = true;
8270 if (AGGREGATE_TYPE_P (type) || VECTOR_TYPE_P (type))
8272 /* In C++14 an NSDMI can participate in aggregate initialization,
8273 and can refer to the address of the object being initialized, so
8274 we need to pass in the relevant VAR_DECL if we want to do the
8275 evaluation in a single pass. The evaluation will dynamically
8276 update ctx.values for the VAR_DECL. We use the same strategy
8277 for C++11 constexpr constructors that refer to the object being
8278 initialized. */
8279 if (constexpr_dtor)
8281 gcc_assert (object && VAR_P (object));
8282 gcc_assert (DECL_DECLARED_CONSTEXPR_P (object));
8283 gcc_assert (DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (object));
8284 if (error_operand_p (DECL_INITIAL (object)))
8285 return t;
8286 ctx.ctor = unshare_expr (DECL_INITIAL (object));
8287 TREE_READONLY (ctx.ctor) = false;
8288 /* Temporarily force decl_really_constant_value to return false
8289 for it, we want to use ctx.ctor for the current value instead. */
8290 DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (object) = false;
8292 else
8294 ctx.ctor = build_constructor (type, NULL);
8295 CONSTRUCTOR_NO_CLEARING (ctx.ctor) = true;
8297 if (!object)
8299 if (TREE_CODE (t) == TARGET_EXPR)
8300 object = TARGET_EXPR_SLOT (t);
8301 else if (TREE_CODE (t) == AGGR_INIT_EXPR)
8302 object = AGGR_INIT_EXPR_SLOT (t);
8304 ctx.object = object;
8305 if (object)
8306 gcc_assert (same_type_ignoring_top_level_qualifiers_p
8307 (type, TREE_TYPE (object)));
8308 if (object && DECL_P (object))
8309 global_ctx.put_value (object, ctx.ctor);
8310 if (TREE_CODE (r) == TARGET_EXPR)
8311 /* Avoid creating another CONSTRUCTOR when we expand the
8312 TARGET_EXPR. */
8313 r = TARGET_EXPR_INITIAL (r);
8316 auto_vec<tree, 16> cleanups;
8317 global_ctx.cleanups = &cleanups;
8319 if (manifestly_const_eval == mce_true)
8320 instantiate_constexpr_fns (r);
8321 r = cxx_eval_constant_expression (&ctx, r, vc_prvalue,
8322 &non_constant_p, &overflow_p);
8324 if (!constexpr_dtor)
8325 verify_constant (r, allow_non_constant, &non_constant_p, &overflow_p);
8326 else
8327 DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (object) = true;
8329 unsigned int i;
8330 tree cleanup;
8331 /* Evaluate the cleanups. */
8332 FOR_EACH_VEC_ELT_REVERSE (cleanups, i, cleanup)
8333 cxx_eval_constant_expression (&ctx, cleanup, vc_discard,
8334 &non_constant_p, &overflow_p);
8336 /* Mutable logic is a bit tricky: we want to allow initialization of
8337 constexpr variables with mutable members, but we can't copy those
8338 members to another constexpr variable. */
8339 if (TREE_CODE (r) == CONSTRUCTOR && CONSTRUCTOR_MUTABLE_POISON (r))
8341 if (!allow_non_constant)
8342 error ("%qE is not a constant expression because it refers to "
8343 "mutable subobjects of %qT", t, type);
8344 non_constant_p = true;
8347 if (TREE_CODE (r) == CONSTRUCTOR && CONSTRUCTOR_NO_CLEARING (r))
8349 if (!allow_non_constant)
8350 error ("%qE is not a constant expression because it refers to "
8351 "an incompletely initialized variable", t);
8352 TREE_CONSTANT (r) = false;
8353 non_constant_p = true;
8356 if (!global_ctx.heap_vars.is_empty ())
8358 tree heap_var = cp_walk_tree_without_duplicates (&r, find_heap_var_refs,
8359 NULL);
8360 unsigned int i;
8361 if (heap_var)
8363 if (!allow_non_constant && !non_constant_p)
8364 error_at (DECL_SOURCE_LOCATION (heap_var),
8365 "%qE is not a constant expression because it refers to "
8366 "a result of %<operator new%>", t);
8367 r = t;
8368 non_constant_p = true;
8370 FOR_EACH_VEC_ELT (global_ctx.heap_vars, i, heap_var)
8372 if (DECL_NAME (heap_var) != heap_deleted_identifier)
8374 if (!allow_non_constant && !non_constant_p)
8375 error_at (DECL_SOURCE_LOCATION (heap_var),
8376 "%qE is not a constant expression because allocated "
8377 "storage has not been deallocated", t);
8378 r = t;
8379 non_constant_p = true;
8381 varpool_node::get (heap_var)->remove ();
8385 /* Check that immediate invocation does not return an expression referencing
8386 any immediate function decls. */
8387 if (is_consteval || in_immediate_context ())
8388 if (tree immediate_fndecl
8389 = cp_walk_tree_without_duplicates (&r, find_immediate_fndecl,
8390 NULL))
8392 if (!allow_non_constant && !non_constant_p)
8393 error_at (cp_expr_loc_or_input_loc (t),
8394 "immediate evaluation returns address of immediate "
8395 "function %qD", immediate_fndecl);
8396 r = t;
8397 non_constant_p = true;
8400 if (non_constant_p)
8401 /* If we saw something bad, go back to our argument. The wrapping below is
8402 only for the cases of TREE_CONSTANT argument or overflow. */
8403 r = t;
8405 if (!non_constant_p && overflow_p)
8406 non_constant_p = true;
8408 /* Unshare the result. */
8409 bool should_unshare = true;
8410 if (r == t || (TREE_CODE (t) == TARGET_EXPR
8411 && TARGET_EXPR_INITIAL (t) == r))
8412 should_unshare = false;
8414 if (non_constant_p && !allow_non_constant)
8415 return error_mark_node;
8416 else if (constexpr_dtor)
8417 return r;
8418 else if (non_constant_p && TREE_CONSTANT (r))
8419 r = mark_non_constant (r);
8420 else if (non_constant_p)
8421 return t;
8423 if (should_unshare)
8424 r = unshare_expr (r);
8426 if (TREE_CODE (r) == CONSTRUCTOR && CLASS_TYPE_P (TREE_TYPE (r)))
8428 r = adjust_temp_type (type, r);
8429 if (TREE_CODE (t) == TARGET_EXPR
8430 && TARGET_EXPR_INITIAL (t) == r)
8431 return t;
8432 else if (TREE_CODE (t) == CONSTRUCTOR || TREE_CODE (t) == CALL_EXPR)
8433 /* Don't add a TARGET_EXPR if our argument didn't have one. */;
8434 else if (TREE_CODE (t) == TARGET_EXPR && TARGET_EXPR_CLEANUP (t))
8435 r = get_target_expr (r);
8436 else
8438 r = get_target_expr (r, tf_warning_or_error | tf_no_cleanup);
8439 TREE_CONSTANT (r) = true;
8443 /* Remember the original location if that wouldn't need a wrapper. */
8444 if (location_t loc = EXPR_LOCATION (t))
8445 protected_set_expr_location (r, loc);
8447 return r;
8450 /* If T represents a constant expression returns its reduced value.
8451 Otherwise return error_mark_node. */
8453 tree
8454 cxx_constant_value (tree t, tree decl /* = NULL_TREE */,
8455 tsubst_flags_t complain /* = tf_error */)
8457 bool sfinae = !(complain & tf_error);
8458 tree r = cxx_eval_outermost_constant_expr (t, sfinae, true, mce_true, false, decl);
8459 if (sfinae && !TREE_CONSTANT (r))
8460 r = error_mark_node;
8461 return r;
8464 /* Like cxx_constant_value, but used for evaluation of constexpr destructors
8465 of constexpr variables. The actual initializer of DECL is not modified. */
8467 void
8468 cxx_constant_dtor (tree t, tree decl)
8470 cxx_eval_outermost_constant_expr (t, false, true, mce_true, true, decl);
8473 /* Helper routine for fold_simple function. Either return simplified
8474 expression T, otherwise NULL_TREE.
8475 In contrast to cp_fully_fold, and to maybe_constant_value, we try to fold
8476 even if we are within template-declaration. So be careful on call, as in
8477 such case types can be undefined. */
8479 static tree
8480 fold_simple_1 (tree t)
8482 tree op1;
8483 enum tree_code code = TREE_CODE (t);
8485 switch (code)
8487 case INTEGER_CST:
8488 case REAL_CST:
8489 case VECTOR_CST:
8490 case FIXED_CST:
8491 case COMPLEX_CST:
8492 return t;
8494 case SIZEOF_EXPR:
8495 return fold_sizeof_expr (t);
8497 case ABS_EXPR:
8498 case ABSU_EXPR:
8499 case CONJ_EXPR:
8500 case REALPART_EXPR:
8501 case IMAGPART_EXPR:
8502 case NEGATE_EXPR:
8503 case BIT_NOT_EXPR:
8504 case TRUTH_NOT_EXPR:
8505 case VIEW_CONVERT_EXPR:
8506 CASE_CONVERT:
8507 case FLOAT_EXPR:
8508 case FIX_TRUNC_EXPR:
8509 case FIXED_CONVERT_EXPR:
8510 case ADDR_SPACE_CONVERT_EXPR:
8512 op1 = TREE_OPERAND (t, 0);
8514 t = const_unop (code, TREE_TYPE (t), op1);
8515 if (!t)
8516 return NULL_TREE;
8518 if (CONVERT_EXPR_CODE_P (code)
8519 && TREE_OVERFLOW_P (t) && !TREE_OVERFLOW_P (op1))
8520 TREE_OVERFLOW (t) = false;
8521 return t;
8523 default:
8524 return NULL_TREE;
8528 /* If T is a simple constant expression, returns its simplified value.
8529 Otherwise returns T. In contrast to maybe_constant_value we
8530 simplify only few operations on constant-expressions, and we don't
8531 try to simplify constexpressions. */
8533 tree
8534 fold_simple (tree t)
8536 if (processing_template_decl)
8537 return t;
8539 tree r = fold_simple_1 (t);
8540 if (r)
8541 return r;
8543 return t;
8546 /* Try folding the expression T to a simple constant.
8547 Returns that constant, otherwise returns T. */
8549 tree
8550 fold_to_constant (tree t)
8552 tree r = fold (t);
8553 if (CONSTANT_CLASS_P (r) && !TREE_OVERFLOW (r))
8554 return r;
8555 else
8556 return t;
8559 /* If T is a constant expression, returns its reduced value.
8560 Otherwise, if T does not have TREE_CONSTANT set, returns T.
8561 Otherwise, returns a version of T without TREE_CONSTANT.
8562 MANIFESTLY_CONST_EVAL is true if T is manifestly const-evaluated
8563 as per P0595. */
8565 static GTY((deletable)) hash_map<tree, tree> *cv_cache;
8567 tree
8568 maybe_constant_value (tree t, tree decl /* = NULL_TREE */,
8569 mce_value manifestly_const_eval /* = mce_unknown */)
8571 tree r;
8573 if (!is_nondependent_constant_expression (t))
8575 if (TREE_OVERFLOW_P (t)
8576 || (!processing_template_decl && TREE_CONSTANT (t)))
8577 t = mark_non_constant (t);
8578 return t;
8580 else if (CONSTANT_CLASS_P (t))
8581 /* No caching or evaluation needed. */
8582 return t;
8584 /* Don't constant evaluate an unevaluated non-manifestly-constant operand,
8585 but at least try folding it to a simple constant. */
8586 if (cp_unevaluated_operand && manifestly_const_eval != mce_true)
8587 return fold_to_constant (t);
8589 if (manifestly_const_eval != mce_unknown)
8590 return cxx_eval_outermost_constant_expr (t, true, true,
8591 manifestly_const_eval, false, decl);
8593 if (cv_cache == NULL)
8594 cv_cache = hash_map<tree, tree>::create_ggc (101);
8595 if (tree *cached = cv_cache->get (t))
8597 r = *cached;
8598 if (r != t)
8600 /* Clear processing_template_decl for sake of break_out_target_exprs;
8601 entries in the cv_cache are non-templated. */
8602 processing_template_decl_sentinel ptds;
8604 r = break_out_target_exprs (r, /*clear_loc*/true);
8605 protected_set_expr_location (r, EXPR_LOCATION (t));
8607 return r;
8610 uid_sensitive_constexpr_evaluation_checker c;
8611 r = cxx_eval_outermost_constant_expr (t, true, true,
8612 manifestly_const_eval, false, decl);
8613 gcc_checking_assert (r == t
8614 || CONVERT_EXPR_P (t)
8615 || TREE_CODE (t) == VIEW_CONVERT_EXPR
8616 || (TREE_CONSTANT (t) && !TREE_CONSTANT (r))
8617 || !cp_tree_equal (r, t));
8618 if (!c.evaluation_restricted_p ())
8619 cv_cache->put (t, r);
8620 return r;
8623 /* Dispose of the whole CV_CACHE. */
8625 static void
8626 clear_cv_cache (void)
8628 if (cv_cache != NULL)
8629 cv_cache->empty ();
8632 /* Dispose of the whole CV_CACHE and FOLD_CACHE. */
8634 void
8635 clear_cv_and_fold_caches ()
8637 clear_cv_cache ();
8638 clear_fold_cache ();
8641 /* Internal function handling expressions in templates for
8642 fold_non_dependent_expr and fold_non_dependent_init.
8644 If we're in a template, but T isn't value dependent, simplify
8645 it. We're supposed to treat:
8647 template <typename T> void f(T[1 + 1]);
8648 template <typename T> void f(T[2]);
8650 as two declarations of the same function, for example. */
8652 static tree
8653 fold_non_dependent_expr_template (tree t, tsubst_flags_t complain,
8654 bool manifestly_const_eval,
8655 tree object)
8657 gcc_assert (processing_template_decl);
8659 if (is_nondependent_constant_expression (t))
8661 processing_template_decl_sentinel s;
8662 t = instantiate_non_dependent_expr_internal (t, complain);
8664 if (type_unknown_p (t) || BRACE_ENCLOSED_INITIALIZER_P (t))
8666 if (TREE_OVERFLOW_P (t))
8668 t = build_nop (TREE_TYPE (t), t);
8669 TREE_CONSTANT (t) = false;
8671 return t;
8673 else if (CONSTANT_CLASS_P (t))
8674 /* No evaluation needed. */
8675 return t;
8677 /* Don't constant evaluate an unevaluated non-manifestly-constant operand,
8678 but at least try folding it to a simple constant. */
8679 if (cp_unevaluated_operand && !manifestly_const_eval)
8680 return fold_to_constant (t);
8682 tree r = cxx_eval_outermost_constant_expr (t, true, true,
8683 mce_value (manifestly_const_eval),
8684 false, object);
8685 /* cp_tree_equal looks through NOPs, so allow them. */
8686 gcc_checking_assert (r == t
8687 || CONVERT_EXPR_P (t)
8688 || TREE_CODE (t) == VIEW_CONVERT_EXPR
8689 || (TREE_CONSTANT (t) && !TREE_CONSTANT (r))
8690 || !cp_tree_equal (r, t));
8691 return r;
8693 else if (TREE_OVERFLOW_P (t))
8695 t = build_nop (TREE_TYPE (t), t);
8696 TREE_CONSTANT (t) = false;
8699 return t;
8702 /* Like maybe_constant_value but first fully instantiate the argument.
8704 Note: this is equivalent to instantiate_non_dependent_expr (t, complain)
8705 followed by maybe_constant_value but is more efficient,
8706 because it calls instantiation_dependent_expression_p and
8707 potential_constant_expression at most once.
8708 The manifestly_const_eval argument is passed to maybe_constant_value.
8710 Callers should generally pass their active complain, or if they are in a
8711 non-template, diagnosing context, they can use the default of
8712 tf_warning_or_error. Callers that might be within a template context, don't
8713 have a complain parameter, and aren't going to remember the result for long
8714 (e.g. null_ptr_cst_p), can pass tf_none and deal with error_mark_node
8715 appropriately. */
8717 tree
8718 fold_non_dependent_expr (tree t,
8719 tsubst_flags_t complain /* = tf_warning_or_error */,
8720 bool manifestly_const_eval /* = false */,
8721 tree object /* = NULL_TREE */)
8723 if (t == NULL_TREE)
8724 return NULL_TREE;
8726 if (processing_template_decl)
8727 return fold_non_dependent_expr_template (t, complain,
8728 manifestly_const_eval, object);
8730 return maybe_constant_value (t, object, mce_value (manifestly_const_eval));
8733 /* Like fold_non_dependent_expr, but if EXPR couldn't be folded to a constant,
8734 return the original expression. */
8736 tree
8737 maybe_fold_non_dependent_expr (tree expr,
8738 tsubst_flags_t complain/*=tf_warning_or_error*/)
8740 tree t = fold_non_dependent_expr (expr, complain);
8741 if (t && TREE_CONSTANT (t))
8742 return t;
8744 return expr;
8747 /* Like maybe_constant_init but first fully instantiate the argument. */
8749 tree
8750 fold_non_dependent_init (tree t,
8751 tsubst_flags_t complain /*=tf_warning_or_error*/,
8752 bool manifestly_const_eval /*=false*/,
8753 tree object /* = NULL_TREE */)
8755 if (t == NULL_TREE)
8756 return NULL_TREE;
8758 if (processing_template_decl)
8760 t = fold_non_dependent_expr_template (t, complain,
8761 manifestly_const_eval, object);
8762 /* maybe_constant_init does this stripping, so do it here too. */
8763 if (TREE_CODE (t) == TARGET_EXPR)
8765 tree init = TARGET_EXPR_INITIAL (t);
8766 if (TREE_CODE (init) == CONSTRUCTOR)
8767 t = init;
8769 return t;
8772 return maybe_constant_init (t, object, manifestly_const_eval);
8775 /* Like maybe_constant_value, but returns a CONSTRUCTOR directly, rather
8776 than wrapped in a TARGET_EXPR.
8777 ALLOW_NON_CONSTANT is false if T is required to be a constant expression.
8778 MANIFESTLY_CONST_EVAL is true if T is manifestly const-evaluated as
8779 per P0595 even when ALLOW_NON_CONSTANT is true. */
8781 static tree
8782 maybe_constant_init_1 (tree t, tree decl, bool allow_non_constant,
8783 bool manifestly_const_eval)
8785 if (!t)
8786 return t;
8787 if (TREE_CODE (t) == EXPR_STMT)
8788 t = TREE_OPERAND (t, 0);
8789 if (TREE_CODE (t) == CONVERT_EXPR
8790 && VOID_TYPE_P (TREE_TYPE (t)))
8791 t = TREE_OPERAND (t, 0);
8792 if (TREE_CODE (t) == INIT_EXPR)
8793 t = TREE_OPERAND (t, 1);
8794 if (TREE_CODE (t) == TARGET_EXPR)
8795 t = TARGET_EXPR_INITIAL (t);
8796 if (!is_nondependent_static_init_expression (t))
8797 /* Don't try to evaluate it. */;
8798 else if (CONSTANT_CLASS_P (t) && allow_non_constant)
8799 /* No evaluation needed. */;
8800 else
8802 /* [basic.start.static] allows constant-initialization of variables with
8803 static or thread storage duration even if it isn't required, but we
8804 shouldn't bend the rules the same way for automatic variables. */
8805 bool is_static = (decl && DECL_P (decl)
8806 && (TREE_STATIC (decl) || DECL_EXTERNAL (decl)));
8807 if (is_static)
8808 manifestly_const_eval = true;
8810 if (cp_unevaluated_operand && !manifestly_const_eval)
8811 return fold_to_constant (t);
8813 t = cxx_eval_outermost_constant_expr (t, allow_non_constant, !is_static,
8814 mce_value (manifestly_const_eval),
8815 false, decl);
8817 if (TREE_CODE (t) == TARGET_EXPR)
8819 tree init = TARGET_EXPR_INITIAL (t);
8820 if (TREE_CODE (init) == CONSTRUCTOR)
8821 t = init;
8823 return t;
8826 /* Wrapper for maybe_constant_init_1 which permits non constants. */
8828 tree
8829 maybe_constant_init (tree t, tree decl, bool manifestly_const_eval)
8831 return maybe_constant_init_1 (t, decl, true, manifestly_const_eval);
8834 /* Wrapper for maybe_constant_init_1 which does not permit non constants. */
8836 tree
8837 cxx_constant_init (tree t, tree decl)
8839 return maybe_constant_init_1 (t, decl, false, true);
8842 #if 0
8843 /* FIXME see ADDR_EXPR section in potential_constant_expression_1. */
8844 /* Return true if the object referred to by REF has automatic or thread
8845 local storage. */
8847 enum { ck_ok, ck_bad, ck_unknown };
8848 static int
8849 check_automatic_or_tls (tree ref)
8851 machine_mode mode;
8852 poly_int64 bitsize, bitpos;
8853 tree offset;
8854 int volatilep = 0, unsignedp = 0;
8855 tree decl = get_inner_reference (ref, &bitsize, &bitpos, &offset,
8856 &mode, &unsignedp, &volatilep, false);
8857 duration_kind dk;
8859 /* If there isn't a decl in the middle, we don't know the linkage here,
8860 and this isn't a constant expression anyway. */
8861 if (!DECL_P (decl))
8862 return ck_unknown;
8863 dk = decl_storage_duration (decl);
8864 return (dk == dk_auto || dk == dk_thread) ? ck_bad : ck_ok;
8866 #endif
8868 /* Data structure for passing data from potential_constant_expression_1
8869 to check_for_return_continue via cp_walk_tree. */
8870 struct check_for_return_continue_data {
8871 hash_set<tree> *pset;
8872 tree continue_stmt;
8873 tree break_stmt;
8876 /* Helper function for potential_constant_expression_1 SWITCH_STMT handling,
8877 called through cp_walk_tree. Return the first RETURN_EXPR found, or note
8878 the first CONTINUE_STMT and/or BREAK_STMT if RETURN_EXPR is not found. */
8879 static tree
8880 check_for_return_continue (tree *tp, int *walk_subtrees, void *data)
8882 tree t = *tp, s, b;
8883 check_for_return_continue_data *d = (check_for_return_continue_data *) data;
8884 switch (TREE_CODE (t))
8886 case RETURN_EXPR:
8887 return t;
8889 case CONTINUE_STMT:
8890 if (d->continue_stmt == NULL_TREE)
8891 d->continue_stmt = t;
8892 break;
8894 case BREAK_STMT:
8895 if (d->break_stmt == NULL_TREE)
8896 d->break_stmt = t;
8897 break;
8899 #define RECUR(x) \
8900 if (tree r = cp_walk_tree (&x, check_for_return_continue, data, \
8901 d->pset)) \
8902 return r
8904 /* For loops, walk subtrees manually, so that continue stmts found
8905 inside of the bodies of the loops are ignored. */
8906 case DO_STMT:
8907 *walk_subtrees = 0;
8908 RECUR (DO_COND (t));
8909 s = d->continue_stmt;
8910 b = d->break_stmt;
8911 RECUR (DO_BODY (t));
8912 d->continue_stmt = s;
8913 d->break_stmt = b;
8914 break;
8916 case WHILE_STMT:
8917 *walk_subtrees = 0;
8918 RECUR (WHILE_COND (t));
8919 s = d->continue_stmt;
8920 b = d->break_stmt;
8921 RECUR (WHILE_BODY (t));
8922 d->continue_stmt = s;
8923 d->break_stmt = b;
8924 break;
8926 case FOR_STMT:
8927 *walk_subtrees = 0;
8928 RECUR (FOR_INIT_STMT (t));
8929 RECUR (FOR_COND (t));
8930 RECUR (FOR_EXPR (t));
8931 s = d->continue_stmt;
8932 b = d->break_stmt;
8933 RECUR (FOR_BODY (t));
8934 d->continue_stmt = s;
8935 d->break_stmt = b;
8936 break;
8938 case RANGE_FOR_STMT:
8939 *walk_subtrees = 0;
8940 RECUR (RANGE_FOR_EXPR (t));
8941 s = d->continue_stmt;
8942 b = d->break_stmt;
8943 RECUR (RANGE_FOR_BODY (t));
8944 d->continue_stmt = s;
8945 d->break_stmt = b;
8946 break;
8948 case SWITCH_STMT:
8949 *walk_subtrees = 0;
8950 RECUR (SWITCH_STMT_COND (t));
8951 b = d->break_stmt;
8952 RECUR (SWITCH_STMT_BODY (t));
8953 d->break_stmt = b;
8954 break;
8955 #undef RECUR
8957 case STATEMENT_LIST:
8958 case CONSTRUCTOR:
8959 break;
8961 default:
8962 if (!EXPR_P (t))
8963 *walk_subtrees = 0;
8964 break;
8967 return NULL_TREE;
8970 /* Return true if T denotes a potentially constant expression. Issue
8971 diagnostic as appropriate under control of FLAGS. If WANT_RVAL is true,
8972 an lvalue-rvalue conversion is implied. If NOW is true, we want to
8973 consider the expression in the current context, independent of constexpr
8974 substitution. If FUNDEF_P is true, we're checking a constexpr function body
8975 and hard errors should not be reported by constexpr_error.
8977 C++0x [expr.const] used to say
8979 6 An expression is a potential constant expression if it is
8980 a constant expression where all occurrences of function
8981 parameters are replaced by arbitrary constant expressions
8982 of the appropriate type.
8984 2 A conditional expression is a constant expression unless it
8985 involves one of the following as a potentially evaluated
8986 subexpression (3.2), but subexpressions of logical AND (5.14),
8987 logical OR (5.15), and conditional (5.16) operations that are
8988 not evaluated are not considered. */
8990 static bool
8991 potential_constant_expression_1 (tree t, bool want_rval, bool strict, bool now,
8992 bool fundef_p, tsubst_flags_t flags,
8993 tree *jump_target)
8995 #define RECUR(T,RV) \
8996 potential_constant_expression_1 ((T), (RV), strict, now, fundef_p, flags, \
8997 jump_target)
8999 enum { any = false, rval = true };
9000 int i;
9001 tree tmp;
9003 if (t == error_mark_node)
9004 return false;
9005 if (t == NULL_TREE)
9006 return true;
9007 location_t loc = cp_expr_loc_or_input_loc (t);
9009 if (*jump_target)
9010 /* If we are jumping, ignore everything. This is simpler than the
9011 cxx_eval_constant_expression handling because we only need to be
9012 conservatively correct, and we don't necessarily have a constant value
9013 available, so we don't bother with switch tracking. */
9014 return true;
9016 if (TREE_THIS_VOLATILE (t) && want_rval)
9018 if (flags & tf_error)
9019 constexpr_error (loc, fundef_p, "lvalue-to-rvalue conversion of "
9020 "a volatile lvalue %qE with type %qT", t,
9021 TREE_TYPE (t));
9022 return false;
9024 if (CONSTANT_CLASS_P (t))
9025 return true;
9026 if (CODE_CONTAINS_STRUCT (TREE_CODE (t), TS_TYPED)
9027 && TREE_TYPE (t) == error_mark_node)
9028 return false;
9030 switch (TREE_CODE (t))
9032 case FUNCTION_DECL:
9033 case BASELINK:
9034 case TEMPLATE_DECL:
9035 case OVERLOAD:
9036 case TEMPLATE_ID_EXPR:
9037 case LABEL_DECL:
9038 case CASE_LABEL_EXPR:
9039 case PREDICT_EXPR:
9040 case CONST_DECL:
9041 case SIZEOF_EXPR:
9042 case ALIGNOF_EXPR:
9043 case OFFSETOF_EXPR:
9044 case NOEXCEPT_EXPR:
9045 case TEMPLATE_PARM_INDEX:
9046 case TRAIT_EXPR:
9047 case IDENTIFIER_NODE:
9048 case USERDEF_LITERAL:
9049 /* We can see a FIELD_DECL in a pointer-to-member expression. */
9050 case FIELD_DECL:
9051 case RESULT_DECL:
9052 case USING_DECL:
9053 case USING_STMT:
9054 case PLACEHOLDER_EXPR:
9055 case REQUIRES_EXPR:
9056 case STATIC_ASSERT:
9057 case DEBUG_BEGIN_STMT:
9058 return true;
9060 case RETURN_EXPR:
9061 if (!RECUR (TREE_OPERAND (t, 0), any))
9062 return false;
9063 /* FALLTHROUGH */
9065 case BREAK_STMT:
9066 case CONTINUE_STMT:
9067 *jump_target = t;
9068 return true;
9070 case PARM_DECL:
9071 if (now && want_rval)
9073 tree type = TREE_TYPE (t);
9074 if ((processing_template_decl && !COMPLETE_TYPE_P (type))
9075 || dependent_type_p (type)
9076 || is_really_empty_class (type, /*ignore_vptr*/false))
9077 /* An empty class has no data to read. */
9078 return true;
9079 if (flags & tf_error)
9080 constexpr_error (input_location, fundef_p,
9081 "%qE is not a constant expression", t);
9082 return false;
9084 return true;
9086 case AGGR_INIT_EXPR:
9087 case CALL_EXPR:
9088 /* -- an invocation of a function other than a constexpr function
9089 or a constexpr constructor. */
9091 tree fun = get_function_named_in_call (t);
9092 const int nargs = call_expr_nargs (t);
9093 i = 0;
9095 if (fun == NULL_TREE)
9097 /* Reset to allow the function to continue past the end
9098 of the block below. Otherwise return early. */
9099 bool bail = true;
9101 if (TREE_CODE (t) == CALL_EXPR
9102 && CALL_EXPR_FN (t) == NULL_TREE)
9103 switch (CALL_EXPR_IFN (t))
9105 /* These should be ignored, they are optimized away from
9106 constexpr functions. */
9107 case IFN_UBSAN_NULL:
9108 case IFN_UBSAN_BOUNDS:
9109 case IFN_UBSAN_VPTR:
9110 case IFN_FALLTHROUGH:
9111 case IFN_ASSUME:
9112 return true;
9114 case IFN_ADD_OVERFLOW:
9115 case IFN_SUB_OVERFLOW:
9116 case IFN_MUL_OVERFLOW:
9117 case IFN_LAUNDER:
9118 case IFN_VEC_CONVERT:
9119 bail = false;
9120 break;
9122 default:
9123 break;
9126 if (bail)
9128 /* fold_call_expr can't do anything with IFN calls. */
9129 if (flags & tf_error)
9130 constexpr_error (loc, fundef_p,
9131 "call to internal function %qE", t);
9132 return false;
9136 if (fun && is_overloaded_fn (fun))
9138 if (TREE_CODE (fun) == FUNCTION_DECL)
9140 if (builtin_valid_in_constant_expr_p (fun))
9141 return true;
9142 if (!maybe_constexpr_fn (fun)
9143 /* Allow any built-in function; if the expansion
9144 isn't constant, we'll deal with that then. */
9145 && !fndecl_built_in_p (fun)
9146 /* In C++20, replaceable global allocation functions
9147 are constant expressions. */
9148 && (!cxx_replaceable_global_alloc_fn (fun)
9149 || TREE_CODE (t) != CALL_EXPR
9150 || (!CALL_FROM_NEW_OR_DELETE_P (t)
9151 && (current_function_decl == NULL_TREE
9152 || !is_std_allocator_allocate
9153 (current_function_decl))))
9154 /* Allow placement new in std::construct_at. */
9155 && (!cxx_placement_new_fn (fun)
9156 || TREE_CODE (t) != CALL_EXPR
9157 || current_function_decl == NULL_TREE
9158 || !is_std_construct_at (current_function_decl))
9159 && !cxx_dynamic_cast_fn_p (fun))
9161 if ((flags & tf_error)
9162 && constexpr_error (loc, fundef_p,
9163 "call to non-%<constexpr%> "
9164 "function %qD", fun))
9165 explain_invalid_constexpr_fn (fun);
9166 return false;
9168 /* A call to a non-static member function takes the address
9169 of the object as the first argument. But in a constant
9170 expression the address will be folded away, so look
9171 through it now. */
9172 if (DECL_NONSTATIC_MEMBER_FUNCTION_P (fun)
9173 && !DECL_CONSTRUCTOR_P (fun))
9175 tree x = get_nth_callarg (t, 0);
9176 if (is_this_parameter (x))
9177 return true;
9178 /* Don't require an immediately constant value, as
9179 constexpr substitution might not use the value. */
9180 bool sub_now = false;
9181 if (!potential_constant_expression_1 (x, rval, strict,
9182 sub_now, fundef_p,
9183 flags, jump_target))
9184 return false;
9185 i = 1;
9188 else
9190 if (!RECUR (fun, true))
9191 return false;
9192 fun = get_first_fn (fun);
9194 /* Skip initial arguments to base constructors. */
9195 if (DECL_BASE_CONSTRUCTOR_P (fun))
9196 i = num_artificial_parms_for (fun);
9197 fun = DECL_ORIGIN (fun);
9199 else if (fun)
9201 if (RECUR (fun, FUNCTION_POINTER_TYPE_P (fun) ? rval : any))
9202 /* Might end up being a constant function pointer. But it
9203 could also be a function object with constexpr op(), so
9204 we pass 'any' so that the underlying VAR_DECL is deemed
9205 as potentially-constant even though it wasn't declared
9206 constexpr. */;
9207 else
9208 return false;
9210 for (; i < nargs; ++i)
9212 tree x = get_nth_callarg (t, i);
9213 /* In a template, reference arguments haven't been converted to
9214 REFERENCE_TYPE and we might not even know if the parameter
9215 is a reference, so accept lvalue constants too. */
9216 bool rv = processing_template_decl ? any : rval;
9217 /* Don't require an immediately constant value, as constexpr
9218 substitution might not use the value of the argument. */
9219 bool sub_now = false;
9220 if (!potential_constant_expression_1 (x, rv, strict,
9221 sub_now, fundef_p, flags,
9222 jump_target))
9223 return false;
9225 return true;
9228 case NON_LVALUE_EXPR:
9229 /* -- an lvalue-to-rvalue conversion (4.1) unless it is applied to
9230 -- an lvalue of integral type that refers to a non-volatile
9231 const variable or static data member initialized with
9232 constant expressions, or
9234 -- an lvalue of literal type that refers to non-volatile
9235 object defined with constexpr, or that refers to a
9236 sub-object of such an object; */
9237 return RECUR (TREE_OPERAND (t, 0), rval);
9239 case EXCESS_PRECISION_EXPR:
9240 return RECUR (TREE_OPERAND (t, 0), rval);
9242 case VAR_DECL:
9243 if (DECL_HAS_VALUE_EXPR_P (t))
9245 if (now && is_normal_capture_proxy (t))
9247 /* -- in a lambda-expression, a reference to this or to a
9248 variable with automatic storage duration defined outside that
9249 lambda-expression, where the reference would be an
9250 odr-use. */
9252 if (want_rval)
9253 /* Since we're doing an lvalue-rvalue conversion, this might
9254 not be an odr-use, so evaluate the variable directly. */
9255 return RECUR (DECL_CAPTURED_VARIABLE (t), rval);
9257 if (flags & tf_error)
9259 tree cap = DECL_CAPTURED_VARIABLE (t);
9260 if (constexpr_error (input_location, fundef_p,
9261 "lambda capture of %qE is not a "
9262 "constant expression", cap)
9263 && decl_constant_var_p (cap))
9264 inform (input_location, "because it is used as a glvalue");
9266 return false;
9268 /* Treat __PRETTY_FUNCTION__ inside a template function as
9269 potentially-constant. */
9270 else if (DECL_PRETTY_FUNCTION_P (t)
9271 && DECL_VALUE_EXPR (t) == error_mark_node)
9272 return true;
9273 return RECUR (DECL_VALUE_EXPR (t), rval);
9275 if (want_rval
9276 && !var_in_maybe_constexpr_fn (t)
9277 && !type_dependent_expression_p (t)
9278 && !decl_maybe_constant_var_p (t)
9279 && (strict
9280 || !CP_TYPE_CONST_NON_VOLATILE_P (TREE_TYPE (t))
9281 || (DECL_INITIAL (t)
9282 && !DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (t)))
9283 && COMPLETE_TYPE_P (TREE_TYPE (t))
9284 && !is_really_empty_class (TREE_TYPE (t), /*ignore_vptr*/false))
9286 if (flags & tf_error)
9287 non_const_var_error (loc, t, fundef_p);
9288 return false;
9290 return true;
9292 case NOP_EXPR:
9293 if (REINTERPRET_CAST_P (t))
9295 if (flags & tf_error)
9296 constexpr_error (loc, fundef_p, "%<reinterpret_cast%> is not a "
9297 "constant expression");
9298 return false;
9300 /* FALLTHRU */
9301 case CONVERT_EXPR:
9302 case VIEW_CONVERT_EXPR:
9303 /* -- a reinterpret_cast. FIXME not implemented, and this rule
9304 may change to something more specific to type-punning (DR 1312). */
9306 tree from = TREE_OPERAND (t, 0);
9307 if (location_wrapper_p (t))
9309 iloc_sentinel ils = loc;
9310 return (RECUR (from, want_rval));
9312 if (INDIRECT_TYPE_P (TREE_TYPE (t)))
9314 STRIP_ANY_LOCATION_WRAPPER (from);
9315 if (TREE_CODE (from) == INTEGER_CST
9316 && !integer_zerop (from))
9318 if (flags & tf_error)
9319 constexpr_error (loc, fundef_p,
9320 "%<reinterpret_cast%> from integer to "
9321 "pointer");
9322 return false;
9325 return (RECUR (from, TREE_CODE (t) != VIEW_CONVERT_EXPR));
9328 case ADDRESSOF_EXPR:
9329 /* This is like ADDR_EXPR, except it won't form pointer-to-member. */
9330 t = TREE_OPERAND (t, 0);
9331 goto handle_addr_expr;
9333 case ADDR_EXPR:
9334 /* -- a unary operator & that is applied to an lvalue that
9335 designates an object with thread or automatic storage
9336 duration; */
9337 t = TREE_OPERAND (t, 0);
9339 if (TREE_CODE (t) == OFFSET_REF && PTRMEM_OK_P (t))
9340 /* A pointer-to-member constant. */
9341 return true;
9343 handle_addr_expr:
9344 #if 0
9345 /* FIXME adjust when issue 1197 is fully resolved. For now don't do
9346 any checking here, as we might dereference the pointer later. If
9347 we remove this code, also remove check_automatic_or_tls. */
9348 i = check_automatic_or_tls (t);
9349 if (i == ck_ok)
9350 return true;
9351 if (i == ck_bad)
9353 if (flags & tf_error)
9354 error ("address-of an object %qE with thread local or "
9355 "automatic storage is not a constant expression", t);
9356 return false;
9358 #endif
9359 return RECUR (t, any);
9361 case COMPONENT_REF:
9362 case ARROW_EXPR:
9363 case OFFSET_REF:
9364 /* -- a class member access unless its postfix-expression is
9365 of literal type or of pointer to literal type. */
9366 /* This test would be redundant, as it follows from the
9367 postfix-expression being a potential constant expression. */
9368 if (type_unknown_p (t))
9369 return true;
9370 if (is_overloaded_fn (t))
9371 /* In a template, a COMPONENT_REF of a function expresses ob.fn(),
9372 which uses ob as an lvalue. */
9373 want_rval = false;
9374 gcc_fallthrough ();
9376 case REALPART_EXPR:
9377 case IMAGPART_EXPR:
9378 case BIT_FIELD_REF:
9379 return RECUR (TREE_OPERAND (t, 0), want_rval);
9381 case EXPR_PACK_EXPANSION:
9382 return RECUR (PACK_EXPANSION_PATTERN (t), want_rval);
9384 case INDIRECT_REF:
9386 tree x = TREE_OPERAND (t, 0);
9387 STRIP_NOPS (x);
9388 if (is_this_parameter (x) && !is_capture_proxy (x))
9390 if (!var_in_maybe_constexpr_fn (x))
9392 if (flags & tf_error)
9393 constexpr_error (loc, fundef_p, "use of %<this%> in a "
9394 "constant expression");
9395 return false;
9397 return true;
9399 return RECUR (x, rval);
9402 case STATEMENT_LIST:
9403 for (tree stmt : tsi_range (t))
9404 if (!RECUR (stmt, any))
9405 return false;
9406 return true;
9408 case MODIFY_EXPR:
9409 if (cxx_dialect < cxx14)
9410 goto fail;
9411 if (!RECUR (TREE_OPERAND (t, 0), any))
9412 return false;
9413 /* Just ignore clobbers. */
9414 if (TREE_CLOBBER_P (TREE_OPERAND (t, 1)))
9415 return true;
9416 if (!RECUR (TREE_OPERAND (t, 1), rval))
9417 return false;
9418 return true;
9420 case MODOP_EXPR:
9421 if (cxx_dialect < cxx14)
9422 goto fail;
9423 if (!RECUR (TREE_OPERAND (t, 0), rval))
9424 return false;
9425 if (!RECUR (TREE_OPERAND (t, 2), rval))
9426 return false;
9427 return true;
9429 case DO_STMT:
9430 if (!RECUR (DO_COND (t), rval))
9431 return false;
9432 if (!RECUR (DO_BODY (t), any))
9433 return false;
9434 if (breaks (jump_target) || continues (jump_target))
9435 *jump_target = NULL_TREE;
9436 return true;
9438 case FOR_STMT:
9439 if (!RECUR (FOR_INIT_STMT (t), any))
9440 return false;
9441 tmp = FOR_COND (t);
9442 if (!RECUR (tmp, rval))
9443 return false;
9444 if (tmp)
9446 if (!processing_template_decl)
9447 tmp = cxx_eval_outermost_constant_expr (tmp, true);
9448 /* If we couldn't evaluate the condition, it might not ever be
9449 true. */
9450 if (!integer_onep (tmp))
9452 /* Before returning true, check if the for body can contain
9453 a return. */
9454 hash_set<tree> pset;
9455 check_for_return_continue_data data = { &pset, NULL_TREE,
9456 NULL_TREE };
9457 if (tree ret_expr
9458 = cp_walk_tree (&FOR_BODY (t), check_for_return_continue,
9459 &data, &pset))
9460 *jump_target = ret_expr;
9461 return true;
9464 if (!RECUR (FOR_EXPR (t), any))
9465 return false;
9466 if (!RECUR (FOR_BODY (t), any))
9467 return false;
9468 if (breaks (jump_target) || continues (jump_target))
9469 *jump_target = NULL_TREE;
9470 return true;
9472 case RANGE_FOR_STMT:
9473 if (!RECUR (RANGE_FOR_INIT_STMT (t), any))
9474 return false;
9475 if (!RECUR (RANGE_FOR_EXPR (t), any))
9476 return false;
9477 if (!RECUR (RANGE_FOR_BODY (t), any))
9478 return false;
9479 if (breaks (jump_target) || continues (jump_target))
9480 *jump_target = NULL_TREE;
9481 return true;
9483 case WHILE_STMT:
9484 tmp = WHILE_COND (t);
9485 if (!RECUR (tmp, rval))
9486 return false;
9487 if (!processing_template_decl)
9488 tmp = cxx_eval_outermost_constant_expr (tmp, true);
9489 /* If we couldn't evaluate the condition, it might not ever be true. */
9490 if (!integer_onep (tmp))
9492 /* Before returning true, check if the while body can contain
9493 a return. */
9494 hash_set<tree> pset;
9495 check_for_return_continue_data data = { &pset, NULL_TREE,
9496 NULL_TREE };
9497 if (tree ret_expr
9498 = cp_walk_tree (&WHILE_BODY (t), check_for_return_continue,
9499 &data, &pset))
9500 *jump_target = ret_expr;
9501 return true;
9503 if (!RECUR (WHILE_BODY (t), any))
9504 return false;
9505 if (breaks (jump_target) || continues (jump_target))
9506 *jump_target = NULL_TREE;
9507 return true;
9509 case SWITCH_STMT:
9510 if (!RECUR (SWITCH_STMT_COND (t), rval))
9511 return false;
9512 /* FIXME we don't check SWITCH_STMT_BODY currently, because even
9513 unreachable labels would be checked and it is enough if there is
9514 a single switch cond value for which it is a valid constant
9515 expression. We need to check if there are any RETURN_EXPRs
9516 or CONTINUE_STMTs inside of the body though, as in that case
9517 we need to set *jump_target. */
9518 else
9520 hash_set<tree> pset;
9521 check_for_return_continue_data data = { &pset, NULL_TREE,
9522 NULL_TREE };
9523 if (tree ret_expr
9524 = cp_walk_tree (&SWITCH_STMT_BODY (t), check_for_return_continue,
9525 &data, &pset))
9526 /* The switch might return. */
9527 *jump_target = ret_expr;
9528 else if (data.continue_stmt)
9529 /* The switch can't return, but might continue. */
9530 *jump_target = data.continue_stmt;
9532 return true;
9534 case STMT_EXPR:
9535 return RECUR (STMT_EXPR_STMT (t), rval);
9537 case LAMBDA_EXPR:
9538 if (cxx_dialect >= cxx17)
9539 /* In C++17 lambdas can be constexpr, don't give up yet. */
9540 return true;
9541 else if (flags & tf_error)
9542 constexpr_error (loc, fundef_p, "lambda-expression is not a "
9543 "constant expression before C++17");
9544 return false;
9546 case NEW_EXPR:
9547 case VEC_NEW_EXPR:
9548 case DELETE_EXPR:
9549 case VEC_DELETE_EXPR:
9550 if (cxx_dialect >= cxx20)
9551 /* In C++20, new-expressions are potentially constant. */
9552 return true;
9553 else if (flags & tf_error)
9554 constexpr_error (loc, fundef_p, "new-expression is not a "
9555 "constant expression before C++20");
9556 return false;
9558 case DYNAMIC_CAST_EXPR:
9559 case PSEUDO_DTOR_EXPR:
9560 case THROW_EXPR:
9561 case OMP_PARALLEL:
9562 case OMP_TASK:
9563 case OMP_FOR:
9564 case OMP_SIMD:
9565 case OMP_DISTRIBUTE:
9566 case OMP_TASKLOOP:
9567 case OMP_LOOP:
9568 case OMP_TEAMS:
9569 case OMP_TARGET_DATA:
9570 case OMP_TARGET:
9571 case OMP_SECTIONS:
9572 case OMP_ORDERED:
9573 case OMP_CRITICAL:
9574 case OMP_SINGLE:
9575 case OMP_SCAN:
9576 case OMP_SCOPE:
9577 case OMP_SECTION:
9578 case OMP_MASTER:
9579 case OMP_MASKED:
9580 case OMP_TASKGROUP:
9581 case OMP_TARGET_UPDATE:
9582 case OMP_TARGET_ENTER_DATA:
9583 case OMP_TARGET_EXIT_DATA:
9584 case OMP_ATOMIC:
9585 case OMP_ATOMIC_READ:
9586 case OMP_ATOMIC_CAPTURE_OLD:
9587 case OMP_ATOMIC_CAPTURE_NEW:
9588 case OMP_DEPOBJ:
9589 case OACC_PARALLEL:
9590 case OACC_KERNELS:
9591 case OACC_SERIAL:
9592 case OACC_DATA:
9593 case OACC_HOST_DATA:
9594 case OACC_LOOP:
9595 case OACC_CACHE:
9596 case OACC_DECLARE:
9597 case OACC_ENTER_DATA:
9598 case OACC_EXIT_DATA:
9599 case OACC_UPDATE:
9600 /* GCC internal stuff. */
9601 case VA_ARG_EXPR:
9602 case TRANSACTION_EXPR:
9603 case AT_ENCODE_EXPR:
9604 fail:
9605 if (flags & tf_error)
9606 constexpr_error (loc, fundef_p, "expression %qE is not a constant "
9607 "expression", t);
9608 return false;
9610 case ASM_EXPR:
9611 if (flags & tf_error)
9612 inline_asm_in_constexpr_error (loc, fundef_p);
9613 return false;
9615 case OBJ_TYPE_REF:
9616 if (cxx_dialect >= cxx20)
9617 /* In C++20 virtual calls can be constexpr, don't give up yet. */
9618 return true;
9619 else if (flags & tf_error)
9620 constexpr_error (loc, fundef_p, "virtual functions cannot be "
9621 "%<constexpr%> before C++20");
9622 return false;
9624 case TYPEID_EXPR:
9625 /* In C++20, a typeid expression whose operand is of polymorphic
9626 class type can be constexpr. */
9628 tree e = TREE_OPERAND (t, 0);
9629 if (cxx_dialect < cxx20
9630 && strict
9631 && !TYPE_P (e)
9632 && !type_dependent_expression_p (e)
9633 && TYPE_POLYMORPHIC_P (TREE_TYPE (e)))
9635 if (flags & tf_error)
9636 constexpr_error (loc, fundef_p, "%<typeid%> is not a "
9637 "constant expression because %qE is "
9638 "of polymorphic type", e);
9639 return false;
9641 return true;
9644 case POINTER_DIFF_EXPR:
9645 case MINUS_EXPR:
9646 want_rval = true;
9647 goto binary;
9649 case LT_EXPR:
9650 case LE_EXPR:
9651 case GT_EXPR:
9652 case GE_EXPR:
9653 case EQ_EXPR:
9654 case NE_EXPR:
9655 case SPACESHIP_EXPR:
9656 want_rval = true;
9657 goto binary;
9659 case PREINCREMENT_EXPR:
9660 case POSTINCREMENT_EXPR:
9661 case PREDECREMENT_EXPR:
9662 case POSTDECREMENT_EXPR:
9663 if (cxx_dialect < cxx14)
9664 goto fail;
9665 goto unary;
9667 case BIT_NOT_EXPR:
9668 /* A destructor. */
9669 if (TYPE_P (TREE_OPERAND (t, 0)))
9670 return true;
9671 /* fall through. */
9673 case CONJ_EXPR:
9674 case SAVE_EXPR:
9675 case FIX_TRUNC_EXPR:
9676 case FLOAT_EXPR:
9677 case NEGATE_EXPR:
9678 case ABS_EXPR:
9679 case ABSU_EXPR:
9680 case TRUTH_NOT_EXPR:
9681 case FIXED_CONVERT_EXPR:
9682 case UNARY_PLUS_EXPR:
9683 case UNARY_LEFT_FOLD_EXPR:
9684 case UNARY_RIGHT_FOLD_EXPR:
9685 unary:
9686 return RECUR (TREE_OPERAND (t, 0), rval);
9688 case CAST_EXPR:
9689 case CONST_CAST_EXPR:
9690 case STATIC_CAST_EXPR:
9691 case REINTERPRET_CAST_EXPR:
9692 case IMPLICIT_CONV_EXPR:
9693 if (!cast_valid_in_integral_constant_expression_p (TREE_TYPE (t)))
9694 /* In C++98, a conversion to non-integral type can't be part of a
9695 constant expression. */
9697 if (flags & tf_error)
9698 constexpr_error (loc, fundef_p,
9699 "cast to non-integral type %qT in a constant "
9700 "expression", TREE_TYPE (t));
9701 return false;
9703 /* This might be a conversion from a class to a (potentially) literal
9704 type. Let's consider it potentially constant since the conversion
9705 might be a constexpr user-defined conversion. */
9706 else if (cxx_dialect >= cxx11
9707 && (dependent_type_p (TREE_TYPE (t))
9708 || !COMPLETE_TYPE_P (TREE_TYPE (t))
9709 || literal_type_p (TREE_TYPE (t)))
9710 && TREE_OPERAND (t, 0))
9712 tree type = TREE_TYPE (TREE_OPERAND (t, 0));
9713 /* If this is a dependent type, it could end up being a class
9714 with conversions. */
9715 if (type == NULL_TREE || WILDCARD_TYPE_P (type))
9716 return true;
9717 /* Or a non-dependent class which has conversions. */
9718 else if (CLASS_TYPE_P (type)
9719 && (TYPE_HAS_CONVERSION (type) || dependent_scope_p (type)))
9720 return true;
9723 return (RECUR (TREE_OPERAND (t, 0),
9724 !TYPE_REF_P (TREE_TYPE (t))));
9726 case BIND_EXPR:
9727 return RECUR (BIND_EXPR_BODY (t), want_rval);
9729 case NON_DEPENDENT_EXPR:
9730 /* Treat NON_DEPENDENT_EXPR as non-constant: it's not handled by
9731 constexpr evaluation or tsubst, so fold_non_dependent_expr can't
9732 do anything useful with it. And we shouldn't see it in a context
9733 where a constant expression is strictly required, hence the assert. */
9734 gcc_checking_assert (!(flags & tf_error));
9735 return false;
9737 case CLEANUP_POINT_EXPR:
9738 case MUST_NOT_THROW_EXPR:
9739 case TRY_CATCH_EXPR:
9740 case TRY_BLOCK:
9741 case EH_SPEC_BLOCK:
9742 case EXPR_STMT:
9743 case PAREN_EXPR:
9744 /* For convenience. */
9745 case LOOP_EXPR:
9746 case EXIT_EXPR:
9747 return RECUR (TREE_OPERAND (t, 0), want_rval);
9749 case DECL_EXPR:
9750 tmp = DECL_EXPR_DECL (t);
9751 if (VAR_P (tmp) && !DECL_ARTIFICIAL (tmp)
9752 && (processing_template_decl
9753 ? !decl_maybe_constant_var_p (tmp)
9754 : !decl_constant_var_p (tmp)))
9756 if (CP_DECL_THREAD_LOCAL_P (tmp) && !DECL_REALLY_EXTERN (tmp))
9758 if (flags & tf_error)
9759 constexpr_error (DECL_SOURCE_LOCATION (tmp), fundef_p,
9760 "%qD defined %<thread_local%> in "
9761 "%<constexpr%> context", tmp);
9762 return false;
9764 else if (TREE_STATIC (tmp))
9766 if (flags & tf_error)
9767 constexpr_error (DECL_SOURCE_LOCATION (tmp), fundef_p,
9768 "%qD defined %<static%> in %<constexpr%> "
9769 "context", tmp);
9770 return false;
9772 else if (!check_for_uninitialized_const_var
9773 (tmp, /*constexpr_context_p=*/true, flags))
9774 return false;
9776 if (VAR_P (tmp))
9777 return RECUR (DECL_INITIAL (tmp), want_rval);
9778 return true;
9780 case TRY_FINALLY_EXPR:
9781 return (RECUR (TREE_OPERAND (t, 0), want_rval)
9782 && RECUR (TREE_OPERAND (t, 1), any));
9784 case SCOPE_REF:
9785 return RECUR (TREE_OPERAND (t, 1), want_rval);
9787 case TARGET_EXPR:
9788 if (!TARGET_EXPR_DIRECT_INIT_P (t)
9789 && !literal_type_p (TREE_TYPE (t)))
9791 if (flags & tf_error)
9793 auto_diagnostic_group d;
9794 if (constexpr_error (loc, fundef_p,
9795 "temporary of non-literal type %qT in a "
9796 "constant expression", TREE_TYPE (t)))
9797 explain_non_literal_class (TREE_TYPE (t));
9799 return false;
9801 /* FALLTHRU */
9802 case INIT_EXPR:
9803 return RECUR (TREE_OPERAND (t, 1), rval);
9805 case CONSTRUCTOR:
9807 vec<constructor_elt, va_gc> *v = CONSTRUCTOR_ELTS (t);
9808 constructor_elt *ce;
9809 for (i = 0; vec_safe_iterate (v, i, &ce); ++i)
9810 if (!RECUR (ce->value, want_rval))
9811 return false;
9812 return true;
9815 case TREE_LIST:
9817 gcc_assert (TREE_PURPOSE (t) == NULL_TREE
9818 || DECL_P (TREE_PURPOSE (t)));
9819 if (!RECUR (TREE_VALUE (t), want_rval))
9820 return false;
9821 if (TREE_CHAIN (t) == NULL_TREE)
9822 return true;
9823 return RECUR (TREE_CHAIN (t), want_rval);
9826 case TRUNC_DIV_EXPR:
9827 case CEIL_DIV_EXPR:
9828 case FLOOR_DIV_EXPR:
9829 case ROUND_DIV_EXPR:
9830 case TRUNC_MOD_EXPR:
9831 case CEIL_MOD_EXPR:
9832 case ROUND_MOD_EXPR:
9834 tree denom = TREE_OPERAND (t, 1);
9835 if (!RECUR (denom, rval))
9836 return false;
9837 /* We can't call cxx_eval_outermost_constant_expr on an expression
9838 that hasn't been through instantiate_non_dependent_expr yet. */
9839 if (!processing_template_decl)
9840 denom = cxx_eval_outermost_constant_expr (denom, true);
9841 if (integer_zerop (denom))
9843 if (flags & tf_error)
9844 constexpr_error (input_location, fundef_p,
9845 "division by zero is not a constant expression");
9846 return false;
9848 else
9850 want_rval = true;
9851 return RECUR (TREE_OPERAND (t, 0), want_rval);
9855 case COMPOUND_EXPR:
9857 /* check_return_expr sometimes wraps a TARGET_EXPR in a
9858 COMPOUND_EXPR; don't get confused. */
9859 tree op0 = TREE_OPERAND (t, 0);
9860 tree op1 = TREE_OPERAND (t, 1);
9861 STRIP_NOPS (op1);
9862 if (TREE_CODE (op0) == TARGET_EXPR && op1 == TARGET_EXPR_SLOT (op0))
9863 return RECUR (op0, want_rval);
9864 else
9865 goto binary;
9868 /* If the first operand is the non-short-circuit constant, look at
9869 the second operand; otherwise we only care about the first one for
9870 potentiality. */
9871 case TRUTH_AND_EXPR:
9872 case TRUTH_ANDIF_EXPR:
9873 tmp = boolean_true_node;
9874 goto truth;
9875 case TRUTH_OR_EXPR:
9876 case TRUTH_ORIF_EXPR:
9877 tmp = boolean_false_node;
9878 truth:
9880 tree op0 = TREE_OPERAND (t, 0);
9881 tree op1 = TREE_OPERAND (t, 1);
9882 if (!RECUR (op0, rval))
9883 return false;
9884 if (!(flags & tf_error) && RECUR (op1, rval))
9885 /* When quiet, try to avoid expensive trial evaluation by first
9886 checking potentiality of the second operand. */
9887 return true;
9888 if (!processing_template_decl)
9889 op0 = cxx_eval_outermost_constant_expr (op0, true);
9890 if (tree_int_cst_equal (op0, tmp))
9891 return (flags & tf_error) ? RECUR (op1, rval) : false;
9892 else
9893 return true;
9896 case PLUS_EXPR:
9897 case MULT_EXPR:
9898 case POINTER_PLUS_EXPR:
9899 case RDIV_EXPR:
9900 case EXACT_DIV_EXPR:
9901 case MIN_EXPR:
9902 case MAX_EXPR:
9903 case LSHIFT_EXPR:
9904 case RSHIFT_EXPR:
9905 case LROTATE_EXPR:
9906 case RROTATE_EXPR:
9907 case BIT_IOR_EXPR:
9908 case BIT_XOR_EXPR:
9909 case BIT_AND_EXPR:
9910 case TRUTH_XOR_EXPR:
9911 case UNORDERED_EXPR:
9912 case ORDERED_EXPR:
9913 case UNLT_EXPR:
9914 case UNLE_EXPR:
9915 case UNGT_EXPR:
9916 case UNGE_EXPR:
9917 case UNEQ_EXPR:
9918 case LTGT_EXPR:
9919 case RANGE_EXPR:
9920 case COMPLEX_EXPR:
9921 want_rval = true;
9922 /* Fall through. */
9923 case ARRAY_REF:
9924 case ARRAY_RANGE_REF:
9925 case MEMBER_REF:
9926 case DOTSTAR_EXPR:
9927 case MEM_REF:
9928 case BINARY_LEFT_FOLD_EXPR:
9929 case BINARY_RIGHT_FOLD_EXPR:
9930 binary:
9931 for (i = 0; i < 2; ++i)
9932 if (!RECUR (TREE_OPERAND (t, i), want_rval))
9933 return false;
9934 return true;
9936 case VEC_PERM_EXPR:
9937 for (i = 0; i < 3; ++i)
9938 if (!RECUR (TREE_OPERAND (t, i), true))
9939 return false;
9940 return true;
9942 case COND_EXPR:
9943 if (COND_EXPR_IS_VEC_DELETE (t) && cxx_dialect < cxx20)
9945 if (flags & tf_error)
9946 constexpr_error (loc, fundef_p, "%<delete[]%> is not a "
9947 "constant expression");
9948 return false;
9950 /* Fall through. */
9951 case IF_STMT:
9952 case VEC_COND_EXPR:
9953 /* If the condition is a known constant, we know which of the legs we
9954 care about; otherwise we only require that the condition and
9955 either of the legs be potentially constant. */
9956 tmp = TREE_OPERAND (t, 0);
9957 if (!RECUR (tmp, rval))
9958 return false;
9959 if (!processing_template_decl)
9960 tmp = cxx_eval_outermost_constant_expr (tmp, true);
9961 /* potential_constant_expression* isn't told if it is called for
9962 manifestly_const_eval or not, so for consteval if always
9963 process both branches as if the condition is not a known
9964 constant. */
9965 if (TREE_CODE (t) != IF_STMT || !IF_STMT_CONSTEVAL_P (t))
9967 if (integer_zerop (tmp))
9968 return RECUR (TREE_OPERAND (t, 2), want_rval);
9969 else if (TREE_CODE (tmp) == INTEGER_CST)
9970 return RECUR (TREE_OPERAND (t, 1), want_rval);
9972 tmp = *jump_target;
9973 for (i = 1; i < 3; ++i)
9975 tree this_jump_target = tmp;
9976 if (potential_constant_expression_1 (TREE_OPERAND (t, i),
9977 want_rval, strict, now, fundef_p,
9978 tf_none, &this_jump_target))
9980 if (returns (&this_jump_target))
9981 *jump_target = this_jump_target;
9982 else if (!returns (jump_target))
9984 if (breaks (&this_jump_target)
9985 || continues (&this_jump_target))
9986 *jump_target = this_jump_target;
9987 if (i == 1)
9989 /* If the then branch is potentially constant, but
9990 does not return, check if the else branch
9991 couldn't return, break or continue. */
9992 hash_set<tree> pset;
9993 check_for_return_continue_data data = { &pset, NULL_TREE,
9994 NULL_TREE };
9995 if (tree ret_expr
9996 = cp_walk_tree (&TREE_OPERAND (t, 2),
9997 check_for_return_continue, &data,
9998 &pset))
9999 *jump_target = ret_expr;
10000 else if (*jump_target == NULL_TREE)
10002 if (data.continue_stmt)
10003 *jump_target = data.continue_stmt;
10004 else if (data.break_stmt)
10005 *jump_target = data.break_stmt;
10009 return true;
10012 if (flags & tf_error)
10014 if (TREE_CODE (t) == IF_STMT)
10015 constexpr_error (loc, fundef_p, "neither branch of %<if%> is a "
10016 "constant expression");
10017 else
10018 constexpr_error (loc, fundef_p, "expression %qE is not a "
10019 "constant expression", t);
10021 return false;
10023 case VEC_INIT_EXPR:
10024 if (VEC_INIT_EXPR_IS_CONSTEXPR (t))
10025 return true;
10026 if (flags & tf_error)
10028 if (constexpr_error (loc, fundef_p, "non-constant array "
10029 "initialization"))
10030 diagnose_non_constexpr_vec_init (t);
10032 return false;
10034 case TYPE_DECL:
10035 case TAG_DEFN:
10036 /* We can see these in statement-expressions. */
10037 return true;
10039 case CLEANUP_STMT:
10040 if (!RECUR (CLEANUP_BODY (t), any))
10041 return false;
10042 if (!CLEANUP_EH_ONLY (t) && !RECUR (CLEANUP_EXPR (t), any))
10043 return false;
10044 return true;
10046 case EMPTY_CLASS_EXPR:
10047 return true;
10049 case GOTO_EXPR:
10051 tree *target = &TREE_OPERAND (t, 0);
10052 /* Gotos representing break, continue and cdtor return are OK. */
10053 if (breaks (target) || continues (target) || returns (target))
10055 *jump_target = *target;
10056 return true;
10058 if (flags & tf_error)
10059 constexpr_error (loc, fundef_p, "%<goto%> is not a constant "
10060 "expression");
10061 return false;
10064 case ASSERTION_STMT:
10065 case PRECONDITION_STMT:
10066 case POSTCONDITION_STMT:
10067 if (!checked_contract_p (get_contract_semantic (t)))
10068 return true;
10069 return RECUR (CONTRACT_CONDITION (t), rval);
10071 case LABEL_EXPR:
10072 t = LABEL_EXPR_LABEL (t);
10073 if (DECL_ARTIFICIAL (t) || cxx_dialect >= cxx23)
10074 return true;
10075 else if (flags & tf_error)
10076 constexpr_error (loc, fundef_p, "label definition in %<constexpr%> "
10077 "function only available with %<-std=c++2b%> or "
10078 "%<-std=gnu++2b%>");
10079 return false;
10081 case ANNOTATE_EXPR:
10082 return RECUR (TREE_OPERAND (t, 0), rval);
10084 case BIT_CAST_EXPR:
10085 return RECUR (TREE_OPERAND (t, 0), rval);
10087 /* Coroutine await, yield and return expressions are not. */
10088 case CO_AWAIT_EXPR:
10089 case CO_YIELD_EXPR:
10090 case CO_RETURN_EXPR:
10091 return false;
10093 case NONTYPE_ARGUMENT_PACK:
10095 tree args = ARGUMENT_PACK_ARGS (t);
10096 int len = TREE_VEC_LENGTH (args);
10097 for (int i = 0; i < len; ++i)
10098 if (!RECUR (TREE_VEC_ELT (args, i), any))
10099 return false;
10100 return true;
10103 default:
10104 if (objc_non_constant_expr_p (t))
10105 return false;
10107 sorry ("unexpected AST of kind %s", get_tree_code_name (TREE_CODE (t)));
10108 gcc_unreachable ();
10109 return false;
10111 #undef RECUR
10114 bool
10115 potential_constant_expression_1 (tree t, bool want_rval, bool strict, bool now,
10116 bool fundef_p, tsubst_flags_t flags)
10118 if (flags & tf_error)
10120 /* Check potentiality quietly first, as that could be performed more
10121 efficiently in some cases (currently only for TRUTH_*_EXPR). If
10122 that fails, replay the check noisily to give errors. */
10123 flags &= ~tf_error;
10124 if (potential_constant_expression_1 (t, want_rval, strict, now, fundef_p,
10125 flags))
10126 return true;
10127 flags |= tf_error;
10130 tree target = NULL_TREE;
10131 return potential_constant_expression_1 (t, want_rval, strict, now, fundef_p,
10132 flags, &target);
10135 /* The main entry point to the above. */
10137 bool
10138 potential_constant_expression (tree t)
10140 return potential_constant_expression_1 (t, /*want_rval*/false, /*strict*/true,
10141 /*now*/false, /*fundef_p*/false,
10142 tf_none);
10145 /* As above, but require a constant rvalue. */
10147 bool
10148 potential_rvalue_constant_expression (tree t)
10150 return potential_constant_expression_1 (t, /*want_rval*/true, /*strict*/true,
10151 /*now*/false, /*fundef_p*/false,
10152 tf_none);
10155 /* Like above, but complain about non-constant expressions. */
10157 bool
10158 require_potential_constant_expression (tree t)
10160 return potential_constant_expression_1 (t, /*want_rval*/false, /*strict*/true,
10161 /*now*/false, /*fundef_p*/false,
10162 tf_warning_or_error);
10165 /* Cross product of the above. */
10167 bool
10168 require_potential_rvalue_constant_expression (tree t)
10170 return potential_constant_expression_1 (t, /*want_rval*/true, /*strict*/true,
10171 /*now*/false, /*fundef_p*/false,
10172 tf_warning_or_error);
10175 /* Like require_potential_rvalue_constant_expression, but fundef_p is true. */
10177 bool
10178 require_potential_rvalue_constant_expression_fncheck (tree t)
10180 return potential_constant_expression_1 (t, /*want_rval*/true, /*strict*/true,
10181 /*now*/false, /*fundef_p*/true,
10182 tf_warning_or_error);
10185 /* Like above, but don't consider PARM_DECL a potential_constant_expression. */
10187 bool
10188 require_rvalue_constant_expression (tree t)
10190 return potential_constant_expression_1 (t, /*want_rval*/true, /*strict*/true,
10191 /*now*/true, /*fundef_p*/false,
10192 tf_warning_or_error);
10195 /* Like potential_constant_expression, but don't consider possible constexpr
10196 substitution of the current function. That is, PARM_DECL qualifies under
10197 potential_constant_expression, but not here.
10199 This is basically what you can check when any actual constant values might
10200 be value-dependent. */
10202 bool
10203 is_constant_expression (tree t)
10205 return potential_constant_expression_1 (t, /*want_rval*/false, /*strict*/true,
10206 /*now*/true, /*fundef_p*/false,
10207 tf_none);
10210 /* As above, but expect an rvalue. */
10212 bool
10213 is_rvalue_constant_expression (tree t)
10215 return potential_constant_expression_1 (t, /*want_rval*/true, /*strict*/true,
10216 /*now*/true, /*fundef_p*/false,
10217 tf_none);
10220 /* Like above, but complain about non-constant expressions. */
10222 bool
10223 require_constant_expression (tree t)
10225 return potential_constant_expression_1 (t, /*want_rval*/false, /*strict*/true,
10226 /*now*/true, /*fundef_p*/false,
10227 tf_warning_or_error);
10230 /* Like is_constant_expression, but allow const variables that are not allowed
10231 under constexpr rules. */
10233 bool
10234 is_static_init_expression (tree t)
10236 return potential_constant_expression_1 (t, /*want_rval*/false,
10237 /*strict*/false, /*now*/true,
10238 /*fundef_p*/false, tf_none);
10241 /* Returns true if T is a potential constant expression that is not
10242 instantiation-dependent, and therefore a candidate for constant folding even
10243 in a template. */
10245 bool
10246 is_nondependent_constant_expression (tree t)
10248 return (!type_unknown_p (t)
10249 && is_constant_expression (t)
10250 && !instantiation_dependent_expression_p (t));
10253 /* Returns true if T is a potential static initializer expression that is not
10254 instantiation-dependent. */
10256 bool
10257 is_nondependent_static_init_expression (tree t)
10259 return (!type_unknown_p (t)
10260 && is_static_init_expression (t)
10261 && !instantiation_dependent_expression_p (t));
10264 /* True iff FN is an implicitly constexpr function. */
10266 bool
10267 decl_implicit_constexpr_p (tree fn)
10269 if (!(flag_implicit_constexpr
10270 && TREE_CODE (fn) == FUNCTION_DECL
10271 && DECL_DECLARED_CONSTEXPR_P (fn)))
10272 return false;
10274 if (DECL_CLONED_FUNCTION_P (fn))
10275 fn = DECL_CLONED_FUNCTION (fn);
10277 return (DECL_LANG_SPECIFIC (fn)
10278 && DECL_LANG_SPECIFIC (fn)->u.fn.implicit_constexpr);
10281 /* Finalize constexpr processing after parsing. */
10283 void
10284 fini_constexpr (void)
10286 /* The contexpr call and fundef copies tables are no longer needed. */
10287 constexpr_call_table = NULL;
10288 fundef_copies_table = NULL;
10291 #include "gt-cp-constexpr.h"