PR c++/83116
[official-gcc.git] / gcc / cp / constexpr.c
blob518798e0c431819a9b8aef60035e37a5c5144643
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-2017 Free Software Foundation, Inc.
7 This file is part of GCC.
9 GCC is free software; you can redistribute it and/or modify it
10 under the terms of the GNU General Public License as published by
11 the Free Software Foundation; either version 3, or (at your option)
12 any later version.
14 GCC is distributed in the hope that it will be useful, but
15 WITHOUT ANY WARRANTY; without even the implied warranty of
16 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
17 General Public License for more details.
19 You should have received a copy of the GNU General Public License
20 along with GCC; see the file COPYING3. If not see
21 <http://www.gnu.org/licenses/>. */
23 #include "config.h"
24 #include "system.h"
25 #include "coretypes.h"
26 #include "cp-tree.h"
27 #include "varasm.h"
28 #include "c-family/c-objc.h"
29 #include "tree-iterator.h"
30 #include "gimplify.h"
31 #include "builtins.h"
32 #include "tree-inline.h"
33 #include "ubsan.h"
34 #include "gimple-fold.h"
35 #include "timevar.h"
37 static bool verify_constant (tree, bool, bool *, bool *);
38 #define VERIFY_CONSTANT(X) \
39 do { \
40 if (verify_constant ((X), ctx->quiet, non_constant_p, overflow_p)) \
41 return t; \
42 } while (0)
44 /* Returns true iff FUN is an instantiation of a constexpr function
45 template or a defaulted constexpr function. */
47 bool
48 is_instantiation_of_constexpr (tree fun)
50 return ((DECL_TEMPLOID_INSTANTIATION (fun)
51 && DECL_DECLARED_CONSTEXPR_P (DECL_TI_TEMPLATE (fun)))
52 || (DECL_DEFAULTED_FN (fun)
53 && DECL_DECLARED_CONSTEXPR_P (fun)));
56 /* Return true if T is a literal type. */
58 bool
59 literal_type_p (tree t)
61 if (SCALAR_TYPE_P (t)
62 || VECTOR_TYPE_P (t)
63 || TREE_CODE (t) == REFERENCE_TYPE
64 || (VOID_TYPE_P (t) && cxx_dialect >= cxx14))
65 return true;
66 if (CLASS_TYPE_P (t))
68 t = complete_type (t);
69 gcc_assert (COMPLETE_TYPE_P (t) || errorcount);
70 return CLASSTYPE_LITERAL_P (t);
72 if (TREE_CODE (t) == ARRAY_TYPE)
73 return literal_type_p (strip_array_types (t));
74 return false;
77 /* If DECL is a variable declared `constexpr', require its type
78 be literal. Return the DECL if OK, otherwise NULL. */
80 tree
81 ensure_literal_type_for_constexpr_object (tree decl)
83 tree type = TREE_TYPE (decl);
84 if (VAR_P (decl)
85 && (DECL_DECLARED_CONSTEXPR_P (decl)
86 || var_in_constexpr_fn (decl))
87 && !processing_template_decl)
89 tree stype = strip_array_types (type);
90 if (CLASS_TYPE_P (stype) && !COMPLETE_TYPE_P (complete_type (stype)))
91 /* Don't complain here, we'll complain about incompleteness
92 when we try to initialize the variable. */;
93 else if (!literal_type_p (type))
95 if (DECL_DECLARED_CONSTEXPR_P (decl))
97 error ("the type %qT of %<constexpr%> variable %qD "
98 "is not literal", type, decl);
99 explain_non_literal_class (type);
101 else
103 if (!is_instantiation_of_constexpr (current_function_decl))
105 error ("variable %qD of non-literal type %qT in %<constexpr%> "
106 "function", decl, type);
107 explain_non_literal_class (type);
109 cp_function_chain->invalid_constexpr = true;
111 return NULL;
114 return decl;
117 /* Representation of entries in the constexpr function definition table. */
119 struct GTY((for_user)) constexpr_fundef {
120 tree decl;
121 tree body;
124 struct constexpr_fundef_hasher : ggc_ptr_hash<constexpr_fundef>
126 static hashval_t hash (constexpr_fundef *);
127 static bool equal (constexpr_fundef *, constexpr_fundef *);
130 /* This table holds all constexpr function definitions seen in
131 the current translation unit. */
133 static GTY (()) hash_table<constexpr_fundef_hasher> *constexpr_fundef_table;
135 /* Utility function used for managing the constexpr function table.
136 Return true if the entries pointed to by P and Q are for the
137 same constexpr function. */
139 inline bool
140 constexpr_fundef_hasher::equal (constexpr_fundef *lhs, constexpr_fundef *rhs)
142 return lhs->decl == rhs->decl;
145 /* Utility function used for managing the constexpr function table.
146 Return a hash value for the entry pointed to by Q. */
148 inline hashval_t
149 constexpr_fundef_hasher::hash (constexpr_fundef *fundef)
151 return DECL_UID (fundef->decl);
154 /* Return a previously saved definition of function FUN. */
156 static constexpr_fundef *
157 retrieve_constexpr_fundef (tree fun)
159 constexpr_fundef fundef = { NULL, NULL };
160 if (constexpr_fundef_table == NULL)
161 return NULL;
163 fundef.decl = fun;
164 return constexpr_fundef_table->find (&fundef);
167 /* Check whether the parameter and return types of FUN are valid for a
168 constexpr function, and complain if COMPLAIN. */
170 bool
171 is_valid_constexpr_fn (tree fun, bool complain)
173 bool ret = true;
175 if (DECL_INHERITED_CTOR (fun)
176 && TREE_CODE (fun) == TEMPLATE_DECL)
178 ret = false;
179 if (complain)
180 error ("inherited constructor %qD is not %<constexpr%>",
181 DECL_INHERITED_CTOR (fun));
183 else
185 for (tree parm = FUNCTION_FIRST_USER_PARM (fun);
186 parm != NULL_TREE; parm = TREE_CHAIN (parm))
187 if (!literal_type_p (TREE_TYPE (parm)))
189 ret = false;
190 if (complain)
192 error ("invalid type for parameter %d of %<constexpr%> "
193 "function %q+#D", DECL_PARM_INDEX (parm), fun);
194 explain_non_literal_class (TREE_TYPE (parm));
199 if (LAMBDA_TYPE_P (CP_DECL_CONTEXT (fun)) && cxx_dialect < cxx17)
201 ret = false;
202 if (complain)
203 inform (DECL_SOURCE_LOCATION (fun),
204 "lambdas are implicitly %<constexpr%> only in C++17 and later");
206 else if (!DECL_CONSTRUCTOR_P (fun))
208 tree rettype = TREE_TYPE (TREE_TYPE (fun));
209 if (!literal_type_p (rettype))
211 ret = false;
212 if (complain)
214 error ("invalid return type %qT of %<constexpr%> function %q+D",
215 rettype, fun);
216 explain_non_literal_class (rettype);
220 /* C++14 DR 1684 removed this restriction. */
221 if (cxx_dialect < cxx14
222 && DECL_NONSTATIC_MEMBER_FUNCTION_P (fun)
223 && !CLASSTYPE_LITERAL_P (DECL_CONTEXT (fun)))
225 ret = false;
226 if (complain
227 && pedwarn (DECL_SOURCE_LOCATION (fun), OPT_Wpedantic,
228 "enclosing class of %<constexpr%> non-static member "
229 "function %q+#D is not a literal type", fun))
230 explain_non_literal_class (DECL_CONTEXT (fun));
233 else if (CLASSTYPE_VBASECLASSES (DECL_CONTEXT (fun)))
235 ret = false;
236 if (complain)
237 error ("%q#T has virtual base classes", DECL_CONTEXT (fun));
240 return ret;
243 /* Subroutine of build_data_member_initialization. MEMBER is a COMPONENT_REF
244 for a member of an anonymous aggregate, INIT is the initializer for that
245 member, and VEC_OUTER is the vector of constructor elements for the class
246 whose constructor we are processing. Add the initializer to the vector
247 and return true to indicate success. */
249 static bool
250 build_anon_member_initialization (tree member, tree init,
251 vec<constructor_elt, va_gc> **vec_outer)
253 /* MEMBER presents the relevant fields from the inside out, but we need
254 to build up the initializer from the outside in so that we can reuse
255 previously built CONSTRUCTORs if this is, say, the second field in an
256 anonymous struct. So we use a vec as a stack. */
257 auto_vec<tree, 2> fields;
260 fields.safe_push (TREE_OPERAND (member, 1));
261 member = TREE_OPERAND (member, 0);
263 while (ANON_AGGR_TYPE_P (TREE_TYPE (member))
264 && TREE_CODE (member) == COMPONENT_REF);
266 /* VEC has the constructor elements vector for the context of FIELD.
267 If FIELD is an anonymous aggregate, we will push inside it. */
268 vec<constructor_elt, va_gc> **vec = vec_outer;
269 tree field;
270 while (field = fields.pop(),
271 ANON_AGGR_TYPE_P (TREE_TYPE (field)))
273 tree ctor;
274 /* If there is already an outer constructor entry for the anonymous
275 aggregate FIELD, use it; otherwise, insert one. */
276 if (vec_safe_is_empty (*vec)
277 || (*vec)->last().index != field)
279 ctor = build_constructor (TREE_TYPE (field), NULL);
280 CONSTRUCTOR_APPEND_ELT (*vec, field, ctor);
282 else
283 ctor = (*vec)->last().value;
284 vec = &CONSTRUCTOR_ELTS (ctor);
287 /* Now we're at the innermost field, the one that isn't an anonymous
288 aggregate. Add its initializer to the CONSTRUCTOR and we're done. */
289 gcc_assert (fields.is_empty());
290 CONSTRUCTOR_APPEND_ELT (*vec, field, init);
292 return true;
295 /* Subroutine of build_constexpr_constructor_member_initializers.
296 The expression tree T represents a data member initialization
297 in a (constexpr) constructor definition. Build a pairing of
298 the data member with its initializer, and prepend that pair
299 to the existing initialization pair INITS. */
301 static bool
302 build_data_member_initialization (tree t, vec<constructor_elt, va_gc> **vec)
304 tree member, init;
305 if (TREE_CODE (t) == CLEANUP_POINT_EXPR)
306 t = TREE_OPERAND (t, 0);
307 if (TREE_CODE (t) == EXPR_STMT)
308 t = TREE_OPERAND (t, 0);
309 if (t == error_mark_node)
310 return false;
311 if (TREE_CODE (t) == STATEMENT_LIST)
313 tree_stmt_iterator i;
314 for (i = tsi_start (t); !tsi_end_p (i); tsi_next (&i))
316 if (! build_data_member_initialization (tsi_stmt (i), vec))
317 return false;
319 return true;
321 if (TREE_CODE (t) == CLEANUP_STMT)
323 /* We can't see a CLEANUP_STMT in a constructor for a literal class,
324 but we can in a constexpr constructor for a non-literal class. Just
325 ignore it; either all the initialization will be constant, in which
326 case the cleanup can't run, or it can't be constexpr.
327 Still recurse into CLEANUP_BODY. */
328 return build_data_member_initialization (CLEANUP_BODY (t), vec);
330 if (TREE_CODE (t) == CONVERT_EXPR)
331 t = TREE_OPERAND (t, 0);
332 if (TREE_CODE (t) == INIT_EXPR
333 /* vptr initialization shows up as a MODIFY_EXPR. In C++14 we only
334 use what this function builds for cx_check_missing_mem_inits, and
335 assignment in the ctor body doesn't count. */
336 || (cxx_dialect < cxx14 && TREE_CODE (t) == MODIFY_EXPR))
338 member = TREE_OPERAND (t, 0);
339 init = break_out_target_exprs (TREE_OPERAND (t, 1));
341 else if (TREE_CODE (t) == CALL_EXPR)
343 tree fn = get_callee_fndecl (t);
344 if (!fn || !DECL_CONSTRUCTOR_P (fn))
345 /* We're only interested in calls to subobject constructors. */
346 return true;
347 member = CALL_EXPR_ARG (t, 0);
348 /* We don't use build_cplus_new here because it complains about
349 abstract bases. Leaving the call unwrapped means that it has the
350 wrong type, but cxx_eval_constant_expression doesn't care. */
351 init = break_out_target_exprs (t);
353 else if (TREE_CODE (t) == BIND_EXPR)
354 return build_data_member_initialization (BIND_EXPR_BODY (t), vec);
355 else
356 /* Don't add anything else to the CONSTRUCTOR. */
357 return true;
358 if (INDIRECT_REF_P (member))
359 member = TREE_OPERAND (member, 0);
360 if (TREE_CODE (member) == NOP_EXPR)
362 tree op = member;
363 STRIP_NOPS (op);
364 if (TREE_CODE (op) == ADDR_EXPR)
366 gcc_assert (same_type_ignoring_top_level_qualifiers_p
367 (TREE_TYPE (TREE_TYPE (op)),
368 TREE_TYPE (TREE_TYPE (member))));
369 /* Initializing a cv-qualified member; we need to look through
370 the const_cast. */
371 member = op;
373 else if (op == current_class_ptr
374 && (same_type_ignoring_top_level_qualifiers_p
375 (TREE_TYPE (TREE_TYPE (member)),
376 current_class_type)))
377 /* Delegating constructor. */
378 member = op;
379 else
381 /* This is an initializer for an empty base; keep it for now so
382 we can check it in cxx_eval_bare_aggregate. */
383 gcc_assert (is_empty_class (TREE_TYPE (TREE_TYPE (member))));
386 if (TREE_CODE (member) == ADDR_EXPR)
387 member = TREE_OPERAND (member, 0);
388 if (TREE_CODE (member) == COMPONENT_REF)
390 tree aggr = TREE_OPERAND (member, 0);
391 if (TREE_CODE (aggr) == VAR_DECL)
392 /* Initializing a local variable, don't add anything. */
393 return true;
394 if (TREE_CODE (aggr) != COMPONENT_REF)
395 /* Normal member initialization. */
396 member = TREE_OPERAND (member, 1);
397 else if (ANON_AGGR_TYPE_P (TREE_TYPE (aggr)))
398 /* Initializing a member of an anonymous union. */
399 return build_anon_member_initialization (member, init, vec);
400 else
401 /* We're initializing a vtable pointer in a base. Leave it as
402 COMPONENT_REF so we remember the path to get to the vfield. */
403 gcc_assert (TREE_TYPE (member) == vtbl_ptr_type_node);
406 /* Value-initialization can produce multiple initializers for the
407 same field; use the last one. */
408 if (!vec_safe_is_empty (*vec) && (*vec)->last().index == member)
409 (*vec)->last().value = init;
410 else
411 CONSTRUCTOR_APPEND_ELT (*vec, member, init);
412 return true;
415 /* Subroutine of check_constexpr_ctor_body_1 and constexpr_fn_retval.
416 In C++11 mode checks that the TYPE_DECLs in the BIND_EXPR_VARS of a
417 BIND_EXPR conform to 7.1.5/3/4 on typedef and alias declarations. */
419 static bool
420 check_constexpr_bind_expr_vars (tree t)
422 gcc_assert (TREE_CODE (t) == BIND_EXPR);
424 for (tree var = BIND_EXPR_VARS (t); var; var = DECL_CHAIN (var))
425 if (TREE_CODE (var) == TYPE_DECL
426 && DECL_IMPLICIT_TYPEDEF_P (var)
427 && !LAMBDA_TYPE_P (TREE_TYPE (var)))
428 return false;
429 return true;
432 /* Subroutine of check_constexpr_ctor_body. */
434 static bool
435 check_constexpr_ctor_body_1 (tree last, tree list)
437 switch (TREE_CODE (list))
439 case DECL_EXPR:
440 if (TREE_CODE (DECL_EXPR_DECL (list)) == USING_DECL
441 || TREE_CODE (DECL_EXPR_DECL (list)) == TYPE_DECL)
442 return true;
443 return false;
445 case CLEANUP_POINT_EXPR:
446 return check_constexpr_ctor_body (last, TREE_OPERAND (list, 0),
447 /*complain=*/false);
449 case BIND_EXPR:
450 if (!check_constexpr_bind_expr_vars (list)
451 || !check_constexpr_ctor_body (last, BIND_EXPR_BODY (list),
452 /*complain=*/false))
453 return false;
454 return true;
456 case USING_STMT:
457 case STATIC_ASSERT:
458 case DEBUG_BEGIN_STMT:
459 return true;
461 default:
462 return false;
466 /* Make sure that there are no statements after LAST in the constructor
467 body represented by LIST. */
469 bool
470 check_constexpr_ctor_body (tree last, tree list, bool complain)
472 /* C++14 doesn't require a constexpr ctor to have an empty body. */
473 if (cxx_dialect >= cxx14)
474 return true;
476 bool ok = true;
477 if (TREE_CODE (list) == STATEMENT_LIST)
479 tree_stmt_iterator i = tsi_last (list);
480 for (; !tsi_end_p (i); tsi_prev (&i))
482 tree t = tsi_stmt (i);
483 if (t == last)
484 break;
485 if (!check_constexpr_ctor_body_1 (last, t))
487 ok = false;
488 break;
492 else if (list != last
493 && !check_constexpr_ctor_body_1 (last, list))
494 ok = false;
495 if (!ok)
497 if (complain)
498 error ("%<constexpr%> constructor does not have empty body");
499 DECL_DECLARED_CONSTEXPR_P (current_function_decl) = false;
501 return ok;
504 /* V is a vector of constructor elements built up for the base and member
505 initializers of a constructor for TYPE. They need to be in increasing
506 offset order, which they might not be yet if TYPE has a primary base
507 which is not first in the base-clause or a vptr and at least one base
508 all of which are non-primary. */
510 static vec<constructor_elt, va_gc> *
511 sort_constexpr_mem_initializers (tree type, vec<constructor_elt, va_gc> *v)
513 tree pri = CLASSTYPE_PRIMARY_BINFO (type);
514 tree field_type;
515 unsigned i;
516 constructor_elt *ce;
518 if (pri)
519 field_type = BINFO_TYPE (pri);
520 else if (TYPE_CONTAINS_VPTR_P (type))
521 field_type = vtbl_ptr_type_node;
522 else
523 return v;
525 /* Find the element for the primary base or vptr and move it to the
526 beginning of the vec. */
527 for (i = 0; vec_safe_iterate (v, i, &ce); ++i)
528 if (TREE_TYPE (ce->index) == field_type)
529 break;
531 if (i > 0 && i < vec_safe_length (v))
533 vec<constructor_elt, va_gc> &vref = *v;
534 constructor_elt elt = vref[i];
535 for (; i > 0; --i)
536 vref[i] = vref[i-1];
537 vref[0] = elt;
540 return v;
543 /* Build compile-time evalable representations of member-initializer list
544 for a constexpr constructor. */
546 static tree
547 build_constexpr_constructor_member_initializers (tree type, tree body)
549 vec<constructor_elt, va_gc> *vec = NULL;
550 bool ok = true;
551 while (true)
552 switch (TREE_CODE (body))
554 case MUST_NOT_THROW_EXPR:
555 case EH_SPEC_BLOCK:
556 body = TREE_OPERAND (body, 0);
557 break;
559 case STATEMENT_LIST:
560 for (tree_stmt_iterator i = tsi_start (body);
561 !tsi_end_p (i); tsi_next (&i))
563 body = tsi_stmt (i);
564 if (TREE_CODE (body) == BIND_EXPR)
565 break;
567 break;
569 case BIND_EXPR:
570 body = BIND_EXPR_BODY (body);
571 goto found;
573 default:
574 gcc_unreachable ();
576 found:
577 if (TREE_CODE (body) == CLEANUP_POINT_EXPR)
579 body = TREE_OPERAND (body, 0);
580 if (TREE_CODE (body) == EXPR_STMT)
581 body = TREE_OPERAND (body, 0);
582 if (TREE_CODE (body) == INIT_EXPR
583 && (same_type_ignoring_top_level_qualifiers_p
584 (TREE_TYPE (TREE_OPERAND (body, 0)),
585 current_class_type)))
587 /* Trivial copy. */
588 return TREE_OPERAND (body, 1);
590 ok = build_data_member_initialization (body, &vec);
592 else if (TREE_CODE (body) == STATEMENT_LIST)
594 tree_stmt_iterator i;
595 for (i = tsi_start (body); !tsi_end_p (i); tsi_next (&i))
597 ok = build_data_member_initialization (tsi_stmt (i), &vec);
598 if (!ok)
599 break;
602 else if (TREE_CODE (body) == TRY_BLOCK)
604 error ("body of %<constexpr%> constructor cannot be "
605 "a function-try-block");
606 return error_mark_node;
608 else if (EXPR_P (body))
609 ok = build_data_member_initialization (body, &vec);
610 else
611 gcc_assert (errorcount > 0);
612 if (ok)
614 if (vec_safe_length (vec) > 0)
616 /* In a delegating constructor, return the target. */
617 constructor_elt *ce = &(*vec)[0];
618 if (ce->index == current_class_ptr)
620 body = ce->value;
621 vec_free (vec);
622 return body;
625 vec = sort_constexpr_mem_initializers (type, vec);
626 return build_constructor (type, vec);
628 else
629 return error_mark_node;
632 /* We have an expression tree T that represents a call, either CALL_EXPR
633 or AGGR_INIT_EXPR. If the call is lexically to a named function,
634 retrun the _DECL for that function. */
636 static tree
637 get_function_named_in_call (tree t)
639 tree fun = cp_get_callee (t);
640 if (fun && TREE_CODE (fun) == ADDR_EXPR
641 && TREE_CODE (TREE_OPERAND (fun, 0)) == FUNCTION_DECL)
642 fun = TREE_OPERAND (fun, 0);
643 return fun;
646 /* Subroutine of register_constexpr_fundef. BODY is the body of a function
647 declared to be constexpr, or a sub-statement thereof. Returns the
648 return value if suitable, error_mark_node for a statement not allowed in
649 a constexpr function, or NULL_TREE if no return value was found. */
651 static tree
652 constexpr_fn_retval (tree body)
654 switch (TREE_CODE (body))
656 case STATEMENT_LIST:
658 tree_stmt_iterator i;
659 tree expr = NULL_TREE;
660 for (i = tsi_start (body); !tsi_end_p (i); tsi_next (&i))
662 tree s = constexpr_fn_retval (tsi_stmt (i));
663 if (s == error_mark_node)
664 return error_mark_node;
665 else if (s == NULL_TREE)
666 /* Keep iterating. */;
667 else if (expr)
668 /* Multiple return statements. */
669 return error_mark_node;
670 else
671 expr = s;
673 return expr;
676 case RETURN_EXPR:
677 return break_out_target_exprs (TREE_OPERAND (body, 0));
679 case DECL_EXPR:
681 tree decl = DECL_EXPR_DECL (body);
682 if (TREE_CODE (decl) == USING_DECL
683 /* Accept __func__, __FUNCTION__, and __PRETTY_FUNCTION__. */
684 || DECL_ARTIFICIAL (decl))
685 return NULL_TREE;
686 return error_mark_node;
689 case CLEANUP_POINT_EXPR:
690 return constexpr_fn_retval (TREE_OPERAND (body, 0));
692 case BIND_EXPR:
693 if (!check_constexpr_bind_expr_vars (body))
694 return error_mark_node;
695 return constexpr_fn_retval (BIND_EXPR_BODY (body));
697 case USING_STMT:
698 case DEBUG_BEGIN_STMT:
699 return NULL_TREE;
701 case CALL_EXPR:
703 tree fun = get_function_named_in_call (body);
704 if (fun != NULL_TREE
705 && DECL_FUNCTION_CODE (fun) == BUILT_IN_UNREACHABLE)
706 return NULL_TREE;
708 /* Fallthru. */
710 default:
711 return error_mark_node;
715 /* Subroutine of register_constexpr_fundef. BODY is the DECL_SAVED_TREE of
716 FUN; do the necessary transformations to turn it into a single expression
717 that we can store in the hash table. */
719 static tree
720 massage_constexpr_body (tree fun, tree body)
722 if (DECL_CONSTRUCTOR_P (fun))
723 body = build_constexpr_constructor_member_initializers
724 (DECL_CONTEXT (fun), body);
725 else if (cxx_dialect < cxx14)
727 if (TREE_CODE (body) == EH_SPEC_BLOCK)
728 body = EH_SPEC_STMTS (body);
729 if (TREE_CODE (body) == MUST_NOT_THROW_EXPR)
730 body = TREE_OPERAND (body, 0);
731 body = constexpr_fn_retval (body);
733 return body;
736 /* CTYPE is a type constructed from BODY. Return true if some
737 bases/fields are uninitialized, and complain if COMPLAIN. */
739 static bool
740 cx_check_missing_mem_inits (tree ctype, tree body, bool complain)
742 unsigned nelts = 0;
744 if (body)
746 if (TREE_CODE (body) != CONSTRUCTOR)
747 return false;
748 nelts = CONSTRUCTOR_NELTS (body);
750 tree field = TYPE_FIELDS (ctype);
752 if (TREE_CODE (ctype) == UNION_TYPE)
754 if (nelts == 0 && next_initializable_field (field))
756 if (complain)
757 error ("%<constexpr%> constructor for union %qT must "
758 "initialize exactly one non-static data member", ctype);
759 return true;
761 return false;
764 /* Iterate over the CONSTRUCTOR, checking any missing fields don't
765 need an explicit initialization. */
766 bool bad = false;
767 for (unsigned i = 0; i <= nelts; ++i)
769 tree index = NULL_TREE;
770 if (i < nelts)
772 index = CONSTRUCTOR_ELT (body, i)->index;
773 /* Skip base and vtable inits. */
774 if (TREE_CODE (index) != FIELD_DECL
775 || DECL_ARTIFICIAL (index))
776 continue;
779 for (; field != index; field = DECL_CHAIN (field))
781 tree ftype;
782 if (TREE_CODE (field) != FIELD_DECL)
783 continue;
784 if (DECL_C_BIT_FIELD (field) && !DECL_NAME (field))
785 continue;
786 if (DECL_ARTIFICIAL (field))
787 continue;
788 if (ANON_AGGR_TYPE_P (TREE_TYPE (field)))
790 /* Recurse to check the anonummous aggregate member. */
791 bad |= cx_check_missing_mem_inits
792 (TREE_TYPE (field), NULL_TREE, complain);
793 if (bad && !complain)
794 return true;
795 continue;
797 ftype = strip_array_types (TREE_TYPE (field));
798 if (type_has_constexpr_default_constructor (ftype))
800 /* It's OK to skip a member with a trivial constexpr ctor.
801 A constexpr ctor that isn't trivial should have been
802 added in by now. */
803 gcc_checking_assert (!TYPE_HAS_COMPLEX_DFLT (ftype)
804 || errorcount != 0);
805 continue;
807 if (!complain)
808 return true;
809 error ("member %qD must be initialized by mem-initializer "
810 "in %<constexpr%> constructor", field);
811 inform (DECL_SOURCE_LOCATION (field), "declared here");
812 bad = true;
814 if (field == NULL_TREE)
815 break;
817 if (ANON_AGGR_TYPE_P (TREE_TYPE (index)))
819 /* Check the anonymous aggregate initializer is valid. */
820 bad |= cx_check_missing_mem_inits
821 (TREE_TYPE (index), CONSTRUCTOR_ELT (body, i)->value, complain);
822 if (bad && !complain)
823 return true;
825 field = DECL_CHAIN (field);
828 return bad;
831 /* We are processing the definition of the constexpr function FUN.
832 Check that its BODY fulfills the propriate requirements and
833 enter it in the constexpr function definition table.
834 For constructor BODY is actually the TREE_LIST of the
835 member-initializer list. */
837 tree
838 register_constexpr_fundef (tree fun, tree body)
840 constexpr_fundef entry;
841 constexpr_fundef **slot;
843 if (!is_valid_constexpr_fn (fun, !DECL_GENERATED_P (fun)))
844 return NULL;
846 tree massaged = massage_constexpr_body (fun, body);
847 if (massaged == NULL_TREE || massaged == error_mark_node)
849 if (!DECL_CONSTRUCTOR_P (fun))
850 error ("body of %<constexpr%> function %qD not a return-statement",
851 fun);
852 return NULL;
855 if (!potential_rvalue_constant_expression (massaged))
857 if (!DECL_GENERATED_P (fun))
858 require_potential_rvalue_constant_expression (massaged);
859 return NULL;
862 if (DECL_CONSTRUCTOR_P (fun)
863 && cx_check_missing_mem_inits (DECL_CONTEXT (fun),
864 massaged, !DECL_GENERATED_P (fun)))
865 return NULL;
867 /* Create the constexpr function table if necessary. */
868 if (constexpr_fundef_table == NULL)
869 constexpr_fundef_table
870 = hash_table<constexpr_fundef_hasher>::create_ggc (101);
872 entry.decl = fun;
873 entry.body = body;
874 slot = constexpr_fundef_table->find_slot (&entry, INSERT);
876 gcc_assert (*slot == NULL);
877 *slot = ggc_alloc<constexpr_fundef> ();
878 **slot = entry;
880 return fun;
883 /* FUN is a non-constexpr function called in a context that requires a
884 constant expression. If it comes from a constexpr template, explain why
885 the instantiation isn't constexpr. */
887 void
888 explain_invalid_constexpr_fn (tree fun)
890 static hash_set<tree> *diagnosed;
891 tree body;
892 location_t save_loc;
893 /* Only diagnose defaulted functions, lambdas, or instantiations. */
894 if (!DECL_DEFAULTED_FN (fun)
895 && !LAMBDA_TYPE_P (CP_DECL_CONTEXT (fun))
896 && !is_instantiation_of_constexpr (fun))
897 return;
898 if (diagnosed == NULL)
899 diagnosed = new hash_set<tree>;
900 if (diagnosed->add (fun))
901 /* Already explained. */
902 return;
904 save_loc = input_location;
905 if (!lambda_static_thunk_p (fun))
907 /* Diagnostics should completely ignore the static thunk, so leave
908 input_location set to our caller's location. */
909 input_location = DECL_SOURCE_LOCATION (fun);
910 inform (input_location,
911 "%qD is not usable as a %<constexpr%> function because:", fun);
913 /* First check the declaration. */
914 if (is_valid_constexpr_fn (fun, true))
916 /* Then if it's OK, the body. */
917 if (!DECL_DECLARED_CONSTEXPR_P (fun)
918 && !LAMBDA_TYPE_P (CP_DECL_CONTEXT (fun)))
919 explain_implicit_non_constexpr (fun);
920 else
922 body = massage_constexpr_body (fun, DECL_SAVED_TREE (fun));
923 require_potential_rvalue_constant_expression (body);
924 if (DECL_CONSTRUCTOR_P (fun))
925 cx_check_missing_mem_inits (DECL_CONTEXT (fun), body, true);
928 input_location = save_loc;
931 /* Objects of this type represent calls to constexpr functions
932 along with the bindings of parameters to their arguments, for
933 the purpose of compile time evaluation. */
935 struct GTY((for_user)) constexpr_call {
936 /* Description of the constexpr function definition. */
937 constexpr_fundef *fundef;
938 /* Parameter bindings environment. A TREE_LIST where each TREE_PURPOSE
939 is a parameter _DECL and the TREE_VALUE is the value of the parameter.
940 Note: This arrangement is made to accommodate the use of
941 iterative_hash_template_arg (see pt.c). If you change this
942 representation, also change the hash calculation in
943 cxx_eval_call_expression. */
944 tree bindings;
945 /* Result of the call.
946 NULL means the call is being evaluated.
947 error_mark_node means that the evaluation was erroneous;
948 otherwise, the actuall value of the call. */
949 tree result;
950 /* The hash of this call; we remember it here to avoid having to
951 recalculate it when expanding the hash table. */
952 hashval_t hash;
955 struct constexpr_call_hasher : ggc_ptr_hash<constexpr_call>
957 static hashval_t hash (constexpr_call *);
958 static bool equal (constexpr_call *, constexpr_call *);
961 enum constexpr_switch_state {
962 /* Used when processing a switch for the first time by cxx_eval_switch_expr
963 and default: label for that switch has not been seen yet. */
964 css_default_not_seen,
965 /* Used when processing a switch for the first time by cxx_eval_switch_expr
966 and default: label for that switch has been seen already. */
967 css_default_seen,
968 /* Used when processing a switch for the second time by
969 cxx_eval_switch_expr, where default: label should match. */
970 css_default_processing
973 /* The constexpr expansion context. CALL is the current function
974 expansion, CTOR is the current aggregate initializer, OBJECT is the
975 object being initialized by CTOR, either a VAR_DECL or a _REF. VALUES
976 is a map of values of variables initialized within the expression. */
978 struct constexpr_ctx {
979 /* The innermost call we're evaluating. */
980 constexpr_call *call;
981 /* Values for any temporaries or local variables within the
982 constant-expression. */
983 hash_map<tree,tree> *values;
984 /* SAVE_EXPRs that we've seen within the current LOOP_EXPR. NULL if we
985 aren't inside a loop. */
986 hash_set<tree> *save_exprs;
987 /* The CONSTRUCTOR we're currently building up for an aggregate
988 initializer. */
989 tree ctor;
990 /* The object we're building the CONSTRUCTOR for. */
991 tree object;
992 /* If inside SWITCH_EXPR. */
993 constexpr_switch_state *css_state;
994 /* Whether we should error on a non-constant expression or fail quietly. */
995 bool quiet;
996 /* Whether we are strictly conforming to constant expression rules or
997 trying harder to get a constant value. */
998 bool strict;
1001 /* A table of all constexpr calls that have been evaluated by the
1002 compiler in this translation unit. */
1004 static GTY (()) hash_table<constexpr_call_hasher> *constexpr_call_table;
1006 static tree cxx_eval_constant_expression (const constexpr_ctx *, tree,
1007 bool, bool *, bool *, tree * = NULL);
1009 /* Compute a hash value for a constexpr call representation. */
1011 inline hashval_t
1012 constexpr_call_hasher::hash (constexpr_call *info)
1014 return info->hash;
1017 /* Return true if the objects pointed to by P and Q represent calls
1018 to the same constexpr function with the same arguments.
1019 Otherwise, return false. */
1021 bool
1022 constexpr_call_hasher::equal (constexpr_call *lhs, constexpr_call *rhs)
1024 tree lhs_bindings;
1025 tree rhs_bindings;
1026 if (lhs == rhs)
1027 return 1;
1028 if (!constexpr_fundef_hasher::equal (lhs->fundef, rhs->fundef))
1029 return 0;
1030 lhs_bindings = lhs->bindings;
1031 rhs_bindings = rhs->bindings;
1032 while (lhs_bindings != NULL && rhs_bindings != NULL)
1034 tree lhs_arg = TREE_VALUE (lhs_bindings);
1035 tree rhs_arg = TREE_VALUE (rhs_bindings);
1036 gcc_assert (TREE_TYPE (lhs_arg) == TREE_TYPE (rhs_arg));
1037 if (!cp_tree_equal (lhs_arg, rhs_arg))
1038 return 0;
1039 lhs_bindings = TREE_CHAIN (lhs_bindings);
1040 rhs_bindings = TREE_CHAIN (rhs_bindings);
1042 return lhs_bindings == rhs_bindings;
1045 /* Initialize the constexpr call table, if needed. */
1047 static void
1048 maybe_initialize_constexpr_call_table (void)
1050 if (constexpr_call_table == NULL)
1051 constexpr_call_table = hash_table<constexpr_call_hasher>::create_ggc (101);
1054 /* During constexpr CALL_EXPR evaluation, to avoid issues with sharing when
1055 a function happens to get called recursively, we unshare the callee
1056 function's body and evaluate this unshared copy instead of evaluating the
1057 original body.
1059 FUNDEF_COPIES_TABLE is a per-function freelist of these unshared function
1060 copies. The underlying data structure of FUNDEF_COPIES_TABLE is a hash_map
1061 that's keyed off of the original FUNCTION_DECL and whose value is a
1062 TREE_LIST of this function's unused copies awaiting reuse.
1064 This is not GC-deletable to avoid GC affecting UID generation. */
1066 static GTY(()) hash_map<tree, tree> *fundef_copies_table;
1068 /* Initialize FUNDEF_COPIES_TABLE if it's not initialized. */
1070 static void
1071 maybe_initialize_fundef_copies_table ()
1073 if (fundef_copies_table == NULL)
1074 fundef_copies_table = hash_map<tree,tree>::create_ggc (101);
1077 /* Reuse a copy or create a new unshared copy of the function FUN.
1078 Return this copy. We use a TREE_LIST whose PURPOSE is body, VALUE
1079 is parms, TYPE is result. */
1081 static tree
1082 get_fundef_copy (tree fun)
1084 maybe_initialize_fundef_copies_table ();
1086 tree copy;
1087 bool existed;
1088 tree *slot = &fundef_copies_table->get_or_insert (fun, &existed);
1090 if (!existed)
1092 /* There is no cached function available, or in use. We can use
1093 the function directly. That the slot is now created records
1094 that this function is now in use. */
1095 copy = build_tree_list (DECL_SAVED_TREE (fun), DECL_ARGUMENTS (fun));
1096 TREE_TYPE (copy) = DECL_RESULT (fun);
1098 else if (*slot == NULL_TREE)
1100 /* We've already used the function itself, so make a copy. */
1101 copy = build_tree_list (NULL, NULL);
1102 TREE_PURPOSE (copy) = copy_fn (fun, TREE_VALUE (copy), TREE_TYPE (copy));
1104 else
1106 /* We have a cached function available. */
1107 copy = *slot;
1108 *slot = TREE_CHAIN (copy);
1111 return copy;
1114 /* Save the copy COPY of function FUN for later reuse by
1115 get_fundef_copy(). By construction, there will always be an entry
1116 to find. */
1118 static void
1119 save_fundef_copy (tree fun, tree copy)
1121 tree *slot = fundef_copies_table->get (fun);
1122 TREE_CHAIN (copy) = *slot;
1123 *slot = copy;
1126 /* We have an expression tree T that represents a call, either CALL_EXPR
1127 or AGGR_INIT_EXPR. Return the Nth argument. */
1129 static inline tree
1130 get_nth_callarg (tree t, int n)
1132 switch (TREE_CODE (t))
1134 case CALL_EXPR:
1135 return CALL_EXPR_ARG (t, n);
1137 case AGGR_INIT_EXPR:
1138 return AGGR_INIT_EXPR_ARG (t, n);
1140 default:
1141 gcc_unreachable ();
1142 return NULL;
1146 /* Attempt to evaluate T which represents a call to a builtin function.
1147 We assume here that all builtin functions evaluate to scalar types
1148 represented by _CST nodes. */
1150 static tree
1151 cxx_eval_builtin_function_call (const constexpr_ctx *ctx, tree t, tree fun,
1152 bool lval,
1153 bool *non_constant_p, bool *overflow_p)
1155 const int nargs = call_expr_nargs (t);
1156 tree *args = (tree *) alloca (nargs * sizeof (tree));
1157 tree new_call;
1158 int i;
1160 /* Don't fold __builtin_constant_p within a constexpr function. */
1161 bool bi_const_p = (DECL_FUNCTION_CODE (fun) == BUILT_IN_CONSTANT_P);
1163 if (bi_const_p
1164 && current_function_decl
1165 && DECL_DECLARED_CONSTEXPR_P (current_function_decl))
1167 *non_constant_p = true;
1168 return t;
1171 /* Be permissive for arguments to built-ins; __builtin_constant_p should
1172 return constant false for a non-constant argument. */
1173 constexpr_ctx new_ctx = *ctx;
1174 new_ctx.quiet = true;
1175 bool dummy1 = false, dummy2 = false;
1176 for (i = 0; i < nargs; ++i)
1178 args[i] = cxx_eval_constant_expression (&new_ctx, CALL_EXPR_ARG (t, i),
1179 false, &dummy1, &dummy2);
1180 if (bi_const_p)
1181 /* For __built_in_constant_p, fold all expressions with constant values
1182 even if they aren't C++ constant-expressions. */
1183 args[i] = cp_fully_fold (args[i]);
1186 bool save_ffbcp = force_folding_builtin_constant_p;
1187 force_folding_builtin_constant_p = true;
1188 new_call = fold_builtin_call_array (EXPR_LOCATION (t), TREE_TYPE (t),
1189 CALL_EXPR_FN (t), nargs, args);
1190 force_folding_builtin_constant_p = save_ffbcp;
1191 if (new_call == NULL)
1193 if (!*non_constant_p && !ctx->quiet)
1195 /* Do not allow__builtin_unreachable in constexpr function.
1196 The __builtin_unreachable call with BUILTINS_LOCATION
1197 comes from cp_maybe_instrument_return. */
1198 if (DECL_FUNCTION_CODE (fun) == BUILT_IN_UNREACHABLE
1199 && EXPR_LOCATION (t) == BUILTINS_LOCATION)
1200 error ("%<constexpr%> call flows off the end of the function");
1201 else
1203 new_call = build_call_array_loc (EXPR_LOCATION (t), TREE_TYPE (t),
1204 CALL_EXPR_FN (t), nargs, args);
1205 error ("%q+E is not a constant expression", new_call);
1208 *non_constant_p = true;
1209 return t;
1212 if (!is_constant_expression (new_call))
1214 if (!*non_constant_p && !ctx->quiet)
1215 error ("%q+E is not a constant expression", new_call);
1216 *non_constant_p = true;
1217 return t;
1220 return cxx_eval_constant_expression (&new_ctx, new_call, lval,
1221 non_constant_p, overflow_p);
1224 /* TEMP is the constant value of a temporary object of type TYPE. Adjust
1225 the type of the value to match. */
1227 static tree
1228 adjust_temp_type (tree type, tree temp)
1230 if (TREE_TYPE (temp) == type)
1231 return temp;
1232 /* Avoid wrapping an aggregate value in a NOP_EXPR. */
1233 if (TREE_CODE (temp) == CONSTRUCTOR)
1234 return build_constructor (type, CONSTRUCTOR_ELTS (temp));
1235 gcc_assert (scalarish_type_p (type));
1236 return cp_fold_convert (type, temp);
1239 /* Callback for walk_tree used by unshare_constructor. */
1241 static tree
1242 find_constructor (tree *tp, int *walk_subtrees, void *)
1244 if (TYPE_P (*tp))
1245 *walk_subtrees = 0;
1246 if (TREE_CODE (*tp) == CONSTRUCTOR)
1247 return *tp;
1248 return NULL_TREE;
1251 /* If T is a CONSTRUCTOR or an expression that has a CONSTRUCTOR node as a
1252 subexpression, return an unshared copy of T. Otherwise return T. */
1254 static tree
1255 unshare_constructor (tree t)
1257 tree ctor = walk_tree (&t, find_constructor, NULL, NULL);
1258 if (ctor != NULL_TREE)
1259 return unshare_expr (t);
1260 return t;
1263 /* Subroutine of cxx_eval_call_expression.
1264 We are processing a call expression (either CALL_EXPR or
1265 AGGR_INIT_EXPR) in the context of CTX. Evaluate
1266 all arguments and bind their values to correspondings
1267 parameters, making up the NEW_CALL context. */
1269 static void
1270 cxx_bind_parameters_in_call (const constexpr_ctx *ctx, tree t,
1271 constexpr_call *new_call,
1272 bool *non_constant_p, bool *overflow_p,
1273 bool *non_constant_args)
1275 const int nargs = call_expr_nargs (t);
1276 tree fun = new_call->fundef->decl;
1277 tree parms = DECL_ARGUMENTS (fun);
1278 int i;
1279 tree *p = &new_call->bindings;
1280 for (i = 0; i < nargs; ++i)
1282 tree x, arg;
1283 tree type = parms ? TREE_TYPE (parms) : void_type_node;
1284 x = get_nth_callarg (t, i);
1285 /* For member function, the first argument is a pointer to the implied
1286 object. For a constructor, it might still be a dummy object, in
1287 which case we get the real argument from ctx. */
1288 if (i == 0 && DECL_CONSTRUCTOR_P (fun)
1289 && is_dummy_object (x))
1291 x = ctx->object;
1292 x = build_address (x);
1294 bool lval = false;
1295 arg = cxx_eval_constant_expression (ctx, x, lval,
1296 non_constant_p, overflow_p);
1297 /* Don't VERIFY_CONSTANT here. */
1298 if (*non_constant_p && ctx->quiet)
1299 return;
1300 /* Just discard ellipsis args after checking their constantitude. */
1301 if (!parms)
1302 continue;
1304 if (!*non_constant_p)
1306 /* Make sure the binding has the same type as the parm. But
1307 only for constant args. */
1308 if (TREE_CODE (type) != REFERENCE_TYPE)
1309 arg = adjust_temp_type (type, arg);
1310 if (!TREE_CONSTANT (arg))
1311 *non_constant_args = true;
1312 *p = build_tree_list (parms, arg);
1313 p = &TREE_CHAIN (*p);
1315 parms = TREE_CHAIN (parms);
1319 /* Variables and functions to manage constexpr call expansion context.
1320 These do not need to be marked for PCH or GC. */
1322 /* FIXME remember and print actual constant arguments. */
1323 static vec<tree> call_stack;
1324 static int call_stack_tick;
1325 static int last_cx_error_tick;
1327 static bool
1328 push_cx_call_context (tree call)
1330 ++call_stack_tick;
1331 if (!EXPR_HAS_LOCATION (call))
1332 SET_EXPR_LOCATION (call, input_location);
1333 call_stack.safe_push (call);
1334 if (call_stack.length () > (unsigned) max_constexpr_depth)
1335 return false;
1336 return true;
1339 static void
1340 pop_cx_call_context (void)
1342 ++call_stack_tick;
1343 call_stack.pop ();
1346 vec<tree>
1347 cx_error_context (void)
1349 vec<tree> r = vNULL;
1350 if (call_stack_tick != last_cx_error_tick
1351 && !call_stack.is_empty ())
1352 r = call_stack;
1353 last_cx_error_tick = call_stack_tick;
1354 return r;
1357 /* Evaluate a call T to a GCC internal function when possible and return
1358 the evaluated result or, under the control of CTX, give an error, set
1359 NON_CONSTANT_P, and return the unevaluated call T otherwise. */
1361 static tree
1362 cxx_eval_internal_function (const constexpr_ctx *ctx, tree t,
1363 bool lval,
1364 bool *non_constant_p, bool *overflow_p)
1366 enum tree_code opcode = ERROR_MARK;
1368 switch (CALL_EXPR_IFN (t))
1370 case IFN_UBSAN_NULL:
1371 case IFN_UBSAN_BOUNDS:
1372 case IFN_UBSAN_VPTR:
1373 case IFN_FALLTHROUGH:
1374 return void_node;
1376 case IFN_ADD_OVERFLOW:
1377 opcode = PLUS_EXPR;
1378 break;
1379 case IFN_SUB_OVERFLOW:
1380 opcode = MINUS_EXPR;
1381 break;
1382 case IFN_MUL_OVERFLOW:
1383 opcode = MULT_EXPR;
1384 break;
1386 case IFN_LAUNDER:
1387 return cxx_eval_constant_expression (ctx, CALL_EXPR_ARG (t, 0),
1388 false, non_constant_p, overflow_p);
1390 default:
1391 if (!ctx->quiet)
1392 error_at (EXPR_LOC_OR_LOC (t, input_location),
1393 "call to internal function %qE", t);
1394 *non_constant_p = true;
1395 return t;
1398 /* Evaluate constant arguments using OPCODE and return a complex
1399 number containing the result and the overflow bit. */
1400 tree arg0 = cxx_eval_constant_expression (ctx, CALL_EXPR_ARG (t, 0), lval,
1401 non_constant_p, overflow_p);
1402 tree arg1 = cxx_eval_constant_expression (ctx, CALL_EXPR_ARG (t, 1), lval,
1403 non_constant_p, overflow_p);
1405 if (TREE_CODE (arg0) == INTEGER_CST && TREE_CODE (arg1) == INTEGER_CST)
1407 location_t loc = EXPR_LOC_OR_LOC (t, input_location);
1408 tree type = TREE_TYPE (TREE_TYPE (t));
1409 tree result = fold_binary_loc (loc, opcode, type,
1410 fold_convert_loc (loc, type, arg0),
1411 fold_convert_loc (loc, type, arg1));
1412 tree ovf
1413 = build_int_cst (type, arith_overflowed_p (opcode, type, arg0, arg1));
1414 /* Reset TREE_OVERFLOW to avoid warnings for the overflow. */
1415 if (TREE_OVERFLOW (result))
1416 TREE_OVERFLOW (result) = 0;
1418 return build_complex (TREE_TYPE (t), result, ovf);
1421 *non_constant_p = true;
1422 return t;
1425 /* Clean CONSTRUCTOR_NO_IMPLICIT_ZERO from CTOR and its sub-aggregates. */
1427 static void
1428 clear_no_implicit_zero (tree ctor)
1430 if (CONSTRUCTOR_NO_IMPLICIT_ZERO (ctor))
1432 CONSTRUCTOR_NO_IMPLICIT_ZERO (ctor) = false;
1433 tree elt; unsigned HOST_WIDE_INT idx;
1434 FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (ctor), idx, elt)
1435 if (TREE_CODE (elt) == CONSTRUCTOR)
1436 clear_no_implicit_zero (elt);
1440 /* Subroutine of cxx_eval_constant_expression.
1441 Evaluate the call expression tree T in the context of OLD_CALL expression
1442 evaluation. */
1444 static tree
1445 cxx_eval_call_expression (const constexpr_ctx *ctx, tree t,
1446 bool lval,
1447 bool *non_constant_p, bool *overflow_p)
1449 location_t loc = EXPR_LOC_OR_LOC (t, input_location);
1450 tree fun = get_function_named_in_call (t);
1451 constexpr_call new_call = { NULL, NULL, NULL, 0 };
1452 bool depth_ok;
1454 if (fun == NULL_TREE)
1455 return cxx_eval_internal_function (ctx, t, lval,
1456 non_constant_p, overflow_p);
1458 if (TREE_CODE (fun) != FUNCTION_DECL)
1460 /* Might be a constexpr function pointer. */
1461 fun = cxx_eval_constant_expression (ctx, fun,
1462 /*lval*/false, non_constant_p,
1463 overflow_p);
1464 STRIP_NOPS (fun);
1465 if (TREE_CODE (fun) == ADDR_EXPR)
1466 fun = TREE_OPERAND (fun, 0);
1468 if (TREE_CODE (fun) != FUNCTION_DECL)
1470 if (!ctx->quiet && !*non_constant_p)
1471 error_at (loc, "expression %qE does not designate a %<constexpr%> "
1472 "function", fun);
1473 *non_constant_p = true;
1474 return t;
1476 if (DECL_CLONED_FUNCTION_P (fun))
1477 fun = DECL_CLONED_FUNCTION (fun);
1479 if (is_ubsan_builtin_p (fun))
1480 return void_node;
1482 if (is_builtin_fn (fun))
1483 return cxx_eval_builtin_function_call (ctx, t, fun,
1484 lval, non_constant_p, overflow_p);
1485 if (!DECL_DECLARED_CONSTEXPR_P (fun))
1487 if (!ctx->quiet)
1489 if (!lambda_static_thunk_p (fun))
1490 error_at (loc, "call to non-%<constexpr%> function %qD", fun);
1491 explain_invalid_constexpr_fn (fun);
1493 *non_constant_p = true;
1494 return t;
1497 constexpr_ctx new_ctx = *ctx;
1498 if (DECL_CONSTRUCTOR_P (fun) && !ctx->object
1499 && TREE_CODE (t) == AGGR_INIT_EXPR)
1501 /* We want to have an initialization target for an AGGR_INIT_EXPR.
1502 If we don't already have one in CTX, use the AGGR_INIT_EXPR_SLOT. */
1503 new_ctx.object = AGGR_INIT_EXPR_SLOT (t);
1504 tree ctor = new_ctx.ctor = build_constructor (DECL_CONTEXT (fun), NULL);
1505 CONSTRUCTOR_NO_IMPLICIT_ZERO (ctor) = true;
1506 ctx->values->put (new_ctx.object, ctor);
1507 ctx = &new_ctx;
1510 /* Shortcut trivial constructor/op=. */
1511 if (trivial_fn_p (fun))
1513 tree init = NULL_TREE;
1514 if (call_expr_nargs (t) == 2)
1515 init = convert_from_reference (get_nth_callarg (t, 1));
1516 else if (TREE_CODE (t) == AGGR_INIT_EXPR
1517 && AGGR_INIT_ZERO_FIRST (t))
1518 init = build_zero_init (DECL_CONTEXT (fun), NULL_TREE, false);
1519 if (init)
1521 tree op = get_nth_callarg (t, 0);
1522 if (is_dummy_object (op))
1523 op = ctx->object;
1524 else
1525 op = build1 (INDIRECT_REF, TREE_TYPE (TREE_TYPE (op)), op);
1526 tree set = build2 (MODIFY_EXPR, TREE_TYPE (op), op, init);
1527 new_ctx.call = &new_call;
1528 return cxx_eval_constant_expression (&new_ctx, set, lval,
1529 non_constant_p, overflow_p);
1533 /* We can't defer instantiating the function any longer. */
1534 if (!DECL_INITIAL (fun)
1535 && DECL_TEMPLOID_INSTANTIATION (fun))
1537 location_t save_loc = input_location;
1538 input_location = loc;
1539 ++function_depth;
1540 instantiate_decl (fun, /*defer_ok*/false, /*expl_inst*/false);
1541 --function_depth;
1542 input_location = save_loc;
1545 /* If in direct recursive call, optimize definition search. */
1546 if (ctx && ctx->call && ctx->call->fundef && ctx->call->fundef->decl == fun)
1547 new_call.fundef = ctx->call->fundef;
1548 else
1550 new_call.fundef = retrieve_constexpr_fundef (fun);
1551 if (new_call.fundef == NULL || new_call.fundef->body == NULL
1552 || fun == current_function_decl)
1554 if (!ctx->quiet)
1556 /* We need to check for current_function_decl here in case we're
1557 being called during cp_fold_function, because at that point
1558 DECL_INITIAL is set properly and we have a fundef but we
1559 haven't lowered invisirefs yet (c++/70344). */
1560 if (DECL_INITIAL (fun) == error_mark_node
1561 || fun == current_function_decl)
1562 error_at (loc, "%qD called in a constant expression before its "
1563 "definition is complete", fun);
1564 else if (DECL_INITIAL (fun))
1566 /* The definition of fun was somehow unsuitable. But pretend
1567 that lambda static thunks don't exist. */
1568 if (!lambda_static_thunk_p (fun))
1569 error_at (loc, "%qD called in a constant expression", fun);
1570 explain_invalid_constexpr_fn (fun);
1572 else
1573 error_at (loc, "%qD used before its definition", fun);
1575 *non_constant_p = true;
1576 return t;
1580 bool non_constant_args = false;
1581 cxx_bind_parameters_in_call (ctx, t, &new_call,
1582 non_constant_p, overflow_p, &non_constant_args);
1583 if (*non_constant_p)
1584 return t;
1586 depth_ok = push_cx_call_context (t);
1588 tree result = NULL_TREE;
1590 constexpr_call *entry = NULL;
1591 if (depth_ok && !non_constant_args && ctx->strict)
1593 new_call.hash = iterative_hash_template_arg
1594 (new_call.bindings, constexpr_fundef_hasher::hash (new_call.fundef));
1596 /* If we have seen this call before, we are done. */
1597 maybe_initialize_constexpr_call_table ();
1598 constexpr_call **slot
1599 = constexpr_call_table->find_slot (&new_call, INSERT);
1600 entry = *slot;
1601 if (entry == NULL)
1603 /* We need to keep a pointer to the entry, not just the slot, as the
1604 slot can move in the call to cxx_eval_builtin_function_call. */
1605 *slot = entry = ggc_alloc<constexpr_call> ();
1606 *entry = new_call;
1608 /* Calls that are in progress have their result set to NULL,
1609 so that we can detect circular dependencies. */
1610 else if (entry->result == NULL)
1612 if (!ctx->quiet)
1613 error ("call has circular dependency");
1614 *non_constant_p = true;
1615 entry->result = result = error_mark_node;
1617 else
1618 result = entry->result;
1621 if (!depth_ok)
1623 if (!ctx->quiet)
1624 error ("%<constexpr%> evaluation depth exceeds maximum of %d (use "
1625 "-fconstexpr-depth= to increase the maximum)",
1626 max_constexpr_depth);
1627 *non_constant_p = true;
1628 result = error_mark_node;
1630 else
1632 if (result && result != error_mark_node)
1633 /* OK */;
1634 else if (!DECL_SAVED_TREE (fun))
1636 /* When at_eof >= 2, cgraph has started throwing away
1637 DECL_SAVED_TREE, so fail quietly. FIXME we get here because of
1638 late code generation for VEC_INIT_EXPR, which needs to be
1639 completely reconsidered. */
1640 gcc_assert (at_eof >= 2 && ctx->quiet);
1641 *non_constant_p = true;
1643 else
1645 tree body, parms, res;
1647 /* Reuse or create a new unshared copy of this function's body. */
1648 tree copy = get_fundef_copy (fun);
1649 body = TREE_PURPOSE (copy);
1650 parms = TREE_VALUE (copy);
1651 res = TREE_TYPE (copy);
1653 /* Associate the bindings with the remapped parms. */
1654 tree bound = new_call.bindings;
1655 tree remapped = parms;
1656 while (bound)
1658 tree oparm = TREE_PURPOSE (bound);
1659 tree arg = TREE_VALUE (bound);
1660 gcc_assert (DECL_NAME (remapped) == DECL_NAME (oparm));
1661 /* Don't share a CONSTRUCTOR that might be changed. */
1662 arg = unshare_constructor (arg);
1663 ctx->values->put (remapped, arg);
1664 bound = TREE_CHAIN (bound);
1665 remapped = DECL_CHAIN (remapped);
1667 /* Add the RESULT_DECL to the values map, too. */
1668 tree slot = NULL_TREE;
1669 if (DECL_BY_REFERENCE (res))
1671 slot = AGGR_INIT_EXPR_SLOT (t);
1672 tree addr = build_address (slot);
1673 addr = build_nop (TREE_TYPE (res), addr);
1674 ctx->values->put (res, addr);
1675 ctx->values->put (slot, NULL_TREE);
1677 else
1678 ctx->values->put (res, NULL_TREE);
1680 /* Track the callee's evaluated SAVE_EXPRs so that we can forget
1681 their values after the call. */
1682 constexpr_ctx ctx_with_save_exprs = *ctx;
1683 hash_set<tree> save_exprs;
1684 ctx_with_save_exprs.save_exprs = &save_exprs;
1685 ctx_with_save_exprs.call = &new_call;
1687 tree jump_target = NULL_TREE;
1688 cxx_eval_constant_expression (&ctx_with_save_exprs, body,
1689 lval, non_constant_p, overflow_p,
1690 &jump_target);
1692 if (DECL_CONSTRUCTOR_P (fun))
1693 /* This can be null for a subobject constructor call, in
1694 which case what we care about is the initialization
1695 side-effects rather than the value. We could get at the
1696 value by evaluating *this, but we don't bother; there's
1697 no need to put such a call in the hash table. */
1698 result = lval ? ctx->object : ctx->ctor;
1699 else if (VOID_TYPE_P (TREE_TYPE (res)))
1700 result = void_node;
1701 else
1703 result = *ctx->values->get (slot ? slot : res);
1704 if (result == NULL_TREE && !*non_constant_p)
1706 if (!ctx->quiet)
1707 error ("%<constexpr%> call flows off the end "
1708 "of the function");
1709 *non_constant_p = true;
1713 /* Forget the saved values of the callee's SAVE_EXPRs. */
1714 for (hash_set<tree>::iterator iter = save_exprs.begin();
1715 iter != save_exprs.end(); ++iter)
1716 ctx_with_save_exprs.values->remove (*iter);
1718 /* Remove the parms/result from the values map. Is it worth
1719 bothering to do this when the map itself is only live for
1720 one constexpr evaluation? If so, maybe also clear out
1721 other vars from call, maybe in BIND_EXPR handling? */
1722 ctx->values->remove (res);
1723 if (slot)
1724 ctx->values->remove (slot);
1725 for (tree parm = parms; parm; parm = TREE_CHAIN (parm))
1726 ctx->values->remove (parm);
1728 /* Make the unshared function copy we used available for re-use. */
1729 save_fundef_copy (fun, copy);
1732 if (result == error_mark_node)
1733 *non_constant_p = true;
1734 if (*non_constant_p || *overflow_p)
1735 result = error_mark_node;
1736 else if (!result)
1737 result = void_node;
1738 if (entry)
1739 entry->result = result;
1742 /* The result of a constexpr function must be completely initialized. */
1743 if (TREE_CODE (result) == CONSTRUCTOR)
1744 clear_no_implicit_zero (result);
1746 pop_cx_call_context ();
1747 return unshare_constructor (result);
1750 /* FIXME speed this up, it's taking 16% of compile time on sieve testcase. */
1752 bool
1753 reduced_constant_expression_p (tree t)
1755 switch (TREE_CODE (t))
1757 case PTRMEM_CST:
1758 /* Even if we can't lower this yet, it's constant. */
1759 return true;
1761 case CONSTRUCTOR:
1762 /* And we need to handle PTRMEM_CST wrapped in a CONSTRUCTOR. */
1763 tree idx, val, field; unsigned HOST_WIDE_INT i;
1764 if (CONSTRUCTOR_NO_IMPLICIT_ZERO (t))
1765 field = next_initializable_field (TYPE_FIELDS (TREE_TYPE (t)));
1766 else
1767 field = NULL_TREE;
1768 FOR_EACH_CONSTRUCTOR_ELT (CONSTRUCTOR_ELTS (t), i, idx, val)
1770 if (!val)
1771 /* We're in the middle of initializing this element. */
1772 return false;
1773 if (!reduced_constant_expression_p (val))
1774 return false;
1775 if (field)
1777 if (idx != field)
1778 return false;
1779 field = next_initializable_field (DECL_CHAIN (field));
1782 if (field)
1783 return false;
1784 else if (CONSTRUCTOR_NO_IMPLICIT_ZERO (t))
1785 /* All the fields are initialized. */
1786 CONSTRUCTOR_NO_IMPLICIT_ZERO (t) = false;
1787 return true;
1789 default:
1790 /* FIXME are we calling this too much? */
1791 return initializer_constant_valid_p (t, TREE_TYPE (t)) != NULL_TREE;
1795 /* Some expressions may have constant operands but are not constant
1796 themselves, such as 1/0. Call this function (or rather, the macro
1797 following it) to check for that condition.
1799 We only call this in places that require an arithmetic constant, not in
1800 places where we might have a non-constant expression that can be a
1801 component of a constant expression, such as the address of a constexpr
1802 variable that might be dereferenced later. */
1804 static bool
1805 verify_constant (tree t, bool allow_non_constant, bool *non_constant_p,
1806 bool *overflow_p)
1808 if (!*non_constant_p && !reduced_constant_expression_p (t))
1810 if (!allow_non_constant)
1811 error ("%q+E is not a constant expression", t);
1812 *non_constant_p = true;
1814 if (TREE_OVERFLOW_P (t))
1816 if (!allow_non_constant)
1818 permerror (input_location, "overflow in constant expression");
1819 /* If we're being permissive (and are in an enforcing
1820 context), ignore the overflow. */
1821 if (flag_permissive)
1822 return *non_constant_p;
1824 *overflow_p = true;
1826 return *non_constant_p;
1829 /* Check whether the shift operation with code CODE and type TYPE on LHS
1830 and RHS is undefined. If it is, give an error with an explanation,
1831 and return true; return false otherwise. */
1833 static bool
1834 cxx_eval_check_shift_p (location_t loc, const constexpr_ctx *ctx,
1835 enum tree_code code, tree type, tree lhs, tree rhs)
1837 if ((code != LSHIFT_EXPR && code != RSHIFT_EXPR)
1838 || TREE_CODE (lhs) != INTEGER_CST
1839 || TREE_CODE (rhs) != INTEGER_CST)
1840 return false;
1842 tree lhstype = TREE_TYPE (lhs);
1843 unsigned HOST_WIDE_INT uprec = TYPE_PRECISION (TREE_TYPE (lhs));
1845 /* [expr.shift] The behavior is undefined if the right operand
1846 is negative, or greater than or equal to the length in bits
1847 of the promoted left operand. */
1848 if (tree_int_cst_sgn (rhs) == -1)
1850 if (!ctx->quiet)
1851 permerror (loc, "right operand of shift expression %q+E is negative",
1852 build2_loc (loc, code, type, lhs, rhs));
1853 return (!flag_permissive || ctx->quiet);
1855 if (compare_tree_int (rhs, uprec) >= 0)
1857 if (!ctx->quiet)
1858 permerror (loc, "right operand of shift expression %q+E is >= than "
1859 "the precision of the left operand",
1860 build2_loc (loc, code, type, lhs, rhs));
1861 return (!flag_permissive || ctx->quiet);
1864 /* The value of E1 << E2 is E1 left-shifted E2 bit positions; [...]
1865 if E1 has a signed type and non-negative value, and E1x2^E2 is
1866 representable in the corresponding unsigned type of the result type,
1867 then that value, converted to the result type, is the resulting value;
1868 otherwise, the behavior is undefined. */
1869 if (code == LSHIFT_EXPR && !TYPE_UNSIGNED (lhstype)
1870 && (cxx_dialect >= cxx11))
1872 if (tree_int_cst_sgn (lhs) == -1)
1874 if (!ctx->quiet)
1875 permerror (loc,
1876 "left operand of shift expression %q+E is negative",
1877 build2_loc (loc, code, type, lhs, rhs));
1878 return (!flag_permissive || ctx->quiet);
1880 /* For signed x << y the following:
1881 (unsigned) x >> ((prec (lhs) - 1) - y)
1882 if > 1, is undefined. The right-hand side of this formula
1883 is the highest bit of the LHS that can be set (starting from 0),
1884 so that the shift doesn't overflow. We then right-shift the LHS
1885 to see whether any other bit is set making the original shift
1886 undefined -- the result is not representable in the corresponding
1887 unsigned type. */
1888 tree t = build_int_cst (unsigned_type_node, uprec - 1);
1889 t = fold_build2 (MINUS_EXPR, unsigned_type_node, t, rhs);
1890 tree ulhs = fold_convert (unsigned_type_for (lhstype), lhs);
1891 t = fold_build2 (RSHIFT_EXPR, TREE_TYPE (ulhs), ulhs, t);
1892 if (tree_int_cst_lt (integer_one_node, t))
1894 if (!ctx->quiet)
1895 permerror (loc, "shift expression %q+E overflows",
1896 build2_loc (loc, code, type, lhs, rhs));
1897 return (!flag_permissive || ctx->quiet);
1900 return false;
1903 /* Subroutine of cxx_eval_constant_expression.
1904 Attempt to reduce the unary expression tree T to a compile time value.
1905 If successful, return the value. Otherwise issue a diagnostic
1906 and return error_mark_node. */
1908 static tree
1909 cxx_eval_unary_expression (const constexpr_ctx *ctx, tree t,
1910 bool /*lval*/,
1911 bool *non_constant_p, bool *overflow_p)
1913 tree r;
1914 tree orig_arg = TREE_OPERAND (t, 0);
1915 tree arg = cxx_eval_constant_expression (ctx, orig_arg, /*lval*/false,
1916 non_constant_p, overflow_p);
1917 VERIFY_CONSTANT (arg);
1918 location_t loc = EXPR_LOCATION (t);
1919 enum tree_code code = TREE_CODE (t);
1920 tree type = TREE_TYPE (t);
1921 r = fold_unary_loc (loc, code, type, arg);
1922 if (r == NULL_TREE)
1924 if (arg == orig_arg)
1925 r = t;
1926 else
1927 r = build1_loc (loc, code, type, arg);
1929 VERIFY_CONSTANT (r);
1930 return r;
1933 /* Helper function for cxx_eval_binary_expression. Try to optimize
1934 original POINTER_PLUS_EXPR T, LHS p+ RHS, return NULL_TREE if the
1935 generic folding should be used. */
1937 static tree
1938 cxx_fold_pointer_plus_expression (const constexpr_ctx *ctx, tree t,
1939 tree lhs, tree rhs, bool *non_constant_p,
1940 bool *overflow_p)
1942 STRIP_NOPS (lhs);
1943 if (TREE_CODE (lhs) != ADDR_EXPR)
1944 return NULL_TREE;
1946 lhs = TREE_OPERAND (lhs, 0);
1948 /* &A[i] p+ j => &A[i + j] */
1949 if (TREE_CODE (lhs) == ARRAY_REF
1950 && TREE_CODE (TREE_OPERAND (lhs, 1)) == INTEGER_CST
1951 && TREE_CODE (rhs) == INTEGER_CST
1952 && TYPE_SIZE_UNIT (TREE_TYPE (lhs))
1953 && TREE_CODE (TYPE_SIZE_UNIT (TREE_TYPE (lhs))) == INTEGER_CST)
1955 tree orig_type = TREE_TYPE (t);
1956 location_t loc = EXPR_LOCATION (t);
1957 tree type = TREE_TYPE (lhs);
1959 t = fold_convert_loc (loc, ssizetype, TREE_OPERAND (lhs, 1));
1960 tree nelts = array_type_nelts_top (TREE_TYPE (TREE_OPERAND (lhs, 0)));
1961 nelts = cxx_eval_constant_expression (ctx, nelts, false, non_constant_p,
1962 overflow_p);
1963 if (*non_constant_p)
1964 return NULL_TREE;
1965 /* Don't fold an out-of-bound access. */
1966 if (!tree_int_cst_le (t, nelts))
1967 return NULL_TREE;
1968 rhs = cp_fold_convert (ssizetype, rhs);
1969 /* Don't fold if rhs can't be divided exactly by TYPE_SIZE_UNIT.
1970 constexpr int A[1]; ... (char *)&A[0] + 1 */
1971 if (!integer_zerop (fold_build2_loc (loc, TRUNC_MOD_EXPR, sizetype,
1972 rhs, TYPE_SIZE_UNIT (type))))
1973 return NULL_TREE;
1974 /* Make sure to treat the second operand of POINTER_PLUS_EXPR
1975 as signed. */
1976 rhs = fold_build2_loc (loc, EXACT_DIV_EXPR, ssizetype, rhs,
1977 TYPE_SIZE_UNIT (type));
1978 t = size_binop_loc (loc, PLUS_EXPR, rhs, t);
1979 t = build4_loc (loc, ARRAY_REF, type, TREE_OPERAND (lhs, 0),
1980 t, NULL_TREE, NULL_TREE);
1981 t = cp_build_addr_expr (t, tf_warning_or_error);
1982 t = cp_fold_convert (orig_type, t);
1983 return cxx_eval_constant_expression (ctx, t, /*lval*/false,
1984 non_constant_p, overflow_p);
1987 return NULL_TREE;
1990 /* Subroutine of cxx_eval_constant_expression.
1991 Like cxx_eval_unary_expression, except for binary expressions. */
1993 static tree
1994 cxx_eval_binary_expression (const constexpr_ctx *ctx, tree t,
1995 bool /*lval*/,
1996 bool *non_constant_p, bool *overflow_p)
1998 tree r = NULL_TREE;
1999 tree orig_lhs = TREE_OPERAND (t, 0);
2000 tree orig_rhs = TREE_OPERAND (t, 1);
2001 tree lhs, rhs;
2002 lhs = cxx_eval_constant_expression (ctx, orig_lhs, /*lval*/false,
2003 non_constant_p, overflow_p);
2004 /* Don't VERIFY_CONSTANT here, it's unnecessary and will break pointer
2005 subtraction. */
2006 if (*non_constant_p)
2007 return t;
2008 rhs = cxx_eval_constant_expression (ctx, orig_rhs, /*lval*/false,
2009 non_constant_p, overflow_p);
2010 if (*non_constant_p)
2011 return t;
2013 location_t loc = EXPR_LOCATION (t);
2014 enum tree_code code = TREE_CODE (t);
2015 tree type = TREE_TYPE (t);
2017 if (code == EQ_EXPR || code == NE_EXPR)
2019 bool is_code_eq = (code == EQ_EXPR);
2021 if (TREE_CODE (lhs) == PTRMEM_CST
2022 && TREE_CODE (rhs) == PTRMEM_CST)
2023 r = constant_boolean_node (cp_tree_equal (lhs, rhs) == is_code_eq,
2024 type);
2025 else if ((TREE_CODE (lhs) == PTRMEM_CST
2026 || TREE_CODE (rhs) == PTRMEM_CST)
2027 && (null_member_pointer_value_p (lhs)
2028 || null_member_pointer_value_p (rhs)))
2029 r = constant_boolean_node (!is_code_eq, type);
2030 else if (TREE_CODE (lhs) == PTRMEM_CST)
2031 lhs = cplus_expand_constant (lhs);
2032 else if (TREE_CODE (rhs) == PTRMEM_CST)
2033 rhs = cplus_expand_constant (rhs);
2035 if (code == POINTER_PLUS_EXPR && !*non_constant_p
2036 && integer_zerop (lhs) && !integer_zerop (rhs))
2038 if (!ctx->quiet)
2039 error ("arithmetic involving a null pointer in %qE", lhs);
2040 return t;
2042 else if (code == POINTER_PLUS_EXPR)
2043 r = cxx_fold_pointer_plus_expression (ctx, t, lhs, rhs, non_constant_p,
2044 overflow_p);
2046 if (r == NULL_TREE)
2047 r = fold_binary_loc (loc, code, type, lhs, rhs);
2049 if (r == NULL_TREE)
2051 if (lhs == orig_lhs && rhs == orig_rhs)
2052 r = t;
2053 else
2054 r = build2_loc (loc, code, type, lhs, rhs);
2056 else if (cxx_eval_check_shift_p (loc, ctx, code, type, lhs, rhs))
2057 *non_constant_p = true;
2058 /* Don't VERIFY_CONSTANT if this might be dealing with a pointer to
2059 a local array in a constexpr function. */
2060 bool ptr = POINTER_TYPE_P (TREE_TYPE (lhs));
2061 if (!ptr)
2062 VERIFY_CONSTANT (r);
2063 return r;
2066 /* Subroutine of cxx_eval_constant_expression.
2067 Attempt to evaluate condition expressions. Dead branches are not
2068 looked into. */
2070 static tree
2071 cxx_eval_conditional_expression (const constexpr_ctx *ctx, tree t,
2072 bool lval,
2073 bool *non_constant_p, bool *overflow_p,
2074 tree *jump_target)
2076 tree val = cxx_eval_constant_expression (ctx, TREE_OPERAND (t, 0),
2077 /*lval*/false,
2078 non_constant_p, overflow_p);
2079 VERIFY_CONSTANT (val);
2080 /* Don't VERIFY_CONSTANT the other operands. */
2081 if (integer_zerop (val))
2082 return cxx_eval_constant_expression (ctx, TREE_OPERAND (t, 2),
2083 lval,
2084 non_constant_p, overflow_p,
2085 jump_target);
2086 return cxx_eval_constant_expression (ctx, TREE_OPERAND (t, 1),
2087 lval,
2088 non_constant_p, overflow_p,
2089 jump_target);
2092 /* Subroutine of cxx_eval_constant_expression.
2093 Attempt to evaluate vector condition expressions. Unlike
2094 cxx_eval_conditional_expression, VEC_COND_EXPR acts like a normal
2095 ternary arithmetics operation, where all 3 arguments have to be
2096 evaluated as constants and then folding computes the result from
2097 them. */
2099 static tree
2100 cxx_eval_vector_conditional_expression (const constexpr_ctx *ctx, tree t,
2101 bool *non_constant_p, bool *overflow_p)
2103 tree arg1 = cxx_eval_constant_expression (ctx, TREE_OPERAND (t, 0),
2104 /*lval*/false,
2105 non_constant_p, overflow_p);
2106 VERIFY_CONSTANT (arg1);
2107 tree arg2 = cxx_eval_constant_expression (ctx, TREE_OPERAND (t, 1),
2108 /*lval*/false,
2109 non_constant_p, overflow_p);
2110 VERIFY_CONSTANT (arg2);
2111 tree arg3 = cxx_eval_constant_expression (ctx, TREE_OPERAND (t, 2),
2112 /*lval*/false,
2113 non_constant_p, overflow_p);
2114 VERIFY_CONSTANT (arg3);
2115 location_t loc = EXPR_LOCATION (t);
2116 tree type = TREE_TYPE (t);
2117 tree r = fold_ternary_loc (loc, VEC_COND_EXPR, type, arg1, arg2, arg3);
2118 if (r == NULL_TREE)
2120 if (arg1 == TREE_OPERAND (t, 0)
2121 && arg2 == TREE_OPERAND (t, 1)
2122 && arg3 == TREE_OPERAND (t, 2))
2123 r = t;
2124 else
2125 r = build3_loc (loc, VEC_COND_EXPR, type, arg1, arg2, arg3);
2127 VERIFY_CONSTANT (r);
2128 return r;
2131 /* Returns less than, equal to, or greater than zero if KEY is found to be
2132 less than, to match, or to be greater than the constructor_elt's INDEX. */
2134 static int
2135 array_index_cmp (tree key, tree index)
2137 gcc_assert (TREE_CODE (key) == INTEGER_CST);
2139 switch (TREE_CODE (index))
2141 case INTEGER_CST:
2142 return tree_int_cst_compare (key, index);
2143 case RANGE_EXPR:
2145 tree lo = TREE_OPERAND (index, 0);
2146 tree hi = TREE_OPERAND (index, 1);
2147 if (tree_int_cst_lt (key, lo))
2148 return -1;
2149 else if (tree_int_cst_lt (hi, key))
2150 return 1;
2151 else
2152 return 0;
2154 default:
2155 gcc_unreachable ();
2159 /* Returns the index of the constructor_elt of ARY which matches DINDEX, or -1
2160 if none. If INSERT is true, insert a matching element rather than fail. */
2162 static HOST_WIDE_INT
2163 find_array_ctor_elt (tree ary, tree dindex, bool insert = false)
2165 if (tree_int_cst_sgn (dindex) < 0)
2166 return -1;
2168 unsigned HOST_WIDE_INT i = tree_to_uhwi (dindex);
2169 vec<constructor_elt, va_gc> *elts = CONSTRUCTOR_ELTS (ary);
2170 unsigned HOST_WIDE_INT len = vec_safe_length (elts);
2172 unsigned HOST_WIDE_INT end = len;
2173 unsigned HOST_WIDE_INT begin = 0;
2175 /* If the last element of the CONSTRUCTOR has its own index, we can assume
2176 that the same is true of the other elements and index directly. */
2177 if (end > 0)
2179 tree cindex = (*elts)[end-1].index;
2180 if (TREE_CODE (cindex) == INTEGER_CST
2181 && compare_tree_int (cindex, end-1) == 0)
2183 if (i < end)
2184 return i;
2185 else
2186 begin = end;
2190 /* Otherwise, find a matching index by means of a binary search. */
2191 while (begin != end)
2193 unsigned HOST_WIDE_INT middle = (begin + end) / 2;
2194 constructor_elt &elt = (*elts)[middle];
2195 tree idx = elt.index;
2197 int cmp = array_index_cmp (dindex, idx);
2198 if (cmp < 0)
2199 end = middle;
2200 else if (cmp > 0)
2201 begin = middle + 1;
2202 else
2204 if (insert && TREE_CODE (idx) == RANGE_EXPR)
2206 /* We need to split the range. */
2207 constructor_elt e;
2208 tree lo = TREE_OPERAND (idx, 0);
2209 tree hi = TREE_OPERAND (idx, 1);
2210 if (tree_int_cst_lt (lo, dindex))
2212 /* There are still some lower elts; shorten the range. */
2213 tree new_hi = int_const_binop (MINUS_EXPR, dindex,
2214 size_one_node);
2215 if (tree_int_cst_equal (lo, new_hi))
2216 /* Only one element left, no longer a range. */
2217 elt.index = lo;
2218 else
2219 TREE_OPERAND (idx, 1) = new_hi;
2220 /* Append the element we want to insert. */
2221 ++middle;
2222 e.index = dindex;
2223 e.value = unshare_constructor (elt.value);
2224 vec_safe_insert (CONSTRUCTOR_ELTS (ary), middle, e);
2226 else
2227 /* No lower elts, the range elt is now ours. */
2228 elt.index = dindex;
2230 if (tree_int_cst_lt (dindex, hi))
2232 /* There are still some higher elts; append a range. */
2233 tree new_lo = int_const_binop (PLUS_EXPR, dindex,
2234 size_one_node);
2235 if (tree_int_cst_equal (new_lo, hi))
2236 e.index = hi;
2237 else
2238 e.index = build2 (RANGE_EXPR, sizetype, new_lo, hi);
2239 e.value = unshare_constructor (elt.value);
2240 vec_safe_insert (CONSTRUCTOR_ELTS (ary), middle+1, e);
2243 return middle;
2247 if (insert)
2249 constructor_elt e = { dindex, NULL_TREE };
2250 vec_safe_insert (CONSTRUCTOR_ELTS (ary), end, e);
2251 return end;
2254 return -1;
2257 /* Under the control of CTX, issue a detailed diagnostic for
2258 an out-of-bounds subscript INDEX into the expression ARRAY. */
2260 static void
2261 diag_array_subscript (const constexpr_ctx *ctx, tree array, tree index)
2263 if (!ctx->quiet)
2265 tree arraytype = TREE_TYPE (array);
2267 /* Convert the unsigned array subscript to a signed integer to avoid
2268 printing huge numbers for small negative values. */
2269 tree sidx = fold_convert (ssizetype, index);
2270 if (DECL_P (array))
2272 error ("array subscript value %qE is outside the bounds "
2273 "of array %qD of type %qT", sidx, array, arraytype);
2274 inform (DECL_SOURCE_LOCATION (array), "declared here");
2276 else
2277 error ("array subscript value %qE is outside the bounds "
2278 "of array type %qT", sidx, arraytype);
2282 /* Extract element INDEX consisting of CHARS_PER_ELT chars from
2283 STRING_CST STRING. */
2285 static tree
2286 extract_string_elt (tree string, unsigned chars_per_elt, unsigned index)
2288 tree type = cv_unqualified (TREE_TYPE (TREE_TYPE (string)));
2289 tree r;
2291 if (chars_per_elt == 1)
2292 r = build_int_cst (type, TREE_STRING_POINTER (string)[index]);
2293 else
2295 const unsigned char *ptr
2296 = ((const unsigned char *)TREE_STRING_POINTER (string)
2297 + index * chars_per_elt);
2298 r = native_interpret_expr (type, ptr, chars_per_elt);
2300 return r;
2303 /* Subroutine of cxx_eval_constant_expression.
2304 Attempt to reduce a reference to an array slot. */
2306 static tree
2307 cxx_eval_array_reference (const constexpr_ctx *ctx, tree t,
2308 bool lval,
2309 bool *non_constant_p, bool *overflow_p)
2311 tree oldary = TREE_OPERAND (t, 0);
2312 tree ary = cxx_eval_constant_expression (ctx, oldary,
2313 lval,
2314 non_constant_p, overflow_p);
2315 tree index, oldidx;
2316 HOST_WIDE_INT i = 0;
2317 tree elem_type = NULL_TREE;
2318 unsigned len = 0, elem_nchars = 1;
2319 if (*non_constant_p)
2320 return t;
2321 oldidx = TREE_OPERAND (t, 1);
2322 index = cxx_eval_constant_expression (ctx, oldidx,
2323 false,
2324 non_constant_p, overflow_p);
2325 VERIFY_CONSTANT (index);
2326 if (!lval)
2328 elem_type = TREE_TYPE (TREE_TYPE (ary));
2329 if (TREE_CODE (ary) == VIEW_CONVERT_EXPR
2330 && VECTOR_TYPE_P (TREE_TYPE (TREE_OPERAND (ary, 0)))
2331 && TREE_TYPE (t) == TREE_TYPE (TREE_TYPE (TREE_OPERAND (ary, 0))))
2332 ary = TREE_OPERAND (ary, 0);
2333 if (TREE_CODE (ary) == CONSTRUCTOR)
2334 len = CONSTRUCTOR_NELTS (ary);
2335 else if (TREE_CODE (ary) == STRING_CST)
2337 elem_nchars = (TYPE_PRECISION (elem_type)
2338 / TYPE_PRECISION (char_type_node));
2339 len = (unsigned) TREE_STRING_LENGTH (ary) / elem_nchars;
2341 else if (TREE_CODE (ary) == VECTOR_CST)
2342 len = VECTOR_CST_NELTS (ary);
2343 else
2345 /* We can't do anything with other tree codes, so use
2346 VERIFY_CONSTANT to complain and fail. */
2347 VERIFY_CONSTANT (ary);
2348 gcc_unreachable ();
2351 if (!tree_fits_shwi_p (index)
2352 || (i = tree_to_shwi (index)) < 0)
2354 diag_array_subscript (ctx, ary, index);
2355 *non_constant_p = true;
2356 return t;
2360 tree nelts;
2361 if (TREE_CODE (TREE_TYPE (ary)) == ARRAY_TYPE)
2362 nelts = array_type_nelts_top (TREE_TYPE (ary));
2363 else if (VECTOR_TYPE_P (TREE_TYPE (ary)))
2364 nelts = size_int (TYPE_VECTOR_SUBPARTS (TREE_TYPE (ary)));
2365 else
2366 gcc_unreachable ();
2368 /* For VLAs, the number of elements won't be an integer constant. */
2369 nelts = cxx_eval_constant_expression (ctx, nelts, false, non_constant_p,
2370 overflow_p);
2371 VERIFY_CONSTANT (nelts);
2372 if ((lval
2373 ? !tree_int_cst_le (index, nelts)
2374 : !tree_int_cst_lt (index, nelts))
2375 || tree_int_cst_sgn (index) < 0)
2377 diag_array_subscript (ctx, ary, index);
2378 *non_constant_p = true;
2379 return t;
2382 if (lval && ary == oldary && index == oldidx)
2383 return t;
2384 else if (lval)
2385 return build4 (ARRAY_REF, TREE_TYPE (t), ary, index, NULL, NULL);
2387 bool found;
2388 if (TREE_CODE (ary) == CONSTRUCTOR)
2390 HOST_WIDE_INT ix = find_array_ctor_elt (ary, index);
2391 found = (ix >= 0);
2392 if (found)
2393 i = ix;
2395 else
2396 found = (i < len);
2398 if (found)
2400 tree r;
2401 if (TREE_CODE (ary) == CONSTRUCTOR)
2402 r = (*CONSTRUCTOR_ELTS (ary))[i].value;
2403 else if (TREE_CODE (ary) == VECTOR_CST)
2404 r = VECTOR_CST_ELT (ary, i);
2405 else
2406 r = extract_string_elt (ary, elem_nchars, i);
2408 if (r)
2409 /* Don't VERIFY_CONSTANT here. */
2410 return r;
2412 /* Otherwise the element doesn't have a value yet. */
2415 /* Not found. */
2417 if (TREE_CODE (ary) == CONSTRUCTOR
2418 && CONSTRUCTOR_NO_IMPLICIT_ZERO (ary))
2420 /* 'ary' is part of the aggregate initializer we're currently
2421 building; if there's no initializer for this element yet,
2422 that's an error. */
2423 if (!ctx->quiet)
2424 error ("accessing uninitialized array element");
2425 *non_constant_p = true;
2426 return t;
2429 /* If it's within the array bounds but doesn't have an explicit
2430 initializer, it's value-initialized. */
2431 tree val = build_value_init (elem_type, tf_warning_or_error);
2432 return cxx_eval_constant_expression (ctx, val, lval, non_constant_p,
2433 overflow_p);
2436 /* Subroutine of cxx_eval_constant_expression.
2437 Attempt to reduce a field access of a value of class type. */
2439 static tree
2440 cxx_eval_component_reference (const constexpr_ctx *ctx, tree t,
2441 bool lval,
2442 bool *non_constant_p, bool *overflow_p)
2444 unsigned HOST_WIDE_INT i;
2445 tree field;
2446 tree value;
2447 tree part = TREE_OPERAND (t, 1);
2448 tree orig_whole = TREE_OPERAND (t, 0);
2449 tree whole = cxx_eval_constant_expression (ctx, orig_whole,
2450 lval,
2451 non_constant_p, overflow_p);
2452 if (TREE_CODE (whole) == INDIRECT_REF
2453 && integer_zerop (TREE_OPERAND (whole, 0))
2454 && !ctx->quiet)
2455 error ("dereferencing a null pointer in %qE", orig_whole);
2457 if (TREE_CODE (whole) == PTRMEM_CST)
2458 whole = cplus_expand_constant (whole);
2459 if (whole == orig_whole)
2460 return t;
2461 if (lval)
2462 return fold_build3 (COMPONENT_REF, TREE_TYPE (t),
2463 whole, part, NULL_TREE);
2464 /* Don't VERIFY_CONSTANT here; we only want to check that we got a
2465 CONSTRUCTOR. */
2466 if (!*non_constant_p && TREE_CODE (whole) != CONSTRUCTOR)
2468 if (!ctx->quiet)
2469 error ("%qE is not a constant expression", orig_whole);
2470 *non_constant_p = true;
2472 if (DECL_MUTABLE_P (part))
2474 if (!ctx->quiet)
2475 error ("mutable %qD is not usable in a constant expression", part);
2476 *non_constant_p = true;
2478 if (*non_constant_p)
2479 return t;
2480 bool pmf = TYPE_PTRMEMFUNC_P (TREE_TYPE (whole));
2481 FOR_EACH_CONSTRUCTOR_ELT (CONSTRUCTOR_ELTS (whole), i, field, value)
2483 /* Use name match for PMF fields, as a variant will have a
2484 different FIELD_DECL with a different type. */
2485 if (pmf ? DECL_NAME (field) == DECL_NAME (part)
2486 : field == part)
2488 if (value)
2489 return value;
2490 else
2491 /* We're in the middle of initializing it. */
2492 break;
2495 if (TREE_CODE (TREE_TYPE (whole)) == UNION_TYPE
2496 && CONSTRUCTOR_NELTS (whole) > 0)
2498 /* DR 1188 says we don't have to deal with this. */
2499 if (!ctx->quiet)
2500 error ("accessing %qD member instead of initialized %qD member in "
2501 "constant expression", part, CONSTRUCTOR_ELT (whole, 0)->index);
2502 *non_constant_p = true;
2503 return t;
2506 /* We only create a CONSTRUCTOR for a subobject when we modify it, so empty
2507 classes never get represented; throw together a value now. */
2508 if (is_really_empty_class (TREE_TYPE (t)))
2509 return build_constructor (TREE_TYPE (t), NULL);
2511 gcc_assert (DECL_CONTEXT (part) == TYPE_MAIN_VARIANT (TREE_TYPE (whole)));
2513 if (CONSTRUCTOR_NO_IMPLICIT_ZERO (whole))
2515 /* 'whole' is part of the aggregate initializer we're currently
2516 building; if there's no initializer for this member yet, that's an
2517 error. */
2518 if (!ctx->quiet)
2519 error ("accessing uninitialized member %qD", part);
2520 *non_constant_p = true;
2521 return t;
2524 /* If there's no explicit init for this field, it's value-initialized. */
2525 value = build_value_init (TREE_TYPE (t), tf_warning_or_error);
2526 return cxx_eval_constant_expression (ctx, value,
2527 lval,
2528 non_constant_p, overflow_p);
2531 /* Subroutine of cxx_eval_constant_expression.
2532 Attempt to reduce a field access of a value of class type that is
2533 expressed as a BIT_FIELD_REF. */
2535 static tree
2536 cxx_eval_bit_field_ref (const constexpr_ctx *ctx, tree t,
2537 bool lval,
2538 bool *non_constant_p, bool *overflow_p)
2540 tree orig_whole = TREE_OPERAND (t, 0);
2541 tree retval, fldval, utype, mask;
2542 bool fld_seen = false;
2543 HOST_WIDE_INT istart, isize;
2544 tree whole = cxx_eval_constant_expression (ctx, orig_whole,
2545 lval,
2546 non_constant_p, overflow_p);
2547 tree start, field, value;
2548 unsigned HOST_WIDE_INT i;
2550 if (whole == orig_whole)
2551 return t;
2552 /* Don't VERIFY_CONSTANT here; we only want to check that we got a
2553 CONSTRUCTOR. */
2554 if (!*non_constant_p
2555 && TREE_CODE (whole) != VECTOR_CST
2556 && TREE_CODE (whole) != CONSTRUCTOR)
2558 if (!ctx->quiet)
2559 error ("%qE is not a constant expression", orig_whole);
2560 *non_constant_p = true;
2562 if (*non_constant_p)
2563 return t;
2565 if (TREE_CODE (whole) == VECTOR_CST)
2566 return fold_ternary (BIT_FIELD_REF, TREE_TYPE (t), whole,
2567 TREE_OPERAND (t, 1), TREE_OPERAND (t, 2));
2569 start = TREE_OPERAND (t, 2);
2570 istart = tree_to_shwi (start);
2571 isize = tree_to_shwi (TREE_OPERAND (t, 1));
2572 utype = TREE_TYPE (t);
2573 if (!TYPE_UNSIGNED (utype))
2574 utype = build_nonstandard_integer_type (TYPE_PRECISION (utype), 1);
2575 retval = build_int_cst (utype, 0);
2576 FOR_EACH_CONSTRUCTOR_ELT (CONSTRUCTOR_ELTS (whole), i, field, value)
2578 tree bitpos = bit_position (field);
2579 if (bitpos == start && DECL_SIZE (field) == TREE_OPERAND (t, 1))
2580 return value;
2581 if (TREE_CODE (TREE_TYPE (field)) == INTEGER_TYPE
2582 && TREE_CODE (value) == INTEGER_CST
2583 && tree_fits_shwi_p (bitpos)
2584 && tree_fits_shwi_p (DECL_SIZE (field)))
2586 HOST_WIDE_INT bit = tree_to_shwi (bitpos);
2587 HOST_WIDE_INT sz = tree_to_shwi (DECL_SIZE (field));
2588 HOST_WIDE_INT shift;
2589 if (bit >= istart && bit + sz <= istart + isize)
2591 fldval = fold_convert (utype, value);
2592 mask = build_int_cst_type (utype, -1);
2593 mask = fold_build2 (LSHIFT_EXPR, utype, mask,
2594 size_int (TYPE_PRECISION (utype) - sz));
2595 mask = fold_build2 (RSHIFT_EXPR, utype, mask,
2596 size_int (TYPE_PRECISION (utype) - sz));
2597 fldval = fold_build2 (BIT_AND_EXPR, utype, fldval, mask);
2598 shift = bit - istart;
2599 if (BYTES_BIG_ENDIAN)
2600 shift = TYPE_PRECISION (utype) - shift - sz;
2601 fldval = fold_build2 (LSHIFT_EXPR, utype, fldval,
2602 size_int (shift));
2603 retval = fold_build2 (BIT_IOR_EXPR, utype, retval, fldval);
2604 fld_seen = true;
2608 if (fld_seen)
2609 return fold_convert (TREE_TYPE (t), retval);
2610 gcc_unreachable ();
2611 return error_mark_node;
2614 /* Subroutine of cxx_eval_constant_expression.
2615 Evaluate a short-circuited logical expression T in the context
2616 of a given constexpr CALL. BAILOUT_VALUE is the value for
2617 early return. CONTINUE_VALUE is used here purely for
2618 sanity check purposes. */
2620 static tree
2621 cxx_eval_logical_expression (const constexpr_ctx *ctx, tree t,
2622 tree bailout_value, tree continue_value,
2623 bool lval,
2624 bool *non_constant_p, bool *overflow_p)
2626 tree r;
2627 tree lhs = cxx_eval_constant_expression (ctx, TREE_OPERAND (t, 0),
2628 lval,
2629 non_constant_p, overflow_p);
2630 VERIFY_CONSTANT (lhs);
2631 if (tree_int_cst_equal (lhs, bailout_value))
2632 return lhs;
2633 gcc_assert (tree_int_cst_equal (lhs, continue_value));
2634 r = cxx_eval_constant_expression (ctx, TREE_OPERAND (t, 1),
2635 lval, non_constant_p,
2636 overflow_p);
2637 VERIFY_CONSTANT (r);
2638 return r;
2641 /* REF is a COMPONENT_REF designating a particular field. V is a vector of
2642 CONSTRUCTOR elements to initialize (part of) an object containing that
2643 field. Return a pointer to the constructor_elt corresponding to the
2644 initialization of the field. */
2646 static constructor_elt *
2647 base_field_constructor_elt (vec<constructor_elt, va_gc> *v, tree ref)
2649 tree aggr = TREE_OPERAND (ref, 0);
2650 tree field = TREE_OPERAND (ref, 1);
2651 HOST_WIDE_INT i;
2652 constructor_elt *ce;
2654 gcc_assert (TREE_CODE (ref) == COMPONENT_REF);
2656 if (TREE_CODE (aggr) == COMPONENT_REF)
2658 constructor_elt *base_ce
2659 = base_field_constructor_elt (v, aggr);
2660 v = CONSTRUCTOR_ELTS (base_ce->value);
2663 for (i = 0; vec_safe_iterate (v, i, &ce); ++i)
2664 if (ce->index == field)
2665 return ce;
2667 gcc_unreachable ();
2668 return NULL;
2671 /* Some of the expressions fed to the constexpr mechanism are calls to
2672 constructors, which have type void. In that case, return the type being
2673 initialized by the constructor. */
2675 static tree
2676 initialized_type (tree t)
2678 if (TYPE_P (t))
2679 return t;
2680 tree type = cv_unqualified (TREE_TYPE (t));
2681 if (TREE_CODE (t) == CALL_EXPR || TREE_CODE (t) == AGGR_INIT_EXPR)
2683 /* A constructor call has void type, so we need to look deeper. */
2684 tree fn = get_function_named_in_call (t);
2685 if (fn && TREE_CODE (fn) == FUNCTION_DECL
2686 && DECL_CXX_CONSTRUCTOR_P (fn))
2687 type = DECL_CONTEXT (fn);
2689 return type;
2692 /* We're about to initialize element INDEX of an array or class from VALUE.
2693 Set up NEW_CTX appropriately by adjusting .object to refer to the
2694 subobject and creating a new CONSTRUCTOR if the element is itself
2695 a class or array. */
2697 static void
2698 init_subob_ctx (const constexpr_ctx *ctx, constexpr_ctx &new_ctx,
2699 tree index, tree &value)
2701 new_ctx = *ctx;
2703 if (index && TREE_CODE (index) != INTEGER_CST
2704 && TREE_CODE (index) != FIELD_DECL)
2705 /* This won't have an element in the new CONSTRUCTOR. */
2706 return;
2708 tree type = initialized_type (value);
2709 if (!AGGREGATE_TYPE_P (type) && !VECTOR_TYPE_P (type))
2710 /* A non-aggregate member doesn't get its own CONSTRUCTOR. */
2711 return;
2713 /* The sub-aggregate initializer might contain a placeholder;
2714 update object to refer to the subobject and ctor to refer to
2715 the (newly created) sub-initializer. */
2716 if (ctx->object)
2717 new_ctx.object = build_ctor_subob_ref (index, type, ctx->object);
2718 tree elt = build_constructor (type, NULL);
2719 CONSTRUCTOR_NO_IMPLICIT_ZERO (elt) = true;
2720 new_ctx.ctor = elt;
2722 if (TREE_CODE (value) == TARGET_EXPR)
2723 /* Avoid creating another CONSTRUCTOR when we expand the TARGET_EXPR. */
2724 value = TARGET_EXPR_INITIAL (value);
2727 /* We're about to process an initializer for a class or array TYPE. Make
2728 sure that CTX is set up appropriately. */
2730 static void
2731 verify_ctor_sanity (const constexpr_ctx *ctx, tree type)
2733 /* We don't bother building a ctor for an empty base subobject. */
2734 if (is_empty_class (type))
2735 return;
2737 /* We're in the middle of an initializer that might involve placeholders;
2738 our caller should have created a CONSTRUCTOR for us to put the
2739 initializer into. We will either return that constructor or T. */
2740 gcc_assert (ctx->ctor);
2741 gcc_assert (same_type_ignoring_top_level_qualifiers_p
2742 (type, TREE_TYPE (ctx->ctor)));
2743 /* We used to check that ctx->ctor was empty, but that isn't the case when
2744 the object is zero-initialized before calling the constructor. */
2745 if (ctx->object)
2747 tree otype = TREE_TYPE (ctx->object);
2748 gcc_assert (same_type_ignoring_top_level_qualifiers_p (type, otype)
2749 /* Handle flexible array members. */
2750 || (TREE_CODE (otype) == ARRAY_TYPE
2751 && TYPE_DOMAIN (otype) == NULL_TREE
2752 && TREE_CODE (type) == ARRAY_TYPE
2753 && (same_type_ignoring_top_level_qualifiers_p
2754 (TREE_TYPE (type), TREE_TYPE (otype)))));
2756 gcc_assert (!ctx->object || !DECL_P (ctx->object)
2757 || *(ctx->values->get (ctx->object)) == ctx->ctor);
2760 /* Subroutine of cxx_eval_constant_expression.
2761 The expression tree T denotes a C-style array or a C-style
2762 aggregate. Reduce it to a constant expression. */
2764 static tree
2765 cxx_eval_bare_aggregate (const constexpr_ctx *ctx, tree t,
2766 bool lval,
2767 bool *non_constant_p, bool *overflow_p)
2769 vec<constructor_elt, va_gc> *v = CONSTRUCTOR_ELTS (t);
2770 bool changed = false;
2771 gcc_assert (!BRACE_ENCLOSED_INITIALIZER_P (t));
2772 tree type = TREE_TYPE (t);
2774 constexpr_ctx new_ctx;
2775 if (TYPE_PTRMEMFUNC_P (type) || VECTOR_TYPE_P (type))
2777 /* We don't really need the ctx->ctor business for a PMF or
2778 vector, but it's simpler to use the same code. */
2779 new_ctx = *ctx;
2780 new_ctx.ctor = build_constructor (type, NULL);
2781 new_ctx.object = NULL_TREE;
2782 ctx = &new_ctx;
2784 verify_ctor_sanity (ctx, type);
2785 vec<constructor_elt, va_gc> **p = &CONSTRUCTOR_ELTS (ctx->ctor);
2786 vec_alloc (*p, vec_safe_length (v));
2788 unsigned i;
2789 tree index, value;
2790 bool constant_p = true;
2791 bool side_effects_p = false;
2792 FOR_EACH_CONSTRUCTOR_ELT (v, i, index, value)
2794 tree orig_value = value;
2795 init_subob_ctx (ctx, new_ctx, index, value);
2796 if (new_ctx.ctor != ctx->ctor)
2797 /* If we built a new CONSTRUCTOR, attach it now so that other
2798 initializers can refer to it. */
2799 CONSTRUCTOR_APPEND_ELT (*p, index, new_ctx.ctor);
2800 tree elt = cxx_eval_constant_expression (&new_ctx, value,
2801 lval,
2802 non_constant_p, overflow_p);
2803 /* Don't VERIFY_CONSTANT here. */
2804 if (ctx->quiet && *non_constant_p)
2805 break;
2806 if (elt != orig_value)
2807 changed = true;
2809 if (!TREE_CONSTANT (elt))
2810 constant_p = false;
2811 if (TREE_SIDE_EFFECTS (elt))
2812 side_effects_p = true;
2813 if (index && TREE_CODE (index) == COMPONENT_REF)
2815 /* This is an initialization of a vfield inside a base
2816 subaggregate that we already initialized; push this
2817 initialization into the previous initialization. */
2818 constructor_elt *inner = base_field_constructor_elt (*p, index);
2819 inner->value = elt;
2820 changed = true;
2822 else if (index
2823 && (TREE_CODE (index) == NOP_EXPR
2824 || TREE_CODE (index) == POINTER_PLUS_EXPR))
2826 /* This is an initializer for an empty base; now that we've
2827 checked that it's constant, we can ignore it. */
2828 gcc_assert (is_empty_class (TREE_TYPE (TREE_TYPE (index))));
2829 changed = true;
2831 else if (new_ctx.ctor != ctx->ctor)
2833 /* We appended this element above; update the value. */
2834 gcc_assert ((*p)->last().index == index);
2835 (*p)->last().value = elt;
2837 else
2838 CONSTRUCTOR_APPEND_ELT (*p, index, elt);
2840 if (*non_constant_p || !changed)
2841 return t;
2842 t = ctx->ctor;
2843 /* We're done building this CONSTRUCTOR, so now we can interpret an
2844 element without an explicit initializer as value-initialized. */
2845 CONSTRUCTOR_NO_IMPLICIT_ZERO (t) = false;
2846 TREE_CONSTANT (t) = constant_p;
2847 TREE_SIDE_EFFECTS (t) = side_effects_p;
2848 if (VECTOR_TYPE_P (type))
2849 t = fold (t);
2850 return t;
2853 /* Subroutine of cxx_eval_constant_expression.
2854 The expression tree T is a VEC_INIT_EXPR which denotes the desired
2855 initialization of a non-static data member of array type. Reduce it to a
2856 CONSTRUCTOR.
2858 Note that apart from value-initialization (when VALUE_INIT is true),
2859 this is only intended to support value-initialization and the
2860 initializations done by defaulted constructors for classes with
2861 non-static data members of array type. In this case, VEC_INIT_EXPR_INIT
2862 will either be NULL_TREE for the default constructor, or a COMPONENT_REF
2863 for the copy/move constructor. */
2865 static tree
2866 cxx_eval_vec_init_1 (const constexpr_ctx *ctx, tree atype, tree init,
2867 bool value_init, bool lval,
2868 bool *non_constant_p, bool *overflow_p)
2870 tree elttype = TREE_TYPE (atype);
2871 unsigned HOST_WIDE_INT max = tree_to_uhwi (array_type_nelts_top (atype));
2872 verify_ctor_sanity (ctx, atype);
2873 vec<constructor_elt, va_gc> **p = &CONSTRUCTOR_ELTS (ctx->ctor);
2874 vec_alloc (*p, max + 1);
2875 bool pre_init = false;
2876 unsigned HOST_WIDE_INT i;
2878 /* For the default constructor, build up a call to the default
2879 constructor of the element type. We only need to handle class types
2880 here, as for a constructor to be constexpr, all members must be
2881 initialized, which for a defaulted default constructor means they must
2882 be of a class type with a constexpr default constructor. */
2883 if (TREE_CODE (elttype) == ARRAY_TYPE)
2884 /* We only do this at the lowest level. */;
2885 else if (value_init)
2887 init = build_value_init (elttype, tf_warning_or_error);
2888 pre_init = true;
2890 else if (!init)
2892 vec<tree, va_gc> *argvec = make_tree_vector ();
2893 init = build_special_member_call (NULL_TREE, complete_ctor_identifier,
2894 &argvec, elttype, LOOKUP_NORMAL,
2895 tf_warning_or_error);
2896 release_tree_vector (argvec);
2897 init = build_aggr_init_expr (TREE_TYPE (init), init);
2898 pre_init = true;
2901 for (i = 0; i < max; ++i)
2903 tree idx = build_int_cst (size_type_node, i);
2904 tree eltinit;
2905 bool reuse = false;
2906 constexpr_ctx new_ctx;
2907 init_subob_ctx (ctx, new_ctx, idx, pre_init ? init : elttype);
2908 if (new_ctx.ctor != ctx->ctor)
2909 CONSTRUCTOR_APPEND_ELT (*p, idx, new_ctx.ctor);
2910 if (TREE_CODE (elttype) == ARRAY_TYPE)
2912 /* A multidimensional array; recurse. */
2913 if (value_init || init == NULL_TREE)
2915 eltinit = NULL_TREE;
2916 reuse = i == 0;
2918 else
2919 eltinit = cp_build_array_ref (input_location, init, idx,
2920 tf_warning_or_error);
2921 eltinit = cxx_eval_vec_init_1 (&new_ctx, elttype, eltinit, value_init,
2922 lval,
2923 non_constant_p, overflow_p);
2925 else if (pre_init)
2927 /* Initializing an element using value or default initialization
2928 we just pre-built above. */
2929 eltinit = cxx_eval_constant_expression (&new_ctx, init, lval,
2930 non_constant_p, overflow_p);
2931 reuse = i == 0;
2933 else
2935 /* Copying an element. */
2936 gcc_assert (same_type_ignoring_top_level_qualifiers_p
2937 (atype, TREE_TYPE (init)));
2938 eltinit = cp_build_array_ref (input_location, init, idx,
2939 tf_warning_or_error);
2940 if (!lvalue_p (init))
2941 eltinit = move (eltinit);
2942 eltinit = force_rvalue (eltinit, tf_warning_or_error);
2943 eltinit = (cxx_eval_constant_expression
2944 (&new_ctx, eltinit, lval,
2945 non_constant_p, overflow_p));
2947 if (*non_constant_p && !ctx->quiet)
2948 break;
2949 if (new_ctx.ctor != ctx->ctor)
2951 /* We appended this element above; update the value. */
2952 gcc_assert ((*p)->last().index == idx);
2953 (*p)->last().value = eltinit;
2955 else
2956 CONSTRUCTOR_APPEND_ELT (*p, idx, eltinit);
2957 /* Reuse the result of cxx_eval_constant_expression call
2958 from the first iteration to all others if it is a constant
2959 initializer that doesn't require relocations. */
2960 if (reuse
2961 && max > 1
2962 && (initializer_constant_valid_p (eltinit, TREE_TYPE (eltinit))
2963 == null_pointer_node))
2965 if (new_ctx.ctor != ctx->ctor)
2966 eltinit = new_ctx.ctor;
2967 for (i = 1; i < max; ++i)
2969 idx = build_int_cst (size_type_node, i);
2970 CONSTRUCTOR_APPEND_ELT (*p, idx, unshare_constructor (eltinit));
2972 break;
2976 if (!*non_constant_p)
2978 init = ctx->ctor;
2979 CONSTRUCTOR_NO_IMPLICIT_ZERO (init) = false;
2981 return init;
2984 static tree
2985 cxx_eval_vec_init (const constexpr_ctx *ctx, tree t,
2986 bool lval,
2987 bool *non_constant_p, bool *overflow_p)
2989 tree atype = TREE_TYPE (t);
2990 tree init = VEC_INIT_EXPR_INIT (t);
2991 tree r = cxx_eval_vec_init_1 (ctx, atype, init,
2992 VEC_INIT_EXPR_VALUE_INIT (t),
2993 lval, non_constant_p, overflow_p);
2994 if (*non_constant_p)
2995 return t;
2996 else
2997 return r;
3000 /* A less strict version of fold_indirect_ref_1, which requires cv-quals to
3001 match. We want to be less strict for simple *& folding; if we have a
3002 non-const temporary that we access through a const pointer, that should
3003 work. We handle this here rather than change fold_indirect_ref_1
3004 because we're dealing with things like ADDR_EXPR of INTEGER_CST which
3005 don't really make sense outside of constant expression evaluation. Also
3006 we want to allow folding to COMPONENT_REF, which could cause trouble
3007 with TBAA in fold_indirect_ref_1.
3009 Try to keep this function synced with fold_indirect_ref_1. */
3011 static tree
3012 cxx_fold_indirect_ref (location_t loc, tree type, tree op0, bool *empty_base)
3014 tree sub, subtype;
3016 sub = op0;
3017 STRIP_NOPS (sub);
3018 subtype = TREE_TYPE (sub);
3019 if (!POINTER_TYPE_P (subtype))
3020 return NULL_TREE;
3022 if (TREE_CODE (sub) == ADDR_EXPR)
3024 tree op = TREE_OPERAND (sub, 0);
3025 tree optype = TREE_TYPE (op);
3027 /* *&CONST_DECL -> to the value of the const decl. */
3028 if (TREE_CODE (op) == CONST_DECL)
3029 return DECL_INITIAL (op);
3030 /* *&p => p; make sure to handle *&"str"[cst] here. */
3031 if (same_type_ignoring_top_level_qualifiers_p (optype, type)
3032 /* Also handle the case where the desired type is an array of unknown
3033 bounds because the variable has had its bounds deduced since the
3034 ADDR_EXPR was created. */
3035 || (TREE_CODE (type) == ARRAY_TYPE
3036 && TREE_CODE (optype) == ARRAY_TYPE
3037 && TYPE_DOMAIN (type) == NULL_TREE
3038 && same_type_ignoring_top_level_qualifiers_p (TREE_TYPE (optype),
3039 TREE_TYPE (type))))
3041 tree fop = fold_read_from_constant_string (op);
3042 if (fop)
3043 return fop;
3044 else
3045 return op;
3047 /* *(foo *)&fooarray => fooarray[0] */
3048 else if (TREE_CODE (optype) == ARRAY_TYPE
3049 && (same_type_ignoring_top_level_qualifiers_p
3050 (type, TREE_TYPE (optype))))
3052 tree type_domain = TYPE_DOMAIN (optype);
3053 tree min_val = size_zero_node;
3054 if (type_domain && TYPE_MIN_VALUE (type_domain))
3055 min_val = TYPE_MIN_VALUE (type_domain);
3056 return build4_loc (loc, ARRAY_REF, type, op, min_val,
3057 NULL_TREE, NULL_TREE);
3059 /* *(foo *)&complexfoo => __real__ complexfoo */
3060 else if (TREE_CODE (optype) == COMPLEX_TYPE
3061 && (same_type_ignoring_top_level_qualifiers_p
3062 (type, TREE_TYPE (optype))))
3063 return fold_build1_loc (loc, REALPART_EXPR, type, op);
3064 /* *(foo *)&vectorfoo => BIT_FIELD_REF<vectorfoo,...> */
3065 else if (VECTOR_TYPE_P (optype)
3066 && (same_type_ignoring_top_level_qualifiers_p
3067 (type, TREE_TYPE (optype))))
3069 tree part_width = TYPE_SIZE (type);
3070 tree index = bitsize_int (0);
3071 return fold_build3_loc (loc, BIT_FIELD_REF, type, op, part_width, index);
3073 /* Also handle conversion to an empty base class, which
3074 is represented with a NOP_EXPR. */
3075 else if (is_empty_class (type)
3076 && CLASS_TYPE_P (optype)
3077 && DERIVED_FROM_P (type, optype))
3079 *empty_base = true;
3080 return op;
3082 /* *(foo *)&struct_with_foo_field => COMPONENT_REF */
3083 else if (RECORD_OR_UNION_TYPE_P (optype))
3085 tree field = TYPE_FIELDS (optype);
3086 for (; field; field = DECL_CHAIN (field))
3087 if (TREE_CODE (field) == FIELD_DECL
3088 && TREE_TYPE (field) != error_mark_node
3089 && integer_zerop (byte_position (field))
3090 && (same_type_ignoring_top_level_qualifiers_p
3091 (TREE_TYPE (field), type)))
3092 return fold_build3 (COMPONENT_REF, type, op, field, NULL_TREE);
3095 else if (TREE_CODE (sub) == POINTER_PLUS_EXPR
3096 && TREE_CODE (TREE_OPERAND (sub, 1)) == INTEGER_CST)
3098 tree op00 = TREE_OPERAND (sub, 0);
3099 tree op01 = TREE_OPERAND (sub, 1);
3101 STRIP_NOPS (op00);
3102 if (TREE_CODE (op00) == ADDR_EXPR)
3104 tree op00type;
3105 op00 = TREE_OPERAND (op00, 0);
3106 op00type = TREE_TYPE (op00);
3108 /* ((foo*)&vectorfoo)[1] => BIT_FIELD_REF<vectorfoo,...> */
3109 if (VECTOR_TYPE_P (op00type)
3110 && (same_type_ignoring_top_level_qualifiers_p
3111 (type, TREE_TYPE (op00type))))
3113 HOST_WIDE_INT offset = tree_to_shwi (op01);
3114 tree part_width = TYPE_SIZE (type);
3115 unsigned HOST_WIDE_INT part_widthi = tree_to_shwi (part_width)/BITS_PER_UNIT;
3116 unsigned HOST_WIDE_INT indexi = offset * BITS_PER_UNIT;
3117 tree index = bitsize_int (indexi);
3119 if (offset / part_widthi < TYPE_VECTOR_SUBPARTS (op00type))
3120 return fold_build3_loc (loc,
3121 BIT_FIELD_REF, type, op00,
3122 part_width, index);
3125 /* ((foo*)&complexfoo)[1] => __imag__ complexfoo */
3126 else if (TREE_CODE (op00type) == COMPLEX_TYPE
3127 && (same_type_ignoring_top_level_qualifiers_p
3128 (type, TREE_TYPE (op00type))))
3130 tree size = TYPE_SIZE_UNIT (type);
3131 if (tree_int_cst_equal (size, op01))
3132 return fold_build1_loc (loc, IMAGPART_EXPR, type, op00);
3134 /* ((foo *)&fooarray)[1] => fooarray[1] */
3135 else if (TREE_CODE (op00type) == ARRAY_TYPE
3136 && (same_type_ignoring_top_level_qualifiers_p
3137 (type, TREE_TYPE (op00type))))
3139 tree type_domain = TYPE_DOMAIN (op00type);
3140 tree min_val = size_zero_node;
3141 if (type_domain && TYPE_MIN_VALUE (type_domain))
3142 min_val = TYPE_MIN_VALUE (type_domain);
3143 op01 = size_binop_loc (loc, EXACT_DIV_EXPR, op01,
3144 TYPE_SIZE_UNIT (type));
3145 op01 = size_binop_loc (loc, PLUS_EXPR, op01, min_val);
3146 return build4_loc (loc, ARRAY_REF, type, op00, op01,
3147 NULL_TREE, NULL_TREE);
3149 /* Also handle conversion to an empty base class, which
3150 is represented with a NOP_EXPR. */
3151 else if (is_empty_class (type)
3152 && CLASS_TYPE_P (op00type)
3153 && DERIVED_FROM_P (type, op00type))
3155 *empty_base = true;
3156 return op00;
3158 /* ((foo *)&struct_with_foo_field)[1] => COMPONENT_REF */
3159 else if (RECORD_OR_UNION_TYPE_P (op00type))
3161 tree field = TYPE_FIELDS (op00type);
3162 for (; field; field = DECL_CHAIN (field))
3163 if (TREE_CODE (field) == FIELD_DECL
3164 && TREE_TYPE (field) != error_mark_node
3165 && tree_int_cst_equal (byte_position (field), op01)
3166 && (same_type_ignoring_top_level_qualifiers_p
3167 (TREE_TYPE (field), type)))
3168 return fold_build3 (COMPONENT_REF, type, op00,
3169 field, NULL_TREE);
3173 /* *(foo *)fooarrptr => (*fooarrptr)[0] */
3174 else if (TREE_CODE (TREE_TYPE (subtype)) == ARRAY_TYPE
3175 && (same_type_ignoring_top_level_qualifiers_p
3176 (type, TREE_TYPE (TREE_TYPE (subtype)))))
3178 tree type_domain;
3179 tree min_val = size_zero_node;
3180 tree newsub = cxx_fold_indirect_ref (loc, TREE_TYPE (subtype), sub, NULL);
3181 if (newsub)
3182 sub = newsub;
3183 else
3184 sub = build1_loc (loc, INDIRECT_REF, TREE_TYPE (subtype), sub);
3185 type_domain = TYPE_DOMAIN (TREE_TYPE (sub));
3186 if (type_domain && TYPE_MIN_VALUE (type_domain))
3187 min_val = TYPE_MIN_VALUE (type_domain);
3188 return build4_loc (loc, ARRAY_REF, type, sub, min_val, NULL_TREE,
3189 NULL_TREE);
3192 return NULL_TREE;
3195 static tree
3196 cxx_eval_indirect_ref (const constexpr_ctx *ctx, tree t,
3197 bool lval,
3198 bool *non_constant_p, bool *overflow_p)
3200 tree orig_op0 = TREE_OPERAND (t, 0);
3201 bool empty_base = false;
3203 /* We can handle a MEM_REF like an INDIRECT_REF, if MEM_REF's second
3204 operand is an integer-zero. Otherwise reject the MEM_REF for now. */
3206 if (TREE_CODE (t) == MEM_REF
3207 && (!TREE_OPERAND (t, 1) || !integer_zerop (TREE_OPERAND (t, 1))))
3209 gcc_assert (ctx->quiet);
3210 *non_constant_p = true;
3211 return t;
3214 /* First try to simplify it directly. */
3215 tree r = cxx_fold_indirect_ref (EXPR_LOCATION (t), TREE_TYPE (t), orig_op0,
3216 &empty_base);
3217 if (!r)
3219 /* If that didn't work, evaluate the operand first. */
3220 tree op0 = cxx_eval_constant_expression (ctx, orig_op0,
3221 /*lval*/false, non_constant_p,
3222 overflow_p);
3223 /* Don't VERIFY_CONSTANT here. */
3224 if (*non_constant_p)
3225 return t;
3227 if (!lval && integer_zerop (op0))
3229 if (!ctx->quiet)
3230 error ("dereferencing a null pointer");
3231 *non_constant_p = true;
3232 return t;
3235 r = cxx_fold_indirect_ref (EXPR_LOCATION (t), TREE_TYPE (t), op0,
3236 &empty_base);
3237 if (r == NULL_TREE)
3239 /* We couldn't fold to a constant value. Make sure it's not
3240 something we should have been able to fold. */
3241 tree sub = op0;
3242 STRIP_NOPS (sub);
3243 if (TREE_CODE (sub) == ADDR_EXPR)
3245 gcc_assert (!same_type_ignoring_top_level_qualifiers_p
3246 (TREE_TYPE (TREE_TYPE (sub)), TREE_TYPE (t)));
3247 /* DR 1188 says we don't have to deal with this. */
3248 if (!ctx->quiet)
3249 error ("accessing value of %qE through a %qT glvalue in a "
3250 "constant expression", build_fold_indirect_ref (sub),
3251 TREE_TYPE (t));
3252 *non_constant_p = true;
3253 return t;
3256 if (lval && op0 != orig_op0)
3257 return build1 (INDIRECT_REF, TREE_TYPE (t), op0);
3258 if (!lval)
3259 VERIFY_CONSTANT (t);
3260 return t;
3264 r = cxx_eval_constant_expression (ctx, r,
3265 lval, non_constant_p, overflow_p);
3266 if (*non_constant_p)
3267 return t;
3269 /* If we're pulling out the value of an empty base, just return an empty
3270 CONSTRUCTOR. */
3271 if (empty_base && !lval)
3273 r = build_constructor (TREE_TYPE (t), NULL);
3274 TREE_CONSTANT (r) = true;
3277 return r;
3280 /* Complain about R, a VAR_DECL, not being usable in a constant expression.
3281 Shared between potential_constant_expression and
3282 cxx_eval_constant_expression. */
3284 static void
3285 non_const_var_error (tree r)
3287 tree type = TREE_TYPE (r);
3288 error ("the value of %qD is not usable in a constant "
3289 "expression", r);
3290 /* Avoid error cascade. */
3291 if (DECL_INITIAL (r) == error_mark_node)
3292 return;
3293 if (DECL_DECLARED_CONSTEXPR_P (r))
3294 inform (DECL_SOURCE_LOCATION (r),
3295 "%qD used in its own initializer", r);
3296 else if (INTEGRAL_OR_ENUMERATION_TYPE_P (type))
3298 if (!CP_TYPE_CONST_P (type))
3299 inform (DECL_SOURCE_LOCATION (r),
3300 "%q#D is not const", r);
3301 else if (CP_TYPE_VOLATILE_P (type))
3302 inform (DECL_SOURCE_LOCATION (r),
3303 "%q#D is volatile", r);
3304 else if (!DECL_INITIAL (r)
3305 || !TREE_CONSTANT (DECL_INITIAL (r))
3306 || !DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (r))
3307 inform (DECL_SOURCE_LOCATION (r),
3308 "%qD was not initialized with a constant "
3309 "expression", r);
3310 else
3311 gcc_unreachable ();
3313 else if (TREE_CODE (type) == REFERENCE_TYPE)
3314 inform (DECL_SOURCE_LOCATION (r),
3315 "%qD was not initialized with a constant "
3316 "expression", r);
3317 else
3319 if (cxx_dialect >= cxx11 && !DECL_DECLARED_CONSTEXPR_P (r))
3320 inform (DECL_SOURCE_LOCATION (r),
3321 "%qD was not declared %<constexpr%>", r);
3322 else
3323 inform (DECL_SOURCE_LOCATION (r),
3324 "%qD does not have integral or enumeration type",
3329 /* Subroutine of cxx_eval_constant_expression.
3330 Like cxx_eval_unary_expression, except for trinary expressions. */
3332 static tree
3333 cxx_eval_trinary_expression (const constexpr_ctx *ctx, tree t,
3334 bool lval,
3335 bool *non_constant_p, bool *overflow_p)
3337 int i;
3338 tree args[3];
3339 tree val;
3341 for (i = 0; i < 3; i++)
3343 args[i] = cxx_eval_constant_expression (ctx, TREE_OPERAND (t, i),
3344 lval,
3345 non_constant_p, overflow_p);
3346 VERIFY_CONSTANT (args[i]);
3349 val = fold_ternary_loc (EXPR_LOCATION (t), TREE_CODE (t), TREE_TYPE (t),
3350 args[0], args[1], args[2]);
3351 if (val == NULL_TREE)
3352 return t;
3353 VERIFY_CONSTANT (val);
3354 return val;
3357 /* True if T was declared in a function declared to be constexpr, and
3358 therefore potentially constant in C++14. */
3360 bool
3361 var_in_constexpr_fn (tree t)
3363 tree ctx = DECL_CONTEXT (t);
3364 return (ctx && TREE_CODE (ctx) == FUNCTION_DECL
3365 && DECL_DECLARED_CONSTEXPR_P (ctx));
3368 /* True if T was declared in a function that might be constexpr: either a
3369 function that was declared constexpr, or a C++17 lambda op(). */
3371 bool
3372 var_in_maybe_constexpr_fn (tree t)
3374 if (cxx_dialect >= cxx17
3375 && DECL_FUNCTION_SCOPE_P (t)
3376 && LAMBDA_FUNCTION_P (DECL_CONTEXT (t)))
3377 return true;
3378 return var_in_constexpr_fn (t);
3381 /* We're assigning INIT to TARGET. In do_build_copy_constructor and
3382 build_over_call we implement trivial copy of a class with tail padding using
3383 assignment of character arrays, which is valid in normal code, but not in
3384 constexpr evaluation. We don't need to worry about clobbering tail padding
3385 in constexpr evaluation, so strip the type punning. */
3387 static void
3388 maybe_simplify_trivial_copy (tree &target, tree &init)
3390 if (TREE_CODE (target) == MEM_REF
3391 && TREE_CODE (init) == MEM_REF
3392 && TREE_TYPE (target) == TREE_TYPE (init)
3393 && TREE_CODE (TREE_TYPE (target)) == ARRAY_TYPE
3394 && TREE_TYPE (TREE_TYPE (target)) == unsigned_char_type_node)
3396 target = build_fold_indirect_ref (TREE_OPERAND (target, 0));
3397 init = build_fold_indirect_ref (TREE_OPERAND (init, 0));
3401 /* Evaluate an INIT_EXPR or MODIFY_EXPR. */
3403 static tree
3404 cxx_eval_store_expression (const constexpr_ctx *ctx, tree t,
3405 bool lval,
3406 bool *non_constant_p, bool *overflow_p)
3408 constexpr_ctx new_ctx = *ctx;
3410 tree init = TREE_OPERAND (t, 1);
3411 if (TREE_CLOBBER_P (init))
3412 /* Just ignore clobbers. */
3413 return void_node;
3415 /* First we figure out where we're storing to. */
3416 tree target = TREE_OPERAND (t, 0);
3418 maybe_simplify_trivial_copy (target, init);
3420 tree type = TREE_TYPE (target);
3421 target = cxx_eval_constant_expression (ctx, target,
3422 true,
3423 non_constant_p, overflow_p);
3424 if (*non_constant_p)
3425 return t;
3427 /* cxx_eval_array_reference for lval = true allows references one past
3428 end of array, because it does not know if it is just taking address
3429 (which is valid), or actual dereference. Here we know it is
3430 a dereference, so diagnose it here. */
3431 for (tree probe = target; probe; )
3433 switch (TREE_CODE (probe))
3435 case ARRAY_REF:
3436 tree nelts, ary;
3437 ary = TREE_OPERAND (probe, 0);
3438 if (TREE_CODE (TREE_TYPE (ary)) == ARRAY_TYPE)
3439 nelts = array_type_nelts_top (TREE_TYPE (ary));
3440 else if (VECTOR_TYPE_P (TREE_TYPE (ary)))
3441 nelts = size_int (TYPE_VECTOR_SUBPARTS (TREE_TYPE (ary)));
3442 else
3443 gcc_unreachable ();
3444 nelts = cxx_eval_constant_expression (ctx, nelts, false,
3445 non_constant_p, overflow_p);
3446 VERIFY_CONSTANT (nelts);
3447 gcc_assert (TREE_CODE (nelts) == INTEGER_CST
3448 && TREE_CODE (TREE_OPERAND (probe, 1)) == INTEGER_CST);
3449 if (wi::to_widest (TREE_OPERAND (probe, 1)) == wi::to_widest (nelts))
3451 diag_array_subscript (ctx, ary, TREE_OPERAND (probe, 1));
3452 *non_constant_p = true;
3453 return t;
3455 /* FALLTHRU */
3457 case BIT_FIELD_REF:
3458 case COMPONENT_REF:
3459 probe = TREE_OPERAND (probe, 0);
3460 continue;
3462 default:
3463 probe = NULL_TREE;
3464 continue;
3468 if (!same_type_ignoring_top_level_qualifiers_p (TREE_TYPE (target), type))
3470 /* For initialization of an empty base, the original target will be
3471 *(base*)this, which the above evaluation resolves to the object
3472 argument, which has the derived type rather than the base type. In
3473 this situation, just evaluate the initializer and return, since
3474 there's no actual data to store. */
3475 gcc_assert (is_empty_class (type));
3476 return cxx_eval_constant_expression (ctx, init, false,
3477 non_constant_p, overflow_p);
3480 /* And then find the underlying variable. */
3481 vec<tree,va_gc> *refs = make_tree_vector();
3482 tree object = NULL_TREE;
3483 for (tree probe = target; object == NULL_TREE; )
3485 switch (TREE_CODE (probe))
3487 case BIT_FIELD_REF:
3488 case COMPONENT_REF:
3489 case ARRAY_REF:
3490 vec_safe_push (refs, TREE_OPERAND (probe, 1));
3491 vec_safe_push (refs, TREE_TYPE (probe));
3492 probe = TREE_OPERAND (probe, 0);
3493 break;
3495 default:
3496 object = probe;
3500 /* And then find/build up our initializer for the path to the subobject
3501 we're initializing. */
3502 tree *valp;
3503 if (object == ctx->object && VAR_P (object)
3504 && DECL_NAME (object) && ctx->call == NULL)
3505 /* The variable we're building up an aggregate initializer for is outside
3506 the constant-expression, so don't evaluate the store. We check
3507 DECL_NAME to handle TARGET_EXPR temporaries, which are fair game. */
3508 valp = NULL;
3509 else if (DECL_P (object))
3510 valp = ctx->values->get (object);
3511 else
3512 valp = NULL;
3513 if (!valp)
3515 /* A constant-expression cannot modify objects from outside the
3516 constant-expression. */
3517 if (!ctx->quiet)
3518 error ("modification of %qE is not a constant expression", object);
3519 *non_constant_p = true;
3520 return t;
3522 type = TREE_TYPE (object);
3523 bool no_zero_init = true;
3525 vec<tree,va_gc> *ctors = make_tree_vector ();
3526 while (!refs->is_empty())
3528 if (*valp == NULL_TREE)
3530 *valp = build_constructor (type, NULL);
3531 CONSTRUCTOR_NO_IMPLICIT_ZERO (*valp) = no_zero_init;
3533 else if (TREE_CODE (*valp) == STRING_CST)
3535 /* An array was initialized with a string constant, and now
3536 we're writing into one of its elements. Explode the
3537 single initialization into a set of element
3538 initializations. */
3539 gcc_assert (TREE_CODE (type) == ARRAY_TYPE);
3541 tree string = *valp;
3542 tree elt_type = TREE_TYPE (type);
3543 unsigned chars_per_elt = (TYPE_PRECISION (elt_type)
3544 / TYPE_PRECISION (char_type_node));
3545 unsigned num_elts = TREE_STRING_LENGTH (string) / chars_per_elt;
3546 tree ary_ctor = build_constructor (type, NULL);
3548 vec_safe_reserve (CONSTRUCTOR_ELTS (ary_ctor), num_elts);
3549 for (unsigned ix = 0; ix != num_elts; ix++)
3551 constructor_elt elt =
3553 build_int_cst (size_type_node, ix),
3554 extract_string_elt (string, chars_per_elt, ix)
3556 CONSTRUCTOR_ELTS (ary_ctor)->quick_push (elt);
3559 *valp = ary_ctor;
3562 /* If the value of object is already zero-initialized, any new ctors for
3563 subobjects will also be zero-initialized. */
3564 no_zero_init = CONSTRUCTOR_NO_IMPLICIT_ZERO (*valp);
3566 vec_safe_push (ctors, *valp);
3568 enum tree_code code = TREE_CODE (type);
3569 type = refs->pop();
3570 tree index = refs->pop();
3572 constructor_elt *cep = NULL;
3573 if (code == ARRAY_TYPE)
3575 HOST_WIDE_INT i
3576 = find_array_ctor_elt (*valp, index, /*insert*/true);
3577 gcc_assert (i >= 0);
3578 cep = CONSTRUCTOR_ELT (*valp, i);
3579 gcc_assert (TREE_CODE (cep->index) != RANGE_EXPR);
3581 else
3583 gcc_assert (TREE_CODE (index) == FIELD_DECL);
3585 /* We must keep the CONSTRUCTOR's ELTS in FIELD order.
3586 Usually we meet initializers in that order, but it is
3587 possible for base types to be placed not in program
3588 order. */
3589 tree fields = TYPE_FIELDS (DECL_CONTEXT (index));
3590 unsigned HOST_WIDE_INT idx;
3592 if (code == UNION_TYPE && CONSTRUCTOR_NELTS (*valp)
3593 && CONSTRUCTOR_ELT (*valp, 0)->index != index)
3594 /* Changing active member. */
3595 vec_safe_truncate (CONSTRUCTOR_ELTS (*valp), 0);
3597 for (idx = 0;
3598 vec_safe_iterate (CONSTRUCTOR_ELTS (*valp), idx, &cep);
3599 idx++, fields = DECL_CHAIN (fields))
3601 if (index == cep->index)
3602 goto found;
3604 /* The field we're initializing must be on the field
3605 list. Look to see if it is present before the
3606 field the current ELT initializes. */
3607 for (; fields != cep->index; fields = DECL_CHAIN (fields))
3608 if (index == fields)
3609 goto insert;
3612 /* We fell off the end of the CONSTRUCTOR, so insert a new
3613 entry at the end. */
3614 insert:
3616 constructor_elt ce = { index, NULL_TREE };
3618 vec_safe_insert (CONSTRUCTOR_ELTS (*valp), idx, ce);
3619 cep = CONSTRUCTOR_ELT (*valp, idx);
3621 found:;
3623 valp = &cep->value;
3625 release_tree_vector (refs);
3627 if (AGGREGATE_TYPE_P (type) || VECTOR_TYPE_P (type))
3629 /* Create a new CONSTRUCTOR in case evaluation of the initializer
3630 wants to modify it. */
3631 if (*valp == NULL_TREE)
3633 *valp = build_constructor (type, NULL);
3634 CONSTRUCTOR_NO_IMPLICIT_ZERO (*valp) = no_zero_init;
3636 else if (TREE_CODE (*valp) == PTRMEM_CST)
3637 *valp = cplus_expand_constant (*valp);
3638 new_ctx.ctor = *valp;
3639 new_ctx.object = target;
3642 init = cxx_eval_constant_expression (&new_ctx, init, false,
3643 non_constant_p, overflow_p);
3644 /* Don't share a CONSTRUCTOR that might be changed later. */
3645 init = unshare_constructor (init);
3646 if (target == object)
3647 /* The hash table might have moved since the get earlier. */
3648 valp = ctx->values->get (object);
3650 if (TREE_CODE (init) == CONSTRUCTOR)
3652 /* An outer ctx->ctor might be pointing to *valp, so replace
3653 its contents. */
3654 CONSTRUCTOR_ELTS (*valp) = CONSTRUCTOR_ELTS (init);
3655 TREE_CONSTANT (*valp) = TREE_CONSTANT (init);
3656 TREE_SIDE_EFFECTS (*valp) = TREE_SIDE_EFFECTS (init);
3657 CONSTRUCTOR_NO_IMPLICIT_ZERO (*valp)
3658 = CONSTRUCTOR_NO_IMPLICIT_ZERO (init);
3660 else
3661 *valp = init;
3663 /* Update TREE_CONSTANT and TREE_SIDE_EFFECTS on enclosing
3664 CONSTRUCTORs, if any. */
3665 tree elt;
3666 unsigned i;
3667 bool c = TREE_CONSTANT (init);
3668 bool s = TREE_SIDE_EFFECTS (init);
3669 if (!c || s)
3670 FOR_EACH_VEC_SAFE_ELT (ctors, i, elt)
3672 if (!c)
3673 TREE_CONSTANT (elt) = false;
3674 if (s)
3675 TREE_SIDE_EFFECTS (elt) = true;
3677 release_tree_vector (ctors);
3679 if (*non_constant_p)
3680 return t;
3681 else if (lval)
3682 return target;
3683 else
3684 return init;
3687 /* Evaluate a ++ or -- expression. */
3689 static tree
3690 cxx_eval_increment_expression (const constexpr_ctx *ctx, tree t,
3691 bool lval,
3692 bool *non_constant_p, bool *overflow_p)
3694 enum tree_code code = TREE_CODE (t);
3695 tree type = TREE_TYPE (t);
3696 tree op = TREE_OPERAND (t, 0);
3697 tree offset = TREE_OPERAND (t, 1);
3698 gcc_assert (TREE_CONSTANT (offset));
3700 /* The operand as an lvalue. */
3701 op = cxx_eval_constant_expression (ctx, op, true,
3702 non_constant_p, overflow_p);
3704 /* The operand as an rvalue. */
3705 tree val
3706 = cxx_eval_constant_expression (ctx, op, false,
3707 non_constant_p, overflow_p);
3708 /* Don't VERIFY_CONSTANT if this might be dealing with a pointer to
3709 a local array in a constexpr function. */
3710 bool ptr = POINTER_TYPE_P (TREE_TYPE (val));
3711 if (!ptr)
3712 VERIFY_CONSTANT (val);
3714 /* The modified value. */
3715 bool inc = (code == PREINCREMENT_EXPR || code == POSTINCREMENT_EXPR);
3716 tree mod;
3717 if (POINTER_TYPE_P (type))
3719 /* The middle end requires pointers to use POINTER_PLUS_EXPR. */
3720 offset = convert_to_ptrofftype (offset);
3721 if (!inc)
3722 offset = fold_build1 (NEGATE_EXPR, TREE_TYPE (offset), offset);
3723 mod = fold_build2 (POINTER_PLUS_EXPR, type, val, offset);
3725 else
3726 mod = fold_build2 (inc ? PLUS_EXPR : MINUS_EXPR, type, val, offset);
3727 if (!ptr)
3728 VERIFY_CONSTANT (mod);
3730 /* Storing the modified value. */
3731 tree store = build2 (MODIFY_EXPR, type, op, mod);
3732 cxx_eval_constant_expression (ctx, store,
3733 true, non_constant_p, overflow_p);
3735 /* And the value of the expression. */
3736 if (code == PREINCREMENT_EXPR || code == PREDECREMENT_EXPR)
3738 /* Prefix ops are lvalues. */
3739 if (lval)
3740 return op;
3741 else
3742 /* But we optimize when the caller wants an rvalue. */
3743 return mod;
3745 else
3746 /* Postfix ops are rvalues. */
3747 return val;
3750 /* Predicates for the meaning of *jump_target. */
3752 static bool
3753 returns (tree *jump_target)
3755 return *jump_target
3756 && (TREE_CODE (*jump_target) == RETURN_EXPR
3757 || (TREE_CODE (*jump_target) == LABEL_DECL
3758 && LABEL_DECL_CDTOR (*jump_target)));
3761 static bool
3762 breaks (tree *jump_target)
3764 return *jump_target
3765 && ((TREE_CODE (*jump_target) == LABEL_DECL
3766 && LABEL_DECL_BREAK (*jump_target))
3767 || TREE_CODE (*jump_target) == EXIT_EXPR);
3770 static bool
3771 continues (tree *jump_target)
3773 return *jump_target
3774 && TREE_CODE (*jump_target) == LABEL_DECL
3775 && LABEL_DECL_CONTINUE (*jump_target);
3778 static bool
3779 switches (tree *jump_target)
3781 return *jump_target
3782 && TREE_CODE (*jump_target) == INTEGER_CST;
3785 /* Subroutine of cxx_eval_statement_list. Determine whether the statement
3786 STMT matches *jump_target. If we're looking for a case label and we see
3787 the default label, note it in ctx->css_state. */
3789 static bool
3790 label_matches (const constexpr_ctx *ctx, tree *jump_target, tree stmt)
3792 switch (TREE_CODE (*jump_target))
3794 case LABEL_DECL:
3795 if (TREE_CODE (stmt) == LABEL_EXPR
3796 && LABEL_EXPR_LABEL (stmt) == *jump_target)
3797 return true;
3798 break;
3800 case INTEGER_CST:
3801 if (TREE_CODE (stmt) == CASE_LABEL_EXPR)
3803 gcc_assert (ctx->css_state != NULL);
3804 if (!CASE_LOW (stmt))
3806 /* default: should appear just once in a SWITCH_EXPR
3807 body (excluding nested SWITCH_EXPR). */
3808 gcc_assert (*ctx->css_state != css_default_seen);
3809 /* When evaluating SWITCH_EXPR body for the second time,
3810 return true for the default: label. */
3811 if (*ctx->css_state == css_default_processing)
3812 return true;
3813 *ctx->css_state = css_default_seen;
3815 else if (CASE_HIGH (stmt))
3817 if (tree_int_cst_le (CASE_LOW (stmt), *jump_target)
3818 && tree_int_cst_le (*jump_target, CASE_HIGH (stmt)))
3819 return true;
3821 else if (tree_int_cst_equal (*jump_target, CASE_LOW (stmt)))
3822 return true;
3824 break;
3826 default:
3827 gcc_unreachable ();
3829 return false;
3832 /* Evaluate a STATEMENT_LIST for side-effects. Handles various jump
3833 semantics, for switch, break, continue, and return. */
3835 static tree
3836 cxx_eval_statement_list (const constexpr_ctx *ctx, tree t,
3837 bool *non_constant_p, bool *overflow_p,
3838 tree *jump_target)
3840 tree_stmt_iterator i;
3841 tree local_target;
3842 /* In a statement-expression we want to return the last value.
3843 For empty statement expression return void_node. */
3844 tree r = void_node;
3845 if (!jump_target)
3847 local_target = NULL_TREE;
3848 jump_target = &local_target;
3850 for (i = tsi_start (t); !tsi_end_p (i); tsi_next (&i))
3852 tree stmt = tsi_stmt (i);
3853 r = cxx_eval_constant_expression (ctx, stmt, false,
3854 non_constant_p, overflow_p,
3855 jump_target);
3856 if (*non_constant_p)
3857 break;
3858 if (returns (jump_target) || breaks (jump_target))
3859 break;
3861 /* Make sure we don't use the "result" of a debug-only marker. That
3862 would be wrong. We should be using the result of the previous
3863 statement, or NULL if there isn't one. In practice, this should
3864 never happen: the statement after the marker should override the
3865 result of the marker, so its value shouldn't survive in R. Now,
3866 should that ever change, we'll need some fixing here to stop
3867 markers from modifying the generated executable code. */
3868 gcc_checking_assert (!r || TREE_CODE (r) != DEBUG_BEGIN_STMT);
3869 return r;
3872 /* Evaluate a LOOP_EXPR for side-effects. Handles break and return
3873 semantics; continue semantics are covered by cxx_eval_statement_list. */
3875 static tree
3876 cxx_eval_loop_expr (const constexpr_ctx *ctx, tree t,
3877 bool *non_constant_p, bool *overflow_p,
3878 tree *jump_target)
3880 constexpr_ctx new_ctx = *ctx;
3882 tree body = TREE_OPERAND (t, 0);
3883 int count = 0;
3886 hash_set<tree> save_exprs;
3887 new_ctx.save_exprs = &save_exprs;
3889 cxx_eval_constant_expression (&new_ctx, body, /*lval*/false,
3890 non_constant_p, overflow_p, jump_target);
3892 /* Forget saved values of SAVE_EXPRs. */
3893 for (hash_set<tree>::iterator iter = save_exprs.begin();
3894 iter != save_exprs.end(); ++iter)
3895 new_ctx.values->remove (*iter);
3896 if (++count >= constexpr_loop_limit)
3898 if (!ctx->quiet)
3899 error_at (EXPR_LOC_OR_LOC (t, input_location),
3900 "%<constexpr%> loop iteration count exceeds limit of %d "
3901 "(use -fconstexpr-loop-limit= to increase the limit)",
3902 constexpr_loop_limit);
3903 *non_constant_p = true;
3904 break;
3907 while (!returns (jump_target)
3908 && !breaks (jump_target)
3909 && !switches (jump_target)
3910 && !*non_constant_p);
3912 if (breaks (jump_target))
3913 *jump_target = NULL_TREE;
3915 return NULL_TREE;
3918 /* Evaluate a SWITCH_EXPR for side-effects. Handles switch and break jump
3919 semantics. */
3921 static tree
3922 cxx_eval_switch_expr (const constexpr_ctx *ctx, tree t,
3923 bool *non_constant_p, bool *overflow_p,
3924 tree *jump_target)
3926 tree cond = TREE_OPERAND (t, 0);
3927 cond = cxx_eval_constant_expression (ctx, cond, false,
3928 non_constant_p, overflow_p);
3929 VERIFY_CONSTANT (cond);
3930 *jump_target = cond;
3932 tree body = TREE_OPERAND (t, 1);
3933 constexpr_ctx new_ctx = *ctx;
3934 constexpr_switch_state css = css_default_not_seen;
3935 new_ctx.css_state = &css;
3936 cxx_eval_constant_expression (&new_ctx, body, false,
3937 non_constant_p, overflow_p, jump_target);
3938 if (switches (jump_target) && css == css_default_seen)
3940 /* If the SWITCH_EXPR body has default: label, process it once again,
3941 this time instructing label_matches to return true for default:
3942 label on switches (jump_target). */
3943 css = css_default_processing;
3944 cxx_eval_constant_expression (&new_ctx, body, false,
3945 non_constant_p, overflow_p, jump_target);
3947 if (breaks (jump_target) || switches (jump_target))
3948 *jump_target = NULL_TREE;
3949 return NULL_TREE;
3952 /* Find the object of TYPE under initialization in CTX. */
3954 static tree
3955 lookup_placeholder (const constexpr_ctx *ctx, bool lval, tree type)
3957 if (!ctx)
3958 return NULL_TREE;
3960 /* We could use ctx->object unconditionally, but using ctx->ctor when we
3961 can is a minor optimization. */
3962 if (!lval && ctx->ctor && same_type_p (TREE_TYPE (ctx->ctor), type))
3963 return ctx->ctor;
3965 if (!ctx->object)
3966 return NULL_TREE;
3968 /* Since an object cannot have a field of its own type, we can search outward
3969 from ctx->object to find the unique containing object of TYPE. */
3970 tree ob = ctx->object;
3971 while (ob)
3973 if (same_type_ignoring_top_level_qualifiers_p (TREE_TYPE (ob), type))
3974 break;
3975 if (handled_component_p (ob))
3976 ob = TREE_OPERAND (ob, 0);
3977 else
3978 ob = NULL_TREE;
3981 return ob;
3984 /* Attempt to reduce the expression T to a constant value.
3985 On failure, issue diagnostic and return error_mark_node. */
3986 /* FIXME unify with c_fully_fold */
3987 /* FIXME overflow_p is too global */
3989 static tree
3990 cxx_eval_constant_expression (const constexpr_ctx *ctx, tree t,
3991 bool lval,
3992 bool *non_constant_p, bool *overflow_p,
3993 tree *jump_target)
3995 constexpr_ctx new_ctx;
3996 tree r = t;
3998 if (jump_target && *jump_target)
4000 /* If we are jumping, ignore all statements/expressions except those
4001 that could have LABEL_EXPR or CASE_LABEL_EXPR in their bodies. */
4002 switch (TREE_CODE (t))
4004 case BIND_EXPR:
4005 case STATEMENT_LIST:
4006 case LOOP_EXPR:
4007 case COND_EXPR:
4008 break;
4009 case LABEL_EXPR:
4010 case CASE_LABEL_EXPR:
4011 if (label_matches (ctx, jump_target, t))
4012 /* Found it. */
4013 *jump_target = NULL_TREE;
4014 return NULL_TREE;
4015 default:
4016 return NULL_TREE;
4019 if (t == error_mark_node)
4021 *non_constant_p = true;
4022 return t;
4024 if (CONSTANT_CLASS_P (t))
4026 if (TREE_OVERFLOW (t))
4028 if (!ctx->quiet)
4029 permerror (input_location, "overflow in constant expression");
4030 if (!flag_permissive || ctx->quiet)
4031 *overflow_p = true;
4034 if (TREE_CODE (t) == INTEGER_CST
4035 && TREE_CODE (TREE_TYPE (t)) == POINTER_TYPE
4036 && !integer_zerop (t))
4038 if (!ctx->quiet)
4039 error ("value %qE of type %qT is not a constant expression",
4040 t, TREE_TYPE (t));
4041 *non_constant_p = true;
4044 return t;
4047 tree_code tcode = TREE_CODE (t);
4048 switch (tcode)
4050 case RESULT_DECL:
4051 if (lval)
4052 return t;
4053 /* We ask for an rvalue for the RESULT_DECL when indirecting
4054 through an invisible reference, or in named return value
4055 optimization. */
4056 return (*ctx->values->get (t));
4058 case VAR_DECL:
4059 if (DECL_HAS_VALUE_EXPR_P (t))
4060 return cxx_eval_constant_expression (ctx, DECL_VALUE_EXPR (t),
4061 lval, non_constant_p, overflow_p);
4062 /* fall through */
4063 case CONST_DECL:
4064 /* We used to not check lval for CONST_DECL, but darwin.c uses
4065 CONST_DECL for aggregate constants. */
4066 if (lval)
4067 return t;
4068 if (COMPLETE_TYPE_P (TREE_TYPE (t))
4069 && is_really_empty_class (TREE_TYPE (t)))
4071 /* If the class is empty, we aren't actually loading anything. */
4072 r = build_constructor (TREE_TYPE (t), NULL);
4073 TREE_CONSTANT (r) = true;
4075 else if (ctx->strict)
4076 r = decl_really_constant_value (t);
4077 else
4078 r = decl_constant_value (t);
4079 if (TREE_CODE (r) == TARGET_EXPR
4080 && TREE_CODE (TARGET_EXPR_INITIAL (r)) == CONSTRUCTOR)
4081 r = TARGET_EXPR_INITIAL (r);
4082 if (VAR_P (r))
4083 if (tree *p = ctx->values->get (r))
4084 if (*p != NULL_TREE)
4085 r = *p;
4086 if (DECL_P (r))
4088 if (!ctx->quiet)
4089 non_const_var_error (r);
4090 *non_constant_p = true;
4092 break;
4094 case DEBUG_BEGIN_STMT:
4095 /* ??? It might be nice to retain this information somehow, so
4096 as to be able to step into a constexpr function call. */
4097 /* Fall through. */
4099 case FUNCTION_DECL:
4100 case TEMPLATE_DECL:
4101 case LABEL_DECL:
4102 case LABEL_EXPR:
4103 case CASE_LABEL_EXPR:
4104 case PREDICT_EXPR:
4105 return t;
4107 case PARM_DECL:
4108 if (lval && TREE_CODE (TREE_TYPE (t)) != REFERENCE_TYPE)
4109 /* glvalue use. */;
4110 else if (tree *p = ctx->values->get (r))
4111 r = *p;
4112 else if (lval)
4113 /* Defer in case this is only used for its type. */;
4114 else if (TREE_CODE (TREE_TYPE (t)) == REFERENCE_TYPE)
4115 /* Defer, there's no lvalue->rvalue conversion. */;
4116 else if (COMPLETE_TYPE_P (TREE_TYPE (t))
4117 && is_really_empty_class (TREE_TYPE (t)))
4119 /* If the class is empty, we aren't actually loading anything. */
4120 r = build_constructor (TREE_TYPE (t), NULL);
4121 TREE_CONSTANT (r) = true;
4123 else
4125 if (!ctx->quiet)
4126 error ("%qE is not a constant expression", t);
4127 *non_constant_p = true;
4129 break;
4131 case CALL_EXPR:
4132 case AGGR_INIT_EXPR:
4133 r = cxx_eval_call_expression (ctx, t, lval,
4134 non_constant_p, overflow_p);
4135 break;
4137 case DECL_EXPR:
4139 r = DECL_EXPR_DECL (t);
4140 if (AGGREGATE_TYPE_P (TREE_TYPE (r))
4141 || VECTOR_TYPE_P (TREE_TYPE (r)))
4143 new_ctx = *ctx;
4144 new_ctx.object = r;
4145 new_ctx.ctor = build_constructor (TREE_TYPE (r), NULL);
4146 CONSTRUCTOR_NO_IMPLICIT_ZERO (new_ctx.ctor) = true;
4147 new_ctx.values->put (r, new_ctx.ctor);
4148 ctx = &new_ctx;
4151 if (tree init = DECL_INITIAL (r))
4153 init = cxx_eval_constant_expression (ctx, init,
4154 false,
4155 non_constant_p, overflow_p);
4156 /* Don't share a CONSTRUCTOR that might be changed. */
4157 init = unshare_constructor (init);
4158 ctx->values->put (r, init);
4160 else if (ctx == &new_ctx)
4161 /* We gave it a CONSTRUCTOR above. */;
4162 else
4163 ctx->values->put (r, NULL_TREE);
4165 break;
4167 case TARGET_EXPR:
4168 if (!literal_type_p (TREE_TYPE (t)))
4170 if (!ctx->quiet)
4172 error ("temporary of non-literal type %qT in a "
4173 "constant expression", TREE_TYPE (t));
4174 explain_non_literal_class (TREE_TYPE (t));
4176 *non_constant_p = true;
4177 break;
4179 if ((AGGREGATE_TYPE_P (TREE_TYPE (t)) || VECTOR_TYPE_P (TREE_TYPE (t))))
4181 /* We're being expanded without an explicit target, so start
4182 initializing a new object; expansion with an explicit target
4183 strips the TARGET_EXPR before we get here. */
4184 new_ctx = *ctx;
4185 new_ctx.ctor = build_constructor (TREE_TYPE (t), NULL);
4186 CONSTRUCTOR_NO_IMPLICIT_ZERO (new_ctx.ctor) = true;
4187 new_ctx.object = TARGET_EXPR_SLOT (t);
4188 ctx->values->put (new_ctx.object, new_ctx.ctor);
4189 ctx = &new_ctx;
4191 /* Pass false for 'lval' because this indicates
4192 initialization of a temporary. */
4193 r = cxx_eval_constant_expression (ctx, TREE_OPERAND (t, 1),
4194 false,
4195 non_constant_p, overflow_p);
4196 if (!*non_constant_p)
4197 /* Adjust the type of the result to the type of the temporary. */
4198 r = adjust_temp_type (TREE_TYPE (t), r);
4199 if (lval)
4201 tree slot = TARGET_EXPR_SLOT (t);
4202 r = unshare_constructor (r);
4203 ctx->values->put (slot, r);
4204 return slot;
4206 break;
4208 case INIT_EXPR:
4209 case MODIFY_EXPR:
4210 gcc_assert (jump_target == NULL || *jump_target == NULL_TREE);
4211 r = cxx_eval_store_expression (ctx, t, lval,
4212 non_constant_p, overflow_p);
4213 break;
4215 case SCOPE_REF:
4216 r = cxx_eval_constant_expression (ctx, TREE_OPERAND (t, 1),
4217 lval,
4218 non_constant_p, overflow_p);
4219 break;
4221 case RETURN_EXPR:
4222 if (TREE_OPERAND (t, 0) != NULL_TREE)
4223 r = cxx_eval_constant_expression (ctx, TREE_OPERAND (t, 0),
4224 lval,
4225 non_constant_p, overflow_p);
4226 *jump_target = t;
4227 break;
4229 case SAVE_EXPR:
4230 /* Avoid evaluating a SAVE_EXPR more than once. */
4231 if (tree *p = ctx->values->get (t))
4232 r = *p;
4233 else
4235 r = cxx_eval_constant_expression (ctx, TREE_OPERAND (t, 0), false,
4236 non_constant_p, overflow_p);
4237 ctx->values->put (t, r);
4238 if (ctx->save_exprs)
4239 ctx->save_exprs->add (t);
4241 break;
4243 case NON_LVALUE_EXPR:
4244 case TRY_CATCH_EXPR:
4245 case TRY_BLOCK:
4246 case CLEANUP_POINT_EXPR:
4247 case MUST_NOT_THROW_EXPR:
4248 case EXPR_STMT:
4249 case EH_SPEC_BLOCK:
4250 r = cxx_eval_constant_expression (ctx, TREE_OPERAND (t, 0),
4251 lval,
4252 non_constant_p, overflow_p,
4253 jump_target);
4254 break;
4256 case TRY_FINALLY_EXPR:
4257 r = cxx_eval_constant_expression (ctx, TREE_OPERAND (t, 0), lval,
4258 non_constant_p, overflow_p,
4259 jump_target);
4260 if (!*non_constant_p)
4261 /* Also evaluate the cleanup. */
4262 cxx_eval_constant_expression (ctx, TREE_OPERAND (t, 1), true,
4263 non_constant_p, overflow_p,
4264 jump_target);
4265 break;
4267 /* These differ from cxx_eval_unary_expression in that this doesn't
4268 check for a constant operand or result; an address can be
4269 constant without its operand being, and vice versa. */
4270 case MEM_REF:
4271 case INDIRECT_REF:
4272 r = cxx_eval_indirect_ref (ctx, t, lval,
4273 non_constant_p, overflow_p);
4274 break;
4276 case ADDR_EXPR:
4278 tree oldop = TREE_OPERAND (t, 0);
4279 tree op = cxx_eval_constant_expression (ctx, oldop,
4280 /*lval*/true,
4281 non_constant_p, overflow_p);
4282 /* Don't VERIFY_CONSTANT here. */
4283 if (*non_constant_p)
4284 return t;
4285 gcc_checking_assert (TREE_CODE (op) != CONSTRUCTOR);
4286 /* This function does more aggressive folding than fold itself. */
4287 r = build_fold_addr_expr_with_type (op, TREE_TYPE (t));
4288 if (TREE_CODE (r) == ADDR_EXPR && TREE_OPERAND (r, 0) == oldop)
4289 return t;
4290 break;
4293 case REALPART_EXPR:
4294 case IMAGPART_EXPR:
4295 if (lval)
4297 r = cxx_eval_constant_expression (ctx, TREE_OPERAND (t, 0), lval,
4298 non_constant_p, overflow_p);
4299 if (r == error_mark_node)
4301 else if (r == TREE_OPERAND (t, 0))
4302 r = t;
4303 else
4304 r = fold_build1 (TREE_CODE (t), TREE_TYPE (t), r);
4305 break;
4307 /* FALLTHRU */
4308 case CONJ_EXPR:
4309 case FIX_TRUNC_EXPR:
4310 case FLOAT_EXPR:
4311 case NEGATE_EXPR:
4312 case ABS_EXPR:
4313 case BIT_NOT_EXPR:
4314 case TRUTH_NOT_EXPR:
4315 case FIXED_CONVERT_EXPR:
4316 r = cxx_eval_unary_expression (ctx, t, lval,
4317 non_constant_p, overflow_p);
4318 break;
4320 case SIZEOF_EXPR:
4321 r = fold_sizeof_expr (t);
4322 VERIFY_CONSTANT (r);
4323 break;
4325 case COMPOUND_EXPR:
4327 /* check_return_expr sometimes wraps a TARGET_EXPR in a
4328 COMPOUND_EXPR; don't get confused. Also handle EMPTY_CLASS_EXPR
4329 introduced by build_call_a. */
4330 tree op0 = TREE_OPERAND (t, 0);
4331 tree op1 = TREE_OPERAND (t, 1);
4332 STRIP_NOPS (op1);
4333 if ((TREE_CODE (op0) == TARGET_EXPR && op1 == TARGET_EXPR_SLOT (op0))
4334 || TREE_CODE (op1) == EMPTY_CLASS_EXPR)
4335 r = cxx_eval_constant_expression (ctx, op0,
4336 lval, non_constant_p, overflow_p,
4337 jump_target);
4338 else
4340 /* Check that the LHS is constant and then discard it. */
4341 cxx_eval_constant_expression (ctx, op0,
4342 true, non_constant_p, overflow_p,
4343 jump_target);
4344 if (*non_constant_p)
4345 return t;
4346 op1 = TREE_OPERAND (t, 1);
4347 r = cxx_eval_constant_expression (ctx, op1,
4348 lval, non_constant_p, overflow_p,
4349 jump_target);
4352 break;
4354 case POINTER_PLUS_EXPR:
4355 case POINTER_DIFF_EXPR:
4356 case PLUS_EXPR:
4357 case MINUS_EXPR:
4358 case MULT_EXPR:
4359 case TRUNC_DIV_EXPR:
4360 case CEIL_DIV_EXPR:
4361 case FLOOR_DIV_EXPR:
4362 case ROUND_DIV_EXPR:
4363 case TRUNC_MOD_EXPR:
4364 case CEIL_MOD_EXPR:
4365 case ROUND_MOD_EXPR:
4366 case RDIV_EXPR:
4367 case EXACT_DIV_EXPR:
4368 case MIN_EXPR:
4369 case MAX_EXPR:
4370 case LSHIFT_EXPR:
4371 case RSHIFT_EXPR:
4372 case LROTATE_EXPR:
4373 case RROTATE_EXPR:
4374 case BIT_IOR_EXPR:
4375 case BIT_XOR_EXPR:
4376 case BIT_AND_EXPR:
4377 case TRUTH_XOR_EXPR:
4378 case LT_EXPR:
4379 case LE_EXPR:
4380 case GT_EXPR:
4381 case GE_EXPR:
4382 case EQ_EXPR:
4383 case NE_EXPR:
4384 case UNORDERED_EXPR:
4385 case ORDERED_EXPR:
4386 case UNLT_EXPR:
4387 case UNLE_EXPR:
4388 case UNGT_EXPR:
4389 case UNGE_EXPR:
4390 case UNEQ_EXPR:
4391 case LTGT_EXPR:
4392 case RANGE_EXPR:
4393 case COMPLEX_EXPR:
4394 r = cxx_eval_binary_expression (ctx, t, lval,
4395 non_constant_p, overflow_p);
4396 break;
4398 /* fold can introduce non-IF versions of these; still treat them as
4399 short-circuiting. */
4400 case TRUTH_AND_EXPR:
4401 case TRUTH_ANDIF_EXPR:
4402 r = cxx_eval_logical_expression (ctx, t, boolean_false_node,
4403 boolean_true_node,
4404 lval,
4405 non_constant_p, overflow_p);
4406 break;
4408 case TRUTH_OR_EXPR:
4409 case TRUTH_ORIF_EXPR:
4410 r = cxx_eval_logical_expression (ctx, t, boolean_true_node,
4411 boolean_false_node,
4412 lval,
4413 non_constant_p, overflow_p);
4414 break;
4416 case ARRAY_REF:
4417 r = cxx_eval_array_reference (ctx, t, lval,
4418 non_constant_p, overflow_p);
4419 break;
4421 case COMPONENT_REF:
4422 if (is_overloaded_fn (t))
4424 /* We can only get here in checking mode via
4425 build_non_dependent_expr, because any expression that
4426 calls or takes the address of the function will have
4427 pulled a FUNCTION_DECL out of the COMPONENT_REF. */
4428 gcc_checking_assert (ctx->quiet || errorcount);
4429 *non_constant_p = true;
4430 return t;
4432 r = cxx_eval_component_reference (ctx, t, lval,
4433 non_constant_p, overflow_p);
4434 break;
4436 case BIT_FIELD_REF:
4437 r = cxx_eval_bit_field_ref (ctx, t, lval,
4438 non_constant_p, overflow_p);
4439 break;
4441 case COND_EXPR:
4442 if (jump_target && *jump_target)
4444 /* When jumping to a label, the label might be either in the
4445 then or else blocks, so process then block first in skipping
4446 mode first, and if we are still in the skipping mode at its end,
4447 process the else block too. */
4448 r = cxx_eval_constant_expression (ctx, TREE_OPERAND (t, 1),
4449 lval, non_constant_p, overflow_p,
4450 jump_target);
4451 if (*jump_target)
4452 r = cxx_eval_constant_expression (ctx, TREE_OPERAND (t, 2),
4453 lval, non_constant_p, overflow_p,
4454 jump_target);
4455 break;
4457 r = cxx_eval_conditional_expression (ctx, t, lval,
4458 non_constant_p, overflow_p,
4459 jump_target);
4460 break;
4461 case VEC_COND_EXPR:
4462 r = cxx_eval_vector_conditional_expression (ctx, t, non_constant_p,
4463 overflow_p);
4464 break;
4466 case CONSTRUCTOR:
4467 if (TREE_CONSTANT (t))
4469 /* Don't re-process a constant CONSTRUCTOR, but do fold it to
4470 VECTOR_CST if applicable. */
4471 /* FIXME after GCC 6 branches, make the verify unconditional. */
4472 if (CHECKING_P)
4473 verify_constructor_flags (t);
4474 else
4475 recompute_constructor_flags (t);
4476 if (TREE_CONSTANT (t))
4477 return fold (t);
4479 r = cxx_eval_bare_aggregate (ctx, t, lval,
4480 non_constant_p, overflow_p);
4481 break;
4483 case VEC_INIT_EXPR:
4484 /* We can get this in a defaulted constructor for a class with a
4485 non-static data member of array type. Either the initializer will
4486 be NULL, meaning default-initialization, or it will be an lvalue
4487 or xvalue of the same type, meaning direct-initialization from the
4488 corresponding member. */
4489 r = cxx_eval_vec_init (ctx, t, lval,
4490 non_constant_p, overflow_p);
4491 break;
4493 case FMA_EXPR:
4494 case VEC_PERM_EXPR:
4495 r = cxx_eval_trinary_expression (ctx, t, lval,
4496 non_constant_p, overflow_p);
4497 break;
4499 case CONVERT_EXPR:
4500 case VIEW_CONVERT_EXPR:
4501 case NOP_EXPR:
4502 case UNARY_PLUS_EXPR:
4504 tree oldop = TREE_OPERAND (t, 0);
4506 tree op = cxx_eval_constant_expression (ctx, oldop,
4507 lval,
4508 non_constant_p, overflow_p);
4509 if (*non_constant_p)
4510 return t;
4511 tree type = TREE_TYPE (t);
4512 if (TREE_CODE (op) == PTRMEM_CST
4513 && !TYPE_PTRMEM_P (type))
4514 op = cplus_expand_constant (op);
4515 if (TREE_CODE (op) == PTRMEM_CST && tcode == NOP_EXPR)
4517 if (same_type_ignoring_top_level_qualifiers_p (type,
4518 TREE_TYPE (op))
4519 || can_convert_qual (type, op))
4520 return cp_fold_convert (type, op);
4521 else
4523 if (!ctx->quiet)
4524 error_at (EXPR_LOC_OR_LOC (t, input_location),
4525 "a reinterpret_cast is not a constant expression");
4526 *non_constant_p = true;
4527 return t;
4531 if (POINTER_TYPE_P (type) && TREE_CODE (op) == INTEGER_CST)
4533 if (integer_zerop (op))
4535 if (TREE_CODE (type) == REFERENCE_TYPE)
4537 if (!ctx->quiet)
4538 error_at (EXPR_LOC_OR_LOC (t, input_location),
4539 "dereferencing a null pointer");
4540 *non_constant_p = true;
4541 return t;
4543 else if (TREE_CODE (TREE_TYPE (op)) == POINTER_TYPE)
4545 tree from = TREE_TYPE (op);
4547 if (!can_convert (type, from, tf_none))
4549 if (!ctx->quiet)
4550 error_at (EXPR_LOC_OR_LOC (t, input_location),
4551 "conversion of %qT null pointer to %qT "
4552 "is not a constant expression",
4553 from, type);
4554 *non_constant_p = true;
4555 return t;
4559 else
4561 /* This detects for example:
4562 reinterpret_cast<void*>(sizeof 0)
4564 if (!ctx->quiet)
4565 error_at (EXPR_LOC_OR_LOC (t, input_location),
4566 "%<reinterpret_cast<%T>(%E)%> is not "
4567 "a constant expression",
4568 type, op);
4569 *non_constant_p = true;
4570 return t;
4573 if (op == oldop && tcode != UNARY_PLUS_EXPR)
4574 /* We didn't fold at the top so we could check for ptr-int
4575 conversion. */
4576 return fold (t);
4577 if (tcode == UNARY_PLUS_EXPR)
4578 r = fold_convert (TREE_TYPE (t), op);
4579 else
4580 r = fold_build1 (tcode, type, op);
4581 /* Conversion of an out-of-range value has implementation-defined
4582 behavior; the language considers it different from arithmetic
4583 overflow, which is undefined. */
4584 if (TREE_OVERFLOW_P (r) && !TREE_OVERFLOW_P (op))
4585 TREE_OVERFLOW (r) = false;
4587 break;
4589 case EMPTY_CLASS_EXPR:
4590 /* This is good enough for a function argument that might not get
4591 used, and they can't do anything with it, so just return it. */
4592 return t;
4594 case STATEMENT_LIST:
4595 new_ctx = *ctx;
4596 new_ctx.ctor = new_ctx.object = NULL_TREE;
4597 return cxx_eval_statement_list (&new_ctx, t,
4598 non_constant_p, overflow_p, jump_target);
4600 case BIND_EXPR:
4601 return cxx_eval_constant_expression (ctx, BIND_EXPR_BODY (t),
4602 lval,
4603 non_constant_p, overflow_p,
4604 jump_target);
4606 case PREINCREMENT_EXPR:
4607 case POSTINCREMENT_EXPR:
4608 case PREDECREMENT_EXPR:
4609 case POSTDECREMENT_EXPR:
4610 return cxx_eval_increment_expression (ctx, t,
4611 lval, non_constant_p, overflow_p);
4613 case LAMBDA_EXPR:
4614 case NEW_EXPR:
4615 case VEC_NEW_EXPR:
4616 case DELETE_EXPR:
4617 case VEC_DELETE_EXPR:
4618 case THROW_EXPR:
4619 case MODOP_EXPR:
4620 /* GCC internal stuff. */
4621 case VA_ARG_EXPR:
4622 case OBJ_TYPE_REF:
4623 case NON_DEPENDENT_EXPR:
4624 case BASELINK:
4625 case OFFSET_REF:
4626 if (!ctx->quiet)
4627 error_at (EXPR_LOC_OR_LOC (t, input_location),
4628 "expression %qE is not a constant expression", t);
4629 *non_constant_p = true;
4630 break;
4632 case PLACEHOLDER_EXPR:
4633 /* Use of the value or address of the current object. */
4634 if (tree ctor = lookup_placeholder (ctx, lval, TREE_TYPE (t)))
4635 return cxx_eval_constant_expression (ctx, ctor, lval,
4636 non_constant_p, overflow_p);
4637 /* A placeholder without a referent. We can get here when
4638 checking whether NSDMIs are noexcept, or in massage_init_elt;
4639 just say it's non-constant for now. */
4640 gcc_assert (ctx->quiet);
4641 *non_constant_p = true;
4642 break;
4644 case EXIT_EXPR:
4646 tree cond = TREE_OPERAND (t, 0);
4647 cond = cxx_eval_constant_expression (ctx, cond, /*lval*/false,
4648 non_constant_p, overflow_p);
4649 VERIFY_CONSTANT (cond);
4650 if (integer_nonzerop (cond))
4651 *jump_target = t;
4653 break;
4655 case GOTO_EXPR:
4656 *jump_target = TREE_OPERAND (t, 0);
4657 gcc_assert (breaks (jump_target) || continues (jump_target)
4658 /* Allow for jumping to a cdtor_label. */
4659 || returns (jump_target));
4660 break;
4662 case LOOP_EXPR:
4663 cxx_eval_loop_expr (ctx, t,
4664 non_constant_p, overflow_p, jump_target);
4665 break;
4667 case SWITCH_EXPR:
4668 cxx_eval_switch_expr (ctx, t,
4669 non_constant_p, overflow_p, jump_target);
4670 break;
4672 case REQUIRES_EXPR:
4673 /* It's possible to get a requires-expression in a constant
4674 expression. For example:
4676 template<typename T> concept bool C() {
4677 return requires (T t) { t; };
4680 template<typename T> requires !C<T>() void f(T);
4682 Normalization leaves f with the associated constraint
4683 '!requires (T t) { ... }' which is not transformed into
4684 a constraint. */
4685 if (!processing_template_decl)
4686 return evaluate_constraint_expression (t, NULL_TREE);
4687 else
4688 *non_constant_p = true;
4689 return t;
4691 case ANNOTATE_EXPR:
4692 gcc_assert (tree_to_uhwi (TREE_OPERAND (t, 1)) == annot_expr_ivdep_kind);
4693 r = cxx_eval_constant_expression (ctx, TREE_OPERAND (t, 0),
4694 lval,
4695 non_constant_p, overflow_p,
4696 jump_target);
4697 break;
4699 default:
4700 if (STATEMENT_CODE_P (TREE_CODE (t)))
4702 /* This function doesn't know how to deal with pre-genericize
4703 statements; this can only happen with statement-expressions,
4704 so for now just fail. */
4705 if (!ctx->quiet)
4706 error_at (EXPR_LOCATION (t),
4707 "statement is not a constant expression");
4709 else
4710 internal_error ("unexpected expression %qE of kind %s", t,
4711 get_tree_code_name (TREE_CODE (t)));
4712 *non_constant_p = true;
4713 break;
4716 if (r == error_mark_node)
4717 *non_constant_p = true;
4719 if (*non_constant_p)
4720 return t;
4721 else
4722 return r;
4725 static tree
4726 cxx_eval_outermost_constant_expr (tree t, bool allow_non_constant,
4727 bool strict = true, tree object = NULL_TREE)
4729 auto_timevar time (TV_CONSTEXPR);
4731 bool non_constant_p = false;
4732 bool overflow_p = false;
4733 hash_map<tree,tree> map;
4735 constexpr_ctx ctx = { NULL, &map, NULL, NULL, NULL, NULL,
4736 allow_non_constant, strict };
4738 tree type = initialized_type (t);
4739 tree r = t;
4740 if (AGGREGATE_TYPE_P (type) || VECTOR_TYPE_P (type))
4742 /* In C++14 an NSDMI can participate in aggregate initialization,
4743 and can refer to the address of the object being initialized, so
4744 we need to pass in the relevant VAR_DECL if we want to do the
4745 evaluation in a single pass. The evaluation will dynamically
4746 update ctx.values for the VAR_DECL. We use the same strategy
4747 for C++11 constexpr constructors that refer to the object being
4748 initialized. */
4749 ctx.ctor = build_constructor (type, NULL);
4750 CONSTRUCTOR_NO_IMPLICIT_ZERO (ctx.ctor) = true;
4751 if (!object)
4753 if (TREE_CODE (t) == TARGET_EXPR)
4754 object = TARGET_EXPR_SLOT (t);
4755 else if (TREE_CODE (t) == AGGR_INIT_EXPR)
4756 object = AGGR_INIT_EXPR_SLOT (t);
4758 ctx.object = object;
4759 if (object)
4760 gcc_assert (same_type_ignoring_top_level_qualifiers_p
4761 (type, TREE_TYPE (object)));
4762 if (object && DECL_P (object))
4763 map.put (object, ctx.ctor);
4764 if (TREE_CODE (r) == TARGET_EXPR)
4765 /* Avoid creating another CONSTRUCTOR when we expand the
4766 TARGET_EXPR. */
4767 r = TARGET_EXPR_INITIAL (r);
4770 r = cxx_eval_constant_expression (&ctx, r,
4771 false, &non_constant_p, &overflow_p);
4773 verify_constant (r, allow_non_constant, &non_constant_p, &overflow_p);
4775 /* Mutable logic is a bit tricky: we want to allow initialization of
4776 constexpr variables with mutable members, but we can't copy those
4777 members to another constexpr variable. */
4778 if (TREE_CODE (r) == CONSTRUCTOR
4779 && CONSTRUCTOR_MUTABLE_POISON (r))
4781 if (!allow_non_constant)
4782 error ("%qE is not a constant expression because it refers to "
4783 "mutable subobjects of %qT", t, type);
4784 non_constant_p = true;
4787 if (TREE_CODE (r) == CONSTRUCTOR
4788 && CONSTRUCTOR_NO_IMPLICIT_ZERO (r))
4790 if (!allow_non_constant)
4791 error ("%qE is not a constant expression because it refers to "
4792 "an incompletely initialized variable", t);
4793 TREE_CONSTANT (r) = false;
4794 non_constant_p = true;
4797 /* Technically we should check this for all subexpressions, but that
4798 runs into problems with our internal representation of pointer
4799 subtraction and the 5.19 rules are still in flux. */
4800 if (CONVERT_EXPR_CODE_P (TREE_CODE (r))
4801 && ARITHMETIC_TYPE_P (TREE_TYPE (r))
4802 && TREE_CODE (TREE_OPERAND (r, 0)) == ADDR_EXPR)
4804 if (!allow_non_constant)
4805 error ("conversion from pointer type %qT "
4806 "to arithmetic type %qT in a constant expression",
4807 TREE_TYPE (TREE_OPERAND (r, 0)), TREE_TYPE (r));
4808 non_constant_p = true;
4811 if (!non_constant_p && overflow_p)
4812 non_constant_p = true;
4814 /* Unshare the result unless it's a CONSTRUCTOR in which case it's already
4815 unshared. */
4816 bool should_unshare = true;
4817 if (r == t || TREE_CODE (r) == CONSTRUCTOR)
4818 should_unshare = false;
4820 if (non_constant_p && !allow_non_constant)
4821 return error_mark_node;
4822 else if (non_constant_p && TREE_CONSTANT (r))
4824 /* This isn't actually constant, so unset TREE_CONSTANT. */
4825 if (EXPR_P (r))
4826 r = copy_node (r);
4827 else if (TREE_CODE (r) == CONSTRUCTOR)
4828 r = build1 (VIEW_CONVERT_EXPR, TREE_TYPE (r), r);
4829 else
4830 r = build_nop (TREE_TYPE (r), r);
4831 TREE_CONSTANT (r) = false;
4833 else if (non_constant_p || r == t)
4834 return t;
4836 if (should_unshare)
4837 r = unshare_expr (r);
4839 if (TREE_CODE (r) == CONSTRUCTOR && CLASS_TYPE_P (TREE_TYPE (r)))
4841 if (TREE_CODE (t) == TARGET_EXPR
4842 && TARGET_EXPR_INITIAL (t) == r)
4843 return t;
4844 else
4846 r = get_target_expr (r);
4847 TREE_CONSTANT (r) = true;
4848 return r;
4851 else
4852 return r;
4855 /* Returns true if T is a valid subexpression of a constant expression,
4856 even if it isn't itself a constant expression. */
4858 bool
4859 is_sub_constant_expr (tree t)
4861 bool non_constant_p = false;
4862 bool overflow_p = false;
4863 hash_map <tree, tree> map;
4865 constexpr_ctx ctx = { NULL, &map, NULL, NULL, NULL, NULL, true, true };
4867 cxx_eval_constant_expression (&ctx, t, false, &non_constant_p,
4868 &overflow_p);
4869 return !non_constant_p && !overflow_p;
4872 /* If T represents a constant expression returns its reduced value.
4873 Otherwise return error_mark_node. If T is dependent, then
4874 return NULL. */
4876 tree
4877 cxx_constant_value (tree t, tree decl)
4879 return cxx_eval_outermost_constant_expr (t, false, true, decl);
4882 /* Helper routine for fold_simple function. Either return simplified
4883 expression T, otherwise NULL_TREE.
4884 In contrast to cp_fully_fold, and to maybe_constant_value, we try to fold
4885 even if we are within template-declaration. So be careful on call, as in
4886 such case types can be undefined. */
4888 static tree
4889 fold_simple_1 (tree t)
4891 tree op1;
4892 enum tree_code code = TREE_CODE (t);
4894 switch (code)
4896 case INTEGER_CST:
4897 case REAL_CST:
4898 case VECTOR_CST:
4899 case FIXED_CST:
4900 case COMPLEX_CST:
4901 return t;
4903 case SIZEOF_EXPR:
4904 return fold_sizeof_expr (t);
4906 case ABS_EXPR:
4907 case CONJ_EXPR:
4908 case REALPART_EXPR:
4909 case IMAGPART_EXPR:
4910 case NEGATE_EXPR:
4911 case BIT_NOT_EXPR:
4912 case TRUTH_NOT_EXPR:
4913 case NOP_EXPR:
4914 case VIEW_CONVERT_EXPR:
4915 case CONVERT_EXPR:
4916 case FLOAT_EXPR:
4917 case FIX_TRUNC_EXPR:
4918 case FIXED_CONVERT_EXPR:
4919 case ADDR_SPACE_CONVERT_EXPR:
4921 op1 = TREE_OPERAND (t, 0);
4923 t = const_unop (code, TREE_TYPE (t), op1);
4924 if (!t)
4925 return NULL_TREE;
4927 if (CONVERT_EXPR_CODE_P (code)
4928 && TREE_OVERFLOW_P (t) && !TREE_OVERFLOW_P (op1))
4929 TREE_OVERFLOW (t) = false;
4930 return t;
4932 default:
4933 return NULL_TREE;
4937 /* If T is a simple constant expression, returns its simplified value.
4938 Otherwise returns T. In contrast to maybe_constant_value do we
4939 simplify only few operations on constant-expressions, and we don't
4940 try to simplify constexpressions. */
4942 tree
4943 fold_simple (tree t)
4945 tree r = NULL_TREE;
4946 if (processing_template_decl)
4947 return t;
4949 r = fold_simple_1 (t);
4950 if (!r)
4951 r = t;
4953 return r;
4956 /* If T is a constant expression, returns its reduced value.
4957 Otherwise, if T does not have TREE_CONSTANT set, returns T.
4958 Otherwise, returns a version of T without TREE_CONSTANT. */
4960 static GTY((deletable)) hash_map<tree, tree> *cv_cache;
4962 tree
4963 maybe_constant_value (tree t, tree decl)
4965 tree r;
4967 if (!is_nondependent_constant_expression (t))
4969 if (TREE_OVERFLOW_P (t))
4971 t = build_nop (TREE_TYPE (t), t);
4972 TREE_CONSTANT (t) = false;
4974 return t;
4976 else if (CONSTANT_CLASS_P (t))
4977 /* No caching or evaluation needed. */
4978 return t;
4980 if (cv_cache == NULL)
4981 cv_cache = hash_map<tree, tree>::create_ggc (101);
4982 if (tree *cached = cv_cache->get (t))
4983 return *cached;
4985 r = cxx_eval_outermost_constant_expr (t, true, true, decl);
4986 gcc_checking_assert (r == t
4987 || CONVERT_EXPR_P (t)
4988 || TREE_CODE (t) == VIEW_CONVERT_EXPR
4989 || (TREE_CONSTANT (t) && !TREE_CONSTANT (r))
4990 || !cp_tree_equal (r, t));
4991 cv_cache->put (t, r);
4992 return r;
4995 /* Dispose of the whole CV_CACHE. */
4997 static void
4998 clear_cv_cache (void)
5000 if (cv_cache != NULL)
5001 cv_cache->empty ();
5004 /* Dispose of the whole CV_CACHE and FOLD_CACHE. */
5006 void
5007 clear_cv_and_fold_caches (void)
5009 clear_cv_cache ();
5010 clear_fold_cache ();
5013 /* Like maybe_constant_value but first fully instantiate the argument.
5015 Note: this is equivalent to instantiate_non_dependent_expr_sfinae
5016 (t, tf_none) followed by maybe_constant_value but is more efficient,
5017 because calls instantiation_dependent_expression_p and
5018 potential_constant_expression at most once. */
5020 tree
5021 fold_non_dependent_expr (tree t)
5023 if (t == NULL_TREE)
5024 return NULL_TREE;
5026 /* If we're in a template, but T isn't value dependent, simplify
5027 it. We're supposed to treat:
5029 template <typename T> void f(T[1 + 1]);
5030 template <typename T> void f(T[2]);
5032 as two declarations of the same function, for example. */
5033 if (processing_template_decl)
5035 if (is_nondependent_constant_expression (t))
5037 processing_template_decl_sentinel s;
5038 t = instantiate_non_dependent_expr_internal (t, tf_none);
5040 if (type_unknown_p (t)
5041 || BRACE_ENCLOSED_INITIALIZER_P (t))
5043 if (TREE_OVERFLOW_P (t))
5045 t = build_nop (TREE_TYPE (t), t);
5046 TREE_CONSTANT (t) = false;
5048 return t;
5051 tree r = cxx_eval_outermost_constant_expr (t, true, true, NULL_TREE);
5052 /* cp_tree_equal looks through NOPs, so allow them. */
5053 gcc_checking_assert (r == t
5054 || CONVERT_EXPR_P (t)
5055 || TREE_CODE (t) == VIEW_CONVERT_EXPR
5056 || (TREE_CONSTANT (t) && !TREE_CONSTANT (r))
5057 || !cp_tree_equal (r, t));
5058 return r;
5060 else if (TREE_OVERFLOW_P (t))
5062 t = build_nop (TREE_TYPE (t), t);
5063 TREE_CONSTANT (t) = false;
5065 return t;
5068 return maybe_constant_value (t);
5071 /* Like maybe_constant_value, but returns a CONSTRUCTOR directly, rather
5072 than wrapped in a TARGET_EXPR. */
5074 tree
5075 maybe_constant_init (tree t, tree decl)
5077 if (!t)
5078 return t;
5079 if (TREE_CODE (t) == EXPR_STMT)
5080 t = TREE_OPERAND (t, 0);
5081 if (TREE_CODE (t) == CONVERT_EXPR
5082 && VOID_TYPE_P (TREE_TYPE (t)))
5083 t = TREE_OPERAND (t, 0);
5084 if (TREE_CODE (t) == INIT_EXPR)
5085 t = TREE_OPERAND (t, 1);
5086 if (TREE_CODE (t) == TARGET_EXPR)
5087 t = TARGET_EXPR_INITIAL (t);
5088 if (!is_nondependent_static_init_expression (t))
5089 /* Don't try to evaluate it. */;
5090 else if (CONSTANT_CLASS_P (t))
5091 /* No evaluation needed. */;
5092 else
5093 t = cxx_eval_outermost_constant_expr (t, true, false, decl);
5094 if (TREE_CODE (t) == TARGET_EXPR)
5096 tree init = TARGET_EXPR_INITIAL (t);
5097 if (TREE_CODE (init) == CONSTRUCTOR)
5098 t = init;
5100 return t;
5103 #if 0
5104 /* FIXME see ADDR_EXPR section in potential_constant_expression_1. */
5105 /* Return true if the object referred to by REF has automatic or thread
5106 local storage. */
5108 enum { ck_ok, ck_bad, ck_unknown };
5109 static int
5110 check_automatic_or_tls (tree ref)
5112 machine_mode mode;
5113 HOST_WIDE_INT bitsize, bitpos;
5114 tree offset;
5115 int volatilep = 0, unsignedp = 0;
5116 tree decl = get_inner_reference (ref, &bitsize, &bitpos, &offset,
5117 &mode, &unsignedp, &volatilep, false);
5118 duration_kind dk;
5120 /* If there isn't a decl in the middle, we don't know the linkage here,
5121 and this isn't a constant expression anyway. */
5122 if (!DECL_P (decl))
5123 return ck_unknown;
5124 dk = decl_storage_duration (decl);
5125 return (dk == dk_auto || dk == dk_thread) ? ck_bad : ck_ok;
5127 #endif
5129 /* Return true if T denotes a potentially constant expression. Issue
5130 diagnostic as appropriate under control of FLAGS. If WANT_RVAL is true,
5131 an lvalue-rvalue conversion is implied. If NOW is true, we want to
5132 consider the expression in the current context, independent of constexpr
5133 substitution.
5135 C++0x [expr.const] used to say
5137 6 An expression is a potential constant expression if it is
5138 a constant expression where all occurrences of function
5139 parameters are replaced by arbitrary constant expressions
5140 of the appropriate type.
5142 2 A conditional expression is a constant expression unless it
5143 involves one of the following as a potentially evaluated
5144 subexpression (3.2), but subexpressions of logical AND (5.14),
5145 logical OR (5.15), and conditional (5.16) operations that are
5146 not evaluated are not considered. */
5148 static bool
5149 potential_constant_expression_1 (tree t, bool want_rval, bool strict, bool now,
5150 tsubst_flags_t flags)
5152 #define RECUR(T,RV) \
5153 potential_constant_expression_1 ((T), (RV), strict, now, flags)
5155 enum { any = false, rval = true };
5156 int i;
5157 tree tmp;
5159 if (t == error_mark_node)
5160 return false;
5161 if (t == NULL_TREE)
5162 return true;
5163 location_t loc = EXPR_LOC_OR_LOC (t, input_location);
5164 if (TREE_THIS_VOLATILE (t) && !DECL_P (t))
5166 if (flags & tf_error)
5167 error_at (loc, "expression %qE has side-effects", t);
5168 return false;
5170 if (CONSTANT_CLASS_P (t))
5171 return true;
5172 if (CODE_CONTAINS_STRUCT (TREE_CODE (t), TS_TYPED)
5173 && TREE_TYPE (t) == error_mark_node)
5174 return false;
5176 switch (TREE_CODE (t))
5178 case FUNCTION_DECL:
5179 case BASELINK:
5180 case TEMPLATE_DECL:
5181 case OVERLOAD:
5182 case TEMPLATE_ID_EXPR:
5183 case LABEL_DECL:
5184 case LABEL_EXPR:
5185 case CASE_LABEL_EXPR:
5186 case CONST_DECL:
5187 case SIZEOF_EXPR:
5188 case ALIGNOF_EXPR:
5189 case OFFSETOF_EXPR:
5190 case NOEXCEPT_EXPR:
5191 case TEMPLATE_PARM_INDEX:
5192 case TRAIT_EXPR:
5193 case IDENTIFIER_NODE:
5194 case USERDEF_LITERAL:
5195 /* We can see a FIELD_DECL in a pointer-to-member expression. */
5196 case FIELD_DECL:
5197 case RESULT_DECL:
5198 case USING_DECL:
5199 case USING_STMT:
5200 case PLACEHOLDER_EXPR:
5201 case BREAK_STMT:
5202 case CONTINUE_STMT:
5203 case REQUIRES_EXPR:
5204 case STATIC_ASSERT:
5205 case DEBUG_BEGIN_STMT:
5206 return true;
5208 case PARM_DECL:
5209 if (now)
5211 if (flags & tf_error)
5212 error ("%qE is not a constant expression", t);
5213 return false;
5215 return true;
5217 case AGGR_INIT_EXPR:
5218 case CALL_EXPR:
5219 /* -- an invocation of a function other than a constexpr function
5220 or a constexpr constructor. */
5222 tree fun = get_function_named_in_call (t);
5223 const int nargs = call_expr_nargs (t);
5224 i = 0;
5226 if (fun == NULL_TREE)
5228 /* Reset to allow the function to continue past the end
5229 of the block below. Otherwise return early. */
5230 bool bail = true;
5232 if (TREE_CODE (t) == CALL_EXPR
5233 && CALL_EXPR_FN (t) == NULL_TREE)
5234 switch (CALL_EXPR_IFN (t))
5236 /* These should be ignored, they are optimized away from
5237 constexpr functions. */
5238 case IFN_UBSAN_NULL:
5239 case IFN_UBSAN_BOUNDS:
5240 case IFN_UBSAN_VPTR:
5241 case IFN_FALLTHROUGH:
5242 return true;
5244 case IFN_ADD_OVERFLOW:
5245 case IFN_SUB_OVERFLOW:
5246 case IFN_MUL_OVERFLOW:
5247 case IFN_LAUNDER:
5248 bail = false;
5250 default:
5251 break;
5254 if (bail)
5256 /* fold_call_expr can't do anything with IFN calls. */
5257 if (flags & tf_error)
5258 error_at (loc, "call to internal function %qE", t);
5259 return false;
5263 if (fun && is_overloaded_fn (fun))
5265 if (TREE_CODE (fun) == FUNCTION_DECL)
5267 if (builtin_valid_in_constant_expr_p (fun))
5268 return true;
5269 if (!DECL_DECLARED_CONSTEXPR_P (fun)
5270 /* Allow any built-in function; if the expansion
5271 isn't constant, we'll deal with that then. */
5272 && !is_builtin_fn (fun))
5274 if (flags & tf_error)
5276 error_at (loc, "call to non-%<constexpr%> function %qD",
5277 fun);
5278 explain_invalid_constexpr_fn (fun);
5280 return false;
5282 /* A call to a non-static member function takes the address
5283 of the object as the first argument. But in a constant
5284 expression the address will be folded away, so look
5285 through it now. */
5286 if (DECL_NONSTATIC_MEMBER_FUNCTION_P (fun)
5287 && !DECL_CONSTRUCTOR_P (fun))
5289 tree x = get_nth_callarg (t, 0);
5290 if (is_this_parameter (x))
5291 return true;
5292 /* Don't require an immediately constant value, as
5293 constexpr substitution might not use the value. */
5294 bool sub_now = false;
5295 if (!potential_constant_expression_1 (x, rval, strict,
5296 sub_now, flags))
5297 return false;
5298 i = 1;
5301 else
5303 if (!RECUR (fun, true))
5304 return false;
5305 fun = get_first_fn (fun);
5307 /* Skip initial arguments to base constructors. */
5308 if (DECL_BASE_CONSTRUCTOR_P (fun))
5309 i = num_artificial_parms_for (fun);
5310 fun = DECL_ORIGIN (fun);
5312 else if (fun)
5314 if (RECUR (fun, rval))
5315 /* Might end up being a constant function pointer. */;
5316 else
5317 return false;
5319 for (; i < nargs; ++i)
5321 tree x = get_nth_callarg (t, i);
5322 /* In a template, reference arguments haven't been converted to
5323 REFERENCE_TYPE and we might not even know if the parameter
5324 is a reference, so accept lvalue constants too. */
5325 bool rv = processing_template_decl ? any : rval;
5326 /* Don't require an immediately constant value, as constexpr
5327 substitution might not use the value of the argument. */
5328 bool sub_now = false;
5329 if (!potential_constant_expression_1 (x, rv, strict,
5330 sub_now, flags))
5331 return false;
5333 return true;
5336 case NON_LVALUE_EXPR:
5337 /* -- an lvalue-to-rvalue conversion (4.1) unless it is applied to
5338 -- an lvalue of integral type that refers to a non-volatile
5339 const variable or static data member initialized with
5340 constant expressions, or
5342 -- an lvalue of literal type that refers to non-volatile
5343 object defined with constexpr, or that refers to a
5344 sub-object of such an object; */
5345 return RECUR (TREE_OPERAND (t, 0), rval);
5347 case VAR_DECL:
5348 if (DECL_HAS_VALUE_EXPR_P (t))
5350 if (now && is_normal_capture_proxy (t))
5352 /* -- in a lambda-expression, a reference to this or to a
5353 variable with automatic storage duration defined outside that
5354 lambda-expression, where the reference would be an
5355 odr-use. */
5356 if (flags & tf_error)
5358 tree cap = DECL_CAPTURED_VARIABLE (t);
5359 error ("lambda capture of %qE is not a constant expression",
5360 cap);
5361 if (!want_rval && decl_constant_var_p (cap))
5362 inform (input_location, "because it is used as a glvalue");
5364 return false;
5366 return RECUR (DECL_VALUE_EXPR (t), rval);
5368 if (want_rval
5369 && !var_in_maybe_constexpr_fn (t)
5370 && !type_dependent_expression_p (t)
5371 && !decl_maybe_constant_var_p (t)
5372 && (strict
5373 || !CP_TYPE_CONST_NON_VOLATILE_P (TREE_TYPE (t))
5374 || (DECL_INITIAL (t)
5375 && !DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (t)))
5376 && COMPLETE_TYPE_P (TREE_TYPE (t))
5377 && !is_really_empty_class (TREE_TYPE (t)))
5379 if (flags & tf_error)
5380 non_const_var_error (t);
5381 return false;
5383 return true;
5385 case NOP_EXPR:
5386 case CONVERT_EXPR:
5387 case VIEW_CONVERT_EXPR:
5388 /* -- a reinterpret_cast. FIXME not implemented, and this rule
5389 may change to something more specific to type-punning (DR 1312). */
5391 tree from = TREE_OPERAND (t, 0);
5392 if (POINTER_TYPE_P (TREE_TYPE (t))
5393 && TREE_CODE (from) == INTEGER_CST
5394 && !integer_zerop (from))
5396 if (flags & tf_error)
5397 error_at (loc, "reinterpret_cast from integer to pointer");
5398 return false;
5400 return (RECUR (from, TREE_CODE (t) != VIEW_CONVERT_EXPR));
5403 case ADDRESSOF_EXPR:
5404 /* This is like ADDR_EXPR, except it won't form pointer-to-member. */
5405 t = TREE_OPERAND (t, 0);
5406 goto handle_addr_expr;
5408 case ADDR_EXPR:
5409 /* -- a unary operator & that is applied to an lvalue that
5410 designates an object with thread or automatic storage
5411 duration; */
5412 t = TREE_OPERAND (t, 0);
5414 if (TREE_CODE (t) == OFFSET_REF && PTRMEM_OK_P (t))
5415 /* A pointer-to-member constant. */
5416 return true;
5418 handle_addr_expr:
5419 #if 0
5420 /* FIXME adjust when issue 1197 is fully resolved. For now don't do
5421 any checking here, as we might dereference the pointer later. If
5422 we remove this code, also remove check_automatic_or_tls. */
5423 i = check_automatic_or_tls (t);
5424 if (i == ck_ok)
5425 return true;
5426 if (i == ck_bad)
5428 if (flags & tf_error)
5429 error ("address-of an object %qE with thread local or "
5430 "automatic storage is not a constant expression", t);
5431 return false;
5433 #endif
5434 return RECUR (t, any);
5436 case REALPART_EXPR:
5437 case IMAGPART_EXPR:
5438 case COMPONENT_REF:
5439 case BIT_FIELD_REF:
5440 case ARROW_EXPR:
5441 case OFFSET_REF:
5442 /* -- a class member access unless its postfix-expression is
5443 of literal type or of pointer to literal type. */
5444 /* This test would be redundant, as it follows from the
5445 postfix-expression being a potential constant expression. */
5446 if (type_unknown_p (t))
5447 return true;
5448 return RECUR (TREE_OPERAND (t, 0), want_rval);
5450 case EXPR_PACK_EXPANSION:
5451 return RECUR (PACK_EXPANSION_PATTERN (t), want_rval);
5453 case INDIRECT_REF:
5455 tree x = TREE_OPERAND (t, 0);
5456 STRIP_NOPS (x);
5457 if (is_this_parameter (x) && !is_capture_proxy (x))
5459 if (!var_in_maybe_constexpr_fn (x))
5461 if (flags & tf_error)
5462 error_at (loc, "use of %<this%> in a constant expression");
5463 return false;
5465 return true;
5467 return RECUR (x, rval);
5470 case STATEMENT_LIST:
5472 tree_stmt_iterator i;
5473 for (i = tsi_start (t); !tsi_end_p (i); tsi_next (&i))
5475 if (!RECUR (tsi_stmt (i), any))
5476 return false;
5478 return true;
5480 break;
5482 case MODIFY_EXPR:
5483 if (cxx_dialect < cxx14)
5484 goto fail;
5485 if (!RECUR (TREE_OPERAND (t, 0), any))
5486 return false;
5487 if (!RECUR (TREE_OPERAND (t, 1), rval))
5488 return false;
5489 return true;
5491 case MODOP_EXPR:
5492 if (cxx_dialect < cxx14)
5493 goto fail;
5494 if (!RECUR (TREE_OPERAND (t, 0), rval))
5495 return false;
5496 if (!RECUR (TREE_OPERAND (t, 2), rval))
5497 return false;
5498 return true;
5500 case DO_STMT:
5501 if (!RECUR (DO_COND (t), rval))
5502 return false;
5503 if (!RECUR (DO_BODY (t), any))
5504 return false;
5505 return true;
5507 case FOR_STMT:
5508 if (!RECUR (FOR_INIT_STMT (t), any))
5509 return false;
5510 if (!RECUR (FOR_COND (t), rval))
5511 return false;
5512 if (!RECUR (FOR_EXPR (t), any))
5513 return false;
5514 if (!RECUR (FOR_BODY (t), any))
5515 return false;
5516 return true;
5518 case RANGE_FOR_STMT:
5519 if (!RECUR (RANGE_FOR_EXPR (t), any))
5520 return false;
5521 if (!RECUR (RANGE_FOR_BODY (t), any))
5522 return false;
5523 return true;
5525 case WHILE_STMT:
5526 if (!RECUR (WHILE_COND (t), rval))
5527 return false;
5528 if (!RECUR (WHILE_BODY (t), any))
5529 return false;
5530 return true;
5532 case SWITCH_STMT:
5533 if (!RECUR (SWITCH_STMT_COND (t), rval))
5534 return false;
5535 /* FIXME we don't check SWITCH_STMT_BODY currently, because even
5536 unreachable labels would be checked. */
5537 return true;
5539 case STMT_EXPR:
5540 return RECUR (STMT_EXPR_STMT (t), rval);
5542 case LAMBDA_EXPR:
5543 if (cxx_dialect >= cxx17)
5544 /* In C++17 lambdas can be constexpr, don't give up yet. */
5545 return true;
5546 else if (flags & tf_error)
5547 error_at (loc, "lambda-expression is not a constant expression "
5548 "before C++17");
5549 return false;
5551 case DYNAMIC_CAST_EXPR:
5552 case PSEUDO_DTOR_EXPR:
5553 case NEW_EXPR:
5554 case VEC_NEW_EXPR:
5555 case DELETE_EXPR:
5556 case VEC_DELETE_EXPR:
5557 case THROW_EXPR:
5558 case OMP_PARALLEL:
5559 case OMP_TASK:
5560 case OMP_FOR:
5561 case OMP_DISTRIBUTE:
5562 case OMP_TASKLOOP:
5563 case OMP_TEAMS:
5564 case OMP_TARGET_DATA:
5565 case OMP_TARGET:
5566 case OMP_SECTIONS:
5567 case OMP_ORDERED:
5568 case OMP_CRITICAL:
5569 case OMP_SINGLE:
5570 case OMP_SECTION:
5571 case OMP_MASTER:
5572 case OMP_TASKGROUP:
5573 case OMP_TARGET_UPDATE:
5574 case OMP_TARGET_ENTER_DATA:
5575 case OMP_TARGET_EXIT_DATA:
5576 case OMP_ATOMIC:
5577 case OMP_ATOMIC_READ:
5578 case OMP_ATOMIC_CAPTURE_OLD:
5579 case OMP_ATOMIC_CAPTURE_NEW:
5580 case OACC_PARALLEL:
5581 case OACC_KERNELS:
5582 case OACC_DATA:
5583 case OACC_HOST_DATA:
5584 case OACC_LOOP:
5585 case OACC_CACHE:
5586 case OACC_DECLARE:
5587 case OACC_ENTER_DATA:
5588 case OACC_EXIT_DATA:
5589 case OACC_UPDATE:
5590 /* GCC internal stuff. */
5591 case VA_ARG_EXPR:
5592 case OBJ_TYPE_REF:
5593 case TRANSACTION_EXPR:
5594 case ASM_EXPR:
5595 case AT_ENCODE_EXPR:
5596 fail:
5597 if (flags & tf_error)
5598 error_at (loc, "expression %qE is not a constant expression", t);
5599 return false;
5601 case TYPEID_EXPR:
5602 /* -- a typeid expression whose operand is of polymorphic
5603 class type; */
5605 tree e = TREE_OPERAND (t, 0);
5606 if (!TYPE_P (e) && !type_dependent_expression_p (e)
5607 && TYPE_POLYMORPHIC_P (TREE_TYPE (e)))
5609 if (flags & tf_error)
5610 error_at (loc, "typeid-expression is not a constant expression "
5611 "because %qE is of polymorphic type", e);
5612 return false;
5614 return true;
5617 case POINTER_DIFF_EXPR:
5618 case MINUS_EXPR:
5619 want_rval = true;
5620 goto binary;
5622 case LT_EXPR:
5623 case LE_EXPR:
5624 case GT_EXPR:
5625 case GE_EXPR:
5626 case EQ_EXPR:
5627 case NE_EXPR:
5628 want_rval = true;
5629 goto binary;
5631 case PREINCREMENT_EXPR:
5632 case POSTINCREMENT_EXPR:
5633 case PREDECREMENT_EXPR:
5634 case POSTDECREMENT_EXPR:
5635 if (cxx_dialect < cxx14)
5636 goto fail;
5637 goto unary;
5639 case BIT_NOT_EXPR:
5640 /* A destructor. */
5641 if (TYPE_P (TREE_OPERAND (t, 0)))
5642 return true;
5643 /* fall through. */
5645 case CONJ_EXPR:
5646 case SAVE_EXPR:
5647 case FIX_TRUNC_EXPR:
5648 case FLOAT_EXPR:
5649 case NEGATE_EXPR:
5650 case ABS_EXPR:
5651 case TRUTH_NOT_EXPR:
5652 case FIXED_CONVERT_EXPR:
5653 case UNARY_PLUS_EXPR:
5654 case UNARY_LEFT_FOLD_EXPR:
5655 case UNARY_RIGHT_FOLD_EXPR:
5656 unary:
5657 return RECUR (TREE_OPERAND (t, 0), rval);
5659 case CAST_EXPR:
5660 case CONST_CAST_EXPR:
5661 case STATIC_CAST_EXPR:
5662 case REINTERPRET_CAST_EXPR:
5663 case IMPLICIT_CONV_EXPR:
5664 if (cxx_dialect < cxx11
5665 && !dependent_type_p (TREE_TYPE (t))
5666 && !INTEGRAL_OR_ENUMERATION_TYPE_P (TREE_TYPE (t)))
5667 /* In C++98, a conversion to non-integral type can't be part of a
5668 constant expression. */
5670 if (flags & tf_error)
5671 error_at (loc,
5672 "cast to non-integral type %qT in a constant expression",
5673 TREE_TYPE (t));
5674 return false;
5677 return (RECUR (TREE_OPERAND (t, 0),
5678 TREE_CODE (TREE_TYPE (t)) != REFERENCE_TYPE));
5680 case BIND_EXPR:
5681 return RECUR (BIND_EXPR_BODY (t), want_rval);
5683 case CLEANUP_POINT_EXPR:
5684 case MUST_NOT_THROW_EXPR:
5685 case TRY_CATCH_EXPR:
5686 case TRY_BLOCK:
5687 case EH_SPEC_BLOCK:
5688 case EXPR_STMT:
5689 case PAREN_EXPR:
5690 case NON_DEPENDENT_EXPR:
5691 /* For convenience. */
5692 case RETURN_EXPR:
5693 case LOOP_EXPR:
5694 case EXIT_EXPR:
5695 return RECUR (TREE_OPERAND (t, 0), want_rval);
5697 case DECL_EXPR:
5698 tmp = DECL_EXPR_DECL (t);
5699 if (VAR_P (tmp) && !DECL_ARTIFICIAL (tmp))
5701 if (TREE_STATIC (tmp))
5703 if (flags & tf_error)
5704 error_at (DECL_SOURCE_LOCATION (tmp), "%qD declared "
5705 "%<static%> in %<constexpr%> context", tmp);
5706 return false;
5708 else if (CP_DECL_THREAD_LOCAL_P (tmp))
5710 if (flags & tf_error)
5711 error_at (DECL_SOURCE_LOCATION (tmp), "%qD declared "
5712 "%<thread_local%> in %<constexpr%> context", tmp);
5713 return false;
5715 else if (!DECL_NONTRIVIALLY_INITIALIZED_P (tmp))
5717 if (flags & tf_error)
5718 error_at (DECL_SOURCE_LOCATION (tmp), "uninitialized "
5719 "variable %qD in %<constexpr%> context", tmp);
5720 return false;
5723 return RECUR (tmp, want_rval);
5725 case TRY_FINALLY_EXPR:
5726 return (RECUR (TREE_OPERAND (t, 0), want_rval)
5727 && RECUR (TREE_OPERAND (t, 1), any));
5729 case SCOPE_REF:
5730 return RECUR (TREE_OPERAND (t, 1), want_rval);
5732 case TARGET_EXPR:
5733 if (!literal_type_p (TREE_TYPE (t)))
5735 if (flags & tf_error)
5737 error_at (loc, "temporary of non-literal type %qT in a "
5738 "constant expression", TREE_TYPE (t));
5739 explain_non_literal_class (TREE_TYPE (t));
5741 return false;
5743 /* FALLTHRU */
5744 case INIT_EXPR:
5745 return RECUR (TREE_OPERAND (t, 1), rval);
5747 case CONSTRUCTOR:
5749 vec<constructor_elt, va_gc> *v = CONSTRUCTOR_ELTS (t);
5750 constructor_elt *ce;
5751 for (i = 0; vec_safe_iterate (v, i, &ce); ++i)
5752 if (!RECUR (ce->value, want_rval))
5753 return false;
5754 return true;
5757 case TREE_LIST:
5759 gcc_assert (TREE_PURPOSE (t) == NULL_TREE
5760 || DECL_P (TREE_PURPOSE (t)));
5761 if (!RECUR (TREE_VALUE (t), want_rval))
5762 return false;
5763 if (TREE_CHAIN (t) == NULL_TREE)
5764 return true;
5765 return RECUR (TREE_CHAIN (t), want_rval);
5768 case TRUNC_DIV_EXPR:
5769 case CEIL_DIV_EXPR:
5770 case FLOOR_DIV_EXPR:
5771 case ROUND_DIV_EXPR:
5772 case TRUNC_MOD_EXPR:
5773 case CEIL_MOD_EXPR:
5774 case ROUND_MOD_EXPR:
5776 tree denom = TREE_OPERAND (t, 1);
5777 if (!RECUR (denom, rval))
5778 return false;
5779 /* We can't call cxx_eval_outermost_constant_expr on an expression
5780 that hasn't been through instantiate_non_dependent_expr yet. */
5781 if (!processing_template_decl)
5782 denom = cxx_eval_outermost_constant_expr (denom, true);
5783 if (integer_zerop (denom))
5785 if (flags & tf_error)
5786 error ("division by zero is not a constant expression");
5787 return false;
5789 else
5791 want_rval = true;
5792 return RECUR (TREE_OPERAND (t, 0), want_rval);
5796 case COMPOUND_EXPR:
5798 /* check_return_expr sometimes wraps a TARGET_EXPR in a
5799 COMPOUND_EXPR; don't get confused. Also handle EMPTY_CLASS_EXPR
5800 introduced by build_call_a. */
5801 tree op0 = TREE_OPERAND (t, 0);
5802 tree op1 = TREE_OPERAND (t, 1);
5803 STRIP_NOPS (op1);
5804 if ((TREE_CODE (op0) == TARGET_EXPR && op1 == TARGET_EXPR_SLOT (op0))
5805 || TREE_CODE (op1) == EMPTY_CLASS_EXPR)
5806 return RECUR (op0, want_rval);
5807 else
5808 goto binary;
5811 /* If the first operand is the non-short-circuit constant, look at
5812 the second operand; otherwise we only care about the first one for
5813 potentiality. */
5814 case TRUTH_AND_EXPR:
5815 case TRUTH_ANDIF_EXPR:
5816 tmp = boolean_true_node;
5817 goto truth;
5818 case TRUTH_OR_EXPR:
5819 case TRUTH_ORIF_EXPR:
5820 tmp = boolean_false_node;
5821 truth:
5823 tree op = TREE_OPERAND (t, 0);
5824 if (!RECUR (op, rval))
5825 return false;
5826 if (!processing_template_decl)
5827 op = cxx_eval_outermost_constant_expr (op, true);
5828 if (tree_int_cst_equal (op, tmp))
5829 return RECUR (TREE_OPERAND (t, 1), rval);
5830 else
5831 return true;
5834 case PLUS_EXPR:
5835 case MULT_EXPR:
5836 case POINTER_PLUS_EXPR:
5837 case RDIV_EXPR:
5838 case EXACT_DIV_EXPR:
5839 case MIN_EXPR:
5840 case MAX_EXPR:
5841 case LSHIFT_EXPR:
5842 case RSHIFT_EXPR:
5843 case LROTATE_EXPR:
5844 case RROTATE_EXPR:
5845 case BIT_IOR_EXPR:
5846 case BIT_XOR_EXPR:
5847 case BIT_AND_EXPR:
5848 case TRUTH_XOR_EXPR:
5849 case UNORDERED_EXPR:
5850 case ORDERED_EXPR:
5851 case UNLT_EXPR:
5852 case UNLE_EXPR:
5853 case UNGT_EXPR:
5854 case UNGE_EXPR:
5855 case UNEQ_EXPR:
5856 case LTGT_EXPR:
5857 case RANGE_EXPR:
5858 case COMPLEX_EXPR:
5859 want_rval = true;
5860 /* Fall through. */
5861 case ARRAY_REF:
5862 case ARRAY_RANGE_REF:
5863 case MEMBER_REF:
5864 case DOTSTAR_EXPR:
5865 case MEM_REF:
5866 case BINARY_LEFT_FOLD_EXPR:
5867 case BINARY_RIGHT_FOLD_EXPR:
5868 binary:
5869 for (i = 0; i < 2; ++i)
5870 if (!RECUR (TREE_OPERAND (t, i), want_rval))
5871 return false;
5872 return true;
5874 case FMA_EXPR:
5875 case VEC_PERM_EXPR:
5876 for (i = 0; i < 3; ++i)
5877 if (!RECUR (TREE_OPERAND (t, i), true))
5878 return false;
5879 return true;
5881 case COND_EXPR:
5882 if (COND_EXPR_IS_VEC_DELETE (t))
5884 if (flags & tf_error)
5885 error_at (loc, "%<delete[]%> is not a constant expression");
5886 return false;
5888 /* Fall through. */
5889 case IF_STMT:
5890 case VEC_COND_EXPR:
5891 /* If the condition is a known constant, we know which of the legs we
5892 care about; otherwise we only require that the condition and
5893 either of the legs be potentially constant. */
5894 tmp = TREE_OPERAND (t, 0);
5895 if (!RECUR (tmp, rval))
5896 return false;
5897 if (!processing_template_decl)
5898 tmp = cxx_eval_outermost_constant_expr (tmp, true);
5899 if (integer_zerop (tmp))
5900 return RECUR (TREE_OPERAND (t, 2), want_rval);
5901 else if (TREE_CODE (tmp) == INTEGER_CST)
5902 return RECUR (TREE_OPERAND (t, 1), want_rval);
5903 for (i = 1; i < 3; ++i)
5904 if (potential_constant_expression_1 (TREE_OPERAND (t, i),
5905 want_rval, strict, now, tf_none))
5906 return true;
5907 if (flags & tf_error)
5908 error_at (loc, "expression %qE is not a constant expression", t);
5909 return false;
5911 case VEC_INIT_EXPR:
5912 if (VEC_INIT_EXPR_IS_CONSTEXPR (t))
5913 return true;
5914 if (flags & tf_error)
5916 error_at (loc, "non-constant array initialization");
5917 diagnose_non_constexpr_vec_init (t);
5919 return false;
5921 case TYPE_DECL:
5922 case TAG_DEFN:
5923 /* We can see these in statement-expressions. */
5924 return true;
5926 case CLEANUP_STMT:
5927 case EMPTY_CLASS_EXPR:
5928 case PREDICT_EXPR:
5929 return false;
5931 case GOTO_EXPR:
5933 tree *target = &TREE_OPERAND (t, 0);
5934 /* Gotos representing break and continue are OK. */
5935 if (breaks (target) || continues (target))
5936 return true;
5937 if (flags & tf_error)
5938 error_at (loc, "%<goto%> is not a constant expression");
5939 return false;
5942 case ANNOTATE_EXPR:
5943 gcc_assert (tree_to_uhwi (TREE_OPERAND (t, 1)) == annot_expr_ivdep_kind);
5944 return RECUR (TREE_OPERAND (t, 0), rval);
5946 default:
5947 if (objc_is_property_ref (t))
5948 return false;
5950 sorry ("unexpected AST of kind %s", get_tree_code_name (TREE_CODE (t)));
5951 gcc_unreachable ();
5952 return false;
5954 #undef RECUR
5957 /* The main entry point to the above. */
5959 bool
5960 potential_constant_expression (tree t)
5962 return potential_constant_expression_1 (t, false, true, false, tf_none);
5965 /* As above, but require a constant rvalue. */
5967 bool
5968 potential_rvalue_constant_expression (tree t)
5970 return potential_constant_expression_1 (t, true, true, false, tf_none);
5973 /* Like above, but complain about non-constant expressions. */
5975 bool
5976 require_potential_constant_expression (tree t)
5978 return potential_constant_expression_1 (t, false, true, false, tf_warning_or_error);
5981 /* Cross product of the above. */
5983 bool
5984 require_potential_rvalue_constant_expression (tree t)
5986 return potential_constant_expression_1 (t, true, true, false, tf_warning_or_error);
5989 /* Like potential_constant_expression, but don't consider possible constexpr
5990 substitution of the current function. That is, PARM_DECL qualifies under
5991 potential_constant_expression, but not here.
5993 This is basically what you can check when any actual constant values might
5994 be value-dependent. */
5996 bool
5997 is_constant_expression (tree t)
5999 return potential_constant_expression_1 (t, false, true, true, tf_none);
6002 /* Like above, but complain about non-constant expressions. */
6004 bool
6005 require_constant_expression (tree t)
6007 return potential_constant_expression_1 (t, false, true, true,
6008 tf_warning_or_error);
6011 /* Like is_constant_expression, but allow const variables that are not allowed
6012 under constexpr rules. */
6014 bool
6015 is_static_init_expression (tree t)
6017 return potential_constant_expression_1 (t, false, false, true, tf_none);
6020 /* Returns true if T is a potential constant expression that is not
6021 instantiation-dependent, and therefore a candidate for constant folding even
6022 in a template. */
6024 bool
6025 is_nondependent_constant_expression (tree t)
6027 return (!type_unknown_p (t)
6028 && !BRACE_ENCLOSED_INITIALIZER_P (t)
6029 && is_constant_expression (t)
6030 && !instantiation_dependent_expression_p (t));
6033 /* Returns true if T is a potential static initializer expression that is not
6034 instantiation-dependent. */
6036 bool
6037 is_nondependent_static_init_expression (tree t)
6039 return (!type_unknown_p (t)
6040 && !BRACE_ENCLOSED_INITIALIZER_P (t)
6041 && is_static_init_expression (t)
6042 && !instantiation_dependent_expression_p (t));
6045 /* Finalize constexpr processing after parsing. */
6047 void
6048 fini_constexpr (void)
6050 /* The contexpr call and fundef copies tables are no longer needed. */
6051 constexpr_call_table = NULL;
6052 fundef_copies_table = NULL;
6055 #include "gt-cp-constexpr.h"