PR c++/70652 - [6 Regression] r234966 causes bootstrap to fail
[official-gcc.git] / gcc / cp / constexpr.c
blob37cc336598306b391ce3ba3181fc2ef2bf57aa42
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-2016 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"
35 static bool verify_constant (tree, bool, bool *, bool *);
36 #define VERIFY_CONSTANT(X) \
37 do { \
38 if (verify_constant ((X), ctx->quiet, non_constant_p, overflow_p)) \
39 return t; \
40 } while (0)
42 /* Returns true iff FUN is an instantiation of a constexpr function
43 template or a defaulted constexpr function. */
45 bool
46 is_instantiation_of_constexpr (tree fun)
48 return ((DECL_TEMPLOID_INSTANTIATION (fun)
49 && DECL_DECLARED_CONSTEXPR_P (DECL_TI_TEMPLATE (fun)))
50 || (DECL_DEFAULTED_FN (fun)
51 && DECL_DECLARED_CONSTEXPR_P (fun)));
54 /* Return true if T is a literal type. */
56 bool
57 literal_type_p (tree t)
59 if (SCALAR_TYPE_P (t)
60 || VECTOR_TYPE_P (t)
61 || TREE_CODE (t) == REFERENCE_TYPE
62 || (VOID_TYPE_P (t) && cxx_dialect >= cxx14))
63 return true;
64 if (CLASS_TYPE_P (t))
66 t = complete_type (t);
67 gcc_assert (COMPLETE_TYPE_P (t) || errorcount);
68 return CLASSTYPE_LITERAL_P (t);
70 if (TREE_CODE (t) == ARRAY_TYPE)
71 return literal_type_p (strip_array_types (t));
72 return false;
75 /* If DECL is a variable declared `constexpr', require its type
76 be literal. Return the DECL if OK, otherwise NULL. */
78 tree
79 ensure_literal_type_for_constexpr_object (tree decl)
81 tree type = TREE_TYPE (decl);
82 if (VAR_P (decl)
83 && (DECL_DECLARED_CONSTEXPR_P (decl)
84 || var_in_constexpr_fn (decl))
85 && !processing_template_decl)
87 tree stype = strip_array_types (type);
88 if (CLASS_TYPE_P (stype) && !COMPLETE_TYPE_P (complete_type (stype)))
89 /* Don't complain here, we'll complain about incompleteness
90 when we try to initialize the variable. */;
91 else if (!literal_type_p (type))
93 if (DECL_DECLARED_CONSTEXPR_P (decl))
95 error ("the type %qT of constexpr variable %qD is not literal",
96 type, decl);
97 explain_non_literal_class (type);
99 else
101 if (!DECL_TEMPLATE_INSTANTIATION (current_function_decl))
103 error ("variable %qD of non-literal type %qT in %<constexpr%> "
104 "function", decl, type);
105 explain_non_literal_class (type);
107 cp_function_chain->invalid_constexpr = true;
109 return NULL;
112 return decl;
115 /* Representation of entries in the constexpr function definition table. */
117 struct GTY((for_user)) constexpr_fundef {
118 tree decl;
119 tree body;
122 struct constexpr_fundef_hasher : ggc_ptr_hash<constexpr_fundef>
124 static hashval_t hash (constexpr_fundef *);
125 static bool equal (constexpr_fundef *, constexpr_fundef *);
128 /* This table holds all constexpr function definitions seen in
129 the current translation unit. */
131 static GTY (()) hash_table<constexpr_fundef_hasher> *constexpr_fundef_table;
133 /* Utility function used for managing the constexpr function table.
134 Return true if the entries pointed to by P and Q are for the
135 same constexpr function. */
137 inline bool
138 constexpr_fundef_hasher::equal (constexpr_fundef *lhs, constexpr_fundef *rhs)
140 return lhs->decl == rhs->decl;
143 /* Utility function used for managing the constexpr function table.
144 Return a hash value for the entry pointed to by Q. */
146 inline hashval_t
147 constexpr_fundef_hasher::hash (constexpr_fundef *fundef)
149 return DECL_UID (fundef->decl);
152 /* Return a previously saved definition of function FUN. */
154 static constexpr_fundef *
155 retrieve_constexpr_fundef (tree fun)
157 constexpr_fundef fundef = { NULL, NULL };
158 if (constexpr_fundef_table == NULL)
159 return NULL;
161 fundef.decl = fun;
162 return constexpr_fundef_table->find (&fundef);
165 /* Check whether the parameter and return types of FUN are valid for a
166 constexpr function, and complain if COMPLAIN. */
168 static bool
169 is_valid_constexpr_fn (tree fun, bool complain)
171 bool ret = true;
173 if (DECL_INHERITED_CTOR_BASE (fun)
174 && TREE_CODE (fun) == TEMPLATE_DECL)
176 ret = false;
177 if (complain)
178 error ("inherited constructor %qD is not constexpr",
179 get_inherited_ctor (fun));
181 else
183 for (tree parm = FUNCTION_FIRST_USER_PARM (fun);
184 parm != NULL_TREE; parm = TREE_CHAIN (parm))
185 if (!literal_type_p (TREE_TYPE (parm)))
187 ret = false;
188 if (complain)
190 error ("invalid type for parameter %d of constexpr "
191 "function %q+#D", DECL_PARM_INDEX (parm), fun);
192 explain_non_literal_class (TREE_TYPE (parm));
197 if (!DECL_CONSTRUCTOR_P (fun))
199 tree rettype = TREE_TYPE (TREE_TYPE (fun));
200 if (!literal_type_p (rettype))
202 ret = false;
203 if (complain)
205 error ("invalid return type %qT of constexpr function %q+D",
206 rettype, fun);
207 explain_non_literal_class (rettype);
211 if (DECL_NONSTATIC_MEMBER_FUNCTION_P (fun)
212 && !CLASSTYPE_LITERAL_P (DECL_CONTEXT (fun)))
214 ret = false;
215 if (complain)
217 error ("enclosing class of constexpr non-static member "
218 "function %q+#D is not a literal type", fun);
219 explain_non_literal_class (DECL_CONTEXT (fun));
223 else if (CLASSTYPE_VBASECLASSES (DECL_CONTEXT (fun)))
225 ret = false;
226 if (complain)
227 error ("%q#T has virtual base classes", DECL_CONTEXT (fun));
230 return ret;
233 /* Subroutine of build_data_member_initialization. MEMBER is a COMPONENT_REF
234 for a member of an anonymous aggregate, INIT is the initializer for that
235 member, and VEC_OUTER is the vector of constructor elements for the class
236 whose constructor we are processing. Add the initializer to the vector
237 and return true to indicate success. */
239 static bool
240 build_anon_member_initialization (tree member, tree init,
241 vec<constructor_elt, va_gc> **vec_outer)
243 /* MEMBER presents the relevant fields from the inside out, but we need
244 to build up the initializer from the outside in so that we can reuse
245 previously built CONSTRUCTORs if this is, say, the second field in an
246 anonymous struct. So we use a vec as a stack. */
247 auto_vec<tree, 2> fields;
250 fields.safe_push (TREE_OPERAND (member, 1));
251 member = TREE_OPERAND (member, 0);
253 while (ANON_AGGR_TYPE_P (TREE_TYPE (member))
254 && TREE_CODE (member) == COMPONENT_REF);
256 /* VEC has the constructor elements vector for the context of FIELD.
257 If FIELD is an anonymous aggregate, we will push inside it. */
258 vec<constructor_elt, va_gc> **vec = vec_outer;
259 tree field;
260 while (field = fields.pop(),
261 ANON_AGGR_TYPE_P (TREE_TYPE (field)))
263 tree ctor;
264 /* If there is already an outer constructor entry for the anonymous
265 aggregate FIELD, use it; otherwise, insert one. */
266 if (vec_safe_is_empty (*vec)
267 || (*vec)->last().index != field)
269 ctor = build_constructor (TREE_TYPE (field), NULL);
270 CONSTRUCTOR_APPEND_ELT (*vec, field, ctor);
272 else
273 ctor = (*vec)->last().value;
274 vec = &CONSTRUCTOR_ELTS (ctor);
277 /* Now we're at the innermost field, the one that isn't an anonymous
278 aggregate. Add its initializer to the CONSTRUCTOR and we're done. */
279 gcc_assert (fields.is_empty());
280 CONSTRUCTOR_APPEND_ELT (*vec, field, init);
282 return true;
285 /* Subroutine of build_constexpr_constructor_member_initializers.
286 The expression tree T represents a data member initialization
287 in a (constexpr) constructor definition. Build a pairing of
288 the data member with its initializer, and prepend that pair
289 to the existing initialization pair INITS. */
291 static bool
292 build_data_member_initialization (tree t, vec<constructor_elt, va_gc> **vec)
294 tree member, init;
295 if (TREE_CODE (t) == CLEANUP_POINT_EXPR)
296 t = TREE_OPERAND (t, 0);
297 if (TREE_CODE (t) == EXPR_STMT)
298 t = TREE_OPERAND (t, 0);
299 if (t == error_mark_node)
300 return false;
301 if (TREE_CODE (t) == STATEMENT_LIST)
303 tree_stmt_iterator i;
304 for (i = tsi_start (t); !tsi_end_p (i); tsi_next (&i))
306 if (! build_data_member_initialization (tsi_stmt (i), vec))
307 return false;
309 return true;
311 if (TREE_CODE (t) == CLEANUP_STMT)
313 /* We can't see a CLEANUP_STMT in a constructor for a literal class,
314 but we can in a constexpr constructor for a non-literal class. Just
315 ignore it; either all the initialization will be constant, in which
316 case the cleanup can't run, or it can't be constexpr.
317 Still recurse into CLEANUP_BODY. */
318 return build_data_member_initialization (CLEANUP_BODY (t), vec);
320 if (TREE_CODE (t) == CONVERT_EXPR)
321 t = TREE_OPERAND (t, 0);
322 if (TREE_CODE (t) == INIT_EXPR
323 /* vptr initialization shows up as a MODIFY_EXPR. In C++14 we only
324 use what this function builds for cx_check_missing_mem_inits, and
325 assignment in the ctor body doesn't count. */
326 || (cxx_dialect < cxx14 && TREE_CODE (t) == MODIFY_EXPR))
328 member = TREE_OPERAND (t, 0);
329 init = break_out_target_exprs (TREE_OPERAND (t, 1));
331 else if (TREE_CODE (t) == CALL_EXPR)
333 tree fn = get_callee_fndecl (t);
334 if (!fn || !DECL_CONSTRUCTOR_P (fn))
335 /* We're only interested in calls to subobject constructors. */
336 return true;
337 member = CALL_EXPR_ARG (t, 0);
338 /* We don't use build_cplus_new here because it complains about
339 abstract bases. Leaving the call unwrapped means that it has the
340 wrong type, but cxx_eval_constant_expression doesn't care. */
341 init = break_out_target_exprs (t);
343 else if (TREE_CODE (t) == BIND_EXPR)
344 return build_data_member_initialization (BIND_EXPR_BODY (t), vec);
345 else
346 /* Don't add anything else to the CONSTRUCTOR. */
347 return true;
348 if (INDIRECT_REF_P (member))
349 member = TREE_OPERAND (member, 0);
350 if (TREE_CODE (member) == NOP_EXPR)
352 tree op = member;
353 STRIP_NOPS (op);
354 if (TREE_CODE (op) == ADDR_EXPR)
356 gcc_assert (same_type_ignoring_top_level_qualifiers_p
357 (TREE_TYPE (TREE_TYPE (op)),
358 TREE_TYPE (TREE_TYPE (member))));
359 /* Initializing a cv-qualified member; we need to look through
360 the const_cast. */
361 member = op;
363 else if (op == current_class_ptr
364 && (same_type_ignoring_top_level_qualifiers_p
365 (TREE_TYPE (TREE_TYPE (member)),
366 current_class_type)))
367 /* Delegating constructor. */
368 member = op;
369 else
371 /* This is an initializer for an empty base; keep it for now so
372 we can check it in cxx_eval_bare_aggregate. */
373 gcc_assert (is_empty_class (TREE_TYPE (TREE_TYPE (member))));
376 if (TREE_CODE (member) == ADDR_EXPR)
377 member = TREE_OPERAND (member, 0);
378 if (TREE_CODE (member) == COMPONENT_REF)
380 tree aggr = TREE_OPERAND (member, 0);
381 if (TREE_CODE (aggr) != COMPONENT_REF)
382 /* Normal member initialization. */
383 member = TREE_OPERAND (member, 1);
384 else if (ANON_AGGR_TYPE_P (TREE_TYPE (aggr)))
385 /* Initializing a member of an anonymous union. */
386 return build_anon_member_initialization (member, init, vec);
387 else
388 /* We're initializing a vtable pointer in a base. Leave it as
389 COMPONENT_REF so we remember the path to get to the vfield. */
390 gcc_assert (TREE_TYPE (member) == vtbl_ptr_type_node);
393 CONSTRUCTOR_APPEND_ELT (*vec, member, init);
394 return true;
397 /* Subroutine of check_constexpr_ctor_body_1 and constexpr_fn_retval.
398 In C++11 mode checks that the TYPE_DECLs in the BIND_EXPR_VARS of a
399 BIND_EXPR conform to 7.1.5/3/4 on typedef and alias declarations. */
401 static bool
402 check_constexpr_bind_expr_vars (tree t)
404 gcc_assert (TREE_CODE (t) == BIND_EXPR);
406 for (tree var = BIND_EXPR_VARS (t); var; var = DECL_CHAIN (var))
407 if (TREE_CODE (var) == TYPE_DECL
408 && DECL_IMPLICIT_TYPEDEF_P (var)
409 && !LAMBDA_TYPE_P (TREE_TYPE (var)))
410 return false;
411 return true;
414 /* Subroutine of check_constexpr_ctor_body. */
416 static bool
417 check_constexpr_ctor_body_1 (tree last, tree list)
419 switch (TREE_CODE (list))
421 case DECL_EXPR:
422 if (TREE_CODE (DECL_EXPR_DECL (list)) == USING_DECL)
423 return true;
424 return false;
426 case CLEANUP_POINT_EXPR:
427 return check_constexpr_ctor_body (last, TREE_OPERAND (list, 0),
428 /*complain=*/false);
430 case BIND_EXPR:
431 if (!check_constexpr_bind_expr_vars (list)
432 || !check_constexpr_ctor_body (last, BIND_EXPR_BODY (list),
433 /*complain=*/false))
434 return false;
435 return true;
437 case USING_STMT:
438 case STATIC_ASSERT:
439 return true;
441 default:
442 return false;
446 /* Make sure that there are no statements after LAST in the constructor
447 body represented by LIST. */
449 bool
450 check_constexpr_ctor_body (tree last, tree list, bool complain)
452 /* C++14 doesn't require a constexpr ctor to have an empty body. */
453 if (cxx_dialect >= cxx14)
454 return true;
456 bool ok = true;
457 if (TREE_CODE (list) == STATEMENT_LIST)
459 tree_stmt_iterator i = tsi_last (list);
460 for (; !tsi_end_p (i); tsi_prev (&i))
462 tree t = tsi_stmt (i);
463 if (t == last)
464 break;
465 if (!check_constexpr_ctor_body_1 (last, t))
467 ok = false;
468 break;
472 else if (list != last
473 && !check_constexpr_ctor_body_1 (last, list))
474 ok = false;
475 if (!ok)
477 if (complain)
478 error ("constexpr constructor does not have empty body");
479 DECL_DECLARED_CONSTEXPR_P (current_function_decl) = false;
481 return ok;
484 /* V is a vector of constructor elements built up for the base and member
485 initializers of a constructor for TYPE. They need to be in increasing
486 offset order, which they might not be yet if TYPE has a primary base
487 which is not first in the base-clause or a vptr and at least one base
488 all of which are non-primary. */
490 static vec<constructor_elt, va_gc> *
491 sort_constexpr_mem_initializers (tree type, vec<constructor_elt, va_gc> *v)
493 tree pri = CLASSTYPE_PRIMARY_BINFO (type);
494 tree field_type;
495 unsigned i;
496 constructor_elt *ce;
498 if (pri)
499 field_type = BINFO_TYPE (pri);
500 else if (TYPE_CONTAINS_VPTR_P (type))
501 field_type = vtbl_ptr_type_node;
502 else
503 return v;
505 /* Find the element for the primary base or vptr and move it to the
506 beginning of the vec. */
507 for (i = 0; vec_safe_iterate (v, i, &ce); ++i)
508 if (TREE_TYPE (ce->index) == field_type)
509 break;
511 if (i > 0 && i < vec_safe_length (v))
513 vec<constructor_elt, va_gc> &vref = *v;
514 constructor_elt elt = vref[i];
515 for (; i > 0; --i)
516 vref[i] = vref[i-1];
517 vref[0] = elt;
520 return v;
523 /* Build compile-time evalable representations of member-initializer list
524 for a constexpr constructor. */
526 static tree
527 build_constexpr_constructor_member_initializers (tree type, tree body)
529 vec<constructor_elt, va_gc> *vec = NULL;
530 bool ok = true;
531 while (true)
532 switch (TREE_CODE (body))
534 case MUST_NOT_THROW_EXPR:
535 case EH_SPEC_BLOCK:
536 body = TREE_OPERAND (body, 0);
537 break;
539 case STATEMENT_LIST:
540 for (tree_stmt_iterator i = tsi_start (body);
541 !tsi_end_p (i); tsi_next (&i))
543 body = tsi_stmt (i);
544 if (TREE_CODE (body) == BIND_EXPR)
545 break;
547 break;
549 case BIND_EXPR:
550 body = BIND_EXPR_BODY (body);
551 goto found;
553 default:
554 gcc_unreachable ();
556 found:
557 if (TREE_CODE (body) == CLEANUP_POINT_EXPR)
559 body = TREE_OPERAND (body, 0);
560 if (TREE_CODE (body) == EXPR_STMT)
561 body = TREE_OPERAND (body, 0);
562 if (TREE_CODE (body) == INIT_EXPR
563 && (same_type_ignoring_top_level_qualifiers_p
564 (TREE_TYPE (TREE_OPERAND (body, 0)),
565 current_class_type)))
567 /* Trivial copy. */
568 return TREE_OPERAND (body, 1);
570 ok = build_data_member_initialization (body, &vec);
572 else if (TREE_CODE (body) == STATEMENT_LIST)
574 tree_stmt_iterator i;
575 for (i = tsi_start (body); !tsi_end_p (i); tsi_next (&i))
577 ok = build_data_member_initialization (tsi_stmt (i), &vec);
578 if (!ok)
579 break;
582 else if (TREE_CODE (body) == TRY_BLOCK)
584 error ("body of %<constexpr%> constructor cannot be "
585 "a function-try-block");
586 return error_mark_node;
588 else if (EXPR_P (body))
589 ok = build_data_member_initialization (body, &vec);
590 else
591 gcc_assert (errorcount > 0);
592 if (ok)
594 if (vec_safe_length (vec) > 0)
596 /* In a delegating constructor, return the target. */
597 constructor_elt *ce = &(*vec)[0];
598 if (ce->index == current_class_ptr)
600 body = ce->value;
601 vec_free (vec);
602 return body;
605 vec = sort_constexpr_mem_initializers (type, vec);
606 return build_constructor (type, vec);
608 else
609 return error_mark_node;
612 /* Subroutine of register_constexpr_fundef. BODY is the body of a function
613 declared to be constexpr, or a sub-statement thereof. Returns the
614 return value if suitable, error_mark_node for a statement not allowed in
615 a constexpr function, or NULL_TREE if no return value was found. */
617 static tree
618 constexpr_fn_retval (tree body)
620 switch (TREE_CODE (body))
622 case STATEMENT_LIST:
624 tree_stmt_iterator i;
625 tree expr = NULL_TREE;
626 for (i = tsi_start (body); !tsi_end_p (i); tsi_next (&i))
628 tree s = constexpr_fn_retval (tsi_stmt (i));
629 if (s == error_mark_node)
630 return error_mark_node;
631 else if (s == NULL_TREE)
632 /* Keep iterating. */;
633 else if (expr)
634 /* Multiple return statements. */
635 return error_mark_node;
636 else
637 expr = s;
639 return expr;
642 case RETURN_EXPR:
643 return break_out_target_exprs (TREE_OPERAND (body, 0));
645 case DECL_EXPR:
647 tree decl = DECL_EXPR_DECL (body);
648 if (TREE_CODE (decl) == USING_DECL
649 /* Accept __func__, __FUNCTION__, and __PRETTY_FUNCTION__. */
650 || DECL_ARTIFICIAL (decl))
651 return NULL_TREE;
652 return error_mark_node;
655 case CLEANUP_POINT_EXPR:
656 return constexpr_fn_retval (TREE_OPERAND (body, 0));
658 case BIND_EXPR:
659 if (!check_constexpr_bind_expr_vars (body))
660 return error_mark_node;
661 return constexpr_fn_retval (BIND_EXPR_BODY (body));
663 case USING_STMT:
664 return NULL_TREE;
666 default:
667 return error_mark_node;
671 /* Subroutine of register_constexpr_fundef. BODY is the DECL_SAVED_TREE of
672 FUN; do the necessary transformations to turn it into a single expression
673 that we can store in the hash table. */
675 static tree
676 massage_constexpr_body (tree fun, tree body)
678 if (DECL_CONSTRUCTOR_P (fun))
679 body = build_constexpr_constructor_member_initializers
680 (DECL_CONTEXT (fun), body);
681 else if (cxx_dialect < cxx14)
683 if (TREE_CODE (body) == EH_SPEC_BLOCK)
684 body = EH_SPEC_STMTS (body);
685 if (TREE_CODE (body) == MUST_NOT_THROW_EXPR)
686 body = TREE_OPERAND (body, 0);
687 body = constexpr_fn_retval (body);
689 return body;
692 /* FUN is a constexpr constructor with massaged body BODY. Return true
693 if some bases/fields are uninitialized, and complain if COMPLAIN. */
695 static bool
696 cx_check_missing_mem_inits (tree fun, tree body, bool complain)
698 bool bad;
699 tree field;
700 unsigned i, nelts;
701 tree ctype;
703 if (TREE_CODE (body) != CONSTRUCTOR)
704 return false;
706 nelts = CONSTRUCTOR_NELTS (body);
707 ctype = DECL_CONTEXT (fun);
708 field = TYPE_FIELDS (ctype);
710 if (TREE_CODE (ctype) == UNION_TYPE)
712 if (nelts == 0 && next_initializable_field (field))
714 if (complain)
715 error ("%<constexpr%> constructor for union %qT must "
716 "initialize exactly one non-static data member", ctype);
717 return true;
719 return false;
722 bad = false;
723 for (i = 0; i <= nelts; ++i)
725 tree index;
726 if (i == nelts)
727 index = NULL_TREE;
728 else
730 index = CONSTRUCTOR_ELT (body, i)->index;
731 /* Skip base and vtable inits. */
732 if (TREE_CODE (index) != FIELD_DECL
733 || DECL_ARTIFICIAL (index))
734 continue;
736 for (; field != index; field = DECL_CHAIN (field))
738 tree ftype;
739 if (TREE_CODE (field) != FIELD_DECL
740 || (DECL_C_BIT_FIELD (field) && !DECL_NAME (field))
741 || DECL_ARTIFICIAL (field))
742 continue;
743 ftype = strip_array_types (TREE_TYPE (field));
744 if (type_has_constexpr_default_constructor (ftype))
746 /* It's OK to skip a member with a trivial constexpr ctor.
747 A constexpr ctor that isn't trivial should have been
748 added in by now. */
749 gcc_checking_assert (!TYPE_HAS_COMPLEX_DFLT (ftype)
750 || errorcount != 0);
751 continue;
753 if (!complain)
754 return true;
755 error ("member %qD must be initialized by mem-initializer "
756 "in %<constexpr%> constructor", field);
757 inform (DECL_SOURCE_LOCATION (field), "declared here");
758 bad = true;
760 if (field == NULL_TREE)
761 break;
762 field = DECL_CHAIN (field);
765 return bad;
768 /* We are processing the definition of the constexpr function FUN.
769 Check that its BODY fulfills the propriate requirements and
770 enter it in the constexpr function definition table.
771 For constructor BODY is actually the TREE_LIST of the
772 member-initializer list. */
774 tree
775 register_constexpr_fundef (tree fun, tree body)
777 constexpr_fundef entry;
778 constexpr_fundef **slot;
780 if (!is_valid_constexpr_fn (fun, !DECL_GENERATED_P (fun)))
781 return NULL;
783 tree massaged = massage_constexpr_body (fun, body);
784 if (massaged == NULL_TREE || massaged == error_mark_node)
786 if (!DECL_CONSTRUCTOR_P (fun))
787 error ("body of constexpr function %qD not a return-statement", fun);
788 return NULL;
791 if (!potential_rvalue_constant_expression (massaged))
793 if (!DECL_GENERATED_P (fun))
794 require_potential_rvalue_constant_expression (massaged);
795 return NULL;
798 if (DECL_CONSTRUCTOR_P (fun)
799 && cx_check_missing_mem_inits (fun, massaged, !DECL_GENERATED_P (fun)))
800 return NULL;
802 /* Create the constexpr function table if necessary. */
803 if (constexpr_fundef_table == NULL)
804 constexpr_fundef_table
805 = hash_table<constexpr_fundef_hasher>::create_ggc (101);
807 entry.decl = fun;
808 entry.body = body;
809 slot = constexpr_fundef_table->find_slot (&entry, INSERT);
811 gcc_assert (*slot == NULL);
812 *slot = ggc_alloc<constexpr_fundef> ();
813 **slot = entry;
815 return fun;
818 /* FUN is a non-constexpr function called in a context that requires a
819 constant expression. If it comes from a constexpr template, explain why
820 the instantiation isn't constexpr. */
822 void
823 explain_invalid_constexpr_fn (tree fun)
825 static hash_set<tree> *diagnosed;
826 tree body;
827 location_t save_loc;
828 /* Only diagnose defaulted functions or instantiations. */
829 if (!DECL_DEFAULTED_FN (fun)
830 && !is_instantiation_of_constexpr (fun))
831 return;
832 if (diagnosed == NULL)
833 diagnosed = new hash_set<tree>;
834 if (diagnosed->add (fun))
835 /* Already explained. */
836 return;
838 save_loc = input_location;
839 input_location = DECL_SOURCE_LOCATION (fun);
840 inform (input_location,
841 "%qD is not usable as a constexpr function because:", fun);
842 /* First check the declaration. */
843 if (is_valid_constexpr_fn (fun, true))
845 /* Then if it's OK, the body. */
846 if (!DECL_DECLARED_CONSTEXPR_P (fun))
847 explain_implicit_non_constexpr (fun);
848 else
850 body = massage_constexpr_body (fun, DECL_SAVED_TREE (fun));
851 require_potential_rvalue_constant_expression (body);
852 if (DECL_CONSTRUCTOR_P (fun))
853 cx_check_missing_mem_inits (fun, body, true);
856 input_location = save_loc;
859 /* Objects of this type represent calls to constexpr functions
860 along with the bindings of parameters to their arguments, for
861 the purpose of compile time evaluation. */
863 struct GTY((for_user)) constexpr_call {
864 /* Description of the constexpr function definition. */
865 constexpr_fundef *fundef;
866 /* Parameter bindings environment. A TREE_LIST where each TREE_PURPOSE
867 is a parameter _DECL and the TREE_VALUE is the value of the parameter.
868 Note: This arrangement is made to accommodate the use of
869 iterative_hash_template_arg (see pt.c). If you change this
870 representation, also change the hash calculation in
871 cxx_eval_call_expression. */
872 tree bindings;
873 /* Result of the call.
874 NULL means the call is being evaluated.
875 error_mark_node means that the evaluation was erroneous;
876 otherwise, the actuall value of the call. */
877 tree result;
878 /* The hash of this call; we remember it here to avoid having to
879 recalculate it when expanding the hash table. */
880 hashval_t hash;
883 struct constexpr_call_hasher : ggc_ptr_hash<constexpr_call>
885 static hashval_t hash (constexpr_call *);
886 static bool equal (constexpr_call *, constexpr_call *);
889 /* The constexpr expansion context. CALL is the current function
890 expansion, CTOR is the current aggregate initializer, OBJECT is the
891 object being initialized by CTOR, either a VAR_DECL or a _REF. VALUES
892 is a map of values of variables initialized within the expression. */
894 struct constexpr_ctx {
895 /* The innermost call we're evaluating. */
896 constexpr_call *call;
897 /* Values for any temporaries or local variables within the
898 constant-expression. */
899 hash_map<tree,tree> *values;
900 /* SAVE_EXPRs that we've seen within the current LOOP_EXPR. NULL if we
901 aren't inside a loop. */
902 hash_set<tree> *save_exprs;
903 /* The CONSTRUCTOR we're currently building up for an aggregate
904 initializer. */
905 tree ctor;
906 /* The object we're building the CONSTRUCTOR for. */
907 tree object;
908 /* Whether we should error on a non-constant expression or fail quietly. */
909 bool quiet;
910 /* Whether we are strictly conforming to constant expression rules or
911 trying harder to get a constant value. */
912 bool strict;
915 /* A table of all constexpr calls that have been evaluated by the
916 compiler in this translation unit. */
918 static GTY ((deletable)) hash_table<constexpr_call_hasher> *constexpr_call_table;
920 static tree cxx_eval_constant_expression (const constexpr_ctx *, tree,
921 bool, bool *, bool *, tree * = NULL);
923 /* Compute a hash value for a constexpr call representation. */
925 inline hashval_t
926 constexpr_call_hasher::hash (constexpr_call *info)
928 return info->hash;
931 /* Return true if the objects pointed to by P and Q represent calls
932 to the same constexpr function with the same arguments.
933 Otherwise, return false. */
935 bool
936 constexpr_call_hasher::equal (constexpr_call *lhs, constexpr_call *rhs)
938 tree lhs_bindings;
939 tree rhs_bindings;
940 if (lhs == rhs)
941 return 1;
942 if (!constexpr_fundef_hasher::equal (lhs->fundef, rhs->fundef))
943 return 0;
944 lhs_bindings = lhs->bindings;
945 rhs_bindings = rhs->bindings;
946 while (lhs_bindings != NULL && rhs_bindings != NULL)
948 tree lhs_arg = TREE_VALUE (lhs_bindings);
949 tree rhs_arg = TREE_VALUE (rhs_bindings);
950 gcc_assert (TREE_TYPE (lhs_arg) == TREE_TYPE (rhs_arg));
951 if (!cp_tree_equal (lhs_arg, rhs_arg))
952 return 0;
953 lhs_bindings = TREE_CHAIN (lhs_bindings);
954 rhs_bindings = TREE_CHAIN (rhs_bindings);
956 return lhs_bindings == rhs_bindings;
959 /* Initialize the constexpr call table, if needed. */
961 static void
962 maybe_initialize_constexpr_call_table (void)
964 if (constexpr_call_table == NULL)
965 constexpr_call_table = hash_table<constexpr_call_hasher>::create_ggc (101);
968 /* The representation of a single node in the per-function freelist maintained
969 by FUNDEF_COPIES_TABLE. */
971 struct fundef_copy
973 tree body;
974 tree parms;
975 tree res;
976 fundef_copy *prev;
979 /* During constexpr CALL_EXPR evaluation, to avoid issues with sharing when
980 a function happens to get called recursively, we unshare the callee
981 function's body and evaluate this unshared copy instead of evaluating the
982 original body.
984 FUNDEF_COPIES_TABLE is a per-function freelist of these unshared function
985 copies. The underlying data structure of FUNDEF_COPIES_TABLE is a hash_map
986 that's keyed off of the original FUNCTION_DECL and whose value is the chain
987 of this function's unused copies awaiting reuse. */
989 struct fundef_copies_table_t
991 hash_map<tree, fundef_copy *> *map;
994 static GTY((deletable)) fundef_copies_table_t fundef_copies_table;
996 /* Initialize FUNDEF_COPIES_TABLE if it's not initialized. */
998 static void
999 maybe_initialize_fundef_copies_table ()
1001 if (fundef_copies_table.map == NULL)
1002 fundef_copies_table.map = hash_map<tree, fundef_copy *>::create_ggc (101);
1005 /* Reuse a copy or create a new unshared copy of the function FUN.
1006 Return this copy. */
1008 static fundef_copy *
1009 get_fundef_copy (tree fun)
1011 maybe_initialize_fundef_copies_table ();
1013 fundef_copy *copy;
1014 fundef_copy **slot = &fundef_copies_table.map->get_or_insert (fun, NULL);
1015 if (*slot == NULL)
1017 copy = ggc_alloc<fundef_copy> ();
1018 copy->body = copy_fn (fun, copy->parms, copy->res);
1019 copy->prev = NULL;
1021 else
1023 copy = *slot;
1024 *slot = (*slot)->prev;
1027 return copy;
1030 /* Save the copy COPY of function FUN for later reuse by get_fundef_copy(). */
1032 static void
1033 save_fundef_copy (tree fun, fundef_copy *copy)
1035 fundef_copy **slot = &fundef_copies_table.map->get_or_insert (fun, NULL);
1036 copy->prev = *slot;
1037 *slot = copy;
1040 /* We have an expression tree T that represents a call, either CALL_EXPR
1041 or AGGR_INIT_EXPR. If the call is lexically to a named function,
1042 retrun the _DECL for that function. */
1044 static tree
1045 get_function_named_in_call (tree t)
1047 tree fun = NULL;
1048 switch (TREE_CODE (t))
1050 case CALL_EXPR:
1051 fun = CALL_EXPR_FN (t);
1052 break;
1054 case AGGR_INIT_EXPR:
1055 fun = AGGR_INIT_EXPR_FN (t);
1056 break;
1058 default:
1059 gcc_unreachable();
1060 break;
1062 if (fun && TREE_CODE (fun) == ADDR_EXPR
1063 && TREE_CODE (TREE_OPERAND (fun, 0)) == FUNCTION_DECL)
1064 fun = TREE_OPERAND (fun, 0);
1065 return fun;
1068 /* We have an expression tree T that represents a call, either CALL_EXPR
1069 or AGGR_INIT_EXPR. Return the Nth argument. */
1071 static inline tree
1072 get_nth_callarg (tree t, int n)
1074 switch (TREE_CODE (t))
1076 case CALL_EXPR:
1077 return CALL_EXPR_ARG (t, n);
1079 case AGGR_INIT_EXPR:
1080 return AGGR_INIT_EXPR_ARG (t, n);
1082 default:
1083 gcc_unreachable ();
1084 return NULL;
1088 /* Attempt to evaluate T which represents a call to a builtin function.
1089 We assume here that all builtin functions evaluate to scalar types
1090 represented by _CST nodes. */
1092 static tree
1093 cxx_eval_builtin_function_call (const constexpr_ctx *ctx, tree t, tree fun,
1094 bool lval,
1095 bool *non_constant_p, bool *overflow_p)
1097 const int nargs = call_expr_nargs (t);
1098 tree *args = (tree *) alloca (nargs * sizeof (tree));
1099 tree new_call;
1100 int i;
1102 /* Don't fold __builtin_constant_p within a constexpr function. */
1103 bool bi_const_p = (DECL_FUNCTION_CODE (fun) == BUILT_IN_CONSTANT_P);
1105 if (bi_const_p
1106 && current_function_decl
1107 && DECL_DECLARED_CONSTEXPR_P (current_function_decl))
1109 *non_constant_p = true;
1110 return t;
1113 /* Be permissive for arguments to built-ins; __builtin_constant_p should
1114 return constant false for a non-constant argument. */
1115 constexpr_ctx new_ctx = *ctx;
1116 new_ctx.quiet = true;
1117 bool dummy1 = false, dummy2 = false;
1118 for (i = 0; i < nargs; ++i)
1120 args[i] = cxx_eval_constant_expression (&new_ctx, CALL_EXPR_ARG (t, i),
1121 lval, &dummy1, &dummy2);
1122 if (bi_const_p)
1123 /* For __built_in_constant_p, fold all expressions with constant values
1124 even if they aren't C++ constant-expressions. */
1125 args[i] = cp_fully_fold (args[i]);
1128 bool save_ffbcp = force_folding_builtin_constant_p;
1129 force_folding_builtin_constant_p = true;
1130 new_call = fold_build_call_array_loc (EXPR_LOCATION (t), TREE_TYPE (t),
1131 CALL_EXPR_FN (t), nargs, args);
1132 /* Fold away the NOP_EXPR from fold_builtin_n. */
1133 new_call = fold (new_call);
1134 force_folding_builtin_constant_p = save_ffbcp;
1135 VERIFY_CONSTANT (new_call);
1136 return new_call;
1139 /* TEMP is the constant value of a temporary object of type TYPE. Adjust
1140 the type of the value to match. */
1142 static tree
1143 adjust_temp_type (tree type, tree temp)
1145 if (TREE_TYPE (temp) == type)
1146 return temp;
1147 /* Avoid wrapping an aggregate value in a NOP_EXPR. */
1148 if (TREE_CODE (temp) == CONSTRUCTOR)
1149 return build_constructor (type, CONSTRUCTOR_ELTS (temp));
1150 gcc_assert (scalarish_type_p (type));
1151 return cp_fold_convert (type, temp);
1154 /* Callback for walk_tree used by unshare_constructor. */
1156 static tree
1157 find_constructor (tree *tp, int *walk_subtrees, void *)
1159 if (TYPE_P (*tp))
1160 *walk_subtrees = 0;
1161 if (TREE_CODE (*tp) == CONSTRUCTOR)
1162 return *tp;
1163 return NULL_TREE;
1166 /* If T is a CONSTRUCTOR or an expression that has a CONSTRUCTOR node as a
1167 subexpression, return an unshared copy of T. Otherwise return T. */
1169 static tree
1170 unshare_constructor (tree t)
1172 tree ctor = walk_tree (&t, find_constructor, NULL, NULL);
1173 if (ctor != NULL_TREE)
1174 return unshare_expr (t);
1175 return t;
1178 /* Subroutine of cxx_eval_call_expression.
1179 We are processing a call expression (either CALL_EXPR or
1180 AGGR_INIT_EXPR) in the context of CTX. Evaluate
1181 all arguments and bind their values to correspondings
1182 parameters, making up the NEW_CALL context. */
1184 static void
1185 cxx_bind_parameters_in_call (const constexpr_ctx *ctx, tree t,
1186 constexpr_call *new_call,
1187 bool *non_constant_p, bool *overflow_p,
1188 bool *non_constant_args)
1190 const int nargs = call_expr_nargs (t);
1191 tree fun = new_call->fundef->decl;
1192 tree parms = DECL_ARGUMENTS (fun);
1193 int i;
1194 tree *p = &new_call->bindings;
1195 for (i = 0; i < nargs; ++i)
1197 tree x, arg;
1198 tree type = parms ? TREE_TYPE (parms) : void_type_node;
1199 x = get_nth_callarg (t, i);
1200 /* For member function, the first argument is a pointer to the implied
1201 object. For a constructor, it might still be a dummy object, in
1202 which case we get the real argument from ctx. */
1203 if (i == 0 && DECL_CONSTRUCTOR_P (fun)
1204 && is_dummy_object (x))
1206 x = ctx->object;
1207 x = cp_build_addr_expr (x, tf_warning_or_error);
1209 bool lval = false;
1210 arg = cxx_eval_constant_expression (ctx, x, lval,
1211 non_constant_p, overflow_p);
1212 /* Don't VERIFY_CONSTANT here. */
1213 if (*non_constant_p && ctx->quiet)
1214 return;
1215 /* Just discard ellipsis args after checking their constantitude. */
1216 if (!parms)
1217 continue;
1218 if (*non_constant_p)
1219 /* Don't try to adjust the type of non-constant args. */
1220 goto next;
1222 /* Make sure the binding has the same type as the parm. */
1223 if (TREE_CODE (type) != REFERENCE_TYPE)
1224 arg = adjust_temp_type (type, arg);
1225 if (!TREE_CONSTANT (arg))
1226 *non_constant_args = true;
1227 *p = build_tree_list (parms, arg);
1228 p = &TREE_CHAIN (*p);
1229 next:
1230 parms = TREE_CHAIN (parms);
1234 /* Variables and functions to manage constexpr call expansion context.
1235 These do not need to be marked for PCH or GC. */
1237 /* FIXME remember and print actual constant arguments. */
1238 static vec<tree> call_stack = vNULL;
1239 static int call_stack_tick;
1240 static int last_cx_error_tick;
1242 static bool
1243 push_cx_call_context (tree call)
1245 ++call_stack_tick;
1246 if (!EXPR_HAS_LOCATION (call))
1247 SET_EXPR_LOCATION (call, input_location);
1248 call_stack.safe_push (call);
1249 if (call_stack.length () > (unsigned) max_constexpr_depth)
1250 return false;
1251 return true;
1254 static void
1255 pop_cx_call_context (void)
1257 ++call_stack_tick;
1258 call_stack.pop ();
1261 vec<tree>
1262 cx_error_context (void)
1264 vec<tree> r = vNULL;
1265 if (call_stack_tick != last_cx_error_tick
1266 && !call_stack.is_empty ())
1267 r = call_stack;
1268 last_cx_error_tick = call_stack_tick;
1269 return r;
1272 /* Subroutine of cxx_eval_constant_expression.
1273 Evaluate the call expression tree T in the context of OLD_CALL expression
1274 evaluation. */
1276 static tree
1277 cxx_eval_call_expression (const constexpr_ctx *ctx, tree t,
1278 bool lval,
1279 bool *non_constant_p, bool *overflow_p)
1281 location_t loc = EXPR_LOC_OR_LOC (t, input_location);
1282 tree fun = get_function_named_in_call (t);
1283 constexpr_call new_call = { NULL, NULL, NULL, 0 };
1284 bool depth_ok;
1286 if (fun == NULL_TREE)
1287 switch (CALL_EXPR_IFN (t))
1289 case IFN_UBSAN_NULL:
1290 case IFN_UBSAN_BOUNDS:
1291 case IFN_UBSAN_VPTR:
1292 return void_node;
1293 default:
1294 if (!ctx->quiet)
1295 error_at (loc, "call to internal function");
1296 *non_constant_p = true;
1297 return t;
1300 if (TREE_CODE (fun) != FUNCTION_DECL)
1302 /* Might be a constexpr function pointer. */
1303 fun = cxx_eval_constant_expression (ctx, fun,
1304 /*lval*/false, non_constant_p,
1305 overflow_p);
1306 STRIP_NOPS (fun);
1307 if (TREE_CODE (fun) == ADDR_EXPR)
1308 fun = TREE_OPERAND (fun, 0);
1310 if (TREE_CODE (fun) != FUNCTION_DECL)
1312 if (!ctx->quiet && !*non_constant_p)
1313 error_at (loc, "expression %qE does not designate a constexpr "
1314 "function", fun);
1315 *non_constant_p = true;
1316 return t;
1318 if (DECL_CLONED_FUNCTION_P (fun))
1319 fun = DECL_CLONED_FUNCTION (fun);
1321 if (is_ubsan_builtin_p (fun))
1322 return void_node;
1324 if (is_builtin_fn (fun))
1325 return cxx_eval_builtin_function_call (ctx, t, fun,
1326 lval, non_constant_p, overflow_p);
1327 if (!DECL_DECLARED_CONSTEXPR_P (fun))
1329 if (!ctx->quiet)
1331 error_at (loc, "call to non-constexpr function %qD", fun);
1332 explain_invalid_constexpr_fn (fun);
1334 *non_constant_p = true;
1335 return t;
1338 constexpr_ctx new_ctx = *ctx;
1339 if (DECL_CONSTRUCTOR_P (fun) && !ctx->object
1340 && TREE_CODE (t) == AGGR_INIT_EXPR)
1342 /* We want to have an initialization target for an AGGR_INIT_EXPR.
1343 If we don't already have one in CTX, use the AGGR_INIT_EXPR_SLOT. */
1344 new_ctx.object = AGGR_INIT_EXPR_SLOT (t);
1345 tree ctor = new_ctx.ctor = build_constructor (DECL_CONTEXT (fun), NULL);
1346 CONSTRUCTOR_NO_IMPLICIT_ZERO (ctor) = true;
1347 ctx->values->put (new_ctx.object, ctor);
1348 ctx = &new_ctx;
1351 /* Shortcut trivial constructor/op=. */
1352 if (trivial_fn_p (fun))
1354 tree init = NULL_TREE;
1355 if (call_expr_nargs (t) == 2)
1356 init = convert_from_reference (get_nth_callarg (t, 1));
1357 else if (TREE_CODE (t) == AGGR_INIT_EXPR
1358 && AGGR_INIT_ZERO_FIRST (t))
1359 init = build_zero_init (DECL_CONTEXT (fun), NULL_TREE, false);
1360 if (init)
1362 tree op = get_nth_callarg (t, 0);
1363 if (is_dummy_object (op))
1364 op = ctx->object;
1365 else
1366 op = build1 (INDIRECT_REF, TREE_TYPE (TREE_TYPE (op)), op);
1367 tree set = build2 (MODIFY_EXPR, TREE_TYPE (op), op, init);
1368 return cxx_eval_constant_expression (ctx, set, lval,
1369 non_constant_p, overflow_p);
1373 /* We can't defer instantiating the function any longer. */
1374 if (!DECL_INITIAL (fun)
1375 && DECL_TEMPLOID_INSTANTIATION (fun))
1377 ++function_depth;
1378 instantiate_decl (fun, /*defer_ok*/false, /*expl_inst*/false);
1379 --function_depth;
1382 /* If in direct recursive call, optimize definition search. */
1383 if (ctx && ctx->call && ctx->call->fundef->decl == fun)
1384 new_call.fundef = ctx->call->fundef;
1385 else
1387 new_call.fundef = retrieve_constexpr_fundef (fun);
1388 if (new_call.fundef == NULL || new_call.fundef->body == NULL)
1390 if (!ctx->quiet)
1392 if (DECL_INITIAL (fun) == error_mark_node)
1393 error_at (loc, "%qD called in a constant expression before its "
1394 "definition is complete", fun);
1395 else if (DECL_INITIAL (fun))
1397 /* The definition of fun was somehow unsuitable. */
1398 error_at (loc, "%qD called in a constant expression", fun);
1399 explain_invalid_constexpr_fn (fun);
1401 else
1402 error_at (loc, "%qD used before its definition", fun);
1404 *non_constant_p = true;
1405 return t;
1409 bool non_constant_args = false;
1410 cxx_bind_parameters_in_call (ctx, t, &new_call,
1411 non_constant_p, overflow_p, &non_constant_args);
1412 if (*non_constant_p)
1413 return t;
1415 depth_ok = push_cx_call_context (t);
1417 tree result = NULL_TREE;
1419 constexpr_call *entry = NULL;
1420 if (depth_ok && !non_constant_args)
1422 new_call.hash = iterative_hash_template_arg
1423 (new_call.bindings, constexpr_fundef_hasher::hash (new_call.fundef));
1425 /* If we have seen this call before, we are done. */
1426 maybe_initialize_constexpr_call_table ();
1427 constexpr_call **slot
1428 = constexpr_call_table->find_slot (&new_call, INSERT);
1429 entry = *slot;
1430 if (entry == NULL)
1432 /* We need to keep a pointer to the entry, not just the slot, as the
1433 slot can move in the call to cxx_eval_builtin_function_call. */
1434 *slot = entry = ggc_alloc<constexpr_call> ();
1435 *entry = new_call;
1437 /* Calls which are in progress have their result set to NULL
1438 so that we can detect circular dependencies. */
1439 else if (entry->result == NULL)
1441 if (!ctx->quiet)
1442 error ("call has circular dependency");
1443 *non_constant_p = true;
1444 entry->result = result = error_mark_node;
1446 else
1447 result = entry->result;
1450 if (!depth_ok)
1452 if (!ctx->quiet)
1453 error ("constexpr evaluation depth exceeds maximum of %d (use "
1454 "-fconstexpr-depth= to increase the maximum)",
1455 max_constexpr_depth);
1456 *non_constant_p = true;
1457 result = error_mark_node;
1459 else
1461 if (!result || result == error_mark_node)
1463 gcc_assert (DECL_SAVED_TREE (fun));
1464 tree body, parms, res;
1466 /* Reuse or create a new unshared copy of this function's body. */
1467 fundef_copy *copy = get_fundef_copy (fun);
1468 body = copy->body;
1469 parms = copy->parms;
1470 res = copy->res;
1472 /* Associate the bindings with the remapped parms. */
1473 tree bound = new_call.bindings;
1474 tree remapped = parms;
1475 while (bound)
1477 tree oparm = TREE_PURPOSE (bound);
1478 tree arg = TREE_VALUE (bound);
1479 gcc_assert (DECL_NAME (remapped) == DECL_NAME (oparm));
1480 /* Don't share a CONSTRUCTOR that might be changed. */
1481 arg = unshare_constructor (arg);
1482 ctx->values->put (remapped, arg);
1483 bound = TREE_CHAIN (bound);
1484 remapped = DECL_CHAIN (remapped);
1486 /* Add the RESULT_DECL to the values map, too. */
1487 tree slot = NULL_TREE;
1488 if (DECL_BY_REFERENCE (res))
1490 slot = AGGR_INIT_EXPR_SLOT (t);
1491 tree addr = build_address (slot);
1492 addr = build_nop (TREE_TYPE (res), addr);
1493 ctx->values->put (res, addr);
1494 ctx->values->put (slot, NULL_TREE);
1496 else
1497 ctx->values->put (res, NULL_TREE);
1499 /* Track the callee's evaluated SAVE_EXPRs so that we can forget
1500 their values after the call. */
1501 constexpr_ctx ctx_with_save_exprs = *ctx;
1502 hash_set<tree> save_exprs;
1503 ctx_with_save_exprs.save_exprs = &save_exprs;
1505 tree jump_target = NULL_TREE;
1506 cxx_eval_constant_expression (&ctx_with_save_exprs, body,
1507 lval, non_constant_p, overflow_p,
1508 &jump_target);
1510 if (DECL_CONSTRUCTOR_P (fun))
1511 /* This can be null for a subobject constructor call, in
1512 which case what we care about is the initialization
1513 side-effects rather than the value. We could get at the
1514 value by evaluating *this, but we don't bother; there's
1515 no need to put such a call in the hash table. */
1516 result = lval ? ctx->object : ctx->ctor;
1517 else if (VOID_TYPE_P (TREE_TYPE (res)))
1518 result = void_node;
1519 else
1521 result = *ctx->values->get (slot ? slot : res);
1522 if (result == NULL_TREE && !*non_constant_p)
1524 if (!ctx->quiet)
1525 error ("constexpr call flows off the end "
1526 "of the function");
1527 *non_constant_p = true;
1531 /* Forget the saved values of the callee's SAVE_EXPRs. */
1532 for (hash_set<tree>::iterator iter = save_exprs.begin();
1533 iter != save_exprs.end(); ++iter)
1534 ctx_with_save_exprs.values->remove (*iter);
1536 /* Remove the parms/result from the values map. Is it worth
1537 bothering to do this when the map itself is only live for
1538 one constexpr evaluation? If so, maybe also clear out
1539 other vars from call, maybe in BIND_EXPR handling? */
1540 ctx->values->remove (res);
1541 if (slot)
1542 ctx->values->remove (slot);
1543 for (tree parm = parms; parm; parm = TREE_CHAIN (parm))
1544 ctx->values->remove (parm);
1546 /* Make the unshared function copy we used available for re-use. */
1547 save_fundef_copy (fun, copy);
1550 if (result == error_mark_node)
1551 *non_constant_p = true;
1552 if (*non_constant_p || *overflow_p)
1553 result = error_mark_node;
1554 else if (!result)
1555 result = void_node;
1556 if (entry)
1557 entry->result = result;
1560 pop_cx_call_context ();
1561 return unshare_constructor (result);
1564 /* FIXME speed this up, it's taking 16% of compile time on sieve testcase. */
1566 bool
1567 reduced_constant_expression_p (tree t)
1569 switch (TREE_CODE (t))
1571 case PTRMEM_CST:
1572 /* Even if we can't lower this yet, it's constant. */
1573 return true;
1575 case CONSTRUCTOR:
1576 /* And we need to handle PTRMEM_CST wrapped in a CONSTRUCTOR. */
1577 tree elt; unsigned HOST_WIDE_INT idx;
1578 FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (t), idx, elt)
1579 if (!reduced_constant_expression_p (elt))
1580 return false;
1581 return true;
1583 default:
1584 /* FIXME are we calling this too much? */
1585 return initializer_constant_valid_p (t, TREE_TYPE (t)) != NULL_TREE;
1589 /* Some expressions may have constant operands but are not constant
1590 themselves, such as 1/0. Call this function (or rather, the macro
1591 following it) to check for that condition.
1593 We only call this in places that require an arithmetic constant, not in
1594 places where we might have a non-constant expression that can be a
1595 component of a constant expression, such as the address of a constexpr
1596 variable that might be dereferenced later. */
1598 static bool
1599 verify_constant (tree t, bool allow_non_constant, bool *non_constant_p,
1600 bool *overflow_p)
1602 if (!*non_constant_p && !reduced_constant_expression_p (t))
1604 if (!allow_non_constant)
1605 error ("%q+E is not a constant expression", t);
1606 *non_constant_p = true;
1608 if (TREE_OVERFLOW_P (t))
1610 if (!allow_non_constant)
1612 permerror (input_location, "overflow in constant expression");
1613 /* If we're being permissive (and are in an enforcing
1614 context), ignore the overflow. */
1615 if (flag_permissive)
1616 return *non_constant_p;
1618 *overflow_p = true;
1620 return *non_constant_p;
1623 /* Check whether the shift operation with code CODE and type TYPE on LHS
1624 and RHS is undefined. If it is, give an error with an explanation,
1625 and return true; return false otherwise. */
1627 static bool
1628 cxx_eval_check_shift_p (location_t loc, const constexpr_ctx *ctx,
1629 enum tree_code code, tree type, tree lhs, tree rhs)
1631 if ((code != LSHIFT_EXPR && code != RSHIFT_EXPR)
1632 || TREE_CODE (lhs) != INTEGER_CST
1633 || TREE_CODE (rhs) != INTEGER_CST)
1634 return false;
1636 tree lhstype = TREE_TYPE (lhs);
1637 unsigned HOST_WIDE_INT uprec = TYPE_PRECISION (TREE_TYPE (lhs));
1639 /* [expr.shift] The behavior is undefined if the right operand
1640 is negative, or greater than or equal to the length in bits
1641 of the promoted left operand. */
1642 if (tree_int_cst_sgn (rhs) == -1)
1644 if (!ctx->quiet)
1645 permerror (loc, "right operand of shift expression %q+E is negative",
1646 build2_loc (loc, code, type, lhs, rhs));
1647 return (!flag_permissive || ctx->quiet);
1649 if (compare_tree_int (rhs, uprec) >= 0)
1651 if (!ctx->quiet)
1652 permerror (loc, "right operand of shift expression %q+E is >= than "
1653 "the precision of the left operand",
1654 build2_loc (loc, code, type, lhs, rhs));
1655 return (!flag_permissive || ctx->quiet);
1658 /* The value of E1 << E2 is E1 left-shifted E2 bit positions; [...]
1659 if E1 has a signed type and non-negative value, and E1x2^E2 is
1660 representable in the corresponding unsigned type of the result type,
1661 then that value, converted to the result type, is the resulting value;
1662 otherwise, the behavior is undefined. */
1663 if (code == LSHIFT_EXPR && !TYPE_UNSIGNED (lhstype)
1664 && (cxx_dialect >= cxx11))
1666 if (tree_int_cst_sgn (lhs) == -1)
1668 if (!ctx->quiet)
1669 permerror (loc,
1670 "left operand of shift expression %q+E is negative",
1671 build2_loc (loc, code, type, lhs, rhs));
1672 return (!flag_permissive || ctx->quiet);
1674 /* For signed x << y the following:
1675 (unsigned) x >> ((prec (lhs) - 1) - y)
1676 if > 1, is undefined. The right-hand side of this formula
1677 is the highest bit of the LHS that can be set (starting from 0),
1678 so that the shift doesn't overflow. We then right-shift the LHS
1679 to see whether any other bit is set making the original shift
1680 undefined -- the result is not representable in the corresponding
1681 unsigned type. */
1682 tree t = build_int_cst (unsigned_type_node, uprec - 1);
1683 t = fold_build2 (MINUS_EXPR, unsigned_type_node, t, rhs);
1684 tree ulhs = fold_convert (unsigned_type_for (lhstype), lhs);
1685 t = fold_build2 (RSHIFT_EXPR, TREE_TYPE (ulhs), ulhs, t);
1686 if (tree_int_cst_lt (integer_one_node, t))
1688 if (!ctx->quiet)
1689 permerror (loc, "shift expression %q+E overflows",
1690 build2_loc (loc, code, type, lhs, rhs));
1691 return (!flag_permissive || ctx->quiet);
1694 return false;
1697 /* Subroutine of cxx_eval_constant_expression.
1698 Attempt to reduce the unary expression tree T to a compile time value.
1699 If successful, return the value. Otherwise issue a diagnostic
1700 and return error_mark_node. */
1702 static tree
1703 cxx_eval_unary_expression (const constexpr_ctx *ctx, tree t,
1704 bool /*lval*/,
1705 bool *non_constant_p, bool *overflow_p)
1707 tree r;
1708 tree orig_arg = TREE_OPERAND (t, 0);
1709 tree arg = cxx_eval_constant_expression (ctx, orig_arg, /*lval*/false,
1710 non_constant_p, overflow_p);
1711 VERIFY_CONSTANT (arg);
1712 location_t loc = EXPR_LOCATION (t);
1713 enum tree_code code = TREE_CODE (t);
1714 tree type = TREE_TYPE (t);
1715 r = fold_unary_loc (loc, code, type, arg);
1716 if (r == NULL_TREE)
1718 if (arg == orig_arg)
1719 r = t;
1720 else
1721 r = build1_loc (loc, code, type, arg);
1723 VERIFY_CONSTANT (r);
1724 return r;
1727 /* Subroutine of cxx_eval_constant_expression.
1728 Like cxx_eval_unary_expression, except for binary expressions. */
1730 static tree
1731 cxx_eval_binary_expression (const constexpr_ctx *ctx, tree t,
1732 bool /*lval*/,
1733 bool *non_constant_p, bool *overflow_p)
1735 tree r = NULL_TREE;
1736 tree orig_lhs = TREE_OPERAND (t, 0);
1737 tree orig_rhs = TREE_OPERAND (t, 1);
1738 tree lhs, rhs;
1739 lhs = cxx_eval_constant_expression (ctx, orig_lhs, /*lval*/false,
1740 non_constant_p, overflow_p);
1741 /* Don't VERIFY_CONSTANT here, it's unnecessary and will break pointer
1742 subtraction. */
1743 if (*non_constant_p)
1744 return t;
1745 rhs = cxx_eval_constant_expression (ctx, orig_rhs, /*lval*/false,
1746 non_constant_p, overflow_p);
1747 if (*non_constant_p)
1748 return t;
1750 location_t loc = EXPR_LOCATION (t);
1751 enum tree_code code = TREE_CODE (t);
1752 tree type = TREE_TYPE (t);
1754 if (code == EQ_EXPR || code == NE_EXPR)
1756 bool is_code_eq = (code == EQ_EXPR);
1758 if (TREE_CODE (lhs) == PTRMEM_CST
1759 && TREE_CODE (rhs) == PTRMEM_CST)
1760 r = constant_boolean_node (cp_tree_equal (lhs, rhs) == is_code_eq,
1761 type);
1762 else if ((TREE_CODE (lhs) == PTRMEM_CST
1763 || TREE_CODE (rhs) == PTRMEM_CST)
1764 && (null_member_pointer_value_p (lhs)
1765 || null_member_pointer_value_p (rhs)))
1766 r = constant_boolean_node (!is_code_eq, type);
1769 if (r == NULL_TREE)
1770 r = fold_binary_loc (loc, code, type, lhs, rhs);
1772 if (r == NULL_TREE)
1774 if (lhs == orig_lhs && rhs == orig_rhs)
1775 r = t;
1776 else
1777 r = build2_loc (loc, code, type, lhs, rhs);
1779 else if (cxx_eval_check_shift_p (loc, ctx, code, type, lhs, rhs))
1780 *non_constant_p = true;
1781 /* Don't VERIFY_CONSTANT if this might be dealing with a pointer to
1782 a local array in a constexpr function. */
1783 bool ptr = POINTER_TYPE_P (TREE_TYPE (lhs));
1784 if (!ptr)
1785 VERIFY_CONSTANT (r);
1786 return r;
1789 /* Subroutine of cxx_eval_constant_expression.
1790 Attempt to evaluate condition expressions. Dead branches are not
1791 looked into. */
1793 static tree
1794 cxx_eval_conditional_expression (const constexpr_ctx *ctx, tree t,
1795 bool lval,
1796 bool *non_constant_p, bool *overflow_p,
1797 tree *jump_target)
1799 tree val = cxx_eval_constant_expression (ctx, TREE_OPERAND (t, 0),
1800 /*lval*/false,
1801 non_constant_p, overflow_p);
1802 VERIFY_CONSTANT (val);
1803 /* Don't VERIFY_CONSTANT the other operands. */
1804 if (integer_zerop (val))
1805 return cxx_eval_constant_expression (ctx, TREE_OPERAND (t, 2),
1806 lval,
1807 non_constant_p, overflow_p,
1808 jump_target);
1809 return cxx_eval_constant_expression (ctx, TREE_OPERAND (t, 1),
1810 lval,
1811 non_constant_p, overflow_p,
1812 jump_target);
1815 /* Returns less than, equal to, or greater than zero if KEY is found to be
1816 less than, to match, or to be greater than the constructor_elt's INDEX. */
1818 static int
1819 array_index_cmp (tree key, tree index)
1821 gcc_assert (TREE_CODE (key) == INTEGER_CST);
1823 switch (TREE_CODE (index))
1825 case INTEGER_CST:
1826 return tree_int_cst_compare (key, index);
1827 case RANGE_EXPR:
1829 tree lo = TREE_OPERAND (index, 0);
1830 tree hi = TREE_OPERAND (index, 1);
1831 if (tree_int_cst_lt (key, lo))
1832 return -1;
1833 else if (tree_int_cst_lt (hi, key))
1834 return 1;
1835 else
1836 return 0;
1838 default:
1839 gcc_unreachable ();
1843 /* Returns the index of the constructor_elt of ARY which matches DINDEX, or -1
1844 if none. If INSERT is true, insert a matching element rather than fail. */
1846 static HOST_WIDE_INT
1847 find_array_ctor_elt (tree ary, tree dindex, bool insert = false)
1849 if (tree_int_cst_sgn (dindex) < 0)
1850 return -1;
1852 unsigned HOST_WIDE_INT i = tree_to_uhwi (dindex);
1853 vec<constructor_elt, va_gc> *elts = CONSTRUCTOR_ELTS (ary);
1854 unsigned HOST_WIDE_INT len = vec_safe_length (elts);
1856 unsigned HOST_WIDE_INT end = len;
1857 unsigned HOST_WIDE_INT begin = 0;
1859 /* If the last element of the CONSTRUCTOR has its own index, we can assume
1860 that the same is true of the other elements and index directly. */
1861 if (end > 0)
1863 tree cindex = (*elts)[end-1].index;
1864 if (TREE_CODE (cindex) == INTEGER_CST
1865 && compare_tree_int (cindex, end-1) == 0)
1867 if (i < end)
1868 return i;
1869 else
1870 begin = end;
1874 /* Otherwise, find a matching index by means of a binary search. */
1875 while (begin != end)
1877 unsigned HOST_WIDE_INT middle = (begin + end) / 2;
1878 constructor_elt &elt = (*elts)[middle];
1879 tree idx = elt.index;
1881 int cmp = array_index_cmp (dindex, idx);
1882 if (cmp < 0)
1883 end = middle;
1884 else if (cmp > 0)
1885 begin = middle + 1;
1886 else
1888 if (insert && TREE_CODE (idx) == RANGE_EXPR)
1890 /* We need to split the range. */
1891 constructor_elt e;
1892 tree lo = TREE_OPERAND (idx, 0);
1893 tree hi = TREE_OPERAND (idx, 1);
1894 if (tree_int_cst_lt (lo, dindex))
1896 /* There are still some lower elts; shorten the range. */
1897 tree new_hi = int_const_binop (MINUS_EXPR, dindex,
1898 size_one_node);
1899 if (tree_int_cst_equal (lo, new_hi))
1900 /* Only one element left, no longer a range. */
1901 elt.index = lo;
1902 else
1903 TREE_OPERAND (idx, 1) = new_hi;
1904 /* Append the element we want to insert. */
1905 ++middle;
1906 e.index = dindex;
1907 e.value = unshare_constructor (elt.value);
1908 vec_safe_insert (CONSTRUCTOR_ELTS (ary), middle, e);
1910 else
1911 /* No lower elts, the range elt is now ours. */
1912 elt.index = dindex;
1914 if (tree_int_cst_lt (dindex, hi))
1916 /* There are still some higher elts; append a range. */
1917 tree new_lo = int_const_binop (PLUS_EXPR, dindex,
1918 size_one_node);
1919 if (tree_int_cst_equal (new_lo, hi))
1920 e.index = hi;
1921 else
1922 e.index = build2 (RANGE_EXPR, sizetype, new_lo, hi);
1923 e.value = unshare_constructor (elt.value);
1924 vec_safe_insert (CONSTRUCTOR_ELTS (ary), middle+1, e);
1927 return middle;
1931 if (insert)
1933 constructor_elt e = { dindex, NULL_TREE };
1934 vec_safe_insert (CONSTRUCTOR_ELTS (ary), end, e);
1935 return end;
1938 return -1;
1941 /* Under the control of CTX, issue a detailed diagnostic for
1942 an out-of-bounds subscript INDEX into the expression ARRAY. */
1944 static void
1945 diag_array_subscript (const constexpr_ctx *ctx, tree array, tree index)
1947 if (!ctx->quiet)
1949 tree arraytype = TREE_TYPE (array);
1951 /* Convert the unsigned array subscript to a signed integer to avoid
1952 printing huge numbers for small negative values. */
1953 tree sidx = fold_convert (ssizetype, index);
1954 if (DECL_P (array))
1956 error ("array subscript value %qE is outside the bounds "
1957 "of array %qD of type %qT", sidx, array, arraytype);
1958 inform (DECL_SOURCE_LOCATION (array), "declared here");
1960 else
1961 error ("array subscript value %qE is outside the bounds "
1962 "of array type %qT", sidx, arraytype);
1966 /* Subroutine of cxx_eval_constant_expression.
1967 Attempt to reduce a reference to an array slot. */
1969 static tree
1970 cxx_eval_array_reference (const constexpr_ctx *ctx, tree t,
1971 bool lval,
1972 bool *non_constant_p, bool *overflow_p)
1974 tree oldary = TREE_OPERAND (t, 0);
1975 tree ary = cxx_eval_constant_expression (ctx, oldary,
1976 lval,
1977 non_constant_p, overflow_p);
1978 tree index, oldidx;
1979 HOST_WIDE_INT i;
1980 tree elem_type;
1981 unsigned len, elem_nchars = 1;
1982 if (*non_constant_p)
1983 return t;
1984 oldidx = TREE_OPERAND (t, 1);
1985 index = cxx_eval_constant_expression (ctx, oldidx,
1986 false,
1987 non_constant_p, overflow_p);
1988 VERIFY_CONSTANT (index);
1989 if (lval && ary == oldary && index == oldidx)
1990 return t;
1991 else if (lval)
1992 return build4 (ARRAY_REF, TREE_TYPE (t), ary, index, NULL, NULL);
1993 elem_type = TREE_TYPE (TREE_TYPE (ary));
1994 if (TREE_CODE (ary) == CONSTRUCTOR)
1995 len = CONSTRUCTOR_NELTS (ary);
1996 else if (TREE_CODE (ary) == STRING_CST)
1998 elem_nchars = (TYPE_PRECISION (elem_type)
1999 / TYPE_PRECISION (char_type_node));
2000 len = (unsigned) TREE_STRING_LENGTH (ary) / elem_nchars;
2002 else
2004 /* We can't do anything with other tree codes, so use
2005 VERIFY_CONSTANT to complain and fail. */
2006 VERIFY_CONSTANT (ary);
2007 gcc_unreachable ();
2010 if (!tree_fits_shwi_p (index)
2011 || (i = tree_to_shwi (index)) < 0)
2013 diag_array_subscript (ctx, ary, index);
2014 *non_constant_p = true;
2015 return t;
2018 tree nelts = array_type_nelts_top (TREE_TYPE (ary));
2019 /* For VLAs, the number of elements won't be an integer constant. */
2020 nelts = cxx_eval_constant_expression (ctx, nelts, false, non_constant_p,
2021 overflow_p);
2022 VERIFY_CONSTANT (nelts);
2023 if (!tree_int_cst_lt (index, nelts))
2025 diag_array_subscript (ctx, ary, index);
2026 *non_constant_p = true;
2027 return t;
2030 bool found;
2031 if (TREE_CODE (ary) == CONSTRUCTOR)
2033 HOST_WIDE_INT ix = find_array_ctor_elt (ary, index);
2034 found = (ix >= 0);
2035 if (found)
2036 i = ix;
2038 else
2039 found = (i < len);
2041 if (!found)
2043 if (TREE_CODE (ary) == CONSTRUCTOR
2044 && CONSTRUCTOR_NO_IMPLICIT_ZERO (ary))
2046 /* 'ary' is part of the aggregate initializer we're currently
2047 building; if there's no initializer for this element yet,
2048 that's an error. */
2049 if (!ctx->quiet)
2050 error ("accessing uninitialized array element");
2051 *non_constant_p = true;
2052 return t;
2055 /* If it's within the array bounds but doesn't have an explicit
2056 initializer, it's value-initialized. */
2057 tree val = build_value_init (elem_type, tf_warning_or_error);
2058 return cxx_eval_constant_expression (ctx, val, lval, non_constant_p,
2059 overflow_p);
2062 if (TREE_CODE (ary) == CONSTRUCTOR)
2063 return (*CONSTRUCTOR_ELTS (ary))[i].value;
2064 else if (elem_nchars == 1)
2065 return build_int_cst (cv_unqualified (TREE_TYPE (TREE_TYPE (ary))),
2066 TREE_STRING_POINTER (ary)[i]);
2067 else
2069 tree type = cv_unqualified (TREE_TYPE (TREE_TYPE (ary)));
2070 return native_interpret_expr (type, (const unsigned char *)
2071 TREE_STRING_POINTER (ary)
2072 + i * elem_nchars, elem_nchars);
2074 /* Don't VERIFY_CONSTANT here. */
2077 /* Subroutine of cxx_eval_constant_expression.
2078 Attempt to reduce a field access of a value of class type. */
2080 static tree
2081 cxx_eval_component_reference (const constexpr_ctx *ctx, tree t,
2082 bool lval,
2083 bool *non_constant_p, bool *overflow_p)
2085 unsigned HOST_WIDE_INT i;
2086 tree field;
2087 tree value;
2088 tree part = TREE_OPERAND (t, 1);
2089 tree orig_whole = TREE_OPERAND (t, 0);
2090 tree whole = cxx_eval_constant_expression (ctx, orig_whole,
2091 lval,
2092 non_constant_p, overflow_p);
2093 if (TREE_CODE (whole) == PTRMEM_CST)
2094 whole = cplus_expand_constant (whole);
2095 if (whole == orig_whole)
2096 return t;
2097 if (lval)
2098 return fold_build3 (COMPONENT_REF, TREE_TYPE (t),
2099 whole, part, NULL_TREE);
2100 /* Don't VERIFY_CONSTANT here; we only want to check that we got a
2101 CONSTRUCTOR. */
2102 if (!*non_constant_p && TREE_CODE (whole) != CONSTRUCTOR)
2104 if (!ctx->quiet)
2105 error ("%qE is not a constant expression", orig_whole);
2106 *non_constant_p = true;
2108 if (DECL_MUTABLE_P (part))
2110 if (!ctx->quiet)
2111 error ("mutable %qD is not usable in a constant expression", part);
2112 *non_constant_p = true;
2114 if (*non_constant_p)
2115 return t;
2116 FOR_EACH_CONSTRUCTOR_ELT (CONSTRUCTOR_ELTS (whole), i, field, value)
2118 if (field == part)
2120 if (value)
2121 return value;
2122 else
2123 /* We're in the middle of initializing it. */
2124 break;
2127 if (TREE_CODE (TREE_TYPE (whole)) == UNION_TYPE
2128 && CONSTRUCTOR_NELTS (whole) > 0)
2130 /* DR 1188 says we don't have to deal with this. */
2131 if (!ctx->quiet)
2132 error ("accessing %qD member instead of initialized %qD member in "
2133 "constant expression", part, CONSTRUCTOR_ELT (whole, 0)->index);
2134 *non_constant_p = true;
2135 return t;
2138 /* We only create a CONSTRUCTOR for a subobject when we modify it, so empty
2139 classes never get represented; throw together a value now. */
2140 if (is_really_empty_class (TREE_TYPE (t)))
2141 return build_constructor (TREE_TYPE (t), NULL);
2143 if (CONSTRUCTOR_NO_IMPLICIT_ZERO (whole))
2145 /* 'whole' is part of the aggregate initializer we're currently
2146 building; if there's no initializer for this member yet, that's an
2147 error. */
2148 if (!ctx->quiet)
2149 error ("accessing uninitialized member %qD", part);
2150 *non_constant_p = true;
2151 return t;
2154 /* If there's no explicit init for this field, it's value-initialized. */
2155 value = build_value_init (TREE_TYPE (t), tf_warning_or_error);
2156 return cxx_eval_constant_expression (ctx, value,
2157 lval,
2158 non_constant_p, overflow_p);
2161 /* Subroutine of cxx_eval_constant_expression.
2162 Attempt to reduce a field access of a value of class type that is
2163 expressed as a BIT_FIELD_REF. */
2165 static tree
2166 cxx_eval_bit_field_ref (const constexpr_ctx *ctx, tree t,
2167 bool lval,
2168 bool *non_constant_p, bool *overflow_p)
2170 tree orig_whole = TREE_OPERAND (t, 0);
2171 tree retval, fldval, utype, mask;
2172 bool fld_seen = false;
2173 HOST_WIDE_INT istart, isize;
2174 tree whole = cxx_eval_constant_expression (ctx, orig_whole,
2175 lval,
2176 non_constant_p, overflow_p);
2177 tree start, field, value;
2178 unsigned HOST_WIDE_INT i;
2180 if (whole == orig_whole)
2181 return t;
2182 /* Don't VERIFY_CONSTANT here; we only want to check that we got a
2183 CONSTRUCTOR. */
2184 if (!*non_constant_p
2185 && TREE_CODE (whole) != VECTOR_CST
2186 && TREE_CODE (whole) != CONSTRUCTOR)
2188 if (!ctx->quiet)
2189 error ("%qE is not a constant expression", orig_whole);
2190 *non_constant_p = true;
2192 if (*non_constant_p)
2193 return t;
2195 if (TREE_CODE (whole) == VECTOR_CST)
2196 return fold_ternary (BIT_FIELD_REF, TREE_TYPE (t), whole,
2197 TREE_OPERAND (t, 1), TREE_OPERAND (t, 2));
2199 start = TREE_OPERAND (t, 2);
2200 istart = tree_to_shwi (start);
2201 isize = tree_to_shwi (TREE_OPERAND (t, 1));
2202 utype = TREE_TYPE (t);
2203 if (!TYPE_UNSIGNED (utype))
2204 utype = build_nonstandard_integer_type (TYPE_PRECISION (utype), 1);
2205 retval = build_int_cst (utype, 0);
2206 FOR_EACH_CONSTRUCTOR_ELT (CONSTRUCTOR_ELTS (whole), i, field, value)
2208 tree bitpos = bit_position (field);
2209 if (bitpos == start && DECL_SIZE (field) == TREE_OPERAND (t, 1))
2210 return value;
2211 if (TREE_CODE (TREE_TYPE (field)) == INTEGER_TYPE
2212 && TREE_CODE (value) == INTEGER_CST
2213 && tree_fits_shwi_p (bitpos)
2214 && tree_fits_shwi_p (DECL_SIZE (field)))
2216 HOST_WIDE_INT bit = tree_to_shwi (bitpos);
2217 HOST_WIDE_INT sz = tree_to_shwi (DECL_SIZE (field));
2218 HOST_WIDE_INT shift;
2219 if (bit >= istart && bit + sz <= istart + isize)
2221 fldval = fold_convert (utype, value);
2222 mask = build_int_cst_type (utype, -1);
2223 mask = fold_build2 (LSHIFT_EXPR, utype, mask,
2224 size_int (TYPE_PRECISION (utype) - sz));
2225 mask = fold_build2 (RSHIFT_EXPR, utype, mask,
2226 size_int (TYPE_PRECISION (utype) - sz));
2227 fldval = fold_build2 (BIT_AND_EXPR, utype, fldval, mask);
2228 shift = bit - istart;
2229 if (BYTES_BIG_ENDIAN)
2230 shift = TYPE_PRECISION (utype) - shift - sz;
2231 fldval = fold_build2 (LSHIFT_EXPR, utype, fldval,
2232 size_int (shift));
2233 retval = fold_build2 (BIT_IOR_EXPR, utype, retval, fldval);
2234 fld_seen = true;
2238 if (fld_seen)
2239 return fold_convert (TREE_TYPE (t), retval);
2240 gcc_unreachable ();
2241 return error_mark_node;
2244 /* Subroutine of cxx_eval_constant_expression.
2245 Evaluate a short-circuited logical expression T in the context
2246 of a given constexpr CALL. BAILOUT_VALUE is the value for
2247 early return. CONTINUE_VALUE is used here purely for
2248 sanity check purposes. */
2250 static tree
2251 cxx_eval_logical_expression (const constexpr_ctx *ctx, tree t,
2252 tree bailout_value, tree continue_value,
2253 bool lval,
2254 bool *non_constant_p, bool *overflow_p)
2256 tree r;
2257 tree lhs = cxx_eval_constant_expression (ctx, TREE_OPERAND (t, 0),
2258 lval,
2259 non_constant_p, overflow_p);
2260 VERIFY_CONSTANT (lhs);
2261 if (tree_int_cst_equal (lhs, bailout_value))
2262 return lhs;
2263 gcc_assert (tree_int_cst_equal (lhs, continue_value));
2264 r = cxx_eval_constant_expression (ctx, TREE_OPERAND (t, 1),
2265 lval, non_constant_p,
2266 overflow_p);
2267 VERIFY_CONSTANT (r);
2268 return r;
2271 /* REF is a COMPONENT_REF designating a particular field. V is a vector of
2272 CONSTRUCTOR elements to initialize (part of) an object containing that
2273 field. Return a pointer to the constructor_elt corresponding to the
2274 initialization of the field. */
2276 static constructor_elt *
2277 base_field_constructor_elt (vec<constructor_elt, va_gc> *v, tree ref)
2279 tree aggr = TREE_OPERAND (ref, 0);
2280 tree field = TREE_OPERAND (ref, 1);
2281 HOST_WIDE_INT i;
2282 constructor_elt *ce;
2284 gcc_assert (TREE_CODE (ref) == COMPONENT_REF);
2286 if (TREE_CODE (aggr) == COMPONENT_REF)
2288 constructor_elt *base_ce
2289 = base_field_constructor_elt (v, aggr);
2290 v = CONSTRUCTOR_ELTS (base_ce->value);
2293 for (i = 0; vec_safe_iterate (v, i, &ce); ++i)
2294 if (ce->index == field)
2295 return ce;
2297 gcc_unreachable ();
2298 return NULL;
2301 /* Some of the expressions fed to the constexpr mechanism are calls to
2302 constructors, which have type void. In that case, return the type being
2303 initialized by the constructor. */
2305 static tree
2306 initialized_type (tree t)
2308 if (TYPE_P (t))
2309 return t;
2310 tree type = cv_unqualified (TREE_TYPE (t));
2311 if (TREE_CODE (t) == CALL_EXPR || TREE_CODE (t) == AGGR_INIT_EXPR)
2313 /* A constructor call has void type, so we need to look deeper. */
2314 tree fn = get_function_named_in_call (t);
2315 if (fn && TREE_CODE (fn) == FUNCTION_DECL
2316 && DECL_CXX_CONSTRUCTOR_P (fn))
2317 type = DECL_CONTEXT (fn);
2319 return type;
2322 /* We're about to initialize element INDEX of an array or class from VALUE.
2323 Set up NEW_CTX appropriately by adjusting .object to refer to the
2324 subobject and creating a new CONSTRUCTOR if the element is itself
2325 a class or array. */
2327 static void
2328 init_subob_ctx (const constexpr_ctx *ctx, constexpr_ctx &new_ctx,
2329 tree index, tree &value)
2331 new_ctx = *ctx;
2333 if (index && TREE_CODE (index) != INTEGER_CST
2334 && TREE_CODE (index) != FIELD_DECL)
2335 /* This won't have an element in the new CONSTRUCTOR. */
2336 return;
2338 tree type = initialized_type (value);
2339 if (!AGGREGATE_TYPE_P (type) && !VECTOR_TYPE_P (type))
2340 /* A non-aggregate member doesn't get its own CONSTRUCTOR. */
2341 return;
2343 /* The sub-aggregate initializer might contain a placeholder;
2344 update object to refer to the subobject and ctor to refer to
2345 the (newly created) sub-initializer. */
2346 if (ctx->object)
2347 new_ctx.object = build_ctor_subob_ref (index, type, ctx->object);
2348 tree elt = build_constructor (type, NULL);
2349 CONSTRUCTOR_NO_IMPLICIT_ZERO (elt) = true;
2350 new_ctx.ctor = elt;
2352 if (TREE_CODE (value) == TARGET_EXPR)
2353 /* Avoid creating another CONSTRUCTOR when we expand the TARGET_EXPR. */
2354 value = TARGET_EXPR_INITIAL (value);
2357 /* We're about to process an initializer for a class or array TYPE. Make
2358 sure that CTX is set up appropriately. */
2360 static void
2361 verify_ctor_sanity (const constexpr_ctx *ctx, tree type)
2363 /* We don't bother building a ctor for an empty base subobject. */
2364 if (is_empty_class (type))
2365 return;
2367 /* We're in the middle of an initializer that might involve placeholders;
2368 our caller should have created a CONSTRUCTOR for us to put the
2369 initializer into. We will either return that constructor or T. */
2370 gcc_assert (ctx->ctor);
2371 gcc_assert (same_type_ignoring_top_level_qualifiers_p
2372 (type, TREE_TYPE (ctx->ctor)));
2373 /* We used to check that ctx->ctor was empty, but that isn't the case when
2374 the object is zero-initialized before calling the constructor. */
2375 if (ctx->object)
2376 gcc_assert (same_type_ignoring_top_level_qualifiers_p
2377 (type, TREE_TYPE (ctx->object)));
2378 gcc_assert (!ctx->object || !DECL_P (ctx->object)
2379 || *(ctx->values->get (ctx->object)) == ctx->ctor);
2382 /* Subroutine of cxx_eval_constant_expression.
2383 The expression tree T denotes a C-style array or a C-style
2384 aggregate. Reduce it to a constant expression. */
2386 static tree
2387 cxx_eval_bare_aggregate (const constexpr_ctx *ctx, tree t,
2388 bool lval,
2389 bool *non_constant_p, bool *overflow_p)
2391 vec<constructor_elt, va_gc> *v = CONSTRUCTOR_ELTS (t);
2392 bool changed = false;
2393 gcc_assert (!BRACE_ENCLOSED_INITIALIZER_P (t));
2394 tree type = TREE_TYPE (t);
2396 constexpr_ctx new_ctx;
2397 if (TYPE_PTRMEMFUNC_P (type) || VECTOR_TYPE_P (type))
2399 /* We don't really need the ctx->ctor business for a PMF or
2400 vector, but it's simpler to use the same code. */
2401 new_ctx = *ctx;
2402 new_ctx.ctor = build_constructor (type, NULL);
2403 new_ctx.object = NULL_TREE;
2404 ctx = &new_ctx;
2406 verify_ctor_sanity (ctx, type);
2407 vec<constructor_elt, va_gc> **p = &CONSTRUCTOR_ELTS (ctx->ctor);
2408 vec_alloc (*p, vec_safe_length (v));
2410 unsigned i;
2411 tree index, value;
2412 bool constant_p = true;
2413 bool side_effects_p = false;
2414 FOR_EACH_CONSTRUCTOR_ELT (v, i, index, value)
2416 tree orig_value = value;
2417 init_subob_ctx (ctx, new_ctx, index, value);
2418 if (new_ctx.ctor != ctx->ctor)
2419 /* If we built a new CONSTRUCTOR, attach it now so that other
2420 initializers can refer to it. */
2421 CONSTRUCTOR_APPEND_ELT (*p, index, new_ctx.ctor);
2422 tree elt = cxx_eval_constant_expression (&new_ctx, value,
2423 lval,
2424 non_constant_p, overflow_p);
2425 /* Don't VERIFY_CONSTANT here. */
2426 if (ctx->quiet && *non_constant_p)
2427 break;
2428 if (elt != orig_value)
2429 changed = true;
2431 if (!TREE_CONSTANT (elt))
2432 constant_p = false;
2433 if (TREE_SIDE_EFFECTS (elt))
2434 side_effects_p = true;
2435 if (index && TREE_CODE (index) == COMPONENT_REF)
2437 /* This is an initialization of a vfield inside a base
2438 subaggregate that we already initialized; push this
2439 initialization into the previous initialization. */
2440 constructor_elt *inner = base_field_constructor_elt (*p, index);
2441 inner->value = elt;
2442 changed = true;
2444 else if (index
2445 && (TREE_CODE (index) == NOP_EXPR
2446 || TREE_CODE (index) == POINTER_PLUS_EXPR))
2448 /* This is an initializer for an empty base; now that we've
2449 checked that it's constant, we can ignore it. */
2450 gcc_assert (is_empty_class (TREE_TYPE (TREE_TYPE (index))));
2451 changed = true;
2453 else if (new_ctx.ctor != ctx->ctor)
2455 /* We appended this element above; update the value. */
2456 gcc_assert ((*p)->last().index == index);
2457 (*p)->last().value = elt;
2459 else
2460 CONSTRUCTOR_APPEND_ELT (*p, index, elt);
2462 if (*non_constant_p || !changed)
2463 return t;
2464 t = ctx->ctor;
2465 /* We're done building this CONSTRUCTOR, so now we can interpret an
2466 element without an explicit initializer as value-initialized. */
2467 CONSTRUCTOR_NO_IMPLICIT_ZERO (t) = false;
2468 TREE_CONSTANT (t) = constant_p;
2469 TREE_SIDE_EFFECTS (t) = side_effects_p;
2470 if (VECTOR_TYPE_P (type))
2471 t = fold (t);
2472 return t;
2475 /* Subroutine of cxx_eval_constant_expression.
2476 The expression tree T is a VEC_INIT_EXPR which denotes the desired
2477 initialization of a non-static data member of array type. Reduce it to a
2478 CONSTRUCTOR.
2480 Note that apart from value-initialization (when VALUE_INIT is true),
2481 this is only intended to support value-initialization and the
2482 initializations done by defaulted constructors for classes with
2483 non-static data members of array type. In this case, VEC_INIT_EXPR_INIT
2484 will either be NULL_TREE for the default constructor, or a COMPONENT_REF
2485 for the copy/move constructor. */
2487 static tree
2488 cxx_eval_vec_init_1 (const constexpr_ctx *ctx, tree atype, tree init,
2489 bool value_init, bool lval,
2490 bool *non_constant_p, bool *overflow_p)
2492 tree elttype = TREE_TYPE (atype);
2493 unsigned HOST_WIDE_INT max = tree_to_uhwi (array_type_nelts_top (atype));
2494 verify_ctor_sanity (ctx, atype);
2495 vec<constructor_elt, va_gc> **p = &CONSTRUCTOR_ELTS (ctx->ctor);
2496 vec_alloc (*p, max + 1);
2497 bool pre_init = false;
2498 unsigned HOST_WIDE_INT i;
2500 /* For the default constructor, build up a call to the default
2501 constructor of the element type. We only need to handle class types
2502 here, as for a constructor to be constexpr, all members must be
2503 initialized, which for a defaulted default constructor means they must
2504 be of a class type with a constexpr default constructor. */
2505 if (TREE_CODE (elttype) == ARRAY_TYPE)
2506 /* We only do this at the lowest level. */;
2507 else if (value_init)
2509 init = build_value_init (elttype, tf_warning_or_error);
2510 pre_init = true;
2512 else if (!init)
2514 vec<tree, va_gc> *argvec = make_tree_vector ();
2515 init = build_special_member_call (NULL_TREE, complete_ctor_identifier,
2516 &argvec, elttype, LOOKUP_NORMAL,
2517 tf_warning_or_error);
2518 release_tree_vector (argvec);
2519 init = build_aggr_init_expr (TREE_TYPE (init), init);
2520 pre_init = true;
2523 for (i = 0; i < max; ++i)
2525 tree idx = build_int_cst (size_type_node, i);
2526 tree eltinit;
2527 bool reuse = false;
2528 constexpr_ctx new_ctx;
2529 init_subob_ctx (ctx, new_ctx, idx, pre_init ? init : elttype);
2530 if (new_ctx.ctor != ctx->ctor)
2531 CONSTRUCTOR_APPEND_ELT (*p, idx, new_ctx.ctor);
2532 if (TREE_CODE (elttype) == ARRAY_TYPE)
2534 /* A multidimensional array; recurse. */
2535 if (value_init || init == NULL_TREE)
2537 eltinit = NULL_TREE;
2538 reuse = i == 0;
2540 else
2541 eltinit = cp_build_array_ref (input_location, init, idx,
2542 tf_warning_or_error);
2543 eltinit = cxx_eval_vec_init_1 (&new_ctx, elttype, eltinit, value_init,
2544 lval,
2545 non_constant_p, overflow_p);
2547 else if (pre_init)
2549 /* Initializing an element using value or default initialization
2550 we just pre-built above. */
2551 eltinit = cxx_eval_constant_expression (&new_ctx, init, lval,
2552 non_constant_p, overflow_p);
2553 reuse = i == 0;
2555 else
2557 /* Copying an element. */
2558 gcc_assert (same_type_ignoring_top_level_qualifiers_p
2559 (atype, TREE_TYPE (init)));
2560 eltinit = cp_build_array_ref (input_location, init, idx,
2561 tf_warning_or_error);
2562 if (!real_lvalue_p (init))
2563 eltinit = move (eltinit);
2564 eltinit = force_rvalue (eltinit, tf_warning_or_error);
2565 eltinit = (cxx_eval_constant_expression
2566 (&new_ctx, eltinit, lval,
2567 non_constant_p, overflow_p));
2569 if (*non_constant_p && !ctx->quiet)
2570 break;
2571 if (new_ctx.ctor != ctx->ctor)
2573 /* We appended this element above; update the value. */
2574 gcc_assert ((*p)->last().index == idx);
2575 (*p)->last().value = eltinit;
2577 else
2578 CONSTRUCTOR_APPEND_ELT (*p, idx, eltinit);
2579 /* Reuse the result of cxx_eval_constant_expression call
2580 from the first iteration to all others if it is a constant
2581 initializer that doesn't require relocations. */
2582 if (reuse
2583 && max > 1
2584 && (initializer_constant_valid_p (eltinit, TREE_TYPE (eltinit))
2585 == null_pointer_node))
2587 if (new_ctx.ctor != ctx->ctor)
2588 eltinit = new_ctx.ctor;
2589 for (i = 1; i < max; ++i)
2591 idx = build_int_cst (size_type_node, i);
2592 CONSTRUCTOR_APPEND_ELT (*p, idx, unshare_constructor (eltinit));
2594 break;
2598 if (!*non_constant_p)
2600 init = ctx->ctor;
2601 CONSTRUCTOR_NO_IMPLICIT_ZERO (init) = false;
2603 return init;
2606 static tree
2607 cxx_eval_vec_init (const constexpr_ctx *ctx, tree t,
2608 bool lval,
2609 bool *non_constant_p, bool *overflow_p)
2611 tree atype = TREE_TYPE (t);
2612 tree init = VEC_INIT_EXPR_INIT (t);
2613 tree r = cxx_eval_vec_init_1 (ctx, atype, init,
2614 VEC_INIT_EXPR_VALUE_INIT (t),
2615 lval, non_constant_p, overflow_p);
2616 if (*non_constant_p)
2617 return t;
2618 else
2619 return r;
2622 /* A less strict version of fold_indirect_ref_1, which requires cv-quals to
2623 match. We want to be less strict for simple *& folding; if we have a
2624 non-const temporary that we access through a const pointer, that should
2625 work. We handle this here rather than change fold_indirect_ref_1
2626 because we're dealing with things like ADDR_EXPR of INTEGER_CST which
2627 don't really make sense outside of constant expression evaluation. Also
2628 we want to allow folding to COMPONENT_REF, which could cause trouble
2629 with TBAA in fold_indirect_ref_1.
2631 Try to keep this function synced with fold_indirect_ref_1. */
2633 static tree
2634 cxx_fold_indirect_ref (location_t loc, tree type, tree op0, bool *empty_base)
2636 tree sub, subtype;
2638 sub = op0;
2639 STRIP_NOPS (sub);
2640 subtype = TREE_TYPE (sub);
2641 if (!POINTER_TYPE_P (subtype))
2642 return NULL_TREE;
2644 if (TREE_CODE (sub) == ADDR_EXPR)
2646 tree op = TREE_OPERAND (sub, 0);
2647 tree optype = TREE_TYPE (op);
2649 /* *&CONST_DECL -> to the value of the const decl. */
2650 if (TREE_CODE (op) == CONST_DECL)
2651 return DECL_INITIAL (op);
2652 /* *&p => p; make sure to handle *&"str"[cst] here. */
2653 if (same_type_ignoring_top_level_qualifiers_p (optype, type)
2654 /* Also handle the case where the desired type is an array of unknown
2655 bounds because the variable has had its bounds deduced since the
2656 ADDR_EXPR was created. */
2657 || (TREE_CODE (type) == ARRAY_TYPE
2658 && TREE_CODE (optype) == ARRAY_TYPE
2659 && TYPE_DOMAIN (type) == NULL_TREE
2660 && same_type_ignoring_top_level_qualifiers_p (TREE_TYPE (optype),
2661 TREE_TYPE (type))))
2663 tree fop = fold_read_from_constant_string (op);
2664 if (fop)
2665 return fop;
2666 else
2667 return op;
2669 /* *(foo *)&fooarray => fooarray[0] */
2670 else if (TREE_CODE (optype) == ARRAY_TYPE
2671 && (same_type_ignoring_top_level_qualifiers_p
2672 (type, TREE_TYPE (optype))))
2674 tree type_domain = TYPE_DOMAIN (optype);
2675 tree min_val = size_zero_node;
2676 if (type_domain && TYPE_MIN_VALUE (type_domain))
2677 min_val = TYPE_MIN_VALUE (type_domain);
2678 return build4_loc (loc, ARRAY_REF, type, op, min_val,
2679 NULL_TREE, NULL_TREE);
2681 /* *(foo *)&complexfoo => __real__ complexfoo */
2682 else if (TREE_CODE (optype) == COMPLEX_TYPE
2683 && (same_type_ignoring_top_level_qualifiers_p
2684 (type, TREE_TYPE (optype))))
2685 return fold_build1_loc (loc, REALPART_EXPR, type, op);
2686 /* *(foo *)&vectorfoo => BIT_FIELD_REF<vectorfoo,...> */
2687 else if (VECTOR_TYPE_P (optype)
2688 && (same_type_ignoring_top_level_qualifiers_p
2689 (type, TREE_TYPE (optype))))
2691 tree part_width = TYPE_SIZE (type);
2692 tree index = bitsize_int (0);
2693 return fold_build3_loc (loc, BIT_FIELD_REF, type, op, part_width, index);
2695 /* Also handle conversion to an empty base class, which
2696 is represented with a NOP_EXPR. */
2697 else if (is_empty_class (type)
2698 && CLASS_TYPE_P (optype)
2699 && DERIVED_FROM_P (type, optype))
2701 *empty_base = true;
2702 return op;
2704 /* *(foo *)&struct_with_foo_field => COMPONENT_REF */
2705 else if (RECORD_OR_UNION_TYPE_P (optype))
2707 tree field = TYPE_FIELDS (optype);
2708 for (; field; field = DECL_CHAIN (field))
2709 if (TREE_CODE (field) == FIELD_DECL
2710 && integer_zerop (byte_position (field))
2711 && (same_type_ignoring_top_level_qualifiers_p
2712 (TREE_TYPE (field), type)))
2714 return fold_build3 (COMPONENT_REF, type, op, field, NULL_TREE);
2715 break;
2719 else if (TREE_CODE (sub) == POINTER_PLUS_EXPR
2720 && TREE_CODE (TREE_OPERAND (sub, 1)) == INTEGER_CST)
2722 tree op00 = TREE_OPERAND (sub, 0);
2723 tree op01 = TREE_OPERAND (sub, 1);
2725 STRIP_NOPS (op00);
2726 if (TREE_CODE (op00) == ADDR_EXPR)
2728 tree op00type;
2729 op00 = TREE_OPERAND (op00, 0);
2730 op00type = TREE_TYPE (op00);
2732 /* ((foo*)&vectorfoo)[1] => BIT_FIELD_REF<vectorfoo,...> */
2733 if (VECTOR_TYPE_P (op00type)
2734 && (same_type_ignoring_top_level_qualifiers_p
2735 (type, TREE_TYPE (op00type))))
2737 HOST_WIDE_INT offset = tree_to_shwi (op01);
2738 tree part_width = TYPE_SIZE (type);
2739 unsigned HOST_WIDE_INT part_widthi = tree_to_shwi (part_width)/BITS_PER_UNIT;
2740 unsigned HOST_WIDE_INT indexi = offset * BITS_PER_UNIT;
2741 tree index = bitsize_int (indexi);
2743 if (offset / part_widthi < TYPE_VECTOR_SUBPARTS (op00type))
2744 return fold_build3_loc (loc,
2745 BIT_FIELD_REF, type, op00,
2746 part_width, index);
2749 /* ((foo*)&complexfoo)[1] => __imag__ complexfoo */
2750 else if (TREE_CODE (op00type) == COMPLEX_TYPE
2751 && (same_type_ignoring_top_level_qualifiers_p
2752 (type, TREE_TYPE (op00type))))
2754 tree size = TYPE_SIZE_UNIT (type);
2755 if (tree_int_cst_equal (size, op01))
2756 return fold_build1_loc (loc, IMAGPART_EXPR, type, op00);
2758 /* ((foo *)&fooarray)[1] => fooarray[1] */
2759 else if (TREE_CODE (op00type) == ARRAY_TYPE
2760 && (same_type_ignoring_top_level_qualifiers_p
2761 (type, TREE_TYPE (op00type))))
2763 tree type_domain = TYPE_DOMAIN (op00type);
2764 tree min_val = size_zero_node;
2765 if (type_domain && TYPE_MIN_VALUE (type_domain))
2766 min_val = TYPE_MIN_VALUE (type_domain);
2767 op01 = size_binop_loc (loc, EXACT_DIV_EXPR, op01,
2768 TYPE_SIZE_UNIT (type));
2769 op01 = size_binop_loc (loc, PLUS_EXPR, op01, min_val);
2770 return build4_loc (loc, ARRAY_REF, type, op00, op01,
2771 NULL_TREE, NULL_TREE);
2773 /* Also handle conversion to an empty base class, which
2774 is represented with a NOP_EXPR. */
2775 else if (is_empty_class (type)
2776 && CLASS_TYPE_P (op00type)
2777 && DERIVED_FROM_P (type, op00type))
2779 *empty_base = true;
2780 return op00;
2782 /* ((foo *)&struct_with_foo_field)[1] => COMPONENT_REF */
2783 else if (RECORD_OR_UNION_TYPE_P (op00type))
2785 tree field = TYPE_FIELDS (op00type);
2786 for (; field; field = DECL_CHAIN (field))
2787 if (TREE_CODE (field) == FIELD_DECL
2788 && tree_int_cst_equal (byte_position (field), op01)
2789 && (same_type_ignoring_top_level_qualifiers_p
2790 (TREE_TYPE (field), type)))
2792 return fold_build3 (COMPONENT_REF, type, op00,
2793 field, NULL_TREE);
2794 break;
2799 /* *(foo *)fooarrptr => (*fooarrptr)[0] */
2800 else if (TREE_CODE (TREE_TYPE (subtype)) == ARRAY_TYPE
2801 && (same_type_ignoring_top_level_qualifiers_p
2802 (type, TREE_TYPE (TREE_TYPE (subtype)))))
2804 tree type_domain;
2805 tree min_val = size_zero_node;
2806 tree newsub = cxx_fold_indirect_ref (loc, TREE_TYPE (subtype), sub, NULL);
2807 if (newsub)
2808 sub = newsub;
2809 else
2810 sub = build1_loc (loc, INDIRECT_REF, TREE_TYPE (subtype), sub);
2811 type_domain = TYPE_DOMAIN (TREE_TYPE (sub));
2812 if (type_domain && TYPE_MIN_VALUE (type_domain))
2813 min_val = TYPE_MIN_VALUE (type_domain);
2814 return build4_loc (loc, ARRAY_REF, type, sub, min_val, NULL_TREE,
2815 NULL_TREE);
2818 return NULL_TREE;
2821 static tree
2822 cxx_eval_indirect_ref (const constexpr_ctx *ctx, tree t,
2823 bool lval,
2824 bool *non_constant_p, bool *overflow_p)
2826 tree orig_op0 = TREE_OPERAND (t, 0);
2827 bool empty_base = false;
2829 /* We can handle a MEM_REF like an INDIRECT_REF, if MEM_REF's second
2830 operand is an integer-zero. Otherwise reject the MEM_REF for now. */
2832 if (TREE_CODE (t) == MEM_REF
2833 && (!TREE_OPERAND (t, 1) || !integer_zerop (TREE_OPERAND (t, 1))))
2835 gcc_assert (ctx->quiet);
2836 *non_constant_p = true;
2837 return t;
2840 /* First try to simplify it directly. */
2841 tree r = cxx_fold_indirect_ref (EXPR_LOCATION (t), TREE_TYPE (t), orig_op0,
2842 &empty_base);
2843 if (!r)
2845 /* If that didn't work, evaluate the operand first. */
2846 tree op0 = cxx_eval_constant_expression (ctx, orig_op0,
2847 /*lval*/false, non_constant_p,
2848 overflow_p);
2849 /* Don't VERIFY_CONSTANT here. */
2850 if (*non_constant_p)
2851 return t;
2853 r = cxx_fold_indirect_ref (EXPR_LOCATION (t), TREE_TYPE (t), op0,
2854 &empty_base);
2855 if (r == NULL_TREE)
2857 /* We couldn't fold to a constant value. Make sure it's not
2858 something we should have been able to fold. */
2859 tree sub = op0;
2860 STRIP_NOPS (sub);
2861 if (TREE_CODE (sub) == ADDR_EXPR)
2863 gcc_assert (!same_type_ignoring_top_level_qualifiers_p
2864 (TREE_TYPE (TREE_TYPE (sub)), TREE_TYPE (t)));
2865 /* DR 1188 says we don't have to deal with this. */
2866 if (!ctx->quiet)
2867 error ("accessing value of %qE through a %qT glvalue in a "
2868 "constant expression", build_fold_indirect_ref (sub),
2869 TREE_TYPE (t));
2870 *non_constant_p = true;
2871 return t;
2874 if (lval && op0 != orig_op0)
2875 return build1 (INDIRECT_REF, TREE_TYPE (t), op0);
2876 if (!lval)
2877 VERIFY_CONSTANT (t);
2878 return t;
2882 r = cxx_eval_constant_expression (ctx, r,
2883 lval, non_constant_p, overflow_p);
2884 if (*non_constant_p)
2885 return t;
2887 /* If we're pulling out the value of an empty base, make sure
2888 that the whole object is constant and then return an empty
2889 CONSTRUCTOR. */
2890 if (empty_base && !lval)
2892 VERIFY_CONSTANT (r);
2893 r = build_constructor (TREE_TYPE (t), NULL);
2894 TREE_CONSTANT (r) = true;
2897 return r;
2900 /* Complain about R, a VAR_DECL, not being usable in a constant expression.
2901 Shared between potential_constant_expression and
2902 cxx_eval_constant_expression. */
2904 static void
2905 non_const_var_error (tree r)
2907 tree type = TREE_TYPE (r);
2908 error ("the value of %qD is not usable in a constant "
2909 "expression", r);
2910 /* Avoid error cascade. */
2911 if (DECL_INITIAL (r) == error_mark_node)
2912 return;
2913 if (DECL_DECLARED_CONSTEXPR_P (r))
2914 inform (DECL_SOURCE_LOCATION (r),
2915 "%qD used in its own initializer", r);
2916 else if (INTEGRAL_OR_ENUMERATION_TYPE_P (type))
2918 if (!CP_TYPE_CONST_P (type))
2919 inform (DECL_SOURCE_LOCATION (r),
2920 "%q#D is not const", r);
2921 else if (CP_TYPE_VOLATILE_P (type))
2922 inform (DECL_SOURCE_LOCATION (r),
2923 "%q#D is volatile", r);
2924 else if (!DECL_INITIAL (r)
2925 || !TREE_CONSTANT (DECL_INITIAL (r))
2926 || !DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (r))
2927 inform (DECL_SOURCE_LOCATION (r),
2928 "%qD was not initialized with a constant "
2929 "expression", r);
2930 else
2931 gcc_unreachable ();
2933 else
2935 if (cxx_dialect >= cxx11 && !DECL_DECLARED_CONSTEXPR_P (r))
2936 inform (DECL_SOURCE_LOCATION (r),
2937 "%qD was not declared %<constexpr%>", r);
2938 else
2939 inform (DECL_SOURCE_LOCATION (r),
2940 "%qD does not have integral or enumeration type",
2945 /* Subroutine of cxx_eval_constant_expression.
2946 Like cxx_eval_unary_expression, except for trinary expressions. */
2948 static tree
2949 cxx_eval_trinary_expression (const constexpr_ctx *ctx, tree t,
2950 bool lval,
2951 bool *non_constant_p, bool *overflow_p)
2953 int i;
2954 tree args[3];
2955 tree val;
2957 for (i = 0; i < 3; i++)
2959 args[i] = cxx_eval_constant_expression (ctx, TREE_OPERAND (t, i),
2960 lval,
2961 non_constant_p, overflow_p);
2962 VERIFY_CONSTANT (args[i]);
2965 val = fold_ternary_loc (EXPR_LOCATION (t), TREE_CODE (t), TREE_TYPE (t),
2966 args[0], args[1], args[2]);
2967 if (val == NULL_TREE)
2968 return t;
2969 VERIFY_CONSTANT (val);
2970 return val;
2973 bool
2974 var_in_constexpr_fn (tree t)
2976 tree ctx = DECL_CONTEXT (t);
2977 return (cxx_dialect >= cxx14 && ctx && TREE_CODE (ctx) == FUNCTION_DECL
2978 && DECL_DECLARED_CONSTEXPR_P (ctx));
2981 /* Evaluate an INIT_EXPR or MODIFY_EXPR. */
2983 static tree
2984 cxx_eval_store_expression (const constexpr_ctx *ctx, tree t,
2985 bool lval,
2986 bool *non_constant_p, bool *overflow_p)
2988 constexpr_ctx new_ctx = *ctx;
2990 tree init = TREE_OPERAND (t, 1);
2991 if (TREE_CLOBBER_P (init))
2992 /* Just ignore clobbers. */
2993 return void_node;
2995 /* First we figure out where we're storing to. */
2996 tree target = TREE_OPERAND (t, 0);
2997 tree type = TREE_TYPE (target);
2998 target = cxx_eval_constant_expression (ctx, target,
2999 true,
3000 non_constant_p, overflow_p);
3001 if (*non_constant_p)
3002 return t;
3004 if (!same_type_ignoring_top_level_qualifiers_p (TREE_TYPE (target), type))
3006 /* For initialization of an empty base, the original target will be
3007 *(base*)this, which the above evaluation resolves to the object
3008 argument, which has the derived type rather than the base type. In
3009 this situation, just evaluate the initializer and return, since
3010 there's no actual data to store. */
3011 gcc_assert (is_empty_class (type));
3012 return cxx_eval_constant_expression (ctx, init, false,
3013 non_constant_p, overflow_p);
3016 /* And then find the underlying variable. */
3017 vec<tree,va_gc> *refs = make_tree_vector();
3018 tree object = NULL_TREE;
3019 for (tree probe = target; object == NULL_TREE; )
3021 switch (TREE_CODE (probe))
3023 case BIT_FIELD_REF:
3024 case COMPONENT_REF:
3025 case ARRAY_REF:
3026 vec_safe_push (refs, TREE_OPERAND (probe, 1));
3027 vec_safe_push (refs, TREE_TYPE (probe));
3028 probe = TREE_OPERAND (probe, 0);
3029 break;
3031 default:
3032 object = probe;
3036 /* And then find/build up our initializer for the path to the subobject
3037 we're initializing. */
3038 tree *valp;
3039 if (DECL_P (object))
3040 valp = ctx->values->get (object);
3041 else
3042 valp = NULL;
3043 if (!valp)
3045 /* A constant-expression cannot modify objects from outside the
3046 constant-expression. */
3047 if (!ctx->quiet)
3048 error ("modification of %qE is not a constant-expression", object);
3049 *non_constant_p = true;
3050 return t;
3052 type = TREE_TYPE (object);
3053 bool no_zero_init = true;
3055 vec<tree,va_gc> *ctors = make_tree_vector ();
3056 while (!refs->is_empty())
3058 if (*valp == NULL_TREE)
3060 *valp = build_constructor (type, NULL);
3061 CONSTRUCTOR_NO_IMPLICIT_ZERO (*valp) = no_zero_init;
3063 /* If the value of object is already zero-initialized, any new ctors for
3064 subobjects will also be zero-initialized. */
3065 no_zero_init = CONSTRUCTOR_NO_IMPLICIT_ZERO (*valp);
3067 vec_safe_push (ctors, *valp);
3069 enum tree_code code = TREE_CODE (type);
3070 type = refs->pop();
3071 tree index = refs->pop();
3073 constructor_elt *cep = NULL;
3074 if (code == ARRAY_TYPE)
3076 HOST_WIDE_INT i
3077 = find_array_ctor_elt (*valp, index, /*insert*/true);
3078 gcc_assert (i >= 0);
3079 cep = CONSTRUCTOR_ELT (*valp, i);
3080 gcc_assert (TREE_CODE (cep->index) != RANGE_EXPR);
3082 else
3084 gcc_assert (TREE_CODE (index) == FIELD_DECL);
3086 /* We must keep the CONSTRUCTOR's ELTS in FIELD order.
3087 Usually we meet initializers in that order, but it is
3088 possible for base types to be placed not in program
3089 order. */
3090 tree fields = TYPE_FIELDS (DECL_CONTEXT (index));
3091 unsigned HOST_WIDE_INT idx;
3093 for (idx = 0;
3094 vec_safe_iterate (CONSTRUCTOR_ELTS (*valp), idx, &cep);
3095 idx++, fields = DECL_CHAIN (fields))
3097 if (index == cep->index)
3098 goto found;
3100 /* The field we're initializing must be on the field
3101 list. Look to see if it is present before the
3102 field the current ELT initializes. */
3103 for (; fields != cep->index; fields = DECL_CHAIN (fields))
3104 if (index == fields)
3105 goto insert;
3108 /* We fell off the end of the CONSTRUCTOR, so insert a new
3109 entry at the end. */
3110 insert:
3112 constructor_elt ce = { index, NULL_TREE };
3114 vec_safe_insert (CONSTRUCTOR_ELTS (*valp), idx, ce);
3115 cep = CONSTRUCTOR_ELT (*valp, idx);
3117 found:;
3119 valp = &cep->value;
3121 release_tree_vector (refs);
3123 if (AGGREGATE_TYPE_P (type) || VECTOR_TYPE_P (type))
3125 /* Create a new CONSTRUCTOR in case evaluation of the initializer
3126 wants to modify it. */
3127 if (*valp == NULL_TREE)
3129 *valp = new_ctx.ctor = build_constructor (type, NULL);
3130 CONSTRUCTOR_NO_IMPLICIT_ZERO (new_ctx.ctor) = no_zero_init;
3132 else
3133 new_ctx.ctor = *valp;
3134 new_ctx.object = target;
3137 init = cxx_eval_constant_expression (&new_ctx, init, false,
3138 non_constant_p, overflow_p);
3139 /* Don't share a CONSTRUCTOR that might be changed later. */
3140 init = unshare_constructor (init);
3141 if (target == object)
3142 /* The hash table might have moved since the get earlier. */
3143 valp = ctx->values->get (object);
3145 if (TREE_CODE (init) == CONSTRUCTOR)
3147 /* An outer ctx->ctor might be pointing to *valp, so replace
3148 its contents. */
3149 CONSTRUCTOR_ELTS (*valp) = CONSTRUCTOR_ELTS (init);
3150 TREE_CONSTANT (*valp) = TREE_CONSTANT (init);
3151 TREE_SIDE_EFFECTS (*valp) = TREE_SIDE_EFFECTS (init);
3153 else
3154 *valp = init;
3156 /* Update TREE_CONSTANT and TREE_SIDE_EFFECTS on enclosing
3157 CONSTRUCTORs, if any. */
3158 tree elt;
3159 unsigned i;
3160 bool c = TREE_CONSTANT (init);
3161 bool s = TREE_SIDE_EFFECTS (init);
3162 if (!c || s)
3163 FOR_EACH_VEC_SAFE_ELT (ctors, i, elt)
3165 if (!c)
3166 TREE_CONSTANT (elt) = false;
3167 if (s)
3168 TREE_SIDE_EFFECTS (elt) = true;
3170 release_tree_vector (ctors);
3172 if (*non_constant_p)
3173 return t;
3174 else if (lval)
3175 return target;
3176 else
3177 return init;
3180 /* Evaluate a ++ or -- expression. */
3182 static tree
3183 cxx_eval_increment_expression (const constexpr_ctx *ctx, tree t,
3184 bool lval,
3185 bool *non_constant_p, bool *overflow_p)
3187 enum tree_code code = TREE_CODE (t);
3188 tree type = TREE_TYPE (t);
3189 tree op = TREE_OPERAND (t, 0);
3190 tree offset = TREE_OPERAND (t, 1);
3191 gcc_assert (TREE_CONSTANT (offset));
3193 /* The operand as an lvalue. */
3194 op = cxx_eval_constant_expression (ctx, op, true,
3195 non_constant_p, overflow_p);
3197 /* The operand as an rvalue. */
3198 tree val = rvalue (op);
3199 val = cxx_eval_constant_expression (ctx, val, false,
3200 non_constant_p, overflow_p);
3201 /* Don't VERIFY_CONSTANT if this might be dealing with a pointer to
3202 a local array in a constexpr function. */
3203 bool ptr = POINTER_TYPE_P (TREE_TYPE (val));
3204 if (!ptr)
3205 VERIFY_CONSTANT (val);
3207 /* The modified value. */
3208 bool inc = (code == PREINCREMENT_EXPR || code == POSTINCREMENT_EXPR);
3209 tree mod;
3210 if (POINTER_TYPE_P (type))
3212 /* The middle end requires pointers to use POINTER_PLUS_EXPR. */
3213 offset = convert_to_ptrofftype (offset);
3214 if (!inc)
3215 offset = fold_build1 (NEGATE_EXPR, TREE_TYPE (offset), offset);
3216 mod = fold_build2 (POINTER_PLUS_EXPR, type, val, offset);
3218 else
3219 mod = fold_build2 (inc ? PLUS_EXPR : MINUS_EXPR, type, val, offset);
3220 if (!ptr)
3221 VERIFY_CONSTANT (mod);
3223 /* Storing the modified value. */
3224 tree store = build2 (MODIFY_EXPR, type, op, mod);
3225 cxx_eval_constant_expression (ctx, store,
3226 true, non_constant_p, overflow_p);
3228 /* And the value of the expression. */
3229 if (code == PREINCREMENT_EXPR || code == PREDECREMENT_EXPR)
3231 /* Prefix ops are lvalues. */
3232 if (lval)
3233 return op;
3234 else
3235 /* But we optimize when the caller wants an rvalue. */
3236 return mod;
3238 else
3239 /* Postfix ops are rvalues. */
3240 return val;
3243 /* Predicates for the meaning of *jump_target. */
3245 static bool
3246 returns (tree *jump_target)
3248 return *jump_target
3249 && TREE_CODE (*jump_target) == RETURN_EXPR;
3252 static bool
3253 breaks (tree *jump_target)
3255 return *jump_target
3256 && TREE_CODE (*jump_target) == LABEL_DECL
3257 && LABEL_DECL_BREAK (*jump_target);
3260 static bool
3261 continues (tree *jump_target)
3263 return *jump_target
3264 && TREE_CODE (*jump_target) == LABEL_DECL
3265 && LABEL_DECL_CONTINUE (*jump_target);
3268 static bool
3269 switches (tree *jump_target)
3271 return *jump_target
3272 && TREE_CODE (*jump_target) == INTEGER_CST;
3275 /* Subroutine of cxx_eval_statement_list. Determine whether the statement
3276 at I matches *jump_target. If we're looking for a case label and we see
3277 the default label, copy I into DEFAULT_LABEL. */
3279 static bool
3280 label_matches (tree *jump_target, tree_stmt_iterator i,
3281 tree_stmt_iterator& default_label)
3283 tree stmt = tsi_stmt (i);
3284 switch (TREE_CODE (*jump_target))
3286 case LABEL_DECL:
3287 if (TREE_CODE (stmt) == LABEL_EXPR
3288 && LABEL_EXPR_LABEL (stmt) == *jump_target)
3289 return true;
3290 break;
3292 case INTEGER_CST:
3293 if (TREE_CODE (stmt) == CASE_LABEL_EXPR)
3295 if (!CASE_LOW (stmt))
3296 default_label = i;
3297 else if (tree_int_cst_equal (*jump_target, CASE_LOW (stmt)))
3298 return true;
3300 break;
3302 default:
3303 gcc_unreachable ();
3305 return false;
3308 /* Evaluate a STATEMENT_LIST for side-effects. Handles various jump
3309 semantics, for switch, break, continue, and return. */
3311 static tree
3312 cxx_eval_statement_list (const constexpr_ctx *ctx, tree t,
3313 bool *non_constant_p, bool *overflow_p,
3314 tree *jump_target)
3316 tree_stmt_iterator i;
3317 tree_stmt_iterator default_label = tree_stmt_iterator();
3318 tree local_target;
3319 /* In a statement-expression we want to return the last value. */
3320 tree r = NULL_TREE;
3321 if (!jump_target)
3323 local_target = NULL_TREE;
3324 jump_target = &local_target;
3326 for (i = tsi_start (t); !tsi_end_p (i); tsi_next (&i))
3328 reenter:
3329 tree stmt = tsi_stmt (i);
3330 if (*jump_target)
3332 if (TREE_CODE (stmt) == STATEMENT_LIST)
3333 /* The label we want might be inside. */;
3334 else if (label_matches (jump_target, i, default_label))
3335 /* Found it. */
3336 *jump_target = NULL_TREE;
3337 else
3338 continue;
3340 r = cxx_eval_constant_expression (ctx, stmt, false,
3341 non_constant_p, overflow_p,
3342 jump_target);
3343 if (*non_constant_p)
3344 break;
3345 if (returns (jump_target) || breaks (jump_target))
3346 break;
3348 if (switches (jump_target) && !tsi_end_p (default_label))
3350 i = default_label;
3351 *jump_target = NULL_TREE;
3352 goto reenter;
3354 return r;
3357 /* Evaluate a LOOP_EXPR for side-effects. Handles break and return
3358 semantics; continue semantics are covered by cxx_eval_statement_list. */
3360 static tree
3361 cxx_eval_loop_expr (const constexpr_ctx *ctx, tree t,
3362 bool *non_constant_p, bool *overflow_p,
3363 tree *jump_target)
3365 constexpr_ctx new_ctx = *ctx;
3367 tree body = TREE_OPERAND (t, 0);
3370 hash_set<tree> save_exprs;
3371 new_ctx.save_exprs = &save_exprs;
3373 cxx_eval_statement_list (&new_ctx, body,
3374 non_constant_p, overflow_p, jump_target);
3376 /* Forget saved values of SAVE_EXPRs. */
3377 for (hash_set<tree>::iterator iter = save_exprs.begin();
3378 iter != save_exprs.end(); ++iter)
3379 new_ctx.values->remove (*iter);
3381 while (!returns (jump_target) && !breaks (jump_target) && !*non_constant_p);
3383 if (breaks (jump_target))
3384 *jump_target = NULL_TREE;
3386 return NULL_TREE;
3389 /* Evaluate a SWITCH_EXPR for side-effects. Handles switch and break jump
3390 semantics. */
3392 static tree
3393 cxx_eval_switch_expr (const constexpr_ctx *ctx, tree t,
3394 bool *non_constant_p, bool *overflow_p,
3395 tree *jump_target)
3397 tree cond = TREE_OPERAND (t, 0);
3398 cond = cxx_eval_constant_expression (ctx, cond, false,
3399 non_constant_p, overflow_p);
3400 VERIFY_CONSTANT (cond);
3401 *jump_target = cond;
3403 tree body = TREE_OPERAND (t, 1);
3404 cxx_eval_statement_list (ctx, body,
3405 non_constant_p, overflow_p, jump_target);
3406 if (breaks (jump_target) || switches (jump_target))
3407 *jump_target = NULL_TREE;
3408 return NULL_TREE;
3411 /* Subroutine of cxx_eval_constant_expression.
3412 Attempt to reduce a POINTER_PLUS_EXPR expression T. */
3414 static tree
3415 cxx_eval_pointer_plus_expression (const constexpr_ctx *ctx, tree t,
3416 bool lval, bool *non_constant_p,
3417 bool *overflow_p)
3419 tree orig_type = TREE_TYPE (t);
3420 tree op00 = TREE_OPERAND (t, 0);
3421 tree op01 = TREE_OPERAND (t, 1);
3422 location_t loc = EXPR_LOCATION (t);
3424 op00 = cxx_eval_constant_expression (ctx, op00, lval,
3425 non_constant_p, overflow_p);
3427 STRIP_NOPS (op00);
3428 if (TREE_CODE (op00) != ADDR_EXPR)
3429 return NULL_TREE;
3431 op01 = cxx_eval_constant_expression (ctx, op01, lval,
3432 non_constant_p, overflow_p);
3433 op00 = TREE_OPERAND (op00, 0);
3435 /* &A[i] p+ j => &A[i + j] */
3436 if (TREE_CODE (op00) == ARRAY_REF
3437 && TREE_CODE (TREE_OPERAND (op00, 1)) == INTEGER_CST
3438 && TREE_CODE (op01) == INTEGER_CST
3439 && TYPE_SIZE_UNIT (TREE_TYPE (op00))
3440 && TREE_CODE (TYPE_SIZE_UNIT (TREE_TYPE (op00))) == INTEGER_CST)
3442 tree type = TREE_TYPE (op00);
3443 t = fold_convert_loc (loc, ssizetype, TREE_OPERAND (op00, 1));
3444 tree nelts = array_type_nelts_top (TREE_TYPE (TREE_OPERAND (op00, 0)));
3445 /* Don't fold an out-of-bound access. */
3446 if (!tree_int_cst_le (t, nelts))
3447 return NULL_TREE;
3448 op01 = cp_fold_convert (ssizetype, op01);
3449 /* Don't fold if op01 can't be divided exactly by TYPE_SIZE_UNIT.
3450 constexpr int A[1]; ... (char *)&A[0] + 1 */
3451 if (!integer_zerop (fold_build2_loc (loc, TRUNC_MOD_EXPR, sizetype,
3452 op01, TYPE_SIZE_UNIT (type))))
3453 return NULL_TREE;
3454 /* Make sure to treat the second operand of POINTER_PLUS_EXPR
3455 as signed. */
3456 op01 = fold_build2_loc (loc, EXACT_DIV_EXPR, ssizetype, op01,
3457 TYPE_SIZE_UNIT (type));
3458 t = size_binop_loc (loc, PLUS_EXPR, op01, t);
3459 t = build4_loc (loc, ARRAY_REF, type, TREE_OPERAND (op00, 0),
3460 t, NULL_TREE, NULL_TREE);
3461 t = cp_build_addr_expr (t, tf_warning_or_error);
3462 t = cp_fold_convert (orig_type, t);
3463 return cxx_eval_constant_expression (ctx, t, lval, non_constant_p,
3464 overflow_p);
3467 return NULL_TREE;
3470 /* Attempt to reduce the expression T to a constant value.
3471 On failure, issue diagnostic and return error_mark_node. */
3472 /* FIXME unify with c_fully_fold */
3473 /* FIXME overflow_p is too global */
3475 static tree
3476 cxx_eval_constant_expression (const constexpr_ctx *ctx, tree t,
3477 bool lval,
3478 bool *non_constant_p, bool *overflow_p,
3479 tree *jump_target)
3481 constexpr_ctx new_ctx;
3482 tree r = t;
3484 if (t == error_mark_node)
3486 *non_constant_p = true;
3487 return t;
3489 if (CONSTANT_CLASS_P (t))
3491 if (TREE_OVERFLOW (t))
3493 if (!ctx->quiet)
3494 permerror (input_location, "overflow in constant expression");
3495 if (!flag_permissive || ctx->quiet)
3496 *overflow_p = true;
3498 return t;
3501 switch (TREE_CODE (t))
3503 case RESULT_DECL:
3504 if (lval)
3505 return t;
3506 /* We ask for an rvalue for the RESULT_DECL when indirecting
3507 through an invisible reference, or in named return value
3508 optimization. */
3509 return (*ctx->values->get (t));
3511 case VAR_DECL:
3512 case CONST_DECL:
3513 /* We used to not check lval for CONST_DECL, but darwin.c uses
3514 CONST_DECL for aggregate constants. */
3515 if (lval)
3516 return t;
3517 if (ctx->strict)
3518 r = decl_really_constant_value (t);
3519 else
3520 r = decl_constant_value (t);
3521 if (TREE_CODE (r) == TARGET_EXPR
3522 && TREE_CODE (TARGET_EXPR_INITIAL (r)) == CONSTRUCTOR)
3523 r = TARGET_EXPR_INITIAL (r);
3524 if (VAR_P (r))
3525 if (tree *p = ctx->values->get (r))
3526 if (*p != NULL_TREE)
3527 r = *p;
3528 if (DECL_P (r))
3530 if (!ctx->quiet)
3531 non_const_var_error (r);
3532 *non_constant_p = true;
3534 break;
3536 case FUNCTION_DECL:
3537 case TEMPLATE_DECL:
3538 case LABEL_DECL:
3539 case LABEL_EXPR:
3540 case CASE_LABEL_EXPR:
3541 return t;
3543 case PARM_DECL:
3544 if (lval && TREE_CODE (TREE_TYPE (t)) != REFERENCE_TYPE)
3545 /* glvalue use. */;
3546 else if (tree *p = ctx->values->get (r))
3547 r = *p;
3548 else if (lval)
3549 /* Defer in case this is only used for its type. */;
3550 else if (TREE_CODE (TREE_TYPE (t)) == REFERENCE_TYPE)
3551 /* Defer, there's no lvalue->rvalue conversion. */;
3552 else if (is_empty_class (TREE_TYPE (t)))
3554 /* If the class is empty, we aren't actually loading anything. */
3555 r = build_constructor (TREE_TYPE (t), NULL);
3556 TREE_CONSTANT (r) = true;
3558 else
3560 if (!ctx->quiet)
3561 error ("%qE is not a constant expression", t);
3562 *non_constant_p = true;
3564 break;
3566 case CALL_EXPR:
3567 case AGGR_INIT_EXPR:
3568 r = cxx_eval_call_expression (ctx, t, lval,
3569 non_constant_p, overflow_p);
3570 break;
3572 case DECL_EXPR:
3574 r = DECL_EXPR_DECL (t);
3575 if (AGGREGATE_TYPE_P (TREE_TYPE (r))
3576 || VECTOR_TYPE_P (TREE_TYPE (r)))
3578 new_ctx = *ctx;
3579 new_ctx.object = r;
3580 new_ctx.ctor = build_constructor (TREE_TYPE (r), NULL);
3581 CONSTRUCTOR_NO_IMPLICIT_ZERO (new_ctx.ctor) = true;
3582 new_ctx.values->put (r, new_ctx.ctor);
3583 ctx = &new_ctx;
3586 if (tree init = DECL_INITIAL (r))
3588 init = cxx_eval_constant_expression (ctx, init,
3589 false,
3590 non_constant_p, overflow_p);
3591 /* Don't share a CONSTRUCTOR that might be changed. */
3592 init = unshare_constructor (init);
3593 ctx->values->put (r, init);
3595 else if (ctx == &new_ctx)
3596 /* We gave it a CONSTRUCTOR above. */;
3597 else
3598 ctx->values->put (r, NULL_TREE);
3600 break;
3602 case TARGET_EXPR:
3603 if (!literal_type_p (TREE_TYPE (t)))
3605 if (!ctx->quiet)
3607 error ("temporary of non-literal type %qT in a "
3608 "constant expression", TREE_TYPE (t));
3609 explain_non_literal_class (TREE_TYPE (t));
3611 *non_constant_p = true;
3612 break;
3614 if ((AGGREGATE_TYPE_P (TREE_TYPE (t)) || VECTOR_TYPE_P (TREE_TYPE (t))))
3616 /* We're being expanded without an explicit target, so start
3617 initializing a new object; expansion with an explicit target
3618 strips the TARGET_EXPR before we get here. */
3619 new_ctx = *ctx;
3620 new_ctx.ctor = build_constructor (TREE_TYPE (t), NULL);
3621 CONSTRUCTOR_NO_IMPLICIT_ZERO (new_ctx.ctor) = true;
3622 new_ctx.object = TARGET_EXPR_SLOT (t);
3623 ctx->values->put (new_ctx.object, new_ctx.ctor);
3624 ctx = &new_ctx;
3626 /* Pass false for 'lval' because this indicates
3627 initialization of a temporary. */
3628 r = cxx_eval_constant_expression (ctx, TREE_OPERAND (t, 1),
3629 false,
3630 non_constant_p, overflow_p);
3631 if (!*non_constant_p)
3632 /* Adjust the type of the result to the type of the temporary. */
3633 r = adjust_temp_type (TREE_TYPE (t), r);
3634 if (lval)
3636 tree slot = TARGET_EXPR_SLOT (t);
3637 r = unshare_constructor (r);
3638 ctx->values->put (slot, r);
3639 return slot;
3641 break;
3643 case INIT_EXPR:
3644 case MODIFY_EXPR:
3645 r = cxx_eval_store_expression (ctx, t, lval,
3646 non_constant_p, overflow_p);
3647 break;
3649 case SCOPE_REF:
3650 r = cxx_eval_constant_expression (ctx, TREE_OPERAND (t, 1),
3651 lval,
3652 non_constant_p, overflow_p);
3653 break;
3655 case RETURN_EXPR:
3656 if (TREE_OPERAND (t, 0) != NULL_TREE)
3657 r = cxx_eval_constant_expression (ctx, TREE_OPERAND (t, 0),
3658 lval,
3659 non_constant_p, overflow_p);
3660 *jump_target = t;
3661 break;
3663 case SAVE_EXPR:
3664 /* Avoid evaluating a SAVE_EXPR more than once. */
3665 if (tree *p = ctx->values->get (t))
3666 r = *p;
3667 else
3669 r = cxx_eval_constant_expression (ctx, TREE_OPERAND (t, 0), false,
3670 non_constant_p, overflow_p);
3671 ctx->values->put (t, r);
3672 if (ctx->save_exprs)
3673 ctx->save_exprs->add (t);
3675 break;
3677 case NON_LVALUE_EXPR:
3678 case TRY_CATCH_EXPR:
3679 case TRY_BLOCK:
3680 case CLEANUP_POINT_EXPR:
3681 case MUST_NOT_THROW_EXPR:
3682 case EXPR_STMT:
3683 case EH_SPEC_BLOCK:
3684 r = cxx_eval_constant_expression (ctx, TREE_OPERAND (t, 0),
3685 lval,
3686 non_constant_p, overflow_p,
3687 jump_target);
3688 break;
3690 case TRY_FINALLY_EXPR:
3691 r = cxx_eval_constant_expression (ctx, TREE_OPERAND (t, 0), lval,
3692 non_constant_p, overflow_p,
3693 jump_target);
3694 if (!*non_constant_p)
3695 /* Also evaluate the cleanup. */
3696 cxx_eval_constant_expression (ctx, TREE_OPERAND (t, 1), true,
3697 non_constant_p, overflow_p,
3698 jump_target);
3699 break;
3701 /* These differ from cxx_eval_unary_expression in that this doesn't
3702 check for a constant operand or result; an address can be
3703 constant without its operand being, and vice versa. */
3704 case MEM_REF:
3705 case INDIRECT_REF:
3706 r = cxx_eval_indirect_ref (ctx, t, lval,
3707 non_constant_p, overflow_p);
3708 break;
3710 case ADDR_EXPR:
3712 tree oldop = TREE_OPERAND (t, 0);
3713 tree op = cxx_eval_constant_expression (ctx, oldop,
3714 /*lval*/true,
3715 non_constant_p, overflow_p);
3716 /* Don't VERIFY_CONSTANT here. */
3717 if (*non_constant_p)
3718 return t;
3719 gcc_checking_assert (TREE_CODE (op) != CONSTRUCTOR);
3720 /* This function does more aggressive folding than fold itself. */
3721 r = build_fold_addr_expr_with_type (op, TREE_TYPE (t));
3722 if (TREE_CODE (r) == ADDR_EXPR && TREE_OPERAND (r, 0) == oldop)
3723 return t;
3724 break;
3727 case REALPART_EXPR:
3728 case IMAGPART_EXPR:
3729 case CONJ_EXPR:
3730 case FIX_TRUNC_EXPR:
3731 case FLOAT_EXPR:
3732 case NEGATE_EXPR:
3733 case ABS_EXPR:
3734 case BIT_NOT_EXPR:
3735 case TRUTH_NOT_EXPR:
3736 case FIXED_CONVERT_EXPR:
3737 r = cxx_eval_unary_expression (ctx, t, lval,
3738 non_constant_p, overflow_p);
3739 break;
3741 case SIZEOF_EXPR:
3742 r = fold_sizeof_expr (t);
3743 VERIFY_CONSTANT (r);
3744 break;
3746 case COMPOUND_EXPR:
3748 /* check_return_expr sometimes wraps a TARGET_EXPR in a
3749 COMPOUND_EXPR; don't get confused. Also handle EMPTY_CLASS_EXPR
3750 introduced by build_call_a. */
3751 tree op0 = TREE_OPERAND (t, 0);
3752 tree op1 = TREE_OPERAND (t, 1);
3753 STRIP_NOPS (op1);
3754 if ((TREE_CODE (op0) == TARGET_EXPR && op1 == TARGET_EXPR_SLOT (op0))
3755 || TREE_CODE (op1) == EMPTY_CLASS_EXPR)
3756 r = cxx_eval_constant_expression (ctx, op0,
3757 lval, non_constant_p, overflow_p,
3758 jump_target);
3759 else
3761 /* Check that the LHS is constant and then discard it. */
3762 cxx_eval_constant_expression (ctx, op0,
3763 true, non_constant_p, overflow_p,
3764 jump_target);
3765 op1 = TREE_OPERAND (t, 1);
3766 r = cxx_eval_constant_expression (ctx, op1,
3767 lval, non_constant_p, overflow_p,
3768 jump_target);
3771 break;
3773 case POINTER_PLUS_EXPR:
3774 r = cxx_eval_pointer_plus_expression (ctx, t, lval, non_constant_p,
3775 overflow_p);
3776 if (r)
3777 break;
3778 /* else fall through */
3780 case PLUS_EXPR:
3781 case MINUS_EXPR:
3782 case MULT_EXPR:
3783 case TRUNC_DIV_EXPR:
3784 case CEIL_DIV_EXPR:
3785 case FLOOR_DIV_EXPR:
3786 case ROUND_DIV_EXPR:
3787 case TRUNC_MOD_EXPR:
3788 case CEIL_MOD_EXPR:
3789 case ROUND_MOD_EXPR:
3790 case RDIV_EXPR:
3791 case EXACT_DIV_EXPR:
3792 case MIN_EXPR:
3793 case MAX_EXPR:
3794 case LSHIFT_EXPR:
3795 case RSHIFT_EXPR:
3796 case LROTATE_EXPR:
3797 case RROTATE_EXPR:
3798 case BIT_IOR_EXPR:
3799 case BIT_XOR_EXPR:
3800 case BIT_AND_EXPR:
3801 case TRUTH_XOR_EXPR:
3802 case LT_EXPR:
3803 case LE_EXPR:
3804 case GT_EXPR:
3805 case GE_EXPR:
3806 case EQ_EXPR:
3807 case NE_EXPR:
3808 case UNORDERED_EXPR:
3809 case ORDERED_EXPR:
3810 case UNLT_EXPR:
3811 case UNLE_EXPR:
3812 case UNGT_EXPR:
3813 case UNGE_EXPR:
3814 case UNEQ_EXPR:
3815 case LTGT_EXPR:
3816 case RANGE_EXPR:
3817 case COMPLEX_EXPR:
3818 r = cxx_eval_binary_expression (ctx, t, lval,
3819 non_constant_p, overflow_p);
3820 break;
3822 /* fold can introduce non-IF versions of these; still treat them as
3823 short-circuiting. */
3824 case TRUTH_AND_EXPR:
3825 case TRUTH_ANDIF_EXPR:
3826 r = cxx_eval_logical_expression (ctx, t, boolean_false_node,
3827 boolean_true_node,
3828 lval,
3829 non_constant_p, overflow_p);
3830 break;
3832 case TRUTH_OR_EXPR:
3833 case TRUTH_ORIF_EXPR:
3834 r = cxx_eval_logical_expression (ctx, t, boolean_true_node,
3835 boolean_false_node,
3836 lval,
3837 non_constant_p, overflow_p);
3838 break;
3840 case ARRAY_REF:
3841 r = cxx_eval_array_reference (ctx, t, lval,
3842 non_constant_p, overflow_p);
3843 break;
3845 case COMPONENT_REF:
3846 if (is_overloaded_fn (t))
3848 /* We can only get here in checking mode via
3849 build_non_dependent_expr, because any expression that
3850 calls or takes the address of the function will have
3851 pulled a FUNCTION_DECL out of the COMPONENT_REF. */
3852 gcc_checking_assert (ctx->quiet || errorcount);
3853 *non_constant_p = true;
3854 return t;
3856 r = cxx_eval_component_reference (ctx, t, lval,
3857 non_constant_p, overflow_p);
3858 break;
3860 case BIT_FIELD_REF:
3861 r = cxx_eval_bit_field_ref (ctx, t, lval,
3862 non_constant_p, overflow_p);
3863 break;
3865 case COND_EXPR:
3866 case VEC_COND_EXPR:
3867 r = cxx_eval_conditional_expression (ctx, t, lval,
3868 non_constant_p, overflow_p,
3869 jump_target);
3870 break;
3872 case CONSTRUCTOR:
3873 if (TREE_CONSTANT (t))
3875 /* Don't re-process a constant CONSTRUCTOR, but do fold it to
3876 VECTOR_CST if applicable. */
3877 /* FIXME after GCC 6 branches, make the verify unconditional. */
3878 if (CHECKING_P)
3879 verify_constructor_flags (t);
3880 else
3881 recompute_constructor_flags (t);
3882 if (TREE_CONSTANT (t))
3883 return fold (t);
3885 r = cxx_eval_bare_aggregate (ctx, t, lval,
3886 non_constant_p, overflow_p);
3887 break;
3889 case VEC_INIT_EXPR:
3890 /* We can get this in a defaulted constructor for a class with a
3891 non-static data member of array type. Either the initializer will
3892 be NULL, meaning default-initialization, or it will be an lvalue
3893 or xvalue of the same type, meaning direct-initialization from the
3894 corresponding member. */
3895 r = cxx_eval_vec_init (ctx, t, lval,
3896 non_constant_p, overflow_p);
3897 break;
3899 case FMA_EXPR:
3900 case VEC_PERM_EXPR:
3901 r = cxx_eval_trinary_expression (ctx, t, lval,
3902 non_constant_p, overflow_p);
3903 break;
3905 case CONVERT_EXPR:
3906 case VIEW_CONVERT_EXPR:
3907 case NOP_EXPR:
3908 case UNARY_PLUS_EXPR:
3910 enum tree_code tcode = TREE_CODE (t);
3911 tree oldop = TREE_OPERAND (t, 0);
3913 tree op = cxx_eval_constant_expression (ctx, oldop,
3914 lval,
3915 non_constant_p, overflow_p);
3916 if (*non_constant_p)
3917 return t;
3918 tree type = TREE_TYPE (t);
3919 if (TREE_CODE (op) == PTRMEM_CST
3920 && !TYPE_PTRMEM_P (type))
3921 op = cplus_expand_constant (op);
3922 if (TREE_CODE (op) == PTRMEM_CST && tcode == NOP_EXPR)
3924 if (same_type_ignoring_top_level_qualifiers_p (type,
3925 TREE_TYPE (op)))
3926 STRIP_NOPS (t);
3927 else
3929 if (!ctx->quiet)
3930 error_at (EXPR_LOC_OR_LOC (t, input_location),
3931 "a reinterpret_cast is not a constant-expression");
3932 *non_constant_p = true;
3933 return t;
3936 if (POINTER_TYPE_P (type)
3937 && TREE_CODE (op) == INTEGER_CST
3938 && !integer_zerop (op))
3940 if (!ctx->quiet)
3941 error_at (EXPR_LOC_OR_LOC (t, input_location),
3942 "reinterpret_cast from integer to pointer");
3943 *non_constant_p = true;
3944 return t;
3946 if (op == oldop && tcode != UNARY_PLUS_EXPR)
3947 /* We didn't fold at the top so we could check for ptr-int
3948 conversion. */
3949 return fold (t);
3950 if (tcode == UNARY_PLUS_EXPR)
3951 r = fold_convert (TREE_TYPE (t), op);
3952 else
3953 r = fold_build1 (tcode, type, op);
3954 /* Conversion of an out-of-range value has implementation-defined
3955 behavior; the language considers it different from arithmetic
3956 overflow, which is undefined. */
3957 if (TREE_OVERFLOW_P (r) && !TREE_OVERFLOW_P (op))
3958 TREE_OVERFLOW (r) = false;
3960 break;
3962 case EMPTY_CLASS_EXPR:
3963 /* This is good enough for a function argument that might not get
3964 used, and they can't do anything with it, so just return it. */
3965 return t;
3967 case STATEMENT_LIST:
3968 new_ctx = *ctx;
3969 new_ctx.ctor = new_ctx.object = NULL_TREE;
3970 return cxx_eval_statement_list (&new_ctx, t,
3971 non_constant_p, overflow_p, jump_target);
3973 case BIND_EXPR:
3974 return cxx_eval_constant_expression (ctx, BIND_EXPR_BODY (t),
3975 lval,
3976 non_constant_p, overflow_p,
3977 jump_target);
3979 case PREINCREMENT_EXPR:
3980 case POSTINCREMENT_EXPR:
3981 case PREDECREMENT_EXPR:
3982 case POSTDECREMENT_EXPR:
3983 return cxx_eval_increment_expression (ctx, t,
3984 lval, non_constant_p, overflow_p);
3986 case LAMBDA_EXPR:
3987 case NEW_EXPR:
3988 case VEC_NEW_EXPR:
3989 case DELETE_EXPR:
3990 case VEC_DELETE_EXPR:
3991 case THROW_EXPR:
3992 case MODOP_EXPR:
3993 /* GCC internal stuff. */
3994 case VA_ARG_EXPR:
3995 case OBJ_TYPE_REF:
3996 case WITH_CLEANUP_EXPR:
3997 case NON_DEPENDENT_EXPR:
3998 case BASELINK:
3999 case OFFSET_REF:
4000 if (!ctx->quiet)
4001 error_at (EXPR_LOC_OR_LOC (t, input_location),
4002 "expression %qE is not a constant-expression", t);
4003 *non_constant_p = true;
4004 break;
4006 case PLACEHOLDER_EXPR:
4007 if (!ctx || !ctx->ctor || (lval && !ctx->object)
4008 || !(same_type_ignoring_top_level_qualifiers_p
4009 (TREE_TYPE (t), TREE_TYPE (ctx->ctor))))
4011 /* A placeholder without a referent. We can get here when
4012 checking whether NSDMIs are noexcept, or in massage_init_elt;
4013 just say it's non-constant for now. */
4014 gcc_assert (ctx->quiet);
4015 *non_constant_p = true;
4016 break;
4018 else
4020 /* Use of the value or address of the current object. We could
4021 use ctx->object unconditionally, but using ctx->ctor when we
4022 can is a minor optimization. */
4023 tree ctor = lval ? ctx->object : ctx->ctor;
4024 return cxx_eval_constant_expression
4025 (ctx, ctor, lval,
4026 non_constant_p, overflow_p);
4028 break;
4030 case GOTO_EXPR:
4031 *jump_target = TREE_OPERAND (t, 0);
4032 gcc_assert (breaks (jump_target) || continues (jump_target));
4033 break;
4035 case LOOP_EXPR:
4036 cxx_eval_loop_expr (ctx, t,
4037 non_constant_p, overflow_p, jump_target);
4038 break;
4040 case SWITCH_EXPR:
4041 cxx_eval_switch_expr (ctx, t,
4042 non_constant_p, overflow_p, jump_target);
4043 break;
4045 case REQUIRES_EXPR:
4046 /* It's possible to get a requires-expression in a constant
4047 expression. For example:
4049 template<typename T> concept bool C() {
4050 return requires (T t) { t; };
4053 template<typename T> requires !C<T>() void f(T);
4055 Normalization leaves f with the associated constraint
4056 '!requires (T t) { ... }' which is not transformed into
4057 a constraint. */
4058 if (!processing_template_decl)
4059 return evaluate_constraint_expression (t, NULL_TREE);
4060 else
4061 *non_constant_p = true;
4062 return t;
4064 default:
4065 if (STATEMENT_CODE_P (TREE_CODE (t)))
4067 /* This function doesn't know how to deal with pre-genericize
4068 statements; this can only happen with statement-expressions,
4069 so for now just fail. */
4070 if (!ctx->quiet)
4071 error_at (EXPR_LOCATION (t),
4072 "statement is not a constant-expression");
4074 else
4075 internal_error ("unexpected expression %qE of kind %s", t,
4076 get_tree_code_name (TREE_CODE (t)));
4077 *non_constant_p = true;
4078 break;
4081 if (r == error_mark_node)
4082 *non_constant_p = true;
4084 if (*non_constant_p)
4085 return t;
4086 else
4087 return r;
4090 static tree
4091 cxx_eval_outermost_constant_expr (tree t, bool allow_non_constant,
4092 bool strict = true, tree object = NULL_TREE)
4094 bool non_constant_p = false;
4095 bool overflow_p = false;
4096 hash_map<tree,tree> map;
4098 constexpr_ctx ctx = { NULL, &map, NULL, NULL, NULL,
4099 allow_non_constant, strict };
4101 tree type = initialized_type (t);
4102 tree r = t;
4103 if (AGGREGATE_TYPE_P (type) || VECTOR_TYPE_P (type))
4105 /* In C++14 an NSDMI can participate in aggregate initialization,
4106 and can refer to the address of the object being initialized, so
4107 we need to pass in the relevant VAR_DECL if we want to do the
4108 evaluation in a single pass. The evaluation will dynamically
4109 update ctx.values for the VAR_DECL. We use the same strategy
4110 for C++11 constexpr constructors that refer to the object being
4111 initialized. */
4112 ctx.ctor = build_constructor (type, NULL);
4113 CONSTRUCTOR_NO_IMPLICIT_ZERO (ctx.ctor) = true;
4114 if (!object)
4116 if (TREE_CODE (t) == TARGET_EXPR)
4117 object = TARGET_EXPR_SLOT (t);
4118 else if (TREE_CODE (t) == AGGR_INIT_EXPR)
4119 object = AGGR_INIT_EXPR_SLOT (t);
4121 ctx.object = object;
4122 if (object)
4123 gcc_assert (same_type_ignoring_top_level_qualifiers_p
4124 (type, TREE_TYPE (object)));
4125 if (object && DECL_P (object))
4126 map.put (object, ctx.ctor);
4127 if (TREE_CODE (r) == TARGET_EXPR)
4128 /* Avoid creating another CONSTRUCTOR when we expand the
4129 TARGET_EXPR. */
4130 r = TARGET_EXPR_INITIAL (r);
4133 r = cxx_eval_constant_expression (&ctx, r,
4134 false, &non_constant_p, &overflow_p);
4136 verify_constant (r, allow_non_constant, &non_constant_p, &overflow_p);
4138 /* Mutable logic is a bit tricky: we want to allow initialization of
4139 constexpr variables with mutable members, but we can't copy those
4140 members to another constexpr variable. */
4141 if (TREE_CODE (r) == CONSTRUCTOR
4142 && CONSTRUCTOR_MUTABLE_POISON (r))
4144 if (!allow_non_constant)
4145 error ("%qE is not a constant expression because it refers to "
4146 "mutable subobjects of %qT", t, type);
4147 non_constant_p = true;
4150 /* Technically we should check this for all subexpressions, but that
4151 runs into problems with our internal representation of pointer
4152 subtraction and the 5.19 rules are still in flux. */
4153 if (CONVERT_EXPR_CODE_P (TREE_CODE (r))
4154 && ARITHMETIC_TYPE_P (TREE_TYPE (r))
4155 && TREE_CODE (TREE_OPERAND (r, 0)) == ADDR_EXPR)
4157 if (!allow_non_constant)
4158 error ("conversion from pointer type %qT "
4159 "to arithmetic type %qT in a constant-expression",
4160 TREE_TYPE (TREE_OPERAND (r, 0)), TREE_TYPE (r));
4161 non_constant_p = true;
4164 if (!non_constant_p && overflow_p)
4165 non_constant_p = true;
4167 /* Unshare the result unless it's a CONSTRUCTOR in which case it's already
4168 unshared. */
4169 bool should_unshare = true;
4170 if (r == t || TREE_CODE (r) == CONSTRUCTOR)
4171 should_unshare = false;
4173 if (non_constant_p && !allow_non_constant)
4174 return error_mark_node;
4175 else if (non_constant_p && TREE_CONSTANT (r))
4177 /* This isn't actually constant, so unset TREE_CONSTANT. */
4178 if (EXPR_P (r))
4179 r = copy_node (r);
4180 else if (TREE_CODE (r) == CONSTRUCTOR)
4181 r = build1 (VIEW_CONVERT_EXPR, TREE_TYPE (r), r);
4182 else
4183 r = build_nop (TREE_TYPE (r), r);
4184 TREE_CONSTANT (r) = false;
4186 else if (non_constant_p || r == t)
4187 return t;
4189 if (should_unshare)
4190 r = unshare_expr (r);
4192 if (TREE_CODE (r) == CONSTRUCTOR && CLASS_TYPE_P (TREE_TYPE (r)))
4194 if (TREE_CODE (t) == TARGET_EXPR
4195 && TARGET_EXPR_INITIAL (t) == r)
4196 return t;
4197 else
4199 r = get_target_expr (r);
4200 TREE_CONSTANT (r) = true;
4201 return r;
4204 else
4205 return r;
4208 /* Returns true if T is a valid subexpression of a constant expression,
4209 even if it isn't itself a constant expression. */
4211 bool
4212 is_sub_constant_expr (tree t)
4214 bool non_constant_p = false;
4215 bool overflow_p = false;
4216 hash_map <tree, tree> map;
4218 constexpr_ctx ctx = { NULL, &map, NULL, NULL, NULL, true, true };
4220 cxx_eval_constant_expression (&ctx, t, false, &non_constant_p,
4221 &overflow_p);
4222 return !non_constant_p && !overflow_p;
4225 /* If T represents a constant expression returns its reduced value.
4226 Otherwise return error_mark_node. If T is dependent, then
4227 return NULL. */
4229 tree
4230 cxx_constant_value (tree t, tree decl)
4232 return cxx_eval_outermost_constant_expr (t, false, true, decl);
4235 /* Helper routine for fold_simple function. Either return simplified
4236 expression T, otherwise NULL_TREE.
4237 In contrast to cp_fully_fold, and to maybe_constant_value, we try to fold
4238 even if we are within template-declaration. So be careful on call, as in
4239 such case types can be undefined. */
4241 static tree
4242 fold_simple_1 (tree t)
4244 tree op1;
4245 enum tree_code code = TREE_CODE (t);
4247 switch (code)
4249 case INTEGER_CST:
4250 case REAL_CST:
4251 case VECTOR_CST:
4252 case FIXED_CST:
4253 case COMPLEX_CST:
4254 return t;
4256 case SIZEOF_EXPR:
4257 return fold_sizeof_expr (t);
4259 case ABS_EXPR:
4260 case CONJ_EXPR:
4261 case REALPART_EXPR:
4262 case IMAGPART_EXPR:
4263 case NEGATE_EXPR:
4264 case BIT_NOT_EXPR:
4265 case TRUTH_NOT_EXPR:
4266 case NOP_EXPR:
4267 case VIEW_CONVERT_EXPR:
4268 case CONVERT_EXPR:
4269 case FLOAT_EXPR:
4270 case FIX_TRUNC_EXPR:
4271 case FIXED_CONVERT_EXPR:
4272 case ADDR_SPACE_CONVERT_EXPR:
4274 op1 = TREE_OPERAND (t, 0);
4276 t = const_unop (code, TREE_TYPE (t), op1);
4277 if (!t)
4278 return NULL_TREE;
4280 if (CONVERT_EXPR_CODE_P (code)
4281 && TREE_OVERFLOW_P (t) && !TREE_OVERFLOW_P (op1))
4282 TREE_OVERFLOW (t) = false;
4283 return t;
4285 default:
4286 return NULL_TREE;
4290 /* If T is a simple constant expression, returns its simplified value.
4291 Otherwise returns T. In contrast to maybe_constant_value do we
4292 simplify only few operations on constant-expressions, and we don't
4293 try to simplify constexpressions. */
4295 tree
4296 fold_simple (tree t)
4298 tree r = NULL_TREE;
4299 if (processing_template_decl)
4300 return t;
4302 r = fold_simple_1 (t);
4303 if (!r)
4304 r = t;
4306 return r;
4309 /* If T is a constant expression, returns its reduced value.
4310 Otherwise, if T does not have TREE_CONSTANT set, returns T.
4311 Otherwise, returns a version of T without TREE_CONSTANT. */
4313 static tree
4314 maybe_constant_value_1 (tree t, tree decl)
4316 tree r;
4318 if (!potential_nondependent_constant_expression (t))
4320 if (TREE_OVERFLOW_P (t))
4322 t = build_nop (TREE_TYPE (t), t);
4323 TREE_CONSTANT (t) = false;
4325 return t;
4328 r = cxx_eval_outermost_constant_expr (t, true, true, decl);
4329 gcc_checking_assert (r == t
4330 || CONVERT_EXPR_P (t)
4331 || TREE_CODE (t) == VIEW_CONVERT_EXPR
4332 || (TREE_CONSTANT (t) && !TREE_CONSTANT (r))
4333 || !cp_tree_equal (r, t));
4334 return r;
4337 static GTY((deletable)) hash_map<tree, tree> *cv_cache;
4339 /* If T is a constant expression, returns its reduced value.
4340 Otherwise, if T does not have TREE_CONSTANT set, returns T.
4341 Otherwise, returns a version of T without TREE_CONSTANT. */
4343 tree
4344 maybe_constant_value (tree t, tree decl)
4346 if (cv_cache == NULL)
4347 cv_cache = hash_map<tree, tree>::create_ggc (101);
4349 if (tree *cached = cv_cache->get (t))
4350 return *cached;
4352 tree ret = maybe_constant_value_1 (t, decl);
4353 cv_cache->put (t, ret);
4354 return ret;
4357 /* Dispose of the whole CV_CACHE. */
4359 static void
4360 clear_cv_cache (void)
4362 if (cv_cache != NULL)
4363 cv_cache->empty ();
4366 /* Dispose of the whole CV_CACHE and FOLD_CACHE. */
4368 void
4369 clear_cv_and_fold_caches (void)
4371 clear_cv_cache ();
4372 clear_fold_cache ();
4375 /* Like maybe_constant_value but first fully instantiate the argument.
4377 Note: this is equivalent to instantiate_non_dependent_expr_sfinae
4378 (t, tf_none) followed by maybe_constant_value but is more efficient,
4379 because calls instantiation_dependent_expression_p and
4380 potential_constant_expression at most once. */
4382 tree
4383 fold_non_dependent_expr (tree t)
4385 if (t == NULL_TREE)
4386 return NULL_TREE;
4388 /* If we're in a template, but T isn't value dependent, simplify
4389 it. We're supposed to treat:
4391 template <typename T> void f(T[1 + 1]);
4392 template <typename T> void f(T[2]);
4394 as two declarations of the same function, for example. */
4395 if (processing_template_decl)
4397 if (potential_nondependent_constant_expression (t))
4399 processing_template_decl_sentinel s;
4400 t = instantiate_non_dependent_expr_internal (t, tf_none);
4402 if (type_unknown_p (t)
4403 || BRACE_ENCLOSED_INITIALIZER_P (t))
4405 if (TREE_OVERFLOW_P (t))
4407 t = build_nop (TREE_TYPE (t), t);
4408 TREE_CONSTANT (t) = false;
4410 return t;
4413 tree r = cxx_eval_outermost_constant_expr (t, true, true, NULL_TREE);
4414 /* cp_tree_equal looks through NOPs, so allow them. */
4415 gcc_checking_assert (r == t
4416 || CONVERT_EXPR_P (t)
4417 || TREE_CODE (t) == VIEW_CONVERT_EXPR
4418 || (TREE_CONSTANT (t) && !TREE_CONSTANT (r))
4419 || !cp_tree_equal (r, t));
4420 return r;
4422 else if (TREE_OVERFLOW_P (t))
4424 t = build_nop (TREE_TYPE (t), t);
4425 TREE_CONSTANT (t) = false;
4427 return t;
4430 return maybe_constant_value (t);
4433 /* Like maybe_constant_value, but returns a CONSTRUCTOR directly, rather
4434 than wrapped in a TARGET_EXPR. */
4436 tree
4437 maybe_constant_init (tree t, tree decl)
4439 if (!t)
4440 return t;
4441 if (TREE_CODE (t) == EXPR_STMT)
4442 t = TREE_OPERAND (t, 0);
4443 if (TREE_CODE (t) == CONVERT_EXPR
4444 && VOID_TYPE_P (TREE_TYPE (t)))
4445 t = TREE_OPERAND (t, 0);
4446 if (TREE_CODE (t) == INIT_EXPR)
4447 t = TREE_OPERAND (t, 1);
4448 if (!potential_nondependent_static_init_expression (t))
4449 /* Don't try to evaluate it. */;
4450 else
4451 t = cxx_eval_outermost_constant_expr (t, true, false, decl);
4452 if (TREE_CODE (t) == TARGET_EXPR)
4454 tree init = TARGET_EXPR_INITIAL (t);
4455 if (TREE_CODE (init) == CONSTRUCTOR)
4456 t = init;
4458 return t;
4461 #if 0
4462 /* FIXME see ADDR_EXPR section in potential_constant_expression_1. */
4463 /* Return true if the object referred to by REF has automatic or thread
4464 local storage. */
4466 enum { ck_ok, ck_bad, ck_unknown };
4467 static int
4468 check_automatic_or_tls (tree ref)
4470 machine_mode mode;
4471 HOST_WIDE_INT bitsize, bitpos;
4472 tree offset;
4473 int volatilep = 0, unsignedp = 0;
4474 tree decl = get_inner_reference (ref, &bitsize, &bitpos, &offset,
4475 &mode, &unsignedp, &volatilep, false);
4476 duration_kind dk;
4478 /* If there isn't a decl in the middle, we don't know the linkage here,
4479 and this isn't a constant expression anyway. */
4480 if (!DECL_P (decl))
4481 return ck_unknown;
4482 dk = decl_storage_duration (decl);
4483 return (dk == dk_auto || dk == dk_thread) ? ck_bad : ck_ok;
4485 #endif
4487 /* Return true if T denotes a potentially constant expression. Issue
4488 diagnostic as appropriate under control of FLAGS. If WANT_RVAL is true,
4489 an lvalue-rvalue conversion is implied.
4491 C++0x [expr.const] used to say
4493 6 An expression is a potential constant expression if it is
4494 a constant expression where all occurrences of function
4495 parameters are replaced by arbitrary constant expressions
4496 of the appropriate type.
4498 2 A conditional expression is a constant expression unless it
4499 involves one of the following as a potentially evaluated
4500 subexpression (3.2), but subexpressions of logical AND (5.14),
4501 logical OR (5.15), and conditional (5.16) operations that are
4502 not evaluated are not considered. */
4504 static bool
4505 potential_constant_expression_1 (tree t, bool want_rval, bool strict,
4506 tsubst_flags_t flags)
4508 #define RECUR(T,RV) potential_constant_expression_1 ((T), (RV), strict, flags)
4509 enum { any = false, rval = true };
4510 int i;
4511 tree tmp;
4513 if (t == error_mark_node)
4514 return false;
4515 if (t == NULL_TREE)
4516 return true;
4517 if (TREE_THIS_VOLATILE (t) && !DECL_P (t))
4519 if (flags & tf_error)
4520 error ("expression %qE has side-effects", t);
4521 return false;
4523 if (CONSTANT_CLASS_P (t))
4524 return true;
4526 switch (TREE_CODE (t))
4528 case FUNCTION_DECL:
4529 case BASELINK:
4530 case TEMPLATE_DECL:
4531 case OVERLOAD:
4532 case TEMPLATE_ID_EXPR:
4533 case LABEL_DECL:
4534 case LABEL_EXPR:
4535 case CASE_LABEL_EXPR:
4536 case CONST_DECL:
4537 case SIZEOF_EXPR:
4538 case ALIGNOF_EXPR:
4539 case OFFSETOF_EXPR:
4540 case NOEXCEPT_EXPR:
4541 case TEMPLATE_PARM_INDEX:
4542 case TRAIT_EXPR:
4543 case IDENTIFIER_NODE:
4544 case USERDEF_LITERAL:
4545 /* We can see a FIELD_DECL in a pointer-to-member expression. */
4546 case FIELD_DECL:
4547 case PARM_DECL:
4548 case RESULT_DECL:
4549 case USING_DECL:
4550 case USING_STMT:
4551 case PLACEHOLDER_EXPR:
4552 case BREAK_STMT:
4553 case CONTINUE_STMT:
4554 case REQUIRES_EXPR:
4555 return true;
4557 case AGGR_INIT_EXPR:
4558 case CALL_EXPR:
4559 /* -- an invocation of a function other than a constexpr function
4560 or a constexpr constructor. */
4562 tree fun = get_function_named_in_call (t);
4563 const int nargs = call_expr_nargs (t);
4564 i = 0;
4566 if (fun == NULL_TREE)
4568 if (TREE_CODE (t) == CALL_EXPR
4569 && CALL_EXPR_FN (t) == NULL_TREE)
4570 switch (CALL_EXPR_IFN (t))
4572 /* These should be ignored, they are optimized away from
4573 constexpr functions. */
4574 case IFN_UBSAN_NULL:
4575 case IFN_UBSAN_BOUNDS:
4576 case IFN_UBSAN_VPTR:
4577 return true;
4578 default:
4579 break;
4581 /* fold_call_expr can't do anything with IFN calls. */
4582 if (flags & tf_error)
4583 error_at (EXPR_LOC_OR_LOC (t, input_location),
4584 "call to internal function");
4585 return false;
4587 if (is_overloaded_fn (fun))
4589 if (TREE_CODE (fun) == FUNCTION_DECL)
4591 if (builtin_valid_in_constant_expr_p (fun))
4592 return true;
4593 if (!DECL_DECLARED_CONSTEXPR_P (fun)
4594 /* Allow any built-in function; if the expansion
4595 isn't constant, we'll deal with that then. */
4596 && !is_builtin_fn (fun))
4598 if (flags & tf_error)
4600 error_at (EXPR_LOC_OR_LOC (t, input_location),
4601 "call to non-constexpr function %qD", fun);
4602 explain_invalid_constexpr_fn (fun);
4604 return false;
4606 /* A call to a non-static member function takes the address
4607 of the object as the first argument. But in a constant
4608 expression the address will be folded away, so look
4609 through it now. */
4610 if (DECL_NONSTATIC_MEMBER_FUNCTION_P (fun)
4611 && !DECL_CONSTRUCTOR_P (fun))
4613 tree x = get_nth_callarg (t, 0);
4614 if (is_this_parameter (x))
4615 return true;
4616 else if (!RECUR (x, rval))
4617 return false;
4618 i = 1;
4621 else
4623 if (!RECUR (fun, true))
4624 return false;
4625 fun = get_first_fn (fun);
4627 /* Skip initial arguments to base constructors. */
4628 if (DECL_BASE_CONSTRUCTOR_P (fun))
4629 i = num_artificial_parms_for (fun);
4630 fun = DECL_ORIGIN (fun);
4632 else
4634 if (RECUR (fun, rval))
4635 /* Might end up being a constant function pointer. */;
4636 else
4637 return false;
4639 for (; i < nargs; ++i)
4641 tree x = get_nth_callarg (t, i);
4642 /* In a template, reference arguments haven't been converted to
4643 REFERENCE_TYPE and we might not even know if the parameter
4644 is a reference, so accept lvalue constants too. */
4645 bool rv = processing_template_decl ? any : rval;
4646 if (!RECUR (x, rv))
4647 return false;
4649 return true;
4652 case NON_LVALUE_EXPR:
4653 /* -- an lvalue-to-rvalue conversion (4.1) unless it is applied to
4654 -- an lvalue of integral type that refers to a non-volatile
4655 const variable or static data member initialized with
4656 constant expressions, or
4658 -- an lvalue of literal type that refers to non-volatile
4659 object defined with constexpr, or that refers to a
4660 sub-object of such an object; */
4661 return RECUR (TREE_OPERAND (t, 0), rval);
4663 case VAR_DECL:
4664 if (want_rval
4665 && !decl_constant_var_p (t)
4666 && (strict
4667 || !CP_TYPE_CONST_NON_VOLATILE_P (TREE_TYPE (t))
4668 || !DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (t))
4669 && !var_in_constexpr_fn (t)
4670 && !type_dependent_expression_p (t))
4672 if (flags & tf_error)
4673 non_const_var_error (t);
4674 return false;
4676 return true;
4678 case NOP_EXPR:
4679 case CONVERT_EXPR:
4680 case VIEW_CONVERT_EXPR:
4681 /* -- a reinterpret_cast. FIXME not implemented, and this rule
4682 may change to something more specific to type-punning (DR 1312). */
4684 tree from = TREE_OPERAND (t, 0);
4685 if (POINTER_TYPE_P (TREE_TYPE (t))
4686 && TREE_CODE (from) == INTEGER_CST
4687 && !integer_zerop (from))
4689 if (flags & tf_error)
4690 error_at (EXPR_LOC_OR_LOC (t, input_location),
4691 "reinterpret_cast from integer to pointer");
4692 return false;
4694 return (RECUR (from, TREE_CODE (t) != VIEW_CONVERT_EXPR));
4697 case ADDR_EXPR:
4698 /* -- a unary operator & that is applied to an lvalue that
4699 designates an object with thread or automatic storage
4700 duration; */
4701 t = TREE_OPERAND (t, 0);
4703 if (TREE_CODE (t) == OFFSET_REF && PTRMEM_OK_P (t))
4704 /* A pointer-to-member constant. */
4705 return true;
4707 #if 0
4708 /* FIXME adjust when issue 1197 is fully resolved. For now don't do
4709 any checking here, as we might dereference the pointer later. If
4710 we remove this code, also remove check_automatic_or_tls. */
4711 i = check_automatic_or_tls (t);
4712 if (i == ck_ok)
4713 return true;
4714 if (i == ck_bad)
4716 if (flags & tf_error)
4717 error ("address-of an object %qE with thread local or "
4718 "automatic storage is not a constant expression", t);
4719 return false;
4721 #endif
4722 return RECUR (t, any);
4724 case COMPONENT_REF:
4725 case BIT_FIELD_REF:
4726 case ARROW_EXPR:
4727 case OFFSET_REF:
4728 /* -- a class member access unless its postfix-expression is
4729 of literal type or of pointer to literal type. */
4730 /* This test would be redundant, as it follows from the
4731 postfix-expression being a potential constant expression. */
4732 if (type_unknown_p (t))
4733 return true;
4734 return RECUR (TREE_OPERAND (t, 0), want_rval);
4736 case EXPR_PACK_EXPANSION:
4737 return RECUR (PACK_EXPANSION_PATTERN (t), want_rval);
4739 case INDIRECT_REF:
4741 tree x = TREE_OPERAND (t, 0);
4742 STRIP_NOPS (x);
4743 if (is_this_parameter (x))
4745 if (DECL_CONTEXT (x)
4746 && !DECL_DECLARED_CONSTEXPR_P (DECL_CONTEXT (x)))
4748 if (flags & tf_error)
4749 error ("use of %<this%> in a constant expression");
4750 return false;
4752 return true;
4754 return RECUR (x, rval);
4757 case STATEMENT_LIST:
4759 tree_stmt_iterator i;
4760 for (i = tsi_start (t); !tsi_end_p (i); tsi_next (&i))
4762 if (!RECUR (tsi_stmt (i), any))
4763 return false;
4765 return true;
4767 break;
4769 case MODIFY_EXPR:
4770 if (cxx_dialect < cxx14)
4771 goto fail;
4772 if (!RECUR (TREE_OPERAND (t, 0), any))
4773 return false;
4774 if (!RECUR (TREE_OPERAND (t, 1), rval))
4775 return false;
4776 return true;
4778 case MODOP_EXPR:
4779 if (cxx_dialect < cxx14)
4780 goto fail;
4781 if (!RECUR (TREE_OPERAND (t, 0), rval))
4782 return false;
4783 if (!RECUR (TREE_OPERAND (t, 2), rval))
4784 return false;
4785 return true;
4787 case DO_STMT:
4788 if (!RECUR (DO_COND (t), rval))
4789 return false;
4790 if (!RECUR (DO_BODY (t), any))
4791 return false;
4792 return true;
4794 case FOR_STMT:
4795 if (!RECUR (FOR_INIT_STMT (t), any))
4796 return false;
4797 if (!RECUR (FOR_COND (t), rval))
4798 return false;
4799 if (!RECUR (FOR_EXPR (t), any))
4800 return false;
4801 if (!RECUR (FOR_BODY (t), any))
4802 return false;
4803 return true;
4805 case WHILE_STMT:
4806 if (!RECUR (WHILE_COND (t), rval))
4807 return false;
4808 if (!RECUR (WHILE_BODY (t), any))
4809 return false;
4810 return true;
4812 case SWITCH_STMT:
4813 if (!RECUR (SWITCH_STMT_COND (t), rval))
4814 return false;
4815 /* FIXME we don't check SWITCH_STMT_BODY currently, because even
4816 unreachable labels would be checked. */
4817 return true;
4819 case STMT_EXPR:
4820 return RECUR (STMT_EXPR_STMT (t), rval);
4822 case LAMBDA_EXPR:
4823 case DYNAMIC_CAST_EXPR:
4824 case PSEUDO_DTOR_EXPR:
4825 case NEW_EXPR:
4826 case VEC_NEW_EXPR:
4827 case DELETE_EXPR:
4828 case VEC_DELETE_EXPR:
4829 case THROW_EXPR:
4830 case OMP_ATOMIC:
4831 case OMP_ATOMIC_READ:
4832 case OMP_ATOMIC_CAPTURE_OLD:
4833 case OMP_ATOMIC_CAPTURE_NEW:
4834 /* GCC internal stuff. */
4835 case VA_ARG_EXPR:
4836 case OBJ_TYPE_REF:
4837 case TRANSACTION_EXPR:
4838 case ASM_EXPR:
4839 case AT_ENCODE_EXPR:
4840 fail:
4841 if (flags & tf_error)
4842 error ("expression %qE is not a constant-expression", t);
4843 return false;
4845 case TYPEID_EXPR:
4846 /* -- a typeid expression whose operand is of polymorphic
4847 class type; */
4849 tree e = TREE_OPERAND (t, 0);
4850 if (!TYPE_P (e) && !type_dependent_expression_p (e)
4851 && TYPE_POLYMORPHIC_P (TREE_TYPE (e)))
4853 if (flags & tf_error)
4854 error ("typeid-expression is not a constant expression "
4855 "because %qE is of polymorphic type", e);
4856 return false;
4858 return true;
4861 case MINUS_EXPR:
4862 want_rval = true;
4863 goto binary;
4865 case LT_EXPR:
4866 case LE_EXPR:
4867 case GT_EXPR:
4868 case GE_EXPR:
4869 case EQ_EXPR:
4870 case NE_EXPR:
4871 want_rval = true;
4872 goto binary;
4874 case PREINCREMENT_EXPR:
4875 case POSTINCREMENT_EXPR:
4876 case PREDECREMENT_EXPR:
4877 case POSTDECREMENT_EXPR:
4878 if (cxx_dialect < cxx14)
4879 goto fail;
4880 goto unary;
4882 case BIT_NOT_EXPR:
4883 /* A destructor. */
4884 if (TYPE_P (TREE_OPERAND (t, 0)))
4885 return true;
4886 /* else fall through. */
4888 case REALPART_EXPR:
4889 case IMAGPART_EXPR:
4890 case CONJ_EXPR:
4891 case SAVE_EXPR:
4892 case FIX_TRUNC_EXPR:
4893 case FLOAT_EXPR:
4894 case NEGATE_EXPR:
4895 case ABS_EXPR:
4896 case TRUTH_NOT_EXPR:
4897 case FIXED_CONVERT_EXPR:
4898 case UNARY_PLUS_EXPR:
4899 case UNARY_LEFT_FOLD_EXPR:
4900 case UNARY_RIGHT_FOLD_EXPR:
4901 unary:
4902 return RECUR (TREE_OPERAND (t, 0), rval);
4904 case CAST_EXPR:
4905 case CONST_CAST_EXPR:
4906 case STATIC_CAST_EXPR:
4907 case REINTERPRET_CAST_EXPR:
4908 case IMPLICIT_CONV_EXPR:
4909 if (cxx_dialect < cxx11
4910 && !dependent_type_p (TREE_TYPE (t))
4911 && !INTEGRAL_OR_ENUMERATION_TYPE_P (TREE_TYPE (t)))
4912 /* In C++98, a conversion to non-integral type can't be part of a
4913 constant expression. */
4915 if (flags & tf_error)
4916 error ("cast to non-integral type %qT in a constant expression",
4917 TREE_TYPE (t));
4918 return false;
4921 return (RECUR (TREE_OPERAND (t, 0),
4922 TREE_CODE (TREE_TYPE (t)) != REFERENCE_TYPE));
4924 case BIND_EXPR:
4925 return RECUR (BIND_EXPR_BODY (t), want_rval);
4927 case WITH_CLEANUP_EXPR:
4928 case CLEANUP_POINT_EXPR:
4929 case MUST_NOT_THROW_EXPR:
4930 case TRY_CATCH_EXPR:
4931 case TRY_BLOCK:
4932 case EH_SPEC_BLOCK:
4933 case EXPR_STMT:
4934 case PAREN_EXPR:
4935 case DECL_EXPR:
4936 case NON_DEPENDENT_EXPR:
4937 /* For convenience. */
4938 case RETURN_EXPR:
4939 return RECUR (TREE_OPERAND (t, 0), want_rval);
4941 case TRY_FINALLY_EXPR:
4942 return (RECUR (TREE_OPERAND (t, 0), want_rval)
4943 && RECUR (TREE_OPERAND (t, 1), any));
4945 case SCOPE_REF:
4946 return RECUR (TREE_OPERAND (t, 1), want_rval);
4948 case TARGET_EXPR:
4949 if (!literal_type_p (TREE_TYPE (t)))
4951 if (flags & tf_error)
4953 error ("temporary of non-literal type %qT in a "
4954 "constant expression", TREE_TYPE (t));
4955 explain_non_literal_class (TREE_TYPE (t));
4957 return false;
4959 case INIT_EXPR:
4960 return RECUR (TREE_OPERAND (t, 1), rval);
4962 case CONSTRUCTOR:
4964 vec<constructor_elt, va_gc> *v = CONSTRUCTOR_ELTS (t);
4965 constructor_elt *ce;
4966 for (i = 0; vec_safe_iterate (v, i, &ce); ++i)
4967 if (!RECUR (ce->value, want_rval))
4968 return false;
4969 return true;
4972 case TREE_LIST:
4974 gcc_assert (TREE_PURPOSE (t) == NULL_TREE
4975 || DECL_P (TREE_PURPOSE (t)));
4976 if (!RECUR (TREE_VALUE (t), want_rval))
4977 return false;
4978 if (TREE_CHAIN (t) == NULL_TREE)
4979 return true;
4980 return RECUR (TREE_CHAIN (t), want_rval);
4983 case TRUNC_DIV_EXPR:
4984 case CEIL_DIV_EXPR:
4985 case FLOOR_DIV_EXPR:
4986 case ROUND_DIV_EXPR:
4987 case TRUNC_MOD_EXPR:
4988 case CEIL_MOD_EXPR:
4989 case ROUND_MOD_EXPR:
4991 tree denom = TREE_OPERAND (t, 1);
4992 if (!RECUR (denom, rval))
4993 return false;
4994 /* We can't call cxx_eval_outermost_constant_expr on an expression
4995 that hasn't been through instantiate_non_dependent_expr yet. */
4996 if (!processing_template_decl)
4997 denom = cxx_eval_outermost_constant_expr (denom, true);
4998 if (integer_zerop (denom))
5000 if (flags & tf_error)
5001 error ("division by zero is not a constant-expression");
5002 return false;
5004 else
5006 want_rval = true;
5007 return RECUR (TREE_OPERAND (t, 0), want_rval);
5011 case COMPOUND_EXPR:
5013 /* check_return_expr sometimes wraps a TARGET_EXPR in a
5014 COMPOUND_EXPR; don't get confused. Also handle EMPTY_CLASS_EXPR
5015 introduced by build_call_a. */
5016 tree op0 = TREE_OPERAND (t, 0);
5017 tree op1 = TREE_OPERAND (t, 1);
5018 STRIP_NOPS (op1);
5019 if ((TREE_CODE (op0) == TARGET_EXPR && op1 == TARGET_EXPR_SLOT (op0))
5020 || TREE_CODE (op1) == EMPTY_CLASS_EXPR)
5021 return RECUR (op0, want_rval);
5022 else
5023 goto binary;
5026 /* If the first operand is the non-short-circuit constant, look at
5027 the second operand; otherwise we only care about the first one for
5028 potentiality. */
5029 case TRUTH_AND_EXPR:
5030 case TRUTH_ANDIF_EXPR:
5031 tmp = boolean_true_node;
5032 goto truth;
5033 case TRUTH_OR_EXPR:
5034 case TRUTH_ORIF_EXPR:
5035 tmp = boolean_false_node;
5036 truth:
5038 tree op = TREE_OPERAND (t, 0);
5039 if (!RECUR (op, rval))
5040 return false;
5041 if (!processing_template_decl)
5042 op = cxx_eval_outermost_constant_expr (op, true);
5043 if (tree_int_cst_equal (op, tmp))
5044 return RECUR (TREE_OPERAND (t, 1), rval);
5045 else
5046 return true;
5049 case PLUS_EXPR:
5050 case MULT_EXPR:
5051 case POINTER_PLUS_EXPR:
5052 case RDIV_EXPR:
5053 case EXACT_DIV_EXPR:
5054 case MIN_EXPR:
5055 case MAX_EXPR:
5056 case LSHIFT_EXPR:
5057 case RSHIFT_EXPR:
5058 case LROTATE_EXPR:
5059 case RROTATE_EXPR:
5060 case BIT_IOR_EXPR:
5061 case BIT_XOR_EXPR:
5062 case BIT_AND_EXPR:
5063 case TRUTH_XOR_EXPR:
5064 case UNORDERED_EXPR:
5065 case ORDERED_EXPR:
5066 case UNLT_EXPR:
5067 case UNLE_EXPR:
5068 case UNGT_EXPR:
5069 case UNGE_EXPR:
5070 case UNEQ_EXPR:
5071 case LTGT_EXPR:
5072 case RANGE_EXPR:
5073 case COMPLEX_EXPR:
5074 want_rval = true;
5075 /* Fall through. */
5076 case ARRAY_REF:
5077 case ARRAY_RANGE_REF:
5078 case MEMBER_REF:
5079 case DOTSTAR_EXPR:
5080 case MEM_REF:
5081 case BINARY_LEFT_FOLD_EXPR:
5082 case BINARY_RIGHT_FOLD_EXPR:
5083 binary:
5084 for (i = 0; i < 2; ++i)
5085 if (!RECUR (TREE_OPERAND (t, i), want_rval))
5086 return false;
5087 return true;
5089 case CILK_SYNC_STMT:
5090 case CILK_SPAWN_STMT:
5091 case ARRAY_NOTATION_REF:
5092 return false;
5094 case FMA_EXPR:
5095 case VEC_PERM_EXPR:
5096 for (i = 0; i < 3; ++i)
5097 if (!RECUR (TREE_OPERAND (t, i), true))
5098 return false;
5099 return true;
5101 case COND_EXPR:
5102 if (COND_EXPR_IS_VEC_DELETE (t))
5104 if (flags & tf_error)
5105 error_at (location_of (t),
5106 "%<delete[]%> is not a constant-expression");
5107 return false;
5109 /* Fall through. */
5110 case IF_STMT:
5111 case VEC_COND_EXPR:
5112 /* If the condition is a known constant, we know which of the legs we
5113 care about; otherwise we only require that the condition and
5114 either of the legs be potentially constant. */
5115 tmp = TREE_OPERAND (t, 0);
5116 if (!RECUR (tmp, rval))
5117 return false;
5118 if (!processing_template_decl)
5119 tmp = cxx_eval_outermost_constant_expr (tmp, true);
5120 if (integer_zerop (tmp))
5121 return RECUR (TREE_OPERAND (t, 2), want_rval);
5122 else if (TREE_CODE (tmp) == INTEGER_CST)
5123 return RECUR (TREE_OPERAND (t, 1), want_rval);
5124 for (i = 1; i < 3; ++i)
5125 if (potential_constant_expression_1 (TREE_OPERAND (t, i),
5126 want_rval, strict, tf_none))
5127 return true;
5128 if (flags & tf_error)
5129 error ("expression %qE is not a constant-expression", t);
5130 return false;
5132 case VEC_INIT_EXPR:
5133 if (VEC_INIT_EXPR_IS_CONSTEXPR (t))
5134 return true;
5135 if (flags & tf_error)
5137 error ("non-constant array initialization");
5138 diagnose_non_constexpr_vec_init (t);
5140 return false;
5142 case TYPE_DECL:
5143 case TAG_DEFN:
5144 /* We can see these in statement-expressions. */
5145 return true;
5147 case EMPTY_CLASS_EXPR:
5148 return false;
5150 default:
5151 if (objc_is_property_ref (t))
5152 return false;
5154 sorry ("unexpected AST of kind %s", get_tree_code_name (TREE_CODE (t)));
5155 gcc_unreachable();
5156 return false;
5158 #undef RECUR
5161 /* The main entry point to the above. */
5163 bool
5164 potential_constant_expression (tree t)
5166 return potential_constant_expression_1 (t, false, true, tf_none);
5169 bool
5170 potential_static_init_expression (tree t)
5172 return potential_constant_expression_1 (t, false, false, tf_none);
5175 /* As above, but require a constant rvalue. */
5177 bool
5178 potential_rvalue_constant_expression (tree t)
5180 return potential_constant_expression_1 (t, true, true, tf_none);
5183 /* Like above, but complain about non-constant expressions. */
5185 bool
5186 require_potential_constant_expression (tree t)
5188 return potential_constant_expression_1 (t, false, true, tf_warning_or_error);
5191 /* Cross product of the above. */
5193 bool
5194 require_potential_rvalue_constant_expression (tree t)
5196 return potential_constant_expression_1 (t, true, true, tf_warning_or_error);
5199 /* Returns true if T is a potential constant expression that is not
5200 instantiation-dependent, and therefore a candidate for constant folding even
5201 in a template. */
5203 bool
5204 potential_nondependent_constant_expression (tree t)
5206 return (!type_unknown_p (t)
5207 && !BRACE_ENCLOSED_INITIALIZER_P (t)
5208 && potential_constant_expression (t)
5209 && !instantiation_dependent_expression_p (t));
5212 /* Returns true if T is a potential static initializer expression that is not
5213 instantiation-dependent. */
5215 bool
5216 potential_nondependent_static_init_expression (tree t)
5218 return (!type_unknown_p (t)
5219 && !BRACE_ENCLOSED_INITIALIZER_P (t)
5220 && potential_static_init_expression (t)
5221 && !instantiation_dependent_expression_p (t));
5224 #include "gt-cp-constexpr.h"