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.
4
5   Copyright (C) 1998-2015 Free Software Foundation, Inc.
6
7   This file is part of GCC.
8
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.
13
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.
18
19You should have received a copy of the GNU General Public License
20along with GCC; see the file COPYING3.  If not see
21<http://www.gnu.org/licenses/>.  */
22
23#include "config.h"
24#include "system.h"
25#include "coretypes.h"
26#include "hash-set.h"
27#include "machmode.h"
28#include "vec.h"
29#include "double-int.h"
30#include "input.h"
31#include "alias.h"
32#include "symtab.h"
33#include "options.h"
34#include "wide-int.h"
35#include "inchash.h"
36#include "tree.h"
37#include "varasm.h"
38#include "cp-tree.h"
39#include "c-family/c-objc.h"
40#include "tree-iterator.h"
41#include "gimplify.h"
42#include "builtins.h"
43#include "tree-inline.h"
44#include "ubsan.h"
45
46static bool verify_constant (tree, bool, bool *, bool *);
47#define VERIFY_CONSTANT(X)						\
48do {									\
49  if (verify_constant ((X), ctx->quiet, non_constant_p, overflow_p)) \
50    return t;								\
51 } while (0)
52
53/* Returns true iff FUN is an instantiation of a constexpr function
54   template or a defaulted constexpr function.  */
55
56bool
57is_instantiation_of_constexpr (tree fun)
58{
59  return ((DECL_TEMPLOID_INSTANTIATION (fun)
60	   && DECL_DECLARED_CONSTEXPR_P (DECL_TI_TEMPLATE (fun)))
61	  || (DECL_DEFAULTED_FN (fun)
62	      && DECL_DECLARED_CONSTEXPR_P (fun)));
63}
64
65/* Return true if T is a literal type.   */
66
67bool
68literal_type_p (tree t)
69{
70  if (SCALAR_TYPE_P (t)
71      || TREE_CODE (t) == VECTOR_TYPE
72      || TREE_CODE (t) == REFERENCE_TYPE
73      || (VOID_TYPE_P (t) && cxx_dialect >= cxx14))
74    return true;
75  if (CLASS_TYPE_P (t))
76    {
77      t = complete_type (t);
78      gcc_assert (COMPLETE_TYPE_P (t) || errorcount);
79      return CLASSTYPE_LITERAL_P (t);
80    }
81  if (TREE_CODE (t) == ARRAY_TYPE)
82    return literal_type_p (strip_array_types (t));
83  return false;
84}
85
86/* If DECL is a variable declared `constexpr', require its type
87   be literal.  Return the DECL if OK, otherwise NULL.  */
88
89tree
90ensure_literal_type_for_constexpr_object (tree decl)
91{
92  tree type = TREE_TYPE (decl);
93  if (VAR_P (decl)
94      && (DECL_DECLARED_CONSTEXPR_P (decl)
95	  || var_in_constexpr_fn (decl))
96      && !processing_template_decl)
97    {
98      tree stype = strip_array_types (type);
99      if (CLASS_TYPE_P (stype) && !COMPLETE_TYPE_P (complete_type (stype)))
100	/* Don't complain here, we'll complain about incompleteness
101	   when we try to initialize the variable.  */;
102      else if (!literal_type_p (type))
103	{
104	  if (DECL_DECLARED_CONSTEXPR_P (decl))
105	    {
106	      error ("the type %qT of constexpr variable %qD is not literal",
107		     type, decl);
108	      explain_non_literal_class (type);
109	    }
110	  else
111	    {
112	      if (!DECL_TEMPLATE_INSTANTIATION (current_function_decl))
113		{
114		  error ("variable %qD of non-literal type %qT in %<constexpr%> "
115			 "function", decl, type);
116		  explain_non_literal_class (type);
117		}
118	      cp_function_chain->invalid_constexpr = true;
119	    }
120	  return NULL;
121	}
122    }
123  return decl;
124}
125
126/* Representation of entries in the constexpr function definition table.  */
127
128struct GTY((for_user)) constexpr_fundef {
129  tree decl;
130  tree body;
131};
132
133struct constexpr_fundef_hasher : ggc_hasher<constexpr_fundef *>
134{
135  static hashval_t hash (constexpr_fundef *);
136  static bool equal (constexpr_fundef *, constexpr_fundef *);
137};
138
139/* This table holds all constexpr function definitions seen in
140   the current translation unit.  */
141
142static GTY (()) hash_table<constexpr_fundef_hasher> *constexpr_fundef_table;
143
144/* Utility function used for managing the constexpr function table.
145   Return true if the entries pointed to by P and Q are for the
146   same constexpr function.  */
147
148inline bool
149constexpr_fundef_hasher::equal (constexpr_fundef *lhs, constexpr_fundef *rhs)
150{
151  return lhs->decl == rhs->decl;
152}
153
154/* Utility function used for managing the constexpr function table.
155   Return a hash value for the entry pointed to by Q.  */
156
157inline hashval_t
158constexpr_fundef_hasher::hash (constexpr_fundef *fundef)
159{
160  return DECL_UID (fundef->decl);
161}
162
163/* Return a previously saved definition of function FUN.   */
164
165static constexpr_fundef *
166retrieve_constexpr_fundef (tree fun)
167{
168  constexpr_fundef fundef = { NULL, NULL };
169  if (constexpr_fundef_table == NULL)
170    return NULL;
171
172  fundef.decl = fun;
173  return constexpr_fundef_table->find (&fundef);
174}
175
176/* Check whether the parameter and return types of FUN are valid for a
177   constexpr function, and complain if COMPLAIN.  */
178
179static bool
180is_valid_constexpr_fn (tree fun, bool complain)
181{
182  bool ret = true;
183
184  if (DECL_INHERITED_CTOR_BASE (fun)
185      && TREE_CODE (fun) == TEMPLATE_DECL)
186    {
187      ret = false;
188      if (complain)
189	error ("inherited constructor %qD is not constexpr",
190	       get_inherited_ctor (fun));
191    }
192  else
193    {
194      for (tree parm = FUNCTION_FIRST_USER_PARM (fun);
195	   parm != NULL_TREE; parm = TREE_CHAIN (parm))
196	if (!literal_type_p (TREE_TYPE (parm)))
197	  {
198	    ret = false;
199	    if (complain)
200	      {
201		error ("invalid type for parameter %d of constexpr "
202		       "function %q+#D", DECL_PARM_INDEX (parm), fun);
203		explain_non_literal_class (TREE_TYPE (parm));
204	      }
205	  }
206    }
207
208  if (!DECL_CONSTRUCTOR_P (fun))
209    {
210      tree rettype = TREE_TYPE (TREE_TYPE (fun));
211      if (!literal_type_p (rettype))
212	{
213	  ret = false;
214	  if (complain)
215	    {
216	      error ("invalid return type %qT of constexpr function %q+D",
217		     rettype, fun);
218	      explain_non_literal_class (rettype);
219	    }
220	}
221
222      if (DECL_NONSTATIC_MEMBER_FUNCTION_P (fun)
223	  && !CLASSTYPE_LITERAL_P (DECL_CONTEXT (fun)))
224	{
225	  ret = false;
226	  if (complain)
227	    {
228	      error ("enclosing class of constexpr non-static member "
229		     "function %q+#D is not a literal type", fun);
230	      explain_non_literal_class (DECL_CONTEXT (fun));
231	    }
232	}
233    }
234  else if (CLASSTYPE_VBASECLASSES (DECL_CONTEXT (fun)))
235    {
236      ret = false;
237      if (complain)
238	error ("%q#T has virtual base classes", DECL_CONTEXT (fun));
239    }
240
241  return ret;
242}
243
244/* Subroutine of build_data_member_initialization.  MEMBER is a COMPONENT_REF
245   for a member of an anonymous aggregate, INIT is the initializer for that
246   member, and VEC_OUTER is the vector of constructor elements for the class
247   whose constructor we are processing.  Add the initializer to the vector
248   and return true to indicate success.  */
249
250static bool
251build_anon_member_initialization (tree member, tree init,
252				  vec<constructor_elt, va_gc> **vec_outer)
253{
254  /* MEMBER presents the relevant fields from the inside out, but we need
255     to build up the initializer from the outside in so that we can reuse
256     previously built CONSTRUCTORs if this is, say, the second field in an
257     anonymous struct.  So we use a vec as a stack.  */
258  auto_vec<tree, 2> fields;
259  do
260    {
261      fields.safe_push (TREE_OPERAND (member, 1));
262      member = TREE_OPERAND (member, 0);
263    }
264  while (ANON_AGGR_TYPE_P (TREE_TYPE (member))
265	 && TREE_CODE (member) == COMPONENT_REF);
266
267  /* VEC has the constructor elements vector for the context of FIELD.
268     If FIELD is an anonymous aggregate, we will push inside it.  */
269  vec<constructor_elt, va_gc> **vec = vec_outer;
270  tree field;
271  while (field = fields.pop(),
272	 ANON_AGGR_TYPE_P (TREE_TYPE (field)))
273    {
274      tree ctor;
275      /* If there is already an outer constructor entry for the anonymous
276	 aggregate FIELD, use it; otherwise, insert one.  */
277      if (vec_safe_is_empty (*vec)
278	  || (*vec)->last().index != field)
279	{
280	  ctor = build_constructor (TREE_TYPE (field), NULL);
281	  CONSTRUCTOR_APPEND_ELT (*vec, field, ctor);
282	}
283      else
284	ctor = (*vec)->last().value;
285      vec = &CONSTRUCTOR_ELTS (ctor);
286    }
287
288  /* Now we're at the innermost field, the one that isn't an anonymous
289     aggregate.  Add its initializer to the CONSTRUCTOR and we're done.  */
290  gcc_assert (fields.is_empty());
291  CONSTRUCTOR_APPEND_ELT (*vec, field, init);
292
293  return true;
294}
295
296/* Subroutine of  build_constexpr_constructor_member_initializers.
297   The expression tree T represents a data member initialization
298   in a (constexpr) constructor definition.  Build a pairing of
299   the data member with its initializer, and prepend that pair
300   to the existing initialization pair INITS.  */
301
302static bool
303build_data_member_initialization (tree t, vec<constructor_elt, va_gc> **vec)
304{
305  tree member, init;
306  if (TREE_CODE (t) == CLEANUP_POINT_EXPR)
307    t = TREE_OPERAND (t, 0);
308  if (TREE_CODE (t) == EXPR_STMT)
309    t = TREE_OPERAND (t, 0);
310  if (t == error_mark_node)
311    return false;
312  if (TREE_CODE (t) == STATEMENT_LIST)
313    {
314      tree_stmt_iterator i;
315      for (i = tsi_start (t); !tsi_end_p (i); tsi_next (&i))
316	{
317	  if (! build_data_member_initialization (tsi_stmt (i), vec))
318	    return false;
319	}
320      return true;
321    }
322  if (TREE_CODE (t) == CLEANUP_STMT)
323    {
324      /* We can't see a CLEANUP_STMT in a constructor for a literal class,
325	 but we can in a constexpr constructor for a non-literal class.  Just
326	 ignore it; either all the initialization will be constant, in which
327	 case the cleanup can't run, or it can't be constexpr.
328	 Still recurse into CLEANUP_BODY.  */
329      return build_data_member_initialization (CLEANUP_BODY (t), vec);
330    }
331  if (TREE_CODE (t) == CONVERT_EXPR)
332    t = TREE_OPERAND (t, 0);
333  if (TREE_CODE (t) == INIT_EXPR
334      /* vptr initialization shows up as a MODIFY_EXPR.  In C++14 we only
335	 use what this function builds for cx_check_missing_mem_inits, and
336	 assignment in the ctor body doesn't count.  */
337      || (cxx_dialect < cxx14 && TREE_CODE (t) == MODIFY_EXPR))
338    {
339      member = TREE_OPERAND (t, 0);
340      init = break_out_target_exprs (TREE_OPERAND (t, 1));
341    }
342  else if (TREE_CODE (t) == CALL_EXPR)
343    {
344      tree fn = get_callee_fndecl (t);
345      if (!fn || !DECL_CONSTRUCTOR_P (fn))
346	/* We're only interested in calls to subobject constructors.  */
347	return true;
348      member = CALL_EXPR_ARG (t, 0);
349      /* We don't use build_cplus_new here because it complains about
350	 abstract bases.  Leaving the call unwrapped means that it has the
351	 wrong type, but cxx_eval_constant_expression doesn't care.  */
352      init = break_out_target_exprs (t);
353    }
354  else if (TREE_CODE (t) == BIND_EXPR)
355    return build_data_member_initialization (BIND_EXPR_BODY (t), vec);
356  else
357    /* Don't add anything else to the CONSTRUCTOR.  */
358    return true;
359  if (INDIRECT_REF_P (member))
360    member = TREE_OPERAND (member, 0);
361  if (TREE_CODE (member) == NOP_EXPR)
362    {
363      tree op = member;
364      STRIP_NOPS (op);
365      if (TREE_CODE (op) == ADDR_EXPR)
366	{
367	  gcc_assert (same_type_ignoring_top_level_qualifiers_p
368		      (TREE_TYPE (TREE_TYPE (op)),
369		       TREE_TYPE (TREE_TYPE (member))));
370	  /* Initializing a cv-qualified member; we need to look through
371	     the const_cast.  */
372	  member = op;
373	}
374      else if (op == current_class_ptr
375	       && (same_type_ignoring_top_level_qualifiers_p
376		   (TREE_TYPE (TREE_TYPE (member)),
377		    current_class_type)))
378	/* Delegating constructor.  */
379	member = op;
380      else
381	{
382	  /* This is an initializer for an empty base; keep it for now so
383	     we can check it in cxx_eval_bare_aggregate.  */
384	  gcc_assert (is_empty_class (TREE_TYPE (TREE_TYPE (member))));
385	}
386    }
387  if (TREE_CODE (member) == ADDR_EXPR)
388    member = TREE_OPERAND (member, 0);
389  if (TREE_CODE (member) == COMPONENT_REF)
390    {
391      tree aggr = TREE_OPERAND (member, 0);
392      if (TREE_CODE (aggr) != COMPONENT_REF)
393	/* Normal member initialization.  */
394	member = TREE_OPERAND (member, 1);
395      else if (ANON_AGGR_TYPE_P (TREE_TYPE (aggr)))
396	/* Initializing a member of an anonymous union.  */
397	return build_anon_member_initialization (member, init, vec);
398      else
399	/* We're initializing a vtable pointer in a base.  Leave it as
400	   COMPONENT_REF so we remember the path to get to the vfield.  */
401	gcc_assert (TREE_TYPE (member) == vtbl_ptr_type_node);
402    }
403
404  CONSTRUCTOR_APPEND_ELT (*vec, member, init);
405  return true;
406}
407
408/* Subroutine of check_constexpr_ctor_body_1 and constexpr_fn_retval.
409   In C++11 mode checks that the TYPE_DECLs in the BIND_EXPR_VARS of a
410   BIND_EXPR conform to 7.1.5/3/4 on typedef and alias declarations.  */
411
412static bool
413check_constexpr_bind_expr_vars (tree t)
414{
415  gcc_assert (TREE_CODE (t) == BIND_EXPR);
416
417  for (tree var = BIND_EXPR_VARS (t); var; var = DECL_CHAIN (var))
418    if (TREE_CODE (var) == TYPE_DECL
419	&& DECL_IMPLICIT_TYPEDEF_P (var)
420	&& !LAMBDA_TYPE_P (TREE_TYPE (var)))
421      return false;
422  return true;
423}
424
425/* Subroutine of check_constexpr_ctor_body.  */
426
427static bool
428check_constexpr_ctor_body_1 (tree last, tree list)
429{
430  switch (TREE_CODE (list))
431    {
432    case DECL_EXPR:
433      if (TREE_CODE (DECL_EXPR_DECL (list)) == USING_DECL)
434	return true;
435      return false;
436
437    case CLEANUP_POINT_EXPR:
438      return check_constexpr_ctor_body (last, TREE_OPERAND (list, 0),
439					/*complain=*/false);
440
441    case BIND_EXPR:
442       if (!check_constexpr_bind_expr_vars (list)
443	   || !check_constexpr_ctor_body (last, BIND_EXPR_BODY (list),
444					  /*complain=*/false))
445	 return false;
446       return true;
447
448    case USING_STMT:
449    case STATIC_ASSERT:
450      return true;
451
452    default:
453      return false;
454    }
455}
456
457/* Make sure that there are no statements after LAST in the constructor
458   body represented by LIST.  */
459
460bool
461check_constexpr_ctor_body (tree last, tree list, bool complain)
462{
463  /* C++14 doesn't require a constexpr ctor to have an empty body.  */
464  if (cxx_dialect >= cxx14)
465    return true;
466
467  bool ok = true;
468  if (TREE_CODE (list) == STATEMENT_LIST)
469    {
470      tree_stmt_iterator i = tsi_last (list);
471      for (; !tsi_end_p (i); tsi_prev (&i))
472	{
473	  tree t = tsi_stmt (i);
474	  if (t == last)
475	    break;
476	  if (!check_constexpr_ctor_body_1 (last, t))
477	    {
478	      ok = false;
479	      break;
480	    }
481	}
482    }
483  else if (list != last
484	   && !check_constexpr_ctor_body_1 (last, list))
485    ok = false;
486  if (!ok)
487    {
488      if (complain)
489	error ("constexpr constructor does not have empty body");
490      DECL_DECLARED_CONSTEXPR_P (current_function_decl) = false;
491    }
492  return ok;
493}
494
495/* V is a vector of constructor elements built up for the base and member
496   initializers of a constructor for TYPE.  They need to be in increasing
497   offset order, which they might not be yet if TYPE has a primary base
498   which is not first in the base-clause or a vptr and at least one base
499   all of which are non-primary.  */
500
501static vec<constructor_elt, va_gc> *
502sort_constexpr_mem_initializers (tree type, vec<constructor_elt, va_gc> *v)
503{
504  tree pri = CLASSTYPE_PRIMARY_BINFO (type);
505  tree field_type;
506  unsigned i;
507  constructor_elt *ce;
508
509  if (pri)
510    field_type = BINFO_TYPE (pri);
511  else if (TYPE_CONTAINS_VPTR_P (type))
512    field_type = vtbl_ptr_type_node;
513  else
514    return v;
515
516  /* Find the element for the primary base or vptr and move it to the
517     beginning of the vec.  */
518  for (i = 0; vec_safe_iterate (v, i, &ce); ++i)
519    if (TREE_TYPE (ce->index) == field_type)
520      break;
521
522  if (i > 0 && i < vec_safe_length (v))
523    {
524      vec<constructor_elt, va_gc> &vref = *v;
525      constructor_elt elt = vref[i];
526      for (; i > 0; --i)
527	vref[i] = vref[i-1];
528      vref[0] = elt;
529    }
530
531  return v;
532}
533
534/* Build compile-time evalable representations of member-initializer list
535   for a constexpr constructor.  */
536
537static tree
538build_constexpr_constructor_member_initializers (tree type, tree body)
539{
540  vec<constructor_elt, va_gc> *vec = NULL;
541  bool ok = true;
542 top:
543  if (TREE_CODE (body) == MUST_NOT_THROW_EXPR
544      || TREE_CODE (body) == EH_SPEC_BLOCK)
545    body = TREE_OPERAND (body, 0);
546  if (TREE_CODE (body) == STATEMENT_LIST)
547    {
548      for (tree_stmt_iterator i = tsi_start (body);
549	   !tsi_end_p (i); tsi_next (&i))
550	{
551	  body = tsi_stmt (i);
552	  if (TREE_CODE (body) == BIND_EXPR)
553	    break;
554	  if (TREE_CODE (body) == MUST_NOT_THROW_EXPR)
555	    goto top;
556	}
557    }
558  if (TREE_CODE (body) == BIND_EXPR)
559    body = BIND_EXPR_BODY (body);
560  if (TREE_CODE (body) == CLEANUP_POINT_EXPR)
561    {
562      body = TREE_OPERAND (body, 0);
563      if (TREE_CODE (body) == EXPR_STMT)
564	body = TREE_OPERAND (body, 0);
565      if (TREE_CODE (body) == INIT_EXPR
566	  && (same_type_ignoring_top_level_qualifiers_p
567	      (TREE_TYPE (TREE_OPERAND (body, 0)),
568	       current_class_type)))
569	{
570	  /* Trivial copy.  */
571	  return TREE_OPERAND (body, 1);
572	}
573      ok = build_data_member_initialization (body, &vec);
574    }
575  else if (TREE_CODE (body) == STATEMENT_LIST)
576    {
577      tree_stmt_iterator i;
578      for (i = tsi_start (body); !tsi_end_p (i); tsi_next (&i))
579	{
580	  ok = build_data_member_initialization (tsi_stmt (i), &vec);
581	  if (!ok)
582	    break;
583	}
584    }
585  else if (TREE_CODE (body) == TRY_BLOCK)
586    {
587      error ("body of %<constexpr%> constructor cannot be "
588	     "a function-try-block");
589      return error_mark_node;
590    }
591  else if (EXPR_P (body))
592    ok = build_data_member_initialization (body, &vec);
593  else
594    gcc_assert (errorcount > 0);
595  if (ok)
596    {
597      if (vec_safe_length (vec) > 0)
598	{
599	  /* In a delegating constructor, return the target.  */
600	  constructor_elt *ce = &(*vec)[0];
601	  if (ce->index == current_class_ptr)
602	    {
603	      body = ce->value;
604	      vec_free (vec);
605	      return body;
606	    }
607	}
608      vec = sort_constexpr_mem_initializers (type, vec);
609      return build_constructor (type, vec);
610    }
611  else
612    return error_mark_node;
613}
614
615/* Subroutine of register_constexpr_fundef.  BODY is the body of a function
616   declared to be constexpr, or a sub-statement thereof.  Returns the
617   return value if suitable, error_mark_node for a statement not allowed in
618   a constexpr function, or NULL_TREE if no return value was found.  */
619
620static tree
621constexpr_fn_retval (tree body)
622{
623  switch (TREE_CODE (body))
624    {
625    case STATEMENT_LIST:
626      {
627	tree_stmt_iterator i;
628	tree expr = NULL_TREE;
629	for (i = tsi_start (body); !tsi_end_p (i); tsi_next (&i))
630	  {
631	    tree s = constexpr_fn_retval (tsi_stmt (i));
632	    if (s == error_mark_node)
633	      return error_mark_node;
634	    else if (s == NULL_TREE)
635	      /* Keep iterating.  */;
636	    else if (expr)
637	      /* Multiple return statements.  */
638	      return error_mark_node;
639	    else
640	      expr = s;
641	  }
642	return expr;
643      }
644
645    case RETURN_EXPR:
646      return break_out_target_exprs (TREE_OPERAND (body, 0));
647
648    case DECL_EXPR:
649      {
650	tree decl = DECL_EXPR_DECL (body);
651	if (TREE_CODE (decl) == USING_DECL
652	    /* Accept __func__, __FUNCTION__, and __PRETTY_FUNCTION__.  */
653	    || DECL_ARTIFICIAL (decl))
654	  return NULL_TREE;
655	return error_mark_node;
656      }
657
658    case CLEANUP_POINT_EXPR:
659      return constexpr_fn_retval (TREE_OPERAND (body, 0));
660
661    case BIND_EXPR:
662      if (!check_constexpr_bind_expr_vars (body))
663	return error_mark_node;
664      return constexpr_fn_retval (BIND_EXPR_BODY (body));
665
666    case USING_STMT:
667      return NULL_TREE;
668
669    default:
670      return error_mark_node;
671    }
672}
673
674/* Subroutine of register_constexpr_fundef.  BODY is the DECL_SAVED_TREE of
675   FUN; do the necessary transformations to turn it into a single expression
676   that we can store in the hash table.  */
677
678static tree
679massage_constexpr_body (tree fun, tree body)
680{
681  if (DECL_CONSTRUCTOR_P (fun))
682    body = build_constexpr_constructor_member_initializers
683      (DECL_CONTEXT (fun), body);
684  else if (cxx_dialect < cxx14)
685    {
686      if (TREE_CODE (body) == EH_SPEC_BLOCK)
687        body = EH_SPEC_STMTS (body);
688      if (TREE_CODE (body) == MUST_NOT_THROW_EXPR)
689	body = TREE_OPERAND (body, 0);
690      body = constexpr_fn_retval (body);
691    }
692  return body;
693}
694
695/* FUN is a constexpr constructor with massaged body BODY.  Return true
696   if some bases/fields are uninitialized, and complain if COMPLAIN.  */
697
698static bool
699cx_check_missing_mem_inits (tree fun, tree body, bool complain)
700{
701  bool bad;
702  tree field;
703  unsigned i, nelts;
704  tree ctype;
705
706  if (TREE_CODE (body) != CONSTRUCTOR)
707    return false;
708
709  nelts = CONSTRUCTOR_NELTS (body);
710  ctype = DECL_CONTEXT (fun);
711  field = TYPE_FIELDS (ctype);
712
713  if (TREE_CODE (ctype) == UNION_TYPE)
714    {
715      if (nelts == 0 && next_initializable_field (field))
716	{
717	  if (complain)
718	    error ("%<constexpr%> constructor for union %qT must "
719		   "initialize exactly one non-static data member", ctype);
720	  return true;
721	}
722      return false;
723    }
724
725  bad = false;
726  for (i = 0; i <= nelts; ++i)
727    {
728      tree index;
729      if (i == nelts)
730	index = NULL_TREE;
731      else
732	{
733	  index = CONSTRUCTOR_ELT (body, i)->index;
734	  /* Skip base and vtable inits.  */
735	  if (TREE_CODE (index) != FIELD_DECL
736	      || DECL_ARTIFICIAL (index))
737	    continue;
738	}
739      for (; field != index; field = DECL_CHAIN (field))
740	{
741	  tree ftype;
742	  if (TREE_CODE (field) != FIELD_DECL
743	      || (DECL_C_BIT_FIELD (field) && !DECL_NAME (field))
744	      || DECL_ARTIFICIAL (field))
745	    continue;
746	  ftype = strip_array_types (TREE_TYPE (field));
747	  if (type_has_constexpr_default_constructor (ftype))
748	    {
749	      /* It's OK to skip a member with a trivial constexpr ctor.
750	         A constexpr ctor that isn't trivial should have been
751	         added in by now.  */
752	      gcc_checking_assert (!TYPE_HAS_COMPLEX_DFLT (ftype)
753				   || errorcount != 0);
754	      continue;
755	    }
756	  if (!complain)
757	    return true;
758	  error ("member %qD must be initialized by mem-initializer "
759		 "in %<constexpr%> constructor", field);
760	  inform (DECL_SOURCE_LOCATION (field), "declared here");
761	  bad = true;
762	}
763      if (field == NULL_TREE)
764	break;
765      field = DECL_CHAIN (field);
766    }
767
768  return bad;
769}
770
771/* We are processing the definition of the constexpr function FUN.
772   Check that its BODY fulfills the propriate requirements and
773   enter it in the constexpr function definition table.
774   For constructor BODY is actually the TREE_LIST of the
775   member-initializer list.  */
776
777tree
778register_constexpr_fundef (tree fun, tree body)
779{
780  constexpr_fundef entry;
781  constexpr_fundef **slot;
782
783  if (!is_valid_constexpr_fn (fun, !DECL_GENERATED_P (fun)))
784    return NULL;
785
786  body = massage_constexpr_body (fun, body);
787  if (body == NULL_TREE || body == error_mark_node)
788    {
789      if (!DECL_CONSTRUCTOR_P (fun))
790	error ("body of constexpr function %qD not a return-statement", fun);
791      return NULL;
792    }
793
794  if (!potential_rvalue_constant_expression (body))
795    {
796      if (!DECL_GENERATED_P (fun))
797	require_potential_rvalue_constant_expression (body);
798      return NULL;
799    }
800
801  if (DECL_CONSTRUCTOR_P (fun)
802      && cx_check_missing_mem_inits (fun, body, !DECL_GENERATED_P (fun)))
803    return NULL;
804
805  /* Create the constexpr function table if necessary.  */
806  if (constexpr_fundef_table == NULL)
807    constexpr_fundef_table
808      = hash_table<constexpr_fundef_hasher>::create_ggc (101);
809
810  entry.decl = fun;
811  entry.body = body;
812  slot = constexpr_fundef_table->find_slot (&entry, INSERT);
813
814  gcc_assert (*slot == NULL);
815  *slot = ggc_alloc<constexpr_fundef> ();
816  **slot = entry;
817
818  return fun;
819}
820
821/* FUN is a non-constexpr function called in a context that requires a
822   constant expression.  If it comes from a constexpr template, explain why
823   the instantiation isn't constexpr.  */
824
825void
826explain_invalid_constexpr_fn (tree fun)
827{
828  static hash_set<tree> *diagnosed;
829  tree body;
830  location_t save_loc;
831  /* Only diagnose defaulted functions or instantiations.  */
832  if (!DECL_DEFAULTED_FN (fun)
833      && !is_instantiation_of_constexpr (fun))
834    return;
835  if (diagnosed == NULL)
836    diagnosed = new hash_set<tree>;
837  if (diagnosed->add (fun))
838    /* Already explained.  */
839    return;
840
841  save_loc = input_location;
842  input_location = DECL_SOURCE_LOCATION (fun);
843  inform (0, "%q+D is not usable as a constexpr function because:", fun);
844  /* First check the declaration.  */
845  if (is_valid_constexpr_fn (fun, true))
846    {
847      /* Then if it's OK, the body.  */
848      if (!DECL_DECLARED_CONSTEXPR_P (fun))
849	explain_implicit_non_constexpr (fun);
850      else
851	{
852	  body = massage_constexpr_body (fun, DECL_SAVED_TREE (fun));
853	  require_potential_rvalue_constant_expression (body);
854	  if (DECL_CONSTRUCTOR_P (fun))
855	    cx_check_missing_mem_inits (fun, body, true);
856	}
857    }
858  input_location = save_loc;
859}
860
861/* Objects of this type represent calls to constexpr functions
862   along with the bindings of parameters to their arguments, for
863   the purpose of compile time evaluation.  */
864
865struct GTY((for_user)) constexpr_call {
866  /* Description of the constexpr function definition.  */
867  constexpr_fundef *fundef;
868  /* Parameter bindings environment.  A TREE_LIST where each TREE_PURPOSE
869     is a parameter _DECL and the TREE_VALUE is the value of the parameter.
870     Note: This arrangement is made to accommodate the use of
871     iterative_hash_template_arg (see pt.c).  If you change this
872     representation, also change the hash calculation in
873     cxx_eval_call_expression.  */
874  tree bindings;
875  /* Result of the call.
876       NULL means the call is being evaluated.
877       error_mark_node means that the evaluation was erroneous;
878       otherwise, the actuall value of the call.  */
879  tree result;
880  /* The hash of this call; we remember it here to avoid having to
881     recalculate it when expanding the hash table.  */
882  hashval_t hash;
883};
884
885struct constexpr_call_hasher : ggc_hasher<constexpr_call *>
886{
887  static hashval_t hash (constexpr_call *);
888  static bool equal (constexpr_call *, constexpr_call *);
889};
890
891/* The constexpr expansion context.  CALL is the current function
892   expansion, CTOR is the current aggregate initializer, OBJECT is the
893   object being initialized by CTOR, either a VAR_DECL or a _REF.  VALUES
894   is a map of values of variables initialized within the expression.  */
895
896struct constexpr_ctx {
897  /* The innermost call we're evaluating.  */
898  constexpr_call *call;
899  /* Values for any temporaries or local variables within the
900     constant-expression. */
901  hash_map<tree,tree> *values;
902  /* SAVE_EXPRs that we've seen within the current LOOP_EXPR.  NULL if we
903     aren't inside a loop.  */
904  hash_set<tree> *save_exprs;
905  /* The CONSTRUCTOR we're currently building up for an aggregate
906     initializer.  */
907  tree ctor;
908  /* The object we're building the CONSTRUCTOR for.  */
909  tree object;
910  /* Whether we should error on a non-constant expression or fail quietly.  */
911  bool quiet;
912  /* Whether we are strictly conforming to constant expression rules or
913     trying harder to get a constant value.  */
914  bool strict;
915};
916
917/* A table of all constexpr calls that have been evaluated by the
918   compiler in this translation unit.  */
919
920static GTY (()) hash_table<constexpr_call_hasher> *constexpr_call_table;
921
922static tree cxx_eval_constant_expression (const constexpr_ctx *, tree,
923					  bool, bool *, bool *, tree * = NULL);
924
925/* Compute a hash value for a constexpr call representation.  */
926
927inline hashval_t
928constexpr_call_hasher::hash (constexpr_call *info)
929{
930  return info->hash;
931}
932
933/* Return true if the objects pointed to by P and Q represent calls
934   to the same constexpr function with the same arguments.
935   Otherwise, return false.  */
936
937bool
938constexpr_call_hasher::equal (constexpr_call *lhs, constexpr_call *rhs)
939{
940  tree lhs_bindings;
941  tree rhs_bindings;
942  if (lhs == rhs)
943    return 1;
944  if (!constexpr_fundef_hasher::equal (lhs->fundef, rhs->fundef))
945    return 0;
946  lhs_bindings = lhs->bindings;
947  rhs_bindings = rhs->bindings;
948  while (lhs_bindings != NULL && rhs_bindings != NULL)
949    {
950      tree lhs_arg = TREE_VALUE (lhs_bindings);
951      tree rhs_arg = TREE_VALUE (rhs_bindings);
952      gcc_assert (TREE_TYPE (lhs_arg) == TREE_TYPE (rhs_arg));
953      if (!cp_tree_equal (lhs_arg, rhs_arg))
954        return 0;
955      lhs_bindings = TREE_CHAIN (lhs_bindings);
956      rhs_bindings = TREE_CHAIN (rhs_bindings);
957    }
958  return lhs_bindings == rhs_bindings;
959}
960
961/* Initialize the constexpr call table, if needed.  */
962
963static void
964maybe_initialize_constexpr_call_table (void)
965{
966  if (constexpr_call_table == NULL)
967    constexpr_call_table = hash_table<constexpr_call_hasher>::create_ggc (101);
968}
969
970/* We have an expression tree T that represents a call, either CALL_EXPR
971   or AGGR_INIT_EXPR.  If the call is lexically to a named function,
972   retrun the _DECL for that function.  */
973
974static tree
975get_function_named_in_call (tree t)
976{
977  tree fun = NULL;
978  switch (TREE_CODE (t))
979    {
980    case CALL_EXPR:
981      fun = CALL_EXPR_FN (t);
982      break;
983
984    case AGGR_INIT_EXPR:
985      fun = AGGR_INIT_EXPR_FN (t);
986      break;
987
988    default:
989      gcc_unreachable();
990      break;
991    }
992  if (fun && TREE_CODE (fun) == ADDR_EXPR
993      && TREE_CODE (TREE_OPERAND (fun, 0)) == FUNCTION_DECL)
994    fun = TREE_OPERAND (fun, 0);
995  return fun;
996}
997
998/* We have an expression tree T that represents a call, either CALL_EXPR
999   or AGGR_INIT_EXPR.  Return the Nth argument.  */
1000
1001static inline tree
1002get_nth_callarg (tree t, int n)
1003{
1004  switch (TREE_CODE (t))
1005    {
1006    case CALL_EXPR:
1007      return CALL_EXPR_ARG (t, n);
1008
1009    case AGGR_INIT_EXPR:
1010      return AGGR_INIT_EXPR_ARG (t, n);
1011
1012    default:
1013      gcc_unreachable ();
1014      return NULL;
1015    }
1016}
1017
1018/* Look up the binding of the function parameter T in a constexpr
1019   function call context CALL.  */
1020
1021static tree
1022lookup_parameter_binding (const constexpr_call *call, tree t)
1023{
1024  tree b = purpose_member (t, call->bindings);
1025  return TREE_VALUE (b);
1026}
1027
1028/* Attempt to evaluate T which represents a call to a builtin function.
1029   We assume here that all builtin functions evaluate to scalar types
1030   represented by _CST nodes.  */
1031
1032static tree
1033cxx_eval_builtin_function_call (const constexpr_ctx *ctx, tree t,
1034				bool lval,
1035				bool *non_constant_p, bool *overflow_p)
1036{
1037  const int nargs = call_expr_nargs (t);
1038  tree *args = (tree *) alloca (nargs * sizeof (tree));
1039  tree new_call;
1040  int i;
1041  for (i = 0; i < nargs; ++i)
1042    {
1043      args[i] = cxx_eval_constant_expression (ctx, CALL_EXPR_ARG (t, i),
1044					      lval,
1045					      non_constant_p, overflow_p);
1046      if (ctx->quiet && *non_constant_p)
1047	return t;
1048    }
1049  if (*non_constant_p)
1050    return t;
1051  new_call = fold_build_call_array_loc (EXPR_LOCATION (t), TREE_TYPE (t),
1052					CALL_EXPR_FN (t), nargs, args);
1053  VERIFY_CONSTANT (new_call);
1054  return new_call;
1055}
1056
1057/* TEMP is the constant value of a temporary object of type TYPE.  Adjust
1058   the type of the value to match.  */
1059
1060static tree
1061adjust_temp_type (tree type, tree temp)
1062{
1063  if (TREE_TYPE (temp) == type)
1064    return temp;
1065  /* Avoid wrapping an aggregate value in a NOP_EXPR.  */
1066  if (TREE_CODE (temp) == CONSTRUCTOR)
1067    return build_constructor (type, CONSTRUCTOR_ELTS (temp));
1068  gcc_assert (scalarish_type_p (type));
1069  return cp_fold_convert (type, temp);
1070}
1071
1072/* True if we want to use the new handling of constexpr calls based on
1073   DECL_SAVED_TREE.  */
1074#define use_new_call true
1075
1076/* Subroutine of cxx_eval_call_expression.
1077   We are processing a call expression (either CALL_EXPR or
1078   AGGR_INIT_EXPR) in the context of CTX.  Evaluate
1079   all arguments and bind their values to correspondings
1080   parameters, making up the NEW_CALL context.  */
1081
1082static void
1083cxx_bind_parameters_in_call (const constexpr_ctx *ctx, tree t,
1084                             constexpr_call *new_call,
1085			     bool *non_constant_p, bool *overflow_p,
1086			     bool *non_constant_args)
1087{
1088  const int nargs = call_expr_nargs (t);
1089  tree fun = new_call->fundef->decl;
1090  tree parms = DECL_ARGUMENTS (fun);
1091  int i;
1092  tree *p = &new_call->bindings;
1093  for (i = 0; i < nargs; ++i)
1094    {
1095      tree x, arg;
1096      tree type = parms ? TREE_TYPE (parms) : void_type_node;
1097      x = get_nth_callarg (t, i);
1098      /* For member function, the first argument is a pointer to the implied
1099         object.  For a constructor, it might still be a dummy object, in
1100         which case we get the real argument from ctx. */
1101      if (i == 0 && DECL_CONSTRUCTOR_P (fun)
1102	  && is_dummy_object (x))
1103	{
1104	  x = ctx->object;
1105	  x = cp_build_addr_expr (x, tf_warning_or_error);
1106	}
1107      bool lval = false;
1108      if (parms && DECL_BY_REFERENCE (parms) && !use_new_call)
1109	{
1110	  /* cp_genericize made this a reference for argument passing, but
1111	     we don't want to treat it like one for C++11 constexpr
1112	     evaluation.  C++14 constexpr evaluation uses the genericized
1113	     DECL_SAVED_TREE.  */
1114	  gcc_assert (TREE_CODE (type) == REFERENCE_TYPE);
1115	  gcc_assert (TREE_CODE (TREE_TYPE (x)) == REFERENCE_TYPE);
1116	  type = TREE_TYPE (type);
1117	  x = convert_from_reference (x);
1118	  lval = true;
1119	}
1120      arg = cxx_eval_constant_expression (ctx, x, lval,
1121					  non_constant_p, overflow_p);
1122      /* Don't VERIFY_CONSTANT here.  */
1123      if (*non_constant_p && ctx->quiet)
1124	return;
1125      /* Just discard ellipsis args after checking their constantitude.  */
1126      if (!parms)
1127	continue;
1128      if (*non_constant_p)
1129	/* Don't try to adjust the type of non-constant args.  */
1130	goto next;
1131
1132      /* Make sure the binding has the same type as the parm.  */
1133      if (TREE_CODE (type) != REFERENCE_TYPE)
1134	arg = adjust_temp_type (type, arg);
1135      if (!TREE_CONSTANT (arg))
1136	*non_constant_args = true;
1137      *p = build_tree_list (parms, arg);
1138      p = &TREE_CHAIN (*p);
1139    next:
1140      parms = TREE_CHAIN (parms);
1141    }
1142}
1143
1144/* Variables and functions to manage constexpr call expansion context.
1145   These do not need to be marked for PCH or GC.  */
1146
1147/* FIXME remember and print actual constant arguments.  */
1148static vec<tree> call_stack = vNULL;
1149static int call_stack_tick;
1150static int last_cx_error_tick;
1151
1152static bool
1153push_cx_call_context (tree call)
1154{
1155  ++call_stack_tick;
1156  if (!EXPR_HAS_LOCATION (call))
1157    SET_EXPR_LOCATION (call, input_location);
1158  call_stack.safe_push (call);
1159  if (call_stack.length () > (unsigned) max_constexpr_depth)
1160    return false;
1161  return true;
1162}
1163
1164static void
1165pop_cx_call_context (void)
1166{
1167  ++call_stack_tick;
1168  call_stack.pop ();
1169}
1170
1171vec<tree>
1172cx_error_context (void)
1173{
1174  vec<tree> r = vNULL;
1175  if (call_stack_tick != last_cx_error_tick
1176      && !call_stack.is_empty ())
1177    r = call_stack;
1178  last_cx_error_tick = call_stack_tick;
1179  return r;
1180}
1181
1182/* Subroutine of cxx_eval_constant_expression.
1183   Evaluate the call expression tree T in the context of OLD_CALL expression
1184   evaluation.  */
1185
1186static tree
1187cxx_eval_call_expression (const constexpr_ctx *ctx, tree t,
1188			  bool lval,
1189			  bool *non_constant_p, bool *overflow_p)
1190{
1191  location_t loc = EXPR_LOC_OR_LOC (t, input_location);
1192  tree fun = get_function_named_in_call (t);
1193  constexpr_call new_call = { NULL, NULL, NULL, 0 };
1194  bool depth_ok;
1195
1196  if (fun == NULL_TREE)
1197    switch (CALL_EXPR_IFN (t))
1198      {
1199      case IFN_UBSAN_NULL:
1200      case IFN_UBSAN_BOUNDS:
1201      case IFN_UBSAN_VPTR:
1202	return void_node;
1203      default:
1204	if (!ctx->quiet)
1205	  error_at (loc, "call to internal function");
1206	*non_constant_p = true;
1207	return t;
1208      }
1209
1210  if (TREE_CODE (fun) != FUNCTION_DECL)
1211    {
1212      /* Might be a constexpr function pointer.  */
1213      fun = cxx_eval_constant_expression (ctx, fun,
1214					  /*lval*/false, non_constant_p,
1215					  overflow_p);
1216      STRIP_NOPS (fun);
1217      if (TREE_CODE (fun) == ADDR_EXPR)
1218	fun = TREE_OPERAND (fun, 0);
1219    }
1220  if (TREE_CODE (fun) != FUNCTION_DECL)
1221    {
1222      if (!ctx->quiet && !*non_constant_p)
1223	error_at (loc, "expression %qE does not designate a constexpr "
1224		  "function", fun);
1225      *non_constant_p = true;
1226      return t;
1227    }
1228  if (DECL_CLONED_FUNCTION_P (fun))
1229    fun = DECL_CLONED_FUNCTION (fun);
1230
1231  if (is_ubsan_builtin_p (fun))
1232    return void_node;
1233
1234  if (is_builtin_fn (fun))
1235    return cxx_eval_builtin_function_call (ctx, t,
1236					   lval, non_constant_p, overflow_p);
1237  if (!DECL_DECLARED_CONSTEXPR_P (fun))
1238    {
1239      if (!ctx->quiet)
1240	{
1241	  error_at (loc, "call to non-constexpr function %qD", fun);
1242	  explain_invalid_constexpr_fn (fun);
1243	}
1244      *non_constant_p = true;
1245      return t;
1246    }
1247
1248  /* We can't defer instantiating the function any longer.  */
1249  if (!DECL_INITIAL (fun)
1250      && DECL_TEMPLOID_INSTANTIATION (fun))
1251    {
1252      ++function_depth;
1253      instantiate_decl (fun, /*defer_ok*/false, /*expl_inst*/false);
1254      --function_depth;
1255    }
1256
1257  /* If in direct recursive call, optimize definition search.  */
1258  if (ctx && ctx->call && ctx->call->fundef->decl == fun)
1259    new_call.fundef = ctx->call->fundef;
1260  else
1261    {
1262      new_call.fundef = retrieve_constexpr_fundef (fun);
1263      if (new_call.fundef == NULL || new_call.fundef->body == NULL)
1264        {
1265	  if (!ctx->quiet)
1266	    {
1267	      if (DECL_INITIAL (fun))
1268		{
1269		  /* The definition of fun was somehow unsuitable.  */
1270		  error_at (loc, "%qD called in a constant expression", fun);
1271		  explain_invalid_constexpr_fn (fun);
1272		}
1273	      else
1274		error_at (loc, "%qD used before its definition", fun);
1275	    }
1276	  *non_constant_p = true;
1277          return t;
1278        }
1279    }
1280
1281  constexpr_ctx new_ctx = *ctx;
1282  if (DECL_CONSTRUCTOR_P (fun) && !ctx->object
1283      && TREE_CODE (t) == AGGR_INIT_EXPR)
1284    {
1285      /* We want to have an initialization target for an AGGR_INIT_EXPR.
1286	 If we don't already have one in CTX, use the AGGR_INIT_EXPR_SLOT.  */
1287      new_ctx.object = AGGR_INIT_EXPR_SLOT (t);
1288      tree ctor = new_ctx.ctor = build_constructor (DECL_CONTEXT (fun), NULL);
1289      CONSTRUCTOR_NO_IMPLICIT_ZERO (ctor) = true;
1290      ctx->values->put (new_ctx.object, ctor);
1291      ctx = &new_ctx;
1292    }
1293
1294  bool non_constant_args = false;
1295  cxx_bind_parameters_in_call (ctx, t, &new_call,
1296			       non_constant_p, overflow_p, &non_constant_args);
1297  if (*non_constant_p)
1298    return t;
1299
1300  depth_ok = push_cx_call_context (t);
1301
1302  tree result = NULL_TREE;
1303
1304  constexpr_call *entry = NULL;
1305  if (!non_constant_args)
1306    {
1307      new_call.hash = iterative_hash_template_arg
1308	(new_call.bindings, constexpr_fundef_hasher::hash (new_call.fundef));
1309
1310      /* If we have seen this call before, we are done.  */
1311      maybe_initialize_constexpr_call_table ();
1312      constexpr_call **slot
1313	= constexpr_call_table->find_slot (&new_call, INSERT);
1314      entry = *slot;
1315      if (entry == NULL)
1316	{
1317	  /* We need to keep a pointer to the entry, not just the slot, as the
1318	     slot can move in the call to cxx_eval_builtin_function_call.  */
1319	  *slot = entry = ggc_alloc<constexpr_call> ();
1320	  *entry = new_call;
1321	}
1322      /* Calls which are in progress have their result set to NULL
1323	 so that we can detect circular dependencies.  */
1324      else if (entry->result == NULL)
1325	{
1326	  if (!ctx->quiet)
1327	    error ("call has circular dependency");
1328	  *non_constant_p = true;
1329	  entry->result = result = error_mark_node;
1330	}
1331      else
1332	result = entry->result;
1333    }
1334
1335  if (!depth_ok)
1336    {
1337      if (!ctx->quiet)
1338	error ("constexpr evaluation depth exceeds maximum of %d (use "
1339	       "-fconstexpr-depth= to increase the maximum)",
1340	       max_constexpr_depth);
1341      *non_constant_p = true;
1342      result = error_mark_node;
1343    }
1344  else
1345    {
1346      if (!result || result == error_mark_node)
1347	{
1348	  if (!use_new_call)
1349	    {
1350	      new_ctx.call = &new_call;
1351	      result = (cxx_eval_constant_expression
1352			(&new_ctx, new_call.fundef->body,
1353			 lval,
1354			 non_constant_p, overflow_p));
1355	    }
1356	  else
1357	    {
1358	      if (DECL_SAVED_TREE (fun) == NULL_TREE
1359		  && (DECL_CONSTRUCTOR_P (fun) || DECL_DESTRUCTOR_P (fun)))
1360		/* The maybe-in-charge 'tor had its DECL_SAVED_TREE
1361		   cleared, try a clone.  */
1362		for (fun = DECL_CHAIN (fun);
1363		     fun && DECL_CLONED_FUNCTION_P (fun);
1364		     fun = DECL_CHAIN (fun))
1365		  if (DECL_SAVED_TREE (fun))
1366		    break;
1367	      if (!DECL_SAVED_TREE (fun))
1368		{
1369		  /* cgraph/gimplification have released the DECL_SAVED_TREE
1370		     for this function.  Fail gracefully.  */
1371		  gcc_assert (ctx->quiet);
1372		  *non_constant_p = true;
1373		  return t;
1374		}
1375	      tree parms, res;
1376
1377	      /* Unshare the whole function body.  */
1378	      tree body = copy_fn (fun, parms, res);
1379
1380	      /* Associate the bindings with the remapped parms.  */
1381	      tree bound = new_call.bindings;
1382	      tree remapped = parms;
1383	      while (bound)
1384		{
1385		  tree oparm = TREE_PURPOSE (bound);
1386		  tree arg = TREE_VALUE (bound);
1387		  gcc_assert (DECL_NAME (remapped) == DECL_NAME (oparm));
1388		  /* Don't share a CONSTRUCTOR that might be changed.  */
1389		  arg = unshare_expr (arg);
1390		  ctx->values->put (remapped, arg);
1391		  bound = TREE_CHAIN (bound);
1392		  remapped = DECL_CHAIN (remapped);
1393		}
1394	      /* Add the RESULT_DECL to the values map, too.  */
1395	      tree slot = NULL_TREE;
1396	      if (DECL_BY_REFERENCE (res))
1397		{
1398		  slot = AGGR_INIT_EXPR_SLOT (t);
1399		  tree addr = build_address (slot);
1400		  addr = build_nop (TREE_TYPE (res), addr);
1401		  ctx->values->put (res, addr);
1402		  ctx->values->put (slot, NULL_TREE);
1403		}
1404	      else
1405		ctx->values->put (res, NULL_TREE);
1406
1407	      tree jump_target = NULL_TREE;
1408	      cxx_eval_constant_expression (ctx, body,
1409					    lval, non_constant_p, overflow_p,
1410					    &jump_target);
1411
1412	      if (DECL_CONSTRUCTOR_P (fun))
1413		/* This can be null for a subobject constructor call, in
1414		   which case what we care about is the initialization
1415		   side-effects rather than the value.  We could get at the
1416		   value by evaluating *this, but we don't bother; there's
1417		   no need to put such a call in the hash table.  */
1418		result = lval ? ctx->object : ctx->ctor;
1419	      else if (VOID_TYPE_P (TREE_TYPE (res)))
1420		result = void_node;
1421	      else
1422		{
1423		  result = *ctx->values->get (slot ? slot : res);
1424		  if (result == NULL_TREE && !*non_constant_p)
1425		    {
1426		      if (!ctx->quiet)
1427			error ("constexpr call flows off the end "
1428			       "of the function");
1429		      *non_constant_p = true;
1430		    }
1431		}
1432
1433	      /* Remove the parms/result from the values map.  Is it worth
1434		 bothering to do this when the map itself is only live for
1435		 one constexpr evaluation?  If so, maybe also clear out
1436		 other vars from call, maybe in BIND_EXPR handling?  */
1437	      ctx->values->remove (res);
1438	      if (slot)
1439		ctx->values->remove (slot);
1440	      for (tree parm = parms; parm; parm = TREE_CHAIN (parm))
1441		ctx->values->remove (parm);
1442	    }
1443	}
1444
1445      if (result == error_mark_node)
1446	*non_constant_p = true;
1447      if (*non_constant_p)
1448	result = error_mark_node;
1449      else if (result)
1450	{
1451	  /* If this was a call to initialize an object, set the type of
1452	     the CONSTRUCTOR to the type of that object.  */
1453	  if (DECL_CONSTRUCTOR_P (fun) && !use_new_call)
1454	    {
1455	      tree ob_arg = get_nth_callarg (t, 0);
1456	      STRIP_NOPS (ob_arg);
1457	      gcc_assert (TYPE_PTR_P (TREE_TYPE (ob_arg))
1458			  && CLASS_TYPE_P (TREE_TYPE (TREE_TYPE (ob_arg))));
1459	      result = adjust_temp_type (TREE_TYPE (TREE_TYPE (ob_arg)),
1460					 result);
1461	    }
1462	}
1463      else
1464	result = void_node;
1465      if (entry)
1466	entry->result = result;
1467    }
1468
1469  pop_cx_call_context ();
1470  return unshare_expr (result);
1471}
1472
1473/* FIXME speed this up, it's taking 16% of compile time on sieve testcase.  */
1474
1475bool
1476reduced_constant_expression_p (tree t)
1477{
1478  switch (TREE_CODE (t))
1479    {
1480    case PTRMEM_CST:
1481      /* Even if we can't lower this yet, it's constant.  */
1482      return true;
1483
1484    case CONSTRUCTOR:
1485      /* And we need to handle PTRMEM_CST wrapped in a CONSTRUCTOR.  */
1486      tree elt; unsigned HOST_WIDE_INT idx;
1487      FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (t), idx, elt)
1488	if (!reduced_constant_expression_p (elt))
1489	  return false;
1490      return true;
1491
1492    default:
1493      /* FIXME are we calling this too much?  */
1494      return initializer_constant_valid_p (t, TREE_TYPE (t)) != NULL_TREE;
1495    }
1496}
1497
1498/* Some expressions may have constant operands but are not constant
1499   themselves, such as 1/0.  Call this function (or rather, the macro
1500   following it) to check for that condition.
1501
1502   We only call this in places that require an arithmetic constant, not in
1503   places where we might have a non-constant expression that can be a
1504   component of a constant expression, such as the address of a constexpr
1505   variable that might be dereferenced later.  */
1506
1507static bool
1508verify_constant (tree t, bool allow_non_constant, bool *non_constant_p,
1509		 bool *overflow_p)
1510{
1511  if (!*non_constant_p && !reduced_constant_expression_p (t))
1512    {
1513      if (!allow_non_constant)
1514	error ("%q+E is not a constant expression", t);
1515      *non_constant_p = true;
1516    }
1517  if (TREE_OVERFLOW_P (t))
1518    {
1519      if (!allow_non_constant)
1520	{
1521	  permerror (input_location, "overflow in constant expression");
1522	  /* If we're being permissive (and are in an enforcing
1523	     context), ignore the overflow.  */
1524	  if (flag_permissive)
1525	    return *non_constant_p;
1526	}
1527      *overflow_p = true;
1528    }
1529  return *non_constant_p;
1530}
1531
1532/* Check whether the shift operation with code CODE and type TYPE on LHS
1533   and RHS is undefined.  If it is, give an error with an explanation,
1534   and return true; return false otherwise.  */
1535
1536static bool
1537cxx_eval_check_shift_p (location_t loc, const constexpr_ctx *ctx,
1538			enum tree_code code, tree type, tree lhs, tree rhs)
1539{
1540  if ((code != LSHIFT_EXPR && code != RSHIFT_EXPR)
1541      || TREE_CODE (lhs) != INTEGER_CST
1542      || TREE_CODE (rhs) != INTEGER_CST)
1543    return false;
1544
1545  tree lhstype = TREE_TYPE (lhs);
1546  unsigned HOST_WIDE_INT uprec = TYPE_PRECISION (TREE_TYPE (lhs));
1547
1548  /* [expr.shift] The behavior is undefined if the right operand
1549     is negative, or greater than or equal to the length in bits
1550     of the promoted left operand.  */
1551  if (tree_int_cst_sgn (rhs) == -1)
1552    {
1553      if (!ctx->quiet)
1554	error_at (loc, "right operand of shift expression %q+E is negative",
1555		  build2_loc (loc, code, type, lhs, rhs));
1556      return true;
1557    }
1558  if (compare_tree_int (rhs, uprec) >= 0)
1559    {
1560      if (!ctx->quiet)
1561	error_at (loc, "right operand of shift expression %q+E is >= than "
1562		  "the precision of the left operand",
1563		  build2_loc (loc, code, type, lhs, rhs));
1564      return true;
1565    }
1566
1567  /* The value of E1 << E2 is E1 left-shifted E2 bit positions; [...]
1568     if E1 has a signed type and non-negative value, and E1x2^E2 is
1569     representable in the corresponding unsigned type of the result type,
1570     then that value, converted to the result type, is the resulting value;
1571     otherwise, the behavior is undefined.  */
1572  if (code == LSHIFT_EXPR && !TYPE_UNSIGNED (lhstype)
1573      && (cxx_dialect >= cxx11))
1574    {
1575      if (tree_int_cst_sgn (lhs) == -1)
1576	{
1577	  if (!ctx->quiet)
1578	    error_at (loc, "left operand of shift expression %q+E is negative",
1579		      build2_loc (loc, code, type, lhs, rhs));
1580	  return true;
1581	}
1582      /* For signed x << y the following:
1583	 (unsigned) x >> ((prec (lhs) - 1) - y)
1584	 if > 1, is undefined.  The right-hand side of this formula
1585	 is the highest bit of the LHS that can be set (starting from 0),
1586	 so that the shift doesn't overflow.  We then right-shift the LHS
1587	 to see whether any other bit is set making the original shift
1588	 undefined -- the result is not representable in the corresponding
1589	 unsigned type.  */
1590      tree t = build_int_cst (unsigned_type_node, uprec - 1);
1591      t = fold_build2 (MINUS_EXPR, unsigned_type_node, t, rhs);
1592      tree ulhs = fold_convert (unsigned_type_for (lhstype), lhs);
1593      t = fold_build2 (RSHIFT_EXPR, TREE_TYPE (ulhs), ulhs, t);
1594      if (tree_int_cst_lt (integer_one_node, t))
1595	{
1596	  if (!ctx->quiet)
1597	    error_at (loc, "shift expression %q+E overflows",
1598		      build2_loc (loc, code, type, lhs, rhs));
1599	  return true;
1600	}
1601    }
1602  return false;
1603}
1604
1605/* Subroutine of cxx_eval_constant_expression.
1606   Attempt to reduce the unary expression tree T to a compile time value.
1607   If successful, return the value.  Otherwise issue a diagnostic
1608   and return error_mark_node.  */
1609
1610static tree
1611cxx_eval_unary_expression (const constexpr_ctx *ctx, tree t,
1612			   bool /*lval*/,
1613			   bool *non_constant_p, bool *overflow_p)
1614{
1615  tree r;
1616  tree orig_arg = TREE_OPERAND (t, 0);
1617  tree arg = cxx_eval_constant_expression (ctx, orig_arg, /*lval*/false,
1618					   non_constant_p, overflow_p);
1619  VERIFY_CONSTANT (arg);
1620  location_t loc = EXPR_LOCATION (t);
1621  enum tree_code code = TREE_CODE (t);
1622  tree type = TREE_TYPE (t);
1623  r = fold_unary_loc (loc, code, type, arg);
1624  if (r == NULL_TREE)
1625    {
1626      if (arg == orig_arg)
1627	r = t;
1628      else
1629	r = build1_loc (loc, code, type, arg);
1630    }
1631  VERIFY_CONSTANT (r);
1632  return r;
1633}
1634
1635/* Subroutine of cxx_eval_constant_expression.
1636   Like cxx_eval_unary_expression, except for binary expressions.  */
1637
1638static tree
1639cxx_eval_binary_expression (const constexpr_ctx *ctx, tree t,
1640			    bool /*lval*/,
1641			    bool *non_constant_p, bool *overflow_p)
1642{
1643  tree r;
1644  tree orig_lhs = TREE_OPERAND (t, 0);
1645  tree orig_rhs = TREE_OPERAND (t, 1);
1646  tree lhs, rhs;
1647  lhs = cxx_eval_constant_expression (ctx, orig_lhs, /*lval*/false,
1648				      non_constant_p, overflow_p);
1649  /* Don't VERIFY_CONSTANT here, it's unnecessary and will break pointer
1650     subtraction.  */
1651  if (*non_constant_p)
1652    return t;
1653  rhs = cxx_eval_constant_expression (ctx, orig_rhs, /*lval*/false,
1654				      non_constant_p, overflow_p);
1655  if (*non_constant_p)
1656    return t;
1657
1658  location_t loc = EXPR_LOCATION (t);
1659  enum tree_code code = TREE_CODE (t);
1660  tree type = TREE_TYPE (t);
1661  r = fold_binary_loc (loc, code, type, lhs, rhs);
1662  if (r == NULL_TREE)
1663    {
1664      if (lhs == orig_lhs && rhs == orig_rhs)
1665	r = t;
1666      else
1667	r = build2_loc (loc, code, type, lhs, rhs);
1668    }
1669  else if (cxx_eval_check_shift_p (loc, ctx, code, type, lhs, rhs))
1670    *non_constant_p = true;
1671  /* Don't VERIFY_CONSTANT if this might be dealing with a pointer to
1672     a local array in a constexpr function.  */
1673  bool ptr = POINTER_TYPE_P (TREE_TYPE (lhs));
1674  if (!ptr)
1675    VERIFY_CONSTANT (r);
1676  return r;
1677}
1678
1679/* Subroutine of cxx_eval_constant_expression.
1680   Attempt to evaluate condition expressions.  Dead branches are not
1681   looked into.  */
1682
1683static tree
1684cxx_eval_conditional_expression (const constexpr_ctx *ctx, tree t,
1685				 bool lval,
1686				 bool *non_constant_p, bool *overflow_p,
1687				 tree *jump_target)
1688{
1689  tree val = cxx_eval_constant_expression (ctx, TREE_OPERAND (t, 0),
1690					   /*lval*/false,
1691					   non_constant_p, overflow_p);
1692  VERIFY_CONSTANT (val);
1693  /* Don't VERIFY_CONSTANT the other operands.  */
1694  if (integer_zerop (val))
1695    return cxx_eval_constant_expression (ctx, TREE_OPERAND (t, 2),
1696					 lval,
1697					 non_constant_p, overflow_p,
1698					 jump_target);
1699  return cxx_eval_constant_expression (ctx, TREE_OPERAND (t, 1),
1700				       lval,
1701				       non_constant_p, overflow_p,
1702				       jump_target);
1703}
1704
1705/* Returns less than, equal to, or greater than zero if KEY is found to be
1706   less than, to match, or to be greater than the constructor_elt's INDEX.  */
1707
1708static int
1709array_index_cmp (tree key, tree index)
1710{
1711  gcc_assert (TREE_CODE (key) == INTEGER_CST);
1712
1713  switch (TREE_CODE (index))
1714    {
1715    case INTEGER_CST:
1716      return tree_int_cst_compare (key, index);
1717    case RANGE_EXPR:
1718      {
1719	tree lo = TREE_OPERAND (index, 0);
1720	tree hi = TREE_OPERAND (index, 1);
1721	if (tree_int_cst_lt (key, lo))
1722	  return -1;
1723	else if (tree_int_cst_lt (hi, key))
1724	  return 1;
1725	else
1726	  return 0;
1727      }
1728    default:
1729      gcc_unreachable ();
1730    }
1731}
1732
1733/* Returns the index of the constructor_elt of ARY which matches DINDEX, or -1
1734   if none.  If INSERT is true, insert a matching element rather than fail.  */
1735
1736static HOST_WIDE_INT
1737find_array_ctor_elt (tree ary, tree dindex, bool insert = false)
1738{
1739  if (tree_int_cst_sgn (dindex) < 0)
1740    return -1;
1741
1742  unsigned HOST_WIDE_INT i = tree_to_uhwi (dindex);
1743  vec<constructor_elt, va_gc> *elts = CONSTRUCTOR_ELTS (ary);
1744  unsigned HOST_WIDE_INT len = vec_safe_length (elts);
1745
1746  unsigned HOST_WIDE_INT end = len;
1747  unsigned HOST_WIDE_INT begin = 0;
1748
1749  /* If the last element of the CONSTRUCTOR has its own index, we can assume
1750     that the same is true of the other elements and index directly.  */
1751  if (end > 0)
1752    {
1753      tree cindex = (*elts)[end-1].index;
1754      if (TREE_CODE (cindex) == INTEGER_CST
1755	  && compare_tree_int (cindex, end-1) == 0)
1756	{
1757	  if (i < end)
1758	    return i;
1759	  else
1760	    begin = end;
1761	}
1762    }
1763
1764  /* Otherwise, find a matching index by means of a binary search.  */
1765  while (begin != end)
1766    {
1767      unsigned HOST_WIDE_INT middle = (begin + end) / 2;
1768      constructor_elt &elt = (*elts)[middle];
1769      tree idx = elt.index;
1770
1771      int cmp = array_index_cmp (dindex, idx);
1772      if (cmp < 0)
1773	end = middle;
1774      else if (cmp > 0)
1775	begin = middle + 1;
1776      else
1777	{
1778	  if (insert && TREE_CODE (idx) == RANGE_EXPR)
1779	    {
1780	      /* We need to split the range.  */
1781	      constructor_elt e;
1782	      tree lo = TREE_OPERAND (idx, 0);
1783	      tree hi = TREE_OPERAND (idx, 1);
1784	      if (tree_int_cst_lt (lo, dindex))
1785		{
1786		  /* There are still some lower elts; shorten the range.  */
1787		  tree new_hi = int_const_binop (MINUS_EXPR, dindex,
1788						 size_one_node);
1789		  if (tree_int_cst_equal (lo, new_hi))
1790		    /* Only one element left, no longer a range.  */
1791		    elt.index = lo;
1792		  else
1793		    TREE_OPERAND (idx, 1) = new_hi;
1794		  /* Append the element we want to insert.  */
1795		  ++middle;
1796		  e.index = dindex;
1797		  e.value = unshare_expr (elt.value);
1798		  vec_safe_insert (CONSTRUCTOR_ELTS (ary), middle, e);
1799		}
1800	      else
1801		/* No lower elts, the range elt is now ours.  */
1802		elt.index = dindex;
1803
1804	      if (tree_int_cst_lt (dindex, hi))
1805		{
1806		  /* There are still some higher elts; append a range.  */
1807		  tree new_lo = int_const_binop (PLUS_EXPR, dindex,
1808						 size_one_node);
1809		  if (tree_int_cst_equal (new_lo, hi))
1810		    e.index = hi;
1811		  else
1812		    e.index = build2 (RANGE_EXPR, sizetype, new_lo, hi);
1813		  e.value = unshare_expr (elt.value);
1814		  vec_safe_insert (CONSTRUCTOR_ELTS (ary), middle+1, e);
1815		}
1816	    }
1817	  return middle;
1818	}
1819    }
1820
1821  if (insert)
1822    {
1823      constructor_elt e = { dindex, NULL_TREE };
1824      vec_safe_insert (CONSTRUCTOR_ELTS (ary), end, e);
1825      return end;
1826    }
1827
1828  return -1;
1829}
1830
1831
1832/* Subroutine of cxx_eval_constant_expression.
1833   Attempt to reduce a reference to an array slot.  */
1834
1835static tree
1836cxx_eval_array_reference (const constexpr_ctx *ctx, tree t,
1837			  bool lval,
1838			  bool *non_constant_p, bool *overflow_p)
1839{
1840  tree oldary = TREE_OPERAND (t, 0);
1841  tree ary = cxx_eval_constant_expression (ctx, oldary,
1842					   lval,
1843					   non_constant_p, overflow_p);
1844  tree index, oldidx;
1845  HOST_WIDE_INT i;
1846  tree elem_type;
1847  unsigned len, elem_nchars = 1;
1848  if (*non_constant_p)
1849    return t;
1850  oldidx = TREE_OPERAND (t, 1);
1851  index = cxx_eval_constant_expression (ctx, oldidx,
1852					false,
1853					non_constant_p, overflow_p);
1854  VERIFY_CONSTANT (index);
1855  if (lval && ary == oldary && index == oldidx)
1856    return t;
1857  else if (lval)
1858    return build4 (ARRAY_REF, TREE_TYPE (t), ary, index, NULL, NULL);
1859  elem_type = TREE_TYPE (TREE_TYPE (ary));
1860  if (TREE_CODE (ary) == CONSTRUCTOR)
1861    len = CONSTRUCTOR_NELTS (ary);
1862  else if (TREE_CODE (ary) == STRING_CST)
1863    {
1864      elem_nchars = (TYPE_PRECISION (elem_type)
1865		     / TYPE_PRECISION (char_type_node));
1866      len = (unsigned) TREE_STRING_LENGTH (ary) / elem_nchars;
1867    }
1868  else
1869    {
1870      /* We can't do anything with other tree codes, so use
1871	 VERIFY_CONSTANT to complain and fail.  */
1872      VERIFY_CONSTANT (ary);
1873      gcc_unreachable ();
1874    }
1875
1876  if (!tree_fits_shwi_p (index)
1877      || (i = tree_to_shwi (index)) < 0)
1878    {
1879      if (!ctx->quiet)
1880	error ("negative array subscript");
1881      *non_constant_p = true;
1882      return t;
1883    }
1884
1885  bool found;
1886  if (TREE_CODE (ary) == CONSTRUCTOR)
1887    {
1888      HOST_WIDE_INT ix = find_array_ctor_elt (ary, index);
1889      found = (ix >= 0);
1890      if (found)
1891	i = ix;
1892    }
1893  else
1894    found = (i < len);
1895
1896  if (!found)
1897    {
1898      if (tree_int_cst_lt (index, array_type_nelts_top (TREE_TYPE (ary))))
1899	{
1900	  /* If it's within the array bounds but doesn't have an explicit
1901	     initializer, it's value-initialized.  */
1902	  tree val = build_value_init (elem_type, tf_warning_or_error);
1903	  return cxx_eval_constant_expression (ctx, val,
1904					       lval,
1905					       non_constant_p, overflow_p);
1906	}
1907
1908      if (!ctx->quiet)
1909	error ("array subscript out of bound");
1910      *non_constant_p = true;
1911      return t;
1912    }
1913
1914  if (TREE_CODE (ary) == CONSTRUCTOR)
1915    return (*CONSTRUCTOR_ELTS (ary))[i].value;
1916  else if (elem_nchars == 1)
1917    return build_int_cst (cv_unqualified (TREE_TYPE (TREE_TYPE (ary))),
1918			  TREE_STRING_POINTER (ary)[i]);
1919  else
1920    {
1921      tree type = cv_unqualified (TREE_TYPE (TREE_TYPE (ary)));
1922      return native_interpret_expr (type, (const unsigned char *)
1923					  TREE_STRING_POINTER (ary)
1924					  + i * elem_nchars, elem_nchars);
1925    }
1926  /* Don't VERIFY_CONSTANT here.  */
1927}
1928
1929/* Subroutine of cxx_eval_constant_expression.
1930   Attempt to reduce a field access of a value of class type.  */
1931
1932static tree
1933cxx_eval_component_reference (const constexpr_ctx *ctx, tree t,
1934			      bool lval,
1935			      bool *non_constant_p, bool *overflow_p)
1936{
1937  unsigned HOST_WIDE_INT i;
1938  tree field;
1939  tree value;
1940  tree part = TREE_OPERAND (t, 1);
1941  tree orig_whole = TREE_OPERAND (t, 0);
1942  tree whole = cxx_eval_constant_expression (ctx, orig_whole,
1943					     lval,
1944					     non_constant_p, overflow_p);
1945  if (whole == orig_whole)
1946    return t;
1947  if (lval)
1948    return fold_build3 (COMPONENT_REF, TREE_TYPE (t),
1949			whole, part, NULL_TREE);
1950  /* Don't VERIFY_CONSTANT here; we only want to check that we got a
1951     CONSTRUCTOR.  */
1952  if (!*non_constant_p && TREE_CODE (whole) != CONSTRUCTOR)
1953    {
1954      if (!ctx->quiet)
1955	error ("%qE is not a constant expression", orig_whole);
1956      *non_constant_p = true;
1957    }
1958  if (DECL_MUTABLE_P (part))
1959    {
1960      if (!ctx->quiet)
1961	error ("mutable %qD is not usable in a constant expression", part);
1962      *non_constant_p = true;
1963    }
1964  if (*non_constant_p)
1965    return t;
1966  FOR_EACH_CONSTRUCTOR_ELT (CONSTRUCTOR_ELTS (whole), i, field, value)
1967    {
1968      if (field == part)
1969	{
1970	  if (value)
1971	    return value;
1972	  else
1973	    /* We're in the middle of initializing it.  */
1974	    break;
1975	}
1976    }
1977  if (TREE_CODE (TREE_TYPE (whole)) == UNION_TYPE
1978      && CONSTRUCTOR_NELTS (whole) > 0)
1979    {
1980      /* DR 1188 says we don't have to deal with this.  */
1981      if (!ctx->quiet)
1982	error ("accessing %qD member instead of initialized %qD member in "
1983	       "constant expression", part, CONSTRUCTOR_ELT (whole, 0)->index);
1984      *non_constant_p = true;
1985      return t;
1986    }
1987
1988  /* We only create a CONSTRUCTOR for a subobject when we modify it, so empty
1989     classes never get represented; throw together a value now.  */
1990  if (is_really_empty_class (TREE_TYPE (t)))
1991    return build_constructor (TREE_TYPE (t), NULL);
1992
1993  if (CONSTRUCTOR_NO_IMPLICIT_ZERO (whole))
1994    {
1995      /* 'whole' is part of the aggregate initializer we're currently
1996	 building; if there's no initializer for this member yet, that's an
1997	 error.  */
1998      if (!ctx->quiet)
1999	error ("accessing uninitialized member %qD", part);
2000      *non_constant_p = true;
2001      return t;
2002    }
2003
2004  /* If there's no explicit init for this field, it's value-initialized.  */
2005  value = build_value_init (TREE_TYPE (t), tf_warning_or_error);
2006  return cxx_eval_constant_expression (ctx, value,
2007				       lval,
2008				       non_constant_p, overflow_p);
2009}
2010
2011/* Subroutine of cxx_eval_constant_expression.
2012   Attempt to reduce a field access of a value of class type that is
2013   expressed as a BIT_FIELD_REF.  */
2014
2015static tree
2016cxx_eval_bit_field_ref (const constexpr_ctx *ctx, tree t,
2017			bool lval,
2018			bool *non_constant_p, bool *overflow_p)
2019{
2020  tree orig_whole = TREE_OPERAND (t, 0);
2021  tree retval, fldval, utype, mask;
2022  bool fld_seen = false;
2023  HOST_WIDE_INT istart, isize;
2024  tree whole = cxx_eval_constant_expression (ctx, orig_whole,
2025					     lval,
2026					     non_constant_p, overflow_p);
2027  tree start, field, value;
2028  unsigned HOST_WIDE_INT i;
2029
2030  if (whole == orig_whole)
2031    return t;
2032  /* Don't VERIFY_CONSTANT here; we only want to check that we got a
2033     CONSTRUCTOR.  */
2034  if (!*non_constant_p
2035      && TREE_CODE (whole) != VECTOR_CST
2036      && TREE_CODE (whole) != CONSTRUCTOR)
2037    {
2038      if (!ctx->quiet)
2039	error ("%qE is not a constant expression", orig_whole);
2040      *non_constant_p = true;
2041    }
2042  if (*non_constant_p)
2043    return t;
2044
2045  if (TREE_CODE (whole) == VECTOR_CST)
2046    return fold_ternary (BIT_FIELD_REF, TREE_TYPE (t), whole,
2047			 TREE_OPERAND (t, 1), TREE_OPERAND (t, 2));
2048
2049  start = TREE_OPERAND (t, 2);
2050  istart = tree_to_shwi (start);
2051  isize = tree_to_shwi (TREE_OPERAND (t, 1));
2052  utype = TREE_TYPE (t);
2053  if (!TYPE_UNSIGNED (utype))
2054    utype = build_nonstandard_integer_type (TYPE_PRECISION (utype), 1);
2055  retval = build_int_cst (utype, 0);
2056  FOR_EACH_CONSTRUCTOR_ELT (CONSTRUCTOR_ELTS (whole), i, field, value)
2057    {
2058      tree bitpos = bit_position (field);
2059      if (bitpos == start && DECL_SIZE (field) == TREE_OPERAND (t, 1))
2060	return value;
2061      if (TREE_CODE (TREE_TYPE (field)) == INTEGER_TYPE
2062	  && TREE_CODE (value) == INTEGER_CST
2063	  && tree_fits_shwi_p (bitpos)
2064	  && tree_fits_shwi_p (DECL_SIZE (field)))
2065	{
2066	  HOST_WIDE_INT bit = tree_to_shwi (bitpos);
2067	  HOST_WIDE_INT sz = tree_to_shwi (DECL_SIZE (field));
2068	  HOST_WIDE_INT shift;
2069	  if (bit >= istart && bit + sz <= istart + isize)
2070	    {
2071	      fldval = fold_convert (utype, value);
2072	      mask = build_int_cst_type (utype, -1);
2073	      mask = fold_build2 (LSHIFT_EXPR, utype, mask,
2074				  size_int (TYPE_PRECISION (utype) - sz));
2075	      mask = fold_build2 (RSHIFT_EXPR, utype, mask,
2076				  size_int (TYPE_PRECISION (utype) - sz));
2077	      fldval = fold_build2 (BIT_AND_EXPR, utype, fldval, mask);
2078	      shift = bit - istart;
2079	      if (BYTES_BIG_ENDIAN)
2080		shift = TYPE_PRECISION (utype) - shift - sz;
2081	      fldval = fold_build2 (LSHIFT_EXPR, utype, fldval,
2082				    size_int (shift));
2083	      retval = fold_build2 (BIT_IOR_EXPR, utype, retval, fldval);
2084	      fld_seen = true;
2085	    }
2086	}
2087    }
2088  if (fld_seen)
2089    return fold_convert (TREE_TYPE (t), retval);
2090  gcc_unreachable ();
2091  return error_mark_node;
2092}
2093
2094/* Subroutine of cxx_eval_constant_expression.
2095   Evaluate a short-circuited logical expression T in the context
2096   of a given constexpr CALL.  BAILOUT_VALUE is the value for
2097   early return.  CONTINUE_VALUE is used here purely for
2098   sanity check purposes.  */
2099
2100static tree
2101cxx_eval_logical_expression (const constexpr_ctx *ctx, tree t,
2102                             tree bailout_value, tree continue_value,
2103			     bool lval,
2104			     bool *non_constant_p, bool *overflow_p)
2105{
2106  tree r;
2107  tree lhs = cxx_eval_constant_expression (ctx, TREE_OPERAND (t, 0),
2108					   lval,
2109					   non_constant_p, overflow_p);
2110  VERIFY_CONSTANT (lhs);
2111  if (tree_int_cst_equal (lhs, bailout_value))
2112    return lhs;
2113  gcc_assert (tree_int_cst_equal (lhs, continue_value));
2114  r = cxx_eval_constant_expression (ctx, TREE_OPERAND (t, 1),
2115				    lval, non_constant_p,
2116				    overflow_p);
2117  VERIFY_CONSTANT (r);
2118  return r;
2119}
2120
2121/* REF is a COMPONENT_REF designating a particular field.  V is a vector of
2122   CONSTRUCTOR elements to initialize (part of) an object containing that
2123   field.  Return a pointer to the constructor_elt corresponding to the
2124   initialization of the field.  */
2125
2126static constructor_elt *
2127base_field_constructor_elt (vec<constructor_elt, va_gc> *v, tree ref)
2128{
2129  tree aggr = TREE_OPERAND (ref, 0);
2130  tree field = TREE_OPERAND (ref, 1);
2131  HOST_WIDE_INT i;
2132  constructor_elt *ce;
2133
2134  gcc_assert (TREE_CODE (ref) == COMPONENT_REF);
2135
2136  if (TREE_CODE (aggr) == COMPONENT_REF)
2137    {
2138      constructor_elt *base_ce
2139	= base_field_constructor_elt (v, aggr);
2140      v = CONSTRUCTOR_ELTS (base_ce->value);
2141    }
2142
2143  for (i = 0; vec_safe_iterate (v, i, &ce); ++i)
2144    if (ce->index == field)
2145      return ce;
2146
2147  gcc_unreachable ();
2148  return NULL;
2149}
2150
2151/* Some of the expressions fed to the constexpr mechanism are calls to
2152   constructors, which have type void.  In that case, return the type being
2153   initialized by the constructor.  */
2154
2155static tree
2156initialized_type (tree t)
2157{
2158  if (TYPE_P (t))
2159    return t;
2160  tree type = cv_unqualified (TREE_TYPE (t));
2161  if (TREE_CODE (t) == CALL_EXPR || TREE_CODE (t) == AGGR_INIT_EXPR)
2162    {
2163      /* A constructor call has void type, so we need to look deeper.  */
2164      tree fn = get_function_named_in_call (t);
2165      if (fn && TREE_CODE (fn) == FUNCTION_DECL
2166	  && DECL_CXX_CONSTRUCTOR_P (fn))
2167	type = DECL_CONTEXT (fn);
2168    }
2169  return type;
2170}
2171
2172/* We're about to initialize element INDEX of an array or class from VALUE.
2173   Set up NEW_CTX appropriately by adjusting .object to refer to the
2174   subobject and creating a new CONSTRUCTOR if the element is itself
2175   a class or array.  */
2176
2177static void
2178init_subob_ctx (const constexpr_ctx *ctx, constexpr_ctx &new_ctx,
2179	       tree index, tree &value)
2180{
2181  new_ctx = *ctx;
2182
2183  if (index && TREE_CODE (index) != INTEGER_CST
2184      && TREE_CODE (index) != FIELD_DECL)
2185    /* This won't have an element in the new CONSTRUCTOR.  */
2186    return;
2187
2188  tree type = initialized_type (value);
2189  if (!AGGREGATE_TYPE_P (type) && !VECTOR_TYPE_P (type))
2190    /* A non-aggregate member doesn't get its own CONSTRUCTOR.  */
2191    return;
2192
2193  /* The sub-aggregate initializer might contain a placeholder;
2194     update object to refer to the subobject and ctor to refer to
2195     the (newly created) sub-initializer.  */
2196  if (ctx->object)
2197    new_ctx.object = build_ctor_subob_ref (index, type, ctx->object);
2198  tree elt = build_constructor (type, NULL);
2199  CONSTRUCTOR_NO_IMPLICIT_ZERO (elt) = true;
2200  new_ctx.ctor = elt;
2201
2202  if (TREE_CODE (value) == TARGET_EXPR)
2203    /* Avoid creating another CONSTRUCTOR when we expand the TARGET_EXPR.  */
2204    value = TARGET_EXPR_INITIAL (value);
2205}
2206
2207/* We're about to process an initializer for a class or array TYPE.  Make
2208   sure that CTX is set up appropriately.  */
2209
2210static void
2211verify_ctor_sanity (const constexpr_ctx *ctx, tree type)
2212{
2213  /* We don't bother building a ctor for an empty base subobject.  */
2214  if (is_empty_class (type))
2215    return;
2216
2217  /* We're in the middle of an initializer that might involve placeholders;
2218     our caller should have created a CONSTRUCTOR for us to put the
2219     initializer into.  We will either return that constructor or T.  */
2220  gcc_assert (ctx->ctor);
2221  gcc_assert (same_type_ignoring_top_level_qualifiers_p
2222	      (type, TREE_TYPE (ctx->ctor)));
2223  /* We used to check that ctx->ctor was empty, but that isn't the case when
2224     the object is zero-initialized before calling the constructor.  */
2225  if (ctx->object)
2226    gcc_assert (same_type_ignoring_top_level_qualifiers_p
2227		(type, TREE_TYPE (ctx->object)));
2228  gcc_assert (!ctx->object || !DECL_P (ctx->object)
2229	      || *(ctx->values->get (ctx->object)) == ctx->ctor);
2230}
2231
2232/* Subroutine of cxx_eval_constant_expression.
2233   The expression tree T denotes a C-style array or a C-style
2234   aggregate.  Reduce it to a constant expression.  */
2235
2236static tree
2237cxx_eval_bare_aggregate (const constexpr_ctx *ctx, tree t,
2238			 bool lval,
2239			 bool *non_constant_p, bool *overflow_p)
2240{
2241  vec<constructor_elt, va_gc> *v = CONSTRUCTOR_ELTS (t);
2242  bool changed = false;
2243  gcc_assert (!BRACE_ENCLOSED_INITIALIZER_P (t));
2244
2245  verify_ctor_sanity (ctx, TREE_TYPE (t));
2246  vec<constructor_elt, va_gc> **p = &CONSTRUCTOR_ELTS (ctx->ctor);
2247  vec_alloc (*p, vec_safe_length (v));
2248
2249  unsigned i; tree index, value;
2250  FOR_EACH_CONSTRUCTOR_ELT (v, i, index, value)
2251    {
2252      tree orig_value = value;
2253      constexpr_ctx new_ctx;
2254      init_subob_ctx (ctx, new_ctx, index, value);
2255      if (new_ctx.ctor != ctx->ctor)
2256	/* If we built a new CONSTRUCTOR, attach it now so that other
2257	   initializers can refer to it.  */
2258	CONSTRUCTOR_APPEND_ELT (*p, index, new_ctx.ctor);
2259      tree elt = cxx_eval_constant_expression (&new_ctx, value,
2260					       lval,
2261					       non_constant_p, overflow_p);
2262      /* Don't VERIFY_CONSTANT here.  */
2263      if (ctx->quiet && *non_constant_p)
2264	break;
2265      if (elt != orig_value)
2266	changed = true;
2267      if (index && TREE_CODE (index) == COMPONENT_REF)
2268	{
2269	  /* This is an initialization of a vfield inside a base
2270	     subaggregate that we already initialized; push this
2271	     initialization into the previous initialization.  */
2272	  constructor_elt *inner = base_field_constructor_elt (*p, index);
2273	  inner->value = elt;
2274	  changed = true;
2275	}
2276      else if (index
2277	       && (TREE_CODE (index) == NOP_EXPR
2278		   || TREE_CODE (index) == POINTER_PLUS_EXPR))
2279	{
2280	  /* This is an initializer for an empty base; now that we've
2281	     checked that it's constant, we can ignore it.  */
2282	  gcc_assert (is_empty_class (TREE_TYPE (TREE_TYPE (index))));
2283	  changed = true;
2284	}
2285      else if (new_ctx.ctor != ctx->ctor)
2286	{
2287	  /* We appended this element above; update the value.  */
2288	  gcc_assert ((*p)->last().index == index);
2289	  (*p)->last().value = elt;
2290	}
2291      else
2292	CONSTRUCTOR_APPEND_ELT (*p, index, elt);
2293    }
2294  if (*non_constant_p || !changed)
2295    return t;
2296  t = ctx->ctor;
2297  /* We're done building this CONSTRUCTOR, so now we can interpret an
2298     element without an explicit initializer as value-initialized.  */
2299  CONSTRUCTOR_NO_IMPLICIT_ZERO (t) = false;
2300  if (TREE_CODE (TREE_TYPE (t)) == VECTOR_TYPE)
2301    t = fold (t);
2302  return t;
2303}
2304
2305/* Subroutine of cxx_eval_constant_expression.
2306   The expression tree T is a VEC_INIT_EXPR which denotes the desired
2307   initialization of a non-static data member of array type.  Reduce it to a
2308   CONSTRUCTOR.
2309
2310   Note that apart from value-initialization (when VALUE_INIT is true),
2311   this is only intended to support value-initialization and the
2312   initializations done by defaulted constructors for classes with
2313   non-static data members of array type.  In this case, VEC_INIT_EXPR_INIT
2314   will either be NULL_TREE for the default constructor, or a COMPONENT_REF
2315   for the copy/move constructor.  */
2316
2317static tree
2318cxx_eval_vec_init_1 (const constexpr_ctx *ctx, tree atype, tree init,
2319		     bool value_init, bool lval,
2320		     bool *non_constant_p, bool *overflow_p)
2321{
2322  tree elttype = TREE_TYPE (atype);
2323  unsigned HOST_WIDE_INT max = tree_to_uhwi (array_type_nelts_top (atype));
2324  verify_ctor_sanity (ctx, atype);
2325  vec<constructor_elt, va_gc> **p = &CONSTRUCTOR_ELTS (ctx->ctor);
2326  vec_alloc (*p, max + 1);
2327  bool pre_init = false;
2328  unsigned HOST_WIDE_INT i;
2329
2330  /* For the default constructor, build up a call to the default
2331     constructor of the element type.  We only need to handle class types
2332     here, as for a constructor to be constexpr, all members must be
2333     initialized, which for a defaulted default constructor means they must
2334     be of a class type with a constexpr default constructor.  */
2335  if (TREE_CODE (elttype) == ARRAY_TYPE)
2336    /* We only do this at the lowest level.  */;
2337  else if (value_init)
2338    {
2339      init = build_value_init (elttype, tf_warning_or_error);
2340      pre_init = true;
2341    }
2342  else if (!init)
2343    {
2344      vec<tree, va_gc> *argvec = make_tree_vector ();
2345      init = build_special_member_call (NULL_TREE, complete_ctor_identifier,
2346					&argvec, elttype, LOOKUP_NORMAL,
2347					tf_warning_or_error);
2348      release_tree_vector (argvec);
2349      init = build_aggr_init_expr (TREE_TYPE (init), init);
2350      pre_init = true;
2351    }
2352
2353  for (i = 0; i < max; ++i)
2354    {
2355      tree idx = build_int_cst (size_type_node, i);
2356      tree eltinit;
2357      constexpr_ctx new_ctx;
2358      init_subob_ctx (ctx, new_ctx, idx, pre_init ? init : elttype);
2359      if (new_ctx.ctor != ctx->ctor)
2360	CONSTRUCTOR_APPEND_ELT (*p, idx, new_ctx.ctor);
2361      if (TREE_CODE (elttype) == ARRAY_TYPE)
2362	{
2363	  /* A multidimensional array; recurse.  */
2364	  if (value_init || init == NULL_TREE)
2365	    eltinit = NULL_TREE;
2366	  else
2367	    eltinit = cp_build_array_ref (input_location, init, idx,
2368					  tf_warning_or_error);
2369	  eltinit = cxx_eval_vec_init_1 (&new_ctx, elttype, eltinit, value_init,
2370					 lval,
2371					 non_constant_p, overflow_p);
2372	}
2373      else if (pre_init)
2374	{
2375	  /* Initializing an element using value or default initialization
2376	     we just pre-built above.  */
2377	  eltinit = (cxx_eval_constant_expression
2378		     (&new_ctx, init,
2379		      lval, non_constant_p, overflow_p));
2380	}
2381      else
2382	{
2383	  /* Copying an element.  */
2384	  gcc_assert (same_type_ignoring_top_level_qualifiers_p
2385		      (atype, TREE_TYPE (init)));
2386	  eltinit = cp_build_array_ref (input_location, init, idx,
2387					tf_warning_or_error);
2388	  if (!real_lvalue_p (init))
2389	    eltinit = move (eltinit);
2390	  eltinit = force_rvalue (eltinit, tf_warning_or_error);
2391	  eltinit = (cxx_eval_constant_expression
2392		     (&new_ctx, eltinit, lval,
2393		      non_constant_p, overflow_p));
2394	}
2395      if (*non_constant_p && !ctx->quiet)
2396	break;
2397      if (new_ctx.ctor != ctx->ctor)
2398	{
2399	  /* We appended this element above; update the value.  */
2400	  gcc_assert ((*p)->last().index == idx);
2401	  (*p)->last().value = eltinit;
2402	}
2403      else
2404	CONSTRUCTOR_APPEND_ELT (*p, idx, eltinit);
2405    }
2406
2407  if (!*non_constant_p)
2408    {
2409      init = ctx->ctor;
2410      CONSTRUCTOR_NO_IMPLICIT_ZERO (init) = false;
2411    }
2412  return init;
2413}
2414
2415static tree
2416cxx_eval_vec_init (const constexpr_ctx *ctx, tree t,
2417		   bool lval,
2418		   bool *non_constant_p, bool *overflow_p)
2419{
2420  tree atype = TREE_TYPE (t);
2421  tree init = VEC_INIT_EXPR_INIT (t);
2422  tree r = cxx_eval_vec_init_1 (ctx, atype, init,
2423				VEC_INIT_EXPR_VALUE_INIT (t),
2424				lval, non_constant_p, overflow_p);
2425  if (*non_constant_p)
2426    return t;
2427  else
2428    return r;
2429}
2430
2431/* A less strict version of fold_indirect_ref_1, which requires cv-quals to
2432   match.  We want to be less strict for simple *& folding; if we have a
2433   non-const temporary that we access through a const pointer, that should
2434   work.  We handle this here rather than change fold_indirect_ref_1
2435   because we're dealing with things like ADDR_EXPR of INTEGER_CST which
2436   don't really make sense outside of constant expression evaluation.  Also
2437   we want to allow folding to COMPONENT_REF, which could cause trouble
2438   with TBAA in fold_indirect_ref_1.
2439
2440   Try to keep this function synced with fold_indirect_ref_1.  */
2441
2442static tree
2443cxx_fold_indirect_ref (location_t loc, tree type, tree op0, bool *empty_base)
2444{
2445  tree sub, subtype;
2446
2447  sub = op0;
2448  STRIP_NOPS (sub);
2449  subtype = TREE_TYPE (sub);
2450  if (!POINTER_TYPE_P (subtype))
2451    return NULL_TREE;
2452
2453  if (TREE_CODE (sub) == ADDR_EXPR)
2454    {
2455      tree op = TREE_OPERAND (sub, 0);
2456      tree optype = TREE_TYPE (op);
2457
2458      /* *&CONST_DECL -> to the value of the const decl.  */
2459      if (TREE_CODE (op) == CONST_DECL)
2460	return DECL_INITIAL (op);
2461      /* *&p => p;  make sure to handle *&"str"[cst] here.  */
2462      if (same_type_ignoring_top_level_qualifiers_p (optype, type))
2463	{
2464	  tree fop = fold_read_from_constant_string (op);
2465	  if (fop)
2466	    return fop;
2467	  else
2468	    return op;
2469	}
2470      /* *(foo *)&fooarray => fooarray[0] */
2471      else if (TREE_CODE (optype) == ARRAY_TYPE
2472	       && (same_type_ignoring_top_level_qualifiers_p
2473		   (type, TREE_TYPE (optype))))
2474	{
2475	  tree type_domain = TYPE_DOMAIN (optype);
2476	  tree min_val = size_zero_node;
2477	  if (type_domain && TYPE_MIN_VALUE (type_domain))
2478	    min_val = TYPE_MIN_VALUE (type_domain);
2479	  return build4_loc (loc, ARRAY_REF, type, op, min_val,
2480			     NULL_TREE, NULL_TREE);
2481	}
2482      /* *(foo *)&complexfoo => __real__ complexfoo */
2483      else if (TREE_CODE (optype) == COMPLEX_TYPE
2484	       && (same_type_ignoring_top_level_qualifiers_p
2485		   (type, TREE_TYPE (optype))))
2486	return fold_build1_loc (loc, REALPART_EXPR, type, op);
2487      /* *(foo *)&vectorfoo => BIT_FIELD_REF<vectorfoo,...> */
2488      else if (TREE_CODE (optype) == VECTOR_TYPE
2489	       && (same_type_ignoring_top_level_qualifiers_p
2490		   (type, TREE_TYPE (optype))))
2491	{
2492	  tree part_width = TYPE_SIZE (type);
2493	  tree index = bitsize_int (0);
2494	  return fold_build3_loc (loc, BIT_FIELD_REF, type, op, part_width, index);
2495	}
2496      /* Also handle conversion to an empty base class, which
2497	 is represented with a NOP_EXPR.  */
2498      else if (is_empty_class (type)
2499	       && CLASS_TYPE_P (optype)
2500	       && DERIVED_FROM_P (type, optype))
2501	{
2502	  *empty_base = true;
2503	  return op;
2504	}
2505      /* *(foo *)&struct_with_foo_field => COMPONENT_REF */
2506      else if (RECORD_OR_UNION_TYPE_P (optype))
2507	{
2508	  tree field = TYPE_FIELDS (optype);
2509	  for (; field; field = DECL_CHAIN (field))
2510	    if (TREE_CODE (field) == FIELD_DECL
2511		&& integer_zerop (byte_position (field))
2512		&& (same_type_ignoring_top_level_qualifiers_p
2513		    (TREE_TYPE (field), type)))
2514	      {
2515		return fold_build3 (COMPONENT_REF, type, op, field, NULL_TREE);
2516		break;
2517	      }
2518	}
2519    }
2520  else if (TREE_CODE (sub) == POINTER_PLUS_EXPR
2521	   && TREE_CODE (TREE_OPERAND (sub, 1)) == INTEGER_CST)
2522    {
2523      tree op00 = TREE_OPERAND (sub, 0);
2524      tree op01 = TREE_OPERAND (sub, 1);
2525
2526      STRIP_NOPS (op00);
2527      if (TREE_CODE (op00) == ADDR_EXPR)
2528	{
2529	  tree op00type;
2530	  op00 = TREE_OPERAND (op00, 0);
2531	  op00type = TREE_TYPE (op00);
2532
2533	  /* ((foo*)&vectorfoo)[1] => BIT_FIELD_REF<vectorfoo,...> */
2534	  if (TREE_CODE (op00type) == VECTOR_TYPE
2535	      && (same_type_ignoring_top_level_qualifiers_p
2536		  (type, TREE_TYPE (op00type))))
2537	    {
2538	      HOST_WIDE_INT offset = tree_to_shwi (op01);
2539	      tree part_width = TYPE_SIZE (type);
2540	      unsigned HOST_WIDE_INT part_widthi = tree_to_shwi (part_width)/BITS_PER_UNIT;
2541	      unsigned HOST_WIDE_INT indexi = offset * BITS_PER_UNIT;
2542	      tree index = bitsize_int (indexi);
2543
2544	      if (offset / part_widthi < TYPE_VECTOR_SUBPARTS (op00type))
2545		return fold_build3_loc (loc,
2546					BIT_FIELD_REF, type, op00,
2547					part_width, index);
2548
2549	    }
2550	  /* ((foo*)&complexfoo)[1] => __imag__ complexfoo */
2551	  else if (TREE_CODE (op00type) == COMPLEX_TYPE
2552		   && (same_type_ignoring_top_level_qualifiers_p
2553		       (type, TREE_TYPE (op00type))))
2554	    {
2555	      tree size = TYPE_SIZE_UNIT (type);
2556	      if (tree_int_cst_equal (size, op01))
2557		return fold_build1_loc (loc, IMAGPART_EXPR, type, op00);
2558	    }
2559	  /* ((foo *)&fooarray)[1] => fooarray[1] */
2560	  else if (TREE_CODE (op00type) == ARRAY_TYPE
2561		   && (same_type_ignoring_top_level_qualifiers_p
2562		       (type, TREE_TYPE (op00type))))
2563	    {
2564	      tree type_domain = TYPE_DOMAIN (op00type);
2565	      tree min_val = size_zero_node;
2566	      if (type_domain && TYPE_MIN_VALUE (type_domain))
2567		min_val = TYPE_MIN_VALUE (type_domain);
2568	      op01 = size_binop_loc (loc, EXACT_DIV_EXPR, op01,
2569				     TYPE_SIZE_UNIT (type));
2570	      op01 = size_binop_loc (loc, PLUS_EXPR, op01, min_val);
2571	      return build4_loc (loc, ARRAY_REF, type, op00, op01,
2572				 NULL_TREE, NULL_TREE);
2573	    }
2574	  /* Also handle conversion to an empty base class, which
2575	     is represented with a NOP_EXPR.  */
2576	  else if (is_empty_class (type)
2577		   && CLASS_TYPE_P (op00type)
2578		   && DERIVED_FROM_P (type, op00type))
2579	    {
2580	      *empty_base = true;
2581	      return op00;
2582	    }
2583	  /* ((foo *)&struct_with_foo_field)[1] => COMPONENT_REF */
2584	  else if (RECORD_OR_UNION_TYPE_P (op00type))
2585	    {
2586	      tree field = TYPE_FIELDS (op00type);
2587	      for (; field; field = DECL_CHAIN (field))
2588		if (TREE_CODE (field) == FIELD_DECL
2589		    && tree_int_cst_equal (byte_position (field), op01)
2590		    && (same_type_ignoring_top_level_qualifiers_p
2591			(TREE_TYPE (field), type)))
2592		  {
2593		    return fold_build3 (COMPONENT_REF, type, op00,
2594				     field, NULL_TREE);
2595		    break;
2596		  }
2597	    }
2598	}
2599    }
2600  /* *(foo *)fooarrptr => (*fooarrptr)[0] */
2601  else if (TREE_CODE (TREE_TYPE (subtype)) == ARRAY_TYPE
2602	   && (same_type_ignoring_top_level_qualifiers_p
2603	       (type, TREE_TYPE (TREE_TYPE (subtype)))))
2604    {
2605      tree type_domain;
2606      tree min_val = size_zero_node;
2607      tree newsub = cxx_fold_indirect_ref (loc, TREE_TYPE (subtype), sub, NULL);
2608      if (newsub)
2609	sub = newsub;
2610      else
2611	sub = build1_loc (loc, INDIRECT_REF, TREE_TYPE (subtype), sub);
2612      type_domain = TYPE_DOMAIN (TREE_TYPE (sub));
2613      if (type_domain && TYPE_MIN_VALUE (type_domain))
2614	min_val = TYPE_MIN_VALUE (type_domain);
2615      return build4_loc (loc, ARRAY_REF, type, sub, min_val, NULL_TREE,
2616			 NULL_TREE);
2617    }
2618
2619  return NULL_TREE;
2620}
2621
2622static tree
2623cxx_eval_indirect_ref (const constexpr_ctx *ctx, tree t,
2624		       bool lval,
2625		       bool *non_constant_p, bool *overflow_p)
2626{
2627  tree orig_op0 = TREE_OPERAND (t, 0);
2628  tree op0 = cxx_eval_constant_expression (ctx, orig_op0,
2629					   /*lval*/false, non_constant_p,
2630					   overflow_p);
2631  bool empty_base = false;
2632  tree r;
2633
2634  /* Don't VERIFY_CONSTANT here.  */
2635  if (*non_constant_p)
2636    return t;
2637
2638  r = cxx_fold_indirect_ref (EXPR_LOCATION (t), TREE_TYPE (t), op0,
2639			     &empty_base);
2640
2641  if (r)
2642    r = cxx_eval_constant_expression (ctx, r,
2643				      lval, non_constant_p, overflow_p);
2644  else
2645    {
2646      tree sub = op0;
2647      STRIP_NOPS (sub);
2648      if (TREE_CODE (sub) == ADDR_EXPR)
2649	{
2650	  /* We couldn't fold to a constant value.  Make sure it's not
2651	     something we should have been able to fold.  */
2652	  gcc_assert (!same_type_ignoring_top_level_qualifiers_p
2653		      (TREE_TYPE (TREE_TYPE (sub)), TREE_TYPE (t)));
2654	  /* DR 1188 says we don't have to deal with this.  */
2655	  if (!ctx->quiet)
2656	    error ("accessing value of %qE through a %qT glvalue in a "
2657		   "constant expression", build_fold_indirect_ref (sub),
2658		   TREE_TYPE (t));
2659	  *non_constant_p = true;
2660	  return t;
2661	}
2662    }
2663
2664  /* If we're pulling out the value of an empty base, make sure
2665     that the whole object is constant and then return an empty
2666     CONSTRUCTOR.  */
2667  if (empty_base && !lval)
2668    {
2669      VERIFY_CONSTANT (r);
2670      r = build_constructor (TREE_TYPE (t), NULL);
2671      TREE_CONSTANT (r) = true;
2672    }
2673
2674  if (r == NULL_TREE)
2675    {
2676      if (lval && op0 != orig_op0)
2677	return build1 (INDIRECT_REF, TREE_TYPE (t), op0);
2678      if (!lval)
2679	VERIFY_CONSTANT (t);
2680      return t;
2681    }
2682  return r;
2683}
2684
2685/* Complain about R, a VAR_DECL, not being usable in a constant expression.
2686   Shared between potential_constant_expression and
2687   cxx_eval_constant_expression.  */
2688
2689static void
2690non_const_var_error (tree r)
2691{
2692  tree type = TREE_TYPE (r);
2693  error ("the value of %qD is not usable in a constant "
2694	 "expression", r);
2695  /* Avoid error cascade.  */
2696  if (DECL_INITIAL (r) == error_mark_node)
2697    return;
2698  if (DECL_DECLARED_CONSTEXPR_P (r))
2699    inform (DECL_SOURCE_LOCATION (r),
2700	    "%qD used in its own initializer", r);
2701  else if (INTEGRAL_OR_ENUMERATION_TYPE_P (type))
2702    {
2703      if (!CP_TYPE_CONST_P (type))
2704	inform (DECL_SOURCE_LOCATION (r),
2705		"%q#D is not const", r);
2706      else if (CP_TYPE_VOLATILE_P (type))
2707	inform (DECL_SOURCE_LOCATION (r),
2708		"%q#D is volatile", r);
2709      else if (!DECL_INITIAL (r)
2710	       || !TREE_CONSTANT (DECL_INITIAL (r)))
2711	inform (DECL_SOURCE_LOCATION (r),
2712		"%qD was not initialized with a constant "
2713		"expression", r);
2714      else
2715	gcc_unreachable ();
2716    }
2717  else
2718    {
2719      if (cxx_dialect >= cxx11 && !DECL_DECLARED_CONSTEXPR_P (r))
2720	inform (DECL_SOURCE_LOCATION (r),
2721		"%qD was not declared %<constexpr%>", r);
2722      else
2723	inform (DECL_SOURCE_LOCATION (r),
2724		"%qD does not have integral or enumeration type",
2725		r);
2726    }
2727}
2728
2729/* Subroutine of cxx_eval_constant_expression.
2730   Like cxx_eval_unary_expression, except for trinary expressions.  */
2731
2732static tree
2733cxx_eval_trinary_expression (const constexpr_ctx *ctx, tree t,
2734			     bool lval,
2735			     bool *non_constant_p, bool *overflow_p)
2736{
2737  int i;
2738  tree args[3];
2739  tree val;
2740
2741  for (i = 0; i < 3; i++)
2742    {
2743      args[i] = cxx_eval_constant_expression (ctx, TREE_OPERAND (t, i),
2744					      lval,
2745					      non_constant_p, overflow_p);
2746      VERIFY_CONSTANT (args[i]);
2747    }
2748
2749  val = fold_ternary_loc (EXPR_LOCATION (t), TREE_CODE (t), TREE_TYPE (t),
2750			  args[0], args[1], args[2]);
2751  if (val == NULL_TREE)
2752    return t;
2753  VERIFY_CONSTANT (val);
2754  return val;
2755}
2756
2757bool
2758var_in_constexpr_fn (tree t)
2759{
2760  tree ctx = DECL_CONTEXT (t);
2761  return (cxx_dialect >= cxx14 && ctx && TREE_CODE (ctx) == FUNCTION_DECL
2762	  && DECL_DECLARED_CONSTEXPR_P (ctx));
2763}
2764
2765/* Evaluate an INIT_EXPR or MODIFY_EXPR.  */
2766
2767static tree
2768cxx_eval_store_expression (const constexpr_ctx *ctx, tree t,
2769			   bool lval,
2770			   bool *non_constant_p, bool *overflow_p)
2771{
2772  constexpr_ctx new_ctx = *ctx;
2773
2774  tree init = TREE_OPERAND (t, 1);
2775
2776  /* First we figure out where we're storing to.  */
2777  tree target = TREE_OPERAND (t, 0);
2778  tree type = TREE_TYPE (target);
2779  target = cxx_eval_constant_expression (ctx, target,
2780					 true,
2781					 non_constant_p, overflow_p);
2782  if (*non_constant_p)
2783    return t;
2784
2785  if (!same_type_ignoring_top_level_qualifiers_p (TREE_TYPE (target), type)
2786      && is_empty_class (type))
2787    {
2788      /* For initialization of an empty base, the original target will be
2789         *(base*)this, which the above evaluation resolves to the object
2790	 argument, which has the derived type rather than the base type.  In
2791	 this situation, just evaluate the initializer and return, since
2792	 there's no actual data to store.  */
2793      return cxx_eval_constant_expression (ctx, init, false,
2794					   non_constant_p, overflow_p);
2795    }
2796
2797  /* And then find the underlying variable.  */
2798  vec<tree,va_gc> *refs = make_tree_vector();
2799  tree object = NULL_TREE;
2800  for (tree probe = target; object == NULL_TREE; )
2801    {
2802      switch (TREE_CODE (probe))
2803	{
2804	case BIT_FIELD_REF:
2805	case COMPONENT_REF:
2806	case ARRAY_REF:
2807	  vec_safe_push (refs, TREE_OPERAND (probe, 1));
2808	  vec_safe_push (refs, TREE_TYPE (probe));
2809	  probe = TREE_OPERAND (probe, 0);
2810	  break;
2811
2812	default:
2813	  object = probe;
2814	}
2815    }
2816
2817  /* And then find/build up our initializer for the path to the subobject
2818     we're initializing.  */
2819  tree *valp;
2820  if (DECL_P (object))
2821    valp = ctx->values->get (object);
2822  else
2823    valp = NULL;
2824  if (!valp)
2825    {
2826      /* A constant-expression cannot modify objects from outside the
2827	 constant-expression.  */
2828      if (!ctx->quiet)
2829	error ("modification of %qE is not a constant-expression", object);
2830      *non_constant_p = true;
2831      return t;
2832    }
2833  type = TREE_TYPE (object);
2834  while (!refs->is_empty())
2835    {
2836      if (*valp == NULL_TREE)
2837	{
2838	  *valp = build_constructor (type, NULL);
2839	  CONSTRUCTOR_NO_IMPLICIT_ZERO (*valp) = true;
2840	}
2841
2842      enum tree_code code = TREE_CODE (type);
2843      type = refs->pop();
2844      tree index = refs->pop();
2845
2846      constructor_elt *cep = NULL;
2847      if (code == ARRAY_TYPE)
2848	{
2849	  HOST_WIDE_INT i
2850	    = find_array_ctor_elt (*valp, index, /*insert*/true);
2851	  gcc_assert (i >= 0);
2852	  cep = CONSTRUCTOR_ELT (*valp, i);
2853	  gcc_assert (TREE_CODE (cep->index) != RANGE_EXPR);
2854	}
2855      else
2856	{
2857	  gcc_assert (TREE_CODE (index) == FIELD_DECL);
2858
2859	  /* We must keep the CONSTRUCTOR's ELTS in FIELD order.
2860	     Usually we meet initializers in that order, but it is
2861	     possible for base types to be placed not in program
2862	     order.  */
2863	  tree fields = TYPE_FIELDS (DECL_CONTEXT (index));
2864	  unsigned HOST_WIDE_INT idx;
2865
2866	  for (idx = 0;
2867	       vec_safe_iterate (CONSTRUCTOR_ELTS (*valp), idx, &cep);
2868	       idx++)
2869	    {
2870	      if (index == cep->index)
2871		goto found;
2872
2873	      /* The field we're initializing must be on the field
2874		 list.  Look to see if it is present before the
2875		 field the current ELT initializes.  */
2876	      for (; fields != cep->index; fields = DECL_CHAIN (fields))
2877		if (index == fields)
2878		  goto insert;
2879	    }
2880
2881	  /* We fell off the end of the CONSTRUCTOR, so insert a new
2882	     entry at the end.  */
2883	insert:
2884	  {
2885	    constructor_elt ce = { index, NULL_TREE };
2886
2887	    vec_safe_insert (CONSTRUCTOR_ELTS (*valp), idx, ce);
2888	    cep = CONSTRUCTOR_ELT (*valp, idx);
2889	  }
2890	found:;
2891	}
2892      valp = &cep->value;
2893    }
2894  release_tree_vector (refs);
2895
2896  if (AGGREGATE_TYPE_P (type) || VECTOR_TYPE_P (type))
2897    {
2898      /* Create a new CONSTRUCTOR in case evaluation of the initializer
2899	 wants to modify it.  */
2900      if (*valp == NULL_TREE)
2901	{
2902	  *valp = new_ctx.ctor = build_constructor (type, NULL);
2903	  CONSTRUCTOR_NO_IMPLICIT_ZERO (new_ctx.ctor) = true;
2904	}
2905      else
2906	new_ctx.ctor = *valp;
2907      new_ctx.object = target;
2908    }
2909
2910  init = cxx_eval_constant_expression (&new_ctx, init, false,
2911				       non_constant_p, overflow_p);
2912  /* Don't share a CONSTRUCTOR that might be changed later.  */
2913  init = unshare_expr (init);
2914  if (target == object)
2915    /* The hash table might have moved since the get earlier.  */
2916    valp = ctx->values->get (object);
2917
2918  if (TREE_CODE (init) == CONSTRUCTOR)
2919    {
2920      /* An outer ctx->ctor might be pointing to *valp, so just replace
2921	 its contents.  */
2922      CONSTRUCTOR_ELTS (*valp) = CONSTRUCTOR_ELTS (init);
2923      CONSTRUCTOR_NO_IMPLICIT_ZERO (*valp)
2924	= CONSTRUCTOR_NO_IMPLICIT_ZERO (init);
2925    }
2926  else
2927    *valp = init;
2928
2929  if (*non_constant_p)
2930    return t;
2931  else if (lval)
2932    return target;
2933  else
2934    return init;
2935}
2936
2937/* Evaluate a ++ or -- expression.  */
2938
2939static tree
2940cxx_eval_increment_expression (const constexpr_ctx *ctx, tree t,
2941			      bool lval,
2942			      bool *non_constant_p, bool *overflow_p)
2943{
2944  enum tree_code code = TREE_CODE (t);
2945  tree type = TREE_TYPE (t);
2946  tree op = TREE_OPERAND (t, 0);
2947  tree offset = TREE_OPERAND (t, 1);
2948  gcc_assert (TREE_CONSTANT (offset));
2949
2950  /* The operand as an lvalue.  */
2951  op = cxx_eval_constant_expression (ctx, op, true,
2952				     non_constant_p, overflow_p);
2953
2954  /* The operand as an rvalue.  */
2955  tree val = rvalue (op);
2956  val = cxx_eval_constant_expression (ctx, val, false,
2957				      non_constant_p, overflow_p);
2958  /* Don't VERIFY_CONSTANT if this might be dealing with a pointer to
2959     a local array in a constexpr function.  */
2960  bool ptr = POINTER_TYPE_P (TREE_TYPE (val));
2961  if (!ptr)
2962    VERIFY_CONSTANT (val);
2963
2964  /* The modified value.  */
2965  bool inc = (code == PREINCREMENT_EXPR || code == POSTINCREMENT_EXPR);
2966  tree mod;
2967  if (POINTER_TYPE_P (type))
2968    {
2969      /* The middle end requires pointers to use POINTER_PLUS_EXPR.  */
2970      offset = convert_to_ptrofftype (offset);
2971      if (!inc)
2972	offset = fold_build1 (NEGATE_EXPR, TREE_TYPE (offset), offset);
2973      mod = fold_build2 (POINTER_PLUS_EXPR, type, val, offset);
2974    }
2975  else
2976    mod = fold_build2 (inc ? PLUS_EXPR : MINUS_EXPR, type, val, offset);
2977  if (!ptr)
2978    VERIFY_CONSTANT (mod);
2979
2980  /* Storing the modified value.  */
2981  tree store = build2 (MODIFY_EXPR, type, op, mod);
2982  cxx_eval_constant_expression (ctx, store,
2983				true, non_constant_p, overflow_p);
2984
2985  /* And the value of the expression.  */
2986  if (code == PREINCREMENT_EXPR || code == PREDECREMENT_EXPR)
2987    {
2988      /* Prefix ops are lvalues.  */
2989      if (lval)
2990	return op;
2991      else
2992	/* But we optimize when the caller wants an rvalue.  */
2993	return mod;
2994    }
2995  else
2996    /* Postfix ops are rvalues.  */
2997    return val;
2998}
2999
3000/* Predicates for the meaning of *jump_target.  */
3001
3002static bool
3003returns (tree *jump_target)
3004{
3005  return *jump_target
3006    && TREE_CODE (*jump_target) == RETURN_EXPR;
3007}
3008
3009static bool
3010breaks (tree *jump_target)
3011{
3012  return *jump_target
3013    && TREE_CODE (*jump_target) == LABEL_DECL
3014    && LABEL_DECL_BREAK (*jump_target);
3015}
3016
3017static bool
3018continues (tree *jump_target)
3019{
3020  return *jump_target
3021    && TREE_CODE (*jump_target) == LABEL_DECL
3022    && LABEL_DECL_CONTINUE (*jump_target);
3023}
3024
3025static bool
3026switches (tree *jump_target)
3027{
3028  return *jump_target
3029    && TREE_CODE (*jump_target) == INTEGER_CST;
3030}
3031
3032/* Subroutine of cxx_eval_statement_list.  Determine whether the statement
3033   at I matches *jump_target.  If we're looking for a case label and we see
3034   the default label, copy I into DEFAULT_LABEL.  */
3035
3036static bool
3037label_matches (tree *jump_target, tree_stmt_iterator i,
3038	       tree_stmt_iterator& default_label)
3039{
3040  tree stmt = tsi_stmt (i);
3041  switch (TREE_CODE (*jump_target))
3042    {
3043    case LABEL_DECL:
3044      if (TREE_CODE (stmt) == LABEL_EXPR
3045	  && LABEL_EXPR_LABEL (stmt) == *jump_target)
3046	return true;
3047      break;
3048
3049    case INTEGER_CST:
3050      if (TREE_CODE (stmt) == CASE_LABEL_EXPR)
3051	{
3052	  if (!CASE_LOW (stmt))
3053	    default_label = i;
3054	  else if (tree_int_cst_equal (*jump_target, CASE_LOW (stmt)))
3055	    return true;
3056	}
3057      break;
3058
3059    default:
3060      gcc_unreachable ();
3061    }
3062  return false;
3063}
3064
3065/* Evaluate a STATEMENT_LIST for side-effects.  Handles various jump
3066   semantics, for switch, break, continue, and return.  */
3067
3068static tree
3069cxx_eval_statement_list (const constexpr_ctx *ctx, tree t,
3070			 bool *non_constant_p, bool *overflow_p,
3071			 tree *jump_target)
3072{
3073  tree_stmt_iterator i;
3074  tree_stmt_iterator default_label = tree_stmt_iterator();
3075  tree local_target;
3076  /* In a statement-expression we want to return the last value.  */
3077  tree r = NULL_TREE;
3078  if (!jump_target)
3079    {
3080      local_target = NULL_TREE;
3081      jump_target = &local_target;
3082    }
3083  for (i = tsi_start (t); !tsi_end_p (i); tsi_next (&i))
3084    {
3085    reenter:
3086      tree stmt = tsi_stmt (i);
3087      if (*jump_target)
3088	{
3089	  if (TREE_CODE (stmt) == STATEMENT_LIST)
3090	    /* The label we want might be inside.  */;
3091	  else if (label_matches (jump_target, i, default_label))
3092	    /* Found it.  */
3093	    *jump_target = NULL_TREE;
3094	  else
3095	    continue;
3096	}
3097      r = cxx_eval_constant_expression (ctx, stmt, false,
3098					non_constant_p, overflow_p,
3099					jump_target);
3100      if (*non_constant_p)
3101	break;
3102      if (returns (jump_target) || breaks (jump_target))
3103	break;
3104    }
3105  if (switches (jump_target) && !tsi_end_p (default_label))
3106    {
3107      i = default_label;
3108      *jump_target = NULL_TREE;
3109      goto reenter;
3110    }
3111  return r;
3112}
3113
3114namespace {
3115bool
3116save_exprs_remover (const tree &expr, constexpr_ctx &ctx)
3117{
3118  ctx.values->remove (expr);
3119  return true;
3120}
3121}
3122
3123/* Evaluate a LOOP_EXPR for side-effects.  Handles break and return
3124   semantics; continue semantics are covered by cxx_eval_statement_list.  */
3125
3126static tree
3127cxx_eval_loop_expr (const constexpr_ctx *ctx, tree t,
3128		    bool *non_constant_p, bool *overflow_p,
3129		    tree *jump_target)
3130{
3131  constexpr_ctx new_ctx = *ctx;
3132
3133  tree body = TREE_OPERAND (t, 0);
3134  do
3135    {
3136      hash_set<tree> save_exprs;
3137      new_ctx.save_exprs = &save_exprs;
3138
3139      cxx_eval_statement_list (&new_ctx, body,
3140			       non_constant_p, overflow_p, jump_target);
3141
3142      /* Forget saved values of SAVE_EXPRs.  */
3143      save_exprs.traverse<constexpr_ctx &, save_exprs_remover>(new_ctx);
3144    }
3145  while (!returns (jump_target) && !breaks (jump_target) && !*non_constant_p);
3146
3147  if (breaks (jump_target))
3148    *jump_target = NULL_TREE;
3149
3150  return NULL_TREE;
3151}
3152
3153/* Evaluate a SWITCH_EXPR for side-effects.  Handles switch and break jump
3154   semantics.  */
3155
3156static tree
3157cxx_eval_switch_expr (const constexpr_ctx *ctx, tree t,
3158		      bool *non_constant_p, bool *overflow_p,
3159		      tree *jump_target)
3160{
3161  tree cond = TREE_OPERAND (t, 0);
3162  cond = cxx_eval_constant_expression (ctx, cond, false,
3163				       non_constant_p, overflow_p);
3164  VERIFY_CONSTANT (cond);
3165  *jump_target = cond;
3166
3167  tree body = TREE_OPERAND (t, 1);
3168  cxx_eval_statement_list (ctx, body,
3169			   non_constant_p, overflow_p, jump_target);
3170  if (breaks (jump_target) || switches (jump_target))
3171    *jump_target = NULL_TREE;
3172  return NULL_TREE;
3173}
3174
3175/* Subroutine of cxx_eval_constant_expression.
3176   Attempt to reduce a POINTER_PLUS_EXPR expression T.  */
3177
3178static tree
3179cxx_eval_pointer_plus_expression (const constexpr_ctx *ctx, tree t,
3180				  bool lval, bool *non_constant_p,
3181				  bool *overflow_p)
3182{
3183  tree orig_type = TREE_TYPE (t);
3184  tree op00 = TREE_OPERAND (t, 0);
3185  tree op01 = TREE_OPERAND (t, 1);
3186  location_t loc = EXPR_LOCATION (t);
3187
3188  op00 = cxx_eval_constant_expression (ctx, op00, lval,
3189				       non_constant_p, overflow_p);
3190
3191  STRIP_NOPS (op00);
3192  if (TREE_CODE (op00) != ADDR_EXPR)
3193    return NULL_TREE;
3194
3195  op00 = TREE_OPERAND (op00, 0);
3196
3197  /* &A[i] p+ j => &A[i + j] */
3198  if (TREE_CODE (op00) == ARRAY_REF
3199      && TREE_CODE (TREE_OPERAND (op00, 1)) == INTEGER_CST
3200      && TREE_CODE (op01) == INTEGER_CST
3201      && TYPE_SIZE_UNIT (TREE_TYPE (op00))
3202      && TREE_CODE (TYPE_SIZE_UNIT (TREE_TYPE (op00))) == INTEGER_CST)
3203    {
3204      tree type = TREE_TYPE (op00);
3205      t = fold_convert_loc (loc, ssizetype, TREE_OPERAND (op00, 1));
3206      tree nelts = array_type_nelts_top (TREE_TYPE (TREE_OPERAND (op00, 0)));
3207      /* Don't fold an out-of-bound access.  */
3208      if (!tree_int_cst_le (t, nelts))
3209	return NULL_TREE;
3210      op01 = cp_fold_convert (ssizetype, op01);
3211      /* Don't fold if op01 can't be divided exactly by TYPE_SIZE_UNIT.
3212	 constexpr int A[1]; ... (char *)&A[0] + 1 */
3213      if (!integer_zerop (fold_build2_loc (loc, TRUNC_MOD_EXPR, sizetype,
3214					   op01, TYPE_SIZE_UNIT (type))))
3215	return NULL_TREE;
3216      /* Make sure to treat the second operand of POINTER_PLUS_EXPR
3217	 as signed.  */
3218      op01 = fold_build2_loc (loc, EXACT_DIV_EXPR, ssizetype, op01,
3219			      TYPE_SIZE_UNIT (type));
3220      t = size_binop_loc (loc, PLUS_EXPR, op01, t);
3221      t = build4_loc (loc, ARRAY_REF, type, TREE_OPERAND (op00, 0),
3222		      t, NULL_TREE, NULL_TREE);
3223      t = cp_build_addr_expr (t, tf_warning_or_error);
3224      t = cp_fold_convert (orig_type, t);
3225      return cxx_eval_constant_expression (ctx, t, lval, non_constant_p,
3226					   overflow_p);
3227    }
3228
3229  return NULL_TREE;
3230}
3231
3232/* Attempt to reduce the expression T to a constant value.
3233   On failure, issue diagnostic and return error_mark_node.  */
3234/* FIXME unify with c_fully_fold */
3235/* FIXME overflow_p is too global */
3236
3237static tree
3238cxx_eval_constant_expression (const constexpr_ctx *ctx, tree t,
3239			      bool lval,
3240			      bool *non_constant_p, bool *overflow_p,
3241			      tree *jump_target)
3242{
3243  constexpr_ctx new_ctx;
3244  tree r = t;
3245
3246  if (t == error_mark_node)
3247    {
3248      *non_constant_p = true;
3249      return t;
3250    }
3251  if (CONSTANT_CLASS_P (t))
3252    {
3253      if (TREE_CODE (t) == PTRMEM_CST)
3254	t = cplus_expand_constant (t);
3255      else if (TREE_OVERFLOW (t) && (!flag_permissive || ctx->quiet))
3256	*overflow_p = true;
3257      return t;
3258    }
3259
3260  switch (TREE_CODE (t))
3261    {
3262    case RESULT_DECL:
3263      if (lval)
3264	return t;
3265      /* We ask for an rvalue for the RESULT_DECL when indirecting
3266	 through an invisible reference, or in named return value
3267	 optimization.  */
3268      return (*ctx->values->get (t));
3269
3270    case VAR_DECL:
3271    case CONST_DECL:
3272      /* We used to not check lval for CONST_DECL, but darwin.c uses
3273	 CONST_DECL for aggregate constants.  */
3274      if (lval)
3275	return t;
3276      if (ctx->strict)
3277	r = decl_really_constant_value (t);
3278      else
3279	r = decl_constant_value (t);
3280      if (TREE_CODE (r) == TARGET_EXPR
3281	  && TREE_CODE (TARGET_EXPR_INITIAL (r)) == CONSTRUCTOR)
3282	r = TARGET_EXPR_INITIAL (r);
3283      if (TREE_CODE (r) == VAR_DECL)
3284	if (tree *p = ctx->values->get (r))
3285	  if (*p != NULL_TREE)
3286	    r = *p;
3287      if (DECL_P (r))
3288	{
3289	  if (!ctx->quiet)
3290	    non_const_var_error (r);
3291	  *non_constant_p = true;
3292	}
3293      break;
3294
3295    case FUNCTION_DECL:
3296    case TEMPLATE_DECL:
3297    case LABEL_DECL:
3298    case LABEL_EXPR:
3299    case CASE_LABEL_EXPR:
3300      return t;
3301
3302    case PARM_DECL:
3303      if (!use_new_call && ctx
3304	  && ctx->call && DECL_CONTEXT (t) == ctx->call->fundef->decl)
3305	r = lookup_parameter_binding (ctx->call, t);
3306      else if (lval && TREE_CODE (TREE_TYPE (t)) != REFERENCE_TYPE)
3307	/* glvalue use.  */;
3308      else if (tree *p = ctx->values->get (r))
3309	r = *p;
3310      else if (lval)
3311	/* Defer in case this is only used for its type.  */;
3312      else if (TREE_CODE (TREE_TYPE (t)) == REFERENCE_TYPE)
3313	/* Defer, there's no lvalue->rvalue conversion.  */;
3314      else if (is_empty_class (TREE_TYPE (t)))
3315	{
3316	  /* If the class is empty, we aren't actually loading anything.  */
3317	  r = build_constructor (TREE_TYPE (t), NULL);
3318	  TREE_CONSTANT (r) = true;
3319	}
3320      else
3321	{
3322	  if (!ctx->quiet)
3323	    error ("%qE is not a constant expression", t);
3324	  *non_constant_p = true;
3325	}
3326      break;
3327
3328    case CALL_EXPR:
3329    case AGGR_INIT_EXPR:
3330      r = cxx_eval_call_expression (ctx, t, lval,
3331				    non_constant_p, overflow_p);
3332      break;
3333
3334    case DECL_EXPR:
3335      {
3336	r = DECL_EXPR_DECL (t);
3337	if (AGGREGATE_TYPE_P (TREE_TYPE (r))
3338	    || VECTOR_TYPE_P (TREE_TYPE (r)))
3339	  {
3340	    new_ctx = *ctx;
3341	    new_ctx.object = r;
3342	    new_ctx.ctor = build_constructor (TREE_TYPE (r), NULL);
3343	    CONSTRUCTOR_NO_IMPLICIT_ZERO (new_ctx.ctor) = true;
3344	    new_ctx.values->put (r, new_ctx.ctor);
3345	    ctx = &new_ctx;
3346	  }
3347
3348	if (tree init = DECL_INITIAL (r))
3349	  {
3350	    init = cxx_eval_constant_expression (ctx, init,
3351						 false,
3352						 non_constant_p, overflow_p);
3353	    /* Don't share a CONSTRUCTOR that might be changed.  */
3354	    init = unshare_expr (init);
3355	    ctx->values->put (r, init);
3356	  }
3357	else if (ctx == &new_ctx)
3358	  /* We gave it a CONSTRUCTOR above.  */;
3359	else
3360	  ctx->values->put (r, NULL_TREE);
3361      }
3362      break;
3363
3364    case TARGET_EXPR:
3365      if (!literal_type_p (TREE_TYPE (t)))
3366	{
3367	  if (!ctx->quiet)
3368	    {
3369	      error ("temporary of non-literal type %qT in a "
3370		     "constant expression", TREE_TYPE (t));
3371	      explain_non_literal_class (TREE_TYPE (t));
3372	    }
3373	  *non_constant_p = true;
3374	  break;
3375	}
3376      if ((AGGREGATE_TYPE_P (TREE_TYPE (t)) || VECTOR_TYPE_P (TREE_TYPE (t))))
3377	{
3378	  /* We're being expanded without an explicit target, so start
3379	     initializing a new object; expansion with an explicit target
3380	     strips the TARGET_EXPR before we get here.  */
3381	  new_ctx = *ctx;
3382	  new_ctx.ctor = build_constructor (TREE_TYPE (t), NULL);
3383	  CONSTRUCTOR_NO_IMPLICIT_ZERO (new_ctx.ctor) = true;
3384	  new_ctx.object = TARGET_EXPR_SLOT (t);
3385	  ctx->values->put (new_ctx.object, new_ctx.ctor);
3386	  ctx = &new_ctx;
3387	}
3388      /* Pass false for 'lval' because this indicates
3389	 initialization of a temporary.  */
3390      r = cxx_eval_constant_expression (ctx, TREE_OPERAND (t, 1),
3391					false,
3392					non_constant_p, overflow_p);
3393      if (!*non_constant_p)
3394	/* Adjust the type of the result to the type of the temporary.  */
3395	r = adjust_temp_type (TREE_TYPE (t), r);
3396      if (lval)
3397	{
3398	  tree slot = TARGET_EXPR_SLOT (t);
3399	  r = unshare_expr (r);
3400	  ctx->values->put (slot, r);
3401	  return slot;
3402	}
3403      break;
3404
3405    case INIT_EXPR:
3406      if (!use_new_call)
3407	{
3408	  /* In C++11 constexpr evaluation we are looking for the value,
3409	     not the side-effect of the initialization.  */
3410	  r = cxx_eval_constant_expression (ctx, TREE_OPERAND (t, 1),
3411					    false,
3412					    non_constant_p, overflow_p);
3413	  break;
3414	}
3415      /* else fall through */
3416    case MODIFY_EXPR:
3417      r = cxx_eval_store_expression (ctx, t, lval,
3418				     non_constant_p, overflow_p);
3419      break;
3420
3421    case SCOPE_REF:
3422      r = cxx_eval_constant_expression (ctx, TREE_OPERAND (t, 1),
3423					lval,
3424					non_constant_p, overflow_p);
3425      break;
3426
3427    case RETURN_EXPR:
3428      if (TREE_OPERAND (t, 0) != NULL_TREE)
3429	r = cxx_eval_constant_expression (ctx, TREE_OPERAND (t, 0),
3430					  lval,
3431					  non_constant_p, overflow_p);
3432      *jump_target = t;
3433      break;
3434
3435    case SAVE_EXPR:
3436      /* Avoid evaluating a SAVE_EXPR more than once.  */
3437      if (tree *p = ctx->values->get (t))
3438	r = *p;
3439      else
3440	{
3441	  r = cxx_eval_constant_expression (ctx, TREE_OPERAND (t, 0), false,
3442					    non_constant_p, overflow_p);
3443	  ctx->values->put (t, r);
3444	  if (ctx->save_exprs)
3445	    ctx->save_exprs->add (t);
3446	}
3447      break;
3448
3449    case NON_LVALUE_EXPR:
3450    case TRY_CATCH_EXPR:
3451    case TRY_BLOCK:
3452    case CLEANUP_POINT_EXPR:
3453    case MUST_NOT_THROW_EXPR:
3454    case EXPR_STMT:
3455    case EH_SPEC_BLOCK:
3456      r = cxx_eval_constant_expression (ctx, TREE_OPERAND (t, 0),
3457					lval,
3458					non_constant_p, overflow_p,
3459					jump_target);
3460      break;
3461
3462    case TRY_FINALLY_EXPR:
3463      r = cxx_eval_constant_expression (ctx, TREE_OPERAND (t, 0), lval,
3464					non_constant_p, overflow_p,
3465					jump_target);
3466      if (!*non_constant_p)
3467	/* Also evaluate the cleanup.  */
3468	cxx_eval_constant_expression (ctx, TREE_OPERAND (t, 1), true,
3469				      non_constant_p, overflow_p,
3470				      jump_target);
3471      break;
3472
3473      /* These differ from cxx_eval_unary_expression in that this doesn't
3474	 check for a constant operand or result; an address can be
3475	 constant without its operand being, and vice versa.  */
3476    case INDIRECT_REF:
3477      r = cxx_eval_indirect_ref (ctx, t, lval,
3478				 non_constant_p, overflow_p);
3479      break;
3480
3481    case ADDR_EXPR:
3482      {
3483	tree oldop = TREE_OPERAND (t, 0);
3484	tree op = cxx_eval_constant_expression (ctx, oldop,
3485						/*lval*/true,
3486						non_constant_p, overflow_p);
3487	/* Don't VERIFY_CONSTANT here.  */
3488	if (*non_constant_p)
3489	  return t;
3490	gcc_checking_assert (TREE_CODE (op) != CONSTRUCTOR);
3491	/* This function does more aggressive folding than fold itself.  */
3492	r = build_fold_addr_expr_with_type (op, TREE_TYPE (t));
3493	if (TREE_CODE (r) == ADDR_EXPR && TREE_OPERAND (r, 0) == oldop)
3494	  return t;
3495	break;
3496      }
3497
3498    case REALPART_EXPR:
3499    case IMAGPART_EXPR:
3500    case CONJ_EXPR:
3501    case FIX_TRUNC_EXPR:
3502    case FLOAT_EXPR:
3503    case NEGATE_EXPR:
3504    case ABS_EXPR:
3505    case BIT_NOT_EXPR:
3506    case TRUTH_NOT_EXPR:
3507    case FIXED_CONVERT_EXPR:
3508      r = cxx_eval_unary_expression (ctx, t, lval,
3509				     non_constant_p, overflow_p);
3510      break;
3511
3512    case SIZEOF_EXPR:
3513      if (SIZEOF_EXPR_TYPE_P (t))
3514	r = cxx_sizeof_or_alignof_type (TREE_TYPE (TREE_OPERAND (t, 0)),
3515					SIZEOF_EXPR, false);
3516      else if (TYPE_P (TREE_OPERAND (t, 0)))
3517	r = cxx_sizeof_or_alignof_type (TREE_OPERAND (t, 0), SIZEOF_EXPR,
3518					false);
3519      else
3520	r = cxx_sizeof_or_alignof_expr (TREE_OPERAND (t, 0), SIZEOF_EXPR,
3521					false);
3522      if (r == error_mark_node)
3523	r = size_one_node;
3524      VERIFY_CONSTANT (r);
3525      break;
3526
3527    case COMPOUND_EXPR:
3528      {
3529	/* check_return_expr sometimes wraps a TARGET_EXPR in a
3530	   COMPOUND_EXPR; don't get confused.  Also handle EMPTY_CLASS_EXPR
3531	   introduced by build_call_a.  */
3532	tree op0 = TREE_OPERAND (t, 0);
3533	tree op1 = TREE_OPERAND (t, 1);
3534	STRIP_NOPS (op1);
3535	if ((TREE_CODE (op0) == TARGET_EXPR && op1 == TARGET_EXPR_SLOT (op0))
3536	    || TREE_CODE (op1) == EMPTY_CLASS_EXPR)
3537	  r = cxx_eval_constant_expression (ctx, op0,
3538					    lval, non_constant_p, overflow_p,
3539					    jump_target);
3540	else
3541	  {
3542	    /* Check that the LHS is constant and then discard it.  */
3543	    cxx_eval_constant_expression (ctx, op0,
3544					  true, non_constant_p, overflow_p,
3545					  jump_target);
3546	    op1 = TREE_OPERAND (t, 1);
3547	    r = cxx_eval_constant_expression (ctx, op1,
3548					      lval, non_constant_p, overflow_p,
3549					      jump_target);
3550	  }
3551      }
3552      break;
3553
3554    case POINTER_PLUS_EXPR:
3555      r = cxx_eval_pointer_plus_expression (ctx, t, lval, non_constant_p,
3556					    overflow_p);
3557      if (r)
3558	break;
3559      /* else fall through */
3560
3561    case PLUS_EXPR:
3562    case MINUS_EXPR:
3563    case MULT_EXPR:
3564    case TRUNC_DIV_EXPR:
3565    case CEIL_DIV_EXPR:
3566    case FLOOR_DIV_EXPR:
3567    case ROUND_DIV_EXPR:
3568    case TRUNC_MOD_EXPR:
3569    case CEIL_MOD_EXPR:
3570    case ROUND_MOD_EXPR:
3571    case RDIV_EXPR:
3572    case EXACT_DIV_EXPR:
3573    case MIN_EXPR:
3574    case MAX_EXPR:
3575    case LSHIFT_EXPR:
3576    case RSHIFT_EXPR:
3577    case LROTATE_EXPR:
3578    case RROTATE_EXPR:
3579    case BIT_IOR_EXPR:
3580    case BIT_XOR_EXPR:
3581    case BIT_AND_EXPR:
3582    case TRUTH_XOR_EXPR:
3583    case LT_EXPR:
3584    case LE_EXPR:
3585    case GT_EXPR:
3586    case GE_EXPR:
3587    case EQ_EXPR:
3588    case NE_EXPR:
3589    case UNORDERED_EXPR:
3590    case ORDERED_EXPR:
3591    case UNLT_EXPR:
3592    case UNLE_EXPR:
3593    case UNGT_EXPR:
3594    case UNGE_EXPR:
3595    case UNEQ_EXPR:
3596    case LTGT_EXPR:
3597    case RANGE_EXPR:
3598    case COMPLEX_EXPR:
3599      r = cxx_eval_binary_expression (ctx, t, lval,
3600				      non_constant_p, overflow_p);
3601      break;
3602
3603      /* fold can introduce non-IF versions of these; still treat them as
3604	 short-circuiting.  */
3605    case TRUTH_AND_EXPR:
3606    case TRUTH_ANDIF_EXPR:
3607      r = cxx_eval_logical_expression (ctx, t, boolean_false_node,
3608				       boolean_true_node,
3609				       lval,
3610				       non_constant_p, overflow_p);
3611      break;
3612
3613    case TRUTH_OR_EXPR:
3614    case TRUTH_ORIF_EXPR:
3615      r = cxx_eval_logical_expression (ctx, t, boolean_true_node,
3616				       boolean_false_node,
3617				       lval,
3618				       non_constant_p, overflow_p);
3619      break;
3620
3621    case ARRAY_REF:
3622      r = cxx_eval_array_reference (ctx, t, lval,
3623				    non_constant_p, overflow_p);
3624      break;
3625
3626    case COMPONENT_REF:
3627      if (is_overloaded_fn (t))
3628	{
3629	  /* We can only get here in checking mode via
3630	     build_non_dependent_expr,  because any expression that
3631	     calls or takes the address of the function will have
3632	     pulled a FUNCTION_DECL out of the COMPONENT_REF.  */
3633	  gcc_checking_assert (ctx->quiet || errorcount);
3634	  *non_constant_p = true;
3635	  return t;
3636	}
3637      r = cxx_eval_component_reference (ctx, t, lval,
3638					non_constant_p, overflow_p);
3639      break;
3640
3641    case BIT_FIELD_REF:
3642      r = cxx_eval_bit_field_ref (ctx, t, lval,
3643				  non_constant_p, overflow_p);
3644      break;
3645
3646    case COND_EXPR:
3647    case VEC_COND_EXPR:
3648      r = cxx_eval_conditional_expression (ctx, t, lval,
3649					   non_constant_p, overflow_p,
3650					   jump_target);
3651      break;
3652
3653    case CONSTRUCTOR:
3654      if (TREE_CONSTANT (t))
3655	/* Don't re-process a constant CONSTRUCTOR, but do fold it to
3656	   VECTOR_CST if applicable.  */
3657	return fold (t);
3658      r = cxx_eval_bare_aggregate (ctx, t, lval,
3659				   non_constant_p, overflow_p);
3660      break;
3661
3662    case VEC_INIT_EXPR:
3663      /* We can get this in a defaulted constructor for a class with a
3664	 non-static data member of array type.  Either the initializer will
3665	 be NULL, meaning default-initialization, or it will be an lvalue
3666	 or xvalue of the same type, meaning direct-initialization from the
3667	 corresponding member.  */
3668      r = cxx_eval_vec_init (ctx, t, lval,
3669			     non_constant_p, overflow_p);
3670      break;
3671
3672    case FMA_EXPR:
3673    case VEC_PERM_EXPR:
3674      r = cxx_eval_trinary_expression (ctx, t, lval,
3675				       non_constant_p, overflow_p);
3676      break;
3677
3678    case CONVERT_EXPR:
3679    case VIEW_CONVERT_EXPR:
3680    case NOP_EXPR:
3681      {
3682	tree oldop = TREE_OPERAND (t, 0);
3683	tree op = cxx_eval_constant_expression (ctx, oldop,
3684						lval,
3685						non_constant_p, overflow_p);
3686	if (*non_constant_p)
3687	  return t;
3688	if (POINTER_TYPE_P (TREE_TYPE (t))
3689	    && TREE_CODE (op) == INTEGER_CST
3690	    && !integer_zerop (op))
3691	  {
3692	    if (!ctx->quiet)
3693	      error_at (EXPR_LOC_OR_LOC (t, input_location),
3694			"reinterpret_cast from integer to pointer");
3695	    *non_constant_p = true;
3696	    return t;
3697	  }
3698	if (op == oldop)
3699	  /* We didn't fold at the top so we could check for ptr-int
3700	     conversion.  */
3701	  return fold (t);
3702	r = fold_build1 (TREE_CODE (t), TREE_TYPE (t), op);
3703	/* Conversion of an out-of-range value has implementation-defined
3704	   behavior; the language considers it different from arithmetic
3705	   overflow, which is undefined.  */
3706	if (TREE_OVERFLOW_P (r) && !TREE_OVERFLOW_P (op))
3707	  TREE_OVERFLOW (r) = false;
3708      }
3709      break;
3710
3711    case EMPTY_CLASS_EXPR:
3712      /* This is good enough for a function argument that might not get
3713	 used, and they can't do anything with it, so just return it.  */
3714      return t;
3715
3716    case STATEMENT_LIST:
3717      new_ctx = *ctx;
3718      new_ctx.ctor = new_ctx.object = NULL_TREE;
3719      return cxx_eval_statement_list (&new_ctx, t,
3720				      non_constant_p, overflow_p, jump_target);
3721
3722    case BIND_EXPR:
3723      return cxx_eval_constant_expression (ctx, BIND_EXPR_BODY (t),
3724					   lval,
3725					   non_constant_p, overflow_p,
3726					   jump_target);
3727
3728    case PREINCREMENT_EXPR:
3729    case POSTINCREMENT_EXPR:
3730    case PREDECREMENT_EXPR:
3731    case POSTDECREMENT_EXPR:
3732      return cxx_eval_increment_expression (ctx, t,
3733					    lval, non_constant_p, overflow_p);
3734
3735    case LAMBDA_EXPR:
3736    case NEW_EXPR:
3737    case VEC_NEW_EXPR:
3738    case DELETE_EXPR:
3739    case VEC_DELETE_EXPR:
3740    case THROW_EXPR:
3741    case MODOP_EXPR:
3742      /* GCC internal stuff.  */
3743    case VA_ARG_EXPR:
3744    case OBJ_TYPE_REF:
3745    case WITH_CLEANUP_EXPR:
3746    case NON_DEPENDENT_EXPR:
3747    case BASELINK:
3748    case OFFSET_REF:
3749      if (!ctx->quiet)
3750        error_at (EXPR_LOC_OR_LOC (t, input_location),
3751		  "expression %qE is not a constant-expression", t);
3752      *non_constant_p = true;
3753      break;
3754
3755    case PLACEHOLDER_EXPR:
3756      if (!ctx || !ctx->ctor || (lval && !ctx->object)
3757	  || !(same_type_ignoring_top_level_qualifiers_p
3758	       (TREE_TYPE (t), TREE_TYPE (ctx->ctor))))
3759	{
3760	  /* A placeholder without a referent.  We can get here when
3761	     checking whether NSDMIs are noexcept, or in massage_init_elt;
3762	     just say it's non-constant for now.  */
3763	  gcc_assert (ctx->quiet);
3764	  *non_constant_p = true;
3765	  break;
3766	}
3767      else
3768	{
3769	  /* Use of the value or address of the current object.  We could
3770	     use ctx->object unconditionally, but using ctx->ctor when we
3771	     can is a minor optimization.  */
3772	  tree ctor = lval ? ctx->object : ctx->ctor;
3773	  return cxx_eval_constant_expression
3774	    (ctx, ctor, lval,
3775	     non_constant_p, overflow_p);
3776	}
3777      break;
3778
3779    case GOTO_EXPR:
3780      *jump_target = TREE_OPERAND (t, 0);
3781      gcc_assert (breaks (jump_target) || continues (jump_target));
3782      break;
3783
3784    case LOOP_EXPR:
3785      cxx_eval_loop_expr (ctx, t,
3786			  non_constant_p, overflow_p, jump_target);
3787      break;
3788
3789    case SWITCH_EXPR:
3790      cxx_eval_switch_expr (ctx, t,
3791			    non_constant_p, overflow_p, jump_target);
3792      break;
3793
3794    default:
3795      if (STATEMENT_CODE_P (TREE_CODE (t)))
3796	{
3797	  /* This function doesn't know how to deal with pre-genericize
3798	     statements; this can only happen with statement-expressions,
3799	     so for now just fail.  */
3800	  if (!ctx->quiet)
3801	    error_at (EXPR_LOCATION (t),
3802		      "statement is not a constant-expression");
3803	}
3804      else
3805	internal_error ("unexpected expression %qE of kind %s", t,
3806			get_tree_code_name (TREE_CODE (t)));
3807      *non_constant_p = true;
3808      break;
3809    }
3810
3811  if (r == error_mark_node)
3812    *non_constant_p = true;
3813
3814  if (*non_constant_p)
3815    return t;
3816  else
3817    return r;
3818}
3819
3820static tree
3821cxx_eval_outermost_constant_expr (tree t, bool allow_non_constant,
3822				  bool strict = true, tree object = NULL_TREE)
3823{
3824  bool non_constant_p = false;
3825  bool overflow_p = false;
3826  hash_map<tree,tree> map;
3827
3828  constexpr_ctx ctx = { NULL, &map, NULL, NULL, NULL,
3829			allow_non_constant, strict };
3830
3831  tree type = initialized_type (t);
3832  tree r = t;
3833  if (AGGREGATE_TYPE_P (type) || VECTOR_TYPE_P (type))
3834    {
3835      /* In C++14 an NSDMI can participate in aggregate initialization,
3836	 and can refer to the address of the object being initialized, so
3837	 we need to pass in the relevant VAR_DECL if we want to do the
3838	 evaluation in a single pass.  The evaluation will dynamically
3839	 update ctx.values for the VAR_DECL.  We use the same strategy
3840	 for C++11 constexpr constructors that refer to the object being
3841	 initialized.  */
3842      ctx.ctor = build_constructor (type, NULL);
3843      CONSTRUCTOR_NO_IMPLICIT_ZERO (ctx.ctor) = true;
3844      if (!object)
3845	{
3846	  if (TREE_CODE (t) == TARGET_EXPR)
3847	    object = TARGET_EXPR_SLOT (t);
3848	  else if (TREE_CODE (t) == AGGR_INIT_EXPR)
3849	    object = AGGR_INIT_EXPR_SLOT (t);
3850	}
3851      ctx.object = object;
3852      if (object)
3853	gcc_assert (same_type_ignoring_top_level_qualifiers_p
3854		    (type, TREE_TYPE (object)));
3855      if (object && DECL_P (object))
3856	map.put (object, ctx.ctor);
3857      if (TREE_CODE (r) == TARGET_EXPR)
3858	/* Avoid creating another CONSTRUCTOR when we expand the
3859	   TARGET_EXPR.  */
3860	r = TARGET_EXPR_INITIAL (r);
3861    }
3862
3863  r = cxx_eval_constant_expression (&ctx, r,
3864				    false, &non_constant_p, &overflow_p);
3865
3866  verify_constant (r, allow_non_constant, &non_constant_p, &overflow_p);
3867
3868  /* Mutable logic is a bit tricky: we want to allow initialization of
3869     constexpr variables with mutable members, but we can't copy those
3870     members to another constexpr variable.  */
3871  if (TREE_CODE (r) == CONSTRUCTOR
3872      && CONSTRUCTOR_MUTABLE_POISON (r))
3873    {
3874      if (!allow_non_constant)
3875	error ("%qE is not a constant expression because it refers to "
3876	       "mutable subobjects of %qT", t, type);
3877      non_constant_p = true;
3878    }
3879
3880  /* Technically we should check this for all subexpressions, but that
3881     runs into problems with our internal representation of pointer
3882     subtraction and the 5.19 rules are still in flux.  */
3883  if (CONVERT_EXPR_CODE_P (TREE_CODE (r))
3884      && ARITHMETIC_TYPE_P (TREE_TYPE (r))
3885      && TREE_CODE (TREE_OPERAND (r, 0)) == ADDR_EXPR)
3886    {
3887      if (!allow_non_constant)
3888	error ("conversion from pointer type %qT "
3889	       "to arithmetic type %qT in a constant-expression",
3890	       TREE_TYPE (TREE_OPERAND (r, 0)), TREE_TYPE (r));
3891      non_constant_p = true;
3892    }
3893
3894  if (!non_constant_p && overflow_p)
3895    non_constant_p = true;
3896
3897  if (non_constant_p && !allow_non_constant)
3898    return error_mark_node;
3899  else if (non_constant_p && TREE_CONSTANT (r))
3900    {
3901      /* This isn't actually constant, so unset TREE_CONSTANT.  */
3902      if (EXPR_P (r))
3903	r = copy_node (r);
3904      else if (TREE_CODE (r) == CONSTRUCTOR)
3905	r = build1 (VIEW_CONVERT_EXPR, TREE_TYPE (r), r);
3906      else
3907	r = build_nop (TREE_TYPE (r), r);
3908      TREE_CONSTANT (r) = false;
3909    }
3910  else if (non_constant_p || r == t)
3911    return t;
3912
3913  if (TREE_CODE (r) == CONSTRUCTOR && CLASS_TYPE_P (TREE_TYPE (r)))
3914    {
3915      if (TREE_CODE (t) == TARGET_EXPR
3916	  && TARGET_EXPR_INITIAL (t) == r)
3917	return t;
3918      else
3919	{
3920	  r = get_target_expr (r);
3921	  TREE_CONSTANT (r) = true;
3922	  return r;
3923	}
3924    }
3925  else
3926    return r;
3927}
3928
3929/* Returns true if T is a valid subexpression of a constant expression,
3930   even if it isn't itself a constant expression.  */
3931
3932bool
3933is_sub_constant_expr (tree t)
3934{
3935  bool non_constant_p = false;
3936  bool overflow_p = false;
3937  hash_map <tree, tree> map;
3938
3939  constexpr_ctx ctx = { NULL, &map, NULL, NULL, NULL, true, true };
3940
3941  cxx_eval_constant_expression (&ctx, t, false, &non_constant_p,
3942				&overflow_p);
3943  return !non_constant_p && !overflow_p;
3944}
3945
3946/* If T represents a constant expression returns its reduced value.
3947   Otherwise return error_mark_node.  If T is dependent, then
3948   return NULL.  */
3949
3950tree
3951cxx_constant_value (tree t, tree decl)
3952{
3953  return cxx_eval_outermost_constant_expr (t, false, true, decl);
3954}
3955
3956/* If T is a constant expression, returns its reduced value.
3957   Otherwise, if T does not have TREE_CONSTANT set, returns T.
3958   Otherwise, returns a version of T without TREE_CONSTANT.  */
3959
3960tree
3961maybe_constant_value (tree t, tree decl)
3962{
3963  tree r;
3964
3965  if (instantiation_dependent_expression_p (t)
3966      || type_unknown_p (t)
3967      || BRACE_ENCLOSED_INITIALIZER_P (t)
3968      || !potential_constant_expression (t))
3969    {
3970      if (TREE_OVERFLOW_P (t))
3971	{
3972	  t = build_nop (TREE_TYPE (t), t);
3973	  TREE_CONSTANT (t) = false;
3974	}
3975      return t;
3976    }
3977
3978  r = cxx_eval_outermost_constant_expr (t, true, true, decl);
3979#ifdef ENABLE_CHECKING
3980  gcc_assert (r == t
3981	      || CONVERT_EXPR_P (t)
3982	      || TREE_CODE (t) == VIEW_CONVERT_EXPR
3983	      || (TREE_CONSTANT (t) && !TREE_CONSTANT (r))
3984	      || !cp_tree_equal (r, t));
3985#endif
3986  return r;
3987}
3988
3989/* Like maybe_constant_value but first fully instantiate the argument.
3990
3991   Note: this is equivalent to instantiate_non_dependent_expr_sfinae
3992   (t, tf_none) followed by maybe_constant_value but is more efficient,
3993   because calls instantiation_dependent_expression_p and
3994   potential_constant_expression at most once.  */
3995
3996tree
3997fold_non_dependent_expr (tree t)
3998{
3999  if (t == NULL_TREE)
4000    return NULL_TREE;
4001
4002  /* If we're in a template, but T isn't value dependent, simplify
4003     it.  We're supposed to treat:
4004
4005       template <typename T> void f(T[1 + 1]);
4006       template <typename T> void f(T[2]);
4007
4008     as two declarations of the same function, for example.  */
4009  if (processing_template_decl)
4010    {
4011      if (!instantiation_dependent_expression_p (t)
4012	  && potential_constant_expression (t))
4013	{
4014	  processing_template_decl_sentinel s;
4015	  t = instantiate_non_dependent_expr_internal (t, tf_none);
4016
4017	  if (type_unknown_p (t)
4018	      || BRACE_ENCLOSED_INITIALIZER_P (t))
4019	    {
4020	      if (TREE_OVERFLOW_P (t))
4021		{
4022		  t = build_nop (TREE_TYPE (t), t);
4023		  TREE_CONSTANT (t) = false;
4024		}
4025	      return t;
4026	    }
4027
4028	  tree r = cxx_eval_outermost_constant_expr (t, true, true, NULL_TREE);
4029#ifdef ENABLE_CHECKING
4030	  /* cp_tree_equal looks through NOPs, so allow them.  */
4031	  gcc_assert (r == t
4032		      || CONVERT_EXPR_P (t)
4033		      || TREE_CODE (t) == VIEW_CONVERT_EXPR
4034		      || (TREE_CONSTANT (t) && !TREE_CONSTANT (r))
4035		      || !cp_tree_equal (r, t));
4036#endif
4037	  return r;
4038	}
4039      else if (TREE_OVERFLOW_P (t))
4040	{
4041	  t = build_nop (TREE_TYPE (t), t);
4042	  TREE_CONSTANT (t) = false;
4043	}
4044      return t;
4045    }
4046
4047  return maybe_constant_value (t);
4048}
4049
4050/* Like maybe_constant_value, but returns a CONSTRUCTOR directly, rather
4051   than wrapped in a TARGET_EXPR.  */
4052
4053tree
4054maybe_constant_init (tree t, tree decl)
4055{
4056  if (TREE_CODE (t) == EXPR_STMT)
4057    t = TREE_OPERAND (t, 0);
4058  if (TREE_CODE (t) == CONVERT_EXPR
4059      && VOID_TYPE_P (TREE_TYPE (t)))
4060    t = TREE_OPERAND (t, 0);
4061  if (TREE_CODE (t) == INIT_EXPR)
4062    t = TREE_OPERAND (t, 1);
4063  if (instantiation_dependent_expression_p (t)
4064      || type_unknown_p (t)
4065      || BRACE_ENCLOSED_INITIALIZER_P (t)
4066      || !potential_static_init_expression (t))
4067    /* Don't try to evaluate it.  */;
4068  else
4069    t = cxx_eval_outermost_constant_expr (t, true, false, decl);
4070  if (TREE_CODE (t) == TARGET_EXPR)
4071    {
4072      tree init = TARGET_EXPR_INITIAL (t);
4073      if (TREE_CODE (init) == CONSTRUCTOR)
4074	t = init;
4075    }
4076  return t;
4077}
4078
4079#if 0
4080/* FIXME see ADDR_EXPR section in potential_constant_expression_1.  */
4081/* Return true if the object referred to by REF has automatic or thread
4082   local storage.  */
4083
4084enum { ck_ok, ck_bad, ck_unknown };
4085static int
4086check_automatic_or_tls (tree ref)
4087{
4088  machine_mode mode;
4089  HOST_WIDE_INT bitsize, bitpos;
4090  tree offset;
4091  int volatilep = 0, unsignedp = 0;
4092  tree decl = get_inner_reference (ref, &bitsize, &bitpos, &offset,
4093				   &mode, &unsignedp, &volatilep, false);
4094  duration_kind dk;
4095
4096  /* If there isn't a decl in the middle, we don't know the linkage here,
4097     and this isn't a constant expression anyway.  */
4098  if (!DECL_P (decl))
4099    return ck_unknown;
4100  dk = decl_storage_duration (decl);
4101  return (dk == dk_auto || dk == dk_thread) ? ck_bad : ck_ok;
4102}
4103#endif
4104
4105/* Return true if T denotes a potentially constant expression.  Issue
4106   diagnostic as appropriate under control of FLAGS.  If WANT_RVAL is true,
4107   an lvalue-rvalue conversion is implied.
4108
4109   C++0x [expr.const] used to say
4110
4111   6 An expression is a potential constant expression if it is
4112     a constant expression where all occurrences of function
4113     parameters are replaced by arbitrary constant expressions
4114     of the appropriate type.
4115
4116   2  A conditional expression is a constant expression unless it
4117      involves one of the following as a potentially evaluated
4118      subexpression (3.2), but subexpressions of logical AND (5.14),
4119      logical OR (5.15), and conditional (5.16) operations that are
4120      not evaluated are not considered.   */
4121
4122static bool
4123potential_constant_expression_1 (tree t, bool want_rval, bool strict,
4124				 tsubst_flags_t flags)
4125{
4126#define RECUR(T,RV) potential_constant_expression_1 ((T), (RV), strict, flags)
4127  enum { any = false, rval = true };
4128  int i;
4129  tree tmp;
4130
4131  if (t == error_mark_node)
4132    return false;
4133  if (t == NULL_TREE)
4134    return true;
4135  if (TREE_THIS_VOLATILE (t))
4136    {
4137      if (flags & tf_error)
4138        error ("expression %qE has side-effects", t);
4139      return false;
4140    }
4141  if (CONSTANT_CLASS_P (t))
4142    return true;
4143
4144  switch (TREE_CODE (t))
4145    {
4146    case FUNCTION_DECL:
4147    case BASELINK:
4148    case TEMPLATE_DECL:
4149    case OVERLOAD:
4150    case TEMPLATE_ID_EXPR:
4151    case LABEL_DECL:
4152    case LABEL_EXPR:
4153    case CASE_LABEL_EXPR:
4154    case CONST_DECL:
4155    case SIZEOF_EXPR:
4156    case ALIGNOF_EXPR:
4157    case OFFSETOF_EXPR:
4158    case NOEXCEPT_EXPR:
4159    case TEMPLATE_PARM_INDEX:
4160    case TRAIT_EXPR:
4161    case IDENTIFIER_NODE:
4162    case USERDEF_LITERAL:
4163      /* We can see a FIELD_DECL in a pointer-to-member expression.  */
4164    case FIELD_DECL:
4165    case PARM_DECL:
4166    case USING_DECL:
4167    case USING_STMT:
4168    case PLACEHOLDER_EXPR:
4169    case BREAK_STMT:
4170    case CONTINUE_STMT:
4171      return true;
4172
4173    case AGGR_INIT_EXPR:
4174    case CALL_EXPR:
4175      /* -- an invocation of a function other than a constexpr function
4176            or a constexpr constructor.  */
4177      {
4178        tree fun = get_function_named_in_call (t);
4179        const int nargs = call_expr_nargs (t);
4180	i = 0;
4181
4182	if (fun == NULL_TREE)
4183	  {
4184	    if (TREE_CODE (t) == CALL_EXPR
4185		&& CALL_EXPR_FN (t) == NULL_TREE)
4186	      switch (CALL_EXPR_IFN (t))
4187		{
4188		/* These should be ignored, they are optimized away from
4189		   constexpr functions.  */
4190		case IFN_UBSAN_NULL:
4191		case IFN_UBSAN_BOUNDS:
4192		case IFN_UBSAN_VPTR:
4193		  return true;
4194		default:
4195		  break;
4196		}
4197	    /* fold_call_expr can't do anything with IFN calls.  */
4198	    if (flags & tf_error)
4199	      error_at (EXPR_LOC_OR_LOC (t, input_location),
4200			"call to internal function");
4201	    return false;
4202	  }
4203	if (is_overloaded_fn (fun))
4204	  {
4205	    if (TREE_CODE (fun) == FUNCTION_DECL)
4206	      {
4207		if (builtin_valid_in_constant_expr_p (fun))
4208		  return true;
4209		if (!DECL_DECLARED_CONSTEXPR_P (fun)
4210		    /* Allow any built-in function; if the expansion
4211		       isn't constant, we'll deal with that then.  */
4212		    && !is_builtin_fn (fun))
4213		  {
4214		    if (flags & tf_error)
4215		      {
4216			error_at (EXPR_LOC_OR_LOC (t, input_location),
4217				  "call to non-constexpr function %qD", fun);
4218			explain_invalid_constexpr_fn (fun);
4219		      }
4220		    return false;
4221		  }
4222		/* A call to a non-static member function takes the address
4223		   of the object as the first argument.  But in a constant
4224		   expression the address will be folded away, so look
4225		   through it now.  */
4226		if (DECL_NONSTATIC_MEMBER_FUNCTION_P (fun)
4227		    && !DECL_CONSTRUCTOR_P (fun))
4228		  {
4229		    tree x = get_nth_callarg (t, 0);
4230		    if (is_this_parameter (x))
4231		      return true;
4232		    else if (!RECUR (x, rval))
4233		      return false;
4234		    i = 1;
4235		  }
4236	      }
4237	    else
4238	      {
4239		if (!RECUR (fun, true))
4240		  return false;
4241		fun = get_first_fn (fun);
4242	      }
4243	    /* Skip initial arguments to base constructors.  */
4244	    if (DECL_BASE_CONSTRUCTOR_P (fun))
4245	      i = num_artificial_parms_for (fun);
4246	    fun = DECL_ORIGIN (fun);
4247	  }
4248	else
4249          {
4250	    if (RECUR (fun, rval))
4251	      /* Might end up being a constant function pointer.  */;
4252	    else
4253	      return false;
4254          }
4255        for (; i < nargs; ++i)
4256          {
4257            tree x = get_nth_callarg (t, i);
4258	    /* In a template, reference arguments haven't been converted to
4259	       REFERENCE_TYPE and we might not even know if the parameter
4260	       is a reference, so accept lvalue constants too.  */
4261	    bool rv = processing_template_decl ? any : rval;
4262	    if (!RECUR (x, rv))
4263	      return false;
4264          }
4265        return true;
4266      }
4267
4268    case NON_LVALUE_EXPR:
4269      /* -- an lvalue-to-rvalue conversion (4.1) unless it is applied to
4270            -- an lvalue of integral type that refers to a non-volatile
4271               const variable or static data member initialized with
4272               constant expressions, or
4273
4274            -- an lvalue of literal type that refers to non-volatile
4275               object defined with constexpr, or that refers to a
4276               sub-object of such an object;  */
4277      return RECUR (TREE_OPERAND (t, 0), rval);
4278
4279    case VAR_DECL:
4280      if (want_rval
4281	  && !decl_constant_var_p (t)
4282	  && (strict
4283	      || !CP_TYPE_CONST_NON_VOLATILE_P (TREE_TYPE (t))
4284	      || !DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (t))
4285	  && !var_in_constexpr_fn (t)
4286	  && !type_dependent_expression_p (t))
4287        {
4288          if (flags & tf_error)
4289            non_const_var_error (t);
4290          return false;
4291        }
4292      return true;
4293
4294    case NOP_EXPR:
4295    case CONVERT_EXPR:
4296    case VIEW_CONVERT_EXPR:
4297      /* -- a reinterpret_cast.  FIXME not implemented, and this rule
4298	 may change to something more specific to type-punning (DR 1312).  */
4299      {
4300        tree from = TREE_OPERAND (t, 0);
4301	if (POINTER_TYPE_P (TREE_TYPE (t))
4302	    && TREE_CODE (from) == INTEGER_CST
4303	    && !integer_zerop (from))
4304	  {
4305	    if (flags & tf_error)
4306	      error_at (EXPR_LOC_OR_LOC (t, input_location),
4307			"reinterpret_cast from integer to pointer");
4308	    return false;
4309	  }
4310        return (RECUR (from, TREE_CODE (t) != VIEW_CONVERT_EXPR));
4311      }
4312
4313    case ADDR_EXPR:
4314      /* -- a unary operator & that is applied to an lvalue that
4315            designates an object with thread or automatic storage
4316            duration;  */
4317      t = TREE_OPERAND (t, 0);
4318
4319      if (TREE_CODE (t) == OFFSET_REF && PTRMEM_OK_P (t))
4320	/* A pointer-to-member constant.  */
4321	return true;
4322
4323#if 0
4324      /* FIXME adjust when issue 1197 is fully resolved.  For now don't do
4325         any checking here, as we might dereference the pointer later.  If
4326         we remove this code, also remove check_automatic_or_tls.  */
4327      i = check_automatic_or_tls (t);
4328      if (i == ck_ok)
4329	return true;
4330      if (i == ck_bad)
4331        {
4332          if (flags & tf_error)
4333            error ("address-of an object %qE with thread local or "
4334                   "automatic storage is not a constant expression", t);
4335          return false;
4336        }
4337#endif
4338      return RECUR (t, any);
4339
4340    case COMPONENT_REF:
4341    case BIT_FIELD_REF:
4342    case ARROW_EXPR:
4343    case OFFSET_REF:
4344      /* -- a class member access unless its postfix-expression is
4345            of literal type or of pointer to literal type.  */
4346      /* This test would be redundant, as it follows from the
4347	 postfix-expression being a potential constant expression.  */
4348      return RECUR (TREE_OPERAND (t, 0), want_rval);
4349
4350    case EXPR_PACK_EXPANSION:
4351      return RECUR (PACK_EXPANSION_PATTERN (t), want_rval);
4352
4353    case INDIRECT_REF:
4354      {
4355        tree x = TREE_OPERAND (t, 0);
4356        STRIP_NOPS (x);
4357        if (is_this_parameter (x))
4358	  {
4359	    if (DECL_CONTEXT (x)
4360		&& !DECL_DECLARED_CONSTEXPR_P (DECL_CONTEXT (x)))
4361	      {
4362		if (flags & tf_error)
4363		  error ("use of %<this%> in a constant expression");
4364		return false;
4365	      }
4366	    return true;
4367	  }
4368	return RECUR (x, rval);
4369      }
4370
4371    case STATEMENT_LIST:
4372      {
4373	tree_stmt_iterator i;
4374	for (i = tsi_start (t); !tsi_end_p (i); tsi_next (&i))
4375	  {
4376	    if (!RECUR (tsi_stmt (i), any))
4377	      return false;
4378	  }
4379	return true;
4380      }
4381      break;
4382
4383    case MODIFY_EXPR:
4384      if (cxx_dialect < cxx14)
4385	goto fail;
4386      if (!RECUR (TREE_OPERAND (t, 0), any))
4387	return false;
4388      if (!RECUR (TREE_OPERAND (t, 1), rval))
4389	return false;
4390      return true;
4391
4392    case MODOP_EXPR:
4393      if (cxx_dialect < cxx14)
4394	goto fail;
4395      if (!RECUR (TREE_OPERAND (t, 0), rval))
4396	return false;
4397      if (!RECUR (TREE_OPERAND (t, 2), rval))
4398	return false;
4399      return true;
4400
4401    case IF_STMT:
4402      if (!RECUR (IF_COND (t), rval))
4403	return false;
4404      if (!RECUR (THEN_CLAUSE (t), any))
4405	return false;
4406      if (!RECUR (ELSE_CLAUSE (t), any))
4407	return false;
4408      return true;
4409
4410    case DO_STMT:
4411      if (!RECUR (DO_COND (t), rval))
4412	return false;
4413      if (!RECUR (DO_BODY (t), any))
4414	return false;
4415      return true;
4416
4417    case FOR_STMT:
4418      if (!RECUR (FOR_INIT_STMT (t), any))
4419	return false;
4420      if (!RECUR (FOR_COND (t), rval))
4421	return false;
4422      if (!RECUR (FOR_EXPR (t), any))
4423	return false;
4424      if (!RECUR (FOR_BODY (t), any))
4425	return false;
4426      return true;
4427
4428    case WHILE_STMT:
4429      if (!RECUR (WHILE_COND (t), rval))
4430	return false;
4431      if (!RECUR (WHILE_BODY (t), any))
4432	return false;
4433      return true;
4434
4435    case SWITCH_STMT:
4436      if (!RECUR (SWITCH_STMT_COND (t), rval))
4437	return false;
4438      if (!RECUR (SWITCH_STMT_BODY (t), any))
4439	return false;
4440      return true;
4441
4442    case STMT_EXPR:
4443      return RECUR (STMT_EXPR_STMT (t), rval);
4444
4445    case LAMBDA_EXPR:
4446    case DYNAMIC_CAST_EXPR:
4447    case PSEUDO_DTOR_EXPR:
4448    case NEW_EXPR:
4449    case VEC_NEW_EXPR:
4450    case DELETE_EXPR:
4451    case VEC_DELETE_EXPR:
4452    case THROW_EXPR:
4453    case OMP_ATOMIC:
4454    case OMP_ATOMIC_READ:
4455    case OMP_ATOMIC_CAPTURE_OLD:
4456    case OMP_ATOMIC_CAPTURE_NEW:
4457      /* GCC internal stuff.  */
4458    case VA_ARG_EXPR:
4459    case OBJ_TYPE_REF:
4460    case TRANSACTION_EXPR:
4461    case ASM_EXPR:
4462    fail:
4463      if (flags & tf_error)
4464        error ("expression %qE is not a constant-expression", t);
4465      return false;
4466
4467    case TYPEID_EXPR:
4468      /* -- a typeid expression whose operand is of polymorphic
4469            class type;  */
4470      {
4471        tree e = TREE_OPERAND (t, 0);
4472        if (!TYPE_P (e) && !type_dependent_expression_p (e)
4473	    && TYPE_POLYMORPHIC_P (TREE_TYPE (e)))
4474          {
4475            if (flags & tf_error)
4476              error ("typeid-expression is not a constant expression "
4477                     "because %qE is of polymorphic type", e);
4478            return false;
4479          }
4480        return true;
4481      }
4482
4483    case MINUS_EXPR:
4484      /* -- a subtraction where both operands are pointers.   */
4485      if (TYPE_PTR_P (TREE_OPERAND (t, 0))
4486          && TYPE_PTR_P (TREE_OPERAND (t, 1)))
4487        {
4488          if (flags & tf_error)
4489            error ("difference of two pointer expressions is not "
4490                   "a constant expression");
4491          return false;
4492        }
4493      want_rval = true;
4494      goto binary;
4495
4496    case LT_EXPR:
4497    case LE_EXPR:
4498    case GT_EXPR:
4499    case GE_EXPR:
4500    case EQ_EXPR:
4501    case NE_EXPR:
4502      /* -- a relational or equality operator where at least
4503            one of the operands is a pointer.  */
4504      if (TYPE_PTR_P (TREE_OPERAND (t, 0))
4505          || TYPE_PTR_P (TREE_OPERAND (t, 1)))
4506        {
4507          if (flags & tf_error)
4508            error ("pointer comparison expression is not a "
4509                   "constant expression");
4510          return false;
4511        }
4512      want_rval = true;
4513      goto binary;
4514
4515    case PREINCREMENT_EXPR:
4516    case POSTINCREMENT_EXPR:
4517    case PREDECREMENT_EXPR:
4518    case POSTDECREMENT_EXPR:
4519      if (cxx_dialect < cxx14)
4520	goto fail;
4521      goto unary;
4522
4523    case BIT_NOT_EXPR:
4524      /* A destructor.  */
4525      if (TYPE_P (TREE_OPERAND (t, 0)))
4526	return true;
4527      /* else fall through.  */
4528
4529    case REALPART_EXPR:
4530    case IMAGPART_EXPR:
4531    case CONJ_EXPR:
4532    case SAVE_EXPR:
4533    case FIX_TRUNC_EXPR:
4534    case FLOAT_EXPR:
4535    case NEGATE_EXPR:
4536    case ABS_EXPR:
4537    case TRUTH_NOT_EXPR:
4538    case FIXED_CONVERT_EXPR:
4539    case UNARY_PLUS_EXPR:
4540    unary:
4541      return RECUR (TREE_OPERAND (t, 0), rval);
4542
4543    case CAST_EXPR:
4544    case CONST_CAST_EXPR:
4545    case STATIC_CAST_EXPR:
4546    case REINTERPRET_CAST_EXPR:
4547    case IMPLICIT_CONV_EXPR:
4548      if (cxx_dialect < cxx11
4549	  && !dependent_type_p (TREE_TYPE (t))
4550	  && !INTEGRAL_OR_ENUMERATION_TYPE_P (TREE_TYPE (t)))
4551	/* In C++98, a conversion to non-integral type can't be part of a
4552	   constant expression.  */
4553	{
4554	  if (flags & tf_error)
4555	    error ("cast to non-integral type %qT in a constant expression",
4556		   TREE_TYPE (t));
4557	  return false;
4558	}
4559
4560      return (RECUR (TREE_OPERAND (t, 0),
4561		     TREE_CODE (TREE_TYPE (t)) != REFERENCE_TYPE));
4562
4563    case BIND_EXPR:
4564      return RECUR (BIND_EXPR_BODY (t), want_rval);
4565
4566    case WITH_CLEANUP_EXPR:
4567    case CLEANUP_POINT_EXPR:
4568    case MUST_NOT_THROW_EXPR:
4569    case TRY_CATCH_EXPR:
4570    case TRY_BLOCK:
4571    case EH_SPEC_BLOCK:
4572    case EXPR_STMT:
4573    case PAREN_EXPR:
4574    case DECL_EXPR:
4575    case NON_DEPENDENT_EXPR:
4576      /* For convenience.  */
4577    case RETURN_EXPR:
4578      return RECUR (TREE_OPERAND (t, 0), want_rval);
4579
4580    case TRY_FINALLY_EXPR:
4581      return (RECUR (TREE_OPERAND (t, 0), want_rval)
4582	      && RECUR (TREE_OPERAND (t, 1), any));
4583
4584    case SCOPE_REF:
4585      return RECUR (TREE_OPERAND (t, 1), want_rval);
4586
4587    case TARGET_EXPR:
4588      if (!literal_type_p (TREE_TYPE (t)))
4589	{
4590	  if (flags & tf_error)
4591	    {
4592	      error ("temporary of non-literal type %qT in a "
4593		     "constant expression", TREE_TYPE (t));
4594	      explain_non_literal_class (TREE_TYPE (t));
4595	    }
4596	  return false;
4597	}
4598    case INIT_EXPR:
4599      return RECUR (TREE_OPERAND (t, 1), rval);
4600
4601    case CONSTRUCTOR:
4602      {
4603        vec<constructor_elt, va_gc> *v = CONSTRUCTOR_ELTS (t);
4604        constructor_elt *ce;
4605        for (i = 0; vec_safe_iterate (v, i, &ce); ++i)
4606	  if (!RECUR (ce->value, want_rval))
4607	    return false;
4608	return true;
4609      }
4610
4611    case TREE_LIST:
4612      {
4613	gcc_assert (TREE_PURPOSE (t) == NULL_TREE
4614		    || DECL_P (TREE_PURPOSE (t)));
4615	if (!RECUR (TREE_VALUE (t), want_rval))
4616	  return false;
4617	if (TREE_CHAIN (t) == NULL_TREE)
4618	  return true;
4619	return RECUR (TREE_CHAIN (t), want_rval);
4620      }
4621
4622    case TRUNC_DIV_EXPR:
4623    case CEIL_DIV_EXPR:
4624    case FLOOR_DIV_EXPR:
4625    case ROUND_DIV_EXPR:
4626    case TRUNC_MOD_EXPR:
4627    case CEIL_MOD_EXPR:
4628    case ROUND_MOD_EXPR:
4629      {
4630	tree denom = TREE_OPERAND (t, 1);
4631	if (!RECUR (denom, rval))
4632	  return false;
4633	/* We can't call cxx_eval_outermost_constant_expr on an expression
4634	   that hasn't been through instantiate_non_dependent_expr yet.  */
4635	if (!processing_template_decl)
4636	  denom = cxx_eval_outermost_constant_expr (denom, true);
4637	if (integer_zerop (denom))
4638	  {
4639	    if (flags & tf_error)
4640	      error ("division by zero is not a constant-expression");
4641	    return false;
4642	  }
4643	else
4644	  {
4645	    want_rval = true;
4646	    return RECUR (TREE_OPERAND (t, 0), want_rval);
4647	  }
4648      }
4649
4650    case COMPOUND_EXPR:
4651      {
4652	/* check_return_expr sometimes wraps a TARGET_EXPR in a
4653	   COMPOUND_EXPR; don't get confused.  Also handle EMPTY_CLASS_EXPR
4654	   introduced by build_call_a.  */
4655	tree op0 = TREE_OPERAND (t, 0);
4656	tree op1 = TREE_OPERAND (t, 1);
4657	STRIP_NOPS (op1);
4658	if ((TREE_CODE (op0) == TARGET_EXPR && op1 == TARGET_EXPR_SLOT (op0))
4659	    || TREE_CODE (op1) == EMPTY_CLASS_EXPR)
4660	  return RECUR (op0, want_rval);
4661	else
4662	  goto binary;
4663      }
4664
4665      /* If the first operand is the non-short-circuit constant, look at
4666	 the second operand; otherwise we only care about the first one for
4667	 potentiality.  */
4668    case TRUTH_AND_EXPR:
4669    case TRUTH_ANDIF_EXPR:
4670      tmp = boolean_true_node;
4671      goto truth;
4672    case TRUTH_OR_EXPR:
4673    case TRUTH_ORIF_EXPR:
4674      tmp = boolean_false_node;
4675    truth:
4676      {
4677	tree op = TREE_OPERAND (t, 0);
4678	if (!RECUR (op, rval))
4679	  return false;
4680	if (!processing_template_decl)
4681	  op = cxx_eval_outermost_constant_expr (op, true);
4682	if (tree_int_cst_equal (op, tmp))
4683	  return RECUR (TREE_OPERAND (t, 1), rval);
4684	else
4685	  return true;
4686      }
4687
4688    case PLUS_EXPR:
4689    case MULT_EXPR:
4690    case POINTER_PLUS_EXPR:
4691    case RDIV_EXPR:
4692    case EXACT_DIV_EXPR:
4693    case MIN_EXPR:
4694    case MAX_EXPR:
4695    case LSHIFT_EXPR:
4696    case RSHIFT_EXPR:
4697    case LROTATE_EXPR:
4698    case RROTATE_EXPR:
4699    case BIT_IOR_EXPR:
4700    case BIT_XOR_EXPR:
4701    case BIT_AND_EXPR:
4702    case TRUTH_XOR_EXPR:
4703    case UNORDERED_EXPR:
4704    case ORDERED_EXPR:
4705    case UNLT_EXPR:
4706    case UNLE_EXPR:
4707    case UNGT_EXPR:
4708    case UNGE_EXPR:
4709    case UNEQ_EXPR:
4710    case LTGT_EXPR:
4711    case RANGE_EXPR:
4712    case COMPLEX_EXPR:
4713      want_rval = true;
4714      /* Fall through.  */
4715    case ARRAY_REF:
4716    case ARRAY_RANGE_REF:
4717    case MEMBER_REF:
4718    case DOTSTAR_EXPR:
4719    case MEM_REF:
4720    binary:
4721      for (i = 0; i < 2; ++i)
4722	if (!RECUR (TREE_OPERAND (t, i), want_rval))
4723	  return false;
4724      return true;
4725
4726    case CILK_SYNC_STMT:
4727    case CILK_SPAWN_STMT:
4728    case ARRAY_NOTATION_REF:
4729      return false;
4730
4731    case FMA_EXPR:
4732    case VEC_PERM_EXPR:
4733     for (i = 0; i < 3; ++i)
4734      if (!RECUR (TREE_OPERAND (t, i), true))
4735	return false;
4736     return true;
4737
4738    case COND_EXPR:
4739    case VEC_COND_EXPR:
4740      /* If the condition is a known constant, we know which of the legs we
4741	 care about; otherwise we only require that the condition and
4742	 either of the legs be potentially constant.  */
4743      tmp = TREE_OPERAND (t, 0);
4744      if (!RECUR (tmp, rval))
4745	return false;
4746      if (!processing_template_decl)
4747	tmp = cxx_eval_outermost_constant_expr (tmp, true);
4748      if (integer_zerop (tmp))
4749	return RECUR (TREE_OPERAND (t, 2), want_rval);
4750      else if (TREE_CODE (tmp) == INTEGER_CST)
4751	return RECUR (TREE_OPERAND (t, 1), want_rval);
4752      for (i = 1; i < 3; ++i)
4753	if (potential_constant_expression_1 (TREE_OPERAND (t, i),
4754					     want_rval, strict, tf_none))
4755	  return true;
4756      if (flags & tf_error)
4757        error ("expression %qE is not a constant-expression", t);
4758      return false;
4759
4760    case VEC_INIT_EXPR:
4761      if (VEC_INIT_EXPR_IS_CONSTEXPR (t))
4762	return true;
4763      if (flags & tf_error)
4764	{
4765	  error ("non-constant array initialization");
4766	  diagnose_non_constexpr_vec_init (t);
4767	}
4768      return false;
4769
4770    case TYPE_DECL:
4771    case TAG_DEFN:
4772      /* We can see these in statement-expressions.  */
4773      return true;
4774
4775    default:
4776      if (objc_is_property_ref (t))
4777	return false;
4778
4779      sorry ("unexpected AST of kind %s", get_tree_code_name (TREE_CODE (t)));
4780      gcc_unreachable();
4781      return false;
4782    }
4783#undef RECUR
4784}
4785
4786/* The main entry point to the above.  */
4787
4788bool
4789potential_constant_expression (tree t)
4790{
4791  return potential_constant_expression_1 (t, false, true, tf_none);
4792}
4793
4794bool
4795potential_static_init_expression (tree t)
4796{
4797  return potential_constant_expression_1 (t, false, false, tf_none);
4798}
4799
4800/* As above, but require a constant rvalue.  */
4801
4802bool
4803potential_rvalue_constant_expression (tree t)
4804{
4805  return potential_constant_expression_1 (t, true, true, tf_none);
4806}
4807
4808/* Like above, but complain about non-constant expressions.  */
4809
4810bool
4811require_potential_constant_expression (tree t)
4812{
4813  return potential_constant_expression_1 (t, false, true, tf_warning_or_error);
4814}
4815
4816/* Cross product of the above.  */
4817
4818bool
4819require_potential_rvalue_constant_expression (tree t)
4820{
4821  return potential_constant_expression_1 (t, true, true, tf_warning_or_error);
4822}
4823
4824#include "gt-cp-constexpr.h"
4825